file_id
int64
1
66.7k
content
stringlengths
14
343k
repo
stringlengths
6
92
path
stringlengths
5
169
274
package com.crossoverjie.basic; import java.lang.reflect.Field; /** * Function: * * @author crossoverJie * Date: 08/03/2018 13:56 * @since JDK 1.8 */ public class StringTest { public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { String a = "123"; //这里的 a 和 b 都是同一个对象,指向同一个字符串常量池对象。 String b = "123" ; String c = new String("123") ; System.out.println("a=b:" + (a == b)); System.out.println("a=c:" + (a == c)); System.out.println("a=" + a); a = "456"; System.out.println("a=" + a); //用反射的方式改变字符串的值 Field value = a.getClass().getDeclaredField("value"); //改变 value 的访问属性 value.setAccessible(true) ; char[] values = (char[]) value.get(a); values[0] = '9' ; System.out.println(a); } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/basic/StringTest.java
275
package com.taobao.arthas.core; import com.taobao.arthas.common.JavaVersionUtils; /** * 全局开关 * Created by vlinux on 15/6/4. */ public class GlobalOptions { public static final String STRICT_MESSAGE = "By default, strict mode is true, " + "not allowed to set object properties. " + "Want to set object properties, execute `options strict false`"; /** * 是否支持系统类<br/> * 这个开关打开之后将能代理到来自JVM的部分类,由于有非常强的安全风险可能会引起系统崩溃<br/> * 所以这个开关默认是关闭的,除非你非常了解你要做什么,否则请不要打开 */ @Option(level = 0, name = "unsafe", summary = "Option to support system-level class", description = "This option enables to proxy functionality of JVM classes." + " Due to serious security risk a JVM crash is possibly be introduced." + " Do not activate it unless you are able to manage." ) public static volatile boolean isUnsafe = false; /** * 是否支持dump被增强的类<br/> * 这个开关打开这后,每次增强类的时候都将会将增强的类dump到文件中,以便于进行反编译分析 */ @Option(level = 1, name = "dump", summary = "Option to dump the enhanced classes", description = "This option enables the enhanced classes to be dumped to external file " + "for further de-compilation and analysis." ) public static volatile boolean isDump = false; /** * 是否支持批量增强<br/> * 这个开关打开后,每次均是批量增强类 */ @Option(level = 1, name = "batch-re-transform", summary = "Option to support batch reTransform Class", description = "This options enables to reTransform classes with batch mode." ) public static volatile boolean isBatchReTransform = true; /** * 是否支持json格式化输出<br/> * 这个开关打开后,使用json格式输出目标对象,配合-x参数使用 */ @Option(level = 2, name = "json-format", summary = "Option to support JSON format of object output", description = "This option enables to format object output with JSON when -x option selected." ) public static volatile boolean isUsingJson = false; /** * 是否关闭子类 */ @Option( level = 1, name = "disable-sub-class", summary = "Option to control include sub class when class matching", description = "This option disable to include sub class when matching class." ) public static volatile boolean isDisableSubClass = false; /** * 是否在interface类里搜索函数 * https://github.com/alibaba/arthas/issues/1105 */ @Option( level = 1, name = "support-default-method", summary = "Option to control include default method in interface when class matching", description = "This option disable to include default method in interface when matching class." ) public static volatile boolean isSupportDefaultMethod = JavaVersionUtils.isGreaterThanJava7(); /** * 是否日志中保存命令执行结果 */ @Option(level = 1, name = "save-result", summary = "Option to print command's result to log file", description = "This option enables to save each command's result to log file, " + "which path is ${user.home}/logs/arthas-cache/result.log." ) public static volatile boolean isSaveResult = false; /** * job的超时时间 */ @Option(level = 2, name = "job-timeout", summary = "Option to job timeout", description = "This option setting job timeout,The unit can be d, h, m, s for day, hour, minute, second. " + "1d is one day in default" ) public static volatile String jobTimeout = "1d"; /** * 是否打印parent类里的field * @see com.taobao.arthas.core.view.ObjectView */ @Option(level = 1, name = "print-parent-fields", summary = "Option to print all fileds in parent class", description = "This option enables print files in parent class, default value true." ) public static volatile boolean printParentFields = true; /** * 是否打开verbose 开关 */ @Option(level = 1, name = "verbose", summary = "Option to print verbose information", description = "This option enables print verbose information, default value false." ) public static volatile boolean verbose = false; /** * 是否打开strict 开关 */ @Option(level = 1, name = "strict", summary = "Option to strict mode", description = STRICT_MESSAGE ) public static volatile boolean strict = true; }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/GlobalOptions.java
276
package cn.hutool.http; /** * Http 头域 * * @author Looly */ public enum Header { //------------------------------------------------------------- 通用头域 /** * 提供验证头,例如: * <pre> * Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l * </pre> */ AUTHORIZATION("Authorization"), /** * 提供给代理服务器的用于身份验证的凭证,例如: * <pre> * Proxy-Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l * </pre> */ PROXY_AUTHORIZATION("Proxy-Authorization"), /** * 提供日期和时间标志,说明报文是什么时间创建的 */ DATE("Date"), /** * 允许客户端和服务器指定与请求/响应连接有关的选项 */ CONNECTION("Connection"), /** * 给出发送端使用的MIME版本 */ MIME_VERSION("MIME-Version"), /** * 如果报文采用了分块传输编码(chunked transfer encoding) 方式,就可以用这个首部列出位于报文拖挂(trailer)部分的首部集合 */ TRAILER("Trailer"), /** * 告知接收端为了保证报文的可靠传输,对报文采用了什么编码方式 */ TRANSFER_ENCODING("Transfer-Encoding"), /** * 给出了发送端可能想要"升级"使用的新版本和协议 */ UPGRADE("Upgrade"), /** * 显示了报文经过的中间节点 */ VIA("Via"), /** * 指定请求和响应遵循的缓存机制 */ CACHE_CONTROL("Cache-Control"), /** * 用来包含实现特定的指令,最常用的是Pragma:no-cache。在HTTP/1.1协议中,它的含义和Cache- Control:no-cache相同 */ PRAGMA("Pragma"), /** * 请求表示提交内容类型或返回返回内容的MIME类型 */ CONTENT_TYPE("Content-Type"), //------------------------------------------------------------- 请求头域 /** * 指定请求资源的Intenet主机和端口号,必须表示请求url的原始服务器或网关的位置。HTTP/1.1请求必须包含主机头域,否则系统会以400状态码返回 */ HOST("Host"), /** * 允许客户端指定请求uri的源资源地址,这可以允许服务器生成回退链表,可用来登陆、优化cache等。他也允许废除的或错误的连接由于维护的目的被 追踪。如果请求的uri没有自己的uri地址,Referer不能被发送。如果指定的是部分uri地址,则此地址应该是一个相对地址 */ REFERER("Referer"), /** * 指定请求的域 */ ORIGIN("Origin"), /** * HTTP客户端运行的浏览器类型的详细信息。通过该头部信息,web服务器可以判断到当前HTTP请求的客户端浏览器类别 */ USER_AGENT("User-Agent"), /** * 指定客户端能够接收的内容类型,内容类型中的先后次序表示客户端接收的先后次序 */ ACCEPT("Accept"), /** * 指定HTTP客户端浏览器用来展示返回信息所优先选择的语言 */ ACCEPT_LANGUAGE("Accept-Language"), /** * 指定客户端浏览器可以支持的web服务器返回内容压缩编码类型 */ ACCEPT_ENCODING("Accept-Encoding"), /** * 浏览器可以接受的字符编码集 */ ACCEPT_CHARSET("Accept-Charset"), /** * HTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器 */ COOKIE("Cookie"), /** * 请求的内容长度 */ CONTENT_LENGTH("Content-Length"), //------------------------------------------------------------- 响应头域 /** * 提供WWW验证响应头 */ WWW_AUTHENTICATE("WWW-Authenticate"), /** * Cookie */ SET_COOKIE("Set-Cookie"), /** * Content-Encoding */ CONTENT_ENCODING("Content-Encoding"), /** * Content-Disposition */ CONTENT_DISPOSITION("Content-Disposition"), /** * ETag */ ETAG("ETag"), /** * 重定向指示到的URL */ LOCATION("Location"); private final String value; Header(String value) { this.value = value; } /** * 获取值 * * @return 值 */ public String getValue(){ return this.value; } @Override public String toString() { return getValue(); } }
dromara/hutool
hutool-http/src/main/java/cn/hutool/http/Header.java
277
package com.xkcoding.task.config; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledThreadPoolExecutor; /** * <p> * 定时任务配置,配置线程池,使用不同线程执行任务,提升效率 * </p> * * @author yangkai.shen * @date Created in 2018-11-22 19:02 */ @Configuration @EnableScheduling @ComponentScan(basePackages = {"com.xkcoding.task.job"}) public class TaskConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskExecutor()); } /** * 这里等同于配置文件配置 * {@code spring.task.scheduling.pool.size=20} - Maximum allowed number of threads. * {@code spring.task.scheduling.thread-name-prefix=Job-Thread- } - Prefix to use for the names of newly created threads. * {@link org.springframework.boot.autoconfigure.task.TaskSchedulingProperties} */ @Bean public Executor taskExecutor() { return new ScheduledThreadPoolExecutor(20, new BasicThreadFactory.Builder().namingPattern("Job-Thread-%d").build()); } }
xkcoding/spring-boot-demo
demo-task/src/main/java/com/xkcoding/task/config/TaskConfig.java
280
package io.mycat.cache.index; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; /** * 分布式索引一致性 * * @author Hash Zhang * @version 1.0 * @time 00:15:03 2016/5/23 */ public class Shard<S> { // S类封装了机器节点的信息 ,如name、password、ip、port等 private TreeMap<Long, S> nodes; // 虚拟节点 private List<S> shards; // 真实机器节点 private static final int NODE_NUM = 100; // 每个机器节点关联的虚拟节点个数 public Shard(List<S> shards) { super(); this.shards = shards; init(); } private void init() { // 初始化一致性hash环 nodes = new TreeMap<Long, S>(); for (int i = 0; i != shards.size(); ++i) { // 每个真实机器节点都需要关联虚拟节点 final S shardInfo = shards.get(i); for (int n = 0; n < NODE_NUM; n++) { // 一个真实机器节点关联NODE_NUM个虚拟节点 nodes.put(hash("SHARD-" + i + "-NODE-" + n), shardInfo); } } } public S getShardInfo(String key) { SortedMap<Long, S> tail = nodes.tailMap(hash(key)); // 沿环的顺时针找到一个虚拟节点 if (tail.size() == 0) { return nodes.get(nodes.firstKey()); } return tail.get(tail.firstKey()); // 返回该虚拟节点对应的真实机器节点的信息 } /** * MurMurHash算法,是非加密HASH算法,性能很高, * 比传统的CRC32,MD5,SHA-1(这两个算法都是加密HASH算法,复杂度本身就很高,带来的性能上的损害也不可避免) * 等HASH算法要快很多,而且据说这个算法的碰撞率很低. * http://murmurhash.googlepages.com/ */ private Long hash(String key) { ByteBuffer buf = ByteBuffer.wrap(key.getBytes()); int seed = 0x1234ABCD; ByteOrder byteOrder = buf.order(); buf.order(ByteOrder.LITTLE_ENDIAN); long m = 0xc6a4a7935bd1e995L; int r = 47; long h = seed ^ (buf.remaining() * m); long k; while (buf.remaining() >= 8) { k = buf.getLong(); k *= m; k ^= k >>> r; k *= m; h ^= k; h *= m; } if (buf.remaining() > 0) { ByteBuffer finish = ByteBuffer.allocate(8).order( ByteOrder.LITTLE_ENDIAN); // for big-endian version, do this first: // finish.position(8-buf.remaining()); finish.put(buf).rewind(); h ^= finish.getLong(); h *= m; } h ^= h >>> r; h *= m; h ^= h >>> r; buf.order(byteOrder); return h; } public static void main(String[] args) { List<String> stringList = new ArrayList<>(); stringList.add("host1"); stringList.add("host2"); stringList.add("host3"); stringList.add("host4"); stringList.add("host5"); Shard<String> stringShard = new Shard<>(stringList); for (int i = 0; i < 10; i++) { System.out.println(i+":"+stringShard.getShardInfo(""+i)); } stringList = new ArrayList<>(); stringList.add("host1"); stringList.add("host2"); stringList.add("host3"); stringList.add("host4"); stringShard = new Shard<>(stringList); for (int i = 0; i < 10; i++) { System.out.println(i+":"+stringShard.getShardInfo(""+i)); } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/cache/index/Shard.java
283
package org.ansj.domain; import org.ansj.library.NatureLibrary; import java.io.Serializable; /** * 这里面封装了一些基本的词性. * * @author ansj * */ public class Nature implements Serializable { /** * */ private static final long serialVersionUID = -1427092012930357598L; // 词性的名称 public final String natureStr; // 词性对照表的位置 public final int index; // 词性的下标值 public final int natureIndex; // 词性的频率 public final int allFrequency; public static final Nature NW = NatureLibrary.getNature("nw"); public static final Nature NRF = NatureLibrary.getNature("nrf"); public static final Nature NR = NatureLibrary.getNature("nr"); public static final Nature MQ = NatureLibrary.getNature("mq"); public static final Nature NULL = NatureLibrary.getNature("null"); public Nature(String natureStr, int index, int natureIndex, int allFrequency) { this.natureStr = natureStr; this.index = index; this.natureIndex = natureIndex; this.allFrequency = allFrequency; } public Nature(String natureStr) { this.natureStr = natureStr; this.index = 0; this.natureIndex = 0; this.allFrequency = 0; } @Override public String toString() { return natureStr + ":" + index + ":" + natureIndex; } }
NLPchina/ansj_seg
src/main/java/org/ansj/domain/Nature.java
284
/* * 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; import android.app.Application; import com.lzy.okgo.OkGo; import com.lzy.okgo.cache.CacheEntity; import com.lzy.okgo.cache.CacheMode; import com.lzy.okgo.cookie.CookieJarImpl; import com.lzy.okgo.cookie.store.DBCookieStore; import com.lzy.okgo.https.HttpsUtils; import com.lzy.okgo.interceptor.HttpLoggingInterceptor; import com.lzy.okgo.model.HttpHeaders; import com.lzy.okgo.model.HttpParams; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; import okhttp3.OkHttpClient; /** * ================================================ * 作 者:廖子尧 github 地址 https://github.com/jeasonlzy/ * 版 本:1.0 * 创建日期:2015/9/23 * 描 述: * 修订历史: * ================================================ */ public class GApp extends Application { @Override public void onCreate() { super.onCreate(); // System.setProperty("http.proxyHost", "192.168.1.104"); //个人测试网络时用的,删掉即可 // System.setProperty("http.proxyPort", "8888"); initOkGo(); } private void initOkGo() { //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------// HttpHeaders headers = new HttpHeaders(); headers.put("commonHeaderKey1", "commonHeaderValue1"); //header不支持中文,不允许有特殊字符 headers.put("commonHeaderKey2", "commonHeaderValue2"); HttpParams params = new HttpParams(); params.put("commonParamsKey1", "commonParamsValue1"); //param支持中文,直接传,不要自己编码 params.put("commonParamsKey2", "这里支持中文参数"); //----------------------------------------------------------------------------------------// OkHttpClient.Builder builder = new OkHttpClient.Builder(); //log相关 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo"); loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY); //log打印级别,决定了log显示的详细程度 loggingInterceptor.setColorLevel(Level.INFO); //log颜色级别,决定了log在控制台显示的颜色 builder.addInterceptor(loggingInterceptor); //添加OkGo默认debug日志 //第三方的开源库,使用通知显示当前请求的log,不过在做文件下载的时候,这个库好像有问题,对文件判断不准确 //builder.addInterceptor(new ChuckInterceptor(this)); //超时时间设置,默认60秒 builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); //全局的读取超时时间 builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); //全局的写入超时时间 builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); //全局的连接超时时间 //自动管理cookie(或者叫session的保持),以下几种任选其一就行 //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this))); //使用sp保持cookie,如果cookie不过期,则一直有效 builder.cookieJar(new CookieJarImpl(new DBCookieStore(this))); //使用数据库保持cookie,如果cookie不过期,则一直有效 //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore())); //使用内存保持cookie,app退出后,cookie消失 //https相关设置,以下几种方案根据需要自己设置 //方法一:信任所有证书,不安全有风险 HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory(); //方法二:自定义信任规则,校验服务端证书 HttpsUtils.SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager()); //方法三:使用预埋证书,校验服务端证书(自签名证书) //HttpsUtils.SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(getAssets().open("srca.cer")); //方法四:使用bks证书和密码管理客户端证书(双向认证),使用预埋证书,校验服务端证书(自签名证书) //HttpsUtils.SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer")); builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager); //配置https的域名匹配规则,详细看demo的初始化介绍,不需要就不要加入,使用不当会导致https握手失败 builder.hostnameVerifier(new SafeHostnameVerifier()); // 其他统一的配置 // 详细说明看GitHub文档:https://github.com/jeasonlzy/ OkGo.getInstance().init(this) //必须调用初始化 .setOkHttpClient(builder.build()) //建议设置OkHttpClient,不设置会使用默认的 .setCacheMode(CacheMode.NO_CACHE) //全局统一缓存模式,默认不使用缓存,可以不传 .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE) //全局统一缓存时间,默认永不过期,可以不传 .setRetryCount(3) //全局统一超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0 .addCommonHeaders(headers) //全局公共头 .addCommonParams(params); //全局公共参数 } /** * 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定 * 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定 * 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定 * 重要的事情说三遍,以下代码不要直接使用 */ private class SafeTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { for (X509Certificate certificate : chain) { certificate.checkValidity(); //检查证书是否过期,签名是否通过等 } } catch (Exception e) { throw new CertificateException(e); } } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } /** * 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定 * 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定 * 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定 * 重要的事情说三遍,以下代码不要直接使用 */ private class SafeHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { //验证主机名是否匹配 //return hostname.equals("server.jeasonlzy.com"); return true; } } }
jeasonlzy/okhttp-OkGo
demo/src/main/java/com/lzy/demo/GApp.java
286
import java.lang.Math; import java.util.Arrays; import java.util.Collections; /** * Created by steven on 2017/3/22. */ public class Exercise { public static void main(String[] args) { String[] aa = "39,State-gov,77516,Bachelors,13,Never-married,Adm-clerical,Not-in-family,White,Male,2174,0,40,United-States,<=50K.".split(","); //String[] aa = "aaa|bbb|ccc".split("\\|"); 这样才能得到正确的结果 for (int i = 0 ; i <aa.length ; i++ ) { //System.out.println(aa[i]); } for(int i=1;i<=10;i++) { int a = (int) (1 + Math.random() * (10 - 1 + 1)); //System.out.println(a); } double bb = Math.log10(0.002); //System.out.println(bb); //System.out.println(0/13); int age=Integer.parseInt("10"); //System.out.println(age); Integer[] a = {4,23,43,12,-8,94,52}; Arrays.sort(a, Collections.reverseOrder()); //数组排序 for(int i=0;i<a.length;i++) { //System.out.print(a[i]+ " "); } int[] ai = {1,2,3,4,5}; Variance(ai); //System.out.println(Variance(ai)[0]+" "+Variance(ai)[1]); for(int i=0;i<10;i++) { int ap = (int) (1 + Math.random() * 100);System.out.println(ap); } } public static double[] Variance(int[] x) { int m=x.length; double sum=0; for(int i=0;i<m;i++){//求和 sum+=x[i]; } double dAve=1.0*sum/m;//求平均值 double dVar=0; for(int i=0;i<m;i++){//求方差 dVar+=(x[i]-dAve)*(x[i]-dAve); } double[] d ={dAve,dVar}; return d; } }
PKUanonym/REKCARC-TSC-UHT
大三下/机器学习概论/hw/2017实验/exp1/Bayes/src/Exercise.java
288
package org.nutz; /** * 用于识别当前版本号和版权声明! <br/> * Nutz is Licensed under the Apache License, Version 2.0 (the "License") * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * * @author Wendal([email protected]) * */ public final class Nutz { /** * 标示类,没有new的可能性 */ Nutz() {} /** * 获取 Nutz 的版本号,版本号的命名规范 * * <pre> * [大版本号].[质量号].[发布流水号] * </pre> * * 这里有点说明 * <ul> * <li>大版本号 - 表示 API 的版本,如果没有重大变化,基本上同样的大版本号,使用方式是一致的 * <li>质量号 - 可能为 a: Alpha内部测试品质, b:Beta 公测品质, r:Release 最终发布版 * <li>发布流水 - 每次发布增加 1 * </ul> * * @return nutz 项目的版本号 */ public static String version() { return "1.r.70-SNAPSHOT"; } /** * 大版本号 */ public static int majorVersion() { return 1; } /** * 发布流水 */ public static int minorVersion() { return 69; } /** * 质量号 */ public static String releaseLevel() { return "r"; } }
nutzam/nutz
src/org/nutz/Nutz.java
291
class Solution { private int[] cookies; private int[] cnt; private int k; private int n; private int ans = 1 << 30; public int distributeCookies(int[] cookies, int k) { n = cookies.length; cnt = new int[k]; // 升序排列 Arrays.sort(cookies); this.cookies = cookies; this.k = k; // 这里搜索顺序是 n-1, n-2,...0 dfs(n - 1); return ans; } private void dfs(int i) { if (i < 0) { // ans = Arrays.stream(cnt).max().getAsInt(); ans = 0; for (int v : cnt) { ans = Math.max(ans, v); } return; } for (int j = 0; j < k; ++j) { if (cnt[j] + cookies[i] >= ans || (j > 0 && cnt[j] == cnt[j - 1])) { continue; } cnt[j] += cookies[i]; dfs(i - 1); cnt[j] -= cookies[i]; } } }
doocs/leetcode
solution/2300-2399/2305.Fair Distribution of Cookies/Solution.java
292
package com.blankj.medium._0209; import java.util.Arrays; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2020/06/30 * desc : * </pre> */ public class Solution { // public int minSubArrayLen(int s, int[] nums) { // int ans = Integer.MAX_VALUE; // for (int i = 0; i < nums.length; i++) { // int sum = nums[i]; // if (sum >= s) { // return 1; // } // for (int j = i + 1; j < nums.length; j++) { // sum += nums[j]; // if (sum >= s) { // ans = Math.min(ans, j - i + 1); // break; // } // } // } // return ans == Integer.MAX_VALUE ? 0 : ans; // } // public int minSubArrayLen(int s, int[] nums) { // int left = 0, right = 0, sum = 0, ans = Integer.MAX_VALUE; // while (right < nums.length) { // sum += nums[right++]; // 向右扩大窗口 // while (sum >= s) { // 如果不小于 s,则收缩窗口左边界 // ans = Math.min(ans, right - left);// 更新结果 // sum -= nums[left++]; // 向左缩小窗口 // } // } // return ans == Integer.MAX_VALUE ? 0 : ans; // } public int minSubArrayLen(int s, int[] nums) { int ans = Integer.MAX_VALUE; int[] sums = new int[nums.length + 1]; for (int i = 0; i < nums.length; i++) { sums[i + 1] = sums[i] + nums[i]; } for (int i = 0; i < nums.length; i++) { int target = s + sums[i]; // 确定要搜索的目标值 // Java 二分查找 Arrays.binarySearch 如果找到就会返回该元素的索引; // 如果没找到就会返回一个负数,这个负数取反之后再减一就是查找的值应该在数组中的位置; // 例如 [-1, 0, 1, 5] 中二分查找 2,其返回值就是 -4,其 -(-4) - 1 = 3,所以 2 这个元素插入到数组的索引就是 3 int bound = Arrays.binarySearch(sums, target); if (bound < 0) { bound = -bound - 1; } if (bound < sums.length) { // 当 bound 确定插入点不在 sums 数组的最后面时,说明不小于 target 的值了 ans = Math.min(ans, bound - i); } } return ans == Integer.MAX_VALUE ? 0 : ans; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.minSubArrayLen(7, new int[]{2, 3, 1, 2, 4, 3})); } }
Blankj/awesome-java-leetcode
src/com/blankj/medium/_0209/Solution.java
293
package com.example.gsyvideoplayer.video; import android.content.Context; import android.graphics.Matrix; import android.graphics.SurfaceTexture; import android.os.Handler; import android.util.AttributeSet; import android.view.Surface; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.example.gsyvideoplayer.R; import com.example.gsyvideoplayer.model.SwitchVideoModel; import com.example.gsyvideoplayer.view.SwitchVideoTypeDialog; import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer; import com.shuyu.gsyvideoplayer.utils.GSYVideoType; import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer; import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by shuyu on 2016/12/7. * 注意 * 这个播放器的demo配置切换到全屏播放器 * 这只是单纯的作为全屏播放显示,如果需要做大小屏幕切换,请记得在这里耶设置上视频全屏的需要的自定义配置 */ public class SampleVideo extends StandardGSYVideoPlayer { private TextView mMoreScale; private TextView mSwitchSize; private TextView mChangeRotate; private TextView mChangeTransform; private List<SwitchVideoModel> mUrlList = new ArrayList<>(); //记住切换数据源类型 private int mType = 0; private int mTransformSize = 0; //数据源 private int mSourcePosition = 0; private String mTypeText = "标准"; /** * 1.5.0开始加入,如果需要不同布局区分功能,需要重载 */ public SampleVideo(Context context, Boolean fullFlag) { super(context, fullFlag); } public SampleVideo(Context context) { super(context); } public SampleVideo(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void init(Context context) { super.init(context); initView(); } private void initView() { mMoreScale = (TextView) findViewById(R.id.moreScale); mSwitchSize = (TextView) findViewById(R.id.switchSize); mChangeRotate = (TextView) findViewById(R.id.change_rotate); mChangeTransform = (TextView) findViewById(R.id.change_transform); //切换清晰度 mMoreScale.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!mHadPlay) { return; } if (mType == 0) { mType = 1; } else if (mType == 1) { mType = 2; } else if (mType == 2) { mType = 3; } else if (mType == 3) { mType = 4; } else if (mType == 4) { mType = 0; } resolveTypeUI(); } }); //切换视频清晰度 mSwitchSize.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showSwitchDialog(); } }); //旋转播放角度 mChangeRotate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!mHadPlay) { return; } if ((mTextureView.getRotation() - mRotate) == 270) { mTextureView.setRotation(mRotate); mTextureView.requestLayout(); } else { mTextureView.setRotation(mTextureView.getRotation() + 90); mTextureView.requestLayout(); } } }); //镜像旋转 mChangeTransform.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!mHadPlay) { return; } if (mTransformSize == 0) { mTransformSize = 1; } else if (mTransformSize == 1) { mTransformSize = 2; } else if (mTransformSize == 2) { mTransformSize = 0; } resolveTransform(); } }); } /** * 需要在尺寸发生变化的时候重新处理 */ @Override public void onSurfaceSizeChanged(Surface surface, int width, int height) { super.onSurfaceSizeChanged(surface, width, height); resolveTransform(); } @Override public void onSurfaceAvailable(Surface surface) { super.onSurfaceAvailable(surface); resolveRotateUI(); resolveTransform(); } /** * 处理镜像旋转 * 注意,暂停时 */ protected void resolveTransform() { switch (mTransformSize) { case 1: { Matrix transform = new Matrix(); transform.setScale(-1, 1, mTextureView.getWidth() / 2, 0); mTextureView.setTransform(transform); mChangeTransform.setText("左右镜像"); mTextureView.invalidate(); } break; case 2: { Matrix transform = new Matrix(); transform.setScale(1, -1, 0, mTextureView.getHeight() / 2); mTextureView.setTransform(transform); mChangeTransform.setText("上下镜像"); mTextureView.invalidate(); } break; case 0: { Matrix transform = new Matrix(); transform.setScale(1, 1, mTextureView.getWidth() / 2, 0); mTextureView.setTransform(transform); mChangeTransform.setText("旋转镜像"); mTextureView.invalidate(); } break; } } /** * 设置播放URL * * @param url 播放url * @param cacheWithPlay 是否边播边缓存 * @param title title * @return */ public boolean setUp(List<SwitchVideoModel> url, boolean cacheWithPlay, String title) { mUrlList = url; return setUp(url.get(mSourcePosition).getUrl(), cacheWithPlay, title); } /** * 设置播放URL * * @param url 播放url * @param cacheWithPlay 是否边播边缓存 * @param cachePath 缓存路径,如果是M3U8或者HLS,请设置为false * @param title title * @return */ public boolean setUp(List<SwitchVideoModel> url, boolean cacheWithPlay, File cachePath, String title) { mUrlList = url; return setUp(url.get(mSourcePosition).getUrl(), cacheWithPlay, cachePath, title); } @Override public int getLayoutId() { return R.layout.sample_video; } /** * 全屏时将对应处理参数逻辑赋给全屏播放器 * * @param context * @param actionBar * @param statusBar * @return */ @Override public GSYBaseVideoPlayer startWindowFullscreen(Context context, boolean actionBar, boolean statusBar) { SampleVideo sampleVideo = (SampleVideo) super.startWindowFullscreen(context, actionBar, statusBar); sampleVideo.mSourcePosition = mSourcePosition; sampleVideo.mType = mType; sampleVideo.mTransformSize = mTransformSize; sampleVideo.mUrlList = mUrlList; sampleVideo.mTypeText = mTypeText; //sampleVideo.resolveTransform(); sampleVideo.resolveTypeUI(); //sampleVideo.resolveRotateUI(); //这个播放器的demo配置切换到全屏播放器 //这只是单纯的作为全屏播放显示,如果需要做大小屏幕切换,请记得在这里耶设置上视频全屏的需要的自定义配置 //比如已旋转角度之类的等等 //可参考super中的实现 return sampleVideo; } /** * 推出全屏时将对应处理参数逻辑返回给非播放器 * * @param oldF * @param vp * @param gsyVideoPlayer */ @Override protected void resolveNormalVideoShow(View oldF, ViewGroup vp, GSYVideoPlayer gsyVideoPlayer) { super.resolveNormalVideoShow(oldF, vp, gsyVideoPlayer); if (gsyVideoPlayer != null) { SampleVideo sampleVideo = (SampleVideo) gsyVideoPlayer; mSourcePosition = sampleVideo.mSourcePosition; mType = sampleVideo.mType; mTransformSize = sampleVideo.mTransformSize; mTypeText = sampleVideo.mTypeText; setUp(mUrlList, mCache, mCachePath, mTitle); resolveTypeUI(); } } /** * 旋转逻辑 */ private void resolveRotateUI() { if (!mHadPlay) { return; } mTextureView.setRotation(mRotate); mTextureView.requestLayout(); } /** * 显示比例 * 注意,GSYVideoType.setShowType是全局静态生效,除非重启APP。 */ private void resolveTypeUI() { if (!mHadPlay) { return; } if (mType == 1) { mMoreScale.setText("16:9"); GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9); } else if (mType == 2) { mMoreScale.setText("4:3"); GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_4_3); } else if (mType == 3) { mMoreScale.setText("全屏"); GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL); } else if (mType == 4) { mMoreScale.setText("拉伸全屏"); GSYVideoType.setShowType(GSYVideoType.SCREEN_MATCH_FULL); } else if (mType == 0) { mMoreScale.setText("默认比例"); GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT); } changeTextureViewShowType(); if (mTextureView != null) mTextureView.requestLayout(); mSwitchSize.setText(mTypeText); } /** * 弹出切换清晰度 */ private void showSwitchDialog() { if (!mHadPlay) { return; } SwitchVideoTypeDialog switchVideoTypeDialog = new SwitchVideoTypeDialog(getContext()); switchVideoTypeDialog.initList(mUrlList, new SwitchVideoTypeDialog.OnListItemClickListener() { @Override public void onItemClick(int position) { final String name = mUrlList.get(position).getName(); if (mSourcePosition != position) { if ((mCurrentState == GSYVideoPlayer.CURRENT_STATE_PLAYING || mCurrentState == GSYVideoPlayer.CURRENT_STATE_PAUSE)) { final String url = mUrlList.get(position).getUrl(); onVideoPause(); final long currentPosition = mCurrentPosition; getGSYVideoManager().releaseMediaPlayer(); cancelProgressTimer(); hideAllWidget(); new Handler().postDelayed(new Runnable() { @Override public void run() { setUp(url, mCache, mCachePath, mTitle); setSeekOnStart(currentPosition); startPlayLogic(); cancelProgressTimer(); hideAllWidget(); } }, 500); mTypeText = name; mSwitchSize.setText(name); mSourcePosition = position; } } else { Toast.makeText(getContext(), "已经是 " + name, Toast.LENGTH_LONG).show(); } } }); switchVideoTypeDialog.show(); } }
CarGuo/GSYVideoPlayer
app/src/main/java/com/example/gsyvideoplayer/video/SampleVideo.java
294
/* * The MIT License (MIT) * * Copyright (c) 2014-2023 [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.pagehelper; import com.github.pagehelper.dialect.AbstractHelperDialect; import com.github.pagehelper.page.PageAutoDialect; import com.github.pagehelper.page.PageBoundSqlInterceptors; import com.github.pagehelper.page.PageMethod; import com.github.pagehelper.page.PageParams; import com.github.pagehelper.parser.CountSqlParser; import com.github.pagehelper.util.StringUtil; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.session.RowBounds; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinWorkerThread; import java.util.concurrent.Future; /** * Mybatis - 通用分页拦截器<br/> * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper * * @author liuzh/abel533/isea533 * @version 5.0.0 */ public class PageHelper extends PageMethod implements Dialect, BoundSqlInterceptor.Chain { private PageParams pageParams; private PageAutoDialect autoDialect; private PageBoundSqlInterceptors pageBoundSqlInterceptors; private ForkJoinPool asyncCountService; @Override public boolean skip(MappedStatement ms, Object parameterObject, RowBounds rowBounds) { Page page = pageParams.getPage(parameterObject, rowBounds); if (page == null) { return true; } else { //设置默认的 count 列 if (StringUtil.isEmpty(page.getCountColumn())) { page.setCountColumn(pageParams.getCountColumn()); } //设置默认的异步 count 设置 if (page.getAsyncCount() == null) { page.setAsyncCount(pageParams.isAsyncCount()); } autoDialect.initDelegateDialect(ms, page.getDialectClass()); return false; } } @Override public boolean isAsyncCount() { return getLocalPage().asyncCount(); } @Override public <T> Future<T> asyncCountTask(Callable<T> task) { //异步执行时需要将ThreadLocal值传递,否则会找不到 AbstractHelperDialect dialectThreadLocal = autoDialect.getDialectThreadLocal(); Page<Object> localPage = getLocalPage(); String countId = UUID.randomUUID().toString(); return asyncCountService.submit(() -> { try { //设置 ThreadLocal autoDialect.setDialectThreadLocal(dialectThreadLocal); setLocalPage(localPage); return task.call(); } finally { autoDialect.clearDelegate(); clearPage(); } }); } @Override public boolean beforeCount(MappedStatement ms, Object parameterObject, RowBounds rowBounds) { return autoDialect.getDelegate().beforeCount(ms, parameterObject, rowBounds); } @Override public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey) { return autoDialect.getDelegate().getCountSql(ms, boundSql, parameterObject, rowBounds, countKey); } @Override public boolean afterCount(long count, Object parameterObject, RowBounds rowBounds) { return autoDialect.getDelegate().afterCount(count, parameterObject, rowBounds); } @Override public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey) { return autoDialect.getDelegate().processParameterObject(ms, parameterObject, boundSql, pageKey); } @Override public boolean beforePage(MappedStatement ms, Object parameterObject, RowBounds rowBounds) { return autoDialect.getDelegate().beforePage(ms, parameterObject, rowBounds); } @Override public String getPageSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey pageKey) { return autoDialect.getDelegate().getPageSql(ms, boundSql, parameterObject, rowBounds, pageKey); } public String getPageSql(String sql, Page page, RowBounds rowBounds, CacheKey pageKey) { return autoDialect.getDelegate().getPageSql(sql, page, pageKey); } @Override public Object afterPage(List pageList, Object parameterObject, RowBounds rowBounds) { //这个方法即使不分页也会被执行,所以要判断 null AbstractHelperDialect delegate = autoDialect.getDelegate(); if (delegate != null) { return delegate.afterPage(pageList, parameterObject, rowBounds); } return pageList; } @Override public void afterAll() { //这个方法即使不分页也会被执行,所以要判断 null AbstractHelperDialect delegate = autoDialect.getDelegate(); if (delegate != null) { delegate.afterAll(); autoDialect.clearDelegate(); } clearPage(); } @Override public BoundSql doBoundSql(BoundSqlInterceptor.Type type, BoundSql boundSql, CacheKey cacheKey) { Page<Object> localPage = getLocalPage(); BoundSqlInterceptor.Chain chain = localPage != null ? localPage.getChain() : null; if (chain == null) { BoundSqlInterceptor boundSqlInterceptor = localPage != null ? localPage.getBoundSqlInterceptor() : null; BoundSqlInterceptor.Chain defaultChain = pageBoundSqlInterceptors != null ? pageBoundSqlInterceptors.getChain() : null; if (boundSqlInterceptor != null) { chain = new BoundSqlInterceptorChain(defaultChain, Arrays.asList(boundSqlInterceptor)); } else if (defaultChain != null) { chain = defaultChain; } if (chain == null) { chain = DO_NOTHING; } if (localPage != null) { localPage.setChain(chain); } } return chain.doBoundSql(type, boundSql, cacheKey); } @Override public void setProperties(Properties properties) { setStaticProperties(properties); pageParams = new PageParams(); autoDialect = new PageAutoDialect(); pageBoundSqlInterceptors = new PageBoundSqlInterceptors(); pageParams.setProperties(properties); autoDialect.setProperties(properties); pageBoundSqlInterceptors.setProperties(properties); //20180902新增 aggregateFunctions, 允许手动添加聚合函数(影响行数) CountSqlParser.addAggregateFunctions(properties.getProperty("aggregateFunctions")); // 异步 asyncCountService 并发度设置,这里默认为应用可用的处理器核心数 * 2,更合理的值应该综合考虑数据库服务器的处理能力 int asyncCountParallelism = Integer.parseInt(properties.getProperty("asyncCountParallelism", "" + (Runtime.getRuntime().availableProcessors() * 2))); asyncCountService = new ForkJoinPool(asyncCountParallelism, pool -> { final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); worker.setName("pagehelper-async-count-" + worker.getPoolIndex()); return worker; }, null, true); } }
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/PageHelper.java
296
/*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; /**SQL语句,函数名尽量和JDK中相同或类似功能的函数的名称一致 * @author Lemon */ public class SQL { public static final String JOIN = " JOIN "; public static final String ON = " ON "; public static final String OR = " OR "; public static final String AND = " AND "; public static final String NOT = " NOT "; public static final String AS = " AS "; public static final String IS = " IS "; public static final String NULL = " NULL "; public static final String IS_NOT = " IS NOT "; public static final String IS_NULL = " IS NULL "; public static final String IS_NOT_NULL = " IS NOT NULL "; //括号必须紧跟函数名! count (...) 报错! public static final String COUNT = "count"; public static final String SUM = "sum"; public static final String MAX = "max"; public static final String MIN = "min"; public static final String AVG = "avg"; /** * isNull = true * @return {@link #isNull(boolean)} */ public static String isNull() { return isNull(true); } /** * @param isNull * @return {@link #IS} + (isNull ? "" : {@link #NOT}) + {@link #NULL}; */ public static String isNull(boolean isNull) { return IS + (isNull ? "" : NOT) + NULL; } /** * isNull = true * @param s * @return {@link #isNull(String, boolean)} */ public static String isNull(String s) { return isNull(s, true); } /** * @param s * @param isNull * @return s + {@link #isNull(boolean)} */ public static String isNull(String s, boolean isNull) { return s + isNull(isNull); } /** * isEmpty = true * @param s * @return {@link #isEmpty(String, boolean)} */ public static String isEmpty(String s) { return isEmpty(s, true); } /** * trim = false * @param s * @param isEmpty * @return {@link #isEmpty(String, boolean, boolean)} */ public static String isEmpty(String s, boolean isEmpty) { return isEmpty(s, isEmpty, false); } /** * nullable = true * @param s * @param isEmpty <=0 * @param trim s = trim(s); * @return {@link #isEmpty(String, boolean, boolean, boolean)} */ public static String isEmpty(String s, boolean isEmpty, boolean trim) { return isEmpty(s, isEmpty, trim, true); } /** * @param s * @param isEmpty <=0 * @param trim s = trim(s); * @param nullable isNull(s, true) + {@link #OR} + * @return {@link #lengthCompare(String, String)} */ public static String isEmpty(String s, boolean isEmpty, boolean trim, boolean nullable) { if (trim) { s = trim(s); } return (nullable ? isNull(s, true) + OR : "") + lengthCompare(s, (isEmpty ? "<=" : ">") + "0"); } /** * @param s 因为POWER(x,y)等函数含有不只一个key,所以需要客户端添加进去,服务端检测到条件中有'('和')'时就不转换,直接当SQL语句查询 * @return {@link #length(String)} + compare */ public static String lengthCompare(String s, String compare) { return length(s) + compare; } /** * @param s 因为POWER(x,y)等函数含有不只一个key,所以需要客户端添加进去,服务端检测到条件中有'('和')'时就不转换,直接当SQL语句查询 * @return "length(" + s + ")" */ public static String length(String s) { return "length(" + s + ")"; } /** * @param s 因为POWER(x,y)等函数含有不只一个key,所以需要客户端添加进去,服务端检测到条件中有'('和')'时就不转换,直接当SQL语句查询 * @return "char_length(" + s + ")" */ public static String charLength(String s) { return "char_length(" + s + ")"; } /** * @param s * @return "trim(" + s + ")" */ public static String trim(String s) { return "trim(" + s + ")"; } /** * @param s * @return "ltrim(" + s + ")" */ public static String trimLeft(String s) { return "ltrim(" + s + ")"; } /** * @param s * @return "rtrim(" + s + ")" */ public static String trimRight(String s) { return "rtrim(" + s + ")"; } /** * @param s * @param n * @return "left(" + s + "," + n + ")" */ public static String left(String s, int n) { return "left(" + s + "," + n + ")"; } /** * @param s * @param n * @return "right(" + s + "," + n + ")" */ public static String right(String s, int n) { return "right(" + s + "," + n + ")"; } /** * @param s * @param start * @param end * @return "substring(" + s + "," + start + "," + (end-start) + ")" */ public static String subString(String s, int start, int end) { return "substring(" + s + "," + start + "," + (end-start) + ")"; } /** * @param s * @param c * @return "instr(" + s + ", " + c + ")" */ public static String indexOf(String s, String c) { return "instr(" + s + ", " + c + ")"; } /** * @param s * @param c1 * @param c2 * @return "replace(" + s + ", " + c1 + ", " + c2 + ")" */ public static String replace(String s, String c1, String c2) { return "replace(" + s + ", " + c1 + ", " + c2 + ")"; } /** * @param s1 * @param s2 * @return "concat(" + s1 + ", " + s2 + ")" */ public static String concat(String s1, String s2) { return "concat(" + s1 + ", " + s2 + ")"; } /** * @param s1 * @param s2 * @return "strcmp(" + s1 + ", " + s2 + ")" */ public static String equals(String s1, String s2) { return "strcmp(" + s1 + ", " + s2 + ")"; } /** * @param s * @return "upper(" + s + ")" */ public static String toUpperCase(String s) { return "upper(" + s + ")"; } /** * @param s * @return "lower(" + s + ")" */ public static String toLowerCase(String s) { return "lower(" + s + ")"; } //column and function<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /**字段 * @param column * @return column.isEmpty() ? "*" : column; */ public static String column(String column) { column = StringUtil.getTrimedString(column); return column.isEmpty() ? "*" : column; } /**有别名的字段 * @param column * @return {@link #count(String)} + {@link #AS}; */ public static String columnAs(String column) { return count(column) + AS; } /**函数 * @param column if (StringUtil.isEmpty(column, true) || column.contains(",")) -> column = null; * @return " " + fun + "(" + {@link #column(String)} + ") "; */ public static String function(String fun, String column) { // 支持 fun(col1,col2..) // if (StringUtil.isEmpty(column, true) || column.contains(",")) { // column = null; //解决 count(id,name) 这种多个字段导致的SQL异常 // } return " " + fun + "(" + column(column) + ") "; } /**有别名的函数 * @param column * @return {@link #function(String, String)} + {@link #AS} + fun; */ public static String functionAs(String fun, String column) { return function(fun, column) + AS + fun + " "; } /**计数 * column = null * @return {@link #count(String)} */ public static String count() { return count(null); } /**计数 * fun = {@link #COUNT} * @param column * @return {@link #functionAs(String, String)} */ public static String count(String column) { return functionAs(COUNT, column); } /**求和 * fun = {@link #SUM} * @param column * @return {@link #functionAs(String, String)} */ public static String sum(String column) { return functionAs(SUM, column); } /**最大值 * fun = {@link #MAX} * @param column * @return {@link #functionAs(String, String)} */ public static String max(String column) { return functionAs(MAX, column); } /**最小值 * fun = {@link #MIN} * @param column * @return {@link #functionAs(String, String)} */ public static String min(String column) { return functionAs(MIN, column); } /**平均值 * fun = {@link #AVG} * @param column * @return {@link #functionAs(String, String)} */ public static String avg(String column) { return functionAs(AVG, column); } //column and function>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //search<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< public static final int SEARCH_TYPE_CONTAIN_FULL = 0; public static final int SEARCH_TYPE_CONTAIN_ORDER = 1; public static final int SEARCH_TYPE_CONTAIN_SINGLE = 2; public static final int SEARCH_TYPE_CONTAIN_ANY = 3; public static final int SEARCH_TYPE_START = 4; public static final int SEARCH_TYPE_END = 5; public static final int SEARCH_TYPE_START_SINGLE = 6; public static final int SEARCH_TYPE_END_SINGLE = 7; public static final int SEARCH_TYPE_PART_MATCH = 8; /**获取搜索值 * @param s * @return */ public static String search(String s) { return search(s, SEARCH_TYPE_CONTAIN_FULL); } /**获取搜索值 * @param s * @param type * @return */ public static String search(String s, int type) { return search(s, type, true); } /**获取搜索值 * @param s * @param type * @param ignoreCase * @return default SEARCH_TYPE_CONTAIN_FULL */ public static String search(String s, int type, boolean ignoreCase) { if (s == null) { return null; } switch (type) { case SEARCH_TYPE_CONTAIN_SINGLE: return "_" + s + "_"; case SEARCH_TYPE_CONTAIN_ORDER: char[] cs = s.toCharArray(); if (cs == null) { return null; } String value = "%"; for (int i = 0; i < cs.length; i++) { value += cs[i] + "%"; } return value; case SEARCH_TYPE_START: return s + "%"; case SEARCH_TYPE_END: return "%" + s; case SEARCH_TYPE_START_SINGLE: return s + "_"; case SEARCH_TYPE_END_SINGLE: return "_" + s; case SEARCH_TYPE_CONTAIN_ANY: case SEARCH_TYPE_PART_MATCH: cs = s.toCharArray(); if (cs == null) { return null; } value = ""; for (int i = 0; i < cs.length; i++) { value += search("" + cs[i], SEARCH_TYPE_CONTAIN_FULL, ignoreCase); } return value; default://SEARCH_TYPE_CONTAIN_FULL return "%" + s + "%"; } } //search>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> public static boolean isBooleanOrNumber(String type) { type = StringUtil.toUpperCase(type, true); return type.isEmpty() || (type.endsWith("INT") && type.endsWith("POINT") == false) || type.endsWith("BOOLEAN") || type.endsWith("ENUM") || type.endsWith("FLOAT") || type.endsWith("DOUBLE") || type.endsWith("DECIMAL"); } }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/SQL.java
297
/* * The MIT License (MIT) * * Copyright (c) 2014-2023 [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.pagehelper; import com.github.pagehelper.cache.Cache; import com.github.pagehelper.cache.CacheFactory; import com.github.pagehelper.page.PageMethod; import com.github.pagehelper.util.ClassUtil; import com.github.pagehelper.util.ExecutorUtil; import com.github.pagehelper.util.MSUtils; import com.github.pagehelper.util.StringUtil; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.CachingExecutor; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.SimpleExecutor; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.transaction.Transaction; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.managed.ManagedTransactionFactory; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.Future; /** * Mybatis - 通用分页拦截器 * <p> * GitHub: https://github.com/pagehelper/Mybatis-PageHelper * <p> * Gitee : https://gitee.com/free/Mybatis_PageHelper * * @author liuzh/abel533/isea533 * @version 5.0.0 */ @SuppressWarnings({"rawtypes", "unchecked"}) @Intercepts( { @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}), } ) public class PageInterceptor implements Interceptor { private static final Log log = LogFactory.getLog(PageInterceptor.class); private static boolean debug = false; protected Cache<String, MappedStatement> msCountMap = null; protected CountMsIdGen countMsIdGen = CountMsIdGen.DEFAULT; private volatile Dialect dialect; private String countSuffix = "_COUNT"; private String default_dialect_class = "com.github.pagehelper.PageHelper"; public PageInterceptor() { String bannerEnabled = System.getProperty("pagehelper.banner"); if (StringUtil.isEmpty(bannerEnabled)) { bannerEnabled = System.getenv("PAGEHELPER_BANNER"); } //默认 TRUE if (StringUtil.isEmpty(bannerEnabled) || Boolean.parseBoolean(bannerEnabled)) { log.debug("\n\n" + ",------. ,--. ,--. ,--. \n" + "| .--. ' ,--,--. ,---. ,---. | '--' | ,---. | | ,---. ,---. ,--.--. \n" + "| '--' | ' ,-. | | .-. | | .-. : | .--. | | .-. : | | | .-. | | .-. : | .--' \n" + "| | --' \\ '-' | ' '-' ' \\ --. | | | | \\ --. | | | '-' ' \\ --. | | \n" + "`--' `--`--' .`- / `----' `--' `--' `----' `--' | |-' `----' `--' \n" + " `---' `--' is intercepting.\n"); } } public static boolean isDebug() { return debug; } /** * 输出启用分页方法时的调用堆栈信息 */ protected void debugStackTraceLog() { if (isDebug()) { Page<Object> page = PageMethod.getLocalPage(); log.debug(page.getStackTrace()); } } @Override public Object intercept(Invocation invocation) throws Throwable { try { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; Executor executor = (Executor) invocation.getTarget(); CacheKey cacheKey; BoundSql boundSql; //由于逻辑关系,只会进入一次 if (args.length == 4) { //4 个参数时 boundSql = ms.getBoundSql(parameter); cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); } else { //6 个参数时 cacheKey = (CacheKey) args[4]; boundSql = (BoundSql) args[5]; } checkDialectExists(); //对 boundSql 的拦截处理 if (dialect instanceof BoundSqlInterceptor.Chain) { boundSql = ((BoundSqlInterceptor.Chain) dialect).doBoundSql(BoundSqlInterceptor.Type.ORIGINAL, boundSql, cacheKey); } List resultList; //调用方法判断是否需要进行分页,如果不需要,直接返回结果 if (!dialect.skip(ms, parameter, rowBounds)) { //开启debug时,输出触发当前分页执行时的PageHelper调用堆栈 // 如果和当前调用堆栈不一致,说明在启用分页后没有消费,当前线程再次执行时消费,调用堆栈显示的方法使用不安全 debugStackTraceLog(); Future<Long> countFuture = null; //判断是否需要进行 count 查询 if (dialect.beforeCount(ms, parameter, rowBounds)) { if (dialect.isAsyncCount()) { countFuture = asyncCount(ms, boundSql, parameter, rowBounds); } else { //查询总数 Long count = count(executor, ms, parameter, rowBounds, null, boundSql); //处理查询总数,返回 true 时继续分页查询,false 时直接返回 if (!dialect.afterCount(count, parameter, rowBounds)) { //当查询总数为 0 时,直接返回空的结果 return dialect.afterPage(new ArrayList(), parameter, rowBounds); } } } resultList = ExecutorUtil.pageQuery(dialect, executor, ms, parameter, rowBounds, resultHandler, boundSql, cacheKey); if (countFuture != null) { Long count = countFuture.get(); dialect.afterCount(count, parameter, rowBounds); } } else { //rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页 resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); } return dialect.afterPage(resultList, parameter, rowBounds); } finally { if (dialect != null) { dialect.afterAll(); } } } /** * 异步查询总数 */ private Future<Long> asyncCount(MappedStatement ms, BoundSql boundSql, Object parameter, RowBounds rowBounds) { Configuration configuration = ms.getConfiguration(); //异步不能复用 BoundSql,因为分页使用时会添加分页参数,这里需要复制一个新的 BoundSql countBoundSql = new BoundSql(configuration, boundSql.getSql(), new ArrayList<>(boundSql.getParameterMappings()), parameter); //异步想要起作用需要新的数据库连接,需要独立的事务,创建新的Executor,因此异步查询只适合在独立查询中使用,如果混合增删改操作,不能开启异步 Environment environment = configuration.getEnvironment(); TransactionFactory transactionFactory = null; if (environment == null || environment.getTransactionFactory() == null) { transactionFactory = new ManagedTransactionFactory(); } else { transactionFactory = environment.getTransactionFactory(); } //创建新的事务 Transaction tx = transactionFactory.newTransaction(environment.getDataSource(), null, false); //使用新的 Executor 执行 count 查询,这里没有加载拦截器,避免递归死循环 Executor countExecutor = new CachingExecutor(new SimpleExecutor(configuration, tx)); return dialect.asyncCountTask(() -> { try { return count(countExecutor, ms, parameter, rowBounds, null, countBoundSql); } finally { tx.close(); } }); } /** * Spring bean 方式配置时,如果没有配置属性就不会执行下面的 setProperties 方法,就不会初始化 * <p> * 因此这里会出现 null 的情况 fixed #26 */ private void checkDialectExists() { if (dialect == null) { synchronized (default_dialect_class) { if (dialect == null) { setProperties(new Properties()); } } } } private Long count(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { String countMsId = countMsIdGen.genCountMsId(ms, parameter, boundSql, countSuffix); Long count; //先判断是否存在手写的 count 查询 MappedStatement countMs = ExecutorUtil.getExistedMappedStatement(ms.getConfiguration(), countMsId); if (countMs != null) { count = ExecutorUtil.executeManualCount(executor, countMs, parameter, boundSql, resultHandler); } else { if (msCountMap != null) { countMs = msCountMap.get(countMsId); } //自动创建 if (countMs == null) { //根据当前的 ms 创建一个返回值为 Long 类型的 ms countMs = MSUtils.newCountMappedStatement(ms, countMsId); if (msCountMap != null) { msCountMap.put(countMsId, countMs); } } count = ExecutorUtil.executeAutoCount(this.dialect, executor, countMs, parameter, boundSql, rowBounds, resultHandler); } return count; } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { //缓存 count ms msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties); String dialectClass = properties.getProperty("dialect"); if (StringUtil.isEmpty(dialectClass)) { dialectClass = default_dialect_class; } Dialect tempDialect = ClassUtil.newInstance(dialectClass, properties); tempDialect.setProperties(properties); String countSuffix = properties.getProperty("countSuffix"); if (StringUtil.isNotEmpty(countSuffix)) { this.countSuffix = countSuffix; } // debug模式,用于排查不安全分页调用 debug = Boolean.parseBoolean(properties.getProperty("debug")); // 通过 countMsId 配置自定义类 String countMsIdGenClass = properties.getProperty("countMsIdGen"); if (StringUtil.isNotEmpty(countMsIdGenClass)) { countMsIdGen = ClassUtil.newInstance(countMsIdGenClass, properties); } // 初始化完成后再设置值,保证 dialect 完成初始化 dialect = tempDialect; } }
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/PageInterceptor.java
299
package com.blankj.utilcode.util; import static android.Manifest.permission.EXPAND_STATUS_BAR; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Point; import android.os.Build; import android.provider.Settings; import android.util.TypedValue; import android.view.Display; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.view.Window; import android.view.WindowManager; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.annotation.RequiresPermission; import androidx.drawerlayout.widget.DrawerLayout; import java.lang.reflect.Method; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/09/23 * desc : utils about bar * </pre> */ public final class BarUtils { /////////////////////////////////////////////////////////////////////////// // status bar /////////////////////////////////////////////////////////////////////////// private static final String TAG_STATUS_BAR = "TAG_STATUS_BAR"; private static final String TAG_OFFSET = "TAG_OFFSET"; private static final int KEY_OFFSET = -123; private BarUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * Return the status bar's height. * * @return the status bar's height */ public static int getStatusBarHeight() { Resources resources = Resources.getSystem(); int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android"); return resources.getDimensionPixelSize(resourceId); } /** * Set the status bar's visibility. * * @param activity The activity. * @param isVisible True to set status bar visible, false otherwise. */ public static void setStatusBarVisibility(@NonNull final Activity activity, final boolean isVisible) { setStatusBarVisibility(activity.getWindow(), isVisible); } /** * Set the status bar's visibility. * * @param window The window. * @param isVisible True to set status bar visible, false otherwise. */ public static void setStatusBarVisibility(@NonNull final Window window, final boolean isVisible) { if (isVisible) { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); showStatusBarView(window); addMarginTopEqualStatusBarHeight(window); } else { window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); hideStatusBarView(window); subtractMarginTopEqualStatusBarHeight(window); } } /** * Return whether the status bar is visible. * * @param activity The activity. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isStatusBarVisible(@NonNull final Activity activity) { int flags = activity.getWindow().getAttributes().flags; return (flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0; } /** * Set the status bar's light mode. * * @param activity The activity. * @param isLightMode True to set status bar light mode, false otherwise. */ public static void setStatusBarLightMode(@NonNull final Activity activity, final boolean isLightMode) { setStatusBarLightMode(activity.getWindow(), isLightMode); } /** * Set the status bar's light mode. * * @param window The window. * @param isLightMode True to set status bar light mode, false otherwise. */ public static void setStatusBarLightMode(@NonNull final Window window, final boolean isLightMode) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { View decorView = window.getDecorView(); int vis = decorView.getSystemUiVisibility(); if (isLightMode) { vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } else { vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } decorView.setSystemUiVisibility(vis); } } /** * Is the status bar light mode. * * @param activity The activity. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isStatusBarLightMode(@NonNull final Activity activity) { return isStatusBarLightMode(activity.getWindow()); } /** * Is the status bar light mode. * * @param window The window. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isStatusBarLightMode(@NonNull final Window window) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { View decorView = window.getDecorView(); int vis = decorView.getSystemUiVisibility(); return (vis & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) != 0; } return false; } /** * Add the top margin size equals status bar's height for view. * * @param view The view. */ public static void addMarginTopEqualStatusBarHeight(@NonNull View view) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; view.setTag(TAG_OFFSET); Object haveSetOffset = view.getTag(KEY_OFFSET); if (haveSetOffset != null && (Boolean) haveSetOffset) return; MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams(); layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin + getStatusBarHeight(), layoutParams.rightMargin, layoutParams.bottomMargin); view.setTag(KEY_OFFSET, true); } /** * Subtract the top margin size equals status bar's height for view. * * @param view The view. */ public static void subtractMarginTopEqualStatusBarHeight(@NonNull View view) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; Object haveSetOffset = view.getTag(KEY_OFFSET); if (haveSetOffset == null || !(Boolean) haveSetOffset) return; MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams(); layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin - getStatusBarHeight(), layoutParams.rightMargin, layoutParams.bottomMargin); view.setTag(KEY_OFFSET, false); } private static void addMarginTopEqualStatusBarHeight(@NonNull final Window window) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; View withTag = window.getDecorView().findViewWithTag(TAG_OFFSET); if (withTag == null) return; addMarginTopEqualStatusBarHeight(withTag); } private static void subtractMarginTopEqualStatusBarHeight(@NonNull final Window window) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; View withTag = window.getDecorView().findViewWithTag(TAG_OFFSET); if (withTag == null) return; subtractMarginTopEqualStatusBarHeight(withTag); } /** * Set the status bar's color. * * @param activity The activity. * @param color The status bar's color. */ public static View setStatusBarColor(@NonNull final Activity activity, @ColorInt final int color) { return setStatusBarColor(activity, color, false); } /** * Set the status bar's color. * * @param activity The activity. * @param color The status bar's color. * @param isDecor True to add fake status bar in DecorView, * false to add fake status bar in ContentView. */ public static View setStatusBarColor(@NonNull final Activity activity, @ColorInt final int color, final boolean isDecor) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return null; transparentStatusBar(activity); return applyStatusBarColor(activity, color, isDecor); } /** * Set the status bar's color. * * @param window The window. * @param color The status bar's color. */ public static View setStatusBarColor(@NonNull final Window window, @ColorInt final int color) { return setStatusBarColor(window, color, false); } /** * Set the status bar's color. * * @param window The window. * @param color The status bar's color. * @param isDecor True to add fake status bar in DecorView, * false to add fake status bar in ContentView. */ public static View setStatusBarColor(@NonNull final Window window, @ColorInt final int color, final boolean isDecor) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return null; transparentStatusBar(window); return applyStatusBarColor(window, color, isDecor); } /** * Set the status bar's color. * * @param fakeStatusBar The fake status bar view. * @param color The status bar's color. */ public static void setStatusBarColor(@NonNull final View fakeStatusBar, @ColorInt final int color) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; Activity activity = UtilsBridge.getActivityByContext(fakeStatusBar.getContext()); if (activity == null) return; transparentStatusBar(activity); fakeStatusBar.setVisibility(View.VISIBLE); ViewGroup.LayoutParams layoutParams = fakeStatusBar.getLayoutParams(); layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; layoutParams.height = getStatusBarHeight(); fakeStatusBar.setBackgroundColor(color); } /** * Set the custom status bar. * * @param fakeStatusBar The fake status bar view. */ public static void setStatusBarCustom(@NonNull final View fakeStatusBar) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; Activity activity = UtilsBridge.getActivityByContext(fakeStatusBar.getContext()); if (activity == null) return; transparentStatusBar(activity); fakeStatusBar.setVisibility(View.VISIBLE); ViewGroup.LayoutParams layoutParams = fakeStatusBar.getLayoutParams(); if (layoutParams == null) { layoutParams = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight() ); fakeStatusBar.setLayoutParams(layoutParams); } else { layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; layoutParams.height = getStatusBarHeight(); } } /** * Set the status bar's color for DrawerLayout. * <p>DrawLayout must add {@code android:fitsSystemWindows="true"}</p> * * @param drawer The DrawLayout. * @param fakeStatusBar The fake status bar view. * @param color The status bar's color. */ public static void setStatusBarColor4Drawer(@NonNull final DrawerLayout drawer, @NonNull final View fakeStatusBar, @ColorInt final int color) { setStatusBarColor4Drawer(drawer, fakeStatusBar, color, false); } /** * Set the status bar's color for DrawerLayout. * <p>DrawLayout must add {@code android:fitsSystemWindows="true"}</p> * * @param drawer The DrawLayout. * @param fakeStatusBar The fake status bar view. * @param color The status bar's color. * @param isTop True to set DrawerLayout at the top layer, false otherwise. */ public static void setStatusBarColor4Drawer(@NonNull final DrawerLayout drawer, @NonNull final View fakeStatusBar, @ColorInt final int color, final boolean isTop) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; Activity activity = UtilsBridge.getActivityByContext(fakeStatusBar.getContext()); if (activity == null) return; transparentStatusBar(activity); drawer.setFitsSystemWindows(false); setStatusBarColor(fakeStatusBar, color); for (int i = 0, count = drawer.getChildCount(); i < count; i++) { drawer.getChildAt(i).setFitsSystemWindows(false); } if (isTop) { hideStatusBarView(activity); } else { setStatusBarColor(activity, color, false); } } private static View applyStatusBarColor(@NonNull final Activity activity, final int color, boolean isDecor) { return applyStatusBarColor(activity.getWindow(), color, isDecor); } private static View applyStatusBarColor(@NonNull final Window window, final int color, boolean isDecor) { ViewGroup parent = isDecor ? (ViewGroup) window.getDecorView() : (ViewGroup) window.findViewById(android.R.id.content); View fakeStatusBarView = parent.findViewWithTag(TAG_STATUS_BAR); if (fakeStatusBarView != null) { if (fakeStatusBarView.getVisibility() == View.GONE) { fakeStatusBarView.setVisibility(View.VISIBLE); } fakeStatusBarView.setBackgroundColor(color); } else { fakeStatusBarView = createStatusBarView(window.getContext(), color); parent.addView(fakeStatusBarView); } return fakeStatusBarView; } private static void hideStatusBarView(@NonNull final Activity activity) { hideStatusBarView(activity.getWindow()); } private static void hideStatusBarView(@NonNull final Window window) { ViewGroup decorView = (ViewGroup) window.getDecorView(); View fakeStatusBarView = decorView.findViewWithTag(TAG_STATUS_BAR); if (fakeStatusBarView == null) return; fakeStatusBarView.setVisibility(View.GONE); } private static void showStatusBarView(@NonNull final Window window) { ViewGroup decorView = (ViewGroup) window.getDecorView(); View fakeStatusBarView = decorView.findViewWithTag(TAG_STATUS_BAR); if (fakeStatusBarView == null) return; fakeStatusBarView.setVisibility(View.VISIBLE); } private static View createStatusBarView(@NonNull final Context context, final int color) { View statusBarView = new View(context); statusBarView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight())); statusBarView.setBackgroundColor(color); statusBarView.setTag(TAG_STATUS_BAR); return statusBarView; } public static void transparentStatusBar(@NonNull final Activity activity) { transparentStatusBar(activity.getWindow()); } public static void transparentStatusBar(@NonNull final Window window) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; int vis = window.getDecorView().getSystemUiVisibility(); window.getDecorView().setSystemUiVisibility(option | vis); window.setStatusBarColor(Color.TRANSPARENT); } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } /////////////////////////////////////////////////////////////////////////// // action bar /////////////////////////////////////////////////////////////////////////// /** * Return the action bar's height. * * @return the action bar's height */ public static int getActionBarHeight() { TypedValue tv = new TypedValue(); if (Utils.getApp().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { return TypedValue.complexToDimensionPixelSize( tv.data, Utils.getApp().getResources().getDisplayMetrics() ); } return 0; } /////////////////////////////////////////////////////////////////////////// // notification bar /////////////////////////////////////////////////////////////////////////// /** * Set the notification bar's visibility. * <p>Must hold {@code <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />}</p> * * @param isVisible True to set notification bar visible, false otherwise. */ @RequiresPermission(EXPAND_STATUS_BAR) public static void setNotificationBarVisibility(final boolean isVisible) { String methodName; if (isVisible) { methodName = (Build.VERSION.SDK_INT <= 16) ? "expand" : "expandNotificationsPanel"; } else { methodName = (Build.VERSION.SDK_INT <= 16) ? "collapse" : "collapsePanels"; } invokePanels(methodName); } private static void invokePanels(final String methodName) { try { @SuppressLint("WrongConstant") Object service = Utils.getApp().getSystemService("statusbar"); @SuppressLint("PrivateApi") Class<?> statusBarManager = Class.forName("android.app.StatusBarManager"); Method expand = statusBarManager.getMethod(methodName); expand.invoke(service); } catch (Exception e) { e.printStackTrace(); } } /////////////////////////////////////////////////////////////////////////// // navigation bar /////////////////////////////////////////////////////////////////////////// /** * Return the navigation bar's height. * * @return the navigation bar's height */ public static int getNavBarHeight() { Resources res = Resources.getSystem(); int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId != 0) { return res.getDimensionPixelSize(resourceId); } else { return 0; } } /** * Set the navigation bar's visibility. * * @param activity The activity. * @param isVisible True to set navigation bar visible, false otherwise. */ public static void setNavBarVisibility(@NonNull final Activity activity, boolean isVisible) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; setNavBarVisibility(activity.getWindow(), isVisible); } /** * Set the navigation bar's visibility. * * @param window The window. * @param isVisible True to set navigation bar visible, false otherwise. */ public static void setNavBarVisibility(@NonNull final Window window, boolean isVisible) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return; final ViewGroup decorView = (ViewGroup) window.getDecorView(); for (int i = 0, count = decorView.getChildCount(); i < count; i++) { final View child = decorView.getChildAt(i); final int id = child.getId(); if (id != View.NO_ID) { String resourceEntryName = getResNameById(id); if ("navigationBarBackground".equals(resourceEntryName)) { child.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE); } } } final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; if (isVisible) { decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() & ~uiOptions); } else { decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | uiOptions); } } /** * Return whether the navigation bar visible. * <p>Call it in onWindowFocusChanged will get right result.</p> * * @param activity The activity. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isNavBarVisible(@NonNull final Activity activity) { return isNavBarVisible(activity.getWindow()); } /** * Return whether the navigation bar visible. * <p>Call it in onWindowFocusChanged will get right result.</p> * * @param window The window. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isNavBarVisible(@NonNull final Window window) { boolean isVisible = false; ViewGroup decorView = (ViewGroup) window.getDecorView(); for (int i = 0, count = decorView.getChildCount(); i < count; i++) { final View child = decorView.getChildAt(i); final int id = child.getId(); if (id != View.NO_ID) { String resourceEntryName = getResNameById(id); if ("navigationBarBackground".equals(resourceEntryName) && child.getVisibility() == View.VISIBLE) { isVisible = true; break; } } } if (isVisible) { // 对于三星手机,android10以下非OneUI2的版本,比如 s8,note8 等设备上, // 导航栏显示存在bug:"当用户隐藏导航栏时显示输入法的时候导航栏会跟随显示",会导致隐藏输入法之后判断错误 // 这个问题在 OneUI 2 & android 10 版本已修复 if (UtilsBridge.isSamsung() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { try { return Settings.Global.getInt(Utils.getApp().getContentResolver(), "navigationbar_hide_bar_enabled") == 0; } catch (Exception ignore) { } } int visibility = decorView.getSystemUiVisibility(); isVisible = (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0; } return isVisible; } private static String getResNameById(int id) { try { return Utils.getApp().getResources().getResourceEntryName(id); } catch (Exception ignore) { return ""; } } /** * Set the navigation bar's color. * * @param activity The activity. * @param color The navigation bar's color. */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public static void setNavBarColor(@NonNull final Activity activity, @ColorInt final int color) { setNavBarColor(activity.getWindow(), color); } /** * Set the navigation bar's color. * * @param window The window. * @param color The navigation bar's color. */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public static void setNavBarColor(@NonNull final Window window, @ColorInt final int color) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setNavigationBarColor(color); } /** * Return the color of navigation bar. * * @param activity The activity. * @return the color of navigation bar */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public static int getNavBarColor(@NonNull final Activity activity) { return getNavBarColor(activity.getWindow()); } /** * Return the color of navigation bar. * * @param window The window. * @return the color of navigation bar */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public static int getNavBarColor(@NonNull final Window window) { return window.getNavigationBarColor(); } /** * Return whether the navigation bar visible. * * @return {@code true}: yes<br>{@code false}: no */ public static boolean isSupportNavBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { WindowManager wm = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE); if (wm == null) return false; Display display = wm.getDefaultDisplay(); Point size = new Point(); Point realSize = new Point(); display.getSize(size); display.getRealSize(realSize); return realSize.y != size.y || realSize.x != size.x; } boolean menu = ViewConfiguration.get(Utils.getApp()).hasPermanentMenuKey(); boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK); return !menu && !back; } /** * Set the nav bar's light mode. * * @param activity The activity. * @param isLightMode True to set nav bar light mode, false otherwise. */ public static void setNavBarLightMode(@NonNull final Activity activity, final boolean isLightMode) { setNavBarLightMode(activity.getWindow(), isLightMode); } /** * Set the nav bar's light mode. * * @param window The window. * @param isLightMode True to set nav bar light mode, false otherwise. */ public static void setNavBarLightMode(@NonNull final Window window, final boolean isLightMode) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { View decorView = window.getDecorView(); int vis = decorView.getSystemUiVisibility(); if (isLightMode) { vis |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; } else { vis &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; } decorView.setSystemUiVisibility(vis); } } /** * Is the nav bar light mode. * * @param activity The activity. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isNavBarLightMode(@NonNull final Activity activity) { return isNavBarLightMode(activity.getWindow()); } /** * Is the nav bar light mode. * * @param window The window. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isNavBarLightMode(@NonNull final Window window) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { View decorView = window.getDecorView(); int vis = decorView.getSystemUiVisibility(); return (vis & View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR) != 0; } return false; } public static void transparentNavBar(@NonNull final Activity activity) { transparentNavBar(activity.getWindow()); } public static void transparentNavBar(@NonNull final Window window) { if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { window.setNavigationBarContrastEnforced(false); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.setNavigationBarColor(Color.TRANSPARENT); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if ((window.getAttributes().flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0) { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } } View decorView = window.getDecorView(); int vis = decorView.getSystemUiVisibility(); int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; decorView.setSystemUiVisibility(vis | option); } }
Blankj/AndroidUtilCode
lib/utilcode/src/main/java/com/blankj/utilcode/util/BarUtils.java
300
package com.blankj.utilcode.util; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.os.Build; import android.os.SystemClock; import android.util.Log; import android.util.StateSet; import android.view.MotionEvent; import android.view.TouchDelegate; import android.view.View; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.core.view.ViewCompat; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/06/12 * desc : utils about click * </pre> */ public class ClickUtils { private static final int PRESSED_VIEW_SCALE_TAG = -1; private static final float PRESSED_VIEW_SCALE_DEFAULT_VALUE = -0.06f; private static final int PRESSED_VIEW_ALPHA_TAG = -2; private static final int PRESSED_VIEW_ALPHA_SRC_TAG = -3; private static final float PRESSED_VIEW_ALPHA_DEFAULT_VALUE = 0.8f; private static final int PRESSED_BG_ALPHA_STYLE = 4; private static final float PRESSED_BG_ALPHA_DEFAULT_VALUE = 0.9f; private static final int PRESSED_BG_DARK_STYLE = 5; private static final float PRESSED_BG_DARK_DEFAULT_VALUE = 0.9f; private static final long DEBOUNCING_DEFAULT_VALUE = 1000; private ClickUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * Apply scale animation for the views' click. * * @param views The views. */ public static void applyPressedViewScale(final View... views) { applyPressedViewScale(views, null); } /** * Apply scale animation for the views' click. * * @param views The views. * @param scaleFactors The factors of scale for the views. */ public static void applyPressedViewScale(final View[] views, final float[] scaleFactors) { if (views == null || views.length == 0) { return; } for (int i = 0; i < views.length; i++) { if (scaleFactors == null || i >= scaleFactors.length) { applyPressedViewScale(views[i], PRESSED_VIEW_SCALE_DEFAULT_VALUE); } else { applyPressedViewScale(views[i], scaleFactors[i]); } } } /** * Apply scale animation for the views' click. * * @param view The view. * @param scaleFactor The factor of scale for the view. */ public static void applyPressedViewScale(final View view, final float scaleFactor) { if (view == null) { return; } view.setTag(PRESSED_VIEW_SCALE_TAG, scaleFactor); view.setClickable(true); view.setOnTouchListener(OnUtilsTouchListener.getInstance()); } /** * Apply alpha for the views' click. * * @param views The views. */ public static void applyPressedViewAlpha(final View... views) { applyPressedViewAlpha(views, null); } /** * Apply alpha for the views' click. * * @param views The views. * @param alphas The alphas for the views. */ public static void applyPressedViewAlpha(final View[] views, final float[] alphas) { if (views == null || views.length == 0) return; for (int i = 0; i < views.length; i++) { if (alphas == null || i >= alphas.length) { applyPressedViewAlpha(views[i], PRESSED_VIEW_ALPHA_DEFAULT_VALUE); } else { applyPressedViewAlpha(views[i], alphas[i]); } } } /** * Apply scale animation for the views' click. * * @param view The view. * @param alpha The alpha for the view. */ public static void applyPressedViewAlpha(final View view, final float alpha) { if (view == null) { return; } view.setTag(PRESSED_VIEW_ALPHA_TAG, alpha); view.setTag(PRESSED_VIEW_ALPHA_SRC_TAG, view.getAlpha()); view.setClickable(true); view.setOnTouchListener(OnUtilsTouchListener.getInstance()); } /** * Apply alpha for the view's background. * * @param view The views. */ public static void applyPressedBgAlpha(View view) { applyPressedBgAlpha(view, PRESSED_BG_ALPHA_DEFAULT_VALUE); } /** * Apply alpha for the view's background. * * @param view The views. * @param alpha The alpha. */ public static void applyPressedBgAlpha(View view, float alpha) { applyPressedBgStyle(view, PRESSED_BG_ALPHA_STYLE, alpha); } /** * Apply alpha of dark for the view's background. * * @param view The views. */ public static void applyPressedBgDark(View view) { applyPressedBgDark(view, PRESSED_BG_DARK_DEFAULT_VALUE); } /** * Apply alpha of dark for the view's background. * * @param view The views. * @param darkAlpha The alpha of dark. */ public static void applyPressedBgDark(View view, float darkAlpha) { applyPressedBgStyle(view, PRESSED_BG_DARK_STYLE, darkAlpha); } private static void applyPressedBgStyle(View view, int style, float value) { if (view == null) return; Drawable background = view.getBackground(); Object tag = view.getTag(-style); if (tag instanceof Drawable) { ViewCompat.setBackground(view, (Drawable) tag); } else { background = createStyleDrawable(background, style, value); ViewCompat.setBackground(view, background); view.setTag(-style, background); } } private static Drawable createStyleDrawable(Drawable src, int style, float value) { if (src == null) { src = new ColorDrawable(0); } if (src.getConstantState() == null) return src; Drawable pressed = src.getConstantState().newDrawable().mutate(); if (style == PRESSED_BG_ALPHA_STYLE) { pressed = createAlphaDrawable(pressed, value); } else if (style == PRESSED_BG_DARK_STYLE) { pressed = createDarkDrawable(pressed, value); } Drawable disable = src.getConstantState().newDrawable().mutate(); disable = createAlphaDrawable(disable, 0.5f); StateListDrawable drawable = new StateListDrawable(); drawable.addState(new int[]{android.R.attr.state_pressed}, pressed); drawable.addState(new int[]{-android.R.attr.state_enabled}, disable); drawable.addState(StateSet.WILD_CARD, src); return drawable; } private static Drawable createAlphaDrawable(Drawable drawable, float alpha) { ClickDrawableWrapper drawableWrapper = new ClickDrawableWrapper(drawable); drawableWrapper.setAlpha((int) (alpha * 255)); return drawableWrapper; } private static Drawable createDarkDrawable(Drawable drawable, float alpha) { ClickDrawableWrapper drawableWrapper = new ClickDrawableWrapper(drawable); drawableWrapper.setColorFilter(getDarkColorFilter(alpha)); return drawableWrapper; } private static ColorMatrixColorFilter getDarkColorFilter(float darkAlpha) { return new ColorMatrixColorFilter(new ColorMatrix(new float[]{ darkAlpha, 0, 0, 0, 0, 0, darkAlpha, 0, 0, 0, 0, 0, darkAlpha, 0, 0, 0, 0, 0, 2, 0 })); } /** * Apply single debouncing for the view's click. * * @param view The view. * @param listener The listener. */ public static void applySingleDebouncing(final View view, final View.OnClickListener listener) { applySingleDebouncing(new View[]{view}, listener); } /** * Apply single debouncing for the view's click. * * @param view The view. * @param duration The duration of debouncing. * @param listener The listener. */ public static void applySingleDebouncing(final View view, @IntRange(from = 0) long duration, final View.OnClickListener listener) { applySingleDebouncing(new View[]{view}, duration, listener); } /** * Apply single debouncing for the views' click. * * @param views The views. * @param listener The listener. */ public static void applySingleDebouncing(final View[] views, final View.OnClickListener listener) { applySingleDebouncing(views, DEBOUNCING_DEFAULT_VALUE, listener); } /** * Apply single debouncing for the views' click. * * @param views The views. * @param duration The duration of debouncing. * @param listener The listener. */ public static void applySingleDebouncing(final View[] views, @IntRange(from = 0) long duration, final View.OnClickListener listener) { applyDebouncing(views, false, duration, listener); } /** * Apply global debouncing for the view's click. * * @param view The view. * @param listener The listener. */ public static void applyGlobalDebouncing(final View view, final View.OnClickListener listener) { applyGlobalDebouncing(new View[]{view}, listener); } /** * Apply global debouncing for the view's click. * * @param view The view. * @param duration The duration of debouncing. * @param listener The listener. */ public static void applyGlobalDebouncing(final View view, @IntRange(from = 0) long duration, final View.OnClickListener listener) { applyGlobalDebouncing(new View[]{view}, duration, listener); } /** * Apply global debouncing for the views' click. * * @param views The views. * @param listener The listener. */ public static void applyGlobalDebouncing(final View[] views, final View.OnClickListener listener) { applyGlobalDebouncing(views, DEBOUNCING_DEFAULT_VALUE, listener); } /** * Apply global debouncing for the views' click. * * @param views The views. * @param duration The duration of debouncing. * @param listener The listener. */ public static void applyGlobalDebouncing(final View[] views, @IntRange(from = 0) long duration, final View.OnClickListener listener) { applyDebouncing(views, true, duration, listener); } private static void applyDebouncing(final View[] views, final boolean isGlobal, @IntRange(from = 0) long duration, final View.OnClickListener listener) { if (views == null || views.length == 0 || listener == null) return; for (View view : views) { if (view == null) continue; view.setOnClickListener(new OnDebouncingClickListener(isGlobal, duration) { @Override public void onDebouncingClick(View v) { listener.onClick(v); } }); } } /** * Expand the click area of ​​the view * * @param view The view. * @param expandSize The size. */ public static void expandClickArea(@NonNull final View view, final int expandSize) { expandClickArea(view, expandSize, expandSize, expandSize, expandSize); } public static void expandClickArea(@NonNull final View view, final int expandSizeTop, final int expandSizeLeft, final int expandSizeRight, final int expandSizeBottom) { final View parentView = (View) view.getParent(); if (parentView == null) { Log.e("ClickUtils", "expandClickArea must have parent view."); return; } parentView.post(new Runnable() { @Override public void run() { final Rect rect = new Rect(); view.getHitRect(rect); rect.top -= expandSizeTop; rect.bottom += expandSizeBottom; rect.left -= expandSizeLeft; rect.right += expandSizeRight; parentView.setTouchDelegate(new TouchDelegate(rect, view)); } }); } private static final long TIP_DURATION = 2000L; private static long sLastClickMillis; private static int sClickCount; public static void back2HomeFriendly(final CharSequence tip) { back2HomeFriendly(tip, TIP_DURATION, Back2HomeFriendlyListener.DEFAULT); } public static void back2HomeFriendly(@NonNull final CharSequence tip, final long duration, @NonNull Back2HomeFriendlyListener listener) { long nowMillis = SystemClock.elapsedRealtime(); if (Math.abs(nowMillis - sLastClickMillis) < duration) { sClickCount++; if (sClickCount == 2) { UtilsBridge.startHomeActivity(); listener.dismiss(); sLastClickMillis = 0; } } else { sClickCount = 1; listener.show(tip, duration); sLastClickMillis = nowMillis; } } public interface Back2HomeFriendlyListener { Back2HomeFriendlyListener DEFAULT = new Back2HomeFriendlyListener() { @Override public void show(CharSequence text, long duration) { UtilsBridge.toastShowShort(text); } @Override public void dismiss() { UtilsBridge.toastCancel(); } }; void show(CharSequence text, long duration); void dismiss(); } public static abstract class OnDebouncingClickListener implements View.OnClickListener { private static boolean mEnabled = true; private static final Runnable ENABLE_AGAIN = new Runnable() { @Override public void run() { mEnabled = true; } }; private static boolean isValid(@NonNull final View view, final long duration) { return UtilsBridge.isValid(view, duration); } private long mDuration; private boolean mIsGlobal; public OnDebouncingClickListener() { this(true, DEBOUNCING_DEFAULT_VALUE); } public OnDebouncingClickListener(final boolean isGlobal) { this(isGlobal, DEBOUNCING_DEFAULT_VALUE); } public OnDebouncingClickListener(final long duration) { this(true, duration); } public OnDebouncingClickListener(final boolean isGlobal, final long duration) { mIsGlobal = isGlobal; mDuration = duration; } public abstract void onDebouncingClick(View v); @Override public final void onClick(View v) { if (mIsGlobal) { if (mEnabled) { mEnabled = false; v.postDelayed(ENABLE_AGAIN, mDuration); onDebouncingClick(v); } } else { if (isValid(v, mDuration)) { onDebouncingClick(v); } } } } public static abstract class OnMultiClickListener implements View.OnClickListener { private static final long INTERVAL_DEFAULT_VALUE = 666; private final int mTriggerClickCount; private final long mClickInterval; private long mLastClickTime; private int mClickCount; public OnMultiClickListener(int triggerClickCount) { this(triggerClickCount, INTERVAL_DEFAULT_VALUE); } public OnMultiClickListener(int triggerClickCount, long clickInterval) { this.mTriggerClickCount = triggerClickCount; this.mClickInterval = clickInterval; } public abstract void onTriggerClick(View v); public abstract void onBeforeTriggerClick(View v, int count); @Override public void onClick(View v) { if (mTriggerClickCount <= 1) { onTriggerClick(v); return; } long curTime = System.currentTimeMillis(); if (curTime - mLastClickTime < mClickInterval) { mClickCount++; if (mClickCount == mTriggerClickCount) { onTriggerClick(v); } else if (mClickCount < mTriggerClickCount) { onBeforeTriggerClick(v, mClickCount); } else { mClickCount = 1; onBeforeTriggerClick(v, mClickCount); } } else { mClickCount = 1; onBeforeTriggerClick(v, mClickCount); } mLastClickTime = curTime; } } private static class OnUtilsTouchListener implements View.OnTouchListener { public static OnUtilsTouchListener getInstance() { return LazyHolder.INSTANCE; } private OnUtilsTouchListener() {/**/} @Override public boolean onTouch(final View v, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN) { processScale(v, true); processAlpha(v, true); } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { processScale(v, false); processAlpha(v, false); } return false; } private void processScale(final View view, boolean isDown) { Object tag = view.getTag(PRESSED_VIEW_SCALE_TAG); if (!(tag instanceof Float)) return; float value = isDown ? 1 + (Float) tag : 1; view.animate() .scaleX(value) .scaleY(value) .setDuration(200) .start(); } private void processAlpha(final View view, boolean isDown) { Object tag = view.getTag(isDown ? PRESSED_VIEW_ALPHA_TAG : PRESSED_VIEW_ALPHA_SRC_TAG); if (!(tag instanceof Float)) return; view.setAlpha((Float) tag); } private static class LazyHolder { private static final OnUtilsTouchListener INSTANCE = new OnUtilsTouchListener(); } } static class ClickDrawableWrapper extends ShadowUtils.DrawableWrapper { private BitmapDrawable mBitmapDrawable = null; // 低版本ColorDrawable.setColorFilter无效,这里直接用画笔画上 private Paint mColorPaint = null; public ClickDrawableWrapper(Drawable drawable) { super(drawable); if (drawable instanceof ColorDrawable) { mColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); mColorPaint.setColor(((ColorDrawable) drawable).getColor()); } } @Override public void setColorFilter(ColorFilter cf) { super.setColorFilter(cf); // 低版本 StateListDrawable.selectDrawable 会重置 ColorFilter if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { if (mColorPaint != null) { mColorPaint.setColorFilter(cf); } } } @Override public void setAlpha(int alpha) { super.setAlpha(alpha); // 低版本 StateListDrawable.selectDrawable 会重置 Alpha if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { if (mColorPaint != null) { mColorPaint.setColor(((ColorDrawable) getWrappedDrawable()).getColor()); } } } @Override public void draw(Canvas canvas) { if (mBitmapDrawable == null) { Bitmap bitmap = Bitmap.createBitmap(getBounds().width(), getBounds().height(), Bitmap.Config.ARGB_8888); Canvas myCanvas = new Canvas(bitmap); if (mColorPaint != null) { myCanvas.drawRect(getBounds(), mColorPaint); } else { super.draw(myCanvas); } mBitmapDrawable = new BitmapDrawable(Resources.getSystem(), bitmap); mBitmapDrawable.setBounds(getBounds()); } mBitmapDrawable.draw(canvas); } } }
Blankj/AndroidUtilCode
lib/utilcode/src/main/java/com/blankj/utilcode/util/ClickUtils.java
302
M 1531456768 tags: Tree, Hash Table, DFS 给一串3-digit 的数组. 每个数字的表达一个TreeNode, 3 digit分别代表: depth.position.value 这串数字已经从小到大排列. 求: 所有可能的 root->leaf path 的所有可能的 path sum 总和. #### DFS, Hash Table - 因为`前两个digit可以uniquely identify`一个node, 所以可以把前两个digit作为key, 定位node. - 特点: 比如考虑root, 有 n 个leaf, 就会加 n 遍root, 因为有 n 个 unique path嘛. - 实现: 每个node, 上来先把curr value加进sum; 只要有child, 到这个node位置的以上path sum 就要被重加一次. - format: depth.position.value. (on same level, position may not be continuous) - approach: map each number into: <depth.position, value>, and dfs. - Start from dfs(map, rootKey, sum): - 1. add node value to sum - 2. compute potential child. - 3. check child existence, if exist, add sum to result (for both left/right child). Check existence using the map. - 4. also, if child exist, dfs into next level - Space, time O(n) ``` /* If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers. For each integer in this list: The hundreds digit represents the depth D of this node, 1 <= D <= 4. The tens digit represents the position P of this node in the level it belongs to, 1 <= P <= 8. The position is the same as that in a full binary tree. The units digit represents the value V of this node, 0 <= V <= 9. Given a list of ascending three-digits integers representing a binary with the depth smaller than 5. You need to return the sum of all paths from the root towards the leaves. Example 1: Input: [113, 215, 221] Output: 12 Explanation: The tree that the list represents is: 3 / \ 5 1 The path sum is (3 + 5) + (3 + 1) = 12. Example 2: Input: [113, 221] Output: 4 Explanation: The tree that the list represents is: 3 \ 1 The path sum is (3 + 1) = 4. */ /* Thoughts: Goal: find all paths sum format: depth.position.value. (on same level, position may not be continuous) approach: map each number into: <depth.position, value> start from dfs(map, rootKey, sum): 1. add node value to sum 2. compute potential child. 3. check child existence, if exist, add sum to result (for both left/right child). Check existence using the map. 4. also, if child exist, dfs into next level int dfs(num, ) */ class Solution { public int pathSum(int[] nums) { if (nums == null || nums.length == 0) return 0; // build map<[depth][position], value> Map<Integer, Integer> map = new HashMap<>(); for (int num : nums) map.put(num / 10, num % 10);// key = [depth][position] return dfs(map, nums[0] / 10, 0); // key = nums[0] / 10 } // key = [depth][position] private int dfs(Map<Integer, Integer> map, int key, int sum) { sum += map.get(key); // add curr value to sum; will be used in children dfs. // compute left/right child int level = key / 10; int position = key % 10; int leftChildKey = (level + 1) * 10 + position * 2 - 1; int rightChildKey = leftChildKey + 1; // if no children, return leaf sum if (!map.containsKey(leftChildKey) && !map.containsKey(rightChildKey)) return sum; // dfs on child, if applicable int result = 0; if (map.containsKey(leftChildKey)) result += dfs(map, leftChildKey, sum); if (map.containsKey(rightChildKey)) result += dfs(map, rightChildKey, sum); return result; } } ```
awangdev/leet-code
Java/Path Sum IV.java
304
package sorts; /** * 计数排序 * * Author: ZHENG */ public class CountingSort { // 计数排序,a是数组,n是数组大小。假设数组中存储的都是非负整数。 public static void countingSort(int[] a, int n) { if (n <= 1) return; // 查找数组中数据的范围 int max = a[0]; for (int i = 1; i < n; ++i) { if (max < a[i]) { max = a[i]; } } // 申请一个计数数组c,下标大小[0,max] int[] c = new int[max + 1]; // 计算每个元素的个数,放入c中 for (int i = 0; i < n; ++i) { c[a[i]]++; } // 依次累加 for (int i = 1; i < max + 1; ++i) { c[i] = c[i-1] + c[i]; } // 临时数组r,存储排序之后的结果 int[] r = new int[n]; // 计算排序的关键步骤了,有点难理解 for (int i = n - 1; i >= 0; --i) { int index = c[a[i]]-1; r[index] = a[i]; c[a[i]]--; } // 将结果拷贝会a数组 for (int i = 0; i < n; ++i) { a[i] = r[i]; } } }
wangzheng0822/algo
java/13_sorts/CountingSort.java
305
/** * File: n_queens.java * Created Time: 2023-05-04 * Author: krahets ([email protected]) */ package chapter_backtracking; import java.util.*; public class n_queens { /* 回溯算法:n 皇后 */ public static void backtrack(int row, int n, List<List<String>> state, List<List<List<String>>> res, boolean[] cols, boolean[] diags1, boolean[] diags2) { // 当放置完所有行时,记录解 if (row == n) { List<List<String>> copyState = new ArrayList<>(); for (List<String> sRow : state) { copyState.add(new ArrayList<>(sRow)); } res.add(copyState); return; } // 遍历所有列 for (int col = 0; col < n; col++) { // 计算该格子对应的主对角线和次对角线 int diag1 = row - col + n - 1; int diag2 = row + col; // 剪枝:不允许该格子所在列、主对角线、次对角线上存在皇后 if (!cols[col] && !diags1[diag1] && !diags2[diag2]) { // 尝试:将皇后放置在该格子 state.get(row).set(col, "Q"); cols[col] = diags1[diag1] = diags2[diag2] = true; // 放置下一行 backtrack(row + 1, n, state, res, cols, diags1, diags2); // 回退:将该格子恢复为空位 state.get(row).set(col, "#"); cols[col] = diags1[diag1] = diags2[diag2] = false; } } } /* 求解 n 皇后 */ public static List<List<List<String>>> nQueens(int n) { // 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位 List<List<String>> state = new ArrayList<>(); for (int i = 0; i < n; i++) { List<String> row = new ArrayList<>(); for (int j = 0; j < n; j++) { row.add("#"); } state.add(row); } boolean[] cols = new boolean[n]; // 记录列是否有皇后 boolean[] diags1 = new boolean[2 * n - 1]; // 记录主对角线上是否有皇后 boolean[] diags2 = new boolean[2 * n - 1]; // 记录次对角线上是否有皇后 List<List<List<String>>> res = new ArrayList<>(); backtrack(0, n, state, res, cols, diags1, diags2); return res; } public static void main(String[] args) { int n = 4; List<List<List<String>>> res = nQueens(n); System.out.println("输入棋盘长宽为 " + n); System.out.println("皇后放置方案共有 " + res.size() + " 种"); for (List<List<String>> state : res) { System.out.println("--------------------"); for (List<String> row : state) { System.out.println(row); } } } }
krahets/hello-algo
codes/java/chapter_backtracking/n_queens.java
306
package com.macro.mall.service.impl; import com.github.pagehelper.PageHelper; import com.macro.mall.dto.UmsMenuNode; import com.macro.mall.mapper.UmsMenuMapper; import com.macro.mall.model.*; import com.macro.mall.service.UmsMenuService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.stream.Collectors; /** * 后台菜单管理Service实现类 * Created by macro on 2020/2/2. */ @Service public class UmsMenuServiceImpl implements UmsMenuService { @Autowired private UmsMenuMapper menuMapper; @Override public int create(UmsMenu umsMenu) { umsMenu.setCreateTime(new Date()); updateLevel(umsMenu); return menuMapper.insert(umsMenu); } /** * 修改菜单层级 */ private void updateLevel(UmsMenu umsMenu) { if (umsMenu.getParentId() == 0) { //没有父菜单时为一级菜单 umsMenu.setLevel(0); } else { //有父菜单时选择根据父菜单level设置 UmsMenu parentMenu = menuMapper.selectByPrimaryKey(umsMenu.getParentId()); if (parentMenu != null) { umsMenu.setLevel(parentMenu.getLevel() + 1); } else { umsMenu.setLevel(0); } } } @Override public int update(Long id, UmsMenu umsMenu) { umsMenu.setId(id); updateLevel(umsMenu); return menuMapper.updateByPrimaryKeySelective(umsMenu); } @Override public UmsMenu getItem(Long id) { return menuMapper.selectByPrimaryKey(id); } @Override public int delete(Long id) { return menuMapper.deleteByPrimaryKey(id); } @Override public List<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); UmsMenuExample example = new UmsMenuExample(); example.setOrderByClause("sort desc"); example.createCriteria().andParentIdEqualTo(parentId); return menuMapper.selectByExample(example); } @Override public List<UmsMenuNode> treeList() { List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample()); List<UmsMenuNode> result = menuList.stream() .filter(menu -> menu.getParentId().equals(0L)) .map(menu -> covertMenuNode(menu, menuList)) .collect(Collectors.toList()); return result; } @Override public int updateHidden(Long id, Integer hidden) { UmsMenu umsMenu = new UmsMenu(); umsMenu.setId(id); umsMenu.setHidden(hidden); return menuMapper.updateByPrimaryKeySelective(umsMenu); } /** * 将UmsMenu转化为UmsMenuNode并设置children属性 */ private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) { UmsMenuNode node = new UmsMenuNode(); BeanUtils.copyProperties(menu, node); List<UmsMenuNode> children = menuList.stream() .filter(subMenu -> subMenu.getParentId().equals(menu.getId())) .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList()); node.setChildren(children); return node; } }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/service/impl/UmsMenuServiceImpl.java
307
package com.crossoverjie.concurrent; import com.crossoverjie.concurrent.communication.Notify; import com.crossoverjie.concurrent.future.Callable; import com.crossoverjie.concurrent.future.Future; import com.crossoverjie.concurrent.future.FutureTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.AbstractSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; /** * Function:线程池 * * @author crossoverJie * Date: 2019-05-14 10:51 * @since JDK 1.8 */ public class CustomThreadPool { private final static Logger LOGGER = LoggerFactory.getLogger(CustomThreadPool.class); private final ReentrantLock lock = new ReentrantLock(); /** * 最小线程数,也叫核心线程数 */ private volatile int miniSize; /** * 最大线程数 */ private volatile int maxSize; /** * 线程需要被回收的时间 */ private long keepAliveTime; private TimeUnit unit; /** * 存放线程的阻塞队列 */ private BlockingQueue<Runnable> workQueue; /** * 存放线程池 */ private volatile Set<Worker> workers; /** * 是否关闭线程池标志 */ private AtomicBoolean isShutDown = new AtomicBoolean(false); /** * 提交到线程池中的任务总数 */ private AtomicInteger totalTask = new AtomicInteger(); /** * 线程池任务全部执行完毕后的通知组件 */ private Object shutDownNotify = new Object(); private Notify notify; /** * @param miniSize 最小线程数 * @param maxSize 最大线程数 * @param keepAliveTime 线程保活时间 * @param unit * @param workQueue 阻塞队列 * @param notify 通知接口 */ public CustomThreadPool(int miniSize, int maxSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Notify notify) { this.miniSize = miniSize; this.maxSize = maxSize; this.keepAliveTime = keepAliveTime; this.unit = unit; this.workQueue = workQueue; this.notify = notify; workers = new ConcurrentHashSet<>(); } /** * 有返回值 * * @param callable * @param <T> * @return */ public <T> Future<T> submit(Callable<T> callable) { FutureTask<T> future = new FutureTask(callable); execute(future); return future; } /** * 执行任务 * * @param runnable 需要执行的任务 */ public void execute(Runnable runnable) { if (runnable == null) { throw new NullPointerException("runnable nullPointerException"); } if (isShutDown.get()) { LOGGER.info("线程池已经关闭,不能再提交任务!"); return; } //提交的线程 计数 totalTask.incrementAndGet(); //小于最小线程数时新建线程 if (workers.size() < miniSize) { addWorker(runnable); return; } boolean offer = workQueue.offer(runnable); //写入队列失败 if (!offer) { //创建新的线程执行 if (workers.size() < maxSize) { addWorker(runnable); return; } else { LOGGER.error("超过最大线程数"); try { //会阻塞 workQueue.put(runnable); } catch (InterruptedException e) { } } } } /** * 添加任务,需要加锁 * * @param runnable 任务 */ private void addWorker(Runnable runnable) { Worker worker = new Worker(runnable, true); worker.startTask(); workers.add(worker); } /** * 工作线程 */ private final class Worker extends Thread { private Runnable task; private Thread thread; /** * true --> 创建新的线程执行 * false --> 从队列里获取线程执行 */ private boolean isNewTask; public Worker(Runnable task, boolean isNewTask) { this.task = task; this.isNewTask = isNewTask; thread = this; } public void startTask() { thread.start(); } public void close() { thread.interrupt(); } @Override public void run() { Runnable task = null; if (isNewTask) { task = this.task; } boolean compile = true ; try { while ((task != null || (task = getTask()) != null)) { try { //执行任务 task.run(); } catch (Exception e) { compile = false ; throw e ; } finally { //任务执行完毕 task = null; int number = totalTask.decrementAndGet(); //LOGGER.info("number={}",number); if (number == 0) { synchronized (shutDownNotify) { shutDownNotify.notify(); } } } } } finally { //释放线程 boolean remove = workers.remove(this); //LOGGER.info("remove={},size={}", remove, workers.size()); if (!compile){ addWorker(null); } tryClose(true); } } } /** * 从队列中获取任务 * * @return */ private Runnable getTask() { //关闭标识及任务是否全部完成 if (isShutDown.get() && totalTask.get() == 0) { return null; } //while (true) { // // if (workers.size() > miniSize) { // boolean value = number.compareAndSet(number.get(), number.get() - 1); // if (value) { // return null; // } else { // continue; // } // } lock.lock(); try { Runnable task = null; if (workers.size() > miniSize) { //大于核心线程数时需要用保活时间获取任务 task = workQueue.poll(keepAliveTime, unit); } else { task = workQueue.take(); } if (task != null) { return task; } } catch (InterruptedException e) { return null; } finally { lock.unlock(); } return null; //} } /** * 任务执行完毕后关闭线程池 */ public void shutdown() { isShutDown.set(true); tryClose(true); //中断所有线程 //synchronized (shutDownNotify){ // while (totalTask.get() > 0){ // try { // shutDownNotify.wait(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } //} } /** * 立即关闭线程池,会造成任务丢失 */ public void shutDownNow() { isShutDown.set(true); tryClose(false); } /** * 阻塞等到任务执行完毕 */ public void mainNotify() { synchronized (shutDownNotify) { while (totalTask.get() > 0) { try { shutDownNotify.wait(); if (notify != null) { notify.notifyListen(); } } catch (InterruptedException e) { return; } } } } /** * 关闭线程池 * * @param isTry true 尝试关闭 --> 会等待所有任务执行完毕 * false 立即关闭线程池--> 任务有丢失的可能 */ private void tryClose(boolean isTry) { if (!isTry) { closeAllTask(); } else { if (isShutDown.get() && totalTask.get() == 0) { closeAllTask(); } } } /** * 关闭所有任务 */ private void closeAllTask() { for (Worker worker : workers) { //LOGGER.info("开始关闭"); worker.close(); } } /** * 获取工作线程数量 * * @return */ public int getWorkerCount() { return workers.size(); } /** * 内部存放工作线程容器,并发安全。 * * @param <T> */ private final class ConcurrentHashSet<T> extends AbstractSet<T> { private ConcurrentHashMap<T, Object> map = new ConcurrentHashMap<>(); private final Object PRESENT = new Object(); private AtomicInteger count = new AtomicInteger(); @Override public Iterator<T> iterator() { return map.keySet().iterator(); } @Override public boolean add(T t) { count.incrementAndGet(); return map.put(t, PRESENT) == null; } @Override public boolean remove(Object o) { count.decrementAndGet(); return map.remove(o) == PRESENT; } @Override public int size() { return count.get(); } } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/concurrent/CustomThreadPool.java
309
package io.mycat.statistic.stat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import io.mycat.server.parser.ServerParse; /** * SQL统计中,统计出来每个表的读,写的TPS,分辨出当前最热的表, * 并且根据是否有关联JOIN来区分为几个不同的“区域”,是一个重要功能,意味着,某些表可以转移到其他的数据库里,做智能优化。 * * 首先是每个表的读写TPS 2个指标,有时段。然后是 哪那些表有JOIN查询 ,来区分 独立的区域 * * @author zhuam * */ public class TableStat implements Comparable<TableStat> { //1、读写 //2、主表 //3、关联表 次数 //4、读写 TPS public String table; private final AtomicLong rCount = new AtomicLong(0); private final AtomicLong wCount = new AtomicLong(0); // 关联表 private final ConcurrentHashMap<String, RelaTable> relaTableMap = new ConcurrentHashMap<String, RelaTable>(); /** * 最后执行时间 */ private long lastExecuteTime; public TableStat(String table) { super(); this.table = table; } public void reset() { this.rCount.set(0); this.wCount.set(0); this.relaTableMap.clear(); this.lastExecuteTime = 0; } public void update(int sqlType, String sql, long startTime, long endTime, List<String> relaTables) { //记录 RW switch(sqlType) { case ServerParse.SELECT: this.rCount.incrementAndGet(); break; case ServerParse.UPDATE: case ServerParse.INSERT: case ServerParse.DELETE: case ServerParse.REPLACE: this.wCount.incrementAndGet(); break; } // 记录 关联表执行情况 for(String table: relaTables) { RelaTable relaTable = this.relaTableMap.get( table ); if ( relaTable == null ) { relaTable = new RelaTable(table, 1); } else { relaTable.incCount(); } this.relaTableMap.put(table, relaTable); } this.lastExecuteTime = endTime; } public String getTable() { return table; } public long getRCount() { return this.rCount.get(); } public long getWCount() { return this.wCount.get(); } public int getCount() { return (int)(getRCount()+getWCount()); } public List<RelaTable> getRelaTables() { List<RelaTable> tables = new ArrayList<RelaTable>(); tables.addAll( this.relaTableMap.values() ); return tables; } public long getLastExecuteTime() { return lastExecuteTime; } @Override public int compareTo(TableStat o) { long para = o.getCount() - getCount(); long para2 = o.getLastExecuteTime() - getLastExecuteTime(); return para == 0? (para2 == 0? o.getTable().hashCode() - getTable().hashCode() :(int) para2) : (int)para ; } @Override public boolean equals(Object obj) { if(obj instanceof TableStat) { return this.compareTo((TableStat)obj) == 0; } else { return super.equals(obj); } } /** * 关联表 * @author Ben * */ public static class RelaTable { private String tableName; private int count; public RelaTable(String tableName, int count) { super(); this.tableName = tableName; this.count = count; } public String getTableName() { return this.tableName; } public int getCount() { return this.count; } public void incCount() { this.count++; } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/statistic/stat/TableStat.java
310
package com.neo.dao.impl; import com.mongodb.WriteResult; import com.neo.dao.UserDao; import com.neo.entity.UserEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Component; /** * Created by summer on 2017/5/5. */ @Component public class UserDaoImpl implements UserDao { @Autowired private MongoTemplate mongoTemplate; /** * 创建对象 * @param user */ @Override public void saveUser(UserEntity user) { mongoTemplate.save(user); } /** * 根据用户名查询对象 * @param userName * @return */ @Override public UserEntity findUserByUserName(String userName) { Query query=new Query(Criteria.where("userName").is(userName)); UserEntity user = mongoTemplate.findOne(query , UserEntity.class); return user; } /** * 更新对象 * @param user */ @Override public int updateUser(UserEntity user) { Query query=new Query(Criteria.where("id").is(user.getId())); Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord()); //更新查询返回结果集的第一条 WriteResult result =mongoTemplate.updateFirst(query,update,UserEntity.class); //更新查询返回结果集的所有 // mongoTemplate.updateMulti(query,update,UserEntity.class); if(result!=null) return result.getN(); else return 0; } /** * 删除对象 * @param id */ @Override public void deleteUserById(Long id) { Query query=new Query(Criteria.where("id").is(id)); mongoTemplate.remove(query,UserEntity.class); } }
ityouknow/spring-boot-examples
1.x/spring-boot-mongodb/src/main/java/com/neo/dao/impl/UserDaoImpl.java
311
package com.xkcoding.orm.mybatis.plus.entity; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; /** * <p> * 角色实体类 * </p> * * @author yangkai.shen * @date Created in 2019-09-14 14:04 */ @Data @TableName("orm_role") @Accessors(chain = true) @EqualsAndHashCode(callSuper = true) public class Role extends Model<Role> { /** * 主键 */ private Long id; /** * 角色名 */ private String name; /** * 主键值,ActiveRecord 模式这个必须有,否则 xxById 的方法都将失效! * 即使使用 ActiveRecord 不会用到 RoleMapper,RoleMapper 这个接口也必须创建 */ @Override protected Serializable pkVal() { return this.id; } }
xkcoding/spring-boot-demo
demo-orm-mybatis-plus/src/main/java/com/xkcoding/orm/mybatis/plus/entity/Role.java
312
/* * 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.utils; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2016/1/25 * 描 述: * 修订历史: * ================================================ */ public class ApkUtils { /** 安装一个apk文件 */ public static void install(Context context, File uriFile) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(uriFile), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } /** 卸载一个app */ public static void uninstall(Context context, String packageName) { //通过程序的包名创建URI Uri packageURI = Uri.parse("package:" + packageName); //创建Intent意图 Intent intent = new Intent(Intent.ACTION_DELETE, packageURI); //执行卸载程序 context.startActivity(intent); } /** 检查手机上是否安装了指定的软件 */ public static boolean isAvailable(Context context, String packageName) { // 获取packagemanager final PackageManager packageManager = context.getPackageManager(); // 获取所有已安装程序的包信息 List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0); // 用于存储所有已安装程序的包名 List<String> packageNames = new ArrayList<>(); // 从pinfo中将包名字逐一取出,压入pName list中 if (packageInfos != null) { for (int i = 0; i < packageInfos.size(); i++) { String packName = packageInfos.get(i).packageName; packageNames.add(packName); } } // 判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE return packageNames.contains(packageName); } /** 检查手机上是否安装了指定的软件 */ public static boolean isAvailable(Context context, File file) { return isAvailable(context, getPackageName(context, file.getAbsolutePath())); } /** 根据文件路径获取包名 */ public static String getPackageName(Context context, String filePath) { PackageManager packageManager = context.getPackageManager(); PackageInfo info = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES); if (info != null) { ApplicationInfo appInfo = info.applicationInfo; return appInfo.packageName; //得到安装包名称 } return null; } /** 从apk中获取版本信息 */ public static String getChannelFromApk(Context context, String channelPrefix) { //从apk包中获取 ApplicationInfo appinfo = context.getApplicationInfo(); String sourceDir = appinfo.sourceDir; //默认放在meta-inf/里, 所以需要再拼接一下 String key = "META-INF/" + channelPrefix; String ret = ""; ZipFile zipfile = null; try { zipfile = new ZipFile(sourceDir); Enumeration<?> entries = zipfile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = ((ZipEntry) entries.nextElement()); String entryName = entry.getName(); if (entryName.startsWith(key)) { ret = entryName; break; } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipfile != null) { try { zipfile.close(); } catch (IOException e) { e.printStackTrace(); } } } String[] split = ret.split(channelPrefix); String channel = ""; if (split.length >= 2) { channel = ret.substring(key.length()); } return channel; } }
jeasonlzy/okhttp-OkGo
demo/src/main/java/com/lzy/demo/utils/ApkUtils.java
316
package org.pdown.gui.extension.mitm.intercept; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.monkeywie.proxyee.intercept.HttpProxyIntercept; import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptPipeline; import com.github.monkeywie.proxyee.util.HttpUtil; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.LastHttpContent; import io.netty.util.ReferenceCountUtil; import java.net.URLEncoder; import java.util.Arrays; import java.util.Set; import org.pdown.core.entity.HttpRequestInfo; import org.pdown.core.entity.HttpResponseInfo; import org.pdown.core.util.HttpDownUtil; import org.pdown.core.util.ProtoUtil.RequestProto; import org.pdown.gui.DownApplication; import org.pdown.gui.extension.ExtensionContent; import org.pdown.rest.form.HttpRequestForm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SniffIntercept extends HttpProxyIntercept { private final static Logger LOGGER = LoggerFactory.getLogger(SniffIntercept.class); private boolean matchFlag = false; private ByteBuf content; private boolean downFlag = false; @Override public void beforeRequest(Channel clientChannel, HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline) throws Exception { Set<String> sniffRegexs = ExtensionContent.getSniffRegexs(); if (sniffRegexs == null) { matchFlag = false; } else { matchFlag = sniffRegexs.stream().anyMatch(regex -> HttpUtil.checkUrl(httpRequest, regex)); } if (!matchFlag) { super.beforeRequest(clientChannel, httpRequest, pipeline); return; } String contentLength = httpRequest.headers().get(HttpHeaderNames.CONTENT_LENGTH); //缓存request content if (contentLength != null) { content = PooledByteBufAllocator.DEFAULT.buffer(); } pipeline.beforeRequest(clientChannel, HttpRequestInfo.adapter(httpRequest)); } @Override public void beforeRequest(Channel clientChannel, HttpContent httpContent, HttpProxyInterceptPipeline pipeline) throws Exception { if (!matchFlag) { super.beforeRequest(clientChannel, httpContent, pipeline); return; } if (content != null) { ByteBuf temp = httpContent.content().slice(); content.writeBytes(temp); if (httpContent instanceof LastHttpContent) { try { byte[] contentBts = new byte[content.readableBytes()]; content.readBytes(contentBts); ((HttpRequestInfo) pipeline.getHttpRequest()).setContent(contentBts); } finally { ReferenceCountUtil.release(content); } } } pipeline.beforeRequest(clientChannel, httpContent); } @Override public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) throws Exception { if (!matchFlag) { super.afterResponse(clientChannel, proxyChannel, httpResponse, pipeline); return; } if ((httpResponse.status().code() + "").indexOf("20") == 0) { //响应码为20x HttpHeaders httpResHeaders = httpResponse.headers(); String accept = pipeline.getHttpRequest().headers().get(HttpHeaderNames.ACCEPT); String contentType = httpResHeaders.get(HttpHeaderNames.CONTENT_TYPE); //有两种情况进行下载 1.url后缀为.xxx 2.带有CONTENT_DISPOSITION:ATTACHMENT响应头 String disposition = httpResHeaders.get(HttpHeaderNames.CONTENT_DISPOSITION); if (accept != null && accept.matches("^.*text/html.*$") && ((disposition != null && disposition.contains(HttpHeaderValues.ATTACHMENT) && disposition.contains(HttpHeaderValues.FILENAME)) || isDownContentType(contentType))) { downFlag = true; } HttpRequestInfo httpRequestInfo = (HttpRequestInfo) pipeline.getHttpRequest(); if (downFlag) { //如果是下载 LOGGER.debug("=====================下载===========================\n" + pipeline.getHttpRequest().toString() + "\n" + "------------------------------------------------" + httpResponse.toString() + "\n" + "================================================"); proxyChannel.close();//关闭嗅探下载连接 httpRequestInfo.setRequestProto(new RequestProto(pipeline.getRequestProto().getHost(), pipeline.getRequestProto().getPort(), pipeline.getRequestProto().getSsl())); HttpRequestForm requestForm = HttpRequestForm.parse(httpRequestInfo); HttpResponseInfo responseInfo = HttpDownUtil.getHttpResponseInfo(httpRequestInfo, null, null, (NioEventLoopGroup) clientChannel.eventLoop().parent()); httpResponse.headers().clear(); httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html"); httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); String js = "<script type=\"text/javascript\">window.history.go(-1)</script>"; HttpContent httpContent = new DefaultLastHttpContent(); httpContent.content().writeBytes(js.getBytes()); httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpContent.content().readableBytes()); clientChannel.writeAndFlush(httpResponse); clientChannel.writeAndFlush(httpContent); clientChannel.close(); ObjectMapper objectMapper = new ObjectMapper(); String requestParam = URLEncoder.encode(objectMapper.writeValueAsString(requestForm), "utf-8"); String responseParam = URLEncoder.encode(objectMapper.writeValueAsString(responseInfo), "utf-8"); String uri = "/#/tasks?request=" + requestParam + "&response=" + responseParam; DownApplication.INSTANCE.loadUri(uri, false); return; } else { if (httpRequestInfo.content() != null) { httpRequestInfo.setContent(null); } } } super.afterResponse(clientChannel, proxyChannel, httpResponse, pipeline); } @Override public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpContent httpContent, HttpProxyInterceptPipeline pipeline) throws Exception { if (!matchFlag) { super.afterResponse(clientChannel, proxyChannel, httpContent, pipeline); return; } if (downFlag) { httpContent.release(); } else { pipeline.afterResponse(clientChannel, proxyChannel, httpContent); } } //https://chromium.googlesource.com/chromium/src/+/master/net/base/mime_util.cc private static final String[] CONTENT_TYPES = { "application/javascript", "application/x-javascript", "application/wasm", "application/x-chrome-extension", "application/xhtml+xml", "application/font-woff", "application/json", "application/x-shockwave-flash", "audio/mpeg", "audio/flac", "audio/mp3", "audio/ogg", "audio/wav", "audio/webm", "audio/x-m4a", "image/gif", "image/jpeg", "image/png", "image/apng", "image/webp", "image/x-icon", "image/bmp", "image/jpeg", "image/svg+xml", "image/tiff", "image/vnd.microsoft.icon", "image/x-png", "image/x-xbitmap", "video/webm", "video/ogg", "video/mp4", "video/mpeg", "text/css", "text/html", "text/xml", "text/calendar", "text/html", "text/plain", "text/x-sh", "text/xml", "multipart/related", "message/rfc822", }; private boolean isDownContentType(String contentType) { if (contentType != null) { String contentTypeFinal = contentType.split(";")[0].trim().toLowerCase(); return Arrays.stream(CONTENT_TYPES).noneMatch(type -> contentTypeFinal.equals(type)); } return true; } }
proxyee-down-org/proxyee-down
main/src/main/java/org/pdown/gui/extension/mitm/intercept/SniffIntercept.java
318
package com.example.gsyvideoplayer; import android.Manifest; import android.content.Intent; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.example.gsyvideoplayer.databinding.ActivityListVideoBinding; import com.example.gsyvideoplayer.databinding.ActivityMainBinding; import com.example.gsyvideoplayer.simple.SimpleActivity; import com.example.gsyvideoplayer.utils.JumpUtils; import com.shuyu.gsyvideoplayer.GSYVideoManager; import com.shuyu.gsyvideoplayer.cache.CacheFactory; import com.shuyu.gsyvideoplayer.cache.ProxyCacheManager; import com.shuyu.gsyvideoplayer.player.IjkPlayerManager; import com.shuyu.gsyvideoplayer.player.PlayerFactory; import com.shuyu.gsyvideoplayer.player.SystemPlayerManager; import com.shuyu.gsyvideoplayer.utils.Debuger; import permissions.dispatcher.PermissionUtils; import tv.danmaku.ijk.media.exo2.Exo2PlayerManager; import tv.danmaku.ijk.media.exo2.ExoPlayerCacheManager; public class MainActivity extends AppCompatActivity implements View.OnClickListener { ActivityMainBinding binding; final String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; int i = 0; int j = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); Debuger.enable(); binding.openBtn.setOnClickListener(this); binding.listBtn.setOnClickListener(this); binding.listBtn2.setOnClickListener(this); binding.listDetail.setOnClickListener(this); binding.clearCache.setOnClickListener(this); binding.recycler.setOnClickListener(this); binding.recycler2.setOnClickListener(this); binding.recycler2.setOnClickListener(this); binding.listDetailList.setOnClickListener(this); binding.webDetail.setOnClickListener(this); binding.danmakuVideo.setOnClickListener(this); binding.fragmentVideo.setOnClickListener(this); binding.moreType.setOnClickListener(this); binding.inputType.setOnClickListener(this); binding.openBtnEmpty.setOnClickListener(this); binding.openControl.setOnClickListener(this); binding.openFilter.setOnClickListener(this); binding.openBtnPick.setOnClickListener(this); binding.openBtnAuto.setOnClickListener(this); binding.openScroll.setOnClickListener(this); binding.openWindow.setOnClickListener(this); binding.openBtnAd.setOnClickListener(this); binding.openBtnMulti.setOnClickListener(this); binding.openBtnAd2.setOnClickListener(this); binding.openListAd.setOnClickListener(this); binding.openCustomExo.setOnClickListener(this); binding.openSimple.setOnClickListener(this); binding.openSwitch.setOnClickListener(this); binding.mediaCodec.setOnClickListener(this); binding.detailNormalActivity.setOnClickListener(this); binding.detailDownloadActivity.setOnClickListener(this); binding.detailAudioActivity.setOnClickListener(this); binding.detailSubtitleActivity.setOnClickListener(this); binding.changeCore.setOnClickListener(this); binding.viewPager2Activity.setOnClickListener(this); binding.changeCache.setOnClickListener(this); binding.detailDownloadExoActivity.setOnClickListener(this); binding.tvPlay.setOnClickListener(this); boolean hadPermission = PermissionUtils.hasSelfPermissions(this, permissions); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !hadPermission) { String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; requestPermissions(permissions, 1110); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); boolean sdPermissionResult = PermissionUtils.verifyPermissions(grantResults); if (!sdPermissionResult) { Toast.makeText(this, "没获取到sd卡权限,无法播放本地视频哦", Toast.LENGTH_LONG).show(); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.open_simple: //简单的播放 startActivity(new Intent(this, SimpleActivity.class)); break; case R.id.open_btn: //直接一个页面播放的 JumpUtils.goToVideoPlayer(this, binding.openBtn); break; case R.id.list_btn: //普通列表播放,只支持全屏,但是不支持屏幕重力旋转,滑动后不持有 JumpUtils.goToVideoPlayer(this); break; case R.id.list_btn_2: //支持全屏重力旋转的列表播放,滑动后不会被销毁 JumpUtils.goToVideoPlayer2(this); break; case R.id.recycler: //recycler的demo JumpUtils.goToVideoRecyclerPlayer(this); break; case R.id.recycler_2: //recycler的demo JumpUtils.goToVideoRecyclerPlayer2(this); break; case R.id.list_detail: //支持旋转全屏的详情模式 JumpUtils.goToDetailPlayer(this); break; case R.id.list_detail_list: //播放一个连续列表 JumpUtils.goToDetailListPlayer(this); break; case R.id.web_detail: //正常播放,带preview JumpUtils.gotoWebDetail(this); break; case R.id.danmaku_video: //播放一个弹幕视频 JumpUtils.gotoDanmaku(this); break; case R.id.fragment_video: //播放一个弹幕视频 JumpUtils.gotoFragment(this); break; case R.id.more_type: //跳到多类型详情播放器,比如切换分辨率,旋转等 JumpUtils.gotoMoreType(this); break; case R.id.input_type: JumpUtils.gotoInput(this); break; case R.id.open_btn_empty: JumpUtils.goToPlayEmptyControlActivity(this, binding.openBtnEmpty); break; case R.id.open_control: JumpUtils.gotoControl(this); break; case R.id.open_filter: JumpUtils.gotoFilter(this); break; case R.id.open_btn_pick: //无缝切换 JumpUtils.goToVideoPickPlayer(this, binding.openBtn); break; case R.id.open_btn_auto: //列表自动播放 JumpUtils.goToAutoVideoPlayer(this); break; case R.id.open_scroll: //列表自动播放 JumpUtils.goToScrollDetailPlayer(this); break; case R.id.open_window: //多窗体下的悬浮窗 JumpUtils.goToScrollWindow(this); break; case R.id.open_btn_ad: //广告 JumpUtils.goToVideoADPlayer(this); break; case R.id.open_btn_multi: //多个同时播放 JumpUtils.goToMultiVideoPlayer(this); break; case R.id.open_btn_ad2: //多个同时播放 JumpUtils.goToVideoADPlayer2(this); break; case R.id.open_list_ad: //多个同时播放 JumpUtils.goToADListVideoPlayer(this); break; case R.id.open_custom_exo: //多个同时播放 JumpUtils.goToDetailExoListPlayer(this); break; case R.id.open_switch: JumpUtils.goToSwitch(this); break; case R.id.media_codec: JumpUtils.goMediaCodec(this); break; case R.id.detail_normal_activity: JumpUtils.goToDetailNormalActivity(this); break; case R.id.detail_download_activity: JumpUtils.goToDetailDownloadActivity(this); break; case R.id.detail_download_exo_activity: JumpUtils.goToDetailDownloadExoActivity(this); break; case R.id.detail_subtitle_activity: JumpUtils.goToGSYExoSubTitleDetailPlayer(this); break; case R.id.detail_audio_activity: JumpUtils.goToDetailAudioActivity(this); break; case R.id.view_pager2_activity: JumpUtils.goToViewPager2Activity(this); break; case R.id.change_core: i += 1; if (i % 3 == 0) { PlayerFactory.setPlayManager(IjkPlayerManager.class); binding.changeCore.setText("IJK 内核"); } else if (i % 3 == 1) { PlayerFactory.setPlayManager(Exo2PlayerManager.class); binding.changeCore.setText("EXO 内核"); } else if (i % 3 == 2) { PlayerFactory.setPlayManager(SystemPlayerManager.class); binding.changeCore.setText("系统 内核"); } break; case R.id.change_cache: j += 1; if (j % 2 == 0) { CacheFactory.setCacheManager(ProxyCacheManager.class); binding.changeCache.setText("Proxy 缓存"); } else { CacheFactory.setCacheManager(ExoPlayerCacheManager.class); binding.changeCache.setText("EXO 特有缓存"); } break; case R.id.clear_cache: //清理缓存 GSYVideoManager.instance().clearAllDefaultCache(MainActivity.this); //String url = "https://res.exexm.com/cw_145225549855002"; //GSYVideoManager.clearDefaultCache(MainActivity.this, url); break; case R.id.tv_play: JumpUtils.goToTVVideoPlayer(this,binding.tvPlay); break; } } }
CarGuo/GSYVideoPlayer
app/src/main/java/com/example/gsyvideoplayer/MainActivity.java
319
package org.ansj.library; import org.ansj.dic.PathToStream; import org.ansj.domain.KV; import org.ansj.util.MyStaticValue; import org.nlpcn.commons.lang.tire.domain.SmartForest; import org.nlpcn.commons.lang.util.IOUtil; import org.nlpcn.commons.lang.util.StringUtil; import org.nlpcn.commons.lang.util.logging.Log; import java.io.BufferedReader; import java.util.*; import java.util.Map.Entry; public class SynonymsLibrary { private static final Log LOG = MyStaticValue.getLog(SynonymsLibrary.class); // 同义词典 private static final Map<String, KV<String, SmartForest<List<String>>>> SYNONYMS = new HashMap<>(); public static final String DEFAULT = "synonyms"; static { for (Entry<String, String> entry : MyStaticValue.ENV.entrySet()) { if (entry.getKey().startsWith(DEFAULT)) { put(entry.getKey(), entry.getValue()); } } putIfAbsent(DEFAULT, "library/synonyms.dic"); } public static SmartForest<List<String>> get() { return get(DEFAULT); } /** */ public static SmartForest<List<String>> get(String key) { KV<String, SmartForest<List<String>>> kv = SYNONYMS.get(key); if (kv == null) { if (MyStaticValue.ENV.containsKey(key)) { putIfAbsent(key, MyStaticValue.ENV.get(key)); return get(key); } LOG.warn("crf " + key + " not found in config "); return null; } SmartForest<List<String>> sw = kv.getV(); if (sw == null) { sw = init(key, kv, false); } return sw; } /** * 加载词典 * * @param key * @param kv * @param reload 是否更新词典 * @return */ private static synchronized SmartForest<List<String>> init(String key, KV<String, SmartForest<List<String>>> kv, boolean reload) { SmartForest<List<String>> forest = kv.getV(); if (forest != null) { if (reload) { forest.clear(); } else { return forest; } } else { forest = new SmartForest<>(); } LOG.debug("begin init synonyms " + kv.getK()); long start = System.currentTimeMillis(); try (BufferedReader reader = IOUtil.getReader(PathToStream.stream(kv.getK()), IOUtil.UTF8)) { String temp = null; while ((temp = reader.readLine()) != null) { if (StringUtil.isBlank(temp)) { continue; } String[] split = temp.split("\t"); List<String> list = new ArrayList<>(); for (String word : split) { if (StringUtil.isBlank(word)) { continue; } list.add(word); } if (split.length <= 1) { LOG.warn(temp + " in synonymsLibrary not in to library !"); continue; } for (int i = 0; i < split.length; i++) { forest.add(split[i], list); } } kv.setV(forest); LOG.info("load synonyms use time:" + (System.currentTimeMillis() - start) + " path is : " + kv.getK()); return forest; } catch (Exception e) { LOG.error("Init synonyms library error :" + e.getMessage() + ", path: " + kv.getK()); SYNONYMS.remove(key); return null; } } /** * 动态添加 * * @param dicDefault * @param dicDefault2 * @param dic2 */ public static void put(String key, String path) { put(key, path, null); } public static void put(String key, String path, SmartForest<List<String>> value) { SYNONYMS.put(key, KV.with(path, value)); MyStaticValue.ENV.put(key, path); } /** * 删除一个key * * @param key * @return */ public static KV<String, SmartForest<List<String>>> remove(String key) { KV<String, SmartForest<List<String>>> kv = SYNONYMS.get(key); if (kv != null && kv.getV() != null) { //先清空后删除 kv.getV().clear(); } MyStaticValue.ENV.remove(key) ; return SYNONYMS.remove(key); } /** * 刷新一个,将值设置为null * * @param key * @return */ public static void reload(String key) { if (!MyStaticValue.ENV.containsKey(key)) { //如果变量中不存在直接删掉这个key不解释了 remove(key); } putIfAbsent(key, MyStaticValue.ENV.get(key)); KV<String, SmartForest<List<String>>> kv = SYNONYMS.get(key); init(key, kv, true); } public static Set<String> keys() { return SYNONYMS.keySet(); } public static void putIfAbsent(String key, String path) { if (!SYNONYMS.containsKey(key)) { SYNONYMS.put(key, KV.with(path, (SmartForest<List<String>>) null)); } } /** * 覆盖更新同义词 [中国, 中华, 我国] -> replace([中国,华夏]) -> [中国,华夏] * * @param words */ public static void insert(String key, String[] words) { SmartForest<List<String>> synonyms = get(key); List<String> list = new ArrayList<>(); for (String word : words) { if (StringUtil.isBlank(word)) { continue; } list.add(word); } if (list.size() <= 1) { LOG.warn(Arrays.toString(words) + " not have any change because it less than 2 word"); return; } Set<String> set = findAllWords(key, words); for (String word : list) { set.remove(word); synonyms.add(word, list); } for (String word : set) { //删除所有 synonyms.remove(word); synonyms.getBranch(word).setParam(null); } } private static Set<String> findAllWords(String key, String[] words) { SmartForest<List<String>> synonyms = get(key); Set<String> set = new HashSet<>(); for (String word : words) { SmartForest<List<String>> branch = synonyms.getBranch(word); if (branch != null) { List<String> params = branch.getParam(); if (params != null) { set.addAll(params); } } } return set; } /** * 合并更新同义词 覆盖更新同义词 [中国, 中华, 我国] -> append([中国,华夏]) -> [中国, 中华, 我国 , 华夏] * * @param words */ public static void append(String key, String[] words) { SmartForest<List<String>> synonyms = get(key); Set<String> set = new HashSet<>(); for (String word : words) { if (StringUtil.isBlank(word)) { continue; } set.add(word); } if (set.size() <= 1) { LOG.warn(Arrays.toString(words) + " not have any change because it less than 2 word"); return; } set.addAll(findAllWords(key, words)); List<String> list = new ArrayList<>(set); for (String word : list) { synonyms.addBranch(word, list); } } /** * 从同义词组中删除掉一个词 [中国, 中华, 我国] -> remove(我国) -> [中国, 中华] * * @param words */ public static void remove(String key, String word) { SmartForest<List<String>> synonyms = get(key); SmartForest<List<String>> branch = synonyms.getBranch(word); if (branch == null || branch.getStatus() < 2) { return; } List<String> params = branch.getParam(); synonyms.remove(word); branch.setParam(null); params.remove(word); if (params.size() == 1) { //如果是1 个也删除 synonyms.remove(params.get(0)); params.remove(0); } else { params.remove(word); } } }
NLPchina/ansj_seg
src/main/java/org/ansj/library/SynonymsLibrary.java
320
package org.jeecg.config.shiro; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.shiro.mgt.DefaultSessionStorageEvaluator; import org.apache.shiro.mgt.DefaultSubjectDAO; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.crazycake.shiro.*; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.util.oConvertUtils; import org.jeecg.config.JeecgBaseConfig; import org.jeecg.config.shiro.filters.CustomShiroFilterFactoryBean; import org.jeecg.config.shiro.filters.JwtFilter; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.data.redis.RedisProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.*; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.env.Environment; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.filter.DelegatingFilterProxy; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import javax.annotation.Resource; import javax.servlet.DispatcherType; import javax.servlet.Filter; import java.lang.reflect.Method; import java.util.*; /** * @author: Scott * @date: 2018/2/7 * @description: shiro 配置类 */ @Slf4j @Configuration // 免认证注解 @IgnoreAuth 注解生效范围配置 @ComponentScan(basePackages = {"org.jeecg.**.controller"}) public class ShiroConfig { @Resource private LettuceConnectionFactory lettuceConnectionFactory; @Autowired private Environment env; @Resource private JeecgBaseConfig jeecgBaseConfig; @Autowired(required = false) private RedisProperties redisProperties; /** * Filter Chain定义说明 * * 1、一个URL可以配置多个Filter,使用逗号分隔 * 2、当设置多个过滤器时,全部验证通过,才视为通过 * 3、部分过滤器可指定参数,如perms,roles */ @Bean("shiroFilterFactoryBean") public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) { CustomShiroFilterFactoryBean shiroFilterFactoryBean = new CustomShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); // 拦截器 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); //支持yml方式,配置拦截排除 if(jeecgBaseConfig!=null && jeecgBaseConfig.getShiro()!=null){ String shiroExcludeUrls = jeecgBaseConfig.getShiro().getExcludeUrls(); if(oConvertUtils.isNotEmpty(shiroExcludeUrls)){ String[] permissionUrl = shiroExcludeUrls.split(","); for(String url : permissionUrl){ filterChainDefinitionMap.put(url,"anon"); } } } // 配置不会被拦截的链接 顺序判断 filterChainDefinitionMap.put("/sys/cas/client/validateLogin", "anon"); //cas验证登录 filterChainDefinitionMap.put("/sys/randomImage/**", "anon"); //登录验证码接口排除 filterChainDefinitionMap.put("/sys/checkCaptcha", "anon"); //登录验证码接口排除 filterChainDefinitionMap.put("/sys/login", "anon"); //登录接口排除 filterChainDefinitionMap.put("/sys/mLogin", "anon"); //登录接口排除 filterChainDefinitionMap.put("/sys/logout", "anon"); //登出接口排除 filterChainDefinitionMap.put("/sys/thirdLogin/**", "anon"); //第三方登录 filterChainDefinitionMap.put("/sys/getEncryptedString", "anon"); //获取加密串 filterChainDefinitionMap.put("/sys/sms", "anon");//短信验证码 filterChainDefinitionMap.put("/sys/phoneLogin", "anon");//手机登录 filterChainDefinitionMap.put("/sys/user/checkOnlyUser", "anon");//校验用户是否存在 filterChainDefinitionMap.put("/sys/user/register", "anon");//用户注册 filterChainDefinitionMap.put("/sys/user/phoneVerification", "anon");//用户忘记密码验证手机号 filterChainDefinitionMap.put("/sys/user/passwordChange", "anon");//用户更改密码 filterChainDefinitionMap.put("/auth/2step-code", "anon");//登录验证码 filterChainDefinitionMap.put("/sys/common/static/**", "anon");//图片预览 &下载文件不限制token filterChainDefinitionMap.put("/sys/common/pdf/**", "anon");//pdf预览 //filterChainDefinitionMap.put("/sys/common/view/**", "anon");//图片预览不限制token //filterChainDefinitionMap.put("/sys/common/download/**", "anon");//文件下载不限制token filterChainDefinitionMap.put("/generic/**", "anon");//pdf预览需要文件 filterChainDefinitionMap.put("/sys/getLoginQrcode/**", "anon"); //登录二维码 filterChainDefinitionMap.put("/sys/getQrcodeToken/**", "anon"); //监听扫码 filterChainDefinitionMap.put("/sys/checkAuth", "anon"); //授权接口排除 //update-begin--Author:scott Date:20221116 for:排除静态资源后缀 filterChainDefinitionMap.put("/", "anon"); filterChainDefinitionMap.put("/doc.html", "anon"); filterChainDefinitionMap.put("/**/*.js", "anon"); filterChainDefinitionMap.put("/**/*.css", "anon"); filterChainDefinitionMap.put("/**/*.html", "anon"); filterChainDefinitionMap.put("/**/*.svg", "anon"); filterChainDefinitionMap.put("/**/*.pdf", "anon"); filterChainDefinitionMap.put("/**/*.jpg", "anon"); filterChainDefinitionMap.put("/**/*.png", "anon"); filterChainDefinitionMap.put("/**/*.gif", "anon"); filterChainDefinitionMap.put("/**/*.ico", "anon"); filterChainDefinitionMap.put("/**/*.ttf", "anon"); filterChainDefinitionMap.put("/**/*.woff", "anon"); filterChainDefinitionMap.put("/**/*.woff2", "anon"); //update-end--Author:scott Date:20221116 for:排除静态资源后缀 filterChainDefinitionMap.put("/druid/**", "anon"); filterChainDefinitionMap.put("/swagger-ui.html", "anon"); filterChainDefinitionMap.put("/swagger**/**", "anon"); filterChainDefinitionMap.put("/webjars/**", "anon"); filterChainDefinitionMap.put("/v2/**", "anon"); // update-begin--Author:sunjianlei Date:20210510 for:排除消息通告查看详情页面(用于第三方APP) filterChainDefinitionMap.put("/sys/annountCement/show/**", "anon"); // update-end--Author:sunjianlei Date:20210510 for:排除消息通告查看详情页面(用于第三方APP) //积木报表排除 filterChainDefinitionMap.put("/jmreport/**", "anon"); filterChainDefinitionMap.put("/**/*.js.map", "anon"); filterChainDefinitionMap.put("/**/*.css.map", "anon"); //拖拽仪表盘设计器排除 filterChainDefinitionMap.put("/drag/view", "anon"); filterChainDefinitionMap.put("/drag/page/queryById", "anon"); filterChainDefinitionMap.put("/drag/onlDragDatasetHead/getAllChartData", "anon"); filterChainDefinitionMap.put("/drag/onlDragDatasetHead/getTotalData", "anon"); filterChainDefinitionMap.put("/drag/mock/json/**", "anon"); //大屏模板例子 filterChainDefinitionMap.put("/test/bigScreen/**", "anon"); filterChainDefinitionMap.put("/bigscreen/template1/**", "anon"); filterChainDefinitionMap.put("/bigscreen/template2/**", "anon"); //filterChainDefinitionMap.put("/test/jeecgDemo/rabbitMqClientTest/**", "anon"); //MQ测试 //filterChainDefinitionMap.put("/test/jeecgDemo/html", "anon"); //模板页面 //filterChainDefinitionMap.put("/test/jeecgDemo/redis/**", "anon"); //redis测试 //websocket排除 filterChainDefinitionMap.put("/websocket/**", "anon");//系统通知和公告 filterChainDefinitionMap.put("/newsWebsocket/**", "anon");//CMS模块 filterChainDefinitionMap.put("/vxeSocket/**", "anon");//JVxeTable无痕刷新示例 //性能监控——安全隐患泄露TOEKN(durid连接池也有) //filterChainDefinitionMap.put("/actuator/**", "anon"); //测试模块排除 filterChainDefinitionMap.put("/test/seata/**", "anon"); //错误路径排除 filterChainDefinitionMap.put("/error", "anon"); // 企业微信证书排除 filterChainDefinitionMap.put("/WW_verify*", "anon"); // 通过注解免登录url List<String> ignoreAuthUrlList = collectIgnoreAuthUrl(); if (!CollectionUtils.isEmpty(ignoreAuthUrlList)) { for (String url : ignoreAuthUrlList) { filterChainDefinitionMap.put(url, "anon"); } } // 添加自己的过滤器并且取名为jwt Map<String, Filter> filterMap = new HashMap<String, Filter>(1); //如果cloudServer为空 则说明是单体 需要加载跨域配置【微服务跨域切换】 Object cloudServer = env.getProperty(CommonConstant.CLOUD_SERVER_KEY); filterMap.put("jwt", new JwtFilter(cloudServer==null)); shiroFilterFactoryBean.setFilters(filterMap); // <!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 filterChainDefinitionMap.put("/**", "jwt"); // 未授权界面返回JSON shiroFilterFactoryBean.setUnauthorizedUrl("/sys/common/403"); shiroFilterFactoryBean.setLoginUrl("/sys/common/403"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } //update-begin---author:chenrui ---date:20240126 for:【QQYUN-7932】AI助手------------ @Bean public FilterRegistrationBean shiroFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new DelegatingFilterProxy("shiroFilterFactoryBean")); registration.setEnabled(true); registration.addUrlPatterns("/*"); //支持异步 registration.setAsyncSupported(true); registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC); return registration; } //update-end---author:chenrui ---date:20240126 for:【QQYUN-7932】AI助手------------ @Bean("securityManager") public DefaultWebSecurityManager securityManager(ShiroRealm myRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(myRealm); /* * 关闭shiro自带的session,详情见文档 * http://shiro.apache.org/session-management.html#SessionManagement- * StatelessApplications%28Sessionless%29 */ DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO(); DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator(); defaultSessionStorageEvaluator.setSessionStorageEnabled(false); subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator); securityManager.setSubjectDAO(subjectDAO); //自定义缓存实现,使用redis securityManager.setCacheManager(redisCacheManager()); return securityManager; } /** * 下面的代码是添加注解支持 * @return */ @Bean @DependsOn("lifecycleBeanPostProcessor") public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); defaultAdvisorAutoProxyCreator.setProxyTargetClass(true); /** * 解决重复代理问题 github#994 * 添加前缀判断 不匹配 任何Advisor */ defaultAdvisorAutoProxyCreator.setUsePrefix(true); defaultAdvisorAutoProxyCreator.setAdvisorBeanNamePrefix("_no_advisor"); return defaultAdvisorAutoProxyCreator; } @Bean public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor; } /** * cacheManager 缓存 redis实现 * 使用的是shiro-redis开源插件 * * @return */ public RedisCacheManager redisCacheManager() { log.info("===============(1)创建缓存管理器RedisCacheManager"); RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); //redis中针对不同用户缓存(此处的id需要对应user实体中的id字段,用于唯一标识) redisCacheManager.setPrincipalIdFieldName("id"); //用户权限信息缓存时间 redisCacheManager.setExpire(200000); return redisCacheManager; } /** * 配置shiro redisManager * 使用的是shiro-redis开源插件 * * @return */ @Bean public IRedisManager redisManager() { log.info("===============(2)创建RedisManager,连接Redis.."); IRedisManager manager; // sentinel cluster redis(【issues/5569】shiro集成 redis 不支持 sentinel 方式部署的redis集群 #5569) if (Objects.nonNull(redisProperties) && Objects.nonNull(redisProperties.getSentinel()) && !CollectionUtils.isEmpty(redisProperties.getSentinel().getNodes())) { RedisSentinelManager sentinelManager = new RedisSentinelManager(); sentinelManager.setMasterName(redisProperties.getSentinel().getMaster()); sentinelManager.setHost(String.join(",", redisProperties.getSentinel().getNodes())); sentinelManager.setPassword(redisProperties.getSentinel().getPassword()); sentinelManager.setDatabase(redisProperties.getDatabase()); return sentinelManager; } // redis 单机支持,在集群为空,或者集群无机器时候使用 add by [email protected] if (lettuceConnectionFactory.getClusterConfiguration() == null || lettuceConnectionFactory.getClusterConfiguration().getClusterNodes().isEmpty()) { RedisManager redisManager = new RedisManager(); redisManager.setHost(lettuceConnectionFactory.getHostName() + ":" + lettuceConnectionFactory.getPort()); //(lettuceConnectionFactory.getPort()); redisManager.setDatabase(lettuceConnectionFactory.getDatabase()); redisManager.setTimeout(0); if (!StringUtils.isEmpty(lettuceConnectionFactory.getPassword())) { redisManager.setPassword(lettuceConnectionFactory.getPassword()); } manager = redisManager; }else{ // redis集群支持,优先使用集群配置 RedisClusterManager redisManager = new RedisClusterManager(); Set<HostAndPort> portSet = new HashSet<>(); lettuceConnectionFactory.getClusterConfiguration().getClusterNodes().forEach(node -> portSet.add(new HostAndPort(node.getHost() , node.getPort()))); //update-begin--Author:scott Date:20210531 for:修改集群模式下未设置redis密码的bug issues/I3QNIC if (oConvertUtils.isNotEmpty(lettuceConnectionFactory.getPassword())) { JedisCluster jedisCluster = new JedisCluster(portSet, 2000, 2000, 5, lettuceConnectionFactory.getPassword(), new GenericObjectPoolConfig()); redisManager.setPassword(lettuceConnectionFactory.getPassword()); redisManager.setJedisCluster(jedisCluster); } else { JedisCluster jedisCluster = new JedisCluster(portSet); redisManager.setJedisCluster(jedisCluster); } //update-end--Author:scott Date:20210531 for:修改集群模式下未设置redis密码的bug issues/I3QNIC manager = redisManager; } return manager; } @SneakyThrows public List<String> collectIgnoreAuthUrl() { List<String> ignoreAuthUrls = new ArrayList<>(); ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AnnotationTypeFilter(RestController.class)); // 获取当前类的扫描注解的配置 Set<BeanDefinition> components = new HashSet<>(); for (String basePackage : AnnotationUtils.getAnnotation(ShiroConfig.class, ComponentScan.class).basePackages()) { components.addAll(provider.findCandidateComponents(basePackage)); } // 逐个匹配获取免认证路径 for (BeanDefinition component : components) { String beanClassName = component.getBeanClassName(); Class<?> clazz = Class.forName(beanClassName); RequestMapping base = clazz.getAnnotation(RequestMapping.class); String[] baseUrl = {}; if (Objects.nonNull(base)) { baseUrl = base.value(); } Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(IgnoreAuth.class) && method.isAnnotationPresent(RequestMapping.class)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); String[] uri = requestMapping.value(); ignoreAuthUrls.addAll(rebuildUrl(baseUrl, uri)); } else if (method.isAnnotationPresent(IgnoreAuth.class) && method.isAnnotationPresent(GetMapping.class)) { GetMapping requestMapping = method.getAnnotation(GetMapping.class); String[] uri = requestMapping.value(); ignoreAuthUrls.addAll(rebuildUrl(baseUrl, uri)); } else if (method.isAnnotationPresent(IgnoreAuth.class) && method.isAnnotationPresent(PostMapping.class)) { PostMapping requestMapping = method.getAnnotation(PostMapping.class); String[] uri = requestMapping.value(); ignoreAuthUrls.addAll(rebuildUrl(baseUrl, uri)); } else if (method.isAnnotationPresent(IgnoreAuth.class) && method.isAnnotationPresent(PutMapping.class)) { PutMapping requestMapping = method.getAnnotation(PutMapping.class); String[] uri = requestMapping.value(); ignoreAuthUrls.addAll(rebuildUrl(baseUrl, uri)); } else if (method.isAnnotationPresent(IgnoreAuth.class) && method.isAnnotationPresent(DeleteMapping.class)) { DeleteMapping requestMapping = method.getAnnotation(DeleteMapping.class); String[] uri = requestMapping.value(); ignoreAuthUrls.addAll(rebuildUrl(baseUrl, uri)); } else if (method.isAnnotationPresent(IgnoreAuth.class) && method.isAnnotationPresent(PatchMapping.class)) { PatchMapping requestMapping = method.getAnnotation(PatchMapping.class); String[] uri = requestMapping.value(); ignoreAuthUrls.addAll(rebuildUrl(baseUrl, uri)); } } } return ignoreAuthUrls; } private List<String> rebuildUrl(String[] bases, String[] uris) { List<String> urls = new ArrayList<>(); for (String base : bases) { for (String uri : uris) { urls.add(prefix(base)+prefix(uri)); } } return urls; } private String prefix(String seg) { return seg.startsWith("/") ? seg : "/"+seg; } }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/config/shiro/ShiroConfig.java
321
package com.alibaba.otter.canal.client.pulsarmq; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.StringUtils; import org.apache.pulsar.client.api.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson2.JSON; import com.alibaba.otter.canal.client.CanalMQConnector; import com.alibaba.otter.canal.client.CanalMessageDeserializer; import com.alibaba.otter.canal.client.impl.SimpleCanalConnector; import com.alibaba.otter.canal.common.utils.MQUtil; import com.alibaba.otter.canal.protocol.FlatMessage; import com.alibaba.otter.canal.protocol.Message; import com.alibaba.otter.canal.protocol.exception.CanalClientException; import com.google.common.collect.Lists; /** * PulsarMQ的连接 * * <pre> * 注意点: * 1. 相比于canal {@linkplain SimpleCanalConnector}, 这里get和ack操作不能有并发, 必须是一个线程执行get后,内存里执行完毕ack后再取下一个get * </pre> * * todo 重复消费的概率相当高。一次批处理中,只要有一个消息处理失败,则该批次全部重试 * * @since 1.1.1 */ public class PulsarMQCanalConnector implements CanalMQConnector { private static final Logger logger = LoggerFactory .getLogger(PulsarMQCanalConnector.class); private volatile Messages<byte[]> lastGetBatchMessage; /** * 连接pulsar客户端 */ private PulsarClient pulsarClient; /** * 消费者 */ private Consumer<byte[]> consumer; /** * 是否扁平化Canal消息内容 */ private boolean isFlatMessage = false; /** * 主题名称 */ private String topic; /** * 环境连接URL */ private String serviceUrl; /** * 角色认证token */ private String roleToken; /** * listener name */ private String listenerName; /** * 订阅客户端名称 */ private String subscriptName; /** * 每次批量获取数据的最大条目数,默认30 */ private int batchSize = 30; /** * 与{@code batchSize}一起决定批量获取的数据大小 当: * <p> * 1. {@code batchSize} 条消息未消费时<br/> * 2. 距上一次批量消费时间达到{@code batchTimeoutSeconds}秒时 * </p> * 任一条件满足,即执行批量消费 */ private int getBatchTimeoutSeconds = 30; /** * 批量处理消息时,一次批量处理的超时时间秒数 * <p> * 该时间应该根据{@code batchSize}和{@code batchTimeoutSeconds}合理设置 * </p> */ private int batchProcessTimeoutSeconds = 60; /** * 消费失败后的重试秒数,默认60秒 */ private int redeliveryDelaySeconds = 60; /** * 当客户端接收到消息,30秒还没有返回ack给服务端时,ack超时,会重新消费该消息 */ private int ackTimeoutSeconds = 30; /** * 是否开启消息失败重试功能,默认开启 */ private boolean isRetry = true; /** * <p> * true重试(-RETRY)和死信队列(-DLQ)后缀为大写,有些地方创建的为小写,需确保正确 * </p> */ private boolean isRetryDLQUpperCase = false; /** * 最大重试次数 */ private int maxRedeliveryCount = 128; /** * 连接标识位,在连接或关闭连接后改变值 */ private boolean connected = false; /** * 除必要参数外,其他参数使用默认值 * <p> * 由于pulsar会根据subscriptName来区分消费实例,并且已经分配的指定实例的消息会固定到该实例的retry(重试)和dlq(死信)队列中, * 所以subscriptName必传,且必须跟之前的一致,否则会导致之前消费失败的消息不会重消费。 * </p> * * @param isFlatMessage true使用扁平消息 * @param serviceUrl pulsar服务连接地址,通常为:pulsar:host:ip或http://host:ip * @param roleToken 有对应topic的消费者权限的角色token * @param topic 订阅主题 * @param subscriptName 订阅和客户端名称,同一个订阅名视为同一个消费实例 * @date 2021/9/18 08:54 * @author chad * @since 1 by chad at 2021/9/18 完善 */ public PulsarMQCanalConnector(boolean isFlatMessage, String serviceUrl, String roleToken, String topic, String subscriptName){ this(isFlatMessage, serviceUrl, roleToken, topic, subscriptName, null); } public PulsarMQCanalConnector(boolean isFlatMessage, String serviceUrl, String roleToken, String topic, String subscriptName, String listenerName){ this.isFlatMessage = isFlatMessage; this.serviceUrl = serviceUrl; this.roleToken = roleToken; this.topic = topic; this.subscriptName = subscriptName; if (StringUtils.isEmpty(this.subscriptName)) { throw new RuntimeException("Pulsar Consumer subscriptName required"); } this.listenerName = listenerName; } /** * 完全自定义的消费实例参数 * * @date 2021/9/18 10:20 * @author chad * @since 1 by chad at 2021/9/18 完善 */ public PulsarMQCanalConnector(boolean isFlatMessage, String serviceUrl, String roleToken, String topic, String subscriptName, int batchSize, int getBatchTimeoutSeconds, int batchProcessTimeoutSeconds, int redeliveryDelaySeconds, int ackTimeoutSeconds, boolean isRetry, boolean isRetryDLQUpperCase, int maxRedeliveryCount){ this(isFlatMessage, serviceUrl, roleToken, topic, subscriptName, batchSize, getBatchTimeoutSeconds, batchProcessTimeoutSeconds, redeliveryDelaySeconds, ackTimeoutSeconds, isRetry, isRetryDLQUpperCase, maxRedeliveryCount, null); } public PulsarMQCanalConnector(boolean isFlatMessage, String serviceUrl, String roleToken, String topic, String subscriptName, int batchSize, int getBatchTimeoutSeconds, int batchProcessTimeoutSeconds, int redeliveryDelaySeconds, int ackTimeoutSeconds, boolean isRetry, boolean isRetryDLQUpperCase, int maxRedeliveryCount, String listenerName){ this.isFlatMessage = isFlatMessage; this.serviceUrl = serviceUrl; this.roleToken = roleToken; this.topic = topic; this.subscriptName = subscriptName; if (StringUtils.isEmpty(this.subscriptName)) { throw new RuntimeException("Pulsar Consumer subscriptName required"); } this.batchSize = batchSize; this.getBatchTimeoutSeconds = getBatchTimeoutSeconds; this.batchProcessTimeoutSeconds = batchProcessTimeoutSeconds; this.redeliveryDelaySeconds = redeliveryDelaySeconds; this.ackTimeoutSeconds = ackTimeoutSeconds; this.isRetry = isRetry; this.isRetryDLQUpperCase = isRetryDLQUpperCase; this.maxRedeliveryCount = maxRedeliveryCount; this.listenerName = listenerName; } @Override public void connect() throws CanalClientException { // 连接创建客户端 try { ClientBuilder builder = PulsarClient.builder() .serviceUrl(serviceUrl) .authentication(AuthenticationFactory.token(roleToken)); if (StringUtils.isNotEmpty(listenerName)) { builder.listenerName(listenerName); } pulsarClient = builder.build(); } catch (PulsarClientException e) { throw new RuntimeException(e); } } @Override public void disconnect() throws CanalClientException { try { if (null != this.consumer && this.consumer.isConnected()) { this.consumer.close(); } } catch (PulsarClientException e) { logger.error("close pulsar consumer error", e); } try { if (null != this.pulsarClient) { this.pulsarClient.close(); } } catch (PulsarClientException e) { logger.error("close pulsar client error", e); } this.connected = false; } @Override public boolean checkValid() throws CanalClientException { return connected; } @Override public synchronized void subscribe(String filter) throws CanalClientException { if (connected) { return; } ConsumerBuilder<byte[]> builder = pulsarClient.newConsumer(); if (MQUtil.isPatternTopic(this.topic)) { // 正则 builder.topicsPattern(this.topic); } else {// 多个topic builder.topic(this.topic); } // 为保证消息的有序性,仅支持单消费实例模式 // 灾备模式,一个分区只能有一个消费者,如果当前消费者不可用,自动切换到其他消费者 builder.subscriptionType(SubscriptionType.Failover); builder // 调用consumer.negativeAcknowledge(message) (即nack)来表示消费失败的消息 // 在指定的时间进行重新消费,默认是1分钟。 .negativeAckRedeliveryDelay(this.redeliveryDelaySeconds, TimeUnit.SECONDS) .subscriptionName(this.subscriptName); if (this.isRetry) { DeadLetterPolicy.DeadLetterPolicyBuilder dlqBuilder = DeadLetterPolicy.builder() // 最大重试次数 .maxRedeliverCount(this.maxRedeliveryCount); // 指定重试队列,不是多个或通配符topic才能判断重试队列 if (!MQUtil.isPatternTag(this.topic)) { String retryTopic = this.topic + (this.isRetryDLQUpperCase ? "-RETRY" : "-retry"); dlqBuilder.retryLetterTopic(retryTopic); String dlqTopic = this.topic + (this.isRetryDLQUpperCase ? "-DLQ" : "-dlq"); dlqBuilder.deadLetterTopic(dlqTopic); } // 默认关闭,如果需要重试则开启 builder.enableRetry(true).deadLetterPolicy(dlqBuilder.build()); } // ack超时 builder.ackTimeout(this.ackTimeoutSeconds, TimeUnit.SECONDS); // pulsar批量获取消息设置 builder.batchReceivePolicy(new BatchReceivePolicy.Builder().maxNumMessages(this.batchSize) .timeout(this.getBatchTimeoutSeconds, TimeUnit.SECONDS) .build()); try { this.consumer = builder.subscribe(); connected = true; } catch (PulsarClientException e) { throw new RuntimeException(e); } } @Override public void subscribe() throws CanalClientException { this.subscribe(null); } @Override public void unsubscribe() throws CanalClientException { try { if (null != this.consumer) { this.consumer.unsubscribe(); } } catch (PulsarClientException e) { throw new CanalClientException(e.getMessage(), e); } } /** * 不关注业务执行结果,只要收到消息即认识消费成功,自动ack * * @param timeout 阻塞获取消息的超时时间 * @param unit 时间单位 * @return java.util.List<com.alibaba.otter.canal.protocol.Message> * @date 2021/9/13 22:24 * @author chad * @since 1 by chad at 2021/9/13 添加注释 */ @Override public List<Message> getList(Long timeout, TimeUnit unit) throws CanalClientException { List<Message> messages = getListWithoutAck(timeout, unit); if (messages != null && !messages.isEmpty()) { ack(); } return messages; } /** * 关心业务执行结果,业务侧根据执行结果调用 * {@link PulsarMQCanalConnector#ack()}或{@link PulsarMQCanalConnector#rollback()} * <p> * 本方法示支持多线程,在MQ保障顺序的前提下,也无法提供单Topic多线程 * </p> * * @param timeout 阻塞获取消息的超时时间 * @param unit 时间单位 * @return java.util.List<com.alibaba.otter.canal.protocol.Message> * @date 2021/9/13 22:26 * @author chad * @since 1 by chad at 2021/9/13 添加注释 */ @Override public List<Message> getListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException { return getListWithoutAck(); } @Override public List<FlatMessage> getFlatList(Long timeout, TimeUnit unit) throws CanalClientException { List<FlatMessage> messages = getFlatListWithoutAck(timeout, unit); if (messages != null && !messages.isEmpty()) { ack(); } return messages; } @Override public List<FlatMessage> getFlatListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException { return getListWithoutAck(); } /** * 获取泛型数据,供其他方法调用 * <p> * 不支持多线程调用 * </p> * * @return java.util.List<T> * @date 2021/9/14 15:20 * @author chad * @since 1 by chad at 2021/9/14 * 供{@link PulsarMQCanalConnector#getListWithoutAck(Long, TimeUnit)} * 和{@link PulsarMQCanalConnector#getFlatListWithoutAck(Long, TimeUnit)}调用 */ private <T> List<T> getListWithoutAck() { if (null != this.lastGetBatchMessage) { throw new CanalClientException("mq get/ack not support concurrent & async ack"); } List messageList = Lists.newArrayList(); try { this.lastGetBatchMessage = consumer.batchReceive(); if (null == this.lastGetBatchMessage || this.lastGetBatchMessage.size() < 1) { this.lastGetBatchMessage = null; return messageList; } } catch (PulsarClientException e) { logger.error("Receiver Pulsar MQ message error", e); throw new CanalClientException(e); } for (org.apache.pulsar.client.api.Message<byte[]> msgExt : this.lastGetBatchMessage) { byte[] data = msgExt.getData(); if (data == null) { logger.warn("Received message data is null"); continue; } try { if (isFlatMessage) { FlatMessage flatMessage = JSON.parseObject(data, FlatMessage.class); messageList.add(flatMessage); } else { Message message = CanalMessageDeserializer.deserializer(data); messageList.add(message); } } catch (Exception ex) { logger.error("Add message error", ex); throw new CanalClientException(ex); } } return messageList; } /** * 当业务侧执行成功时,需要手动执行消息的ack操作 * * @return void * @date 2021/9/13 22:27 * @author chad * @since 1 by chad at 2021/9/13 添加注释 */ @Override public void ack() throws CanalClientException { // 为什么要一个批次要么全部成功要么全部失败 try { if (this.lastGetBatchMessage != null) { this.consumer.acknowledge(this.lastGetBatchMessage); } } catch (Throwable e) { if (this.lastGetBatchMessage != null) { this.consumer.negativeAcknowledge(this.lastGetBatchMessage); } } finally { this.lastGetBatchMessage = null; } } /** * 当业务侧执行失败时,需要手动执行消息的rollback操作,从而让消息重新消费 * * @return void * @date 2021/9/13 22:28 * @author chad * @since 1 by chad at 2021/9/13 添加注释 */ @Override public void rollback() throws CanalClientException { try { if (this.lastGetBatchMessage != null) { this.consumer.negativeAcknowledge(this.lastGetBatchMessage); } } finally { this.lastGetBatchMessage = null; } } @Override public Message get(int batchSize) throws CanalClientException { throw new CanalClientException("mq not support this method"); } @Override public Message get(int batchSize, Long timeout, TimeUnit unit) throws CanalClientException { throw new CanalClientException("mq not support this method"); } @Override public Message getWithoutAck(int batchSize) throws CanalClientException { throw new CanalClientException("mq not support this method"); } @Override public Message getWithoutAck(int batchSize, Long timeout, TimeUnit unit) throws CanalClientException { throw new CanalClientException("mq not support this method"); } @Override public void ack(long batchId) throws CanalClientException { throw new CanalClientException("mq not support this method"); } @Override public void rollback(long batchId) throws CanalClientException { throw new CanalClientException("mq not support this method"); } }
alibaba/canal
client/src/main/java/com/alibaba/otter/canal/client/pulsarmq/PulsarMQCanalConnector.java
322
/* * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.fastjson.parser; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.util.ASMUtils; import com.alibaba.fastjson.util.IOUtils; import java.math.BigDecimal; import java.math.MathContext; import java.util.*; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_hashcode; import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_prime; //这个类,为了性能优化做了很多特别处理,一切都是为了性能!!! /** * @author wenshao[[email protected]] */ public final class JSONScanner extends JSONLexerBase { private final String text; private final int len; public JSONScanner(String input){ this(input, JSON.DEFAULT_PARSER_FEATURE); } public JSONScanner(String input, int features){ super(features); text = input; len = text.length(); bp = -1; next(); if (ch == 65279) { // utf-8 bom next(); } } public final char charAt(int index) { if (index >= len) { return EOI; } return text.charAt(index); } public final char next() { int index = ++bp; return ch = (index >= this.len ? // EOI // : text.charAt(index)); } public JSONScanner(char[] input, int inputLength){ this(input, inputLength, JSON.DEFAULT_PARSER_FEATURE); } public JSONScanner(char[] input, int inputLength, int features){ this(new String(input, 0, inputLength), features); } protected final void copyTo(int offset, int count, char[] dest) { text.getChars(offset, offset + count, dest, 0); } static boolean charArrayCompare(String src, int offset, char[] dest) { final int destLen = dest.length; if (destLen + offset > src.length()) { return false; } for (int i = 0; i < destLen; ++i) { if (dest[i] != src.charAt(offset + i)) { return false; } } return true; } public final boolean charArrayCompare(char[] chars) { return charArrayCompare(text, bp, chars); } public final int indexOf(char ch, int startIndex) { return text.indexOf(ch, startIndex); } public final String addSymbol(int offset, int len, int hash, final SymbolTable symbolTable) { return symbolTable.addSymbol(text, offset, len, hash); } public byte[] bytesValue() { if (token == JSONToken.HEX) { int start = np + 1, len = sp; if (len % 2 != 0) { throw new JSONException("illegal state. " + len); } byte[] bytes = new byte[len / 2]; for (int i = 0; i < bytes.length; ++i) { char c0 = text.charAt(start + i * 2); char c1 = text.charAt(start + i * 2 + 1); int b0 = c0 - (c0 <= 57 ? 48 : 55); int b1 = c1 - (c1 <= 57 ? 48 : 55); bytes[i] = (byte) ((b0 << 4) | b1); } return bytes; } if (!hasSpecial) { return IOUtils.decodeBase64(text, np + 1, sp); } else { String escapedText = new String(sbuf, 0, sp); return IOUtils.decodeBase64(escapedText); } } /** * The value of a literal token, recorded as a string. For integers, leading 0x and 'l' suffixes are suppressed. */ public final String stringVal() { if (!hasSpecial) { return this.subString(np + 1, sp); } else { return new String(sbuf, 0, sp); } } public final String subString(int offset, int count) { if (ASMUtils.IS_ANDROID) { if (count < sbuf.length) { text.getChars(offset, offset + count, sbuf, 0); return new String(sbuf, 0, count); } else { char[] chars = new char[count]; text.getChars(offset, offset + count, chars, 0); return new String(chars); } } else { return text.substring(offset, offset + count); } } public final char[] sub_chars(int offset, int count) { if (ASMUtils.IS_ANDROID && count < sbuf.length) { text.getChars(offset, offset + count, sbuf, 0); return sbuf; } else { char[] chars = new char[count]; text.getChars(offset, offset + count, chars, 0); return chars; } } public final String numberString() { char chLocal = charAt(np + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } return this.subString(np, sp); } public final BigDecimal decimalValue() { char chLocal = charAt(np + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } if (sp > 65535) { throw new JSONException("decimal overflow"); } int offset = np, count = sp; if (count < sbuf.length) { text.getChars(offset, offset + count, sbuf, 0); return new BigDecimal(sbuf, 0, count, MathContext.UNLIMITED); } else { char[] chars = new char[count]; text.getChars(offset, offset + count, chars, 0); return new BigDecimal(chars, 0, chars.length, MathContext.UNLIMITED); } } public boolean scanISO8601DateIfMatch() { return scanISO8601DateIfMatch(true); } public boolean scanISO8601DateIfMatch(boolean strict) { int rest = len - bp; return scanISO8601DateIfMatch(strict, rest); } private boolean scanISO8601DateIfMatch(boolean strict, int rest) { if (rest < 8) { return false; } char c0 = charAt(bp); char c1 = charAt(bp + 1); char c2 = charAt(bp + 2); char c3 = charAt(bp + 3); char c4 = charAt(bp + 4); char c5 = charAt(bp + 5); char c6 = charAt(bp + 6); char c7 = charAt(bp + 7); if ((!strict) && rest > 13) { char c_r0 = charAt(bp + rest - 1); char c_r1 = charAt(bp + rest - 2); if (c0 == '/' && c1 == 'D' && c2 == 'a' && c3 == 't' && c4 == 'e' && c5 == '(' && c_r0 == '/' && c_r1 == ')') { int plusIndex = -1; for (int i = 6; i < rest; ++i) { char c = charAt(bp + i); if (c == '+') { plusIndex = i; } else if (c < '0' || c > '9') { break; } } if (plusIndex == -1) { return false; } int offset = bp + 6; String numberText = this.subString(offset, bp + plusIndex - offset); long millis = Long.parseLong(numberText); calendar = Calendar.getInstance(timeZone, locale); calendar.setTimeInMillis(millis); token = JSONToken.LITERAL_ISO8601_DATE; return true; } } char c10; if (rest == 8 || rest == 14 || (rest == 16 && ((c10 = charAt(bp + 10)) == 'T' || c10 == ' ')) || (rest == 17 && charAt(bp + 6) != '-')) { if (strict) { return false; } char y0, y1, y2, y3, M0, M1, d0, d1; char c8 = charAt(bp + 8); final boolean c_47 = c4 == '-' && c7 == '-'; final boolean sperate16 = c_47 && rest == 16; final boolean sperate17 = c_47 && rest == 17; if (sperate17 || sperate16) { y0 = c0; y1 = c1; y2 = c2; y3 = c3; M0 = c5; M1 = c6; d0 = c8; d1 = charAt(bp + 9); } else if (c4 == '-' && c6 == '-') { y0 = c0; y1 = c1; y2 = c2; y3 = c3; M0 = '0'; M1 = c5; d0 = '0'; d1 = c7; } else { y0 = c0; y1 = c1; y2 = c2; y3 = c3; M0 = c4; M1 = c5; d0 = c6; d1 = c7; } if (!checkDate(y0, y1, y2, y3, M0, M1, d0, d1)) { return false; } setCalendar(y0, y1, y2, y3, M0, M1, d0, d1); int hour, minute, seconds, millis; if (rest != 8) { char c9 = charAt(bp + 9); c10 = charAt(bp + 10); char c11 = charAt(bp + 11); char c12 = charAt(bp + 12); char c13 = charAt(bp + 13); char h0, h1, m0, m1, s0, s1; if ((sperate17 && c10 == 'T' && c13 == ':' && charAt(bp + 16) == 'Z') || (sperate16 && (c10 == ' ' || c10 == 'T') && c13 == ':')) { h0 = c11; h1 = c12; m0 = charAt(bp + 14); m1 = charAt(bp + 15); s0 = '0'; s1 = '0'; } else { h0 = c8; h1 = c9; m0 = c10; m1 = c11; s0 = c12; s1 = c13; } if (!checkTime(h0, h1, m0, m1, s0, s1)) { return false; } if (rest == 17 && !sperate17) { char S0 = charAt(bp + 14); char S1 = charAt(bp + 15); char S2 = charAt(bp + 16); if (S0 < '0' || S0 > '9') { return false; } if (S1 < '0' || S1 > '9') { return false; } if (S2 < '0' || S2 > '9') { return false; } millis = (S0 - '0') * 100 + (S1 - '0') * 10 + (S2 - '0'); } else { millis = 0; } hour = (h0 - '0') * 10 + (h1 - '0'); minute = (m0 - '0') * 10 + (m1 - '0'); seconds = (s0 - '0') * 10 + (s1 - '0'); } else { hour = 0; minute = 0; seconds = 0; millis = 0; } calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, seconds); calendar.set(Calendar.MILLISECOND, millis); token = JSONToken.LITERAL_ISO8601_DATE; return true; } if (rest < 9) { return false; } char c8 = charAt(bp + 8); char c9 = charAt(bp + 9); int date_len = 10; char y0, y1, y2, y3, M0, M1, d0, d1; if ((c4 == '-' && c7 == '-') // cn || (c4 == '/' && c7 == '/') // tw yyyy/mm/dd ) { y0 = c0; y1 = c1; y2 = c2; y3 = c3; M0 = c5; M1 = c6; if (c9 == ' ') { d0 = '0'; d1 = c8; date_len = 9; } else { d0 = c8; d1 = c9; } } else if ((c4 == '-' && c6 == '-') // cn yyyy-m-dd ) { y0 = c0; y1 = c1; y2 = c2; y3 = c3; M0 = '0'; M1 = c5; if (c8 == ' ') { d0 = '0'; d1 = c7; date_len = 8; } else { d0 = c7; d1 = c8; date_len = 9; } } else if ((c2 == '.' && c5 == '.') // de dd.mm.yyyy || (c2 == '-' && c5 == '-') // in dd-mm-yyyy ) { d0 = c0; d1 = c1; M0 = c3; M1 = c4; y0 = c6; y1 = c7; y2 = c8; y3 = c9; } else if (c8 == 'T') { y0 = c0; y1 = c1; y2 = c2; y3 = c3; M0 = c4; M1 = c5; d0 = c6; d1 = c7; date_len = 8; } else { if (c4 == '年' || c4 == '년') { y0 = c0; y1 = c1; y2 = c2; y3 = c3; if (c7 == '月' || c7 == '월') { M0 = c5; M1 = c6; if (c9 == '日' || c9 == '일') { d0 = '0'; d1 = c8; } else if (charAt(bp + 10) == '日' || charAt(bp + 10) == '일'){ d0 = c8; d1 = c9; date_len = 11; } else { return false; } } else if (c6 == '月' || c6 == '월') { M0 = '0'; M1 = c5; if (c8 == '日' || c8 == '일') { d0 = '0'; d1 = c7; } else if (c9 == '日' || c9 == '일'){ d0 = c7; d1 = c8; } else { return false; } } else { return false; } } else { return false; } } if (!checkDate(y0, y1, y2, y3, M0, M1, d0, d1)) { return false; } setCalendar(y0, y1, y2, y3, M0, M1, d0, d1); char t = charAt(bp + date_len); if (t == 'T' && rest == 16 && date_len == 8 && charAt(bp + 15) == 'Z') { char h0 = charAt(bp + date_len + 1); char h1 = charAt(bp + date_len + 2); char m0 = charAt(bp + date_len + 3); char m1 = charAt(bp + date_len + 4); char s0 = charAt(bp + date_len + 5); char s1 = charAt(bp + date_len + 6); if (!checkTime(h0, h1, m0, m1, s0, s1)) { return false; } setTime(h0, h1, m0, m1, s0, s1); calendar.set(Calendar.MILLISECOND, 0); if (calendar.getTimeZone().getRawOffset() != 0) { String[] timeZoneIDs = TimeZone.getAvailableIDs(0); if (timeZoneIDs.length > 0) { TimeZone timeZone = TimeZone.getTimeZone(timeZoneIDs[0]); calendar.setTimeZone(timeZone); } } token = JSONToken.LITERAL_ISO8601_DATE; return true; } else if (t == 'T' || (t == ' ' && !strict)) { if (rest < date_len + 9) { // "0000-00-00T00:00:00".length() return false; } } else if (t == '"' || t == EOI || t == '日' || t == '일') { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); ch = charAt(bp += date_len); token = JSONToken.LITERAL_ISO8601_DATE; return true; } else if (t == '+' || t == '-') { if (len == date_len + 6) { if (charAt(bp + date_len + 3) != ':' // || charAt(bp + date_len + 4) != '0' // || charAt(bp + date_len + 5) != '0') { return false; } setTime('0', '0', '0', '0', '0', '0'); calendar.set(Calendar.MILLISECOND, 0); setTimeZone(t, charAt(bp + date_len + 1), charAt(bp + date_len + 2)); return true; } return false; } else { return false; } if (charAt(bp + date_len + 3) != ':') { return false; } if (charAt(bp + date_len + 6) != ':') { return false; } char h0 = charAt(bp + date_len + 1); char h1 = charAt(bp + date_len + 2); char m0 = charAt(bp + date_len + 4); char m1 = charAt(bp + date_len + 5); char s0 = charAt(bp + date_len + 7); char s1 = charAt(bp + date_len + 8); if (!checkTime(h0, h1, m0, m1, s0, s1)) { return false; } setTime(h0, h1, m0, m1, s0, s1); char dot = charAt(bp + date_len + 9); int millisLen = -1; // 有可能没有毫秒区域,没有毫秒区域的时候下一个字符位置有可能是'Z'、'+'、'-' int millis = 0; if (dot == '.') { // 0000-00-00T00:00:00.000 if (rest < date_len + 11) { return false; } char S0 = charAt(bp + date_len + 10); if (S0 < '0' || S0 > '9') { return false; } millis = S0 - '0'; millisLen = 1; if (rest > date_len + 11) { char S1 = charAt(bp + date_len + 11); if (S1 >= '0' && S1 <= '9') { millis = millis * 10 + (S1 - '0'); millisLen = 2; } } if (millisLen == 2) { char S2 = charAt(bp + date_len + 12); if (S2 >= '0' && S2 <= '9') { millis = millis * 10 + (S2 - '0'); millisLen = 3; } } } calendar.set(Calendar.MILLISECOND, millis); int timzeZoneLength = 0; char timeZoneFlag = charAt(bp + date_len + 10 + millisLen); if (timeZoneFlag == ' ') { millisLen++; timeZoneFlag = charAt(bp + date_len + 10 + millisLen); } if (timeZoneFlag == '+' || timeZoneFlag == '-') { char t0 = charAt(bp + date_len + 10 + millisLen + 1); if (t0 < '0' || t0 > '1') { return false; } char t1 = charAt(bp + date_len + 10 + millisLen + 2); if (t1 < '0' || t1 > '9') { return false; } char t2 = charAt(bp + date_len + 10 + millisLen + 3); char t3 = '0', t4 = '0'; if (t2 == ':') { // ThreeLetterISO8601TimeZone t3 = charAt(bp + date_len + 10 + millisLen + 4); t4 = charAt(bp + date_len + 10 + millisLen + 5); if(t3 == '4' && t4 == '5') { // handle some special timezones like xx:45 if (t0 == '1' && (t1 == '2' || t1 == '3')) { // NZ-CHAT => +12:45 // Pacific/Chatham => +12:45 // NZ-CHAT => +13:45 (DST) // Pacific/Chatham => +13:45 (DST) } else if (t0 == '0' && (t1 == '5' || t1 == '8')) { // Asia/Kathmandu => +05:45 // Asia/Katmandu => +05:45 // Australia/Eucla => +08:45 } else { return false; } } else { //handle normal timezone like xx:00 and xx:30 if (t3 != '0' && t3 != '3') { return false; } if (t4 != '0') { return false; } } timzeZoneLength = 6; } else if (t2 == '0') { // TwoLetterISO8601TimeZone t3 = charAt(bp + date_len + 10 + millisLen + 4); if (t3 != '0' && t3 != '3') { return false; } timzeZoneLength = 5; } else if (t2 == '3' && charAt(bp + date_len + 10 + millisLen + 4) == '0') { t3 = '3'; t4 = '0'; timzeZoneLength = 5; } else if (t2 == '4' && charAt(bp + date_len + 10 + millisLen + 4) == '5') { t3 = '4'; t4 = '5'; timzeZoneLength = 5; } else { timzeZoneLength = 3; } setTimeZone(timeZoneFlag, t0, t1, t3, t4); } else if (timeZoneFlag == 'Z') {// UTC timzeZoneLength = 1; if (calendar.getTimeZone().getRawOffset() != 0) { String[] timeZoneIDs = TimeZone.getAvailableIDs(0); if (timeZoneIDs.length > 0) { TimeZone timeZone = TimeZone.getTimeZone(timeZoneIDs[0]); calendar.setTimeZone(timeZone); } } } char end = charAt(bp + (date_len + 10 + millisLen + timzeZoneLength)); if (end != EOI && end != '"') { return false; } ch = charAt(bp += (date_len + 10 + millisLen + timzeZoneLength)); token = JSONToken.LITERAL_ISO8601_DATE; return true; } protected void setTime(char h0, char h1, char m0, char m1, char s0, char s1) { int hour = (h0 - '0') * 10 + (h1 - '0'); int minute = (m0 - '0') * 10 + (m1 - '0'); int seconds = (s0 - '0') * 10 + (s1 - '0'); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, seconds); } protected void setTimeZone(char timeZoneFlag, char t0, char t1) { setTimeZone(timeZoneFlag, t0, t1, '0', '0'); } protected void setTimeZone(char timeZoneFlag, char t0, char t1, char t3, char t4) { int timeZoneOffset = ((t0 - '0') * 10 + (t1 - '0')) * 3600 * 1000; timeZoneOffset += ((t3 - '0') * 10 + (t4 - '0')) * 60 * 1000; if (timeZoneFlag == '-') { timeZoneOffset = -timeZoneOffset; } if (calendar.getTimeZone().getRawOffset() != timeZoneOffset) { calendar.setTimeZone(new SimpleTimeZone(timeZoneOffset, Integer.toString(timeZoneOffset))); } } private boolean checkTime(char h0, char h1, char m0, char m1, char s0, char s1) { if (h0 == '0') { if (h1 < '0' || h1 > '9') { return false; } } else if (h0 == '1') { if (h1 < '0' || h1 > '9') { return false; } } else if (h0 == '2') { if (h1 < '0' || h1 > '4') { return false; } } else { return false; } if (m0 >= '0' && m0 <= '5') { if (m1 < '0' || m1 > '9') { return false; } } else if (m0 == '6') { if (m1 != '0') { return false; } } else { return false; } if (s0 >= '0' && s0 <= '5') { if (s1 < '0' || s1 > '9') { return false; } } else if (s0 == '6') { if (s1 != '0') { return false; } } else { return false; } return true; } private void setCalendar(char y0, char y1, char y2, char y3, char M0, char M1, char d0, char d1) { calendar = Calendar.getInstance(timeZone, locale); int year = (y0 - '0') * 1000 + (y1 - '0') * 100 + (y2 - '0') * 10 + (y3 - '0'); int month = (M0 - '0') * 10 + (M1 - '0') - 1; int day = (d0 - '0') * 10 + (d1 - '0'); // calendar.set(year, month, day); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); } static boolean checkDate(char y0, char y1, char y2, char y3, char M0, char M1, int d0, int d1) { if (y0 < '0' || y0 > '9') { return false; } if (y1 < '0' || y1 > '9') { return false; } if (y2 < '0' || y2 > '9') { return false; } if (y3 < '0' || y3 > '9') { return false; } if (M0 == '0') { if (M1 < '1' || M1 > '9') { return false; } } else if (M0 == '1') { if (M1 != '0' && M1 != '1' && M1 != '2') { return false; } } else { return false; } if (d0 == '0') { if (d1 < '1' || d1 > '9') { return false; } } else if (d0 == '1' || d0 == '2') { if (d1 < '0' || d1 > '9') { return false; } } else if (d0 == '3') { if (d1 != '0' && d1 != '1') { return false; } } else { return false; } return true; } @Override public boolean isEOF() { return bp == len || (ch == EOI && bp + 1 >= len); } public int scanFieldInt(char[] fieldName) { matchStat = UNKNOWN; int startPos = this.bp; char startChar = this.ch; if (!charArrayCompare(text, bp, fieldName)) { matchStat = NOT_MATCH_NAME; return 0; } int index = bp + fieldName.length; char ch = charAt(index++); final boolean quote = ch == '"'; if (quote) { ch = charAt(index++); } final boolean negative = ch == '-'; if (negative) { ch = charAt(index++); } int value; if (ch >= '0' && ch <= '9') { value = ch - '0'; for (;;) { ch = charAt(index++); if (ch >= '0' && ch <= '9') { int value_10 = value * 10; if (value_10 < value) { matchStat = NOT_MATCH; return 0; } value = value_10 + (ch - '0'); } else if (ch == '.') { matchStat = NOT_MATCH; return 0; } else { break; } } if (value < 0) { matchStat = NOT_MATCH; return 0; } if (quote) { if (ch != '"') { matchStat = NOT_MATCH; return 0; } else { ch = charAt(index++); } } for (;;) { if (ch == ',' || ch == '}') { bp = index - 1; break; } else if(isWhitespace(ch)) { ch = charAt(index++); continue; } else { matchStat = NOT_MATCH; return 0; } } } else { matchStat = NOT_MATCH; return 0; } if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; token = JSONToken.COMMA; return negative ? -value : value; } if (ch == '}') { bp = index - 1; ch = charAt(++bp); for (; ; ) { if (ch == ',') { token = JSONToken.COMMA; this.ch = charAt(++bp); break; } else if (ch == ']') { token = JSONToken.RBRACKET; this.ch = charAt(++bp); break; } else if (ch == '}') { token = JSONToken.RBRACE; this.ch = charAt(++bp); break; } else if (ch == EOI) { token = JSONToken.EOF; break; } else if (isWhitespace(ch)) { ch = charAt(++bp); continue; } else { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return 0; } } matchStat = END; } return negative ? -value : value; } public String scanFieldString(char[] fieldName) { matchStat = UNKNOWN; int startPos = this.bp; char startChar = this.ch; for (;;) { if (!charArrayCompare(text, bp, fieldName)) { if (isWhitespace(ch)) { next(); while (isWhitespace(ch)) { next(); } continue; } matchStat = NOT_MATCH_NAME; return stringDefaultValue(); } else { break; } } int index = bp + fieldName.length; int spaceCount = 0; char ch = charAt(index++); if (ch != '"') { while (isWhitespace(ch)) { spaceCount++; ch = charAt(index++); } if (ch != '"') { matchStat = NOT_MATCH; return stringDefaultValue(); } } final String strVal; { int startIndex = index; int endIndex = indexOf('"', startIndex); if (endIndex == -1) { throw new JSONException("unclosed str"); } String stringVal = subString(startIndex, endIndex - startIndex); if (stringVal.indexOf('\\') != -1) { for (;;) { int slashCount = 0; for (int i = endIndex - 1; i >= 0; --i) { if (charAt(i) == '\\') { slashCount++; } else { break; } } if (slashCount % 2 == 0) { break; } endIndex = indexOf('"', endIndex + 1); } int chars_len = endIndex - (bp + fieldName.length + 1 + spaceCount); char[] chars = sub_chars(bp + fieldName.length + 1 + spaceCount, chars_len); stringVal = readString(chars, chars_len); } if ((this.features & Feature.TrimStringFieldValue.mask) != 0) { stringVal = stringVal.trim(); } ch = charAt(endIndex + 1); for (;;) { if (ch == ',' || ch == '}') { bp = endIndex + 1; this.ch = ch; strVal = stringVal; break; } else if (isWhitespace(ch)) { endIndex++; ch = charAt(endIndex + 1); } else { matchStat = NOT_MATCH; return stringDefaultValue(); } } } if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; return strVal; } else { //condition ch == '}' is always 'true' ch = charAt(++bp); if (ch == ',') { token = JSONToken.COMMA; this.ch = charAt(++bp); } else if (ch == ']') { token = JSONToken.RBRACKET; this.ch = charAt(++bp); } else if (ch == '}') { token = JSONToken.RBRACE; this.ch = charAt(++bp); } else if (ch == EOI) { token = JSONToken.EOF; } else { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return stringDefaultValue(); } matchStat = END; } return strVal; } public java.util.Date scanFieldDate(char[] fieldName) { matchStat = UNKNOWN; int startPos = this.bp; char startChar = this.ch; if (!charArrayCompare(text, bp, fieldName)) { matchStat = NOT_MATCH_NAME; return null; } int index = bp + fieldName.length; char ch = charAt(index++); final java.util.Date dateVal; if (ch == '"') { int startIndex = index; int endIndex = indexOf('"', startIndex); if (endIndex == -1) { throw new JSONException("unclosed str"); } int rest = endIndex - startIndex; bp = index; if (scanISO8601DateIfMatch(false, rest)) { dateVal = calendar.getTime(); } else { bp = startPos; matchStat = NOT_MATCH; return null; } ch = charAt(endIndex + 1); bp = startPos; for (; ; ) { if (ch == ',' || ch == '}') { bp = endIndex + 1; this.ch = ch; break; } else if (isWhitespace(ch)) { endIndex++; ch = charAt(endIndex + 1); } else { matchStat = NOT_MATCH; return null; } } } else if (ch == '-' || (ch >= '0' && ch <= '9')) { long millis = 0; boolean negative = false; if (ch == '-') { ch = charAt(index++); negative = true; } if (ch >= '0' && ch <= '9') { millis = ch - '0'; for (; ; ) { ch = charAt(index++); if (ch >= '0' && ch <= '9') { millis = millis * 10 + (ch - '0'); } else { if (ch == ',' || ch == '}') { bp = index - 1; } break; } } } if (millis < 0) { matchStat = NOT_MATCH; return null; } if (negative) { millis = -millis; } dateVal = new java.util.Date(millis); } else { matchStat = NOT_MATCH; return null; } if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; token = JSONToken.COMMA; return dateVal; } else { //condition ch == '}' is always 'true' ch = charAt(++bp); if (ch == ',') { token = JSONToken.COMMA; this.ch = charAt(++bp); } else if (ch == ']') { token = JSONToken.RBRACKET; this.ch = charAt(++bp); } else if (ch == '}') { token = JSONToken.RBRACE; this.ch = charAt(++bp); } else if (ch == EOI) { token = JSONToken.EOF; } else { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return null; } matchStat = END; } return dateVal; } public long scanFieldSymbol(char[] fieldName) { matchStat = UNKNOWN; for (;;) { if (!charArrayCompare(text, bp, fieldName)) { if (isWhitespace(ch)) { next(); while (isWhitespace(ch)) { next(); } continue; } matchStat = NOT_MATCH_NAME; return 0; } else { break; } } int index = bp + fieldName.length; int spaceCount = 0; char ch = charAt(index++); if (ch != '"') { while (isWhitespace(ch)) { ch = charAt(index++); spaceCount++; } if (ch != '"') { matchStat = NOT_MATCH; return 0; } } long hash = fnv1a_64_magic_hashcode; for (;;) { ch = charAt(index++); if (ch == '\"') { bp = index; this.ch = ch = charAt(bp); break; } else if (index > len) { matchStat = NOT_MATCH; return 0; } hash ^= ch; hash *= fnv1a_64_magic_prime; } for (;;) { if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; return hash; } else if (ch == '}') { next(); skipWhitespace(); ch = getCurrent(); if (ch == ',') { token = JSONToken.COMMA; this.ch = charAt(++bp); } else if (ch == ']') { token = JSONToken.RBRACKET; this.ch = charAt(++bp); } else if (ch == '}') { token = JSONToken.RBRACE; this.ch = charAt(++bp); } else if (ch == EOI) { token = JSONToken.EOF; } else { matchStat = NOT_MATCH; return 0; } matchStat = END; break; } else if (isWhitespace(ch)) { ch = charAt(++bp); continue; } else { matchStat = NOT_MATCH; return 0; } } return hash; } @SuppressWarnings("unchecked") public Collection<String> scanFieldStringArray(char[] fieldName, Class<?> type) { matchStat = UNKNOWN; while (ch == '\n' || ch == ' ') { int index = ++bp; ch = (index >= this.len ? // EOI // : text.charAt(index)); } if (!charArrayCompare(text, bp, fieldName)) { matchStat = NOT_MATCH_NAME; return null; } Collection<String> list = newCollectionByType(type); // if (type.isAssignableFrom(HashSet.class)) { // list = new HashSet<String>(); // } else if (type.isAssignableFrom(ArrayList.class)) { // list = new ArrayList<String>(); // } else { // try { // list = (Collection<String>) type.newInstance(); // } catch (Exception e) { // throw new JSONException(e.getMessage(), e); // } // } int startPos = this.bp; char startChar = this.ch; int index = bp + fieldName.length; char ch = charAt(index++); if (ch == '[') { ch = charAt(index++); for (;;) { if (ch == '"') { int startIndex = index; int endIndex = indexOf('"', startIndex); if (endIndex == -1) { throw new JSONException("unclosed str"); } String stringVal = subString(startIndex, endIndex - startIndex); if (stringVal.indexOf('\\') != -1) { for (;;) { int slashCount = 0; for (int i = endIndex - 1; i >= 0; --i) { if (charAt(i) == '\\') { slashCount++; } else { break; } } if (slashCount % 2 == 0) { break; } endIndex = indexOf('"', endIndex + 1); } int chars_len = endIndex - startIndex; char[] chars = sub_chars(startIndex, chars_len); stringVal = readString(chars, chars_len); } index = endIndex + 1; ch = charAt(index++); list.add(stringVal); } else if (ch == 'n' && text.startsWith("ull", index)) { index += 3; ch = charAt(index++); list.add(null); } else if (ch == ']' && list.size() == 0) { ch = charAt(index++); break; } else { matchStat = NOT_MATCH; return null; } if (ch == ',') { ch = charAt(index++); continue; } if (ch == ']') { ch = charAt(index++); while (isWhitespace(ch)) { ch = charAt(index++); } break; } matchStat = NOT_MATCH; return null; } } else if (text.startsWith("ull", index)) { index += 3; ch = charAt(index++); list = null; } else { matchStat = NOT_MATCH; return null; } bp = index; if (ch == ',') { this.ch = charAt(bp); matchStat = VALUE; return list; } else if (ch == '}') { ch = charAt(bp); for (;;) { if (ch == ',') { token = JSONToken.COMMA; this.ch = charAt(++bp); break; } else if (ch == ']') { token = JSONToken.RBRACKET; this.ch = charAt(++bp); break; } else if (ch == '}') { token = JSONToken.RBRACE; this.ch = charAt(++bp); break; } else if (ch == EOI) { token = JSONToken.EOF; this.ch = ch; break; } else { boolean space = false; while (isWhitespace(ch)) { ch = charAt(index++); bp = index; space = true; } if (space) { continue; } matchStat = NOT_MATCH; return null; } } matchStat = END; } else { this.ch = startChar; bp = startPos; matchStat = NOT_MATCH; return null; } return list; } public long scanFieldLong(char[] fieldName) { matchStat = UNKNOWN; int startPos = this.bp; char startChar = this.ch; if (!charArrayCompare(text, bp, fieldName)) { matchStat = NOT_MATCH_NAME; return 0; } int index = bp + fieldName.length; char ch = charAt(index++); final boolean quote = ch == '"'; if (quote) { ch = charAt(index++); } boolean negative = false; if (ch == '-') { ch = charAt(index++); negative = true; } long value; if (ch >= '0' && ch <= '9') { value = ch - '0'; for (;;) { ch = charAt(index++); if (ch >= '0' && ch <= '9') { value = value * 10 + (ch - '0'); } else if (ch == '.') { matchStat = NOT_MATCH; return 0; } else { if (quote) { if (ch != '"') { matchStat = NOT_MATCH; return 0; } else { ch = charAt(index++); } } if (ch == ',' || ch == '}') { bp = index - 1; } break; } } boolean valid = value >= 0 || (value == -9223372036854775808L && negative); if (!valid) { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return 0; } } else { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return 0; } for (;;) { if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; token = JSONToken.COMMA; return negative ? -value : value; } else if (ch == '}') { ch = charAt(++bp); for (;;) { if (ch == ',') { token = JSONToken.COMMA; this.ch = charAt(++bp); break; } else if (ch == ']') { token = JSONToken.RBRACKET; this.ch = charAt(++bp); break; } else if (ch == '}') { token = JSONToken.RBRACE; this.ch = charAt(++bp); break; } else if (ch == EOI) { token = JSONToken.EOF; break; } else if (isWhitespace(ch)) { ch = charAt(++bp); } else { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return 0; } } matchStat = END; break; } else if (isWhitespace(ch)) { bp = index; ch = charAt(index++); continue; } else { matchStat = NOT_MATCH; return 0; } } return negative ? -value : value; } public boolean scanFieldBoolean(char[] fieldName) { matchStat = UNKNOWN; if (!charArrayCompare(text, bp, fieldName)) { matchStat = NOT_MATCH_NAME; return false; } int startPos = bp; int index = bp + fieldName.length; char ch = charAt(index++); final boolean quote = ch == '"'; if (quote) { ch = charAt(index++); } boolean value; if (ch == 't') { if (charAt(index++) != 'r') { matchStat = NOT_MATCH; return false; } if (charAt(index++) != 'u') { matchStat = NOT_MATCH; return false; } if (charAt(index++) != 'e') { matchStat = NOT_MATCH; return false; } if (quote && charAt(index++) != '"') { matchStat = NOT_MATCH; return false; } bp = index; ch = charAt(bp); value = true; } else if (ch == 'f') { if (charAt(index++) != 'a') { matchStat = NOT_MATCH; return false; } if (charAt(index++) != 'l') { matchStat = NOT_MATCH; return false; } if (charAt(index++) != 's') { matchStat = NOT_MATCH; return false; } if (charAt(index++) != 'e') { matchStat = NOT_MATCH; return false; } if (quote && charAt(index++) != '"') { matchStat = NOT_MATCH; return false; } bp = index; ch = charAt(bp); value = false; } else if (ch == '1') { if (quote && charAt(index++) != '"') { matchStat = NOT_MATCH; return false; } bp = index; ch = charAt(bp); value = true; } else if (ch == '0') { if (quote && charAt(index++) != '"') { matchStat = NOT_MATCH; return false; } bp = index; ch = charAt(bp); value = false; } else { matchStat = NOT_MATCH; return false; } for (;;) { if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; token = JSONToken.COMMA; break; } else if (ch == '}') { ch = charAt(++bp); for (;;) { if (ch == ',') { token = JSONToken.COMMA; this.ch = charAt(++bp); } else if (ch == ']') { token = JSONToken.RBRACKET; this.ch = charAt(++bp); } else if (ch == '}') { token = JSONToken.RBRACE; this.ch = charAt(++bp); } else if (ch == EOI) { token = JSONToken.EOF; } else if (isWhitespace(ch)) { ch = charAt(++bp); continue; } else { matchStat = NOT_MATCH; return false; } break; } matchStat = END; break; } else if (isWhitespace(ch)) { ch = charAt(++bp); } else { bp = startPos; ch = charAt(bp); matchStat = NOT_MATCH; return false; } } return value; } public final int scanInt(char expectNext) { matchStat = UNKNOWN; final int mark = bp; int offset = bp; char chLocal = charAt(offset++); while (isWhitespace(chLocal)) { chLocal = charAt(offset++); } final boolean quote = chLocal == '"'; if (quote) { chLocal = charAt(offset++); } final boolean negative = chLocal == '-'; if (negative) { chLocal = charAt(offset++); } int value; if (chLocal >= '0' && chLocal <= '9') { value = chLocal - '0'; for (;;) { chLocal = charAt(offset++); if (chLocal >= '0' && chLocal <= '9') { int value_10 = value * 10; if (value_10 < value) { throw new JSONException("parseInt error : " + subString(mark, offset - 1)); } value = value_10 + (chLocal - '0'); } else if (chLocal == '.') { matchStat = NOT_MATCH; return 0; } else { if (quote) { if (chLocal != '"') { matchStat = NOT_MATCH; return 0; } else { chLocal = charAt(offset++); } } break; } } if (value < 0) { matchStat = NOT_MATCH; return 0; } } else if (chLocal == 'n' && charAt(offset++) == 'u' && charAt(offset++) == 'l' && charAt(offset++) == 'l') { matchStat = VALUE_NULL; value = 0; chLocal = charAt(offset++); if (quote && chLocal == '"') { chLocal = charAt(offset++); } for (;;) { if (chLocal == ',') { bp = offset; this.ch = charAt(bp); matchStat = VALUE_NULL; token = JSONToken.COMMA; return value; } else if (chLocal == ']') { bp = offset; this.ch = charAt(bp); matchStat = VALUE_NULL; token = JSONToken.RBRACKET; return value; } else if (isWhitespace(chLocal)) { chLocal = charAt(offset++); continue; } break; } matchStat = NOT_MATCH; return 0; } else { matchStat = NOT_MATCH; return 0; } for (;;) { if (chLocal == expectNext) { bp = offset; this.ch = charAt(bp); matchStat = VALUE; token = JSONToken.COMMA; return negative ? -value : value; } else { if (isWhitespace(chLocal)) { chLocal = charAt(offset++); continue; } matchStat = NOT_MATCH; return negative ? -value : value; } } } public double scanDouble(char seperator) { matchStat = UNKNOWN; int offset = bp; char chLocal = charAt(offset++); final boolean quote = chLocal == '"'; if (quote) { chLocal = charAt(offset++); } boolean negative = chLocal == '-'; if (negative) { chLocal = charAt(offset++); } double value; if (chLocal >= '0' && chLocal <= '9') { long intVal = chLocal - '0'; for (; ; ) { chLocal = charAt(offset++); if (chLocal >= '0' && chLocal <= '9') { intVal = intVal * 10 + (chLocal - '0'); continue; } else { break; } } long power = 1; boolean small = (chLocal == '.'); if (small) { chLocal = charAt(offset++); if (chLocal >= '0' && chLocal <= '9') { intVal = intVal * 10 + (chLocal - '0'); power = 10; for (; ; ) { chLocal = charAt(offset++); if (chLocal >= '0' && chLocal <= '9') { intVal = intVal * 10 + (chLocal - '0'); power *= 10; continue; } else { break; } } } else { matchStat = NOT_MATCH; return 0; } } boolean exp = chLocal == 'e' || chLocal == 'E'; if (exp) { chLocal = charAt(offset++); if (chLocal == '+' || chLocal == '-') { chLocal = charAt(offset++); } for (; ; ) { if (chLocal >= '0' && chLocal <= '9') { chLocal = charAt(offset++); } else { break; } } } int start, count; if (quote) { if (chLocal != '"') { matchStat = NOT_MATCH; return 0; } else { chLocal = charAt(offset++); } start = bp + 1; count = offset - start - 2; } else { start = bp; count = offset - start - 1; } if (!exp && count < 18) { value = ((double) intVal) / power; if (negative) { value = -value; } } else { String text = this.subString(start, count); value = Double.parseDouble(text); } } else if (chLocal == 'n' && charAt(offset++) == 'u' && charAt(offset++) == 'l' && charAt(offset++) == 'l') { matchStat = VALUE_NULL; value = 0; chLocal = charAt(offset++); if (quote && chLocal == '"') { chLocal = charAt(offset++); } for (;;) { if (chLocal == ',') { bp = offset; this.ch = charAt(bp); matchStat = VALUE_NULL; token = JSONToken.COMMA; return value; } else if (chLocal == ']') { bp = offset; this.ch = charAt(bp); matchStat = VALUE_NULL; token = JSONToken.RBRACKET; return value; } else if (isWhitespace(chLocal)) { chLocal = charAt(offset++); continue; } break; } matchStat = NOT_MATCH; return 0; } else { matchStat = NOT_MATCH; return 0; } if (chLocal == seperator) { bp = offset; this.ch = this.charAt(bp); matchStat = VALUE; token = JSONToken.COMMA; return value; } else { matchStat = NOT_MATCH; return value; } } public long scanLong(char seperator) { matchStat = UNKNOWN; int offset = bp; char chLocal = charAt(offset++); final boolean quote = chLocal == '"'; if (quote) { chLocal = charAt(offset++); } final boolean negative = chLocal == '-'; if (negative) { chLocal = charAt(offset++); } long value; if (chLocal >= '0' && chLocal <= '9') { value = chLocal - '0'; for (;;) { chLocal = charAt(offset++); if (chLocal >= '0' && chLocal <= '9') { value = value * 10 + (chLocal - '0'); } else if (chLocal == '.') { matchStat = NOT_MATCH; return 0; } else { if (quote) { if (chLocal != '"') { matchStat = NOT_MATCH; return 0; } else { chLocal = charAt(offset++); } } break; } } boolean valid = value >= 0 || (value == -9223372036854775808L && negative); if (!valid) { matchStat = NOT_MATCH; return 0; } } else if (chLocal == 'n' && charAt(offset++) == 'u' && charAt(offset++) == 'l' && charAt(offset++) == 'l') { matchStat = VALUE_NULL; value = 0; chLocal = charAt(offset++); if (quote && chLocal == '"') { chLocal = charAt(offset++); } for (;;) { if (chLocal == ',') { bp = offset; this.ch = charAt(bp); matchStat = VALUE_NULL; token = JSONToken.COMMA; return value; } else if (chLocal == ']') { bp = offset; this.ch = charAt(bp); matchStat = VALUE_NULL; token = JSONToken.RBRACKET; return value; } else if (isWhitespace(chLocal)) { chLocal = charAt(offset++); continue; } break; } matchStat = NOT_MATCH; return 0; } else { matchStat = NOT_MATCH; return 0; } for (;;) { if (chLocal == seperator) { bp = offset; this.ch = charAt(bp); matchStat = VALUE; token = JSONToken.COMMA; return negative ? -value : value; } else { if (isWhitespace(chLocal)) { chLocal = charAt(offset++); continue; } matchStat = NOT_MATCH; return value; } } } public java.util.Date scanDate(char seperator) { matchStat = UNKNOWN; int startPos = this.bp; char startChar = this.ch; int index = bp; char ch = charAt(index++); final java.util.Date dateVal; if (ch == '"') { int startIndex = index; int endIndex = indexOf('"', startIndex); if (endIndex == -1) { throw new JSONException("unclosed str"); } int rest = endIndex - startIndex; bp = index; if (scanISO8601DateIfMatch(false, rest)) { dateVal = calendar.getTime(); } else { bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return null; } ch = charAt(endIndex + 1); bp = startPos; for (; ; ) { if (ch == ',' || ch == ']') { bp = endIndex + 1; this.ch = ch; break; } else if (isWhitespace(ch)) { endIndex++; ch = charAt(endIndex + 1); } else { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return null; } } } else if (ch == '-' || (ch >= '0' && ch <= '9')) { long millis = 0; boolean negative = false; if (ch == '-') { ch = charAt(index++); negative = true; } if (ch >= '0' && ch <= '9') { millis = ch - '0'; for (; ; ) { ch = charAt(index++); if (ch >= '0' && ch <= '9') { millis = millis * 10 + (ch - '0'); } else { if (ch == ',' || ch == ']') { bp = index - 1; } break; } } } if (millis < 0) { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return null; } if (negative) { millis = -millis; } dateVal = new java.util.Date(millis); } else if (ch == 'n' && charAt(index++) == 'u' && charAt(index++) == 'l' && charAt(index++) == 'l') { dateVal = null; ch = charAt(index); bp = index; } else { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return null; } if (ch == ',') { this.ch = charAt(++bp); matchStat = VALUE; return dateVal; } else { //condition ch == '}' is always 'true' ch = charAt(++bp); if (ch == ',') { token = JSONToken.COMMA; this.ch = charAt(++bp); } else if (ch == ']') { token = JSONToken.RBRACKET; this.ch = charAt(++bp); } else if (ch == '}') { token = JSONToken.RBRACE; this.ch = charAt(++bp); } else if (ch == EOI) { this.ch = EOI; token = JSONToken.EOF; } else { this.bp = startPos; this.ch = startChar; matchStat = NOT_MATCH; return null; } matchStat = END; } return dateVal; } protected final void arrayCopy(int srcPos, char[] dest, int destPos, int length) { text.getChars(srcPos, srcPos + length, dest, destPos); } public String info() { StringBuilder buf = new StringBuilder(); // buf.append("pos ").append(bp); // return "pos " + bp // // + ", json : " // // + (text.length() < 65536 // // ? text // // : text.substring(0, 65536)); int line = 1; int column = 1; for (int i = 0; i < bp; ++i, column++) { char ch = text.charAt(i); if (ch == '\n') { column = 1; line++; } } buf.append("pos ").append(bp) .append(", line ").append(line) .append(", column ").append(column); if (text.length() < 65535) { buf.append(text); } else { buf.append(text.substring(0, 65535)); } return buf.toString(); } // for hsf support public String[] scanFieldStringArray(char[] fieldName, int argTypesCount, SymbolTable typeSymbolTable) { int startPos = bp; char starChar = ch; while (isWhitespace(ch)) { next(); } int offset; char ch; if (fieldName != null) { matchStat = UNKNOWN; if (!charArrayCompare(fieldName)) { matchStat = NOT_MATCH_NAME; return null; } offset = bp + fieldName.length; ch = text.charAt(offset++); while (isWhitespace(ch)) { ch = text.charAt(offset++); } if (ch == ':') { ch = text.charAt(offset++); } else { matchStat = NOT_MATCH; return null; } while (isWhitespace(ch)) { ch = text.charAt(offset++); } } else { offset = bp + 1; ch = this.ch; } if (ch == '[') { bp = offset; this.ch = text.charAt(bp); } else if (ch == 'n' && text.startsWith("ull", bp + 1)) { bp += 4; this.ch = text.charAt(bp); return null; } else { matchStat = NOT_MATCH; return null; } String[] types = argTypesCount >= 0 ? new String[argTypesCount] : new String[4]; int typeIndex = 0; for (;;) { while (isWhitespace(this.ch)) { next(); } if (this.ch != '\"') { this.bp = startPos; this.ch = starChar; matchStat = NOT_MATCH; return null; } String type = scanSymbol(typeSymbolTable, '"'); if (typeIndex == types.length) { int newCapacity = types.length + (types.length >> 1) + 1; String[] array = new String[newCapacity]; System.arraycopy(types, 0, array, 0, types.length); types = array; } types[typeIndex++] = type; while (isWhitespace(this.ch)) { next(); } if (this.ch == ',') { next(); continue; } break; } if (types.length != typeIndex) { String[] array = new String[typeIndex]; System.arraycopy(types, 0, array, 0, typeIndex); types = array; } while (isWhitespace(this.ch)) { next(); } if (this.ch == ']') { next(); } else { this.bp = startPos; this.ch = starChar; matchStat = NOT_MATCH; return null; } return types; } public boolean matchField2(char[] fieldName) { while (isWhitespace(ch)) { next(); } if (!charArrayCompare(fieldName)) { matchStat = NOT_MATCH_NAME; return false; } int offset = bp + fieldName.length; char ch = text.charAt(offset++); while (isWhitespace(ch)) { ch = text.charAt(offset++); } if (ch == ':') { this.bp = offset; this.ch = charAt(bp); return true; } else { matchStat = NOT_MATCH_NAME; return false; } } public final void skipObject() { skipObject(false); } public final void skipObject(boolean valid) { boolean quote = false; int braceCnt = 0; int i = bp; for (; i < text.length(); ++i) { final char ch = text.charAt(i); if (ch == '\\') { if (i < len - 1) { ++i; continue; } else { this.ch = ch; this.bp = i; throw new JSONException("illegal str, " + info()); } } else if (ch == '"') { quote = !quote; } else if (ch == '{') { if (quote) { continue; } braceCnt++; } else if (ch == '}') { if (quote) { continue; } else { braceCnt--; } if (braceCnt == -1) { this.bp = i + 1; if (this.bp == text.length()) { this.ch = EOI; this.token = JSONToken.EOF; return; } this.ch = text.charAt(this.bp); if (this.ch == ',') { token = JSONToken.COMMA; int index = ++bp; this.ch = (index >= text.length() // ? EOI // : text.charAt(index)); return; } else if (this.ch == '}') { token = JSONToken.RBRACE; next(); return; } else if (this.ch == ']') { token = JSONToken.RBRACKET; next(); return; } else { nextToken(JSONToken.COMMA); } return; } } } for (int j = 0; j < bp; j++) { if (j < text.length() && text.charAt(j) == ' ') { i++; } } if (i == text.length()) { throw new JSONException("illegal str, " + info()); } } public final void skipArray() { skipArray(false); } public final void skipArray(boolean valid) { boolean quote = false; int bracketCnt = 0; int i = bp; for (; i < text.length(); ++i) { char ch = text.charAt(i); if (ch == '\\') { if (i < len - 1) { ++i; continue; } else { this.ch = ch; this.bp = i; throw new JSONException("illegal str, " + info()); } } else if (ch == '"') { quote = !quote; } else if (ch == '[') { if (quote) { continue; } bracketCnt++; } else if (ch == '{' && valid) { { int index = ++bp; this.ch = (index >= text.length() // ? EOI // : text.charAt(index)); } skipObject(valid); } else if (ch == ']') { if (quote) { continue; } else { bracketCnt--; } if (bracketCnt == -1) { this.bp = i + 1; if (this.bp == text.length()) { this.ch = EOI; token = JSONToken.EOF; return; } this.ch = text.charAt(this.bp); nextToken(JSONToken.COMMA); return; } } } if (i == text.length()) { throw new JSONException("illegal str, " + info()); } } public final void skipString() { if (ch == '"') { for (int i = bp + 1; i < text.length(); ++i) { char c = text.charAt(i); if (c == '\\') { if (i < len - 1) { ++i; continue; } } else if (c == '"') { this.ch = text.charAt(bp = i + 1); return; } } throw new JSONException("unclosed str"); } else { throw new UnsupportedOperationException(); } } public boolean seekArrayToItem(int index) { if (index < 0) { throw new IllegalArgumentException("index must > 0, but " + index); } if (token == JSONToken.EOF) { return false; } if (token != JSONToken.LBRACKET) { throw new UnsupportedOperationException(); } // nextToken(); for (int i = 0; i < index; ++i) { skipWhitespace(); if (ch == '"' || ch == '\'') { skipString(); if (ch == ',') { next(); continue; } else if (ch == ']') { next(); nextToken(JSONToken.COMMA); return false; } else { throw new JSONException("illegal json."); } } else if (ch == '{') { next(); token = JSONToken.LBRACE; skipObject(false); } else if (ch == '[') { next(); token = JSONToken.LBRACKET; skipArray(false); } else { boolean match = false; for (int j = bp + 1; j < text.length(); ++j) { char c = text.charAt(j); if (c == ',') { match = true; bp = j + 1; ch = charAt(bp); break; } else if (c == ']') { bp = j + 1; ch = charAt(bp); nextToken(); return false; } } if (!match) { throw new JSONException("illegal json."); } continue; } if (token == JSONToken.COMMA) { continue; } else if (token == JSONToken.RBRACKET) { return false; } else { throw new UnsupportedOperationException(); } } nextToken(); return true; } public int seekObjectToField(long fieldNameHash, boolean deepScan) { if (token == JSONToken.EOF) { return JSONLexer.NOT_MATCH; } if (token == JSONToken.RBRACE || token == JSONToken.RBRACKET) { nextToken(); return JSONLexer.NOT_MATCH; } if (token != JSONToken.LBRACE && token != JSONToken.COMMA) { throw new UnsupportedOperationException(JSONToken.name(token)); } for (;;) { if (ch == '}') { next(); nextToken(); return JSONLexer.NOT_MATCH; } if (ch == EOI) { return JSONLexer.NOT_MATCH; } if (ch != '"') { skipWhitespace(); } long hash; if (ch == '"') { hash = fnv1a_64_magic_hashcode; for (int i = bp + 1; i < text.length(); ++i) { char c = text.charAt(i); if (c == '\\') { ++i; if (i == text.length()) { throw new JSONException("unclosed str, " + info()); } c = text.charAt(i); } if (c == '"') { bp = i + 1; ch = (bp >= text.length() // ? EOI // : text.charAt(bp)); break; } hash ^= c; hash *= fnv1a_64_magic_prime; } } else { throw new UnsupportedOperationException(); } if (hash == fieldNameHash) { if (ch != ':') { skipWhitespace(); } if (ch == ':') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } if (ch == ',') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.COMMA; } else if (ch == ']') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.RBRACKET; } else if (ch == '}') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.RBRACE; } else if (ch >= '0' && ch <= '9') { sp = 0; pos = bp; scanNumber(); } else { nextToken(JSONToken.LITERAL_INT); } } return VALUE; } if (ch != ':') { skipWhitespace(); } if (ch == ':') { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } else { throw new JSONException("illegal json, " + info()); } if (ch != '"' && ch != '\'' && ch != '{' && ch != '[' && ch != '0' && ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6' && ch != '7' && ch != '8' && ch != '9' && ch != '+' && ch != '-') { skipWhitespace(); } // skip fieldValues if (ch == '-' || ch == '+' || (ch >= '0' && ch <= '9')) { next(); while (ch >= '0' && ch <= '9') { next(); } // scale if (ch == '.') { next(); while (ch >= '0' && ch <= '9') { next(); } } // exp if (ch == 'E' || ch == 'e') { next(); if (ch == '-' || ch == '+') { next(); } while (ch >= '0' && ch <= '9') { next(); } } if (ch != ',') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == '"') { skipString(); if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == 't') { next(); if (ch == 'r') { next(); if (ch == 'u') { next(); if (ch == 'e') { next(); } } } if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == 'n') { next(); if (ch == 'u') { next(); if (ch == 'l') { next(); if (ch == 'l') { next(); } } } if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == 'f') { next(); if (ch == 'a') { next(); if (ch == 'l') { next(); if (ch == 's') { next(); if (ch == 'e') { next(); } } } } if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == '{') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } if (deepScan) { token = JSONToken.LBRACE; return OBJECT; } skipObject(false); if (token == JSONToken.RBRACE) { return JSONLexer.NOT_MATCH; } } else if (ch == '[') { next(); if (deepScan) { token = JSONToken.LBRACKET; return ARRAY; } skipArray(false); if (token == JSONToken.RBRACE) { return JSONLexer.NOT_MATCH; } } else { throw new UnsupportedOperationException(); } } } public int seekObjectToField(long[] fieldNameHash) { if (token != JSONToken.LBRACE && token != JSONToken.COMMA) { throw new UnsupportedOperationException(); } for (;;) { if (ch == '}') { next(); nextToken(); this.matchStat = JSONLexer.NOT_MATCH; return -1; } if (ch == EOI) { this.matchStat = JSONLexer.NOT_MATCH; return -1; } if (ch != '"') { skipWhitespace(); } long hash; if (ch == '"') { hash = fnv1a_64_magic_hashcode; for (int i = bp + 1; i < text.length(); ++i) { char c = text.charAt(i); if (c == '\\') { ++i; if (i == text.length()) { throw new JSONException("unclosed str, " + info()); } c = text.charAt(i); } if (c == '"') { bp = i + 1; ch = (bp >= text.length() // ? EOI // : text.charAt(bp)); break; } hash ^= c; hash *= fnv1a_64_magic_prime; } } else { throw new UnsupportedOperationException(); } int matchIndex = -1; for (int i = 0; i < fieldNameHash.length; i++) { if (hash == fieldNameHash[i]) { matchIndex = i; break; } } if (matchIndex != -1) { if (ch != ':') { skipWhitespace(); } if (ch == ':') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } if (ch == ',') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.COMMA; } else if (ch == ']') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.RBRACKET; } else if (ch == '}') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } token = JSONToken.RBRACE; } else if (ch >= '0' && ch <= '9') { sp = 0; pos = bp; scanNumber(); } else { nextToken(JSONToken.LITERAL_INT); } } matchStat = VALUE; return matchIndex; } if (ch != ':') { skipWhitespace(); } if (ch == ':') { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } else { throw new JSONException("illegal json, " + info()); } if (ch != '"' && ch != '\'' && ch != '{' && ch != '[' && ch != '0' && ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6' && ch != '7' && ch != '8' && ch != '9' && ch != '+' && ch != '-') { skipWhitespace(); } // skip fieldValues if (ch == '-' || ch == '+' || (ch >= '0' && ch <= '9')) { next(); while (ch >= '0' && ch <= '9') { next(); } // scale if (ch == '.') { next(); while (ch >= '0' && ch <= '9') { next(); } } // exp if (ch == 'E' || ch == 'e') { next(); if (ch == '-' || ch == '+') { next(); } while (ch >= '0' && ch <= '9') { next(); } } if (ch != ',') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == '"') { skipString(); if (ch != ',' && ch != '}') { skipWhitespace(); } if (ch == ',') { next(); } } else if (ch == '{') { { int index = ++bp; ch = (index >= text.length() // ? EOI // : text.charAt(index)); } skipObject(false); } else if (ch == '[') { next(); skipArray(false); } else { throw new UnsupportedOperationException(); } } } public String scanTypeName(SymbolTable symbolTable) { if (text.startsWith("\"@type\":\"", bp)) { int p = text.indexOf('"', bp + 9); if (p != -1) { bp += 9; int h = 0; for (int i = bp; i < p; i++) { h = 31 * h + text.charAt(i); } String typeName = addSymbol(bp, p - bp, h, symbolTable); char separator = text.charAt(p + 1); if (separator != ',' && separator != ']') { return null; } bp = p + 2; ch = text.charAt(bp); return typeName; } } return null; } }
alibaba/fastjson
src/main/java/com/alibaba/fastjson/parser/JSONScanner.java
323
M tags: String, DP, Partition DP time: O(n) space: O(n) 给出一串数字, 要翻译(decode)成英文字母. [1 ~ 26] 对应相对的英文字母. 求有多少种方法可以decode. #### Method1: DP, Bottom-Up by calculating base case first - 加法原理: 根据题意, 有 range = 1 的 [1, 9], range = 2 的 [10~26] 来作为partition. - there can be 2 final states at dp[i]: single digit or double digit. - validate if `single digit`, dp[i] += dp[i - 1]. Last 1 digit can be decoded. - validate if `double digit`, dp[i] += dp[i - 2]. Last 2 digits can be decoded. - note: - get number from char: `c - '0'` - validatae single digit != '0', 因为'0' 不在条件之中(A-Z) - Option1: dp[i] as # ways to decode at index i, including letter i - The validation is done on: 1) single digit i, or 2) double digit [i-1, i] - Option2: Partition DP, dp[i] as # ways to decode for first i letters (excluding letter i) - 定义`dp[i] = 前i个digits最多有多少种decode的方法`: new dp[n + 1]. - dp[i] += dp[i - x], where x = 1, 2 - The validation is done on: 1) single digit [i-1], or 2) double digit [i-2, i-1] - Option2 is better in terms of clean coding. We assume `dp[0]=1` as 1 way to decode 0 digits. - No need to specially handle length == 1, because it is covered later - No need to manualy init the first 2-digit case as in Option1 - Return of `dp[n]` is clean - 引申: 这里只有两种partition的情况 range=1, range =2. 如果有更多partition的种类, 就可能多一层for loop做循环 #### Method2: DFS, Top-Down - if single-digit is working, sum += dfs(s, i+1); - if double-digit is working, sum += dfs(s, i+2); - end case: i >= n, return 0; i == n - 1; i == n - 2 - especially when i = n - 2, handle 2-digt edge case carefully: - 1) check if two-digit range [i, i+1] is valid - 2) check if single-digit [i] is valid; if so, += dfs(s, i + 1) - memo[i]: # ways to decode from [i, n). init with `memo[i]=-1` ``` /* A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). The number of ways decoding "12" is 2. */ /* Method1, Option1: Treating dp[i] as # ways to decode at index i, including letter i Find total number of ways. Think of DP. At last two letters: treat them as 2 separeate letters, or (if possible) treat them as combo. dp[i]: # ways to decode at index i, including letter i dp[i - 1]: # ways to decode s[0, i-1] dp[i - 2]: # ways to decode s[0, i-2] dp[i] = dp[i-1] + dp[i-2] */ class Solution { public int numDecodings(String s) { if (s == null || s.length() == 0 || s.equals("0")) return 0; if (s.length() == 1) return 1; int n = s.length(); int[] dp = new int[n]; dp[0] = s.charAt(0) != '0' ? 1 : 0; dp[1] = s.charAt(1) != '0' ? dp[0] : 0; dp[1] += check(s, 1) ? 1 : 0; for (int i = 2; i < n; i++) { if (s.charAt(i) != '0') dp[i] = dp[i - 1]; // possible to decode with just letter at i if (check(s, i)) dp[i] += dp[i - 2]; // possible to decode with (i-1, i) } return dp[n - 1]; } private boolean check(String s, int i) { int twoDigit = (s.charAt(i - 1) - '0') * 10 + (s.charAt(i) - '0'); return twoDigit <= 26 && twoDigit >= 10; } } /* Method1, Option2: Partition DP: a substring represents meaning. */ class Solution { public int numDecodings(String s) { if (s == null || s.length() == 0) return 0; int n = s.length(); int[] dp = new int[n + 1]; dp[0] = 1; // 1 to help build dp, can be: no digit, means there is only 1 way to decode: no message dp[1] = s.charAt(0) != '0' ? 1 : 0; // only has s.charAt(0); for (int i = 2; i <= n; i++) { if (s.charAt(i - 1) != '0') dp[i] += dp[i - 1]; if (check(s, i - 1)) dp[i] += dp[i - 2]; } return dp[n]; } private boolean check(String s, int i) { int twoDigit = (s.charAt(i - 1) - '0') * 10 + (s.charAt(i) - '0'); return twoDigit <= 26 && twoDigit >= 10; } } /* Method2: DFS, Top-Down - if single-digit is working, sum += dfs(s, i+1); - if double-digit is working, sum += dfs(s, i+2); - end case: i >= n, return 0; i == n - 1; i == n - 2 - memo[i]: # ways to decode from [i, n) */ class Solution { int[] memo; public int numDecodings(String s) { if (s == null) return 0; memo = new int[s.length()]; for (int i = 0; i < s.length(); i++) memo[i] = -1; return dfs(s, 0); } private int dfs(String s, int i) { if (i >= s.length()) return 0; if (memo[i] != -1) return memo[i]; if (i == s.length() - 1) return (s.charAt(i) != '0') ? 1 : 0; if (i == s.length() - 2) { int sum = check(s, i) ? 1 : 0; if (s.charAt(i) != '0') sum += dfs(s, i + 1); return sum; } int sum = (s.charAt(i) != '0') ? dfs(s, i + 1) : 0; sum += check(s, i) ? dfs(s, i + 2) : 0; memo[i] = sum; return memo[i]; } private boolean check(String s, int i) { if (i + 1 >= s.length()) return false; int twoDigit = (s.charAt(i) - '0') * 10 + (s.charAt(i + 1) - '0'); return twoDigit <= 26 && twoDigit >= 10; } } ```
awangdev/leet-code
Java/91. Decode Ways.java
324
package com.blankj.subutil.util; import android.util.Log; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2018/03/21 * desc : 位运算工具类 * </pre> */ public final class BitUtils { private BitUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * 获取运算数指定位置的值<br> * 例如: 0000 1011 获取其第 0 位的值为 1, 第 2 位 的值为 0<br> * * @param source 需要运算的数 * @param pos 指定位置 (0...7) * @return 指定位置的值(0 or 1) */ public static byte getBitValue(byte source, int pos) { return (byte) ((source >> pos) & 1); } /** * 将运算数指定位置的值置为指定值<br> * 例: 0000 1011 需要更新为 0000 1111, 即第 2 位的值需要置为 1<br> * * @param source 需要运算的数 * @param pos 指定位置 (0<=pos<=7) * @param value 只能取值为 0, 或 1, 所有大于0的值作为1处理, 所有小于0的值作为0处理 * @return 运算后的结果数 */ public static byte setBitValue(byte source, int pos, byte value) { byte mask = (byte) (1 << pos); if (value > 0) { source |= mask; } else { source &= (~mask); } return source; } /** * 将运算数指定位置取反值<br> * 例: 0000 1011 指定第 3 位取反, 结果为 0000 0011; 指定第2位取反, 结果为 0000 1111<br> * * @param source * @param pos 指定位置 (0<=pos<=7) * @return 运算后的结果数 */ public static byte reverseBitValue(byte source, int pos) { byte mask = (byte) (1 << pos); return (byte) (source ^ mask); } /** * 检查运算数的指定位置是否为1<br> * * @param source 需要运算的数 * @param pos 指定位置 (0<=pos<=7) * @return true 表示指定位置值为1, false 表示指定位置值为 0 */ public static boolean checkBitValue(byte source, int pos) { source = (byte) (source >>> pos); return (source & 1) == 1; } /** * 入口函数做测试<br> * * @param args */ public static void main(String[] args) { // 取十进制 11 (二级制 0000 1011) 为例子 byte source = 11; // 取第2位值并输出, 结果应为 0000 1011 for (byte i = 7; i >= 0; i--) { Log.d("BitUtils", getBitValue(source, i) + ""); } // 将第6位置为1并输出 , 结果为 75 (0100 1011) Log.d("BitUtils", setBitValue(source, 6, (byte) 1) + ""); // 将第6位取反并输出, 结果应为75(0100 1011) Log.d("BitUtils", reverseBitValue(source, 6) + ""); // 检查第6位是否为1,结果应为false Log.d("BitUtils", checkBitValue(source, 6) + ""); // 输出为1的位, 结果应为 0 1 3 for (byte i = 0; i < 8; i++) { if (checkBitValue(source, i)) { Log.d("BitUtils", i + ""); } } } }
Blankj/AndroidUtilCode
lib/subutil/src/main/java/com/blankj/subutil/util/BitUtils.java
328
package com.alibaba.otter.canal.parse.inbound; import static com.alibaba.otter.canal.parse.driver.mysql.utils.GtidUtil.parseGtidSet; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.lang.math.RandomUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import com.alibaba.otter.canal.common.AbstractCanalLifeCycle; import com.alibaba.otter.canal.common.alarm.CanalAlarmHandler; import com.alibaba.otter.canal.filter.CanalEventFilter; import com.alibaba.otter.canal.parse.CanalEventParser; import com.alibaba.otter.canal.parse.driver.mysql.packets.GTIDSet; import com.alibaba.otter.canal.parse.exception.CanalParseException; import com.alibaba.otter.canal.parse.exception.PositionNotFoundException; import com.alibaba.otter.canal.parse.inbound.mysql.MysqlConnection; import com.alibaba.otter.canal.parse.inbound.mysql.MysqlMultiStageCoprocessor; import com.alibaba.otter.canal.parse.index.CanalLogPositionManager; import com.alibaba.otter.canal.parse.support.AuthenticationInfo; import com.alibaba.otter.canal.protocol.CanalEntry; import com.alibaba.otter.canal.protocol.CanalEntry.Entry; import com.alibaba.otter.canal.protocol.CanalEntry.EntryType; import com.alibaba.otter.canal.protocol.CanalEntry.Header; import com.alibaba.otter.canal.protocol.position.EntryPosition; import com.alibaba.otter.canal.protocol.position.LogIdentity; import com.alibaba.otter.canal.protocol.position.LogPosition; import com.alibaba.otter.canal.sink.CanalEventSink; import com.alibaba.otter.canal.sink.exception.CanalSinkException; import com.taobao.tddl.dbsync.binlog.exception.TableIdNotFoundException; /** * 抽象的EventParser, 最大化共用mysql/oracle版本的实现 * * @author jianghang 2013-1-20 下午08:10:25 * @version 1.0.0 */ public abstract class AbstractEventParser<EVENT> extends AbstractCanalLifeCycle implements CanalEventParser<EVENT> { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected CanalLogPositionManager logPositionManager = null; protected CanalEventSink<List<CanalEntry.Entry>> eventSink = null; protected CanalEventFilter eventFilter = null; protected CanalEventFilter eventBlackFilter = null; // 字段过滤 protected String fieldFilter; protected Map<String, List<String>> fieldFilterMap; protected String fieldBlackFilter; protected Map<String, List<String>> fieldBlackFilterMap; private CanalAlarmHandler alarmHandler = null; // 统计参数 protected AtomicBoolean profilingEnabled = new AtomicBoolean(false); // profile开关参数 protected AtomicLong receivedEventCount = new AtomicLong(); protected AtomicLong parsedEventCount = new AtomicLong(); protected AtomicLong consumedEventCount = new AtomicLong(); protected long parsingInterval = -1; protected long processingInterval = -1; // 认证信息 protected volatile AuthenticationInfo runningInfo; protected String destination; // binLogParser protected BinlogParser binlogParser = null; protected Thread parseThread = null; protected Thread.UncaughtExceptionHandler handler = (t, e) -> logger.error("parse events has an error", e); protected EventTransactionBuffer transactionBuffer; protected int transactionSize = 1024; protected AtomicBoolean needTransactionPosition = new AtomicBoolean(false); protected long lastEntryTime = 0L; protected volatile boolean detectingEnable = true; // 是否开启心跳检查 protected Integer detectingIntervalInSeconds = 3; // 检测频率 protected volatile Timer timer; protected TimerTask heartBeatTimerTask; protected Throwable exception = null; protected boolean isGTIDMode = false; // 是否是GTID模式 protected boolean parallel = true; // 是否开启并行解析模式 protected Integer parallelThreadSize = Runtime.getRuntime() .availableProcessors() * 60 / 100; // 60%的能力跑解析,剩余部分处理网络 protected int parallelBufferSize = 256; // 必须为2的幂 protected MultiStageCoprocessor multiStageCoprocessor; protected ParserExceptionHandler parserExceptionHandler; protected long serverId; protected abstract BinlogParser buildParser(); protected abstract ErosaConnection buildErosaConnection(); protected abstract MultiStageCoprocessor buildMultiStageCoprocessor(); protected abstract EntryPosition findStartPosition(ErosaConnection connection) throws IOException; protected void preDump(ErosaConnection connection) { } protected boolean processTableMeta(EntryPosition position) { return true; } protected void afterDump(ErosaConnection connection) { } public void sendAlarm(String destination, String msg) { if (this.alarmHandler != null) { this.alarmHandler.sendAlarm(destination, msg); } } public AbstractEventParser(){ // 初始化一下 transactionBuffer = new EventTransactionBuffer(transaction -> { boolean successed = consumeTheEventAndProfilingIfNecessary(transaction); if (!running) { return; } if (!successed) { throw new CanalParseException("consume failed!"); } LogPosition position = buildLastTransactionPosition(transaction); if (position != null) { // 可能position为空 logPositionManager.persistLogPosition(AbstractEventParser.this.destination, position); } }); } public void start() { super.start(); MDC.put("destination", destination); // 配置transaction buffer // 初始化缓冲队列 transactionBuffer.setBufferSize(transactionSize);// 设置buffer大小 transactionBuffer.start(); // 构造bin log parser binlogParser = buildParser();// 初始化一下BinLogParser binlogParser.start(); // 启动工作线程 parseThread = new Thread(new Runnable() { public void run() { MDC.put("destination", String.valueOf(destination)); ErosaConnection erosaConnection = null; boolean isMariaDB = false; while (running) { try { // 开始执行replication // 1. 构造Erosa连接 erosaConnection = buildErosaConnection(); // 2. 启动一个心跳线程 startHeartBeat(erosaConnection); // 3. 执行dump前的准备工作 preDump(erosaConnection); erosaConnection.connect();// 链接 long queryServerId = erosaConnection.queryServerId(); if (queryServerId != 0) { serverId = queryServerId; } if (erosaConnection instanceof MysqlConnection) { isMariaDB = ((MysqlConnection) erosaConnection).isMariaDB(); } // 4. 获取最后的位置信息 long start = System.currentTimeMillis(); logger.warn("---> begin to find start position, it will be long time for reset or first position"); EntryPosition position = findStartPosition(erosaConnection); final EntryPosition startPosition = position; if (startPosition == null) { throw new PositionNotFoundException("can't find start position for " + destination); } if (!processTableMeta(startPosition)) { throw new CanalParseException("can't find init table meta for " + destination + " with position : " + startPosition); } long end = System.currentTimeMillis(); logger.warn("---> find start position successfully, {}", startPosition.toString() + " cost : " + (end - start) + "ms , the next step is binlog dump"); // 重新链接,因为在找position过程中可能有状态,需要断开后重建 erosaConnection.reconnect(); final SinkFunction sinkHandler = new SinkFunction<EVENT>() { private LogPosition lastPosition; public boolean sink(EVENT event) { try { CanalEntry.Entry entry = parseAndProfilingIfNecessary(event, false); if (!running) { return false; } if (entry != null) { exception = null; // 有正常数据流过,清空exception transactionBuffer.add(entry); // 记录一下对应的positions this.lastPosition = buildLastPosition(entry); // 记录一下最后一次有数据的时间 lastEntryTime = System.currentTimeMillis(); } return running; } catch (TableIdNotFoundException e) { throw e; } catch (Throwable e) { if (e.getCause() instanceof TableIdNotFoundException) { throw (TableIdNotFoundException) e.getCause(); } // 记录一下,出错的位点信息 processSinkError(e, this.lastPosition, startPosition.getJournalName(), startPosition.getPosition()); throw new CanalParseException(e); // 继续抛出异常,让上层统一感知 } } }; // 4. 开始dump数据 if (parallel) { // build stage processor multiStageCoprocessor = buildMultiStageCoprocessor(); if (isGTIDMode() && StringUtils.isNotEmpty(startPosition.getGtid())) { // 判断所属instance是否启用GTID模式,是的话调用ErosaConnection中GTID对应方法dump数据 GTIDSet gtidSet = parseGtidSet(startPosition.getGtid(), isMariaDB); ((MysqlMultiStageCoprocessor) multiStageCoprocessor).setGtidSet(gtidSet); multiStageCoprocessor.start(); erosaConnection.dump(gtidSet, multiStageCoprocessor); } else { multiStageCoprocessor.start(); if (StringUtils.isEmpty(startPosition.getJournalName()) && startPosition.getTimestamp() != null) { erosaConnection.dump(startPosition.getTimestamp(), multiStageCoprocessor); } else { erosaConnection.dump(startPosition.getJournalName(), startPosition.getPosition(), multiStageCoprocessor); } } } else { if (isGTIDMode() && StringUtils.isNotEmpty(startPosition.getGtid())) { // 判断所属instance是否启用GTID模式,是的话调用ErosaConnection中GTID对应方法dump数据 erosaConnection.dump(parseGtidSet(startPosition.getGtid(), isMariaDB), sinkHandler); } else { if (StringUtils.isEmpty(startPosition.getJournalName()) && startPosition.getTimestamp() != null) { erosaConnection.dump(startPosition.getTimestamp(), sinkHandler); } else { erosaConnection.dump(startPosition.getJournalName(), startPosition.getPosition(), sinkHandler); } } } } catch (TableIdNotFoundException e) { exception = e; // 特殊处理TableIdNotFound异常,出现这样的异常,一种可能就是起始的position是一个事务当中,导致tablemap // Event时间没解析过 needTransactionPosition.compareAndSet(false, true); logger.error(String.format("dump address %s has an error, retrying. caused by ", runningInfo.getAddress().toString()), e); } catch (Throwable e) { processDumpError(e); exception = e; if (!running) { if (!(e instanceof java.nio.channels.ClosedByInterruptException || e.getCause() instanceof java.nio.channels.ClosedByInterruptException)) { throw new CanalParseException(String.format("dump address %s has an error, retrying. ", runningInfo.getAddress().toString()), e); } } else { logger.error(String.format("dump address %s has an error, retrying. caused by ", runningInfo.getAddress().toString()), e); sendAlarm(destination, ExceptionUtils.getFullStackTrace(e)); } if (parserExceptionHandler != null) { parserExceptionHandler.handle(e); } } finally { // 重新置为中断状态 Thread.interrupted(); // 关闭一下链接 afterDump(erosaConnection); try { if (erosaConnection != null) { erosaConnection.disconnect(); } } catch (IOException e1) { if (!running) { throw new CanalParseException(String.format("disconnect address %s has an error, retrying. ", runningInfo.getAddress().toString()), e1); } else { logger.error("disconnect address {} has an error, retrying., caused by ", runningInfo.getAddress().toString(), e1); } } } // 出异常了,退出sink消费,释放一下状态 eventSink.interrupt(); transactionBuffer.reset();// 重置一下缓冲队列,重新记录数据 binlogParser.reset();// 重新置位 if (multiStageCoprocessor != null && multiStageCoprocessor.isStart()) { // 处理 RejectedExecutionException try { multiStageCoprocessor.stop(); } catch (Throwable t) { logger.debug("multi processor rejected:", t); } } if (running) { // sleep一段时间再进行重试 try { Thread.sleep(10000 + RandomUtils.nextInt(10000)); } catch (InterruptedException e) { } } } MDC.remove("destination"); } }); parseThread.setUncaughtExceptionHandler(handler); parseThread.setName(String.format("destination = %s , address = %s , EventParser", destination, runningInfo == null ? null : runningInfo.getAddress())); parseThread.start(); } public void stop() { super.stop(); stopHeartBeat(); // 先停止心跳 parseThread.interrupt(); // 尝试中断 eventSink.interrupt(); if (multiStageCoprocessor != null && multiStageCoprocessor.isStart()) { try { multiStageCoprocessor.stop(); } catch (Throwable t) { logger.debug("multi processor rejected:", t); } } try { parseThread.join();// 等待其结束 } catch (InterruptedException e) { // ignore } if (binlogParser.isStart()) { binlogParser.stop(); } if (transactionBuffer.isStart()) { transactionBuffer.stop(); } } protected boolean consumeTheEventAndProfilingIfNecessary(List<CanalEntry.Entry> entrys) throws CanalSinkException, InterruptedException { long startTs = -1; boolean enabled = getProfilingEnabled(); if (enabled) { startTs = System.currentTimeMillis(); } boolean result = eventSink.sink(entrys, (runningInfo == null) ? null : runningInfo.getAddress(), destination); if (enabled) { this.processingInterval = System.currentTimeMillis() - startTs; } if (consumedEventCount.incrementAndGet() < 0) { consumedEventCount.set(0); } return result; } protected CanalEntry.Entry parseAndProfilingIfNecessary(EVENT bod, boolean isSeek) throws Exception { long startTs = -1; boolean enabled = getProfilingEnabled(); if (enabled) { startTs = System.currentTimeMillis(); } CanalEntry.Entry event = binlogParser.parse(bod, isSeek); if (enabled) { this.parsingInterval = System.currentTimeMillis() - startTs; } if (parsedEventCount.incrementAndGet() < 0) { parsedEventCount.set(0); } return event; } public Boolean getProfilingEnabled() { return profilingEnabled.get(); } protected LogPosition buildLastTransactionPosition(List<CanalEntry.Entry> entries) { // 初始化一下 for (int i = entries.size() - 1; i > 0; i--) { CanalEntry.Entry entry = entries.get(i); if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {// 尽量记录一个事务做为position return buildLastPosition(entry); } } return null; } protected LogPosition buildLastPosition(CanalEntry.Entry entry) { // 初始化一下 LogPosition logPosition = new LogPosition(); EntryPosition position = new EntryPosition(); position.setJournalName(entry.getHeader().getLogfileName()); position.setPosition(entry.getHeader().getLogfileOffset()); position.setTimestamp(entry.getHeader().getExecuteTime()); // add serverId at 2016-06-28 position.setServerId(entry.getHeader().getServerId()); // set gtid position.setGtid(entry.getHeader().getGtid()); logPosition.setPostion(position); LogIdentity identity = new LogIdentity(runningInfo.getAddress(), -1L); logPosition.setIdentity(identity); return logPosition; } protected void processSinkError(Throwable e, LogPosition lastPosition, String startBinlogFile, Long startPosition) { if (lastPosition != null) { logger.warn(String.format("ERROR ## parse this event has an error , last position : [%s]", lastPosition.getPostion()), e); } else { logger.warn(String.format("ERROR ## parse this event has an error , last position : [%s,%s]", startBinlogFile, startPosition), e); } } protected void processDumpError(Throwable e) { // do nothing } protected void startHeartBeat(ErosaConnection connection) { lastEntryTime = 0L; // 初始化 if (timer == null) {// lazy初始化一下 String name = String.format("destination = %s , address = %s , HeartBeatTimeTask", destination, runningInfo == null ? null : runningInfo.getAddress().toString()); synchronized (AbstractEventParser.class) { // synchronized (MysqlEventParser.class) { // why use MysqlEventParser.class, u know, MysqlEventParser is // the child class 4 AbstractEventParser, // do this is ... if (timer == null) { timer = new Timer(name, true); } } } if (heartBeatTimerTask == null) {// fixed issue #56,避免重复创建heartbeat线程 heartBeatTimerTask = buildHeartBeatTimeTask(connection); Integer interval = detectingIntervalInSeconds; timer.schedule(heartBeatTimerTask, interval * 1000L, interval * 1000L); logger.info("start heart beat.... "); } } protected TimerTask buildHeartBeatTimeTask(ErosaConnection connection) { return new TimerTask() { public void run() { try { if (exception == null || lastEntryTime > 0) { // 如果未出现异常,或者有第一条正常数据 long now = System.currentTimeMillis(); long inteval = (now - lastEntryTime) / 1000; if (inteval >= detectingIntervalInSeconds) { Header.Builder headerBuilder = Header.newBuilder(); headerBuilder.setExecuteTime(now); Entry.Builder entryBuilder = Entry.newBuilder(); entryBuilder.setHeader(headerBuilder.build()); entryBuilder.setEntryType(EntryType.HEARTBEAT); Entry entry = entryBuilder.build(); // 提交到sink中,目前不会提交到store中,会在sink中进行忽略 consumeTheEventAndProfilingIfNecessary(Arrays.asList(entry)); } } } catch (Throwable e) { logger.warn("heartBeat run failed ", e); } } }; } protected void stopHeartBeat() { lastEntryTime = 0L; // 初始化 if (timer != null) { timer.cancel(); timer = null; } heartBeatTimerTask = null; } /** * 解析字段过滤规则 */ private Map<String, List<String>> parseFieldFilterMap(String config) { Map<String, List<String>> map = new HashMap<>(); if (StringUtils.isNotBlank(config)) { for (String filter : config.split(",")) { if (StringUtils.isBlank(filter)) { continue; } String[] filterConfig = filter.split(":"); if (filterConfig.length != 2) { continue; } map.put(filterConfig[0].trim().toUpperCase(), Arrays.asList(filterConfig[1].trim().toUpperCase().split("/"))); } } return map; } public void setEventFilter(CanalEventFilter eventFilter) { this.eventFilter = eventFilter; } public void setEventBlackFilter(CanalEventFilter eventBlackFilter) { this.eventBlackFilter = eventBlackFilter; } public Long getParsedEventCount() { return parsedEventCount.get(); } public Long getConsumedEventCount() { return consumedEventCount.get(); } public void setProfilingEnabled(boolean profilingEnabled) { this.profilingEnabled = new AtomicBoolean(profilingEnabled); } public long getParsingInterval() { return parsingInterval; } public long getProcessingInterval() { return processingInterval; } public void setEventSink(CanalEventSink<List<CanalEntry.Entry>> eventSink) { this.eventSink = eventSink; } public void setDestination(String destination) { this.destination = destination; } public void setBinlogParser(BinlogParser binlogParser) { this.binlogParser = binlogParser; } public BinlogParser getBinlogParser() { return binlogParser; } public void setAlarmHandler(CanalAlarmHandler alarmHandler) { this.alarmHandler = alarmHandler; } public CanalAlarmHandler getAlarmHandler() { return this.alarmHandler; } public void setLogPositionManager(CanalLogPositionManager logPositionManager) { this.logPositionManager = logPositionManager; } public void setTransactionSize(int transactionSize) { this.transactionSize = transactionSize; } public CanalLogPositionManager getLogPositionManager() { return logPositionManager; } public void setDetectingEnable(boolean detectingEnable) { this.detectingEnable = detectingEnable; } public void setDetectingIntervalInSeconds(Integer detectingIntervalInSeconds) { this.detectingIntervalInSeconds = detectingIntervalInSeconds; } public Throwable getException() { return exception; } public boolean isGTIDMode() { return isGTIDMode; } public void setIsGTIDMode(boolean isGTIDMode) { this.isGTIDMode = isGTIDMode; } public boolean isParallel() { return parallel; } public void setParallel(boolean parallel) { this.parallel = parallel; } public int getParallelThreadSize() { return parallelThreadSize; } public void setParallelThreadSize(Integer parallelThreadSize) { if (parallelThreadSize != null) { this.parallelThreadSize = parallelThreadSize; } } public Integer getParallelBufferSize() { return parallelBufferSize; } public void setParallelBufferSize(int parallelBufferSize) { this.parallelBufferSize = parallelBufferSize; } public ParserExceptionHandler getParserExceptionHandler() { return parserExceptionHandler; } public void setParserExceptionHandler(ParserExceptionHandler parserExceptionHandler) { this.parserExceptionHandler = parserExceptionHandler; } public long getServerId() { return serverId; } public void setServerId(long serverId) { this.serverId = serverId; } public String getFieldFilter() { return fieldFilter; } public void setFieldFilter(String fieldFilter) { this.fieldFilter = fieldFilter.trim(); this.fieldFilterMap = parseFieldFilterMap(fieldFilter); } public String getFieldBlackFilter() { return fieldBlackFilter; } public void setFieldBlackFilter(String fieldBlackFilter) { this.fieldBlackFilter = fieldBlackFilter; this.fieldBlackFilterMap = parseFieldFilterMap(fieldBlackFilter); } /** * 获取表字段过滤规则 * @return * key: schema.tableName * value: 字段列表 */ public Map<String, List<String>> getFieldFilterMap() { return fieldFilterMap; } /** * 获取表字段过滤规则黑名单 * @return * key: schema.tableName * value: 字段列表 */ public Map<String, List<String>> getFieldBlackFilterMap() { return fieldBlackFilterMap; } }
alibaba/canal
parse/src/main/java/com/alibaba/otter/canal/parse/inbound/AbstractEventParser.java
330
/** * @author mcrwayfun * @version 1.0 * @description * @date Created in 2019/1/2 */ public class Solution { /** * 转圈打印矩阵 * @param matrix 矩阵 * @return 存放结果的list */ public ArrayList<Integer> printMatrix(int[][] matrix) { ArrayList<Integer> reList = new ArrayList<>(); if (matrix == null) { return reList; } int tR = 0; int tC = 0; int dR = matrix.length - 1; int dC = matrix[0].length - 1; while (tR <= dR && tC <= dC) { printMatrix(matrix, tR++, tC++, dR--, dC--, reList); } return reList; } public void printMatrix(int[][] matrix, int tR, int tC, int dR, int dC, ArrayList<Integer> reList) { // 只有一行 if (tR == dR) { for (int i = tC; i <= dC; i++) { reList.add(matrix[tR][i]); } } // 只有一列 else if (tC == dC) { for (int i = tR; i <= dR; i++) { reList.add(matrix[i][tC]); } } else { int curR = tR; int curC = tC; // 从左到右 while (curC != dC) { reList.add(matrix[tR][curC]); curC++; } // 从上到下 while (curR != dR) { reList.add(matrix[curR][dC]); curR++; } // 从右到左 while (curC != tC) { reList.add(matrix[dR][curC]); curC--; } // 从下到上 while (curR != tR) { reList.add(matrix[curR][tC]); curR--; } } } }
geekxh/hello-algorithm
算法读物/剑指offer/29_PrintMatrix/Solution.java
331
package org.nutz.lang; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.nutz.lang.meta.Email; /** * 字符串操作的帮助函数 * * @author zozoh([email protected]) * @author wendal([email protected]) * @author mawm([email protected]) * @author bonyfish([email protected]) * @author pw([email protected]) * @author kerbores([email protected]) */ public class Strings { protected Strings() {} private static Pattern linePattern = Pattern.compile("_(\\w)"); private static Pattern humpPattern = Pattern.compile("[A-Z]"); /** * 蛇形转驼峰 * * @param str * 待转换字符串 * @return 转换结果 */ public static String line2Hump(String str) { str = str.toLowerCase(); Matcher matcher = linePattern.matcher(str); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); } matcher.appendTail(sb); return upperFirst(sb.toString()); } /** * 驼峰转蛇形 * * @param str * 待转换字符串 * @return 转换结果 */ public static String hump2Line(String str) { str = lowerFirst(str); Matcher matcher = humpPattern.matcher(str); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase()); } matcher.appendTail(sb); return sb.toString(); } /** * 是中文字符吗? * * @param c * 待判定字符 * @return 判断结果 */ public static boolean isChineseCharacter(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) { return true; } return false; } /** * 判断字符是否为全角字符 * * @param c * 字符 * @return 判断结果 */ public static boolean isFullWidthCharacter(char c) { // 全角空格为12288,半角空格为32 // 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 // 全角空格 || 其他全角字符 if (c == 12288 || (c > 65280 && c < 65375)) { return true; } // 中文全部是全角 if (isChineseCharacter(c)) { return true; } // 日文判断 // 全角平假名 u3040 - u309F // 全角片假名 u30A0 - u30FF if (c >= '\u3040' && c <= '\u30FF') { return true; } return false; } /** * 转换成半角字符 * * @param c * 待转换字符 * @return 转换后的字符 */ public static char toHalfWidthCharacter(char c) { if (c == 12288) { return (char) 32; } else if (c > 65280 && c < 65375) { return (char) (c - 65248); } return c; } /** * 转换为半角字符串 * * @param str * 待转换字符串 * @return 转换后的字符串 */ public static String toHalfWidthString(CharSequence str) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length(); i++) { sb.append(toHalfWidthCharacter(str.charAt(i))); } return sb.toString(); } /** * 判断是否是全角字符串(所有字符都是全角) * * @param str * 被判断的字符串 * @return 判断结果 */ public static boolean isFullWidthString(CharSequence str) { return charLength(str) == str.length() * 2; } /** * 判断是否是半角字符串(所有字符都是半角) * * @param str * 被判断的字符串 * @return 判断结果 */ public static boolean isHalfWidthString(CharSequence str) { return charLength(str) == str.length(); } /** * 计算字符串的字符长度(全角算2, 半角算1) * * @param str * 被计算的字符串 * @return 字符串的字符长度 */ public static int charLength(CharSequence str) { int clength = 0; for (int i = 0; i < str.length(); i++) { clength += isFullWidthCharacter(str.charAt(i)) ? 2 : 1; } return clength; } /** * 复制字符串 * * @param cs * 字符串 * @param num * 数量 * @return 新字符串 */ public static String dup(CharSequence cs, int num) { if (isEmpty(cs) || num <= 0) return ""; StringBuilder sb = new StringBuilder(cs.length() * num); for (int i = 0; i < num; i++) sb.append(cs); return sb.toString(); } /** * 复制字符 * * @param c * 字符 * @param num * 数量 * @return 新字符串 */ public static String dup(char c, int num) { if (c == 0 || num < 1) return ""; StringBuilder sb = new StringBuilder(num); for (int i = 0; i < num; i++) sb.append(c); return sb.toString(); } /** * 将字符串首字母大写 * * @param s * 字符串 * @return 首字母大写后的新字符串 * @deprecated 推荐使用 {@link #upperFirst(CharSequence)} */ @Deprecated public static String capitalize(CharSequence s) { return upperFirst(s); } /** * 将字符串首字母小写 * * @param s * 字符串 * @return 首字母小写后的新字符串 */ public static String lowerFirst(CharSequence s) { if (null == s) return null; int len = s.length(); if (len == 0) return ""; char c = s.charAt(0); if (Character.isLowerCase(c)) return s.toString(); return new StringBuilder(len).append(Character.toLowerCase(c)) .append(s.subSequence(1, len)) .toString(); } /** * 将字符串首字母大写 * * @param s * 字符串 * @return 首字母大写后的新字符串 */ public static String upperFirst(CharSequence s) { if (null == s) return null; int len = s.length(); if (len == 0) return ""; char c = s.charAt(0); if (Character.isUpperCase(c)) return s.toString(); return new StringBuilder(len).append(Character.toUpperCase(c)) .append(s.subSequence(1, len)) .toString(); } /** * 检查两个字符串的忽略大小写后是否相等. * * @param s1 * 字符串A * @param s2 * 字符串B * @return true 如果两个字符串忽略大小写后相等,且两个字符串均不为null */ public static boolean equalsIgnoreCase(String s1, String s2) { return s1 == null ? s2 == null : s1.equalsIgnoreCase(s2); } /** * 检查两个字符串是否相等. * * @param s1 * 字符串A * @param s2 * 字符串B * @return true 如果两个字符串相等,且两个字符串均不为null */ public static boolean equals(String s1, String s2) { return s1 == null ? s2 == null : s1.equals(s2); } /** * 判断字符串是否以特殊字符开头 * * @param s * 字符串 * @param c * 特殊字符 * @return 是否以特殊字符开头 */ public static boolean startsWithChar(String s, char c) { return null != s ? (s.length() == 0 ? false : s.charAt(0) == c) : false; } /** * 判断字符串是否以特殊字符结尾 * * @param s * 字符串 * @param c * 特殊字符 * @return 是否以特殊字符结尾 */ public static boolean endsWithChar(String s, char c) { return null != s ? (s.length() == 0 ? false : s.charAt(s.length() - 1) == c) : false; } /** * 如果此字符串为 null 或者为空串(""),则返回 true * * @param cs * 字符串 * @return 如果此字符串为 null 或者为空,则返回 true */ public static boolean isEmpty(CharSequence cs) { return null == cs || cs.length() == 0; } /** * 如果此字符串为 null 或者全为空白字符,则返回 true * * @param cs * 字符串 * @return 如果此字符串为 null 或者全为空白字符,则返回 true */ public static boolean isBlank(CharSequence cs) { if (null == cs) return true; int length = cs.length(); for (int i = 0; i < length; i++) { if (!(Character.isWhitespace(cs.charAt(i)))) return false; } return true; } public static boolean isNotBlank(CharSequence cs) { return !isBlank(cs); } /** * 去掉字符串前后空白字符。空白字符的定义由Character.isWhitespace来判断 * * @param cs * 字符串 * @return 去掉了前后空白字符的新字符串 */ public static String trim(CharSequence cs) { if (null == cs) return null; int length = cs.length(); if (length == 0) return cs.toString(); int l = 0; int last = length - 1; int r = last; for (; l < length; l++) { if (!Character.isWhitespace(cs.charAt(l))) break; } for (; r > l; r--) { if (!Character.isWhitespace(cs.charAt(r))) break; } if (l > r) return ""; else if (l == 0 && r == last) return cs.toString(); return cs.subSequence(l, r + 1).toString(); } public static String trimLeft(CharSequence cs) { if (null == cs) return null; int length = cs.length(); if (length == 0) return cs.toString(); int l = 0; for (; l < length; l++) { if (!Character.isWhitespace(cs.charAt(l))) break; } if ((length - 1) == l) return ""; if (l > 0) return cs.subSequence(l, length).toString(); return cs.toString(); } public static String trimRight(CharSequence cs) { if (null == cs) return null; int length = cs.length(); if (length == 0) return cs.toString(); int last = length - 1; int r = last; for (; r > 0; r--) { if (!Character.isWhitespace(cs.charAt(r))) break; } if (0 == r) return ""; if (r == last) return cs.toString(); return cs.subSequence(0, r + 1).toString(); } /** * 将给定字符串,变成 "xxx...xxx" 形式的字符串 * * @param str * 字符串 * @param len * 最大长度 * @return 紧凑的字符串 */ public static String brief(String str, int len) { if (Strings.isBlank(str) || (str.length() + 3) <= len) return str; int w = len / 2; int l = str.length(); return str.substring(0, len - w) + " ... " + str.substring(l - w); } /** * 将字符串按半角逗号,拆分成数组,空元素将被忽略 * * @param s * 字符串 * @return 字符串数组 */ public static String[] splitIgnoreBlank(String s) { return Strings.splitIgnoreBlank(s, ","); } /** * 根据一个正则式,将字符串拆分成数组,空元素将被忽略 * * @param s * 字符串 * @param regex * 正则式 * @return 字符串数组 */ public static String[] splitIgnoreBlank(String s, String regex) { if (null == s) return null; String[] ss = s.split(regex); List<String> list = new LinkedList<String>(); for (String st : ss) { if (isBlank(st)) continue; list.add(trim(st)); } return list.toArray(new String[list.size()]); } /** * 将一个整数转换成最小长度为某一固定数值的十进制形式字符串 * * @param d * 整数 * @param width * 宽度 * @return 新字符串 */ public static String fillDigit(int d, int width) { return Strings.alignRight(String.valueOf(d), width, '0'); } /** * 将一个整数转换成最小长度为某一固定数值的十六进制形式字符串 * * @param d * 整数 * @param width * 宽度 * @return 新字符串 */ public static String fillHex(int d, int width) { return Strings.alignRight(Integer.toHexString(d), width, '0'); } /** * 将一个整数转换成最小长度为某一固定数值的二进制形式字符串 * * @param d * 整数 * @param width * 宽度 * @return 新字符串 */ public static String fillBinary(int d, int width) { return Strings.alignRight(Integer.toBinaryString(d), width, '0'); } /** * 将一个整数转换成固定长度的十进制形式字符串 * * @param d * 整数 * @param width * 宽度 * @return 新字符串 */ public static String toDigit(int d, int width) { return Strings.cutRight(String.valueOf(d), width, '0'); } /** * 将一个整数转换成固定长度的十六进制形式字符串 * * @param d * 整数 * @param width * 宽度 * @return 新字符串 */ public static String toHex(int d, int width) { return Strings.cutRight(Integer.toHexString(d), width, '0'); } /** * 将一个整数转换成固定长度的二进制形式字符串 * * @param d * 整数 * @param width * 宽度 * @return 新字符串 */ public static String toBinary(int d, int width) { return Strings.cutRight(Integer.toBinaryString(d), width, '0'); } /** * 保证字符串为一固定长度。超过长度,切除右侧字符,否则右侧填补字符。 * * @param s * 字符串 * @param width * 长度 * @param c * 补字符 * @return 修饰后的字符串 */ public static String cutRight(String s, int width, char c) { if (null == s) return null; int len = s.length(); if (len == width) return s; if (len < width) return Strings.dup(c, width - len) + s; return s.substring(len - width, len); } /** * 保证字符串为一固定长度。超过长度,切除左侧字符,否则左侧填补字符。 * * @param s * 字符串 * @param width * 长度 * @param c * 补字符 * @return 修饰后的字符串 */ public static String cutLeft(String s, int width, char c) { if (null == s) return null; int len = s.length(); if (len == width) return s; if (len < width) return s + Strings.dup(c, width - len); return s.substring(0, width); } /** * 在字符串左侧填充一定数量的特殊字符 * * @param o * 可被 toString 的对象 * @param width * 字符数量 * @param c * 字符 * @return 新字符串 */ public static String alignRight(Object o, int width, char c) { if (null == o) return null; String s = o.toString(); int len = s.length(); if (len >= width) return s; return new StringBuilder().append(dup(c, width - len)).append(s).toString(); } /** * 在字符串右侧填充一定数量的特殊字符 * * @param o * 可被 toString 的对象 * @param width * 字符数量 * @param c * 字符 * @return 新字符串 */ public static String alignLeft(Object o, int width, char c) { if (null == o) return null; String s = o.toString(); int length = s.length(); if (length >= width) return s; return new StringBuilder().append(s).append(dup(c, width - length)).toString(); } /** * 测试此字符串是否被指定的左字符和右字符所包裹;如果该字符串左右两边有空白的时候,会首先忽略这些空白 * * @param cs * 字符串 * @param lc * 左字符 * @param rc * 右字符 * @return 字符串是被左字符和右字符包裹 */ public static boolean isQuoteByIgnoreBlank(CharSequence cs, char lc, char rc) { if (null == cs) return false; int len = cs.length(); if (len < 2) return false; int l = 0; int last = len - 1; int r = last; for (; l < len; l++) { if (!Character.isWhitespace(cs.charAt(l))) break; } if (cs.charAt(l) != lc) return false; for (; r > l; r--) { if (!Character.isWhitespace(cs.charAt(r))) break; } return l < r && cs.charAt(r) == rc; } /** * 测试此字符串是否被指定的左字符和右字符所包裹 * * @param cs * 字符串 * @param lc * 左字符 * @param rc * 右字符 * @return 字符串是被左字符和右字符包裹 */ public static boolean isQuoteBy(CharSequence cs, char lc, char rc) { if (null == cs) return false; int length = cs.length(); return length > 1 && cs.charAt(0) == lc && cs.charAt(length - 1) == rc; } /** * 测试此字符串是否被指定的左字符串和右字符串所包裹 * * @param str * 字符串 * @param l * 左字符串 * @param r * 右字符串 * @return 字符串是被左字符串和右字符串包裹 */ public static boolean isQuoteBy(String str, String l, String r) { if (null == str || null == l || null == r) return false; return str.startsWith(l) && str.endsWith(r); } /** * 计算一个字符串开头有几个缩进, * * @param str * 给定字符串 * @param tabWidth * 一个 \t 相当于几个空格,默认 4 * @return 返回缩进级别 */ public static int countStrHeadIndent(String str, int tabWidth) { int n = 0; if (!isEmpty(str)) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (' ' == c) n++; else if ('\t' == c) n += tabWidth; else break; } } return n / tabWidth; } /** * 计算一个字符串开头有几个重复的字符 * * @param str * 给定字符串 * @param c * 指定重复字符 * @return 开头重复字符的个数 */ public static int countStrHeadChar(String str, char c) { int re = 0; if (!isEmpty(str)) for (; re < str.length(); re++) { if (str.charAt(re) != c) return re; } return re; } /** * 对字符串反向缩进 * * @param str * 给定字符串 * @param indent * 反向 indent 几次,如果小于等于 0 相当于 1 * @param tabWidth * 一个 \t 相当于几个空格,默认 4 * * @return 反向缩进后的字符串 */ public static String shiftIndent(String str, int indent, int tabWidth) { if (isEmpty(str)) return str; if (indent <= 0) indent = 1; int n = 0; int i = 0; for (; i < str.length(); i++) { if (n > 0 && (n / tabWidth) >= indent) break; char c = str.charAt(i); if (' ' == c) n++; else if ('\t' == c) n += tabWidth; else break; } if (i > 0) return str.substring(i); return str; } /** * 获得一个字符串集合中,最长串的长度 * * @param coll * 字符串集合 * @return 最大长度 */ public static int maxLength(Collection<? extends CharSequence> coll) { int re = 0; if (null != coll) for (CharSequence s : coll) if (null != s) re = Math.max(re, s.length()); return re; } /** * 获得一个字符串数组中,最长串的长度 * * @param array * 字符串数组 * @return 最大长度 */ public static <T extends CharSequence> int maxLength(T[] array) { int re = 0; if (null != array) for (CharSequence s : array) if (null != s) re = Math.max(re, s.length()); return re; } /** * 对指定对象进行 toString 操作;如果该对象为 null ,则返回空串("") * * @param obj * 指定的对象 * @return 对指定对象进行 toString 操作;如果该对象为 null ,则返回空串("") */ public static String sNull(Object obj) { return sNull(obj, ""); } /** * 对指定对象进行 toString 操作;如果该对象为 null ,则返回默认值 * * @param obj * 指定的对象 * @param def * 默认值 * @return 对指定对象进行 toString 操作;如果该对象为 null ,则返回默认值 */ public static String sNull(Object obj, String def) { return obj != null ? obj.toString() : def; } /** * 对指定对象进行 toString 操作;如果该对象为 null ,则返回空串("") * * @param obj * 指定的对象 * @return 对指定对象进行 toString 操作;如果该对象为 null ,则返回空串("") */ public static String sBlank(Object obj) { return sBlank(obj, ""); } /** * 对指定对象进行 toString 操作;如果该对象为 null 或者 toString 方法为空串(""),则返回默认值 * * @param obj * 指定的对象 * @param def * 默认值 * @return 对指定对象进行 toString 操作;如果该对象为 null 或者 toString 方法为空串(""),则返回默认值 */ public static String sBlank(Object obj, String def) { if (null == obj) return def; String s = obj.toString(); return Strings.isBlank(s) ? def : s; } /** * 截去第一个字符 * <p> * 比如: * <ul> * <li>removeFirst("12345") => 2345 * <li>removeFirst("A") => "" * </ul> * * @param str * 字符串 * @return 新字符串 */ public static String removeFirst(CharSequence str) { if (str == null) return null; if (str.length() > 1) return str.subSequence(1, str.length()).toString(); return ""; } /** * 如果str中第一个字符和 c一致,则删除,否则返回 str * <p> * 比如: * <ul> * <li>removeFirst("12345",1) => "2345" * <li>removeFirst("ABC",'B') => "ABC" * <li>removeFirst("A",'B') => "A" * <li>removeFirst("A",'A') => "" * </ul> * * @param str * 字符串 * @param c * 第一个个要被截取的字符 * @return 新字符串 */ public static String removeFirst(String str, char c) { return (Strings.isEmpty(str) || c != str.charAt(0)) ? str : str.substring(1); } /** * 判断一个字符串数组是否包括某一字符串 * * @param ss * 字符串数组 * @param s * 字符串 * @return 是否包含 */ public static boolean isin(String[] ss, String s) { if (null == ss || ss.length == 0 || Strings.isBlank(s)) return false; for (String w : ss) if (s.equals(w)) return true; return false; } /** * 检查一个字符串是否为合法的电子邮件地址 * * @param input * 需要检查的字符串 * @return true 如果是有效的邮箱地址 */ public static final boolean isEmail(CharSequence input) { if (Strings.isBlank(input)) return false; try { new Email(input.toString()); return true; } catch (Exception e) {} return false; } /** * 将一个字符串由驼峰式命名变成分割符分隔单词 * <p> * * <pre> * lowerWord("helloWorld", '-') => "hello-world" * </pre> * * @param cs * 字符串 * @param c * 分隔符 * @return 转换后字符串 */ public static String lowerWord(CharSequence cs, char c) { StringBuilder sb = new StringBuilder(); int len = cs.length(); for (int i = 0; i < len; i++) { char ch = cs.charAt(i); if (Character.isUpperCase(ch)) { if (i > 0) sb.append(c); sb.append(Character.toLowerCase(ch)); } else { sb.append(ch); } } return sb.toString(); } /** * 将一个字符串某一个字符后面的字母变成大写,比如 * <p> * * <pre> * upperWord("hello-world", '-') => "helloWorld" * </pre> * * @param cs * 字符串 * @param c * 分隔符 * @return 转换后字符串 */ public static String upperWord(CharSequence cs, char c) { StringBuilder sb = new StringBuilder(); int len = cs.length(); for (int i = 0; i < len; i++) { char ch = cs.charAt(i); if (ch == c) { do { i++; if (i >= len) return sb.toString(); ch = cs.charAt(i); } while (ch == c); sb.append(Character.toUpperCase(ch)); } else { sb.append(ch); } } return sb.toString(); } private static Map<String, Object> __html_replace_map = Lang.map("'&[A-Z]?[a-z0-9]{2,};':null,'&':'&amp;','<':'&lt;'"); private static Map<String, Object> __html_replace_map_full = Lang.map("'&[A-Z]?[a-z0-9]{2,};':null,'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;'"); /** * 将一个字符串出现的HMTL元素进行转义 * <p> * * 转义字符对应如下 * <ul> * <li><code>&</code> => &amp;amp; * <li><code><</code> => &amp;lt; * <li><code>></code> => &amp;gt; * <li><code>"</code> => &amp;quot; * </ul> * * 其中,特殊的 HTML 字符会被保留,比如: * <ul> * <li><code>&amp;copy;</code> : &copy; * <li><code>&amp;reg;</code> : &reg; * <li><code>&amp;trade;</code> : &trade; * <li><code>&amp;amp;</code> : &amp; * <li><code>&amp;lt;</code> : &lt; * <li><code>&amp;gt;</code> : &gt; * <li><code>&#(两个以上数字);</code> 譬如 <code> &amp;#160;</code> * <li>更多的符合请看 <a href="http://tool.chinaz.com/Tools/htmlchar.aspx">HTML * 特殊符号编码对照表</a> * </ul> * * @param cs * 字符串 * @return 转换后字符串 */ public static String escapeHtml(CharSequence cs) { return replaceBy(cs, __html_replace_map_full); } /** * 将一个字符串出现的HMTL元素进行转义。仅仅替换尽量少的特殊元素 * <p> * * 转义字符对应如下 * <ul> * <li><code>&</code> => &amp;amp; * <li><code><</code> => &amp;lt; * </ul> * * 其中,特殊的 HTML 字符会被保留,比如: * <ul> * <li><code>&amp;copy;</code> : &copy; * <li><code>&amp;reg;</code> : &reg; * <li><code>&amp;trade;</code> : &trade; * <li><code>&amp;amp;</code> : &amp; * <li><code>&amp;lt;</code> : &lt; * <li><code>&amp;gt;</code> : &gt; * <li><code>&#(两个以上数字);</code> 譬如 <code> &amp;#160;</code> * <li>更多的符合请看 <a href="http://tool.chinaz.com/Tools/htmlchar.aspx">HTML * 特殊符号编码对照表</a> * </ul> * * @param cs * 字符串 * @return 转换后字符串 */ public static String escapeHtmlQuick(CharSequence cs) { return replaceBy(cs, __html_replace_map); } /** * 根据一个给定的 Map,来替换一段字符串。 * <p> * 以替换 HTML 为例,这个 Map 可以是 * * <pre> * { * // 值为 Null 表示不变 * "&copy;" : null, * "&#\\d{3,};" : null, // 也可以用正则表达式 * "&(amp|lt|gt|quot|qpos);" : null, * // 有值的,就要替换了 * "&" : "&amp;", // 键不支持正则表达式 * "<" : "&lt;", * ">" : "&gt;", * } * </pre> * * 实际上,本函数会根据 Map 生成一个正则表达式,然后进行替换,效率应该还不错 ^_^ * <p> * <b>!!!注意</b> 有值的组,键值不支持正则表达式 * * @param str * 原始字符串 * @param map * 如何替换的方式 * @return 新字符串 */ public static String replaceBy(CharSequence cs, Map<String, Object> map) { if (null == cs) return null; String str = cs.toString(); if (str.length() == 0) return str; if (null == map || map.isEmpty()) return str; // 准备两个分组 List<String> keys1 = new ArrayList<String>(map.size()); List<String> keys2 = new ArrayList<String>(map.size()); for (Map.Entry<String, Object> en : map.entrySet()) { String key = en.getKey(); // 没值,分作第一组 if (null == en.getValue()) { keys1.add(key); } // 有值,作为第二组 else { keys2.add(key); } } // 准备模式: 0:一组null, 1:一组val, 2: 两组 int mode = -1; // 准备正则表达式 StringBuilder regex = new StringBuilder(); if (keys1.size() > 0) { regex.append("(" + Strings.join("|", keys1) + ")"); mode = 0; } if (keys2.size() > 0) { if (mode < 0) { mode = 1; } else { mode = 2; regex.append('|'); } regex.append("(" + Strings.join("|", keys2) + ")"); } // mode 1,2 的时候才有必要转换吧 if (mode <= 0) return str; // 编译正则表达式 Pattern p = Pattern.compile(regex.toString()); // 准备返回值 StringBuilder sb = new StringBuilder(); int pos = 0; // 匹配字符串 Matcher m = p.matcher(str); while (m.find()) { // 1:一组val if (1 == mode) { // 截取前面的字符串 if (m.start() > pos) { sb.append(str.substring(pos, m.start())); } // 得到 Key,并替换 String key = m.group(1); sb.append(map.get(key)); } // 2: 两组 else { // 如果落到 Null 组了,那么直接 copy if (null != m.group(1)) { sb.append(str.substring(pos, m.end())); } // 否则 else { // 截取前面的字符串 if (m.start() > pos) { sb.append(str.substring(pos, m.start())); } // 得到 Key,并替换 String key = m.group(m.groupCount()); sb.append(map.get(key)); } } // 最后记录一下 pos pos = m.end(); } // 木有匹配,直接返回 if (pos == 0) return str; if (pos < str.length()) sb.append(str.substring(pos)); // 拼上最后一截并返回 return sb.toString(); } /** * 使用 UTF-8 编码将字符串编码为 byte 序列,并将结果存储到新的 byte 数组 * * @param cs * 字符串 * @return UTF-8编码后的 byte 数组 */ public static byte[] getBytesUTF8(CharSequence cs) { try { return cs.toString().getBytes(Encoding.UTF8); } catch (UnsupportedEncodingException e) { throw Lang.wrapThrow(e); } } // ####### 几个常用的color相关的字符串转换放这里 ######## /** * 将数字转为十六进制字符串, 默认要使用2个字符(暂时没考虑负数) * * @param n * 数字 * @return 十六进制字符串 */ public static String num2hex(int n) { String s = Integer.toHexString(n); return n <= 15 ? "0" + s : s; } /** * 十六进制字符串转换为数字 * * @param hex * 十六进制字符串 * @return 十进制数字 */ public static int hex2num(String hex) { return Integer.parseInt(hex, 16); } /** * 使用给定的分隔符, 将一个数组拼接成字符串 * * @param sp * 分隔符 * @param array * 要拼接的数组 * @return 拼接好的字符串 */ public static <T> String join2(String sp, T[] array) { return Lang.concat(sp, array).toString(); } /** * 使用给定的分隔符, 将一个数组拼接成字符串 * * @param sp * 分隔符 * @param array * 要拼接的数组 * @return 拼接好的字符串 */ public static <T> String join(String sp, T... array) { return Lang.concat(sp, array).toString(); } /** * @param off * 数组偏移量 * @param len * 寻取的元素数量 * @param sp * 分隔符 * @param array * 数组 * @return 拼接好的字符串 */ public static <T> String join(int off, int len, String sp, T[] array) { return Lang.concat(off, len, sp, array).toString(); } /** * 使用给定的分隔符, 将一个集合拼接成字符串 * * @param sp * 分隔符 * @param coll * 要拼接的集合 * @return 拼接好的字符串 */ public static <T> String join(String sp, Collection<T> coll) { return Lang.concat(sp, coll).toString(); } /** * 将一个字节数变成人类容易识别的显示字符串,比如 1.5M 等 * * @param size * 字节数 * @param SZU * 千的单位,可能为 1024 或者 1000 * @return 人类容易阅读的字符串 */ private static String _formatSizeForRead(long size, double SZU) { if (size < SZU) { return String.format("%d bytes", size); } double n = size / SZU; if (n < SZU) { return String.format("%5.2f KB", n); } n = n / SZU; if (n < SZU) { return String.format("%5.2f MB", n); } n = n / SZU; return String.format("%5.2f GB", n); } /** * @see #_formatSizeForRead(long, double) */ public static String formatSizeForReadBy1024(long size) { return _formatSizeForRead(size, 1024); } /** * @see #_formatSizeForRead(long, double) */ public static String formatSizeForReadBy1000(long size) { return _formatSizeForRead(size, 1000); } /** * 改变字符编码集 * * @param cs * 原字符串 * @param newCharset * 指定的新编码集 * @return 新字符集编码的字符串 */ public static String changeCharset(CharSequence cs, Charset newCharset) { if (cs != null) { byte[] bs = cs.toString().getBytes(); return new String(bs, newCharset); } return null; } /** * 将字符串根据转移字符转移 * * @param str * 字符串 * @return 转移后的字符串 */ public static String evalEscape(String str) { StringBuilder sb = new StringBuilder(); char[] cs = str.toCharArray(); for (int i = 0; i < cs.length; i++) { char c = cs[i]; // 如果是转义字符 if (c == '\\') { c = cs[++i]; switch (c) { case 'n': sb.append('\n'); break; case 'r': sb.append('\r'); break; case 't': sb.append('\t'); break; case 'b': sb.append('\b'); break; case '\'': case '"': case '\\': sb.append(c); break; default: throw Lang.makeThrow("evalEscape invalid char[%d] '%c' : %s", i, c, str); } } // 否则添加 else { sb.append(c); } } return sb.toString(); } /** * @see #split(String, boolean, boolean, char...) */ public static String[] split(String str, boolean keepQuote, char... seps) { return split(str, keepQuote, false, seps); } /** * 将字符串按照某个或几个分隔符拆分。 其中,遇到字符串 "..." 或者 '...' 并不拆分 * * @param str * 要被拆分的字符串 * @param keepQuote * 是否保持引号 * @param seps * 分隔符 * @return 拆分后的数组 */ public static String[] split(String str, boolean keepQuote, boolean keepBlank, char... seps) { List<String> list = new LinkedList<String>(); char[] cs = str.toCharArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < cs.length; i++) { char c = cs[i]; // 遇到分隔符号 if (Nums.isin(seps, c)) { if (keepBlank || !Strings.isBlank(sb)) { String s2 = sb.toString(); if (!keepQuote) s2 = evalEscape(s2); list.add(s2); sb = new StringBuilder(); } } // 如果是转义字符 else if (c == '\\') { i++; if (keepQuote) sb.append(c); if (i < cs.length) { c = cs[i]; sb.append(c); } else { break; } } // 字符串 else if (c == '\'' || c == '"' || c == '`') { if (keepQuote) sb.append(c); while (++i < cs.length) { char c2 = cs[i]; // 如果是转义字符 if (c2 == '\\') { sb.append('\\'); i++; if (i < cs.length) { c2 = cs[i]; sb.append(c2); } else { break; } } // 退出字符串 else if (c2 == c) { if (keepQuote) sb.append(c2); break; } // 其他附加 else { sb.append(c2); } } } // 其他,计入 else { sb.append(c); } } // 添加最后一个 if (keepBlank || !Strings.isBlank(sb)) { String s2 = sb.toString(); if (!keepQuote) s2 = evalEscape(s2); list.add(s2); } // 返回拆分后的数组 return list.toArray(new String[list.size()]); } public static String safeToString(Object obj, String dft) { if (obj == null) return "null"; try { return obj.toString(); } catch (Exception e) {} if (dft != null) return dft; return String.format("/*%s(toString FAILED)*/", obj.getClass().getName()); } protected static final Pattern reUnicode = Pattern.compile("\\\\u([0-9a-zA-Z]{4})"); public static String unicodeDecode(String s) { Matcher m = reUnicode.matcher(s); StringBuffer sb = new StringBuffer(s.length()); while (m.find()) { m.appendReplacement(sb, Character.toString((char) Integer.parseInt(m.group(1), 16))); } m.appendTail(sb); return sb.toString(); } /** * 按长度截取字符串(尾部补足) * * @param length * 长度 * @param s * 字符串内容 * @param supply * 补足内容 * @return 截断后的字符串 */ public static String cutStr(int length, String s, String supply) { if (Lang.isEmpty(length) || Lang.isEmpty(s)) return null; else if (s.length() <= length) return s; else return s.substring(0, length - 1) + supply; } /** * 判断字符串是否为URL * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isUrl(String s) { try { new java.net.URL(s); } catch (MalformedURLException e) { return false; } return true; } public static Pattern P_CitizenId = Pattern.compile("[1-9]\\d{5}[1-2]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}(\\d|X|x)"); public static Pattern P_Mobile = Pattern.compile("^((13[0-9])|(15[0-9])|(14[0-9])|(16[0-9])|(19[0-9])|(17[0-9])|(18[0-9]))\\d{8}$"); public static Pattern P_ZipCode = Pattern.compile("\\d{6}"); public static Pattern P_Money = Pattern.compile("^(\\d+(?:\\.\\d+)?)$"); public static Pattern P_Number = Pattern.compile("^[\\d]+$"); public static Pattern P_Email = Pattern.compile("^[.\\d\\w_-]+@[\\d\\w_-]+(\\.[\\d\\w]+)+$"); public static Pattern P_QQ = Pattern.compile("[1-9][0-9]{4,10}"); public static Pattern P_USCC = Pattern.compile("^(11|12|13|19|51|52|53|59|91|92|93|Y1)[1-9]{1}[0-9]{5}[0-9A-HJ-NP-RT-UW-Y0-9]{9}[0-90-9A-HJ-NP-RT-UW-Y]{1}$"); public static Pattern P_UnionPayCard = Pattern.compile("^62[0-5]\\d{13,16}$"); /** * 判断字符串是否为身份证号码(18位中国)<br> * 出生日期只支持到到2999年 * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isCitizenId(String s) { if (isBlank(s)) return false; return isMactchRegex(P_CitizenId, s); } /** * 判断是否为手机号码(中国) * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isMobile(String s) { if (isBlank(s)) return false; return isMactchRegex(P_Mobile, s); } /** * 判断字符串是否为邮政编码(中国) * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isZipCode(String s) { if (isBlank(s)) return false; return isMactchRegex(P_ZipCode, s); } /** * 判断字符串是否为货币 * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isMoney(String s) { if (isBlank(s)) return false; return isMactchRegex(P_Money, s); } /** * 判断字符串是否是数字 * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isNumber(String s) { if (isBlank(s)) return false; return isMactchRegex(P_Number, s); } /** * 通过正则表达式验证 * * @param pattern * 正则模式 * @param value * 值 * @return 判断结果 */ public static boolean isMactchRegex(Pattern pattern, String value) { return isMatch(pattern, value); } /** * 给定内容是否匹配正则 * * @param pattern * 模式 * @param content * 内容 * @return 正则为null或者""则不检查,返回true,内容为null返回false */ public static boolean isMatch(Pattern pattern, String content) { if (content == null || pattern == null) // 提供null的字符串为不匹配 return false; return pattern.matcher(content).matches(); } /** * 判断字符串是否为邮箱 * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isEmail(String s) { if (isBlank(s)) return false; return isMatch(P_Email, s); } /** * 判断字符串是否为QQ号 * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isQQ(String s) { if (isBlank(s)) return false; return isMatch(P_QQ, s); } /** * 判断字符串是否为统一社会信用代码(18位)<br> * 统一代码由十八位的阿拉伯数字或大写英文字母(不使用I、O、Z、S、V)组成。<br> * 第1位:登记管理部门代码(共一位字符)[1、5、9、Y]<br> * 第2位:机构类别代码(共一位字符)[与第一位合并成,11、12、13、19、51、52、53、59、91、92、93、Y1]组成。<br> * 第3位~第8位:登记管理机关行政区划码(共六位阿拉伯数字)[100000~999999]<br> * 第9位~第17位:主体标识码(组织机构代码)(共九位字符)<br> * 第18位:校验码​(共一位字符)<br> * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isUSCC(String s) { if (isBlank(s)) return false; return isMatch(P_USCC, s); } /** * 判断字符串是否为银联卡号<br> * 银联卡规则62开头,卡号为16-19位数字 * * @param s * 字符串内容 * @return 判断结果 */ public static boolean isUnionPayCard(String s) { if (isBlank(s)) return false; return isMatch(P_UnionPayCard, s); } /** * 截去最后一个字符 * <p> * 比如: * <ul> * <li>removeLast("12345") => 1234 * <li>removeLast("A") => "" * </ul> * * @param str * 字符串 * @return 新字符串 */ public static String removeLast(CharSequence str) { if (str == null) return null; if (str.length() > 1) return str.subSequence(0, str.length() - 1).toString(); return ""; } /** * 如果str中最后一个字符和 c一致,则删除,否则返回 str * <p> * 比如: * <ul> * <li>removeLast("12345",'5') => "1234" * <li>removeLast("ABC",'B') => "ABC" * <li>removeLast("A",'B') => "A" * <li>removeLast("A",'A') => "" * </ul> * * @param str * 字符串 * @param c * 最后一个个要被截取的字符 * @return 新字符串 */ public static String removeLast(String str, char c) { return (Strings.isEmpty(str) || !str.endsWith(c + "")) ? str : str.subSequence(0, str.length() - 1) .toString(); } }
nutzam/nutz
src/org/nutz/lang/Strings.java
333
package com.crossoverjie.algorithm; /** * 链表排序, 建议使用归并排序, * 问题描述,给定一个Int的链表,要求在时间最优的情况下完成链表元素由大到小的排序, * e.g: 1->5->4->3->2 * 排序后结果 5->4->3->2->1 * * @author [email protected] * @date 6/7/2018 11:42 PM * @since 1.0 */ public class LinkedListMergeSort { /** * 定义链表数据结构,包含当前元素,以及当前元素的后续元素指针 */ final static class Node { int e; Node next; public Node() { } public Node(int e, Node next) { this.e = e; this.next = next; } } public Node mergeSort(Node first, int length) { if (length == 1) { return first; } else { Node middle = new Node(); Node tmp = first; /** * 后期会对这里进行优化,通过一次遍历算出长度和中间元素 */ for (int i = 0; i < length; i++) { if (i == length / 2) { break; } middle = tmp; tmp = tmp.next; } /** * 这里是链表归并时要注意的细节 * 在链表进行归并排序过程中,会涉及到将一个链表打散为两个独立的链表,所以需要在中间元素的位置将其后续指针指为null; */ Node right = middle.next; middle.next = null; Node leftStart = mergeSort(first, length / 2); Node rightStart; if (length % 2 == 0) { rightStart = mergeSort(right, length / 2); } else { rightStart = mergeSort(right, length / 2 + 1); } return mergeList(leftStart, rightStart); } } /** * 合并链表,具体的实现细节可参考<code>MergeTwoSortedLists</code> * * @param left * @param right * @return */ public Node mergeList(Node left, Node right) { Node head = new Node(); Node result = head; /** * 思想就是两个链表同时遍历,将更的元素插入结果中,同时更更大的元素所属的链表的指针向下移动 */ while (!(null == left && null == right)) { Node tmp; if (left == null) { result.next = right; break; } else if (right == null) { result.next = left; break; } else if (left.e >= right.e) { tmp = left; result.next = left; result = tmp; left = left.next; } else { tmp = right; result.next = right; result = tmp; right = right.next; } } return head.next; } public static void main(String[] args) { Node head = new Node(); head.next = new Node(7, new Node(2, new Node(5, new Node(4, new Node(3, new Node(6, new Node(11, null) ) ) ) ) ) ); int length = 0; for (Node e = head.next; null != e; e = e.next) { length++; } LinkedListMergeSort sort = new LinkedListMergeSort(); head.next = sort.mergeSort(head.next, length); for (Node n = head.next; n != null; n = n.next) { System.out.println(n.e); } } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/algorithm/LinkedListMergeSort.java
336
package cn.hutool.http; import cn.hutool.core.util.EscapeUtil; import cn.hutool.core.util.ReUtil; import cn.hutool.core.util.StrUtil; /** * HTML工具类 * * <p> * 比如我们在使用爬虫爬取HTML页面后,需要对返回页面的HTML内容做一定处理,<br> * 比如去掉指定标签(例如广告栏等)、去除JS、去掉样式等等,这些操作都可以使用此工具类完成。 * * @author xiaoleilu * */ public class HtmlUtil { public static final String NBSP = StrUtil.HTML_NBSP; public static final String AMP = StrUtil.HTML_AMP; public static final String QUOTE = StrUtil.HTML_QUOTE; public static final String APOS = StrUtil.HTML_APOS; public static final String LT = StrUtil.HTML_LT; public static final String GT = StrUtil.HTML_GT; public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)"; public static final String RE_SCRIPT = "<[\\s]*?script[^>]*?>.*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; private static final char[][] TEXT = new char[256][]; static { // ascii码值最大的是【0x7f=127】,扩展ascii码值最大的是【0xFF=255】,因为ASCII码使用指定的7位或8位二进制数组合来表示128或256种可能的字符,标准ASCII码也叫基础ASCII码。 for (int i = 0; i < 256; i++) { TEXT[i] = new char[] { (char) i }; } // special HTML characters TEXT['\''] = "&#039;".toCharArray(); // 单引号 ('&apos;' doesn't work - it is not by the w3 specs) TEXT['"'] = QUOTE.toCharArray(); // 双引号 TEXT['&'] = AMP.toCharArray(); // &符 TEXT['<'] = LT.toCharArray(); // 小于号 TEXT['>'] = GT.toCharArray(); // 大于号 TEXT[' '] = NBSP.toCharArray(); // 不断开空格(non-breaking space,缩写nbsp。ASCII值是32:是用键盘输入的空格;ASCII值是160:不间断空格,即 &nbsp,所产生的空格,作用是在页面换行时不被打断) } /** * 转义文本中的HTML字符为安全的字符,以下字符被转义: * <ul> * <li>' 替换为 &amp;#039; (&amp;apos; doesn't work in HTML4)</li> * <li>" 替换为 &amp;quot;</li> * <li>&amp; 替换为 &amp;amp;</li> * <li>&lt; 替换为 &amp;lt;</li> * <li>&gt; 替换为 &amp;gt;</li> * </ul> * * @param text 被转义的文本 * @return 转义后的文本 */ public static String escape(String text) { return encode(text); } /** * 还原被转义的HTML特殊字符 * * @param htmlStr 包含转义符的HTML内容 * @return 转换后的字符串 */ public static String unescape(String htmlStr) { if (StrUtil.isBlank(htmlStr)) { return htmlStr; } return EscapeUtil.unescapeHtml4(htmlStr); } // ---------------------------------------------------------------- encode text /** * 清除所有HTML标签,但是不删除标签内的内容 * * @param content 文本 * @return 清除标签后的文本 */ public static String cleanHtmlTag(String content) { return content.replaceAll(RE_HTML_MARK, ""); } /** * 清除指定HTML标签和被标签包围的内容<br> * 不区分大小写 * * @param content 文本 * @param tagNames 要清除的标签 * @return 去除标签后的文本 */ public static String removeHtmlTag(String content, String... tagNames) { return removeHtmlTag(content, true, tagNames); } /** * 清除指定HTML标签,不包括内容<br> * 不区分大小写 * * @param content 文本 * @param tagNames 要清除的标签 * @return 去除标签后的文本 */ public static String unwrapHtmlTag(String content, String... tagNames) { return removeHtmlTag(content, false, tagNames); } /** * 清除指定HTML标签<br> * 不区分大小写 * * @param content 文本 * @param withTagContent 是否去掉被包含在标签中的内容 * @param tagNames 要清除的标签 * @return 去除标签后的文本 */ public static String removeHtmlTag(String content, boolean withTagContent, String... tagNames) { String regex; for (String tagName : tagNames) { if (StrUtil.isBlank(tagName)) { continue; } tagName = tagName.trim(); // (?i)表示其后面的表达式忽略大小写 if (withTagContent) { // 标签及其包含内容 regex = StrUtil.format("(?i)<{}(\\s+[^>]*?)?/?>(.*?</{}>)?", tagName, tagName); } else { // 标签不包含内容 regex = StrUtil.format("(?i)<{}(\\s+[^>]*?)?/?>|</?{}>", tagName, tagName); } content = ReUtil.delAll(regex, content); // 非自闭标签小写 } return content; } /** * 去除HTML标签中的属性,如果多个标签有相同属性,都去除 * * @param content 文本 * @param attrs 属性名(不区分大小写) * @return 处理后的文本 */ public static String removeHtmlAttr(String content, String... attrs) { String regex; for (final String attr : attrs) { // (?i) 表示忽略大小写 // \s* 属性名前后的空白符去除 // [^>]+? 属性值,至少有一个非>的字符,>表示标签结束 // \s+(?=>) 表示属性值后跟空格加>,即末尾的属性,此时去掉空格 // (?=\s|>) 表示属性值后跟空格(属性后还有别的属性)或者跟>(最后一个属性) regex = StrUtil.format("(?i)(\\s*{}\\s*=\\s*)" + "(" + // name="xxxx" "([\"][^\"]+?[\"])|" + // name=xxx > 或者 name=xxx> 或者 name=xxx name2=xxx "([^>]+?\\s*(?=\\s|>))" + ")", attr); content = content.replaceAll(regex, StrUtil.EMPTY); } // issue#I8YV0K 去除尾部空格 content = ReUtil.replaceAll(content, "\\s+(>|/>)", "$1"); return content; } /** * 去除指定标签的所有属性 * * @param content 内容 * @param tagNames 指定标签 * @return 处理后的文本 */ public static String removeAllHtmlAttr(String content, String... tagNames) { String regex; for (String tagName : tagNames) { regex = StrUtil.format("(?i)<{}[^>]*?>", tagName); content = content.replaceAll(regex, StrUtil.format("<{}>", tagName)); } return content; } /** * Encoder * * @param text 被编码的文本 * @return 编码后的字符 */ private static String encode(String text) { int len; if ((text == null) || ((len = text.length()) == 0)) { return StrUtil.EMPTY; } StringBuilder buffer = new StringBuilder(len + (len >> 2)); char c; for (int i = 0; i < len; i++) { c = text.charAt(i); if (c < 256) { buffer.append(TEXT[c]); } else { buffer.append(c); } } return buffer.toString(); } /** * 过滤HTML文本,防止XSS攻击 * * @param htmlContent HTML内容 * @return 过滤后的内容 */ public static String filter(String htmlContent) { return new HTMLFilter().filter(htmlContent); } }
dromara/hutool
hutool-http/src/main/java/cn/hutool/http/HtmlUtil.java
339
package com.xkcoding.orm.jpa.entity; import com.xkcoding.orm.jpa.entity.base.AbstractAuditModel; import lombok.*; import javax.persistence.*; import java.util.Collection; import java.util.Date; /** * <p> * 用户实体类 * </p> * * @author yangkai.shen * @date Created in 2018-11-07 14:06 */ @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @AllArgsConstructor @Data @Builder @Entity @Table(name = "orm_user") @ToString(callSuper = true) public class User extends AbstractAuditModel { /** * 用户名 */ private String name; /** * 加密后的密码 */ private String password; /** * 加密使用的盐 */ private String salt; /** * 邮箱 */ private String email; /** * 手机号码 */ @Column(name = "phone_number") private String phoneNumber; /** * 状态,-1:逻辑删除,0:禁用,1:启用 */ private Integer status; /** * 上次登录时间 */ @Column(name = "last_login_time") private Date lastLoginTime; /** * 关联部门表 * 1、关系维护端,负责多对多关系的绑定和解除 * 2、@JoinTable注解的name属性指定关联表的名字,joinColumns指定外键的名字,关联到关系维护端(User) * 3、inverseJoinColumns指定外键的名字,要关联的关系被维护端(Department) * 4、其实可以不使用@JoinTable注解,默认生成的关联表名称为主表表名+下划线+从表表名, * 即表名为user_department * 关联到主表的外键名:主表名+下划线+主表中的主键列名,即user_id,这里使用referencedColumnName指定 * 关联到从表的外键名:主表中用于关联的属性名+下划线+从表的主键列名,department_id * 主表就是关系维护端对应的表,从表就是关系被维护端对应的表 */ @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinTable(name = "orm_user_dept", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "dept_id", referencedColumnName = "id")) private Collection<Department> departmentList; }
xkcoding/spring-boot-demo
demo-orm-jpa/src/main/java/com/xkcoding/orm/jpa/entity/User.java
340
E 1517982439 tags: Bit Manipulation 简单, 但是很多知识点: 1. Hex 0xaaaaaaaa 是1010101....1010; 0x55555555 是01010101....0101 2. 可以用这两个hex取单数和负数. 如果需要取其他的pattern, 也可以做. 3. x很可能是negative number, 所以right-shift 要用logic shift, >>> 避免leading负数补位. ``` /* Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on). */ /* Thoughts: index '0' is even, so starting from even bits. Goal: Shift even bits << 1, shift odd bits >> 1. We need to extract all of the odd bits and all of the even bits. Trick: 0xaaaaaaaa represents: 10101010101....1010 Because 0xA: is number 10, and has binary of 1010. Similarly: 0x55555555 represents: 01010101010....0101 Because 0x5: is number 5, and has binary of 0101 Therefore: Get even bits: x & 0x55555555 Get odd bits: x & 0xaaaaaaaa End: Perform the shift and add up the two numbers together. Note: right-shift has to use the logic-shift >>> to resolve the negative number issue. */ public class Solution { public int swapOddEvenBits(int x) { return ((x & 0xaaaaaaaa) >>> 1) + ((x & 0x55555555) << 1); } } ```
awangdev/leet-code
Java/Swap Bits.java
342
package me.zhyd.oauth.utils; import com.xkcoding.http.HttpUtil; import com.xkcoding.http.config.HttpConfig; import com.xkcoding.http.support.HttpHeader; import com.xkcoding.http.support.SimpleHttpResponse; import me.zhyd.oauth.exception.AuthException; import java.util.Map; /** * HttpUtil 工具,统一处理 http 请求,方便对 simple-http 做定制 * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @version 1.0.0 * @since 1.0.0 */ public class HttpUtils { private SimpleHttpResponse httpResponse; public HttpUtils(HttpConfig config) { HttpUtil.setConfig(config); } public HttpUtils() { } /** * GET 请求 * * @param url URL * @return HttpUtils */ public HttpUtils get(String url) { this.httpResponse = HttpUtil.get(url, null, null, false); return this; } /** * GET 请求 * * @param url URL * @param params 参数 * @param header 请求头 * @param encode 是否需要 url encode * @return HttpUtils */ public HttpUtils get(String url, Map<String, String> params, HttpHeader header, boolean encode) { this.httpResponse = HttpUtil.get(url, params, header, encode); return this; } /** * POST 请求 * * @param url URL * @return HttpUtils */ public HttpUtils post(String url) { this.httpResponse = HttpUtil.post(url); return this; } /** * POST 请求 * * @param url URL * @param data JSON 参数 * @return HttpUtils */ public HttpUtils post(String url, String data) { this.httpResponse = HttpUtil.post(url, data); return this; } /** * POST 请求 * * @param url URL * @param data JSON 参数 * @param header 请求头 * @return HttpUtils */ public HttpUtils post(String url, String data, HttpHeader header) { this.httpResponse = HttpUtil.post(url, data, header); return this; } /** * POST 请求 * * @param url URL * @param params form 参数 * @param encode 是否需要 url encode * @return HttpUtils */ public HttpUtils post(String url, Map<String, String> params, boolean encode) { this.httpResponse = HttpUtil.post(url, params, encode); return this; } /** * POST 请求 * * @param url URL * @param params form 参数 * @param header 请求头 * @param encode 是否需要 url encode * @return HttpUtils */ public HttpUtils post(String url, Map<String, String> params, HttpHeader header, boolean encode) { this.httpResponse = HttpUtil.post(url, params, header, encode); return this; } private HttpUtils check() { if (null == httpResponse) { throw new AuthException("Invalid SimpleHttpResponse."); } if (!httpResponse.isSuccess()) { throw new AuthException(httpResponse.getError()); } return this; } public String getBody() { return this.check().getHttpResponse().getBody(); } public SimpleHttpResponse getHttpResponse() { return httpResponse; } }
justauth/JustAuth
src/main/java/me/zhyd/oauth/utils/HttpUtils.java
343
/** * @author Anonymous * @since 2019/11/20 */ public class Solution { class ListNode { int val; ListNode next; } /** * 删除链表的节点 * * @param head 链表头节点 * @param tobeDelete 要删除的节点 */ public ListNode deleteNode(ListNode head, ListNode tobeDelete) { if (head == null || tobeDelete == null) { return head; } // 删除的不是尾节点 if (tobeDelete.next != null) { tobeDelete.val = tobeDelete.next.val; tobeDelete.next = tobeDelete.next.next; } // 链表中仅有一个节点 else if (head == tobeDelete) { head = null; } // 删除的是尾节点 else { ListNode ptr = head; while (ptr.next != tobeDelete) { ptr = ptr.next; } ptr.next = null; } return head; } }
geekxh/hello-algorithm
算法读物/剑指offer/18_01_DeleteNodeInList/Solution.java
344
/** * File: preorder_traversal_iii_template.java * Created Time: 2023-04-16 * Author: krahets ([email protected]) */ package chapter_backtracking; import utils.*; import java.util.*; public class preorder_traversal_iii_template { /* 判断当前状态是否为解 */ static boolean isSolution(List<TreeNode> state) { return !state.isEmpty() && state.get(state.size() - 1).val == 7; } /* 记录解 */ static void recordSolution(List<TreeNode> state, List<List<TreeNode>> res) { res.add(new ArrayList<>(state)); } /* 判断在当前状态下,该选择是否合法 */ static boolean isValid(List<TreeNode> state, TreeNode choice) { return choice != null && choice.val != 3; } /* 更新状态 */ static void makeChoice(List<TreeNode> state, TreeNode choice) { state.add(choice); } /* 恢复状态 */ static void undoChoice(List<TreeNode> state, TreeNode choice) { state.remove(state.size() - 1); } /* 回溯算法:例题三 */ static void backtrack(List<TreeNode> state, List<TreeNode> choices, List<List<TreeNode>> res) { // 检查是否为解 if (isSolution(state)) { // 记录解 recordSolution(state, res); } // 遍历所有选择 for (TreeNode choice : choices) { // 剪枝:检查选择是否合法 if (isValid(state, choice)) { // 尝试:做出选择,更新状态 makeChoice(state, choice); // 进行下一轮选择 backtrack(state, Arrays.asList(choice.left, choice.right), res); // 回退:撤销选择,恢复到之前的状态 undoChoice(state, choice); } } } public static void main(String[] args) { TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7)); System.out.println("\n初始化二叉树"); PrintUtil.printTree(root); // 回溯算法 List<List<TreeNode>> res = new ArrayList<>(); backtrack(new ArrayList<>(), Arrays.asList(root), res); System.out.println("\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点"); for (List<TreeNode> path : res) { List<Integer> vals = new ArrayList<>(); for (TreeNode node : path) { vals.add(node.val); } System.out.println(vals); } } }
krahets/hello-algo
codes/java/chapter_backtracking/preorder_traversal_iii_template.java
345
/** * 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.cfg.Configuration; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; /** * IK分词器主类 * */ public final class IKSegmenter { //字符窜reader private Reader input; //分词器上下文 private AnalyzeContext context; //分词处理器列表 private List<ISegmenter> segmenters; //分词歧义裁决器 private IKArbitrator arbitrator; private Configuration configuration; /** * IK分词器构造函数 * @param input */ public IKSegmenter(Reader input ,Configuration configuration){ this.input = input; this.configuration = configuration; this.init(); } /** * 初始化 */ private void init(){ //初始化分词上下文 this.context = new AnalyzeContext(configuration); //加载子分词器 this.segmenters = this.loadSegmenters(); //加载歧义裁决器 this.arbitrator = new IKArbitrator(); } /** * 初始化词典,加载子分词器实现 * @return List<ISegmenter> */ private List<ISegmenter> loadSegmenters(){ List<ISegmenter> segmenters = new ArrayList<ISegmenter>(4); //处理字母的子分词器 segmenters.add(new LetterSegmenter()); //处理中文数量词的子分词器 segmenters.add(new CN_QuantifierSegmenter()); //处理中文词的子分词器 segmenters.add(new CJKSegmenter()); return segmenters; } /** * 分词,获取下一个词元 * @return Lexeme 词元对象 * @throws java.io.IOException */ public synchronized Lexeme next()throws IOException{ Lexeme l = null; while((l = context.getNextLexeme()) == null ){ /* * 从reader中读取数据,填充buffer * 如果reader是分次读入buffer的,那么buffer要 进行移位处理 * 移位处理上次读入的但未处理的数据 */ int available = context.fillBuffer(this.input); if(available <= 0){ //reader已经读完 context.reset(); return null; }else{ //初始化指针 context.initCursor(); do{ //遍历子分词器 for(ISegmenter segmenter : segmenters){ segmenter.analyze(context); } //字符缓冲区接近读完,需要读入新的字符 if(context.needRefillBuffer()){ break; } //向前移动指针 }while(context.moveCursor()); //重置子分词器,为下轮循环进行初始化 for(ISegmenter segmenter : segmenters){ segmenter.reset(); } } //对分词进行歧义处理 this.arbitrator.process(context, configuration.isUseSmart()); //将分词结果输出到结果集,并处理未切分的单个CJK字符 context.outputToResult(); //记录本次分词的缓冲区位移 context.markBufferOffset(); } return l; } /** * 重置分词器到初始状态 * @param input */ public synchronized void reset(Reader input) { this.input = input; context.reset(); for(ISegmenter segmenter : segmenters){ segmenter.reset(); } } /** * 返回末尾非CJK字符字符数目 */ public int getLastUselessCharNum() { return this.context.getLastUselessCharNum(); } }
infinilabs/analysis-ik
core/src/main/java/org/wltea/analyzer/core/IKSegmenter.java
347
package io.mycat.net; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.atomic.AtomicBoolean; import io.mycat.util.TimeUtil; public class AIOSocketWR extends SocketWR { private static final AIOReadHandler aioReadHandler = new AIOReadHandler(); private static final AIOWriteHandler aioWriteHandler = new AIOWriteHandler(); private final AsynchronousSocketChannel channel; protected final AbstractConnection con; protected final AtomicBoolean writing = new AtomicBoolean(false); public AIOSocketWR(AbstractConnection conn) { channel = (AsynchronousSocketChannel) conn.getChannel(); this.con = conn; } @Override public void asynRead() { ByteBuffer theBuffer = con.readBuffer; if (theBuffer == null) { theBuffer = con.processor.getBufferPool().allocate(con.processor.getBufferPool().getChunkSize()); con.readBuffer = theBuffer; channel.read(theBuffer, this, aioReadHandler); } else if (theBuffer.hasRemaining()) { channel.read(theBuffer, this, aioReadHandler); } else { throw new java.lang.IllegalArgumentException("full buffer to read "); } } private void asynWrite(final ByteBuffer buffer) { buffer.flip(); this.channel.write(buffer, this, aioWriteHandler); } // public int flushChannel(final AsynchronousSocketChannel channel, // final ByteBuffer bb, final long writeTimeout) // { // // if (!bb.hasRemaining()) // { // return 0; // } // int nWrite = bb.limit(); // try // { // while (bb.hasRemaining()) // { // channel.write(bb).get(writeTimeout, TimeUnit.SECONDS); // } // } catch (Exception ie) // { // con.close("write failed " + ie); // // } // return nWrite; // } /** * return true ,means no more data * * @return */ private boolean write0() { if (!writing.compareAndSet(false, true)) { return false; } ByteBuffer theBuffer = con.writeBuffer; if (theBuffer == null || !theBuffer.hasRemaining()) {// writeFinished,但要区分bufer是否NULL,不NULL,要回收 if (theBuffer != null) { con.recycle(theBuffer); con.writeBuffer = null; } // poll again ByteBuffer buffer = con.writeQueue.poll(); // more data if (buffer != null) { if (buffer.limit() == 0) { con.recycle(buffer); con.writeBuffer = null; con.close("quit cmd"); writing.set(false); return true; } else { con.writeBuffer = buffer; asynWrite(buffer); return false; } } else { // no buffer writing.set(false); return true; } } else { theBuffer.compact(); asynWrite(theBuffer); return false; } } protected void onWriteFinished(int result) { con.netOutBytes += result; con.processor.addNetOutBytes(result); con.lastWriteTime = TimeUtil.currentTimeMillis(); boolean noMoreData = this.write0(); if (noMoreData) { this.doNextWriteCheck(); } } public void doNextWriteCheck() { boolean noMoreData = false; noMoreData = this.write0(); if (noMoreData && !con.writeQueue.isEmpty()) { this.write0(); } } @Override public boolean checkAlive() { return channel.isOpen(); } @Override public void disableRead() { // TODO Auto-generated method stub } @Override public void enableRead() { // TODO Auto-generated method stub } } class AIOWriteHandler implements CompletionHandler<Integer, AIOSocketWR> { @Override public void completed(final Integer result, final AIOSocketWR wr) { try { wr.writing.set(false); if (result >= 0) { wr.onWriteFinished(result); } else { wr.con.close("write erro " + result); } } catch (Exception e) { AbstractConnection.LOGGER.warn("caught aio process err:", e); } } @Override public void failed(Throwable exc, AIOSocketWR wr) { wr.writing.set(false); wr.con.close("write failed " + exc); } } class AIOReadHandler implements CompletionHandler<Integer, AIOSocketWR> { @Override public void completed(final Integer i, final AIOSocketWR wr) { // con.getProcessor().getExecutor().execute(new Runnable() { // public void run() { if (i > 0) { try { wr.con.onReadData(i); wr.con.asynRead(); } catch (IOException e) { wr.con.close("handle err:" + e); } } else if (i == -1) { // System.out.println("read -1 xxxxxxxxx "+con); wr.con.close("client closed"); } // } // }); } @Override public void failed(Throwable exc, AIOSocketWR wr) { wr.con.close(exc.toString()); } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/net/AIOSocketWR.java
348
package com.macro.mall.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import com.github.pagehelper.PageHelper; import com.macro.mall.dao.*; import com.macro.mall.dto.PmsProductParam; import com.macro.mall.dto.PmsProductQueryParam; import com.macro.mall.dto.PmsProductResult; import com.macro.mall.mapper.*; import com.macro.mall.model.*; import com.macro.mall.service.PmsProductService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.stream.Collectors; /** * 商品管理Service实现类 * Created by macro on 2018/4/26. */ @Service public class PmsProductServiceImpl implements PmsProductService { private static final Logger LOGGER = LoggerFactory.getLogger(PmsProductServiceImpl.class); @Autowired private PmsProductMapper productMapper; @Autowired private PmsMemberPriceDao memberPriceDao; @Autowired private PmsMemberPriceMapper memberPriceMapper; @Autowired private PmsProductLadderDao productLadderDao; @Autowired private PmsProductLadderMapper productLadderMapper; @Autowired private PmsProductFullReductionDao productFullReductionDao; @Autowired private PmsProductFullReductionMapper productFullReductionMapper; @Autowired private PmsSkuStockDao skuStockDao; @Autowired private PmsSkuStockMapper skuStockMapper; @Autowired private PmsProductAttributeValueDao productAttributeValueDao; @Autowired private PmsProductAttributeValueMapper productAttributeValueMapper; @Autowired private CmsSubjectProductRelationDao subjectProductRelationDao; @Autowired private CmsSubjectProductRelationMapper subjectProductRelationMapper; @Autowired private CmsPrefrenceAreaProductRelationDao prefrenceAreaProductRelationDao; @Autowired private CmsPrefrenceAreaProductRelationMapper prefrenceAreaProductRelationMapper; @Autowired private PmsProductDao productDao; @Autowired private PmsProductVertifyRecordDao productVertifyRecordDao; @Override public int create(PmsProductParam productParam) { int count; //创建商品 PmsProduct product = productParam; product.setId(null); productMapper.insertSelective(product); //根据促销类型设置价格:会员价格、阶梯价格、满减价格 Long productId = product.getId(); //会员价格 relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), productId); //阶梯价格 relateAndInsertList(productLadderDao, productParam.getProductLadderList(), productId); //满减价格 relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), productId); //处理sku的编码 handleSkuStockCode(productParam.getSkuStockList(),productId); //添加sku库存信息 relateAndInsertList(skuStockDao, productParam.getSkuStockList(), productId); //添加商品参数,添加自定义商品规格 relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), productId); //关联专题 relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), productId); //关联优选 relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), productId); count = 1; return count; } private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) { if(CollectionUtils.isEmpty(skuStockList))return; for(int i=0;i<skuStockList.size();i++){ PmsSkuStock skuStock = skuStockList.get(i); if(StrUtil.isEmpty(skuStock.getSkuCode())){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); StringBuilder sb = new StringBuilder(); //日期 sb.append(sdf.format(new Date())); //四位商品id sb.append(String.format("%04d", productId)); //三位索引id sb.append(String.format("%03d", i+1)); skuStock.setSkuCode(sb.toString()); } } } @Override public PmsProductResult getUpdateInfo(Long id) { return productDao.getUpdateInfo(id); } @Override public int update(Long id, PmsProductParam productParam) { int count; //更新商品信息 PmsProduct product = productParam; product.setId(id); productMapper.updateByPrimaryKeySelective(product); //会员价格 PmsMemberPriceExample pmsMemberPriceExample = new PmsMemberPriceExample(); pmsMemberPriceExample.createCriteria().andProductIdEqualTo(id); memberPriceMapper.deleteByExample(pmsMemberPriceExample); relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), id); //阶梯价格 PmsProductLadderExample ladderExample = new PmsProductLadderExample(); ladderExample.createCriteria().andProductIdEqualTo(id); productLadderMapper.deleteByExample(ladderExample); relateAndInsertList(productLadderDao, productParam.getProductLadderList(), id); //满减价格 PmsProductFullReductionExample fullReductionExample = new PmsProductFullReductionExample(); fullReductionExample.createCriteria().andProductIdEqualTo(id); productFullReductionMapper.deleteByExample(fullReductionExample); relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), id); //修改sku库存信息 handleUpdateSkuStockList(id, productParam); //修改商品参数,添加自定义商品规格 PmsProductAttributeValueExample productAttributeValueExample = new PmsProductAttributeValueExample(); productAttributeValueExample.createCriteria().andProductIdEqualTo(id); productAttributeValueMapper.deleteByExample(productAttributeValueExample); relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), id); //关联专题 CmsSubjectProductRelationExample subjectProductRelationExample = new CmsSubjectProductRelationExample(); subjectProductRelationExample.createCriteria().andProductIdEqualTo(id); subjectProductRelationMapper.deleteByExample(subjectProductRelationExample); relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), id); //关联优选 CmsPrefrenceAreaProductRelationExample prefrenceAreaExample = new CmsPrefrenceAreaProductRelationExample(); prefrenceAreaExample.createCriteria().andProductIdEqualTo(id); prefrenceAreaProductRelationMapper.deleteByExample(prefrenceAreaExample); relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), id); count = 1; return count; } private void handleUpdateSkuStockList(Long id, PmsProductParam productParam) { //当前的sku信息 List<PmsSkuStock> currSkuList = productParam.getSkuStockList(); //当前没有sku直接删除 if(CollUtil.isEmpty(currSkuList)){ PmsSkuStockExample skuStockExample = new PmsSkuStockExample(); skuStockExample.createCriteria().andProductIdEqualTo(id); skuStockMapper.deleteByExample(skuStockExample); return; } //获取初始sku信息 PmsSkuStockExample skuStockExample = new PmsSkuStockExample(); skuStockExample.createCriteria().andProductIdEqualTo(id); List<PmsSkuStock> oriStuList = skuStockMapper.selectByExample(skuStockExample); //获取新增sku信息 List<PmsSkuStock> insertSkuList = currSkuList.stream().filter(item->item.getId()==null).collect(Collectors.toList()); //获取需要更新的sku信息 List<PmsSkuStock> updateSkuList = currSkuList.stream().filter(item->item.getId()!=null).collect(Collectors.toList()); List<Long> updateSkuIds = updateSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList()); //获取需要删除的sku信息 List<PmsSkuStock> removeSkuList = oriStuList.stream().filter(item-> !updateSkuIds.contains(item.getId())).collect(Collectors.toList()); handleSkuStockCode(insertSkuList,id); handleSkuStockCode(updateSkuList,id); //新增sku if(CollUtil.isNotEmpty(insertSkuList)){ relateAndInsertList(skuStockDao, insertSkuList, id); } //删除sku if(CollUtil.isNotEmpty(removeSkuList)){ List<Long> removeSkuIds = removeSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList()); PmsSkuStockExample removeExample = new PmsSkuStockExample(); removeExample.createCriteria().andIdIn(removeSkuIds); skuStockMapper.deleteByExample(removeExample); } //修改sku if(CollUtil.isNotEmpty(updateSkuList)){ for (PmsSkuStock pmsSkuStock : updateSkuList) { skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock); } } } @Override public List<PmsProduct> list(PmsProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); PmsProductExample productExample = new PmsProductExample(); PmsProductExample.Criteria criteria = productExample.createCriteria(); criteria.andDeleteStatusEqualTo(0); if (productQueryParam.getPublishStatus() != null) { criteria.andPublishStatusEqualTo(productQueryParam.getPublishStatus()); } if (productQueryParam.getVerifyStatus() != null) { criteria.andVerifyStatusEqualTo(productQueryParam.getVerifyStatus()); } if (!StrUtil.isEmpty(productQueryParam.getKeyword())) { criteria.andNameLike("%" + productQueryParam.getKeyword() + "%"); } if (!StrUtil.isEmpty(productQueryParam.getProductSn())) { criteria.andProductSnEqualTo(productQueryParam.getProductSn()); } if (productQueryParam.getBrandId() != null) { criteria.andBrandIdEqualTo(productQueryParam.getBrandId()); } if (productQueryParam.getProductCategoryId() != null) { criteria.andProductCategoryIdEqualTo(productQueryParam.getProductCategoryId()); } return productMapper.selectByExample(productExample); } @Override public int updateVerifyStatus(List<Long> ids, Integer verifyStatus, String detail) { PmsProduct product = new PmsProduct(); product.setVerifyStatus(verifyStatus); PmsProductExample example = new PmsProductExample(); example.createCriteria().andIdIn(ids); List<PmsProductVertifyRecord> list = new ArrayList<>(); int count = productMapper.updateByExampleSelective(product, example); //修改完审核状态后插入审核记录 for (Long id : ids) { PmsProductVertifyRecord record = new PmsProductVertifyRecord(); record.setProductId(id); record.setCreateTime(new Date()); record.setDetail(detail); record.setStatus(verifyStatus); record.setVertifyMan("test"); list.add(record); } productVertifyRecordDao.insertList(list); return count; } @Override public int updatePublishStatus(List<Long> ids, Integer publishStatus) { PmsProduct record = new PmsProduct(); record.setPublishStatus(publishStatus); PmsProductExample example = new PmsProductExample(); example.createCriteria().andIdIn(ids); return productMapper.updateByExampleSelective(record, example); } @Override public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) { PmsProduct record = new PmsProduct(); record.setRecommandStatus(recommendStatus); PmsProductExample example = new PmsProductExample(); example.createCriteria().andIdIn(ids); return productMapper.updateByExampleSelective(record, example); } @Override public int updateNewStatus(List<Long> ids, Integer newStatus) { PmsProduct record = new PmsProduct(); record.setNewStatus(newStatus); PmsProductExample example = new PmsProductExample(); example.createCriteria().andIdIn(ids); return productMapper.updateByExampleSelective(record, example); } @Override public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) { PmsProduct record = new PmsProduct(); record.setDeleteStatus(deleteStatus); PmsProductExample example = new PmsProductExample(); example.createCriteria().andIdIn(ids); return productMapper.updateByExampleSelective(record, example); } @Override public List<PmsProduct> list(String keyword) { PmsProductExample productExample = new PmsProductExample(); PmsProductExample.Criteria criteria = productExample.createCriteria(); criteria.andDeleteStatusEqualTo(0); if(!StrUtil.isEmpty(keyword)){ criteria.andNameLike("%" + keyword + "%"); productExample.or().andDeleteStatusEqualTo(0).andProductSnLike("%" + keyword + "%"); } return productMapper.selectByExample(productExample); } /** * 建立和插入关系表操作 * * @param dao 可以操作的dao * @param dataList 要插入的数据 * @param productId 建立关系的id */ private void relateAndInsertList(Object dao, List dataList, Long productId) { try { if (CollectionUtils.isEmpty(dataList)) return; for (Object item : dataList) { Method setId = item.getClass().getMethod("setId", Long.class); setId.invoke(item, (Long) null); Method setProductId = item.getClass().getMethod("setProductId", Long.class); setProductId.invoke(item, productId); } Method insertList = dao.getClass().getMethod("insertList", List.class); insertList.invoke(dao, dataList); } catch (Exception e) { LOGGER.warn("创建商品出错:{}", e.getMessage()); throw new RuntimeException(e.getMessage()); } } }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/service/impl/PmsProductServiceImpl.java
349
package com.gcssloop.canvas; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.gcssloop.view.utils.CanvasAidUtils; /** * Author: GcsSloop * <p> * Created Date: 16/8/26 * <p> * Copyright (C) 2016 GcsSloop. * <p> * GitHub: https://github.com/GcsSloop */ public class SetPolyToPoly extends View{ private static final String TAG = "SetPolyToPoly"; private int testPoint = 0; private int triggerRadius = 180; // 触发半径为180px private Bitmap mBitmap; // 要绘制的图片 private Matrix mPolyMatrix; // 测试setPolyToPoly用的Matrix private float[] src = new float[8]; private float[] dst = new float[8]; private Paint pointPaint; public SetPolyToPoly(Context context) { this(context, null); } public SetPolyToPoly(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SetPolyToPoly(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initBitmapAndMatrix(); } private void initBitmapAndMatrix() { mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.poly_test2); float[] temp = {0, 0, // 左上 mBitmap.getWidth(), 0, // 右上 mBitmap.getWidth(), mBitmap.getHeight(), // 右下 0, mBitmap.getHeight()}; // 左下 src = temp.clone(); dst = temp.clone(); pointPaint = new Paint(); pointPaint.setAntiAlias(true); pointPaint.setStrokeWidth(50); pointPaint.setColor(0xffd19165); pointPaint.setStrokeCap(Paint.Cap.ROUND); mPolyMatrix = new Matrix(); mPolyMatrix.setPolyToPoly(src, 0, src, 0, 4); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_MOVE: float tempX = event.getX(); float tempY = event.getY(); // 根据触控位置改变dst for (int i=0; i<testPoint*2; i+=2 ) { if (Math.abs(tempX - dst[i]) <= triggerRadius && Math.abs(tempY - dst[i+1]) <= triggerRadius){ dst[i] = tempX-100; dst[i+1] = tempY-100; break; // 防止两个点的位置重合 } } resetPolyMatrix(testPoint); invalidate(); break; } return true; } public void resetPolyMatrix(int pointCount){ mPolyMatrix.reset(); // 核心要点 mPolyMatrix.setPolyToPoly(src, 0, dst, 0, pointCount); } @Override protected void onDraw(Canvas canvas) { canvas.translate(100,100); // 绘制坐标系 CanvasAidUtils.setCoordinateLen(900, 0, 1200, 0); CanvasAidUtils.drawCoordinateSpace(canvas); // 根据Matrix绘制一个变换后的图片 canvas.drawBitmap(mBitmap, mPolyMatrix, null); float[] dst = new float[8]; mPolyMatrix.mapPoints(dst,src); // 绘制触控点 for (int i=0; i<testPoint*2; i+=2 ) { canvas.drawPoint(dst[i], dst[i+1],pointPaint); } } public void setTestPoint(int testPoint) { this.testPoint = testPoint > 4 || testPoint < 0 ? 4 : testPoint; dst = src.clone(); resetPolyMatrix(this.testPoint); invalidate(); } }
GcsSloop/AndroidNote
CustomView/Advance/Code/SetPolyToPoly.java
350
package org.jeecg.common.constant; /** * @Description: 通用常量 * @author: jeecg-boot */ public interface CommonConstant { /** * 正常状态 */ Integer STATUS_NORMAL = 0; /** * 禁用状态 */ Integer STATUS_DISABLE = -1; /** * 删除标志 */ Integer DEL_FLAG_1 = 1; /** * 未删除 */ Integer DEL_FLAG_0 = 0; /** * 系统日志类型: 登录 */ int LOG_TYPE_1 = 1; /** * 系统日志类型: 操作 */ int LOG_TYPE_2 = 2; /** * 操作日志类型: 查询 */ int OPERATE_TYPE_1 = 1; /** * 操作日志类型: 添加 */ int OPERATE_TYPE_2 = 2; /** * 操作日志类型: 更新 */ int OPERATE_TYPE_3 = 3; /** * 操作日志类型: 删除 */ int OPERATE_TYPE_4 = 4; /** * 操作日志类型: 倒入 */ int OPERATE_TYPE_5 = 5; /** * 操作日志类型: 导出 */ int OPERATE_TYPE_6 = 6; /** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */ Integer SC_INTERNAL_SERVER_ERROR_500 = 500; /** {@code 404 Not Found} (HTTP/1.0 - RFC 1945) */ Integer SC_INTERNAL_NOT_FOUND_404 = 404; /** {@code 200 OK} (HTTP/1.0 - RFC 1945) */ Integer SC_OK_200 = 200; /**访问权限认证未通过 510*/ Integer SC_JEECG_NO_AUTHZ=510; /** 登录用户Shiro权限缓存KEY前缀 */ public static String PREFIX_USER_SHIRO_CACHE = "shiro:cache:org.jeecg.config.shiro.ShiroRealm.authorizationCache:"; /** 登录用户Token令牌缓存KEY前缀 */ String PREFIX_USER_TOKEN = "prefix_user_token:"; // /** Token缓存时间:3600秒即一小时 */ // int TOKEN_EXPIRE_TIME = 3600; /** 登录二维码 */ String LOGIN_QRCODE_PRE = "QRCODELOGIN:"; String LOGIN_QRCODE = "LQ:"; /** 登录二维码token */ String LOGIN_QRCODE_TOKEN = "LQT:"; /** * 0:一级菜单 */ Integer MENU_TYPE_0 = 0; /** * 1:子菜单 */ Integer MENU_TYPE_1 = 1; /** * 2:按钮权限 */ Integer MENU_TYPE_2 = 2; /**通告对象类型(USER:指定用户,ALL:全体用户)*/ String MSG_TYPE_UESR = "USER"; String MSG_TYPE_ALL = "ALL"; /**发布状态(0未发布,1已发布,2已撤销)*/ String NO_SEND = "0"; String HAS_SEND = "1"; String HAS_CANCLE = "2"; /**阅读状态(0未读,1已读)*/ Integer HAS_READ_FLAG = 1; Integer NO_READ_FLAG = 0; /**优先级(L低,M中,H高)*/ String PRIORITY_L = "L"; String PRIORITY_M = "M"; String PRIORITY_H = "H"; /** * 短信模板方式 0 .登录模板、1.注册模板、2.忘记密码模板 */ String SMS_TPL_TYPE_0 = "0"; String SMS_TPL_TYPE_1 = "1"; String SMS_TPL_TYPE_2 = "2"; /** * 状态(0无效1有效) */ String STATUS_0 = "0"; String STATUS_1 = "1"; /** * 同步工作流引擎1同步0不同步 */ Integer ACT_SYNC_1 = 1; Integer ACT_SYNC_0 = 0; /** * 消息类型1:通知公告2:系统消息 */ String MSG_CATEGORY_1 = "1"; String MSG_CATEGORY_2 = "2"; /** * 是否配置菜单的数据权限 1是0否 */ Integer RULE_FLAG_0 = 0; Integer RULE_FLAG_1 = 1; /** * 是否用户已被冻结 1正常(解冻) 2冻结 3离职 */ Integer USER_UNFREEZE = 1; Integer USER_FREEZE = 2; Integer USER_QUIT = 3; /**字典翻译文本后缀*/ String DICT_TEXT_SUFFIX = "_dictText"; /**字典翻译颜色后缀*/ String DICT_COLOR_SUFFIX = "_dictColor"; /** * 表单设计器主表类型 */ Integer DESIGN_FORM_TYPE_MAIN = 1; /** * 表单设计器子表表类型 */ Integer DESIGN_FORM_TYPE_SUB = 2; /** * 表单设计器URL授权通过 */ Integer DESIGN_FORM_URL_STATUS_PASSED = 1; /** * 表单设计器URL授权未通过 */ Integer DESIGN_FORM_URL_STATUS_NOT_PASSED = 2; /** * 表单设计器新增 Flag */ String DESIGN_FORM_URL_TYPE_ADD = "add"; /** * 表单设计器修改 Flag */ String DESIGN_FORM_URL_TYPE_EDIT = "edit"; /** * 表单设计器详情 Flag */ String DESIGN_FORM_URL_TYPE_DETAIL = "detail"; /** * 表单设计器复用数据 Flag */ String DESIGN_FORM_URL_TYPE_REUSE = "reuse"; /** * 表单设计器编辑 Flag (已弃用) */ String DESIGN_FORM_URL_TYPE_VIEW = "view"; /** * online参数值设置(是:Y, 否:N) */ String ONLINE_PARAM_VAL_IS_TURE = "Y"; String ONLINE_PARAM_VAL_IS_FALSE = "N"; /** * 文件上传类型(本地:local,Minio:minio,阿里云:alioss) */ String UPLOAD_TYPE_LOCAL = "local"; String UPLOAD_TYPE_MINIO = "minio"; String UPLOAD_TYPE_OSS = "alioss"; /** * 文档上传自定义桶名称 */ String UPLOAD_CUSTOM_BUCKET = "eoafile"; /** * 文档上传自定义路径 */ String UPLOAD_CUSTOM_PATH = "eoafile"; /** * 文件外链接有效天数 */ Integer UPLOAD_EFFECTIVE_DAYS = 1; /** * 员工身份 (1:普通员工 2:上级) */ Integer USER_IDENTITY_1 = 1; Integer USER_IDENTITY_2 = 2; /** sys_user 表 username 唯一键索引 */ String SQL_INDEX_UNIQ_SYS_USER_USERNAME = "uniq_sys_user_username"; /** sys_user 表 work_no 唯一键索引 */ String SQL_INDEX_UNIQ_SYS_USER_WORK_NO = "uniq_sys_user_work_no"; /** sys_user 表 phone 唯一键索引 */ String SQL_INDEX_UNIQ_SYS_USER_PHONE = "uniq_sys_user_phone"; /** 达梦数据库升提示。违反表[SYS_USER]唯一性约束 */ String SQL_INDEX_UNIQ_SYS_USER = "唯一性约束"; /** sys_user 表 email 唯一键索引 */ String SQL_INDEX_UNIQ_SYS_USER_EMAIL = "uniq_sys_user_email"; /** sys_quartz_job 表 job_class_name 唯一键索引 */ String SQL_INDEX_UNIQ_JOB_CLASS_NAME = "uniq_job_class_name"; /** sys_position 表 code 唯一键索引 */ String SQL_INDEX_UNIQ_CODE = "uniq_code"; /** sys_role 表 code 唯一键索引 */ String SQL_INDEX_UNIQ_SYS_ROLE_CODE = "uniq_sys_role_role_code"; /** sys_depart 表 code 唯一键索引 */ String SQL_INDEX_UNIQ_DEPART_ORG_CODE = "uniq_depart_org_code"; /** sys_category 表 code 唯一键索引 */ String SQL_INDEX_UNIQ_CATEGORY_CODE = "idx_sc_code"; /** * 在线聊天 是否为默认分组 */ String IM_DEFAULT_GROUP = "1"; /** * 在线聊天 图片文件保存路径 */ String IM_UPLOAD_CUSTOM_PATH = "biz/user_imgs"; /** * 在线聊天 用户状态 */ String IM_STATUS_ONLINE = "online"; /** * 在线聊天 SOCKET消息类型 */ String IM_SOCKET_TYPE = "chatMessage"; /** * 在线聊天 是否开启默认添加好友 1是 0否 */ String IM_DEFAULT_ADD_FRIEND = "1"; /** * 在线聊天 用户好友缓存前缀 */ String IM_PREFIX_USER_FRIEND_CACHE = "sys:cache:im:im_prefix_user_friend_"; /** * 考勤补卡业务状态 (1:同意 2:不同意) */ String SIGN_PATCH_BIZ_STATUS_1 = "1"; String SIGN_PATCH_BIZ_STATUS_2 = "2"; /** * 公文文档上传自定义路径 */ String UPLOAD_CUSTOM_PATH_OFFICIAL = "officialdoc"; /** * 公文文档下载自定义路径 */ String DOWNLOAD_CUSTOM_PATH_OFFICIAL = "officaldown"; /** * WPS存储值类别(1 code文号 2 text(WPS模板还是公文发文模板)) */ String WPS_TYPE_1="1"; String WPS_TYPE_2="2"; /**===============================================================================================*/ /** * ::非常重要:: * 注意:这四个常量值如果修改,需要与 jeecg-boot-starter/jeecg-boot-common/org.jeecg.config.FeignConfig 类中的值保持一致。 */ String X_ACCESS_TOKEN = "X-Access-Token"; String X_SIGN = "X-Sign"; String X_TIMESTAMP = "X-TIMESTAMP"; /** 租户请求头 更名为:X-Tenant-Id */ String TENANT_ID = "X-Tenant-Id"; /** 简流接口请求头,用于排除不支持的控件字段 */ String X_MiniFlowExclusionFieldMode = "X-Miniflowexclusionfieldmode"; /**===============================================================================================*/ String TOKEN_IS_INVALID_MSG = "Token失效,请重新登录!"; String X_FORWARDED_SCHEME = "X-Forwarded-Scheme"; /** * 微服务读取配置文件属性 服务地址 */ String CLOUD_SERVER_KEY = "spring.cloud.nacos.discovery.server-addr"; /** * 第三方登录 验证密码/创建用户 都需要设置一个操作码 防止被恶意调用 */ String THIRD_LOGIN_CODE = "third_login_code"; /** * 第三方APP同步方向:本地 --> 第三方APP */ String THIRD_SYNC_TO_APP = "SYNC_TO_APP"; /** * 第三方APP同步方向:第三方APP --> 本地 */ String THIRD_SYNC_TO_LOCAL = "SYNC_TO_LOCAL"; /** 系统通告消息状态:0=未发布 */ String ANNOUNCEMENT_SEND_STATUS_0 = "0"; /** 系统通告消息状态:1=已发布 */ String ANNOUNCEMENT_SEND_STATUS_1 = "1"; /** 系统通告消息状态:2=已撤销 */ String ANNOUNCEMENT_SEND_STATUS_2 = "2"; /**ONLINE 报表权限用 从request中获取地址栏后的参数*/ String ONL_REP_URL_PARAM_STR="onlRepUrlParamStr"; /**POST请求*/ String HTTP_POST = "POST"; /**PUT请求*/ String HTTP_PUT = "PUT"; /**PATCH请求*/ String HTTP_PATCH = "PATCH"; /**未知的*/ String UNKNOWN = "unknown"; /**字符串http*/ String STR_HTTP = "http"; /**String 类型的空值*/ String STRING_NULL = "null"; /**前端vue3版本Header参数名*/ String VERSION="X-Version"; String VERSION_V3 = "v3"; /**存储在线程变量里的动态表名*/ String DYNAMIC_TABLE_NAME="DYNAMIC_TABLE_NAME"; /** * http:// http协议 */ String HTTP_PROTOCOL = "http://"; /** * https:// https协议 */ String HTTPS_PROTOCOL = "https://"; /** 部门表唯一key,id */ String DEPART_KEY_ID = "id"; /** 部门表唯一key,orgCode */ String DEPART_KEY_ORG_CODE = "orgCode"; /**======【消息推送相关】==============================================================================*/ /** * 发消息 会传递一些信息到map */ String NOTICE_MSG_SUMMARY = "NOTICE_MSG_SUMMARY"; /** * 发消息 会传递一个业务ID到map */ String NOTICE_MSG_BUS_ID = "NOTICE_MSG_BUS_ID"; /** * 发消息 消息业务类型 */ String NOTICE_MSG_BUS_TYPE = "NOTICE_MSG_BUS_TYPE"; /** * 邮箱消息中地址登录时地址后携带的token,需要替换成真实的token值 */ String LOGIN_TOKEN = "{LOGIN_TOKEN}"; /** * 模板消息中 跳转地址的对应的key */ String MSG_HREF_URL = "url"; /** * sys_data_log表的类型 用于区别评论区域的日志数据 */ String DATA_LOG_TYPE_COMMENT = "comment"; /** * sys_data_log表的类型 老的数据比较 类型都设置为json */ String DATA_LOG_TYPE_JSON = "json"; /** 消息模板:markdown */ String MSG_TEMPLATE_TYPE_MD = "5"; /**========【消息推送相关】==========================================================================*/ /** * 短信验证码redis-key的前缀 */ String PHONE_REDIS_KEY_PRE = "phone_msg"; /** * 是文件夹 */ String IT_IS_FOLDER = "1"; /** * 文件拥有者 */ String FILE_OWNER = "owner"; /** * 文件管理员 */ String FILE_ADMIN = "admin"; /** * 只允许编辑 */ String FILE_EDITABLE = "editable"; /** * 登录失败,用于记录失败次数的key */ String LOGIN_FAIL = "LOGIN_FAIL_"; /** * 入职事件 */ Integer BPM_USER_EVENT_ADD = 1; /** * 离职事件 */ Integer BPM_USER_EVENT_LEVEL = 2; /** * 用户租户状态(正常/已通过审核的) */ String USER_TENANT_NORMAL = "1"; /** * 用户租户状态(离职) */ String USER_TENANT_QUIT = "2"; /** * 用户租户状态(审核中) */ String USER_TENANT_UNDER_REVIEW = "3"; /** * 用户租户状态(拒绝) */ String USER_TENANT_REFUSE = "4"; /** * 用户租户状态(邀请) */ String USER_TENANT_INVITE = "5"; /** * 不是叶子节点 */ Integer NOT_LEAF = 0; /** * 是叶子节点 */ Integer IS_LEAF = 1; /** * 钉钉 */ String DINGTALK = "DINGTALK"; /** * 企业微信 */ String WECHAT_ENTERPRISE = "WECHAT_ENTERPRISE"; /** * 系统默认租户id 0 */ Integer TENANT_ID_DEFAULT_VALUE = 0; /** * 【low-app用】 应用级别的复制 */ String COPY_LEVEL_APP = "app"; /** * 【low-app用】 菜单级别的复制 */ String COPY_LEVEL_MENU = "menu"; /** * 【low-app用】 应用备份 */ String COPY_LEVEL_BAK = "backup"; /** * 【low-app用】 从备份还原 */ String COPY_LEVEL_COVER = "cover"; /** 【QQYUN-6034】关联字段变更历史值,缓存半个小时 */ String CACHE_REL_FIELD_OLD_VAL = "sys:cache:desform:relFieldOldVal:"; /** * 排序类型:升序 */ String ORDER_TYPE_ASC = "ASC"; /** * 排序类型:降序 */ String ORDER_TYPE_DESC = "DESC"; //update-begin---author:scott ---date:2023-09-10 for:积木报表常量---- /** * 报表允许设计开发的角色 */ public static String[] allowDevRoles = new String[]{"lowdeveloper", "admin"}; /** * 【对应积木报表的常量】 * 数据隔离模式: 按照创建人隔离 */ public static final String SAAS_MODE_CREATED = "created"; /** * 【对应积木报表的常量】 * 数据隔离模式: 按照租户隔离 */ public static final String SAAS_MODE_TENANT = "tenant"; //update-end---author:scott ---date::2023-09-10 for:积木报表常量---- }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/common/constant/CommonConstant.java
351
package com.sample; import android.app.Activity; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Environment; import master.flame.danmaku.danmaku.util.SystemClock; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; import android.text.style.BackgroundColorSpan; import android.text.style.ImageSpan; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.PopupWindow; import android.widget.VideoView; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import master.flame.danmaku.controller.IDanmakuView; import master.flame.danmaku.danmaku.loader.ILoader; import master.flame.danmaku.danmaku.loader.IllegalDataException; import master.flame.danmaku.danmaku.loader.android.DanmakuLoaderFactory; import master.flame.danmaku.danmaku.model.BaseDanmaku; import master.flame.danmaku.danmaku.model.DanmakuTimer; import master.flame.danmaku.danmaku.model.IDanmakus; import master.flame.danmaku.danmaku.model.IDisplayer; import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer; import master.flame.danmaku.danmaku.model.android.DanmakuContext; import master.flame.danmaku.danmaku.model.android.Danmakus; import master.flame.danmaku.danmaku.model.android.SpannedCacheStuffer; import master.flame.danmaku.danmaku.parser.BaseDanmakuParser; import master.flame.danmaku.danmaku.parser.IDataSource; import master.flame.danmaku.danmaku.util.IOUtils; public class MainActivity extends Activity implements View.OnClickListener { private IDanmakuView mDanmakuView; private View mMediaController; public PopupWindow mPopupWindow; private Button mBtnRotate; private Button mBtnHideDanmaku; private Button mBtnShowDanmaku; private BaseDanmakuParser mParser; private Button mBtnPauseDanmaku; private Button mBtnResumeDanmaku; private Button mBtnSendDanmaku; private Button mBtnSendDanmakuTextAndImage; private Button mBtnSendDanmakus; private DanmakuContext mContext; private BaseCacheStuffer.Proxy mCacheStufferAdapter = new BaseCacheStuffer.Proxy() { private Drawable mDrawable; @Override public void prepareDrawing(final BaseDanmaku danmaku, boolean fromWorkerThread) { if (danmaku.text instanceof Spanned) { // 根据你的条件检查是否需要需要更新弹幕 // FIXME 这里只是简单启个线程来加载远程url图片,请使用你自己的异步线程池,最好加上你的缓存池 new Thread() { @Override public void run() { String url = "http://www.bilibili.com/favicon.ico"; InputStream inputStream = null; Drawable drawable = mDrawable; if(drawable == null) { try { URLConnection urlConnection = new URL(url).openConnection(); inputStream = urlConnection.getInputStream(); drawable = BitmapDrawable.createFromStream(inputStream, "bitmap"); mDrawable = drawable; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); } } if (drawable != null) { drawable.setBounds(0, 0, 100, 100); SpannableStringBuilder spannable = createSpannable(drawable); danmaku.text = spannable; if(mDanmakuView != null) { mDanmakuView.invalidateDanmaku(danmaku, false); } return; } } }.start(); } } @Override public void releaseResource(BaseDanmaku danmaku) { // TODO 重要:清理含有ImageSpan的text中的一些占用内存的资源 例如drawable } }; /** * 绘制背景(自定义弹幕样式) */ private static class BackgroundCacheStuffer extends SpannedCacheStuffer { // 通过扩展SimpleTextCacheStuffer或SpannedCacheStuffer个性化你的弹幕样式 final Paint paint = new Paint(); @Override public void measure(BaseDanmaku danmaku, TextPaint paint, boolean fromWorkerThread) { danmaku.padding = 10; // 在背景绘制模式下增加padding super.measure(danmaku, paint, fromWorkerThread); } @Override public void drawBackground(BaseDanmaku danmaku, Canvas canvas, float left, float top) { paint.setColor(0x8125309b); canvas.drawRect(left + 2, top + 2, left + danmaku.paintWidth - 2, top + danmaku.paintHeight - 2, paint); } @Override public void drawStroke(BaseDanmaku danmaku, String lineText, Canvas canvas, float left, float top, Paint paint) { // 禁用描边绘制 } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViews(); } private BaseDanmakuParser createParser(InputStream stream) { if (stream == null) { return new BaseDanmakuParser() { @Override protected Danmakus parse() { return new Danmakus(); } }; } ILoader loader = DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI); try { loader.load(stream); } catch (IllegalDataException e) { e.printStackTrace(); } BaseDanmakuParser parser = new BiliDanmukuParser(); IDataSource<?> dataSource = loader.getDataSource(); parser.load(dataSource); return parser; } private void findViews() { mMediaController = findViewById(R.id.media_controller); mBtnRotate = (Button) findViewById(R.id.rotate); mBtnHideDanmaku = (Button) findViewById(R.id.btn_hide); mBtnShowDanmaku = (Button) findViewById(R.id.btn_show); mBtnPauseDanmaku = (Button) findViewById(R.id.btn_pause); mBtnResumeDanmaku = (Button) findViewById(R.id.btn_resume); mBtnSendDanmaku = (Button) findViewById(R.id.btn_send); mBtnSendDanmakuTextAndImage = (Button) findViewById(R.id.btn_send_image_text); mBtnSendDanmakus = (Button) findViewById(R.id.btn_send_danmakus); mBtnRotate.setOnClickListener(this); mBtnHideDanmaku.setOnClickListener(this); mMediaController.setOnClickListener(this); mBtnShowDanmaku.setOnClickListener(this); mBtnPauseDanmaku.setOnClickListener(this); mBtnResumeDanmaku.setOnClickListener(this); mBtnSendDanmaku.setOnClickListener(this); mBtnSendDanmakuTextAndImage.setOnClickListener(this); mBtnSendDanmakus.setOnClickListener(this); // VideoView VideoView mVideoView = (VideoView) findViewById(R.id.videoview); // DanmakuView // 设置最大显示行数 HashMap<Integer, Integer> maxLinesPair = new HashMap<Integer, Integer>(); maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL, 5); // 滚动弹幕最大显示5行 // 设置是否禁止重叠 HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<Integer, Boolean>(); overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_RL, true); overlappingEnablePair.put(BaseDanmaku.TYPE_FIX_TOP, true); mDanmakuView = (IDanmakuView) findViewById(R.id.sv_danmaku); mContext = DanmakuContext.create(); mContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN, 3).setDuplicateMergingEnabled(false).setScrollSpeedFactor(1.2f).setScaleTextSize(1.2f) .setCacheStuffer(new SpannedCacheStuffer(), mCacheStufferAdapter) // 图文混排使用SpannedCacheStuffer // .setCacheStuffer(new BackgroundCacheStuffer()) // 绘制背景使用BackgroundCacheStuffer .setMaximumLines(maxLinesPair) .preventOverlapping(overlappingEnablePair).setDanmakuMargin(40); if (mDanmakuView != null) { mParser = createParser(this.getResources().openRawResource(R.raw.comments)); mDanmakuView.setCallback(new master.flame.danmaku.controller.DrawHandler.Callback() { @Override public void updateTimer(DanmakuTimer timer) { } @Override public void drawingFinished() { } @Override public void danmakuShown(BaseDanmaku danmaku) { // Log.d("DFM", "danmakuShown(): text=" + danmaku.text); } @Override public void prepared() { mDanmakuView.start(); } }); mDanmakuView.setOnDanmakuClickListener(new IDanmakuView.OnDanmakuClickListener() { @Override public boolean onDanmakuClick(IDanmakus danmakus) { Log.d("DFM", "onDanmakuClick: danmakus size:" + danmakus.size()); BaseDanmaku latest = danmakus.last(); if (null != latest) { Log.d("DFM", "onDanmakuClick: text of latest danmaku:" + latest.text); return true; } return false; } @Override public boolean onDanmakuLongClick(IDanmakus danmakus) { return false; } @Override public boolean onViewClick(IDanmakuView view) { mMediaController.setVisibility(View.VISIBLE); return false; } }); mDanmakuView.prepare(mParser, mContext); mDanmakuView.showFPS(true); mDanmakuView.enableDanmakuDrawingCache(true); } if (mVideoView != null) { mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); } }); mVideoView.setVideoPath(Environment.getExternalStorageDirectory() + "/1.flv"); } } @Override protected void onPause() { super.onPause(); if (mDanmakuView != null && mDanmakuView.isPrepared()) { mDanmakuView.pause(); } } @Override protected void onResume() { super.onResume(); if (mDanmakuView != null && mDanmakuView.isPrepared() && mDanmakuView.isPaused()) { mDanmakuView.resume(); } } @Override protected void onDestroy() { super.onDestroy(); if (mDanmakuView != null) { // dont forget release! mDanmakuView.release(); mDanmakuView = null; } } @Override public void onBackPressed() { super.onBackPressed(); if (mDanmakuView != null) { // dont forget release! mDanmakuView.release(); mDanmakuView = null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { if (v == mMediaController) { mMediaController.setVisibility(View.GONE); } if (mDanmakuView == null || !mDanmakuView.isPrepared()) return; if (v == mBtnRotate) { setRequestedOrientation(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else if (v == mBtnHideDanmaku) { mDanmakuView.hide(); // mPausedPosition = mDanmakuView.hideAndPauseDrawTask(); } else if (v == mBtnShowDanmaku) { mDanmakuView.show(); // mDanmakuView.showAndResumeDrawTask(mPausedPosition); // sync to the video time in your practice } else if (v == mBtnPauseDanmaku) { mDanmakuView.pause(); } else if (v == mBtnResumeDanmaku) { mDanmakuView.resume(); } else if (v == mBtnSendDanmaku) { addDanmaku(false); } else if (v == mBtnSendDanmakuTextAndImage) { addDanmaKuShowTextAndImage(false); } else if (v == mBtnSendDanmakus) { Boolean b = (Boolean) mBtnSendDanmakus.getTag(); timer.cancel(); if (b == null || !b) { mBtnSendDanmakus.setText(R.string.cancel_sending_danmakus); timer = new Timer(); timer.schedule(new AsyncAddTask(), 0, 1000); mBtnSendDanmakus.setTag(true); } else { mBtnSendDanmakus.setText(R.string.send_danmakus); mBtnSendDanmakus.setTag(false); } } } Timer timer = new Timer(); class AsyncAddTask extends TimerTask { @Override public void run() { for (int i = 0; i < 20; i++) { addDanmaku(true); SystemClock.sleep(20); } } }; private void addDanmaku(boolean islive) { BaseDanmaku danmaku = mContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL); if (danmaku == null || mDanmakuView == null) { return; } // for(int i=0;i<100;i++){ // } danmaku.text = "这是一条弹幕" + System.nanoTime(); danmaku.padding = 5; danmaku.priority = 0; // 可能会被各种过滤器过滤并隐藏显示 danmaku.isLive = islive; danmaku.setTime(mDanmakuView.getCurrentTime() + 1200); danmaku.textSize = 25f * (mParser.getDisplayer().getDensity() - 0.6f); danmaku.textColor = Color.RED; danmaku.textShadowColor = Color.WHITE; // danmaku.underlineColor = Color.GREEN; danmaku.borderColor = Color.GREEN; mDanmakuView.addDanmaku(danmaku); } private void addDanmaKuShowTextAndImage(boolean islive) { BaseDanmaku danmaku = mContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL); Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher); drawable.setBounds(0, 0, 100, 100); SpannableStringBuilder spannable = createSpannable(drawable); danmaku.text = spannable; danmaku.padding = 5; danmaku.priority = 1; // 一定会显示, 一般用于本机发送的弹幕 danmaku.isLive = islive; danmaku.setTime(mDanmakuView.getCurrentTime() + 1200); danmaku.textSize = 25f * (mParser.getDisplayer().getDensity() - 0.6f); danmaku.textColor = Color.RED; danmaku.textShadowColor = 0; // 重要:如果有图文混排,最好不要设置描边(设textShadowColor=0),否则会进行两次复杂的绘制导致运行效率降低 danmaku.underlineColor = Color.GREEN; mDanmakuView.addDanmaku(danmaku); } private SpannableStringBuilder createSpannable(Drawable drawable) { String text = "bitmap"; SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text); ImageSpan span = new ImageSpan(drawable);//ImageSpan.ALIGN_BOTTOM); spannableStringBuilder.setSpan(span, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); spannableStringBuilder.append("图文混排"); spannableStringBuilder.setSpan(new BackgroundColorSpan(Color.parseColor("#8A2233B1")), 0, spannableStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); return spannableStringBuilder; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { mDanmakuView.getConfig().setDanmakuMargin(20); } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { mDanmakuView.getConfig().setDanmakuMargin(40); } } }
bilibili/DanmakuFlameMaster
Sample/src/main/java/com/sample/MainActivity.java
353
package org.nutz.dao; import java.sql.ResultSet; import java.util.List; import java.util.Map; import org.nutz.dao.entity.Entity; import org.nutz.dao.entity.Record; import org.nutz.dao.impl.EntityHolder; import org.nutz.dao.jdbc.JdbcExpert; import org.nutz.dao.pager.Pager; import org.nutz.dao.sql.PojoMaker; import org.nutz.dao.sql.Sql; import org.nutz.lang.Configurable; import org.nutz.lang.Each; /** * Nutz.Dao 核心接口。 封装了所有的数据库操作 * * @author zozoh([email protected]) */ public interface Dao extends Configurable { /** * @return 数据源的元数据 */ DatabaseMeta meta(); /** * @return 一个 Sql 管理接口,你可以通过这个接口管理你自定义的 SQL * * @see org.nutz.dao.SqlManager */ SqlManager sqls(); PojoMaker pojoMaker(); /** * 执行一组 Sql,这些 Sql 将会一起被提交 * * @param sqls * 要被执行的 Sql 数组 */ void execute(Sql... sqls); /** * 这个方法试图给你最大的灵活性,因为你的 ConnCallback 实现类将得到一个 Connection 接口 * 的实例。请注意,你不需要关闭这个连接,这个函数在退出时会替你关闭连接。 * <p> * 如果你从当前连接对象中创建了ResultSet对象或者 Statement对象,请自行关闭。Nutz.Dao 的原则是: * <ul> * <li>Nutz.Dao 创建维护的东西 Nutz.Dao 来维护其生命周期 * <li>你创建的东西 (比如 ResultSet) 你来维护其生命周期 * </ul> * * @param callback */ void run(ConnCallback callback); /** * 从一个 ResultSet 中获取一个对象。 * <p> * 因为 Dao 接口可以知道一个 POJO 的映射细节,这个函数可以帮你节省一点体力。 * * @param classOfT * 对象类型 * @param rs * 结果集 * @param fm * 字段过滤器 * @return 对象 */ <T> T getObject(Class<T> classOfT, ResultSet rs, FieldMatcher fm); <T> T getObject(Class<T> classOfT, ResultSet rs, FieldMatcher fm, String prefix); /** * 将一个对象插入到一个数据源。 * <p> * 声明了 '@Id'的字段会在插入数据库时被忽略,因为数据库会自动为其设值。如果想手动设置,请设置 '@Id(auto=false)' * <p> * <b>插入之前</b>,会检查声明了 '@Default(@SQL("SELECT ..."))' 的字段,预先执行 SQL 为字段设置。 * <p> * <b>插入之后</b>,会检查声明了 '@Next(@SQL("SELECT ..."))' 的字段,通过执行 SQL 将值取回 * <p> * 如果你的字段仅仅声明了 '@Id(auto=true)',没有声明 '@Next',则认为你还是想取回插入后最新的 ID 值,因为 * 自动为你添加类似 @Next(@SQL("SELECT MAX(id) FROM tableName")) 的设置 * * * * @param obj * 要被插入的对象 * <p> * 它可以是: * <ul> * <li>普通 POJO * <li>集合 * <li>数组 * <li>Map * </ul> * <b style=color:red>注意:</b> 如果是集合,数组或者 Map,所有的对象必须类型相同,否则可能会出错 * * @return 插入后的对象 * * @see org.nutz.dao.entity.annotation.Id * @see org.nutz.dao.entity.annotation.Default * @see org.nutz.dao.entity.annotation.Next */ <T> T insert(T obj); <T> T insert(Entity<T> entity, T obj); /** * 将一个对象按FieldFilter过滤后,插入到一个数据源。 * <p/> * <code>dao.insert(pet, FieldFilter.create(Pet.class, FieldMatcher.create(false)));</code> * * @param obj * 要被插入的对象 * @param filter * 字段过滤器, 其中FieldMatcher.isIgnoreId生效 * @return 插入后的对象 * @see org.nutz.dao.Dao#insert(Object) */ <T> T insert(T obj, FieldFilter filter); <T> T insert(T obj, String actived); /** * 自由的向一个数据表插入一条数据。数据用名值链描述 * * @param tableName * 数据表名 * @param chain * 数据名值链 */ void insert(String tableName, Chain chain); /** * 与 insert(String tableName, Chain chain) 一样,不过,数据表名,将取自 POJO 的数据表声明,请参看 * '@Table' 注解的详细说明 * * @param classOfT * 实体类型 * @param chain * 数据名值链 * * @see org.nutz.dao.entity.annotation.Table */ void insert(Class<?> classOfT, Chain chain); void insert(Entity<?> entity, Chain chain); /** * 快速插入一个对象。 对象的 '@Prev' 以及 '@Next' 在这个函数里不起作用。 * <p> * 即,你必须为其设置好值,它会统一采用 batch 的方法插入 * * @param obj * 要被插入的对象 * <p> * 它可以是: * <ul> * <li>普通 POJO * <li>集合 * <li>数组 * <li>Map * </ul> * <b style=color:red>注意:</b> 如果是集合,数组或者 Map,所有的对象必须类型相同,否则可能会出错 * */ <T> T fastInsert(T obj); <T> T fastInsert(T obj, boolean detectAllColumns); void fastInsert(Entity<?> entity, Object obj); /** * 将对象插入数据库同时,也将符合一个正则表达式的所有关联字段关联的对象统统插入相应的数据库 * <p> * 关于关联字段更多信息,请参看 '@One' | '@Many' | '@ManyMany' 更多的描述 * * @param obj * 数据对象 * @param regex * 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被插入 * @return 数据对象本身 * * @see org.nutz.dao.entity.annotation.One * @see org.nutz.dao.entity.annotation.Many * @see org.nutz.dao.entity.annotation.ManyMany */ <T> T insertWith(T obj, String regex); /** * 根据一个正则表达式,仅将对象所有的关联字段插入到数据库中,并不包括对象本身 * * @param obj * 数据对象 * @param regex * 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被插入 * @return 数据对象本身 * * @see org.nutz.dao.entity.annotation.One * @see org.nutz.dao.entity.annotation.Many * @see org.nutz.dao.entity.annotation.ManyMany */ <T> T insertLinks(T obj, String regex); /** * 将对象的一个或者多个,多对多的关联信息,插入数据表 * * @param obj * 对象 * @param regex * 正则表达式,描述了那种多对多关联字段将被执行该操作 * * @return 对象自身 * * @see org.nutz.dao.entity.annotation.ManyMany */ <T> T insertRelation(T obj, String regex); /** * 更新一个对象。对象必须有 '@Id' 或者 '@Name' 或者 '@PK' 声明。 * <p> * 并且调用这个函数前, 主键的值必须保证是有效,否则会更新失败 * <p> * 这个对象所有的字段都会被更新,即,所有的没有被设值的字段,都会被置成 NULL,如果遇到 NOT NULL 约束,则会引发异常。 * 如果想有选择的更新个别字段,请使用 org.nutz.dao.FieldFilter * <p> * 如果仅仅想忽略所有的 null 字段,请使用 updateIgnoreNull 方法更新对象 * * @param obj * 要被更新的对象 * <p> * 它可以是: * <ul> * <li>普通 POJO * <li>集合 * <li>数组 * <li>Map * </ul> * <b style=color:red>注意:</b> 如果是集合,数组或者 Map,所有的对象必须类型相同,否则可能会出错 * * @return 返回实际被更新的记录条数,一般的情况下,如果更新成功,返回 1,否则,返回 0 * * @see org.nutz.dao.FieldFilter */ int update(Object obj); /** * 更新对象一部分字段 * * @param obj * 对象 * @param actived * 正则表达式描述要被更新的字段 * @return 返回实际被更新的记录条数,一般的情况下,如果更新成功,返回 1,否则,返回 0 */ int update(Object obj, String actived); /** * 更新对象一部分字段 * * @param obj * 对象 * @param actived * 正则表达式描述要被更新的字段 * @return 返回实际被更新的记录条数,一般的情况下,如果更新成功,返回 1,否则,返回 0 */ int update(Object obj, String actived, String locked, boolean ignoreNull); int update(Object obj, FieldFilter fieldFilter); int update(Object obj, FieldFilter fieldFilter, Condition cnd); int update(Object obj, Condition cnd); int update(Entity<?> entity, Object obj); int update(Entity<?> entity, Object obj, String actived); int update(Entity<?> entity, Object obj, String actived, String locked, boolean ignoreNull); int update(Entity<?> entity, Object obj, FieldFilter fieldFilter); int update(Entity<?> entity, Object obj, FieldFilter fieldFilter, Condition cnd); int update(Entity<?> entity, Object obj, Condition cnd); int update(Entity<?> entity, Chain chain, Condition cnd); /** * 更新一个对象,并且忽略所有 null 字段。 * <p> * 注意: 基本数据类型都是不可能为null的,这些字段肯定会更新 * * @param obj * 要被更新的对象 * <p> * 它可以是: * <ul> * <li>普通 POJO * <li>集合 * <li>数组 * <li>Map * </ul> * <b style=color:red>注意:</b> 如果是集合,数组或者 Map,所有的对象必须类型相同,否则可能会出错 * * @return 返回实际被更新的记录条数,一般的情况下,如果是单一Pojo,更新成功,返回 1,否则,返回 0 */ int updateIgnoreNull(Object obj); /** * 自由的更新多条数据 * * @param tableName * 数据表名 * @param chain * 数据名值链。 * @param cnd * WHERE 条件 * * @return 有多少条记录被更新了 */ int update(String tableName, Chain chain, Condition cnd); /** * 与 update(String tableName, Chain chain, Condition cnd) 一样,不过,数据表名,将取自 * POJO 的数据表声明,请参看 '@Table' 注解的详细说明 * * @param classOfT * 实体类型 * @param chain * 数据名值链 * @param cnd * WHERE 条件 * * @return 有多少条记录被更新了 * * @see org.nutz.dao.entity.annotation.Table */ int update(Class<?> classOfT, Chain chain, Condition cnd); /** * 将对象更新的同时,也将符合一个正则表达式的所有关联字段关联的对象统统更新 * <p> * 关于关联字段更多信息,请参看 '@One' | '@Many' | '@ManyMany' 更多的描述 * * @param obj * 数据对象 * @param regex * 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被更新 * @return 数据对象本身 * * @see org.nutz.dao.entity.annotation.One * @see org.nutz.dao.entity.annotation.Many * @see org.nutz.dao.entity.annotation.ManyMany */ <T> T updateWith(T obj, String regex); /** * 根据一个正则表达式,仅更新对象所有的关联字段,并不包括对象本身 * * @param obj * 数据对象 * @param regex * 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被更新 * @return 数据对象本身 * * @see org.nutz.dao.entity.annotation.One * @see org.nutz.dao.entity.annotation.Many * @see org.nutz.dao.entity.annotation.ManyMany */ <T> T updateLinks(T obj, String regex); /** * 多对多关联是通过一个中间表将两条数据表记录关联起来。 * <p> * 而这个中间表可能还有其他的字段,比如描述关联的权重等 * <p> * 这个操作可以让你一次更新某一个对象中多个多对多关联的数据 * * @param classOfT * 对象类型 * @param regex * 正则表达式,描述了那种多对多关联字段将被执行该操作 * @param chain * 针对中间关联表的名值链。 * @param cnd * 针对中间关联表的 WHERE 条件 * * @return 共有多少条数据被更新 * * @see org.nutz.dao.entity.annotation.ManyMany */ int updateRelation(Class<?> classOfT, String regex, Chain chain, Condition cnd); <T> List<T> query(Class<T> classOfT, Condition cnd, Pager pager, FieldMatcher matcher); <T> List<T> query(Class<T> classOfT, Condition cnd, Pager pager, String regex); /** * 查询一组对象。你可以为这次查询设定条件,并且只获取一部分对象(翻页) * * @param classOfT * 对象类型 * @param cnd * WHERE 条件。如果为 null,将获取全部数据,顺序为数据库原生顺序 * @param pager * 翻页信息。如果为 null,则一次全部返回. 不会使用cnd中的pager!!! * @return 对象列表 */ <T> List<T> query(Class<T> classOfT, Condition cnd, Pager pager); <T> List<T> query(Entity<T> entity, Condition cnd, Pager pager); /** * 查询一组对象。你可以为这次查询设定条件 * * @param classOfT * 对象类型 * @param cnd * WHERE 条件。如果为 null,将获取全部数据,顺序为数据库原生顺序<br> * 只有在调用这个函数的时候, cnd.limit 才会生效 * @return 对象列表 */ <T> List<T> query(Class<T> classOfT, Condition cnd); /** * 查询出一组记录。 * * @param tableName * 表名 - 格式为 <b>tableName[:idName]</b> 比如 : <b>t_pet</b> 或者 * <b>t_pet:id</b> 尤其在 SqlServer2005 的环境下,需要用 t_pet:id 的形式来指明 ID * 字段,否则 不能分页 * @param cnd * 条件 - <b style=color:red>请注意:</b> 你传入的 Criteria 实现必须考虑到 没有 * 'Entity<?>' 传入。即 toSql 函数的参数永远为 null。 * @param pager * 翻页信息 * @return Record 对象。实际上是一个 Map 的包裹类 * * @see org.nutz.dao.Condition */ List<Record> query(String tableName, Condition cnd, Pager pager); /** * 查询出一组记录。 * * @param tableName * 表名 - 格式为 <b>tableName[:idName]</b> 比如 : <b>t_pet</b> 或者 * <b>t_pet:id</b> 尤其在 SqlServer2005 的环境下,需要用 t_pet:id 的形式来指明 ID * 字段,否则 不能分页 * @param cnd * 条件 - <b style=color:red>请注意:</b> 你传入的 Criteria 实现必须考虑到 没有 * 'Entity<?>' 传入。即 toSql 函数的参数永远为 null。 * @param pager * 翻页信息 * @param fields * 需要查询的列, 将直接拼入SQL中.由于不会提前探知表结构,所以这fields并非正则表达式,务必留意. * @return 数据库记录 */ List<Record> query(String tableName, Condition cnd, Pager pager, String fields); /** * 查询出一组记录。 * * @param tableName * 表名 - 格式为 <b>tableName[:idName]</b> 比如 : <b>t_pet</b> 或者 * <b>t_pet:id</b> 尤其在 SqlServer2005 的环境下,需要用 t_pet:id 的形式来指明 ID * 字段,否则 不能分页 * @param cnd * 条件 - <b style=color:red>请注意:</b> 你传入的 Criteria 实现必须考虑到 没有 * 'Entity<?>' 传入。即 toSql 函数的参数永远为 null。 * @return Record 对象。实际上是一个 Map 的包裹类 * * @see org.nutz.dao.Condition */ List<Record> query(String tableName, Condition cnd); /** * 对一组对象进行迭代,这个接口函数非常适用于很大的数据量的集合,因为你不可能把他们都读到内存里 * * @param classOfT * 对象类型 * @param cnd * WHERE 条件。如果为 null,将获取全部数据,顺序为数据库原生顺序 * @param pager * 翻页信息。如果为 null,则一次全部返回 * @param callback * 处理回调 * @return 一共迭代的数量 */ <T> int each(Class<T> classOfT, Condition cnd, Pager pager, Each<T> callback); <T> int each(Entity<T> entity, Condition cnd, Pager pager, Each<T> callback); /** * 对一组对象进行迭代,这个接口函数非常适用于很大的数据量的集合,因为你不可能把他们都读到内存里 * * @param classOfT * 对象类型 * @param cnd * WHERE 条件。如果为 null,将获取全部数据,顺序为数据库原生顺序 * @param callback * 处理回调 * @return 一共迭代的数量 */ <T> int each(Class<T> classOfT, Condition cnd, Each<T> callback); /** * 对一组对象进行迭代,这个接口函数非常适用于很大的数据量的集合,因为你不可能把他们都读到内存里 * * @param tableName * 表名 - 格式为 <b>tableName[:idName]</b> 比如 : <b>t_pet</b> 或者 * <b>t_pet:id</b> 尤其在 SqlServer2005 的环境下,需要用 t_pet:id 的形式来指明 ID * 字段,否则 不能分页 * @param cnd * WHERE 条件。如果为 null,将获取全部数据,顺序为数据库原生顺序 * @param pager * 翻页信息。如果为 null,则一次全部返回 * @param callback * 处理回调 * @return 一共迭代的数量 */ int each(String tableName, Condition cnd, Pager pager, Each<Record> callback); /** * 对一组对象进行迭代,这个接口函数非常适用于很大的数据量的集合,因为你不可能把他们都读到内存里 * * @param tableName * 表名 - 格式为 <b>tableName[:idName]</b> 比如 : <b>t_pet</b> 或者 * <b>t_pet:id</b> 尤其在 SqlServer2005 的环境下,需要用 t_pet:id 的形式来指明 ID * 字段,否则 不能分页 * @param cnd * WHERE 条件。如果为 null,将获取全部数据,顺序为数据库原生顺序 * @param callback * 处理回调 * @return 一共迭代的数量 */ int each(String tableName, Condition cnd, Each<Record> callback); /** * 对一组对象进行迭代,这个接口函数非常适用于很大的数据量的集合,因为你不可能把他们都读到内存里 * * @param tableName * 表名 - 格式为 <b>tableName[:idName]</b> 比如 : <b>t_pet</b> 或者 * <b>t_pet:id</b> 尤其在 SqlServer2005 的环境下,需要用 t_pet:id 的形式来指明 ID * 字段,否则 不能分页 * @param cnd * WHERE 条件。如果为 null,将获取全部数据,顺序为数据库原生顺序 * @param callback * 处理回调 * @param fields * 需要查询的列, 将直接拼入SQL中.由于不会提前探知表结构,所以这fields并非正则表达式,务必留意. * @return 一共迭代的数量 */ int each(String tableName, Condition cnd, Pager pager, Each<Record> callback, String fields); /** * 根据对象 ID 删除一个对象。它只会删除这个对象,关联对象不会被删除。 * <p> * 你的对象必须在某个字段声明了注解 '@Id',否则本操作会抛出一个运行时异常 * <p> * 如果你设定了外键约束,没有正确的清除关联对象会导致这个操作失败 * * * @param classOfT * 对象类型 * @param id * 对象 ID * * @return 影响的行数 * @see org.nutz.dao.entity.annotation.Id * */ int delete(Class<?> classOfT, long id); int delete(Entity<?> entity, long id); /** * 根据对象 Name 删除一个对象。它只会删除这个对象,关联对象不会被删除。 * <p> * 你的对象必须在某个字段声明了注解 '@Name',否则本操作会抛出一个运行时异常 * <p> * 如果你设定了外键约束,没有正确的清除关联对象会导致这个操作失败 * * @param classOfT * 对象类型 * @param name * 对象 Name * * @return 影响的行数 * @see org.nutz.dao.entity.annotation.Name */ int delete(Class<?> classOfT, String name); int delete(Entity<?> entity, String name); /** * 根据复合主键,删除一个对象。该对象必须声明 '@PK',并且,给定的参数顺序 必须同 '@PK' 中声明的顺序一致,否则会产生不可预知的错误。 * * @param classOfT * @param pks * 复合主键需要的参数,必须同 '@PK'中声明的顺序一致 */ <T> int deletex(Class<T> classOfT, Object... pks); /** * 自动判断如何删除一个对象。 * <p> * 如果声明了 '@Id' 则相当于 delete(Class<T>,long)<br> * 如果声明了 '@Name',则相当于 delete(Class<T>,String)<br> * 如果声明了 '@PK',则 deletex(Class<T>,Object ...)<br> * 如果没声明任何上面三个注解,则会抛出一个运行时异常 * * @param obj * 要被删除的对象 */ int delete(Object obj); /** * 将对象删除的同时,也将符合一个正则表达式的所有关联字段关联的对象统统删除 * <p> * <b style=color:red>注意:</b> * <p> * Java 对象的字段会被保留,这里的删除,将只会删除数据库中的记录 * <p> * 关于关联字段更多信息,请参看 '@One' | '@Many' | '@ManyMany' 更多的描述 * * @param obj * 数据对象 * @param regex * 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被删除 * * @return 被影响的记录行数 * * @see org.nutz.dao.entity.annotation.One * @see org.nutz.dao.entity.annotation.Many * @see org.nutz.dao.entity.annotation.ManyMany */ int deleteWith(Object obj, String regex); /** * 根据一个正则表达式,仅删除对象所有的关联字段,并不包括对象本身。 * <p> * <b style=color:red>注意:</b> * <p> * Java 对象的字段会被保留,这里的删除,将只会删除数据库中的记录 * <p> * 关于关联字段更多信息,请参看 '@One' | '@Many' | '@ManyMany' 更多的描述 * * @param obj * 数据对象 * @param regex * 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被删除 * * @return 被影响的记录行数 * * @see org.nutz.dao.entity.annotation.One * @see org.nutz.dao.entity.annotation.Many * @see org.nutz.dao.entity.annotation.ManyMany */ int deleteLinks(Object obj, String regex); /** * 根据对象 ID 获取一个对象。它只会获取这个对象,关联对象不会被获取。 * <p> * 你的对象必须在某个字段声明了注解 '@Id',否则本操作会抛出一个运行时异常 * * @param classOfT * 对象类型 * @param id * 对象 ID * * @see org.nutz.dao.entity.annotation.Id */ <T> T fetch(Class<T> classOfT, long id); <T> T fetch(Entity<T> entity, long id); /** * 根据对象 Name 获取一个对象。它只会获取这个对象,关联对象不会被获取。 * <p> * 你的对象必须在某个字段声明了注解 '@Name',否则本操作会抛出一个运行时异常 * * @param classOfT * 对象类型 * @param name * 对象 Name * @return 对象本身 * * @see org.nutz.dao.entity.annotation.Name */ <T> T fetch(Class<T> classOfT, String name); <T> T fetch(Entity<T> entity, String name); /** * 根据复合主键,获取一个对象。该对象必须声明 '@PK',并且,给定的参数顺序 必须同 '@PK' 中声明的顺序一致,否则会产生不可预知的错误。 * * @param classOfT * @param pks * 复合主键需要的参数,必须同 '@PK'中声明的顺序一致 */ <T> T fetchx(Class<T> classOfT, Object... pks); <T> T fetchx(Entity<T> entity, Object... pks); /** * 根据 WHERE 条件获取一个对象。如果有多个对象符合条件,将只获取 ResultSet 第一个记录 * * @param classOfT * 对象类型 * @param cnd * WHERE 条件 * @return 对象本身 * * @see org.nutz.dao.Condition * @see org.nutz.dao.entity.annotation.Name */ <T> T fetch(Class<T> classOfT, Condition cnd); <T> T fetch(Entity<T> entity, Condition cnd); /** * 根据条件获取一个 Record 对象 * * @param tableName * 表名 * @param cnd * 条件 * @return Record 对象 */ Record fetch(String tableName, Condition cnd); /** * * @param tableName * 表名 * @param cnd * 条件 * @param fields * 需要select的属性, 不可以是null!!! * @return Record 对象 */ Record fetch(String tableName, Condition cnd, String fields); /** * 随便获取一个对象。某些时候,你的数据表永远只有一条记录,这个操作就很适合你 * * @param classOfT * 对象类型 * @return 对象本身 */ <T> T fetch(Class<T> classOfT); /** * 根据一个参考对象自动判断如何获取一个对象。 * <p> * 如果声明了 '@Id' 则相当于 fetch(Class<T>,long)<br> * 如果声明了 '@Name',则相当于 fetch(Class<T>,String)<br> * 如果声明了 '@PK',则 fetchx(Class<T>,Object ...)<br> * 如果没声明任何上面三个注解,则会抛出一个运行时异常 * * @param obj * 参考对象 * * @return 对象本身 */ <T> T fetch(T obj); /** * 根据一个正则表达式,获取对象所有的关联字段 * * @param obj * 数据对象,不可以是Class啊!!!传对象或集合啊!!! * @param regex * 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被查询 * @return 更新后的数据对象本身 * * @see org.nutz.dao.entity.annotation.One * @see org.nutz.dao.entity.annotation.Many * @see org.nutz.dao.entity.annotation.ManyMany */ <T> T fetchLinks(T obj, String regex); /** * 根据一个正则表达式,获取对象所有的关联字段, 并按Condition进行数据过滤排序 * <p/> * <b>严重提醒,当使用Condition进行数据过滤排序时,应当使regex只匹配特定的映射字段</b> * * @param obj * 数据对象,可以是普通对象或集合,但不是类 * @param regex * 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被查询 * @param cnd * 关联字段的过滤(排序,条件语句,分页等) * @return 传入的数据对象 */ <T> T fetchLinks(T obj, String regex, Condition cnd); /** * 根据一个 WHERE 条件,清除一组对象。只包括对象本身,不包括关联字段 * * @param classOfT * 对象类型 * @param cnd * 查询条件,如果为 null,则全部清除 * @return 影响的行数 */ int clear(Class<?> classOfT, Condition cnd); int clear(Entity<?> entity, Condition cnd); /** * 根据一个 WHERE 条件,清除一组记录 * * @param tableName * @param cnd * @return 影响的行数 */ int clear(String tableName, Condition cnd); /** * 清除对象所有的记录 * * @param classOfT * 对象类型 * @return 影响的行数 */ int clear(Class<?> classOfT); /** * 清除数据表所有记录 * * @param tableName * 表名 * @return 影响的行数 */ int clear(String tableName); /** * <pre> * It will delete @One @Many entity records * clear the @ManyMany relations * </pre> * * @param obj * @param regex * @return */ /** * 根据正则表达式,清除对象的关联。 * <p> * 对于 '@One' 和 '@Many',对应的记录将会删除<br> * 而 '@ManyMay' 对应的字段,只会清除关联表中的记录 * * @param obj * 数据对象 * @param regex * 正则表达式,描述了什么样的关联字段将被关注。如果为 null,则表示全部的关联字段都会被清除 * @return 数据对象本身 */ <T> T clearLinks(T obj, String regex); /** * 获取实体描述, 其中包含了Java Pojo<-->数据库的全部映射信息 * * @param classOfT * 对象类型 * @return 实体描述 */ <T> Entity<T> getEntity(Class<T> classOfT); /** * 根据条件,计算某个对象在数据库中有多少条记录 * * @param classOfT * 对象类型 * @param cnd * WHERE 条件 * @return 数量 */ int count(Class<?> classOfT, Condition cnd); int count(Entity<?> entity, Condition cnd); /** * 计算某个对象在数据库中有多少条记录 * * @param classOfT * 对象类型 * @return 数量 */ int count(Class<?> classOfT); int count(Entity<?> entity); /** * 根据条件,计算某个数据表或视图中有多少条记录 * * @param tableName * 表名 * @param cnd * WHERE 条件 * @return 数量 */ int count(String tableName, Condition cnd); /** * 计算某个数据表或视图中有多少条记录 * * @param tableName * 表名 * @return 数量 */ int count(String tableName); /** * 获取某个对象,最大的 ID 值。这个对象必须声明了 '@Id' * * @param classOfT * @return 最大 ID 值 */ int getMaxId(Class<?> classOfT); /** * 对某一个对象字段,进行计算。 * * @param classOfT * 对象类型 * @param funcName * 计算函数名,请确保你的数据库是支持这个函数的 * @param fieldName * 对象 java 字段名 * @return 计算结果 */ int func(Class<?> classOfT, String funcName, String fieldName); /** * 对某一个对象字段,进行计算。 * * @param classOfT * 对象类型 * @param funcName * 计算函数名,请确保你的数据库是支持这个函数的 * @param fieldName * 对象 java 字段名 * @return 计算结果 */ Object func2(Class<?> classOfT, String funcName, String fieldName); /** * 对某一个数据表字段,进行计算。 * * @param tableName * 表名 * @param funcName * 计算函数名,请确保你的数据是支持库这个函数的 * @param colName * 数据库字段名 * @return 计算结果 */ int func(String tableName, String funcName, String colName); /** * 对某一个数据表字段,进行计算。 * * @param tableName * 表名 * @param funcName * 计算函数名,请确保你的数据是支持库这个函数的 * @param colName * 数据库字段名 * @return 计算结果 */ Object func2(String tableName, String funcName, String colName); /** * 对某一个对象字段,进行计算。 * * @param classOfT * 对象类型 * @param funcName * 计算函数名,请确保你的数据库是支持这个函数的 * @param fieldName * 对象 java 字段名 * @param cnd * 过滤条件 * @return 计算结果 */ int func(Class<?> classOfT, String funcName, String fieldName, Condition cnd); /** * 对某一个对象字段,进行计算。 * * @param classOfT * 对象类型 * @param funcName * 计算函数名,请确保你的数据库是支持这个函数的 * @param fieldName * 对象 java 字段名 * @param cnd * 过滤条件 * @return 计算结果 */ Object func2(Class<?> classOfT, String funcName, String fieldName, Condition cnd); /** * 对某一个数据表字段,进行计算。 * * @param tableName * 表名 * @param funcName * 计算函数名,请确保你的数据库是支持这个函数的 * @param colName * 数据库字段名 * @param cnd * 过滤条件 * @return 计算结果 */ int func(String tableName, String funcName, String colName, Condition cnd); /** * 对某一个数据表字段,进行计算。 * * @param tableName * 表名 * @param funcName * 计算函数名,请确保你的数据库是支持这个函数的 * @param colName * 数据库字段名 * @param cnd * 过滤条件 * @return 计算结果 */ Object func2(String tableName, String funcName, String colName, Condition cnd); /** * 根据数据源的类型,创建一个翻页对象 * * @param pageNumber * 第几页 ,从 1 开始。 * @param pageSize * 每页可以有多少条记录 * @return 翻页对象 */ Pager createPager(int pageNumber, int pageSize); /** * @param classOfT * 对象类型 * @return 该类型对象是否在数据库中存在数据表 */ boolean exists(Class<?> classOfT); boolean exists(Entity<?> entity); /** * @param tableName * 表名 * @return 数据库中是否存在这张数据表 */ boolean exists(String tableName); /** * 根据一个实体的配置信息为其创建一张表 * * @param classOfT * 实体类型 * @param dropIfExists * 如果表存在是否强制移除 * @return 实体对象 */ <T> Entity<T> create(Class<T> classOfT, boolean dropIfExists); /** * 根据一个实体的配置信息为其创建一张表 * * @param en * 实体类型,抽象后的 * @param dropIfExists * 如果表存在是否强制移除 * @return 实体对象 */ <T> Entity<T> create(Entity<T> en, boolean dropIfExists); /** * 根据一个实体的配置信息为其创建一张表 * * @param tableName * 表名 * @param map * 实体描述,参考文档中的非Pojo操作 * @param dropIfExists * 如果表存在是否强制移除 * @return 实体对象 */ <T extends Map<String, ?>> Entity<T> create(String tableName, T map, boolean dropIfExists); /** * 根据一个实体的配置信息为其创建一张表, 其中表名从map.get(".table")获取 * * @param map * 实体描述,参考文档中的非Pojo操作 * @param dropIfExists * 如果表存在是否强制移除 * @return 实体对象 */ <T extends Map<String, ?>> Entity<T> create(T map, boolean dropIfExists); /** * 如果一个实体的数据表存在,移除它 * * @param classOfT * 实体类型 * @return 是否移除成功 */ boolean drop(Class<?> classOfT); /** * 如果一个数据表存在,移除它 * * @param tableName * 表名 * @return 是否移除成功 */ boolean drop(String tableName); /** * 执行单条自定义SQL * * @param sql * 自定义SQL对象 * @return 传入的SQL对象,方便链式调用 */ Sql execute(Sql sql); /** * 设置数据库方言. * * @param obj * 可以是类名,JdbcExpert实例,或者数据库名称 * @throws Exception * 类名不合法/不存在的时抛出异常 */ void setExpert(Object obj) throws Exception; /** * 获取数据库方言的实现实例 * * @return 数据库方言的实现实例 */ JdbcExpert getJdbcExpert(); /** * 以特殊规则执行insert * * @param t * 实例对象 * @param ignoreNull * 忽略空值 * @param ignoreZero * 忽略0值 * @param ignoreBlankStr * 忽略空白字符串 * @return 传入的实例变量 */ <T> T insert(T t, boolean ignoreNull, boolean ignoreZero, boolean ignoreBlankStr); /** * 根据对象的主键(@Id/@Name/@Pk)先查询, 如果存在就更新, 不存在就插入 * * @param t * 对象 * @return 原对象 */ <T> T insertOrUpdate(T t); /** * 根据对象的主键(@Id/@Name/@Pk)先查询, 如果存在就更新, 不存在就插入 * * @param t * 对象 * @param insertFieldFilter * 插入时的字段过滤, 可以是null * @param updateFieldFilter * 更新时的字段过滤,可以是null * @return 原对象 */ <T> T insertOrUpdate(T t, FieldFilter insertFieldFilter, FieldFilter updateFieldFilter); /** * 乐观锁, 以特定字段的值作为限制条件,更新对象,并自增该字段. * <p/> * 执行的sql如下: * <p/> * <code>update t_user set age=30, city="广州", version=version+1 where name="wendal" and version=124;</code> * * @param obj * 需要更新的对象, 必须带@Id/@Name/@Pk中的其中一种. * @param fieldFilter * 需要过滤的属性. 若设置了哪些字段不更新,那务必确保过滤掉fieldName的字段 * @param fieldName * 参考字段的Java属性名.默认是"version",可以是任意数值字段 * @return 若更新成功,返回值大于0, 否则小于等于0 */ int updateAndIncrIfMatch(Object obj, FieldFilter fieldFilter, String fieldName); int updateAndIncrIfMatch(Entity<?> entity, Object obj, FieldFilter fieldFilter, String fieldName); /** * 基于版本的更新,版本不一样无法更新到数据 * * @param obj * 需要更新的对象, 必须有version属性 * @return 若更新成功,大于0, 否则小于0 */ int updateWithVersion(Object obj); /** * 基于版本的更新,版本不一样无法更新到数据 * * @param obj * 需要更新的对象, 必须有version属性 * @param fieldFilter * 需要过滤的字段设置 * @return 若更新成功,大于0, 否则小于0 */ int updateWithVersion(Object obj, FieldFilter fieldFilter); /** * 根据查询条件获取一个对象.<b>注意: 条件语句需要加上表名!!!</b> * <p/> * 这个方法是让@One关联的属性,通过left join一次性取出. 与fetch+fetchLinks是等价的 * * @param classOfT * 实体类 * @param regex * 需要过滤的关联属性,可以是null,取出全部关联属性. * @param cnd * 查询条件,必须带表名!!! * @return 实体对象,符合regex的关联属性也会取出 */ <T> T fetchByJoin(Class<T> classOfT, String regex, Condition cnd); /** * 根据对象 ID 获取一个对象。它只会获取这个对象,关联对象不会被获取。 * <p> * 你的对象必须在某个字段声明了注解 '@Id',否则本操作会抛出一个运行时异常 * <p/> * 这个方法是让@One关联的属性,通过left join一次性取出. 与fetch+fetchLinks是等价的 * * @param classOfT * 实体类 * @param regex * 需要取出的关联属性,是正则表达式哦,匹配的是Java属性名 * @param id * 对象id * @return 实体 */ <T> T fetchByJoin(Class<T> classOfT, String regex, long id); /** * 根据对象 NAME 获取一个对象。它只会获取这个对象,关联对象不会被获取。 * <p> * 你的对象必须在某个字段声明了注解 '@Name',否则本操作会抛出一个运行时异常 * <p/> * 这个方法是让@One关联的属性,通过left join一次性取出. 与fetch+fetchLinks是等价的 * * @param classOfT * 实体类 * @param regex * 需要取出的关联属性,是正则表达式哦,匹配的是Java属性名 * @param name * 对象name * @return 实体 */ <T> T fetchByJoin(Class<T> classOfT, String regex, String name); /** * 根据查询条件获取所有对象.<b>注意: 条件语句需要加上主表名或关联属性的JAVA属性名!!!</b> * <p/> * 这个方法是让@One关联的属性,通过left join一次性取出. 与query+fetchLinks是等价的 * * @param classOfT * 实体类 * @param regex * 需要过滤的关联属性,可以是null,取出全部关联属性. * @param cnd * 查询条件, 主表写表名, 子表写关联属性的JAVA属性名! * @return 实体对象的列表,符合regex的关联属性也会取出 */ <T> List<T> queryByJoin(Class<T> classOfT, String regex, Condition cnd); <T> T fetchByJoin(Class<T> classOfT, String regex, Condition cnd, Map<String, Condition> cnds); /** * 根据查询条件获取分页对象.<b>注意: 条件语句需要加上主表名或关联属性的JAVA属性名!!!</b> * <p/> * 这个方法是让@One关联的属性,通过left join一次性取出. 与query+fetchLinks是等价的 * * @param classOfT * 实体类 * @param regex * 需要过滤的关联属性,可以是null,取出全部关联属性. * @param cnd * 查询条件, 主表写表名, 子表写关联属性的JAVA属性名! * @param pager * 分页对象 <b>注意: 分页不要在cnd中传入!</b> * @return 实体对象的列表,符合regex的关联属性也会取出 */ <T> List<T> queryByJoin(Class<T> classOfT, String regex, Condition cnd, Pager pager); <T> List<T> queryByJoin(Class<T> classOfT, String regex, Condition cnd, Pager pager, Map<String, Condition> cnds); /** * 根据查询条件获取分页对象.<b>注意: 条件语句需要加上主表名或关联属性的JAVA属性名!!!</b> * * @param classOfT * 实体类 * @param regex * 需要过滤的关联属性,可以是null,取出全部关联属性. * @param cnd * 查询条件, 主表写表名, 子表写关联属性的JAVA属性名! * @return 数量 */ <T> int countByJoin(Class<T> classOfT, String regex, Condition cnd); EntityHolder getEntityHolder(); void truncate(Class<?> klass); void truncate(String tableName); }
nutzam/nutz
src/org/nutz/dao/Dao.java
354
package com.youth.banner; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.os.Build; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.annotation.ColorInt; import androidx.annotation.ColorRes; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.content.ContextCompat; import androidx.lifecycle.LifecycleOwner; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import androidx.viewpager2.widget.CompositePageTransformer; import androidx.viewpager2.widget.MarginPageTransformer; import androidx.viewpager2.widget.ViewPager2; import com.youth.banner.adapter.BannerAdapter; import com.youth.banner.config.BannerConfig; import com.youth.banner.config.IndicatorConfig; import com.youth.banner.indicator.Indicator; import com.youth.banner.listener.OnBannerListener; import com.youth.banner.listener.OnPageChangeListener; import com.youth.banner.transformer.MZScaleInTransformer; import com.youth.banner.transformer.ScaleInTransformer; import com.youth.banner.util.BannerLifecycleObserverAdapter; import com.youth.banner.util.BannerUtils; import com.youth.banner.util.BannerLifecycleObserver; import com.youth.banner.util.LogUtils; import com.youth.banner.util.ScrollSpeedManger; import java.lang.annotation.Retention; import java.lang.ref.WeakReference; import java.util.List; import static java.lang.annotation.RetentionPolicy.SOURCE; public class Banner<T, BA extends BannerAdapter<T, ? extends RecyclerView.ViewHolder>> extends FrameLayout implements BannerLifecycleObserver { public static final int INVALID_VALUE = -1; private ViewPager2 mViewPager2; private AutoLoopTask mLoopTask; private OnPageChangeListener mOnPageChangeListener; private BA mAdapter; private Indicator mIndicator; private CompositePageTransformer mCompositePageTransformer; private BannerOnPageChangeCallback mPageChangeCallback; // 是否允许无限轮播(即首尾直接切换) private boolean mIsInfiniteLoop = BannerConfig.IS_INFINITE_LOOP; // 是否自动轮播 private boolean mIsAutoLoop = BannerConfig.IS_AUTO_LOOP; // 轮播切换间隔时间 private long mLoopTime = BannerConfig.LOOP_TIME; // 轮播切换时间 private int mScrollTime = BannerConfig.SCROLL_TIME; // 轮播开始位置 private int mStartPosition = 1; // banner圆角半径,默认没有圆角 private float mBannerRadius = 0; // banner圆角方向,如果一个都不设置,默认四个角全部圆角 private boolean mRoundTopLeft, mRoundTopRight, mRoundBottomLeft, mRoundBottomRight; // 指示器相关配置 private int normalWidth = BannerConfig.INDICATOR_NORMAL_WIDTH; private int selectedWidth = BannerConfig.INDICATOR_SELECTED_WIDTH; private int normalColor = BannerConfig.INDICATOR_NORMAL_COLOR; private int selectedColor = BannerConfig.INDICATOR_SELECTED_COLOR; private int indicatorGravity = IndicatorConfig.Direction.CENTER; private int indicatorSpace; private int indicatorMargin; private int indicatorMarginLeft; private int indicatorMarginTop; private int indicatorMarginRight; private int indicatorMarginBottom; private int indicatorHeight = BannerConfig.INDICATOR_HEIGHT; private int indicatorRadius = BannerConfig.INDICATOR_RADIUS; public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; private int mOrientation = HORIZONTAL; // 滑动距离范围 private int mTouchSlop; // 记录触摸的位置(主要用于解决事件冲突问题) private float mStartX, mStartY; // 记录viewpager2是否被拖动 private boolean mIsViewPager2Drag; // 是否要拦截事件 private boolean isIntercept = true; //绘制圆角视图 private Paint mRoundPaint; private Paint mImagePaint; @Retention(SOURCE) @IntDef( {HORIZONTAL, VERTICAL}) public @interface Orientation { } public Banner(Context context) { this(context, null); } public Banner(Context context, AttributeSet attrs) { this(context, attrs, 0); } public Banner(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); initTypedArray(context, attrs); } private void init(Context context) { mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop() / 2; mCompositePageTransformer = new CompositePageTransformer(); mPageChangeCallback = new BannerOnPageChangeCallback(); mLoopTask = new AutoLoopTask(this); mViewPager2 = new ViewPager2(context); mViewPager2.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mViewPager2.setOffscreenPageLimit(2); mViewPager2.registerOnPageChangeCallback(mPageChangeCallback); mViewPager2.setPageTransformer(mCompositePageTransformer); ScrollSpeedManger.reflectLayoutManager(this); addView(mViewPager2); mRoundPaint = new Paint(); mRoundPaint.setColor(Color.WHITE); mRoundPaint.setAntiAlias(true); mRoundPaint.setStyle(Paint.Style.FILL); mRoundPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); mImagePaint = new Paint(); mImagePaint.setXfermode(null); } private void initTypedArray(Context context, AttributeSet attrs) { if (attrs != null) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Banner); mBannerRadius = a.getDimensionPixelSize(R.styleable.Banner_banner_radius, 0); mLoopTime = a.getInt(R.styleable.Banner_banner_loop_time, BannerConfig.LOOP_TIME); mIsAutoLoop = a.getBoolean(R.styleable.Banner_banner_auto_loop, BannerConfig.IS_AUTO_LOOP); mIsInfiniteLoop = a.getBoolean(R.styleable.Banner_banner_infinite_loop, BannerConfig.IS_INFINITE_LOOP); normalWidth = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_normal_width, BannerConfig.INDICATOR_NORMAL_WIDTH); selectedWidth = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_selected_width, BannerConfig.INDICATOR_SELECTED_WIDTH); normalColor = a.getColor(R.styleable.Banner_banner_indicator_normal_color, BannerConfig.INDICATOR_NORMAL_COLOR); selectedColor = a.getColor(R.styleable.Banner_banner_indicator_selected_color, BannerConfig.INDICATOR_SELECTED_COLOR); indicatorGravity = a.getInt(R.styleable.Banner_banner_indicator_gravity, IndicatorConfig.Direction.CENTER); indicatorSpace = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_space, 0); indicatorMargin = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_margin, 0); indicatorMarginLeft = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_marginLeft, 0); indicatorMarginTop = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_marginTop, 0); indicatorMarginRight = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_marginRight, 0); indicatorMarginBottom = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_marginBottom, 0); indicatorHeight = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_height, BannerConfig.INDICATOR_HEIGHT); indicatorRadius = a.getDimensionPixelSize(R.styleable.Banner_banner_indicator_radius, BannerConfig.INDICATOR_RADIUS); mOrientation = a.getInt(R.styleable.Banner_banner_orientation, HORIZONTAL); mRoundTopLeft = a.getBoolean(R.styleable.Banner_banner_round_top_left, false); mRoundTopRight = a.getBoolean(R.styleable.Banner_banner_round_top_right, false); mRoundBottomLeft = a.getBoolean(R.styleable.Banner_banner_round_bottom_left, false); mRoundBottomRight = a.getBoolean(R.styleable.Banner_banner_round_bottom_right, false); a.recycle(); } setOrientation(mOrientation); setInfiniteLoop(); } private void initIndicatorAttr() { if (indicatorMargin != 0) { setIndicatorMargins(new IndicatorConfig.Margins(indicatorMargin)); } else if (indicatorMarginLeft != 0 || indicatorMarginTop != 0 || indicatorMarginRight != 0 || indicatorMarginBottom != 0) { setIndicatorMargins(new IndicatorConfig.Margins( indicatorMarginLeft, indicatorMarginTop, indicatorMarginRight, indicatorMarginBottom)); } if (indicatorSpace > 0) { setIndicatorSpace(indicatorSpace); } if (indicatorGravity != IndicatorConfig.Direction.CENTER) { setIndicatorGravity(indicatorGravity); } if (normalWidth > 0) { setIndicatorNormalWidth(normalWidth); } if (selectedWidth > 0) { setIndicatorSelectedWidth(selectedWidth); } if (indicatorHeight > 0) { setIndicatorHeight(indicatorHeight); } if (indicatorRadius > 0) { setIndicatorRadius(indicatorRadius); } setIndicatorNormalColor(normalColor); setIndicatorSelectedColor(selectedColor); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (!getViewPager2().isUserInputEnabled()) { return super.dispatchTouchEvent(ev); } int action = ev.getActionMasked(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_OUTSIDE) { start(); } else if (action == MotionEvent.ACTION_DOWN) { stop(); } return super.dispatchTouchEvent(ev); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (!getViewPager2().isUserInputEnabled() || !isIntercept) { return super.onInterceptTouchEvent(event); } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mStartX = event.getX(); mStartY = event.getY(); getParent().requestDisallowInterceptTouchEvent(true); break; case MotionEvent.ACTION_MOVE: float endX = event.getX(); float endY = event.getY(); float distanceX = Math.abs(endX - mStartX); float distanceY = Math.abs(endY - mStartY); if (getViewPager2().getOrientation() == HORIZONTAL) { mIsViewPager2Drag = distanceX > mTouchSlop && distanceX > distanceY; } else { mIsViewPager2Drag = distanceY > mTouchSlop && distanceY > distanceX; } getParent().requestDisallowInterceptTouchEvent(mIsViewPager2Drag); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: getParent().requestDisallowInterceptTouchEvent(false); break; } return super.onInterceptTouchEvent(event); } @Override protected void dispatchDraw(Canvas canvas) { if (mBannerRadius > 0) { canvas.saveLayer(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), mImagePaint, Canvas.ALL_SAVE_FLAG); super.dispatchDraw(canvas); //绘制外圆环边框圆环 //默认四个角都设置 if (!mRoundTopRight && !mRoundTopLeft && !mRoundBottomRight && !mRoundBottomLeft) { drawTopLeft(canvas); drawTopRight(canvas); drawBottomLeft(canvas); drawBottomRight(canvas); canvas.restore(); return; } if (mRoundTopLeft) { drawTopLeft(canvas); } if (mRoundTopRight) { drawTopRight(canvas); } if (mRoundBottomLeft) { drawBottomLeft(canvas); } if (mRoundBottomRight) { drawBottomRight(canvas); } canvas.restore(); } else { super.dispatchDraw(canvas); } } private void drawTopLeft(Canvas canvas) { Path path = new Path(); path.moveTo(0, mBannerRadius); path.lineTo(0, 0); path.lineTo(mBannerRadius, 0); path.arcTo(new RectF(0, 0, mBannerRadius * 2, mBannerRadius * 2), -90, -90); path.close(); canvas.drawPath(path, mRoundPaint); } private void drawTopRight(Canvas canvas) { int width = getWidth(); Path path = new Path(); path.moveTo(width - mBannerRadius, 0); path.lineTo(width, 0); path.lineTo(width, mBannerRadius); path.arcTo(new RectF(width - 2 * mBannerRadius, 0, width, mBannerRadius * 2), 0, -90); path.close(); canvas.drawPath(path, mRoundPaint); } private void drawBottomLeft(Canvas canvas) { int height = getHeight(); Path path = new Path(); path.moveTo(0, height - mBannerRadius); path.lineTo(0, height); path.lineTo(mBannerRadius, height); path.arcTo(new RectF(0, height - 2 * mBannerRadius, mBannerRadius * 2, height), 90, 90); path.close(); canvas.drawPath(path, mRoundPaint); } private void drawBottomRight(Canvas canvas) { int height = getHeight(); int width = getWidth(); Path path = new Path(); path.moveTo(width - mBannerRadius, height); path.lineTo(width, height); path.lineTo(width, height - mBannerRadius); path.arcTo(new RectF(width - 2 * mBannerRadius, height - 2 * mBannerRadius, width, height), 0, 90); path.close(); canvas.drawPath(path, mRoundPaint); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); start(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); stop(); } class BannerOnPageChangeCallback extends ViewPager2.OnPageChangeCallback { private int mTempPosition = INVALID_VALUE; private boolean isScrolled; @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { int realPosition = BannerUtils.getRealPosition(isInfiniteLoop(), position, getRealCount()); if (mOnPageChangeListener != null && realPosition == getCurrentItem() - 1) { mOnPageChangeListener.onPageScrolled(realPosition, positionOffset, positionOffsetPixels); } if (getIndicator() != null && realPosition == getCurrentItem() - 1) { getIndicator().onPageScrolled(realPosition, positionOffset, positionOffsetPixels); } } @Override public void onPageSelected(int position) { if (isScrolled) { mTempPosition = position; int realPosition = BannerUtils.getRealPosition(isInfiniteLoop(), position, getRealCount()); if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(realPosition); } if (getIndicator() != null) { getIndicator().onPageSelected(realPosition); } } } @Override public void onPageScrollStateChanged(int state) { //手势滑动中,代码执行滑动中 if (state == ViewPager2.SCROLL_STATE_DRAGGING || state == ViewPager2.SCROLL_STATE_SETTLING) { isScrolled = true; } else if (state == ViewPager2.SCROLL_STATE_IDLE) { //滑动闲置或滑动结束 isScrolled = false; if (mTempPosition != INVALID_VALUE && mIsInfiniteLoop) { if (mTempPosition == 0) { setCurrentItem(getRealCount(), false); } else if (mTempPosition == getItemCount() - 1) { setCurrentItem(1, false); } } } if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrollStateChanged(state); } if (getIndicator() != null) { getIndicator().onPageScrollStateChanged(state); } } } static class AutoLoopTask implements Runnable { private final WeakReference<Banner> reference; AutoLoopTask(Banner banner) { this.reference = new WeakReference<>(banner); } @Override public void run() { Banner banner = reference.get(); if (banner != null && banner.mIsAutoLoop) { int count = banner.getItemCount(); if (count == 0) { return; } int next = (banner.getCurrentItem() + 1) % count; banner.setCurrentItem(next); banner.postDelayed(banner.mLoopTask, banner.mLoopTime); } } } private final RecyclerView.AdapterDataObserver mAdapterDataObserver = new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { if (getItemCount() <= 1) { stop(); } else { start(); } setIndicatorPageChange(); } }; private void initIndicator() { if (getIndicator() == null || getAdapter() == null) { return; } if (getIndicator().getIndicatorConfig().isAttachToBanner()) { removeIndicator(); addView(getIndicator().getIndicatorView()); } initIndicatorAttr(); setIndicatorPageChange(); } private void setInfiniteLoop() { // 当不支持无限循环时,要关闭自动轮播 if (!isInfiniteLoop()) { isAutoLoop(false); } setStartPosition(isInfiniteLoop() ? mStartPosition : 0); } private void setRecyclerViewPadding(int itemPadding) { setRecyclerViewPadding(itemPadding, itemPadding); } private void setRecyclerViewPadding(int leftItemPadding, int rightItemPadding) { RecyclerView recyclerView = (RecyclerView) getViewPager2().getChildAt(0); if (getViewPager2().getOrientation() == ViewPager2.ORIENTATION_VERTICAL) { recyclerView.setPadding(mViewPager2.getPaddingLeft(), leftItemPadding, mViewPager2.getPaddingRight(), rightItemPadding); } else { recyclerView.setPadding(leftItemPadding, mViewPager2.getPaddingTop(), rightItemPadding, mViewPager2.getPaddingBottom()); } recyclerView.setClipToPadding(false); } /** * ********************************************************************** * ------------------------ 对外公开API ---------------------------------* * ********************************************************************** */ public int getCurrentItem() { return getViewPager2().getCurrentItem(); } public int getItemCount() { if (getAdapter() != null) { return getAdapter().getItemCount(); } return 0; } public int getScrollTime() { return mScrollTime; } public boolean isInfiniteLoop() { return mIsInfiniteLoop; } public BannerAdapter getAdapter() { return mAdapter; } public ViewPager2 getViewPager2() { return mViewPager2; } public Indicator getIndicator() { return mIndicator; } public IndicatorConfig getIndicatorConfig() { if (getIndicator() != null) { return getIndicator().getIndicatorConfig(); } return null; } /** * 返回banner真实总数 */ public int getRealCount() { if (getAdapter() != null) { return getAdapter().getRealCount(); } return 0; } //----------------------------------------------------------------------------------------- /** * 是否要拦截事件 * @param intercept * @return */ public Banner setIntercept(boolean intercept) { isIntercept = intercept; return this; } /** * 跳转到指定位置(最好在设置了数据后在调用,不然没有意义) * @param position * @return */ public Banner setCurrentItem(int position) { return setCurrentItem(position, true); } /** * 跳转到指定位置(最好在设置了数据后在调用,不然没有意义) * @param position * @param smoothScroll * @return */ public Banner setCurrentItem(int position, boolean smoothScroll) { getViewPager2().setCurrentItem(position, smoothScroll); return this; } public Banner setIndicatorPageChange() { if (getIndicator() != null) { int realPosition = BannerUtils.getRealPosition(isInfiniteLoop(), getCurrentItem(), getRealCount()); getIndicator().onPageChanged(getRealCount(), realPosition); } return this; } public Banner removeIndicator() { if (getIndicator() != null) { removeView(getIndicator().getIndicatorView()); } return this; } /** * 设置开始的位置 (需要在setAdapter或者setDatas之前调用才有效哦) */ public Banner setStartPosition(int mStartPosition) { this.mStartPosition = mStartPosition; return this; } public int getStartPosition() { return mStartPosition; } /** * 禁止手动滑动 * * @param enabled true 允许,false 禁止 */ public Banner setUserInputEnabled(boolean enabled) { getViewPager2().setUserInputEnabled(enabled); return this; } /** * 添加PageTransformer,可以组合效果 * {@link ViewPager2.PageTransformer} * 如果找不到请导入implementation "androidx.viewpager2:viewpager2:1.0.0" */ public Banner addPageTransformer(@Nullable ViewPager2.PageTransformer transformer) { mCompositePageTransformer.addTransformer(transformer); return this; } /** * 设置PageTransformer,和addPageTransformer不同,这个只支持一种transformer */ public Banner setPageTransformer(@Nullable ViewPager2.PageTransformer transformer) { getViewPager2().setPageTransformer(transformer); return this; } public Banner removeTransformer(ViewPager2.PageTransformer transformer) { mCompositePageTransformer.removeTransformer(transformer); return this; } /** * 添加 ItemDecoration */ public Banner addItemDecoration(RecyclerView.ItemDecoration decor) { getViewPager2().addItemDecoration(decor); return this; } public Banner addItemDecoration(RecyclerView.ItemDecoration decor, int index) { getViewPager2().addItemDecoration(decor, index); return this; } /** * 是否允许自动轮播 * * @param isAutoLoop ture 允许,false 不允许 */ public Banner isAutoLoop(boolean isAutoLoop) { this.mIsAutoLoop = isAutoLoop; return this; } /** * 设置轮播间隔时间 * * @param loopTime 时间(毫秒) */ public Banner setLoopTime(long loopTime) { this.mLoopTime = loopTime; return this; } /** * 设置轮播滑动过程的时间 */ public Banner setScrollTime(int scrollTime) { this.mScrollTime = scrollTime; return this; } /** * 开始轮播 */ public Banner start() { if (mIsAutoLoop) { stop(); postDelayed(mLoopTask, mLoopTime); } return this; } /** * 停止轮播 */ public Banner stop() { if (mIsAutoLoop) { removeCallbacks(mLoopTask); } return this; } /** * 移除一些引用 */ public void destroy() { if (getViewPager2() != null && mPageChangeCallback != null) { getViewPager2().unregisterOnPageChangeCallback(mPageChangeCallback); mPageChangeCallback = null; } stop(); } /** * 设置banner的适配器 */ public Banner setAdapter(BA adapter) { if (adapter == null) { throw new NullPointerException(getContext().getString(R.string.banner_adapter_null_error)); } this.mAdapter = adapter; if (!isInfiniteLoop()) { getAdapter().setIncreaseCount(0); } getAdapter().registerAdapterDataObserver(mAdapterDataObserver); mViewPager2.setAdapter(adapter); setCurrentItem(mStartPosition, false); initIndicator(); return this; } /** * 设置banner的适配器 * @param adapter * @param isInfiniteLoop 是否支持无限循环 * @return */ public Banner setAdapter(BA adapter,boolean isInfiniteLoop) { mIsInfiniteLoop=isInfiniteLoop; setInfiniteLoop(); setAdapter(adapter); return this; } /** * 重新设置banner数据,当然你也可以在你adapter中自己操作数据,不要过于局限在这个方法,举一反三哈 * * @param datas 数据集合,当传null或者datas没有数据时,banner会变成空白的,请做好占位UI处理 */ public Banner setDatas(List<T> datas) { if (getAdapter() != null) { getAdapter().setDatas(datas); setCurrentItem(mStartPosition, false); setIndicatorPageChange(); start(); } return this; } /** * 设置banner轮播方向 * * @param orientation {@link Orientation} */ public Banner setOrientation(@Orientation int orientation) { getViewPager2().setOrientation(orientation); return this; } /** * 改变最小滑动距离 */ public Banner setTouchSlop(int mTouchSlop) { this.mTouchSlop = mTouchSlop; return this; } /** * 设置点击事件 */ public Banner setOnBannerListener(OnBannerListener<T> listener) { if (getAdapter() != null) { getAdapter().setOnBannerListener(listener); } return this; } /** * 添加viewpager切换事件 * <p> * 在viewpager2中切换事件{@link ViewPager2.OnPageChangeCallback}是一个抽象类, * 为了方便使用习惯这里用的是和viewpager一样的{@link ViewPager.OnPageChangeListener}接口 * </p> */ public Banner addOnPageChangeListener(OnPageChangeListener pageListener) { this.mOnPageChangeListener = pageListener; return this; } /** * 设置banner圆角 * <p> * 默认没有圆角,需要取消圆角把半径设置为0即可 * * @param radius 圆角半径 */ public Banner setBannerRound(float radius) { mBannerRadius = radius; return this; } /** * 设置banner圆角(第二种方式,和上面的方法不要同时使用),只支持5.0以上 */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public Banner setBannerRound2(float radius) { BannerUtils.setBannerRound(this, radius); return this; } /** * 为banner添加画廊效果 * * @param itemWidth item左右展示的宽度,单位dp * @param pageMargin 页面间距,单位dp */ public Banner setBannerGalleryEffect(int itemWidth, int pageMargin) { return setBannerGalleryEffect(itemWidth, pageMargin, .85f); } /** * 为banner添加画廊效果 * * @param leftItemWidth item左展示的宽度,单位dp * @param rightItemWidth item右展示的宽度,单位dp * @param pageMargin 页面间距,单位dp */ public Banner setBannerGalleryEffect(int leftItemWidth, int rightItemWidth, int pageMargin) { return setBannerGalleryEffect(leftItemWidth,rightItemWidth, pageMargin, .85f); } /** * 为banner添加画廊效果 * * @param itemWidth item左右展示的宽度,单位dp * @param pageMargin 页面间距,单位dp * @param scale 缩放[0-1],1代表不缩放 */ public Banner setBannerGalleryEffect(int itemWidth, int pageMargin, float scale) { return setBannerGalleryEffect(itemWidth, itemWidth, pageMargin, scale); } /** * 为banner添加画廊效果 * * @param leftItemWidth item左展示的宽度,单位dp * @param rightItemWidth item右展示的宽度,单位dp * @param pageMargin 页面间距,单位dp * @param scale 缩放[0-1],1代表不缩放 */ public Banner setBannerGalleryEffect(int leftItemWidth, int rightItemWidth, int pageMargin, float scale) { if (pageMargin > 0) { addPageTransformer(new MarginPageTransformer(BannerUtils.dp2px(pageMargin))); } if (scale < 1 && scale > 0) { addPageTransformer(new ScaleInTransformer(scale)); } setRecyclerViewPadding(leftItemWidth > 0 ? BannerUtils.dp2px(leftItemWidth + pageMargin) : 0, rightItemWidth > 0 ? BannerUtils.dp2px(rightItemWidth + pageMargin) : 0); return this; } /** * 为banner添加魅族效果 * * @param itemWidth item左右展示的宽度,单位dp */ public Banner setBannerGalleryMZ(int itemWidth) { return setBannerGalleryMZ(itemWidth, .88f); } /** * 为banner添加魅族效果 * * @param itemWidth item左右展示的宽度,单位dp * @param scale 缩放[0-1],1代表不缩放 */ public Banner setBannerGalleryMZ(int itemWidth, float scale) { if (scale < 1 && scale > 0) { addPageTransformer(new MZScaleInTransformer(scale)); } setRecyclerViewPadding(BannerUtils.dp2px(itemWidth)); return this; } /** * ********************************************************************** * ------------------------ 指示器相关设置 --------------------------------* * ********************************************************************** */ /** * 设置轮播指示器(显示在banner上) */ public Banner setIndicator(Indicator indicator) { return setIndicator(indicator, true); } /** * 设置轮播指示器(如果你的指示器写在布局文件中,attachToBanner传false) * * @param attachToBanner 是否将指示器添加到banner中,false 代表你可以将指示器通过布局放在任何位置 * 注意:设置为false后,内置的 setIndicatorGravity()和setIndicatorMargins() 方法将失效。 * 想改变可以自己调用系统提供的属性在布局文件中进行设置。具体可以参照demo */ public Banner setIndicator(Indicator indicator, boolean attachToBanner) { removeIndicator(); indicator.getIndicatorConfig().setAttachToBanner(attachToBanner); this.mIndicator = indicator; initIndicator(); return this; } public Banner setIndicatorSelectedColor(@ColorInt int color) { if (getIndicatorConfig() != null) { getIndicatorConfig().setSelectedColor(color); } return this; } public Banner setIndicatorSelectedColorRes(@ColorRes int color) { setIndicatorSelectedColor(ContextCompat.getColor(getContext(), color)); return this; } public Banner setIndicatorNormalColor(@ColorInt int color) { if (getIndicatorConfig() != null) { getIndicatorConfig().setNormalColor(color); } return this; } public Banner setIndicatorNormalColorRes(@ColorRes int color) { setIndicatorNormalColor(ContextCompat.getColor(getContext(), color)); return this; } public Banner setIndicatorGravity(@IndicatorConfig.Direction int gravity) { if (getIndicatorConfig() != null && getIndicatorConfig().isAttachToBanner()) { getIndicatorConfig().setGravity(gravity); getIndicator().getIndicatorView().postInvalidate(); } return this; } public Banner setIndicatorSpace(int indicatorSpace) { if (getIndicatorConfig() != null) { getIndicatorConfig().setIndicatorSpace(indicatorSpace); } return this; } public Banner setIndicatorMargins(IndicatorConfig.Margins margins) { if (getIndicatorConfig() != null && getIndicatorConfig().isAttachToBanner()) { getIndicatorConfig().setMargins(margins); getIndicator().getIndicatorView().requestLayout(); } return this; } public Banner setIndicatorWidth(int normalWidth, int selectedWidth) { if (getIndicatorConfig() != null) { getIndicatorConfig().setNormalWidth(normalWidth); getIndicatorConfig().setSelectedWidth(selectedWidth); } return this; } public Banner setIndicatorNormalWidth(int normalWidth) { if (getIndicatorConfig() != null) { getIndicatorConfig().setNormalWidth(normalWidth); } return this; } public Banner setIndicatorSelectedWidth(int selectedWidth) { if (getIndicatorConfig() != null) { getIndicatorConfig().setSelectedWidth(selectedWidth); } return this; } public Banner setIndicatorRadius(int indicatorRadius) { if (getIndicatorConfig() != null) { getIndicatorConfig().setRadius(indicatorRadius); } return this; } public Banner setIndicatorHeight(int indicatorHeight) { if (getIndicatorConfig() != null) { getIndicatorConfig().setHeight(indicatorHeight); } return this; } /** * ********************************************************************** * ------------------------ 生命周期控制 --------------------------------* * ********************************************************************** */ public Banner addBannerLifecycleObserver(LifecycleOwner owner) { if (owner != null) { owner.getLifecycle().addObserver(new BannerLifecycleObserverAdapter(owner, this)); } return this; } @Override public void onStart(LifecycleOwner owner) { start(); } @Override public void onStop(LifecycleOwner owner) { stop(); } @Override public void onDestroy(LifecycleOwner owner) { destroy(); } }
youth5201314/banner
banner/src/main/java/com/youth/banner/Banner.java
355
package me.ag2s.umdlib.tool; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Random; import java.util.zip.InflaterInputStream; public class UmdUtils { private static final int EOF = -1; private static final int BUFFER_SIZE = 8 * 1024; /** * 将字符串编码成Unicode形式的byte[] * * @param s 要编码的字符串 * @return 编码好的byte[] */ public static byte[] stringToUnicodeBytes(String s) { if (s == null) { throw new NullPointerException(); } int len = s.length(); byte[] ret = new byte[len * 2]; int a, b, c; for (int i = 0; i < len; i++) { c = s.charAt(i); a = c >> 8; b = c & 0xFF; if (a < 0) { a += 0xFF; } if (b < 0) { b += 0xFF; } ret[i * 2] = (byte) b; ret[i * 2 + 1] = (byte) a; } return ret; } /** * 将编码成Unicode形式的byte[]解码成原始字符串 * * @param bytes 编码成Unicode形式的byte[] * @return 原始字符串 */ public static String unicodeBytesToString(byte[] bytes) { char[] s = new char[bytes.length / 2]; StringBuilder sb = new StringBuilder(); int a, b, c; for (int i = 0; i < s.length; i++) { a = bytes[i * 2 + 1]; b = bytes[i * 2]; c = (a & 0xff) << 8 | (b & 0xff); if (c < 0) { c += 0xffff; } char[] c1 = Character.toChars(c); sb.append(c1); } return sb.toString(); } /** * 将byte[]转化成Hex形式 * * @param bArr byte[] * @return 目标HEX字符串 */ public static String toHex(byte[] bArr) { StringBuilder sb = new StringBuilder(bArr.length); String sTmp; for (int i = 0; i < bArr.length; i++) { sTmp = Integer.toHexString(0xFF & bArr[i]); if (sTmp.length() < 2) sb.append(0); sb.append(sTmp.toUpperCase()); } return sb.toString(); } /** * 解压缩zip的byte[] * * @param compress zippered byte[] * @return decompressed byte[] * @throws Exception 解码时失败时 */ public static byte[] decompress(byte[] compress) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(compress); InflaterInputStream iis = new InflaterInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int c = 0; byte[] buf = new byte[BUFFER_SIZE]; while (true) { c = iis.read(buf); if (c == EOF) break; baos.write(buf, 0, c); } baos.flush(); return baos.toByteArray(); } public static void saveFile(File f, byte[] content) throws IOException { try (FileOutputStream fos = new FileOutputStream(f)) { BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write(content); bos.flush(); } } public static byte[] readFile(File f) throws IOException { try (FileInputStream fis = new FileInputStream(f)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedInputStream bis = new BufferedInputStream(fis); int ch; while ((ch = bis.read()) >= 0) { baos.write(ch); } baos.flush(); return baos.toByteArray(); } } private static final Random random = new Random(); public static byte[] genRandomBytes(int len) { if (len <= 0) { throw new IllegalArgumentException("Length must > 0: " + len); } byte[] ret = new byte[len]; for (int i = 0; i < ret.length; i++) { ret[i] = (byte) random.nextInt(256); } return ret; } }
gedoor/legado
modules/book/src/main/java/me/ag2s/umdlib/tool/UmdUtils.java
357
/*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.io.BufferedReader; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.util.*; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Timestamp; import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.Month; import java.time.Year; import java.util.Map.Entry; import java.util.regex.Pattern; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import apijson.JSONResponse; import apijson.Log; import apijson.NotNull; import apijson.RequestMethod; import apijson.StringUtil; import apijson.orm.Join.On; import apijson.orm.exception.NotExistException; /**executor for query(read) or update(write) MySQL database * @author Lemon */ public abstract class AbstractSQLExecutor<T extends Object> implements SQLExecutor<T> { private static final String TAG = "AbstractSQLExecutor"; public static String KEY_RAW_LIST = "@RAW@LIST"; // 避免和字段命名冲突,不用 $RAW@LIST$ 是因为 $ 会在 fastjson 内部转义,浪费性能 private Parser<T> parser; @Override public Parser<T> getParser() { return parser; } @Override public AbstractSQLExecutor<T> setParser(Parser<T> parser) { this.parser = parser; return this; } private int generatedSQLCount = 0; private int cachedSQLCount = 0; private int executedSQLCount = 0; @Override public int getGeneratedSQLCount() { return generatedSQLCount; } @Override public int getCachedSQLCount() { return cachedSQLCount; } @Override public int getExecutedSQLCount() { return executedSQLCount; } private long executedSQLDuration = 0; private long sqlResultDuration = 0; @Override public long getExecutedSQLDuration() { return executedSQLDuration; } @Override public long getSqlResultDuration() { return sqlResultDuration; } /** * 缓存 Map */ protected Map<String, List<JSONObject>> cacheMap = new HashMap<>(); /**保存缓存 * @param sql key * @param list value * @param config 一般主表 SQLConfig<T> 不为 null,JOIN 副表的为 null */ @Override public void putCache(String sql, List<JSONObject> list, SQLConfig<T> config) { if (sql == null || list == null) { // 空 list 有效,说明查询过 sql 了 || list.isEmpty()) { Log.i(TAG, "saveList sql == null || list == null >> return;"); return; } cacheMap.put(sql, list); } /**获取缓存 * @param sql key * @param config 一般主表 SQLConfig<T> 不为 null,JOIN 副表的为 null */ @Override public List<JSONObject> getCache(String sql, SQLConfig<T> config) { return cacheMap.get(sql); } /**获取缓存 * @param sql key * @param position * @param config 一般主表 SQLConfig<T> 不为 null,JOIN 副表的为 null * @return */ @Override public JSONObject getCacheItem(String sql, int position, SQLConfig<T> config) { List<JSONObject> list = getCache(sql, config); return getCacheItem(list, position, config); } public JSONObject getCacheItem(List<JSONObject> list, int position, SQLConfig<T> config) { // 只要 list 不为 null,则如果 list.get(position) == null,则返回 {} ,避免再次 SQL 查询 if (list == null) { return null; } JSONObject result = position >= list.size() ? null : list.get(position); return result != null ? result : new JSONObject(); } /**移除缓存 * @param sql key * @param config */ @Override public void removeCache(String sql, SQLConfig<T> config) { if (sql == null) { Log.i(TAG, "removeList sql == null >> return;"); return; } cacheMap.remove(sql); } @Override public ResultSet executeQuery(@NotNull Statement statement, String sql) throws Exception { ResultSet rs = statement.executeQuery(sql); return rs; } @Override public int executeUpdate(@NotNull Statement statement, String sql) throws Exception { int c = statement.executeUpdate(sql); return c; } @Override public ResultSet execute(@NotNull Statement statement, String sql) throws Exception { statement.execute(sql); ResultSet rs = statement.getResultSet(); return rs; } /**执行SQL * @param config * @return * @throws Exception */ @Override public JSONObject execute(@NotNull SQLConfig<T> config, boolean unknownType) throws Exception { long executedSQLStartTime = System.currentTimeMillis(); final String sql = config.getSQL(false); if (StringUtil.isEmpty(sql, true)) { Log.e(TAG, "execute StringUtil.isEmpty(sql, true) >> return null;"); return null; } boolean isExplain = config.isExplain(); boolean isHead = RequestMethod.isHeadMethod(config.getMethod(), true); final int position = config.getPosition(); JSONObject result; if (isExplain == false) { generatedSQLCount ++; } long startTime = System.currentTimeMillis(); Log.d(TAG, "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" + "\n已生成 " + generatedSQLCount + " 条 SQL" + "\nexecute startTime = " + startTime + "\ndatabase = " + StringUtil.getString(config.getDatabase()) + "; schema = " + StringUtil.getString(config.getSchema()) + "; sql = \n" + sql + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); ResultSet rs = null; List<JSONObject> resultList = null; Map<String, JSONObject> childMap = null; try { if (unknownType) { if (isExplain == false) { //只有 SELECT 才能 EXPLAIN executedSQLCount ++; executedSQLStartTime = System.currentTimeMillis(); } Statement statement = getStatement(config); rs = execute(statement, sql); int updateCount = statement.getUpdateCount(); if (isExplain == false) { executedSQLDuration += System.currentTimeMillis() - executedSQLStartTime; } result = new JSONObject(true); result.put(JSONResponse.KEY_COUNT, updateCount); result.put("update", updateCount >= 0); //导致后面 rs.getMetaData() 报错 Operation not allowed after ResultSet closed result.put("moreResults", statement.getMoreResults()); } else { RequestMethod method = config.getMethod(); switch (method) { case POST: case PUT: case DELETE: if (isExplain == false) { //只有 SELECT 才能 EXPLAIN executedSQLCount ++; executedSQLStartTime = System.currentTimeMillis(); } int updateCount = executeUpdate(config); if (isExplain == false) { executedSQLDuration += System.currentTimeMillis() - executedSQLStartTime; } if (updateCount <= 0) { throw new IllegalAccessException("没权限访问或对象不存在!"); // NotExistException 会被 catch 转为成功状态 } // updateCount>0时收集结果。例如更新操作成功时,返回count(affected rows)、id字段 result = AbstractParser.newSuccessResult(); // TODO 对 APIAuto 及其它现有的前端/客户端影响比较大,暂时还是返回 code 和 msg,5.0 再移除 new JSONObject(true); //id,id{}至少一个会有,一定会返回,不用抛异常来阻止关联写操作时前面错误导致后面无条件执行! result.put(JSONResponse.KEY_COUNT, updateCount);//返回修改的记录数 String idKey = config.getIdKey(); if (config.getId() != null) { result.put(idKey, config.getId()); } if (config.getIdIn() != null) { result.put(idKey + "[]", config.getIdIn()); } if (method == RequestMethod.PUT || method == RequestMethod.DELETE) { config.setMethod(RequestMethod.GET); removeCache(config.getSQL(false), config); config.setMethod(method); } return result; case GET: case GETS: case HEAD: case HEADS: List<JSONObject> cache = getCache(sql, config); result = getCacheItem(cache, position, config); Log.i(TAG, ">>> execute result = getCache('" + sql + "', " + position + ") = " + result); if (result != null) { if (isExplain == false) { cachedSQLCount ++; } if (cache != null && cache.size() > 1) { result.put(KEY_RAW_LIST, cache); } Log.d(TAG, "\n\n execute result != null >> return result;" + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n"); return result; } if (isExplain == false) { //只有 SELECT 才能 EXPLAIN executedSQLCount ++; executedSQLStartTime = System.currentTimeMillis(); } rs = executeQuery(config); //FIXME SQL Server 是一次返回两个结果集,包括查询结果和执行计划,需要 moreResults if (isExplain == false) { executedSQLDuration += System.currentTimeMillis() - executedSQLStartTime; } break; default: //OPTIONS, TRACE等 Log.e(TAG, "execute sql = " + sql + " ; method = " + config.getMethod() + " >> return null;"); return null; } } if (isExplain == false && isHead) { if (rs.next() == false) { return AbstractParser.newErrorResult(new SQLException("数据库错误, rs.next() 失败!")); } result = AbstractParser.newSuccessResult(); // 兼容nosql,比如 elasticSearch-sql if(config.isElasticsearch()) { result.put(JSONResponse.KEY_COUNT, rs.getObject(1)); }else { result.put(JSONResponse.KEY_COUNT, rs.getLong(1)); } resultList = new ArrayList<>(1); resultList.add(result); } else { // final boolean cache = config.getCount() != 1; // Log.d(TAG, "select cache = " + cache + "; resultList" + (resultList == null ? "=" : "!=") + "null"); try { // 设置初始容量为查到的数据量,解决频繁扩容导致的延迟,貌似只有 rs.last 取 rs.getRow() ? 然后又得 rs.beforeFirst 重置位置以便下方取值 rs.last(); //移到最后一行 resultList = new ArrayList<>(rs.getRow()); rs.beforeFirst(); } catch (Throwable e) { Log.e(TAG, "try { rs.last(); resultList = new ArrayList<>(rs.getRow()); rs.beforeFirst(); >> } catch (Throwable e) = " + e.getMessage()); int capacity; if (config.getId() != null) { // id:Object 一定是 AND 条件,最终返回数据最多就这么多 capacity = 1; } else { Object idIn = config.getIdIn(); if (idIn instanceof Collection<?>) { // id{}:[] 一定是 AND 条件,最终返回数据最多就这么多 capacity = ((Collection<?>) idIn).size(); } else { // 预估容量 capacity = config.getCount() <= 0 ? AbstractParser.MAX_QUERY_COUNT : config.getCount(); if (capacity > 100) { // 有 WHERE 条件,条件越多过滤数据越多,暂时不考虑 @combine:"a | (b & !c)" 里面 | OR 和 ! NOT 条件,太复杂也不是很必要 Map<String, List<String>> combine = config.getCombineMap(); List<String> andList = combine == null ? null : combine.get("&"); int andCondCount = andList == null ? (config.getWhere() == null ? 0 : config.getWhere().size()) : andList.size(); List<String> orList = combine == null ? null : combine.get("|"); int orCondCount = orList == null ? 0 : orList.size(); List<String> notList = combine == null ? null : combine.get("!"); int notCondCount = notList == null ? 0 : notList.size(); // 有 GROUP BY 分组,字段越少过滤数据越多 String[] group = StringUtil.split(config.getGroup()); int groupCount = group == null ? 0 : group.length; if (groupCount > 0 && Arrays.asList(group).contains(config.getIdKey())) { groupCount = 0; } // 有 HAVING 聚合函数,字段越多过滤数据越多,暂时不考虑 @combine:"a | (b & !c)" 里面 | OR 和 ! NOT 条件,太复杂也不是很必要 Map<String, Object> having = config.getHaving(); int havingCount = having == null ? 0 : having.size(); capacity /= Math.pow(1.5, Math.log10(capacity) + andCondCount + ((orCondCount <= 0 ? 0 : 2.0d/orCondCount) // 1: 2.3, 2: 1.5, 3: 1.3, 4: 1.23, 5: 1.18 + (notCondCount/5.0d) // 1: 1.08, 2: 1.18, 3: 1.28, 4: 1.38, 1.50 + (groupCount <= 0 ? 0 : 10.0d/groupCount)) // 1: 57.7, 7.6, 3: 3.9, 4: 2.8, 5: 2.3 + havingCount ); capacity += 1; // 避免正好比需要容量少一点点导致多一次扩容,大量数据 System.arrayCopy } } } resultList = new ArrayList<>(capacity); } int index = -1; long startTime2 = System.currentTimeMillis(); ResultSetMetaData rsmd = rs.getMetaData(); final int length = rsmd.getColumnCount(); sqlResultDuration += System.currentTimeMillis() - startTime2; //<SELECT * FROM Comment WHERE momentId = '470', { id: 1, content: "csdgs" }> childMap = new HashMap<>(); //要存到cacheMap // Map<Integer, Join> columnIndexAndJoinMap = new HashMap<>(length); String lastTableName = null; // 默认就是主表 config.getTable(); String lastAliasName = null; // 默认就是主表 config.getAlias(); int lastViceTableStart = 0; int lastViceColumnStart = 0; Join lastJoin = null; // TODO String[] columnIndexAndTableMap = new String[length]; // WHERE id = ? AND ... 或 WHERE ... AND id = ? 强制排序 remove 再 put,还是重新 getSQL吧 List<Join> joinList = config.getJoinList(); boolean hasJoin = config.hasJoin() && joinList != null && ! joinList.isEmpty(); // 直接用数组存取更快 Map<Integer, Join> columnIndexAndJoinMap = isExplain || ! hasJoin ? null : new HashMap<>(length); Join[] columnIndexAndJoinMap = isExplain || ! hasJoin ? null : new Join[length]; // int viceColumnStart = length + 1; //第一个副表字段的index // FIXME 统计游标查找的时长?可能 ResultSet.next() 及 getTableName, getColumnName, getObject 比较耗时,因为不是一次加载到内存,而是边读边发 long lastCursorTime = System.currentTimeMillis(); while (rs.next()) { sqlResultDuration += System.currentTimeMillis() - lastCursorTime; lastCursorTime = System.currentTimeMillis(); index ++; Log.d(TAG, "\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n execute while (rs.next()){ index = " + index + "\n\n"); JSONObject item = new JSONObject(true); JSONObject curItem = item; boolean isMain = true; for (int i = 1; i <= length; i++) { // if (hasJoin && viceColumnStart > length && config.getSQLTable().equalsIgnoreCase(rsmd.getTableName(i)) == false) { // viceColumnStart = i; // } // bugfix-修复非常规数据库字段,获取表名失败导致输出异常 Join curJoin = columnIndexAndJoinMap == null ? null : columnIndexAndJoinMap[i - 1]; // columnIndexAndJoinMap.get(i); // 为什么 isExplain == false 不用判断?因为所有字段都在一张 Query Plan 表 if (index <= 0 && columnIndexAndJoinMap != null) { // && viceColumnStart > length) { SQLConfig<T> curConfig = curJoin == null || ! curJoin.isSQLJoin() ? null : curJoin.getCacheConfig(); List<String> curColumn = curConfig == null ? null : curConfig.getColumn(); String sqlTable = curConfig == null ? null : curConfig.getSQLTable(); String sqlAlias = curConfig == null ? null : curConfig.getAlias(); List<String> column = config.getColumn(); int mainColumnSize = column == null ? 0 : column.size(); // FIXME 主副表同名导致主表数据当成副表数据 { "[]": { "join": "</Comment:to/id@", "Comment": { "toId>": 0 }, "Comment:to": { "@column": "id,content", "id@": "/Comment/toId" } }, "@explain": true } boolean toFindJoin = mainColumnSize <= 0 || i > mainColumnSize; // 主表就不用找 JOIN 配置 if (StringUtil.isEmpty(sqlTable, true)) { if (toFindJoin) { // 在主表字段数量内的都归属主表 long startTime3 = System.currentTimeMillis(); sqlTable = rsmd.getTableName(i); // SQL 函数甚至部分字段都不返回表名,当然如果没传 @column 生成的 Table.* 则返回的所有字段都会带表名 sqlResultDuration += System.currentTimeMillis() - startTime3; if (StringUtil.isEmpty(sqlTable, true)) { boolean isEmpty = curItem == null || curItem.isEmpty(); String label = isEmpty ? null : getKey(config, rs, rsmd, index, curItem, i, childMap); if (isEmpty || curItem.containsKey(label) == false) { // 重复字段几乎肯定不是一张表的,尤其是主副表同名主键 id sqlTable = i <= 1 ? config.getSQLTable() : lastTableName; // Presto 等引擎 JDBC 返回 rsmd.getTableName(i) 为空,主表如果一个字段都没有会导致 APISJON 主副表所有字段都不返回 } } if (StringUtil.isEmpty(sqlTable, true)) { // hasJoin 已包含这个判断 && joinList != null) { int nextViceColumnStart = lastViceColumnStart; // 主表没有 @column 时会偏小 lastViceColumnStart for (int j = lastViceTableStart; j < joinList.size(); j++) { // 查找副表 @column,定位字段所在表 Join join = joinList.get(j); SQLConfig<T> cfg = join == null || ! join.isSQLJoin() ? null : join.getJoinConfig(); List<String> c = cfg == null ? null : cfg.getColumn(); nextViceColumnStart += (c != null && ! c.isEmpty() ? c.size() : ( StringUtil.equalsIgnoreCase(sqlTable, lastTableName) && StringUtil.equals(sqlAlias, lastAliasName) ? 1 : 0 ) ); if (i < nextViceColumnStart) { sqlTable = cfg.getSQLTable(); sqlAlias = cfg.getAlias(); lastViceTableStart = j; // 避免后面的空 @column 表内字段被放到之前的空 @column 表 curJoin = join; curConfig = cfg; curColumn = c; toFindJoin = false; isMain = false; break; } } } // 没有 @column,仍然定位不了,用前一个 table 名。FIXME 如果刚好某个表内第一个字段是就是 SQL 函数? if (StringUtil.isEmpty(sqlTable, true)) { sqlTable = lastTableName; sqlAlias = lastAliasName; toFindJoin = false; } } } else if (config.isClickHouse() && (sqlTable.startsWith("`") || sqlTable.startsWith("\""))){ sqlTable = sqlTable.substring(1, sqlTable.length() - 1); } if (StringUtil.equalsIgnoreCase(sqlTable, lastTableName) == false || StringUtil.equals(sqlAlias, lastAliasName) == false) { lastTableName = sqlTable; lastAliasName = sqlAlias; lastViceColumnStart = i; if (toFindJoin) { // 找到对应的副表 JOIN 配置 for (int j = lastViceTableStart; j < joinList.size(); j++) { // 查找副表 @column,定位字段所在表 Join join = joinList.get(j); SQLConfig<T> cfg = join == null || ! join.isSQLJoin() ? null : join.getJoinConfig(); if (cfg != null && StringUtil.equalsIgnoreCase(sqlTable, cfg.getSQLTable()) ) { // FIXME 导致副表字段错放到主表 && StringUtil.equals(sqlAlias, cfg.getAlias())) { lastViceTableStart = j; // 避免后面的空 @column 表内字段被放到之前的空 @column 表 curJoin = join; curConfig = cfg; curColumn = curConfig == null ? null : curConfig.getColumn(); isMain = false; break; } } } } if (isMain) { lastViceColumnStart ++; } else { if (curJoin == null) { curJoin = lastJoin; } else { lastJoin = curJoin; } if (curColumn == null) { curConfig = curJoin == null || ! curJoin.isSQLJoin() ? null : curJoin.getJoinConfig(); curColumn = curConfig == null ? null : curConfig.getColumn(); } // 解决后面的表内 SQL 函数被放到之前的空 @column 表 if (curColumn == null || curColumn.isEmpty()) { lastViceColumnStart ++; } } columnIndexAndJoinMap[i - 1] = curJoin; } // 如果是主表则直接用主表对应的 item,否则缓存副表数据到 childMap Join prevJoin = columnIndexAndJoinMap == null || i < 2 ? null : columnIndexAndJoinMap[i - 2]; if (curJoin != prevJoin) { // 前后字段不在同一个表对象,即便后面出现 null,也不该是主表数据,而是逻辑 bug 导致 SQLConfig<T> viceConfig = curJoin != null && curJoin.isSQLJoin() ? curJoin.getCacheConfig() : null; if (viceConfig != null) { //FIXME 只有和主表关联才能用 item,否则应该从 childMap 查其它副表数据 List<On> onList = curJoin.getOnList(); int size = onList == null ? 0 : onList.size(); if (size > 0) { for (int j = size - 1; j >= 0; j--) { On on = onList.get(j); String ok = on == null ? null : on.getOriginKey(); if (ok == null) { throw new NullPointerException("服务器内部错误,List<Join> 中 Join.onList[" + j + (on == null ? "] = null!" : ".getOriginKey() = null!")); } viceConfig.putWhere(ok.substring(0, ok.length() - 1), item.get(on.getTargetKey()), true); } } } String viceSql = viceConfig == null ? null : viceConfig.getSQL(false); //TODO 在 SQLConfig<T> 缓存 SQL,减少大量的重复生成 if (StringUtil.isEmpty(viceSql, true)) { Log.i(TAG, "execute StringUtil.isEmpty(viceSql, true) >> item = null; >> "); curItem = null; } else if (curJoin.isOuterJoin() || curJoin.isAntiJoin()) { Log.i(TAG, "execute curJoin.isOuterJoin() || curJoin.isAntiJoin() >> item = null; >> "); curItem = null; // 肯定没有数据,缓存也无意义 // 副表是按常规条件查询,缓存会导致其它同表同条件对象查询结果集为空 childMap.put(viceSql, new JSONObject()); // 缓存固定空数据,避免后续多余查询 } else { curItem = childMap.get(viceSql); if (curItem == null) { curItem = new JSONObject(true); childMap.put(viceSql, curItem); } } } curItem = onPutColumn(config, rs, rsmd, index, curItem, i, curJoin, childMap); // isExplain == false && hasJoin && i >= viceColumnStart ? childMap : null); } resultList = onPutTable(config, rs, rsmd, resultList, index, item); Log.d(TAG, "execute while (rs.next()) { resultList.put( " + index + ", result); " + "\n >>>>>>>>>>>>>>>>>>>>>>>>>>> \n\n"); } } } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } } if (resultList == null) { return null; } if (unknownType || isExplain) { if (isExplain) { if (result == null) { result = new JSONObject(true); } config.setExplain(false); result.put("sql", config.getSQL(false)); config.setExplain(isExplain); } result.put("list", resultList); if (unknownType == false) { putCache(sql, Arrays.asList(result), config); } return result; } if (isHead == false) { // @ APP JOIN 查询副表并缓存到 childMap <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Map<String, List<JSONObject>> appJoinChildMap = new HashMap<>(); childMap.forEach((viceSql, item) -> appJoinChildMap.put(viceSql, Arrays.asList(item))); executeAppJoin(config, resultList, appJoinChildMap); // @ APP JOIN 查询副表并缓存到 childMap >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //子查询 SELECT Moment.*, Comment.id 中的 Comment 内字段 Set<Entry<String, List<JSONObject>>> set = appJoinChildMap.entrySet(); //<sql, Table> for (Entry<String, List<JSONObject>> entry : set) { putCache(entry.getKey(), entry.getValue(), null); } Log.i(TAG, ">>> execute putCache('" + sql + "', resultList); resultList.size() = " + resultList.size()); // 数组主表对象额外一次返回全部,方便 Parser 缓存来提高性能 result = position >= resultList.size() ? new JSONObject() : resultList.get(position); if (position == 0 && resultList.size() > 1 && result != null && result.isEmpty() == false) { // 不是 main 不会直接执行,count=1 返回的不会超过 1 && config.isMain() && config.getCount() != 1 Log.i(TAG, ">>> execute position == 0 && resultList.size() > 1 && result != null && result.isEmpty() == false" + " >> result = new JSONObject(result); result.put(KEY_RAW_LIST, resultList);"); result = new JSONObject(result); result.put(KEY_RAW_LIST, resultList); } } putCache(sql, resultList, config); long endTime = System.currentTimeMillis(); Log.d(TAG, "\n\n execute endTime = " + endTime + "; duration = " + (endTime - startTime) + "\n return resultList.get(" + position + ");" + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n"); return result; } /**@ APP JOIN 查询副表并缓存到 childMap * @param config * @param resultList * @param childMap * @throws Exception */ protected void executeAppJoin(SQLConfig<T> config, List<JSONObject> resultList, Map<String, List<JSONObject>> childMap) throws Exception { List<Join> joinList = config.getJoinList(); if (joinList != null) { for (Join join : joinList) { if (join.isAppJoin() == false) { Log.i(TAG, "executeAppJoin for (Join j : joinList) >> j.isAppJoin() == false >> continue;"); continue; } SQLConfig<T> cc = join.getCacheConfig(); //这里用config改了getSQL后再还原很麻烦,所以提前给一个config2更好 if (cc == null) { if (Log.DEBUG) { throw new NullPointerException("服务器内部错误, executeAppJoin cc == null ! 导致不能缓存 @ APP JOIN 的副表数据!"); } continue; } SQLConfig<T> jc = join.getJoinConfig(); List<On> onList = join.getOnList(); On on = onList == null || onList.isEmpty() ? null : onList.get(0); // APP JOIN 应该有且只有一个 ON 条件 String originKey = on == null ? null : on.getOriginKey(); if (originKey == null) { throw new NullPointerException("服务器内部错误,List<Join> 中 Join.onList[0" + (on == null ? "] = null!" : ".getOriginKey() = null!")); } String key = on.getKey(); if (key == null) { throw new NullPointerException("服务器内部错误,List<Join> 中 Join.onList[0" + (on == null ? "] = null!" : ".getKey() = null!")); } // 取出 "id@": "@/User/userId" 中所有 userId 的值 List<Object> targetValueList = new ArrayList<>(); for (int i = 0; i < resultList.size(); i++) { JSONObject mainTable = resultList.get(i); Object targetValue = mainTable == null ? null : mainTable.get(on.getTargetKey()); if (targetValue != null && targetValueList.contains(targetValue) == false) { targetValueList.add(targetValue); } } if (targetValueList.isEmpty() && config.isExplain() == false) { throw new NotExistException("targetValueList.isEmpty() && config.isExplain() == false"); } // 替换为 "id{}": [userId1, userId2, userId3...] jc.putWhere(originKey, null, false); // remove originKey jc.putWhere(key + "{}", targetValueList, true); // add originKey{} } jc.setMain(true).setPreparedValueList(new ArrayList<>()); // 放一块逻辑更清晰,也避免解析 * 等不支持或性能开销 // String q = jc.getQuote(); // if (allChildCount > 0 && jc.getCount() <= 0) { // List<String> column = jc.getColumn(); // if (column == null || column.isEmpty()) { // column = Arrays.asList("*;row_number()OVER(PARTITION BY " + q + key + q + " ORDER BY " + q + key + q + " ASC):_row_num_"); // } // else { // column.add("row_number()OVER(PARTITION BY " + q + key + q + " ORDER BY " + q + key + q + " ASC):_row_num_"); // } // jc.setColumn(column); // } int childCount = cc.getCount(); int allChildCount = childCount*config.getCount(); // 所有分组子项数量总和 boolean isOne2Many = childCount != 1 || join.isOne2Many(); // 一对多会漏副表数据 TODO 似乎一对一走以下优化 row_number() <= childCount 逻辑也没问题 // if (isOne2Many == false && allChildCount > 0 && jc.getCount() < allChildCount) { // jc.setCount(allChildCount); // } boolean prepared = jc.isPrepared(); String sql = jc.getSQL(false); if (StringUtil.isEmpty(sql, true)) { throw new NullPointerException(TAG + ".executeAppJoin StringUtil.isEmpty(sql, true) >> return null;"); } String sql2 = null; if (childCount > 0 && isOne2Many && (jc.isMySQL() == false || jc.getDBVersionNums()[0] >= 8)) { // 加 row_number 字段并不会导致 count 等聚合函数统计出错,结果偏大,SQL JOIN 才会,之前没发现是因为缓存失效 bug // boolean noAggrFun = true; // List<String> column = jc.getColumn(); // if (column != null) { // for (String c : column) { // int start = c == null ? -1 : c.indexOf("("); // int end = start <= 0 ? -1 : c.lastIndexOf(")"); // if (start > 0 && end > start) { // String fun = c.substring(0, start); // if (AbstractSQLConfig.SQL_AGGREGATE_FUNCTION_MAP.containsKey(fun)) { // noAggrFun = false; // break; // } // } // } // } // // if (noAggrFun) { // 加 row_number 字段会导致 count 等聚合函数统计出错,结果偏大? String q = jc.getQuote(); sql2 = prepared && jc.isTDengine() == false ? jc.getSQL(true) : sql; String prefix = "SELECT * FROM("; String rnStr = ", row_number() OVER (PARTITION BY " + q + key + q + ((AbstractSQLConfig) jc).getOrderString(true) + ") _row_num_ FROM "; String suffix = ") _t WHERE ( (_row_num_ <= " + childCount + ") )" + (allChildCount > 0 ? " LIMIT " + allChildCount : ""); sql2 = prefix // 放一块逻辑更清晰,也避免解析 * 等不支持或性能开销 + sql + sql2.replaceFirst(" FROM ", rnStr) // * 居然只能放在 row_number() 前面,放后面就报错 "SELECT ", rnStr) + suffix; sql = prepared ? (prefix + sql.replaceFirst(" FROM ", rnStr) + suffix) : sql2; // } } boolean isExplain = jc.isExplain(); if (isExplain == false) { generatedSQLCount ++; } long startTime = System.currentTimeMillis(); Log.d(TAG, "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" + "\n executeAppJoin startTime = " + startTime + "\n sql = \n " + sql + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); //执行副表的批量查询 并 缓存到 childMap ResultSet rs = null; try { long executedSQLStartTime = 0; if (isExplain == false) { //只有 SELECT 才能 EXPLAIN executedSQLCount ++; executedSQLStartTime = System.currentTimeMillis(); } rs = executeQuery(jc, sql2); if (isExplain == false) { executedSQLDuration += System.currentTimeMillis() - executedSQLStartTime; } int count = 0; int index = -1; long startTime2 = System.currentTimeMillis(); ResultSetMetaData rsmd = rs.getMetaData(); final int length = rsmd.getColumnCount(); sqlResultDuration += System.currentTimeMillis() - startTime2; Map<String, Boolean> skipMap = new HashMap<>(); long lastCursorTime = System.currentTimeMillis(); while ((allChildCount <= 0 || count < allChildCount) && rs.next()) { //FIXME 同时有 @ APP JOIN 和 < 等 SQL JOIN 时,next = false 总是无法进入循环,导致缓存失效,可能是连接池或线程问题 sqlResultDuration += System.currentTimeMillis() - lastCursorTime; lastCursorTime = System.currentTimeMillis(); index ++; Log.d(TAG, "\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n executeAppJoin while (rs.next()){ index = " + index + "\n\n"); JSONObject result = new JSONObject(true); for (int i = 1; i <= length; i++) { result = onPutColumn(jc, rs, rsmd, index, result, i, null, null); } //每个 result 都要用新的 SQL 来存 childResultMap = onPutTable(config, rs, rsmd, childResultMap, index, result); Log.d(TAG, "\n executeAppJoin while (rs.next()) { resultList.put(" + index + ", result); " + "\n >>>>>>>>>>>>>>>>>>>>>>>>>>> \n\n"); //TODO 兼容复杂关联 cc.putWhere(key, result.get(key), true); // APP JOIN 应该有且只有一个 ON 条件 String cacheSql = cc.getSQL(false); List<JSONObject> results = childMap.get(cacheSql); if (results == null || skipMap.get(cacheSql) == null) { // 避免添加重复数据 results = new ArrayList<>(childCount); childMap.put(cacheSql, results); skipMap.put(cacheSql, Boolean.TRUE); } if (childCount <= 0 || results.size() < childCount) { // 避免超过子数组每页数量 // if (count == 1 && results.isEmpty() == false) { // 避免添加重复数据 // results.clear(); // } results.add(result); //缓存到 childMap count ++; Log.d(TAG, ">>> executeAppJoin childMap.put('" + cacheSql + "', result); childMap.size() = " + childMap.size()); } } } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } } long endTime = System.currentTimeMillis(); Log.d(TAG, "\n\n executeAppJoin endTime = " + endTime + "; duration = " + (endTime - startTime) + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n"); } } } /**table.put(rsmd.getColumnLabel(i), rs.getObject(i)); * @param config * @param rs * @param rsmd * @param tablePosition 从0开始 * @param table * @param columnIndex 从1开始 * @param childMap * @return result * @throws Exception */ protected JSONObject onPutColumn(@NotNull SQLConfig<T> config, @NotNull ResultSet rs, @NotNull ResultSetMetaData rsmd , final int tablePosition, @NotNull JSONObject table, final int columnIndex, Join join, Map<String, JSONObject> childMap) throws Exception { if (table == null) { // 对应副表 viceSql 不能生成正常 SQL, 或者是 ! - Outer, ( - ANTI JOIN 的副表这种不需要缓存及返回的数据 Log.i(TAG, "onPutColumn table == null >> return table;"); return table; } if (isHideColumn(config, rs, rsmd, tablePosition, table, columnIndex, childMap)) { Log.i(TAG, "onPutColumn isHideColumn(config, rs, rsmd, tablePosition, table, columnIndex, childMap) >> return table;"); return table; } String label = getKey(config, rs, rsmd, tablePosition, table, columnIndex, childMap); Object value = getValue(config, rs, rsmd, tablePosition, table, columnIndex, label, childMap); // 主表必须 put 至少一个 null 进去,否则全部字段为 null 都不 put 会导致中断后续正常返回值 if (value != null || (join == null && table.isEmpty())) { table.put(label, value); } return table; } /**如果不需要这个功能,在子类重写并直接 return false; 来提高性能 * @param config * @param rs * @param rsmd * @param tablePosition * @param table * @param columnIndex * @param childMap * @return * @throws SQLException */ protected boolean isHideColumn(@NotNull SQLConfig<T> config, @NotNull ResultSet rs, @NotNull ResultSetMetaData rsmd , final int tablePosition, @NotNull JSONObject table, final int columnIndex, Map<String, JSONObject> childMap) throws SQLException { return rsmd.getColumnName(columnIndex).startsWith("_"); } /**resultList.put(position, table); * @param config * @param rs * @param rsmd * @param resultList * @param position * @param table * @return resultList */ protected List<JSONObject> onPutTable(@NotNull SQLConfig<T> config, @NotNull ResultSet rs, @NotNull ResultSetMetaData rsmd , @NotNull List<JSONObject> resultList, int position, @NotNull JSONObject table) { resultList.add(table); return resultList; } protected String getKey(@NotNull SQLConfig<T> config, @NotNull ResultSet rs, @NotNull ResultSetMetaData rsmd , final int tablePosition, @NotNull JSONObject table, final int columnIndex, Map<String, JSONObject> childMap) throws Exception { long startTime = System.currentTimeMillis(); String key = rsmd.getColumnLabel(columnIndex); // dotIndex < 0 ? lable : lable.substring(dotIndex + 1); sqlResultDuration += System.currentTimeMillis() - startTime; if (config.isHive()) { String tableName = config.getTable(); String realTableName = AbstractSQLConfig.TABLE_KEY_MAP.get(tableName); String pattern = "^" + (StringUtil.isEmpty(realTableName, true) ? tableName : realTableName) + "\\." + "[a-zA-Z]+$"; boolean isMatch = Pattern.matches(pattern, key); if (isMatch) { key = key.split("\\.")[1]; } } return key; } protected Object getValue(@NotNull SQLConfig<T> config, @NotNull ResultSet rs, @NotNull ResultSetMetaData rsmd , final int tablePosition, @NotNull JSONObject table, final int columnIndex, String lable, Map<String, JSONObject> childMap) throws Exception { long startTime = System.currentTimeMillis(); Object value = rs.getObject(columnIndex); sqlResultDuration += System.currentTimeMillis() - startTime; // Log.d(TAG, "name:" + rsmd.getColumnName(i)); // Log.d(TAG, "lable:" + rsmd.getColumnLabel(i)); // Log.d(TAG, "type:" + rsmd.getColumnType(i)); // Log.d(TAG, "typeName:" + rsmd.getColumnTypeName(i)); // Log.i(TAG, "select while (rs.next()) { >> for (int i = 0; i < length; i++) {" // + "\n >>> value = " + value); boolean castToJson = false; //数据库查出来的null和empty值都有意义,去掉会导致 Moment:{ @column:"content" } 部分无结果及中断数组查询! if (value instanceof Boolean) { //加快判断速度 } else if (value instanceof Number) { value = getNumVal((Number) value); } else if (value instanceof Timestamp) { value = ((Timestamp) value).toString(); } else if (value instanceof Date) { // java.sql.Date 和 java.sql.Time 都继承 java.util.Date value = ((Date) value).toString(); } else if (value instanceof LocalDateTime) { value = ((LocalDateTime) value).toString(); } else if (value instanceof Year) { value = ((Year) value).getValue(); } else if (value instanceof Month) { value = ((Month) value).getValue(); } else if (value instanceof DayOfWeek) { value = ((DayOfWeek) value).getValue(); } else if (value instanceof String && isJSONType(config, rsmd, columnIndex, lable)) { //json String castToJson = true; } else if (value instanceof Blob) { //FIXME 存的是 abcde,取出来直接就是 [97, 98, 99, 100, 101] 这种 byte[] 类型,没有经过以下处理,但最终序列化后又变成了字符串 YWJjZGU= castToJson = true; value = new String(((Blob) value).getBytes(1, (int) ((Blob) value).length()), "UTF-8"); } else if (value instanceof Clob) { //SQL Server TEXT 类型 居然走这个 castToJson = true; StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(((Clob) value).getCharacterStream()); String s = br.readLine(); while (s != null) { sb.append(s); s = br.readLine(); } value = sb.toString(); try { br.close(); } catch (Exception e) { e.printStackTrace(); } } if (castToJson == false) { List<String> json = config.getJson(); castToJson = json != null && json.contains(lable); } if (castToJson) { try { value = JSON.parse((String) value); } catch (Exception e) { Log.e(TAG, "getValue try { value = JSON.parse((String) value); } catch (Exception e) { \n" + e.getMessage()); } } return value; } public Object getNumVal(Number value) { if (value == null) { return null; } if (value instanceof BigInteger) { return ((BigInteger) value).toString(); } if (value instanceof BigDecimal) { return ((BigDecimal) value).toString(); } double v = value.doubleValue(); // if (v > Integer.MAX_VALUE || v < Integer.MIN_VALUE) { // 避免前端/客户端拿到精度丢失甚至严重失真的值 // return value.toString(); // } // JavaScript: Number.MAX_SAFE_INTEGER ~ Number.MIN_SAFE_INTEGER if (v > 9007199254740991L || v < -9007199254740991L) { // 避免前端/客户端拿到精度丢失甚至严重失真的值 return value.toString(); } return value; } /**判断是否为JSON类型 * @param config * @param lable * @param rsmd * @param position * @return */ @Override public boolean isJSONType(@NotNull SQLConfig<T> config, ResultSetMetaData rsmd, int position, String lable) { try { long startTime = System.currentTimeMillis(); String column = rsmd.getColumnTypeName(position); sqlResultDuration += System.currentTimeMillis() - startTime; // nosql elasticSearch jdbc获取不到 字段类型 if(StringUtil.isEmpty(column)) { return false; } //TODO CHAR和JSON类型的字段,getColumnType返回值都是1 ,如果不用CHAR,改用VARCHAR,则可以用上面这行来提高性能。 //return rsmd.getColumnType(position) == 1; if (column.toLowerCase().contains("json")) { return true; } } catch (SQLException e) { e.printStackTrace(); } // List<String> json = config.getJson(); // return json != null && json.contains(lable); return false; } @Override // 重写是为了返回类型从 Statement 改为 PreparedStatement,避免其它方法出错 public PreparedStatement getStatement(@NotNull SQLConfig<T> config) throws Exception { return getStatement(config, null); } @Override public PreparedStatement getStatement(@NotNull SQLConfig<T> config, String sql) throws Exception { if (StringUtil.isEmpty(sql)) { sql = config.getSQL(config.isPrepared()); } PreparedStatement statement; //创建Statement对象 if (config.getMethod() == RequestMethod.POST && config.getId() == null) { //自增id if (config.isOracle()) { // 解决 oracle 使用自增主键 插入获取不到id问题 String[] generatedColumns = {config.getIdKey()}; statement = getConnection(config).prepareStatement(sql, generatedColumns); } else { statement = getConnection(config).prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); } } else if (RequestMethod.isGetMethod(config.getMethod(), true)) { //if (config.isPresto() || config.isTrino()) { // statement = getConnection(config).prepareStatement(sql); // , ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); //} else { // statement = getConnection(config).prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //} if (config.isMySQL() || config.isPostgreSQL() || config.isOracle() || config.isSQLServer() || config.isDb2()) { statement = getConnection(config).prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); } else { statement = getConnection(config).prepareStatement(sql); } } else { statement = getConnection(config).prepareStatement(sql); } List<Object> valueList = config.isPrepared() ? config.getPreparedValueList() : null; // List<Object> withAsExprePreparedValueList = config.isPrepared() ? config.getWithAsExprePreparedValueList() : null; // // // 不同数据库, 预编译mysql使用with-as // if (valueList != null && withAsExprePreparedValueList != null && withAsExprePreparedValueList.size() > 0) { // withAsExprePreparedValueList.addAll(valueList); // valueList = withAsExprePreparedValueList; // // 多条POST/PUT/DELETE语句的情况,需要重新初始化 // config.setWithAsExprePreparedValueList(new ArrayList<>()); // } if (valueList != null && valueList.isEmpty() == false) { for (int i = 0; i < valueList.size(); i++) { statement = setArgument(config, statement, i, valueList.get(i)); } } // statement.close(); return statement; } public PreparedStatement setArgument(@NotNull SQLConfig<T> config, @NotNull PreparedStatement statement, int index, Object value) throws SQLException { //JSON.isBooleanOrNumberOrString(v) 解决 PostgreSQL: Can't infer the SQL type to use for an instance of com.alibaba.fastjson.JSONArray if (apijson.JSON.isBooleanOrNumberOrString(value)) { statement.setObject(index + 1, value); //PostgreSQL JDBC 不支持隐式类型转换 tinyint = varchar 报错 } else { statement.setString(index + 1, value == null ? null : value.toString()); //MySQL setObject 不支持 JSON 类型 } return statement; } protected Map<String, Connection> connectionMap = new HashMap<>(); protected Connection connection; @NotNull @Override public Connection getConnection(@NotNull SQLConfig<T> config) throws Exception { String connectionKey = config.getDatasource() + "-" + config.getDatabase(); connection = connectionMap.get(connectionKey); if (connection == null || connection.isClosed()) { Log.i(TAG, "select connection " + (connection == null ? " = null" : ("isClosed = " + connection.isClosed()))) ; // PostgreSQL 不允许 cross-database connection = DriverManager.getConnection(config.getDBUri(), config.getDBAccount(), config.getDBPassword()); connectionMap.put(connectionKey, connection); } // TDengine 驱动内部事务处理方法都是空实现,手动 commit 无效 int ti = config.isTDengine() ? Connection.TRANSACTION_NONE : getTransactionIsolation(); if (ti != Connection.TRANSACTION_NONE) { //java.sql.SQLException: Transaction isolation level NONE not supported by MySQL begin(ti); } return connection; } //事务处理 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< private int transactionIsolation; @Override public int getTransactionIsolation() { return transactionIsolation; } @Override public void setTransactionIsolation(int transactionIsolation) { this.transactionIsolation = transactionIsolation; } protected Map<Connection, Integer> isolationMap = new LinkedHashMap<>(); @Override public void begin(int transactionIsolation) throws SQLException { Log.d("\n\n" + TAG, "<<<<<<<<<<<<<< TRANSACTION begin transactionIsolation = " + transactionIsolation + " >>>>>>>>>>>>>>>>>>>>>>> \n\n"); // 不做判断,如果掩盖了问题,调用层都不知道为啥事务没有提交成功 // if (connection == null || connection.isClosed()) { // return; // } // 将所有连接设置隔离级别,且禁止自动提交,需要以下代码来 commit/rollback Collection<Connection> connections = connectionMap.values(); if (connections != null) { for (Connection connection : connections) { try { Integer isolation = isolationMap.get(connection); if (isolation == null || isolation != transactionIsolation) { // 只设置一次 Isolation 等级 PG 及 MySQL 某些版本重复设置事务等级会报错 isolationMap.put(connection, transactionIsolation); connection.setTransactionIsolation(transactionIsolation); // 这句导致 TDengine 驱动报错 if (isolation == null) { connection.setAutoCommit(false); // java.sql.SQLException: Can''t call commit when autocommit=true } } } catch (SQLException e) { e.printStackTrace(); } } } } @Override public void rollback() throws SQLException { Log.d("\n\n" + TAG, "<<<<<<<<<<<<<< TRANSACTION rollback >>>>>>>>>>>>>>>>>>>>>>> \n\n"); //权限校验不通过,connection 也不会生成,还是得判断 //不做判断,如果掩盖了问题,调用层都不知道为啥事务没有提交成功 // if (connection == null) { // || connection.isClosed()) { // return; // } // 将所有连接进行回滚 Collection<Connection> connections = connectionMap.values(); if (connections != null) { for (Connection connection : connections) { try { if (connection != null && connection.isClosed() == false) { connection.rollback(); connection.setAutoCommit(true); isolationMap.remove(connection); } } catch (SQLException e) { e.printStackTrace(); } } } } @Override public void rollback(Savepoint savepoint) throws SQLException { Log.d("\n\n" + TAG, "<<<<<<<<<<<<<< TRANSACTION rollback savepoint " + (savepoint == null ? "" : "!") + "= null >>>>>>>>>>>>>>>>>>>>>>> \n\n"); if (savepoint == null) { rollback(); return; } //权限校验不通过,connection 也不会生成,还是得判断 //不做判断,如果掩盖了问题,调用层都不知道为啥事务没有提交成功 // if (connection == null) { // || connection.isClosed()) { // return; // } // 将所有连接进行回滚 Collection<Connection> connections = connectionMap.values(); if (connections != null) { for (Connection connection : connections) { try { if (connection != null && connection.isClosed() == false) { connection.rollback(savepoint); connection.setAutoCommit(true); isolationMap.remove(connection); } } catch (SQLException e) { e.printStackTrace(); } } } } @Override public void commit() throws SQLException { Log.d("\n\n" + TAG, "<<<<<<<<<<<<<< TRANSACTION commit >>>>>>>>>>>>>>>>>>>>>>> \n\n"); //权限校验不通过,connection 也不会生成,还是得判断 //不做判断,如果掩盖了问题,调用层都不知道为啥事务没有提交成功 // if (connection == null) { // || connection.isClosed()) { // return; // } // 将所有连接进行提交 Collection<Connection> connections = connectionMap.values(); if (connections != null) { for (Connection connection : connections) { try { if (connection != null && connection.isClosed() == false) { connection.commit(); isolationMap.remove(connection); } } catch (SQLException e) { e.printStackTrace(); } } } } //事务处理 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /**关闭连接,释放资源 */ @Override public void close() { cacheMap.clear(); cacheMap = null; generatedSQLCount = 0; cachedSQLCount = 0; executedSQLCount = 0; if (connectionMap == null) { return; } Collection<Connection> connections = connectionMap.values(); if (connections != null) { for (Connection connection : connections) { try { if (connection != null && connection.isClosed() == false) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } connectionMap.clear(); connectionMap = null; } @Override public ResultSet executeQuery(@NotNull SQLConfig<T> config, String sql) throws Exception { if (config.isPrepared() == false || config.isTDengine() // TDengine JDBC 不支持 PreparedStatement || (config.isExplain() && (config.isPresto() || config.isTrino()))) { // Presto JDBC 0.277 在 EXPLAIN 模式下预编译值不会替代 ? 占位导致报错 Connection conn = getConnection(config); Statement stt = conn.createStatement(); // Statement stt = config.isTDengine() // ? conn.createStatement() // fix Presto: ResultSet: Exception: set type is TYPE_FORWARD_ONLY, Result set concurrency must be CONCUR_READ_ONLY // : conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); return executeQuery(stt, StringUtil.isEmpty(sql) ? config.getSQL(false) : sql); } // Presto JDBC 0.277 在 EXPLAIN 模式下预编译值不会替代 ? 占位导致报错 PreparedStatement stt = getStatement(config, sql); ResultSet rs = stt.executeQuery(); //PreparedStatement 不用传 SQL // if (config.isExplain() && (config.isSQLServer() || config.isOracle())) { // FIXME 返回的是 boolean 值 rs = stt.getMoreResults(Statement.CLOSE_CURRENT_RESULT); // } return rs; } @Override public int executeUpdate(@NotNull SQLConfig<T> config, String sql) throws Exception { Statement stt; int count; if (config.isTDengine()) { Connection conn = getConnection(config); stt = conn.createStatement(); //stt = config.isTDengine() // ? conn.createStatement() // fix Presto: ResultSet: Exception: set type is TYPE_FORWARD_ONLY, Result set concurrency must be CONCUR_READ_ONLY // : conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); count = stt.executeUpdate(StringUtil.isEmpty(sql) ? config.getSQL(false) : sql); } else { stt = getStatement(config); count = ((PreparedStatement) stt).executeUpdate(); // PreparedStatement 不用传 SQL } if (count <= 0 && config.isHive()) { count = 1; } if (config.getId() == null && config.getMethod() == RequestMethod.POST) { // 自增id ResultSet rs = stt.getGeneratedKeys(); if (rs != null && rs.next()) { config.setId(rs.getLong(1)); } } return count; } }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/orm/AbstractSQLExecutor.java
358
package org.nutz.img; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.Iterator; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import org.nutz.lang.Files; import org.nutz.lang.Lang; import org.nutz.lang.Streams; import org.nutz.lang.Strings; import org.nutz.lang.random.R; import org.nutz.repo.Base64; /** * 对图像操作的简化 API * * @author zozoh([email protected]) */ public class Images { /** * 对一个图像进行旋转 * * @param srcIm * 原图像文件 * @param taIm * 转换后的图像文件 * @param degree * 旋转角度, 90 为顺时针九十度, -90 为逆时针九十度 * @return 旋转后得图像对象 */ public static BufferedImage rotate(Object srcIm, File taIm, int degree) { BufferedImage im = Images.read(srcIm); BufferedImage im2 = Images.rotate(im, degree); Images.write(im2, taIm); return im2; } /** * 对一个图像进行旋转 * * @param srcPath * 原图像文件路径 * @param taPath * 转换后的图像文件路径 * @param degree * 旋转角度, 90 为顺时针九十度, -90 为逆时针九十度 * @return 旋转后得图像对象 */ public static BufferedImage rotate(String srcPath, String taPath, int degree) throws IOException { File srcIm = Files.findFile(srcPath); if (null == srcIm) { throw Lang.makeThrow("Fail to find image file '%s'!", srcPath); } File taIm = Files.createFileIfNoExists(taPath); return rotate(srcIm, taIm, degree); } /** * 对一个图像进行旋转 * * @param image * 图像 * @param degree * 旋转角度, 90 为顺时针九十度, -90 为逆时针九十度 * @return 旋转后得图像对象 */ public static BufferedImage rotate(BufferedImage image, int degree) { int iw = image.getWidth();// 原始图象的宽度 int ih = image.getHeight();// 原始图象的高度 int w = 0; int h = 0; int x = 0; int y = 0; degree = degree % 360; if (degree < 0) { degree = 360 + degree;// 将角度转换到0-360度之间 } double ang = degree * 0.0174532925;// 将角度转为弧度 /** * 确定旋转后的图象的高度和宽度 */ if (degree == 180 || degree == 0 || degree == 360) { w = iw; h = ih; } else if (degree == 90 || degree == 270) { w = ih; h = iw; } else { int d = iw + ih; w = (int) (d * Math.abs(Math.cos(ang))); h = (int) (d * Math.abs(Math.sin(ang))); } x = (w / 2) - (iw / 2);// 确定原点坐标 y = (h / 2) - (ih / 2); BufferedImage rotatedImage = new BufferedImage(w, h, image.getType()); Graphics2D gs = rotatedImage.createGraphics(); gs.fillRect(0, 0, w, h);// 以给定颜色绘制旋转后图片的背景 AffineTransform at = new AffineTransform(); at.rotate(ang, w / 2, h / 2);// 旋转图象 at.translate(x, y); AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); op.filter(image, rotatedImage); image = rotatedImage; return image; } /** * 自动等比缩放一个图片,并将其保存成目标图像文件<br /> * 多余的部分,用给定背景颜色补上<br /> * 如果参数中的宽度或高度为<b>-1</b>的话,着按照指定的高度或宽度对原图等比例缩放图片,不添加背景颜色 * <p> * 图片格式支持 png | gif | jpg | bmp | wbmp * * @param srcIm * 源图像文件对象 * @param taIm * 目标图像文件对象 * @param w * 宽度 * @param h * 高度 * @param bgColor * 背景颜色 * * @return 被转换前的图像对象 * * @throws IOException * 当读写文件失败时抛出 */ public static BufferedImage zoomScale(Object srcIm, File taIm, int w, int h, Color bgColor) throws IOException { BufferedImage old = read(srcIm); BufferedImage im = Images.zoomScale(old, w, h, bgColor); write(im, taIm); return old; } /** * 自动等比缩放一个图片,并将其保存成目标图像文件<br /> * 多余的部分,用给定背景颜色补上<br /> * 如果参数中的宽度或高度为<b>-1</b>的话,着按照指定的高度或宽度对原图等比例缩放图片,不添加背景颜色 * <p> * 图片格式支持 png | gif | jpg | bmp | wbmp * * @param srcPath * 源图像路径 * @param taPath * 目标图像路径,如果不存在,则创建 * @param w * 宽度 * @param h * 高度 * @param bgColor * 背景颜色 * * @return 被转换前的图像对象 * * @throws IOException * 当读写文件失败时抛出 */ public static BufferedImage zoomScale(String srcPath, String taPath, int w, int h, Color bgColor) throws IOException { File srcIm = Files.findFile(srcPath); if (null == srcIm) { throw Lang.makeThrow("Fail to find image file '%s'!", srcPath); } File taIm = Files.createFileIfNoExists(taPath); return zoomScale(srcIm, taIm, w, h, bgColor); } /** * 自动等比缩放一个图片,多余的部分,用给定背景颜色补上<br /> * 如果参数中的宽度或高度为<b>-1</b>的话,着按照指定的高度或宽度对原图等比例缩放图片,不添加背景颜色 * * @param im * 图像对象 * @param w * 宽度 * @param h * 高度 * @param bgColor * 背景颜色 * * @return 被转换后的图像 */ public static BufferedImage zoomScale(BufferedImage im, int w, int h, Color bgColor) { if (w == -1 || h == -1) { return scale(im, w, h); } // 检查背景颜色 // bgColor = null == bgColor ? Color.black : bgColor; // 获得尺寸 int oW = im.getWidth(); int oH = im.getHeight(); float oR = (float) oW / (float) oH; float nR = (float) w / (float) h; int nW, nH, x, y; /* * 缩放 */ // 原图太宽,计算当原图与画布同高时,原图的等比宽度 if (oR > nR) { nW = w; nH = (int) ((w) / oR); x = 0; y = (h - nH) / 2; } // 原图太高 else if (oR < nR) { nH = h; nW = (int) ((h) * oR); x = (w - nW) / 2; y = 0; } // 比例相同 else { nW = w; nH = h; x = 0; y = 0; } // 创建图像 BufferedImage re = new BufferedImage(w, h, im.getType() == 0 ? BufferedImage.TYPE_3BYTE_BGR : im.getType()); Graphics2D gc = re.createGraphics(); if (null != bgColor) { gc.setColor(bgColor); gc.fillRect(0, 0, w, h); } // 绘制图像 gc.drawImage(im, x, y, nW, nH, bgColor, null); // 释放 gc.dispose(); // 返回 return re; } /** * @see #zoomScale(BufferedImage, int, int, Color) */ public static BufferedImage zoomScale(BufferedImage im, int w, int h) { return zoomScale(im, w, h, null); } /** * 自动等比缩放一个图片 * * @param im * 图像对象 * @param w * 宽度 * @param h * 高度 * * @return 被转换后的图像 */ public static BufferedImage scale(BufferedImage im, int w, int h) { // 获得尺寸 int oW = im.getWidth(); int oH = im.getHeight(); int nW = w, nH = h; /* * 缩放 */ // 未指定图像高度,根据原图尺寸计算出高度 if (h == -1) { nH = (int) ((float) w / oW * oH); } // 未指定图像宽度,根据原图尺寸计算出宽度 else if (w == -1) { nW = (int) ((float) h / oH * oW); } // 创建图像 BufferedImage re = new BufferedImage(nW, nH, im.getType()); Graphics2D gc = re.createGraphics(); gc.drawImage(im, 0, 0, nW, nH, null); gc.dispose(); // 返回 return re; } /** * 自动缩放剪切一个图片,令其符合给定的尺寸,并将其保存成目标图像文件 * <p> * 图片格式支持 png | gif | jpg | bmp | wbmp * * @param srcIm * 源图像文件对象 * @param taIm * 目标图像文件对象 * @param w * 宽度 * @param h * 高度 * @return 被转换前的图像对象 * * @throws IOException * 当读写文件失败时抛出 */ public static BufferedImage clipScale(Object srcIm, File taIm, int w, int h) throws IOException { BufferedImage old = read(srcIm); BufferedImage im = Images.clipScale(old, w, h); write(im, taIm); return old; } /** * 自动缩放剪切一个图片,令其符合给定的尺寸,并将其保存到目标图像路径 * <p> * 图片格式支持 png | gif | jpg | bmp | wbmp * * @param srcPath * 源图像路径 * @param taPath * 目标图像路径,如果不存在,则创建 * @param w * 宽度 * @param h * 高度 * * @return 被转换前的图像对象 * * @throws IOException * 当读写文件失败时抛出 */ public static BufferedImage clipScale(String srcPath, String taPath, int w, int h) throws IOException { File srcIm = Files.findFile(srcPath); if (null == srcIm) { throw Lang.makeThrow("Fail to find image file '%s'!", srcPath); } File taIm = Files.createFileIfNoExists(taPath); return clipScale(srcIm, taIm, w, h); } public static BufferedImage clipScale(Object srcIm, int[] startPoint, int[] endPoint) { // 计算给定坐标后的图片的尺寸 int width = endPoint[0] - startPoint[0]; int height = endPoint[1] - startPoint[1]; BufferedImage old = read(srcIm); BufferedImage im = Images.clipScale(old.getSubimage(startPoint[0], startPoint[1], width, height), width, height); return im; } /** * 根据给定的起始坐标点与结束坐标点来剪切一个图片,令其符合给定的尺寸,并将其保存成目标图像文件 * <p> * 图片格式支持 png | gif | jpg | bmp | wbmp * * @param srcIm * 源图像文件对象 * @param taIm * 目标图像文件对象 * @param startPoint * 起始坐标点,其值[x, y]为相对原图片左上角的坐标 * @param endPoint * 结束坐标点,其值[x, y]为相对原图片左上角的坐标 * @return 被转换前的图像对象 * * @throws IOException * 当读写文件失败时抛出 */ public static BufferedImage clipScale(Object srcIm, File taIm, int[] startPoint, int[] endPoint) throws IOException { BufferedImage old = read(srcIm); BufferedImage im = clipScale(old, startPoint, endPoint); write(im, taIm); return old; } /** * 根据给定的起始坐标点与结束坐标点来剪切一个图片,令其符合给定的尺寸,并将其保存成目标图像文件 * <p> * 图片格式支持 png | gif | jpg | bmp | wbmp * * @param srcPath * 源图像文件对象 * @param taPath * 目标图像文件对象 * @param startPoint * 起始坐标点,其值[x, y]为相对原图片左上角的坐标 * @param endPoint * 结束坐标点,其值[x, y]为相对原图片左上角的坐标 * @return 被转换前的图像对象 * * @throws IOException * 当读写文件失败时抛出 */ public static BufferedImage clipScale(String srcPath, String taPath, int[] startPoint, int[] endPoint) throws IOException { File srcIm = Files.findFile(srcPath); if (null == srcIm) { throw Lang.makeThrow("Fail to find image file '%s'!", srcPath); } File taIm = Files.createFileIfNoExists(taPath); return clipScale(srcIm, taIm, startPoint, endPoint); } /** * 自动缩放剪切一个图片,令其符合给定的尺寸 * <p> * 如果图片太大,则将其缩小,如果图片太小,则将其放大,多余的部分被裁减 * * @param im * 图像对象 * @param w * 宽度 * @param h * 高度 * @return 被转换后的图像 */ public static BufferedImage clipScale(BufferedImage im, int w, int h) { // 获得尺寸 int oW = im.getWidth(); int oH = im.getHeight(); float oR = (float) oW / (float) oH; float nR = (float) w / (float) h; int nW, nH, x, y; /* * 裁减 */ // 原图太宽,计算当原图与画布同高时,原图的等比宽度 if (oR > nR) { nW = (h * oW) / oH; nH = h; x = (w - nW) / 2; y = 0; } // 原图太长 else if (oR < nR) { nW = w; nH = (w * oH) / oW; x = 0; y = (h - nH) / 2; } // 比例相同 else { nW = w; nH = h; x = 0; y = 0; } // 创建图像 BufferedImage re = new BufferedImage(w, h, ColorSpace.TYPE_RGB); re.createGraphics().drawImage(im, x, y, nW, nH, Color.black, null); // 返回 return re; } /** * 水平翻转一张图片 * * @param srcIm * 源图片 * @return 被转换后的图像 */ public static BufferedImage flipHorizontal(Object srcIm) { BufferedImage im1 = read(srcIm); int w = im1.getWidth(); int h = im1.getHeight(); BufferedImage flipImage = new BufferedImage(w, h, im1.getType()); Graphics2D gs = flipImage.createGraphics(); gs.drawImage(im1, 0, 0, w, h, w, 0, 0, h, null); gs.dispose(); return flipImage; } /** * 水平翻转一张图片 * * @param srcIm * 源图片 * @param tarIm * 目标图片 * @return 被转换后的图像 */ public static BufferedImage flipHorizontal(Object srcIm, File tarIm) { BufferedImage flipImage = flipHorizontal(srcIm); Images.write(flipImage, tarIm); return flipImage; } /** * 垂直翻转一张图片 * * @param srcIm * 源图片 * @return 被转换后的图像 */ public static BufferedImage flipVertical(Object srcIm) { BufferedImage im1 = read(srcIm); int w = im1.getWidth(); int h = im1.getHeight(); BufferedImage flipImage = new BufferedImage(w, h, im1.getType()); Graphics2D gs = flipImage.createGraphics(); gs.drawImage(im1, 0, 0, w, h, 0, h, w, 0, null); gs.dispose(); return flipImage; } /** * 垂直翻转一张图片 * * @param srcIm * 源图片 * @param tarIm * 目标图片 * @return 被转换后的图像 */ public static BufferedImage flipVertical(Object srcIm, File tarIm) { BufferedImage flipImage = flipVertical(srcIm); Images.write(flipImage, tarIm); return flipImage; } /** * 扭曲图片 * * @param srcIm * 源图片 * @param twistRank * 扭曲程度,默认为1,数值越大扭曲程度越高 * @param bgColor * 扭曲后露出的底图填充色,一般选择要源图片的背景色 * @return 被扭曲后的图片 */ public static BufferedImage twist(Object srcIm, double twistRank, String bgColor) { if (twistRank <= 0) { twistRank = 1; } BufferedImage bufImg = read(srcIm); double period = R.random(0, 7) + 3;// 波形的幅度倍数,越大扭曲的程序越高,一般为3 double phase = R.random(0, 6);// 波形的起始相位,取值区间(0-2*PI) int width = bufImg.getWidth(); int height = bufImg.getHeight(); BufferedImage tarIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gc = tarIm.createGraphics(); gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gc.setBackground(Strings.isBlank(bgColor) ? Colors.randomColor() : Colors.as(bgColor)); gc.clearRect(0, 0, width, height); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int nX = pos4twist(twistRank, phase, period, height, i, j); int nY = j; if (nX >= 0 && nX < width && nY >= 0 && nY < height) { tarIm.setRGB(nX, nY, bufImg.getRGB(i, j)); } } } return tarIm; } // 扭曲相关计算, 后面的参数有两种组合 // 1. height, x, y // 2. width, y, x private static int pos4twist(double rank, double phase, double period, int hOrW, int xOrY, int yOrX) { double dyOrX = Math.PI * rank * yOrX / hOrW + phase; double dxOrY = Math.sin(dyOrX); return xOrY + (int) (dxOrY * period); } public static final int WATERMARK_TOP_LEFT = 1; public static final int WATERMARK_TOP_CENTER = 2; public static final int WATERMARK_TOP_RIGHT = 3; public static final int WATERMARK_CENTER_LEFT = 4; public static final int WATERMARK_CENTER = 5; public static final int WATERMARK_CENTER_RIGHT = 6; public static final int WATERMARK_BOTTOM_LEFT = 7; public static final int WATERMARK_BOTTOM_CENTER = 8; public static final int WATERMARK_BOTTOM_RIGHT = 9; /** * 为图片添加水印,可以设定透明度与水印的位置 * <p> * 水印位置默认支持9种,分别是: * * TOP_LEFT | TOP_CENTER | TOP_RIGHT CENTER_LEFT | CENTER | CENTER_RIGHT * BOTTOM_LEFT | BOTTOM_CENTER | BOTTOM_RIGHT * * * @param srcIm * 源图片 * @param markIm * 水印图片 * @param opacity * 透明度, 要求大于0小于1, 默认为0.5f * @param pos * 共9个位置,请使用 Images.WATERMARK_{XXX} 进行设置,默认为 * Images.WATERMARK_CENTER * @param margin * 水印距离四周的边距 默认为0 * @return */ public static BufferedImage addWatermark(Object srcIm, Object markIm, float opacity, int pos, int margin) { BufferedImage im1 = read(srcIm); BufferedImage im2 = read(markIm); int cw = im1.getWidth(); int ch = im1.getHeight(); int mw = im2.getWidth(); int mh = im2.getHeight(); if (opacity > 1 || opacity <= 0) { opacity = 0.5f; } if (pos > 9 || pos <= 0) { pos = 5; } // 计算水印位置 int px = 0; int py = 0; switch (pos) { case WATERMARK_TOP_LEFT: px = margin; py = margin; break; case WATERMARK_TOP_CENTER: px = (cw - mw) / 2; py = margin; break; case WATERMARK_TOP_RIGHT: px = cw - mw - margin; py = margin; break; case WATERMARK_CENTER_LEFT: px = margin; py = (ch - mh) / 2; break; case WATERMARK_CENTER: px = (cw - mw) / 2; py = (ch - mh) / 2; break; case WATERMARK_CENTER_RIGHT: px = cw - mw - margin; py = (ch - mh) / 2; break; case WATERMARK_BOTTOM_LEFT: px = margin; py = ch - mh - margin; break; case WATERMARK_BOTTOM_CENTER: px = (cw - mw) / 2; py = ch - mh - margin; break; case WATERMARK_BOTTOM_RIGHT: px = cw - mw - margin; py = ch - mh - margin; break; default: } // 添加水印 Graphics2D gs = im1.createGraphics(); gs.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, opacity)); gs.drawImage(im2, px, py, null); gs.dispose(); return im1; } /** * 获取灰度图像 * * @param srcIm * 源图片 * @return 灰度图片 */ public static BufferedImage grayImage(Object srcIm) { BufferedImage srcImage = read(srcIm); BufferedImage grayImage = new BufferedImage(srcImage.getWidth(), srcImage.getHeight(), srcImage.getType()); for (int i = 0; i < srcImage.getWidth(); i++) { for (int j = 0; j < srcImage.getHeight(); j++) { grayImage.setRGB(i, j, Colors.getGray(srcImage, i, j)); } } return grayImage; } /** * 实现两张图片的正片叠底效果 * * @param bgIm * 背景图 * @param itemIm * 上层图 * @param x * 上层图横坐标 * @param y * 上层图横坐标 * @return 正片叠底后的图片 */ public static BufferedImage multiply(Object bgIm, Object itemIm, int x, int y) { BufferedImage viewportImage = read(bgIm); BufferedImage itemImage = read(itemIm); BufferedImage muImage = new BufferedImage(viewportImage.getWidth(), viewportImage.getHeight(), viewportImage.getType()); // 背景图为视口范围,上层图不能超过视口进行绘制, 只有重合部分进行计算叠底 int xMin = x; int xMax = x + itemImage.getWidth(); int yMin = y; int yMax = y + itemImage.getHeight(); for (int i = 0; i < viewportImage.getWidth(); i++) { for (int j = 0; j < viewportImage.getHeight(); j++) { int rgb = 0; // 判断是否重合 if (i >= xMin && i < xMax && j >= yMin && j < yMax) { // 获取两个图rgb值 int vpRGB = viewportImage.getRGB(i, j); int imRGB = itemImage.getRGB(i - x, j - y); rgb = Colors.getMultiply(vpRGB, imRGB); } else { rgb = viewportImage.getRGB(i, j); } muImage.setRGB(i, j, rgb); } } return muImage; } /** * 根据亮度值(灰度值)来自动计算哪些像素需要扣掉。 * * <br> * * 适合前后亮度差别特别明显的图片,比如背景全黑。 * * @param srcIm * 源图片 * @return 抠图后图片对象 */ public static BufferedImage cutoutByLuminance(Object srcIm) { return cutoutByChannel(srcIm, -1); } /** * 根据指定通道的亮度值(灰度值)来自动计算哪些像素需要扣掉。 * * @param srcIm * 源图片 * @param channel * 通道编号,0:red 1:green 2:blue 其他:亮度 * @return 抠图后图片对象 */ public static BufferedImage cutoutByChannel(Object srcIm, int channel) { BufferedImage srcImage = read(srcIm); BufferedImage resultImage = new BufferedImage(srcImage.getWidth(), srcImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); // 开始绘制 for (int i = 0; i < srcImage.getWidth(); i++) { for (int j = 0; j < srcImage.getHeight(); j++) { int pixel = srcImage.getRGB(i, j); int alpha = 0; switch (channel) { case CHANNEL_RED: alpha = Colors.getRGB(pixel)[0]; break; case CHANNEL_GREEN: alpha = Colors.getRGB(pixel)[1]; break; case CHANNEL_BLUE: alpha = Colors.getRGB(pixel)[2]; break; default: alpha = Colors.getLuminance(srcImage, i, j); break; } pixel = (alpha << 24) & 0xff000000 | (pixel & 0x00ffffff); resultImage.setRGB(i, j, pixel); } } return resultImage; } /** * 指定的像素点为背景色参考,在指定范围内的颜色将设置为透明。 * * </br> * !!! 该方法适合背景与前景相差特别大的图片,最好是背景颜色基本一致,前景背景有明显分隔界限。 * * * @param srcIm * 源图片 * @param x * 采样像素点横坐标 * @param y * 采样像素点纵坐标 * @param range * 采样像素可允许色差范围,数值越大去掉的颜色范围越多 * @return 抠图后图片对象 * */ public static BufferedImage cutoutByPixel(Object srcIm, int x, int y, int range) { BufferedImage srcImage = read(srcIm); BufferedImage resultImage = new BufferedImage(srcImage.getWidth(), srcImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); // 获取选样点 int[] srgb = Colors.getRGB(srcImage.getRGB(x, y)); // 开始绘制 for (int i = 0; i < srcImage.getWidth(); i++) { for (int j = 0; j < srcImage.getHeight(); j++) { int pixel = srcImage.getRGB(i, j); int[] crgb = Colors.getRGB(pixel); int alpha = 255; // 范围内的都干掉 if (inRangeColor(srgb, crgb, range)) { alpha = 0; } // 范围大一点点的,可能就需要半透明来处理了 else if (inRangeColor(srgb, crgb, (int) (range * 1.5))) { alpha = 64; } // 范围大一点点的,可能就需要半透明来处理了 else if (inRangeColor(srgb, crgb, range * 2)) { alpha = 128; } // 不在范围的原样输出吧 else { alpha = Colors.getAlpha(pixel); } pixel = (alpha << 24) & 0xff000000 | (pixel & 0x00ffffff); resultImage.setRGB(i, j, pixel); } } return resultImage; } private static boolean inRangeColor(int[] srgb, int[] crgb, int range) { // r if (crgb[0] >= srgb[0] - range && crgb[0] <= srgb[0] + range) { // g if (crgb[1] >= srgb[01] - range && crgb[1] <= srgb[1] + range) { // b if (crgb[2] >= srgb[2] - range && crgb[2] <= srgb[2] + range) { return true; } } } return false; } public static final int CHANNEL_RED = 0; public static final int CHANNEL_GREEN = 1; public static final int CHANNEL_BLUE = 2; /** * 获取三原色通道图片 * * @param srcIm * 源图片 * @param channel * 通道编号,0:red 1:green 2:blue * @return 单一通道图片 */ public static BufferedImage channelImage(Object srcIm, int channel) { BufferedImage srcImage = read(srcIm); BufferedImage rcImage = new BufferedImage(srcImage.getWidth(), srcImage.getHeight(), srcImage.getType()); for (int i = 0; i < srcImage.getWidth(); i++) { for (int j = 0; j < srcImage.getHeight(); j++) { int r = Colors.getRGB(srcImage, i, j)[channel]; rcImage.setRGB(i, j, new Color(r, r, r).getRGB()); } } return rcImage; } /** * 将一个图片文件读入内存 * * @param img * 图片文件 * @return 图片对象 */ public static BufferedImage read(Object img) { try { if (img instanceof BufferedImage) { return (BufferedImage) img; } if (img instanceof CharSequence) { return ImageIO.read(Files.checkFile(img.toString())); } if (img instanceof File) { return ImageIO.read((File) img); } if(img instanceof byte[]) { return ImageIO.read(new ByteArrayInputStream((byte[])img)); } if (img instanceof URL) { img = ((URL) img).openStream(); } if (img instanceof InputStream) { File tmp = File.createTempFile("nutz_img", ".jpg"); Files.write(tmp, img); try { return read(tmp); } finally { tmp.delete(); } } throw Lang.makeThrow("Unkown img info!! --> " + img); } catch (IOException e) { try { InputStream in = null; if (img instanceof File) { in = new FileInputStream((File) img); } else if (img instanceof URL) { in = ((URL) img).openStream(); } else if (img instanceof InputStream) { in = (InputStream) img; } if (in != null) { return readJpeg(in); } } catch (IOException e2) { e2.fillInStackTrace(); } return null; // throw Lang.wrapThrow(e); } } /** * 将内存中一个图片写入目标文件 * * @param im * 图片对象 * @param targetFile * 目标文件,根据其后缀,来决定写入何种图片格式 */ public static void write(RenderedImage im, File targetFile) { try { ImageIO.write(im, Files.getSuffixName(targetFile), targetFile); } catch (IOException e) { throw Lang.wrapThrow(e); } } /** * 将内存中的一个写入输出流 * * @param im * 图片对象 * @param imFormat * 图片格式 * @param out * 输出流 */ public static void write(RenderedImage im, String imFormat, OutputStream out) { try { ImageIO.write(im, imFormat, out); } catch (IOException e) { throw Lang.wrapThrow(e); } } /** * @see #write(RenderedImage, String, OutputStream) */ public static void writeAndClose(RenderedImage im, String imFormat, OutputStream out) { try { ImageIO.write(im, imFormat, out); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(out); } } /** * 写入一个 JPG 图像 * * @param im * 图像对象 * @param targetJpg * 目标输出 JPG 图像文件 * @param quality * 质量 0.1f ~ 1.0f */ public static void writeJpeg(RenderedImage im, Object targetJpg, float quality) { ImageWriter writer = null; try { writer = ImageIO.getImageWritersBySuffix("jpg").next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality); ImageOutputStream os = ImageIO.createImageOutputStream(targetJpg); writer.setOutput(os); writer.write((IIOMetadata) null, new IIOImage(im, null, null), param); os.flush(); os.close(); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { if (writer != null) { try { writer.dispose(); } catch (Throwable e) {} } } } /** * 尝试读取JPEG文件的高级方法,可读取32位的jpeg文件 * <p/> * 来自: * http://stackoverflow.com/questions/2408613/problem-reading-jpeg-image- * using-imageio-readfile-file * */ private static BufferedImage readJpeg(InputStream in) throws IOException { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG"); ImageReader reader = null; while (readers.hasNext()) { reader = readers.next(); if (reader.canReadRaster()) { break; } } if (reader == null) { return null; } try { ImageInputStream input = ImageIO.createImageInputStream(in); reader.setInput(input); // Read the image raster Raster raster = reader.readRaster(0, null); BufferedImage image = createJPEG4(raster); ByteArrayOutputStream out = new ByteArrayOutputStream(); writeJpeg(image, out, 1); out.flush(); return read(new ByteArrayInputStream(out.toByteArray())); } finally { try { reader.dispose(); } catch (Throwable e) {} } } /** * Java's ImageIO can't process 4-component images and Java2D can't apply * AffineTransformOp either, so convert raster data to RGB. Technique due to * MArk Stephens. Free for any use. */ private static BufferedImage createJPEG4(Raster raster) { int w = raster.getWidth(); int h = raster.getHeight(); byte[] rgb = new byte[w * h * 3]; float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null); float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null); float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null); float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null); for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) { float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i]; double val = y + 1.402 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y + 1.772 * (cb - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); } raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[]{0, 1, 2}, null); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); return new BufferedImage(cm, (WritableRaster) raster, true, null); } /** * 生成该图片对应的 Base64 编码的字符串 * * @param targetFile * 图片文件 * @return 图片对应的 Base64 编码的字符串 */ public static String encodeBase64(String targetFile) { return encodeBase64(new File(targetFile)); } /** * 生成该图片对应的 Base64 编码的字符串 * * @param targetFile * 图片文件 * @return 图片对应的 Base64 编码的字符串 */ public static String encodeBase64(File targetFile) { BufferedImage image = null; try { image = ImageIO.read(targetFile); } catch (IOException e) { throw Lang.wrapThrow(e); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); image.flush(); try { ImageIO.write(image, Files.getSuffixName(targetFile), bos); bos.flush(); bos.close(); } catch (IOException e) { throw Lang.wrapThrow(e); } byte[] bImage = baos.toByteArray(); return Base64.encodeToString(bImage, false); } /** * 在一个RGB画布上重新绘制Image,解决CMYK图像偏色的问题 */ public static BufferedImage redraw(BufferedImage img, Color bg) { BufferedImage rgbImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR); Graphics2D g2d = rgbImage.createGraphics(); g2d.drawImage(img, 0, 0, bg, null); g2d.dispose(); return rgbImage; } /** * 文字生成图片,黑底白字。 * * @param content * 文字内容 * @return 图像 */ public static BufferedImage createText(String content) { return createText(content, 0, 0, null, null, null, 0, Font.PLAIN); } /** * 文字生成图片 * * @param content * 文字内容 * @param width * 图片宽度,默认256 * @param height * 图片高度,默认256 * @param fontColor * 文字颜色 默认白色 * @param bgColor * 背景颜色 默认黑色 * @param fontName * 字体名称 需运行环境中已有该字体名称 * @param fontSize * 字体大小 * @param fontStyle * 字体样式 Font.PLAIN || Font.BOLD || Font.ITALIC * @return 图像 */ public static BufferedImage createText(String content, int width, int height, String fontColor, String bgColor, String fontName, int fontSize, int fontStyle) { // 处理下参数 if (Strings.isBlank(content)) { return null; } if (width <= 0) { width = 256; } if (height <= 0) { height = 256; } if (Strings.isBlank(fontColor)) { fontColor = "#FFF"; } if (Strings.isBlank(bgColor)) { bgColor = "#000"; } if (fontSize <= 0) { fontSize = height / 2; } if (fontStyle < 0 || fontStyle > 2) { fontStyle = Font.BOLD; } // 准备 BufferedImage im; Graphics2D gc; Color colorFont = Colors.as(fontColor); Color colorBg = Colors.as(bgColor); // 判断图片格式 int imageType = BufferedImage.TYPE_INT_RGB; if (colorFont.getAlpha() < 255 || colorBg.getAlpha() < 255) { imageType = BufferedImage.TYPE_INT_ARGB; } // 生成背景 im = new BufferedImage(width, height, imageType); gc = im.createGraphics(); gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gc.setBackground(colorBg); gc.clearRect(0, 0, width, height); // 写入文字 Font cFont = Fonts.get(fontName, fontStyle, fontSize); gc.setColor(colorFont); gc.setFont(cFont); FontMetrics cFontM = gc.getFontMetrics(cFont); int cW = cFontM.stringWidth(content); int ascent = cFontM.getAscent(); // 取得Ascent int descent = cFontM.getDescent(); // 取得Descent int x, y; x = width / 2 - cW / 2; y = (height - (ascent + descent)) / 2 + ascent; gc.drawString(content, x, y); return im; } /** * 根据名字生成头像,英文采用第一个字母,中文2个字使用2个字,超过2个字采用第一个字 * * @param name * 名字 * @return 头像 */ public static BufferedImage createAvatar(String name) { return createAvatar(name, 0, null, null, null, 0, Font.BOLD); } /** * 根据名字生成头像,英文采用第一个字母,中文2个字使用2个字,超过2个字采用第一个字 * * @param name * 名字 * @param size * 图片大小,默认256 * @param fontColor * 文字颜色 默认白色 * @param bgColor * 背景颜色 默认黑色 * @param fontName * 字体名称 需运行环境中已有该字体名称 * @param fontSize * 字体大小 * @param fontStyle * 字体样式 Font.PLAIN || Font.BOLD || Font.ITALIC * @return 头像 */ public static BufferedImage createAvatar(String name, int size, String fontColor, String bgColor, String fontName, int fontSize, int fontStyle) { // 检查输入项目 if (Strings.isBlank(name)) { return null; } // 分析要写入的文字 String content = name; if (name.length() > 2) { content = ("" + name.charAt(0)); } content = content.toUpperCase(); return createText(content, size, size, fontColor, bgColor, fontName, fontSize, fontStyle); } /** * 根据指定文字内容,生成验证码,字体颜色随机变化。 * * @param content * 文字内容 * @return 图像 */ public static BufferedImage createCaptcha(String content) { return createCaptcha(content, 0, 0, null, "FFF", null); } /** * 根据指定文字内容,生成验证码 * * @param content * 文字内容 * @param width * 图片宽度 * @param height * 图片高度 * @param fontColor * 文字颜色 默认黑色 * @param bgColor * 背景颜色 默认白色 * @return 图像 */ public static BufferedImage createCaptcha(String content, int width, int height, String fontColor, String bgColor, String fontName) { // 处理下参数 if (Strings.isBlank(content)) { return null; } boolean isChinese = Strings.isChineseCharacter(content.charAt(0)); if (width <= 0) { // 中文字体的话,间距需要多一些 width = content.length() * (isChinese ? 25 : 20) + 20; } if (height <= 0) { height = 30; } Color userColor = Strings.isBlank(fontColor) ? null : Colors.as(fontColor); Color colorBg = Strings.isBlank(bgColor) ? Colors.randomColor() : Colors.as(bgColor); // 生成背景 BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gc = im.createGraphics(); gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gc.setBackground(colorBg); gc.clearRect(0, 0, width, height); // 加入干扰线 for (int i = 0; i < 7; i++) { gc.setColor(userColor == null ? Colors.randomColor(5, 250) : userColor); int x = R.random(0, width); int y = R.random(0, height); int x1 = R.random(0, width); int y1 = R.random(0, height); gc.drawLine(x, y, x1, y1); } // 写入文字 int rx = 10; int ry = isChinese ? height - 8 : height - 10; for (int i = 0; i < content.length(); i++) { int fontStyle = R.random(0, 3); int fontSize = R.random(height - 10, height - 5); Font textFont = Strings.isBlank(fontName) ? Fonts.random(fontStyle, fontSize) : Fonts.get(fontName, fontStyle, fontSize); gc.setColor(userColor == null ? Colors.randomColor(10, 250) : userColor); gc.setFont(textFont); // 设置字体旋转角度 int degree = R.random(0, 64) % 30; // 正向角度 gc.rotate(degree * Math.PI / 180, rx, ry); gc.drawString(content.charAt(i) + "", rx, ry); // 反向角度 gc.rotate(-degree * Math.PI / 180, rx, ry); rx += (isChinese ? 5 : 0) + width / (content.length() + 2); } // 图像扭曲 im = twist(im, 1, bgColor); return im; } }
nutzam/nutz
src/org/nutz/img/Images.java
359
package org.nutz.lang; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintStream; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.lang.management.ManagementFactory; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Queue; import java.util.Set; import java.util.regex.Pattern; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.servlet.http.HttpServletRequest; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.nutz.castor.Castors; import org.nutz.castor.FailToCastObjectException; import org.nutz.dao.entity.annotation.Column; import org.nutz.json.Json; import org.nutz.lang.reflect.ReflectTool; import org.nutz.lang.stream.StringInputStream; import org.nutz.lang.stream.StringOutputStream; import org.nutz.lang.stream.StringWriter; import org.nutz.lang.util.Context; import org.nutz.lang.util.NutMap; import org.nutz.lang.util.NutType; import org.nutz.lang.util.Regex; import org.nutz.lang.util.SimpleContext; /** * 这些帮助函数让 Java 的某些常用功能变得更简单 * * @author zozoh([email protected]) * @author wendal([email protected]) * @author bonyfish([email protected]) * @author wizzer([email protected]) */ public abstract class Lang { public static int HASH_BUFF_SIZE = 16 * 1024; private static final Pattern IPV4_PATTERN = Pattern.compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); private static final Pattern IPV6_STD_PATTERN = Pattern.compile("^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"); private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile("^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$"); public static boolean isIPv4Address(final String input) { return IPV4_PATTERN.matcher(input).matches(); } public static boolean isIPv6StdAddress(final String input) { return IPV6_STD_PATTERN.matcher(input).matches(); } public static boolean isIPv6HexCompressedAddress(final String input) { return IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches(); } public static boolean isIPv6Address(final String input) { return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input); } public static ComboException comboThrow(Throwable... es) { ComboException ce = new ComboException(); for (Throwable e : es) ce.add(e); return ce; } /** * 生成一个未实现的运行时异常 * * @return 一个未实现的运行时异常 */ public static RuntimeException noImplement() { return new RuntimeException("Not implement yet!"); } /** * 生成一个不可能的运行时异常 * * @return 一个不可能的运行时异常 */ public static RuntimeException impossible() { return new RuntimeException("r u kidding me?! It is impossible!"); } /** * 根据格式化字符串,生成运行时异常 * * @param format * 格式 * @param args * 参数 * @return 运行时异常 */ public static RuntimeException makeThrow(String format, Object... args) { return new RuntimeException(String.format(format, args)); } /** * 根据格式化字符串,生成一个指定的异常。 * * @param classOfT * 异常类型, 需要有一个字符串为参数的构造函数 * @param format * 格式 * @param args * 参数 * @return 异常对象 */ @SuppressWarnings("unchecked") public static <T extends Throwable> T makeThrow(Class<T> classOfT, String format, Object... args) { if (classOfT == RuntimeException.class) return (T) new RuntimeException(String.format(format, args)); return Mirror.me(classOfT).born(String.format(format, args)); } /** * 将抛出对象包裹成运行时异常,并增加自己的描述 * * @param e * 抛出对象 * @param fmt * 格式 * @param args * 参数 * @return 运行时异常 */ public static RuntimeException wrapThrow(Throwable e, String fmt, Object... args) { return new RuntimeException(String.format(fmt, args), e); } /** * 用运行时异常包裹抛出对象,如果抛出对象本身就是运行时异常,则直接返回。 * <p> * 如果是 InvocationTargetException,那么将其剥离,只包裹其 TargetException * * @param e * 抛出对象 * @return 运行时异常 */ public static RuntimeException wrapThrow(Throwable e) { if (e instanceof RuntimeException) return (RuntimeException) e; if (e instanceof InvocationTargetException) return wrapThrow(((InvocationTargetException) e).getTargetException()); return new RuntimeException(e); } /** * 用一个指定可抛出类型来包裹一个抛出对象。这个指定的可抛出类型需要有一个构造函数 接受 Throwable 类型的对象 * * @param e * 抛出对象 * @param wrapper * 包裹类型 * @return 包裹后对象 */ @SuppressWarnings("unchecked") public static <T extends Throwable> T wrapThrow(Throwable e, Class<T> wrapper) { if (wrapper.isAssignableFrom(e.getClass())) return (T) e; return Mirror.me(wrapper).born(e); } public static Throwable unwrapThrow(Throwable e) { if (e == null) return null; if (e instanceof InvocationTargetException) { InvocationTargetException itE = (InvocationTargetException) e; if (itE.getTargetException() != null) return unwrapThrow(itE.getTargetException()); } if (e instanceof RuntimeException && e.getCause() != null) return unwrapThrow(e.getCause()); return e; } public static boolean isCauseBy(Throwable e, Class<? extends Throwable> causeType) { if (e.getClass() == causeType) return true; Throwable cause = e.getCause(); if (null == cause) return false; return isCauseBy(cause, causeType); } /** * 判断两个对象是否相等。 这个函数用处是: * <ul> * <li>可以容忍 null * <li>可以容忍不同类型的 Number * <li>对数组,集合, Map 会深层比较 * </ul> * 当然,如果你重写的 equals 方法会优先 * * @param a0 * 比较对象1 * @param a1 * 比较对象2 * @return 是否相等 */ public static boolean equals(Object a0, Object a1) { if (a0 == a1) return true; if (a0 == null && a1 == null) return true; if (a0 == null || a1 == null) return false; // 简单的判断是否等于 if (a0.equals(a1)) return true; Mirror<?> mi = Mirror.me(a0); // 简单类型,变字符串比较,或者正则表达式 if (mi.isSimple() || mi.is(Pattern.class)) { return a0.toString().equals(a1.toString()); } // 如果类型就不能互相转换,那么一定是错的 if (!a0.getClass().isAssignableFrom(a1.getClass()) && !a1.getClass().isAssignableFrom(a0.getClass())) return false; // Map if (a0 instanceof Map && a1 instanceof Map) { Map<?, ?> m1 = (Map<?, ?>) a0; Map<?, ?> m2 = (Map<?, ?>) a1; if (m1.size() != m2.size()) return false; for (Entry<?, ?> e : m1.entrySet()) { Object key = e.getKey(); if (!m2.containsKey(key) || !equals(m1.get(key), m2.get(key))) return false; } return true; } // 数组 else if (a0.getClass().isArray() && a1.getClass().isArray()) { int len = Array.getLength(a0); if (len != Array.getLength(a1)) return false; for (int i = 0; i < len; i++) { if (!equals(Array.get(a0, i), Array.get(a1, i))) return false; } return true; } // 集合 else if (a0 instanceof Collection && a1 instanceof Collection) { Collection<?> c0 = (Collection<?>) a0; Collection<?> c1 = (Collection<?>) a1; if (c0.size() != c1.size()) return false; Iterator<?> it0 = c0.iterator(); Iterator<?> it1 = c1.iterator(); while (it0.hasNext()) { Object o0 = it0.next(); Object o1 = it1.next(); if (!equals(o0, o1)) return false; } return true; } // 一定不相等 return false; } /** * 判断一个数组内是否包括某一个对象。 它的比较将通过 equals(Object,Object) 方法 * * @param array * 数组 * @param ele * 对象 * @return true 包含 false 不包含 */ public static <T> boolean contains(T[] array, T ele) { if (null == array) return false; for (T e : array) { if (equals(e, ele)) return true; } return false; } /** * 从一个文本输入流读取所有内容,并将该流关闭 * * @param reader * 文本输入流 * @return 输入流所有内容 */ public static String readAll(Reader reader) { if (!(reader instanceof BufferedReader)) reader = new BufferedReader(reader); try { StringBuilder sb = new StringBuilder(); char[] data = new char[64]; int len; while (true) { if ((len = reader.read(data)) == -1) break; sb.append(data, 0, len); } return sb.toString(); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(reader); } } /** * 将一段字符串写入一个文本输出流,并将该流关闭 * * @param writer * 文本输出流 * @param str * 字符串 */ public static void writeAll(Writer writer, String str) { try { writer.write(str); writer.flush(); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(writer); } } /** * 根据一段文本模拟出一个输入流对象 * * @param cs * 文本 * @return 输出流对象 */ public static InputStream ins(CharSequence cs) { return new StringInputStream(cs); } /** * 根据一段文本模拟出一个文本输入流对象 * * @param cs * 文本 * @return 文本输出流对象 */ public static Reader inr(CharSequence cs) { return new StringReader(cs.toString()); } /** * 根据一个 StringBuilder 模拟一个文本输出流对象 * * @param sb * StringBuilder 对象 * @return 文本输出流对象 */ public static Writer opw(StringBuilder sb) { return new StringWriter(sb); } /** * 根据一个 StringBuilder 模拟一个输出流对象 * * @param sb * StringBuilder 对象 * @return 输出流对象 */ public static StringOutputStream ops(StringBuilder sb) { return new StringOutputStream(sb); } /** * 较方便的创建一个数组,比如: * * <pre> * String[] strs = Lang.array("A", "B", "A"); => ["A","B","A"] * </pre> * * @param eles * 可变参数 * @return 数组对象 */ public static <T> T[] array(T... eles) { return eles; } /** * 较方便的创建一个没有重复的数组,比如: * * <pre> * String[] strs = Lang.arrayUniq("A","B","A"); => ["A","B"] * String[] strs = Lang.arrayUniq(); => null * </pre> * * 返回的顺序会遵循输入的顺序 * * @param eles * 可变参数 * @return 数组对象 */ @SuppressWarnings("unchecked") public static <T> T[] arrayUniq(T... eles) { if (null == eles || eles.length == 0) return null; // 记录重复 HashSet<T> set = new HashSet<T>(eles.length); for (T ele : eles) { set.add(ele); } // 循环 T[] arr = (T[]) Array.newInstance(eles[0].getClass(), set.size()); int index = 0; for (T ele : eles) { if (set.remove(ele)) Array.set(arr, index++, ele); } return arr; } /** * 判断一个对象是否为空。它支持如下对象类型: * <ul> * <li>null : 一定为空 * <li>数组 * <li>集合 * <li>Map * <li>其他对象 : 一定不为空 * </ul> * * @param obj * 任意对象 * @return 是否为空 */ public static boolean isEmpty(Object obj) { if (obj == null) return true; if (obj.getClass().isArray()) return Array.getLength(obj) == 0; if (obj instanceof Collection<?>) return ((Collection<?>) obj).isEmpty(); if (obj instanceof Map<?, ?>) return ((Map<?, ?>) obj).isEmpty(); return false; } /** * 判断一个数组是否是空数组 * * @param ary * 数组 * @return null 或者空数组都为 true 否则为 false */ public static <T> boolean isEmptyArray(T[] ary) { return null == ary || ary.length == 0; } /** * 较方便的创建一个列表,比如: * * <pre> * List&lt;Pet&gt; pets = Lang.list(pet1, pet2, pet3); * </pre> * * 注,这里的 List,是 ArrayList 的实例 * * @param eles * 可变参数 * @return 列表对象 */ public static <T> ArrayList<T> list(T... eles) { ArrayList<T> list = new ArrayList<T>(eles.length); for (T ele : eles) list.add(ele); return list; } /** * 创建一个 Hash 集合 * * @param eles * 可变参数 * @return 集合对象 */ public static <T> Set<T> set(T... eles) { Set<T> set = new HashSet<T>(); for (T ele : eles) set.add(ele); return set; } /** * 将多个数组,合并成一个数组。如果这些数组为空,则返回 null * * @param arys * 数组对象 * @return 合并后的数组对象 */ @SuppressWarnings("unchecked") public static <T> T[] merge(T[]... arys) { Queue<T> list = new LinkedList<T>(); for (T[] ary : arys) if (null != ary) for (T e : ary) if (null != e) list.add(e); if (list.isEmpty()) return null; Class<T> type = (Class<T>) list.peek().getClass(); return list.toArray((T[]) Array.newInstance(type, list.size())); } /** * 将一个对象添加成为一个数组的第一个元素,从而生成一个新的数组 * * @param e * 对象 * @param eles * 数组 * @return 新数组 */ @SuppressWarnings("unchecked") public static <T> T[] arrayFirst(T e, T[] eles) { try { if (null == eles || eles.length == 0) { T[] arr = (T[]) Array.newInstance(e.getClass(), 1); arr[0] = e; return arr; } T[] arr = (T[]) Array.newInstance(eles.getClass().getComponentType(), eles.length + 1); arr[0] = e; for (int i = 0; i < eles.length; i++) { arr[i + 1] = eles[i]; } return arr; } catch (NegativeArraySizeException e1) { throw Lang.wrapThrow(e1); } } /** * 将一个对象添加成为一个数组的最后一个元素,从而生成一个新的数组 * * @param e * 对象 * @param eles * 数组 * @return 新数组 */ @SuppressWarnings("unchecked") public static <T> T[] arrayLast(T[] eles, T e) { try { if (null == eles || eles.length == 0) { T[] arr = (T[]) Array.newInstance(e.getClass(), 1); arr[0] = e; return arr; } T[] arr = (T[]) Array.newInstance(eles.getClass().getComponentType(), eles.length + 1); for (int i = 0; i < eles.length; i++) { arr[i] = eles[i]; } arr[eles.length] = e; return arr; } catch (NegativeArraySizeException e1) { throw Lang.wrapThrow(e1); } } /** * 将一个数组转换成字符串 * <p> * 所有的元素都被格式化字符串包裹。 这个格式话字符串只能有一个占位符, %s, %d 等,均可,请视你的数组内容而定 * * @param fmt * 格式 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concatBy(String fmt, T[] objs) { StringBuilder sb = new StringBuilder(); for (T obj : objs) sb.append(String.format(fmt, obj)); return sb; } /** * 将一个数组转换成字符串 * <p> * 所有的元素都被格式化字符串包裹。 这个格式话字符串只能有一个占位符, %s, %d 等,均可,请视你的数组内容而定 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param ptn * 格式 * @param c * 分隔符 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concatBy(String ptn, Object c, T[] objs) { StringBuilder sb = new StringBuilder(); for (T obj : objs) sb.append(String.format(ptn, obj)).append(c); if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1); return sb; } /** * 将一个数组转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(Object c, T[] objs) { StringBuilder sb = new StringBuilder(); if (null == objs || 0 == objs.length) return sb; sb.append(objs[0]); for (int i = 1; i < objs.length; i++) sb.append(c).append(objs[i]); return sb; } /** * 清除数组中的特定值 * * @param objs * 数组 * @param val * 值,可以是 null,如果是对象,则会用 equals 来比较 * @return 新的数组实例 */ @SuppressWarnings("unchecked") public static <T> T[] without(T[] objs, T val) { if (null == objs || objs.length == 0) { return objs; } List<T> list = new ArrayList<T>(objs.length); Class<?> eleType = null; for (T obj : objs) { if (obj == val || (null != obj && null != val && obj.equals(val))) continue; if (null == eleType && obj != null) eleType = obj.getClass(); list.add(obj); } if (list.isEmpty()) { return (T[]) new Object[0]; } return list.toArray((T[]) Array.newInstance(eleType, list.size())); } /** * 将一个长整型数组转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param vals * 数组 * @return 拼合后的字符串 */ public static StringBuilder concat(Object c, long[] vals) { StringBuilder sb = new StringBuilder(); if (null == vals || 0 == vals.length) return sb; sb.append(vals[0]); for (int i = 1; i < vals.length; i++) sb.append(c).append(vals[i]); return sb; } /** * 将一个整型数组转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param vals * 数组 * @return 拼合后的字符串 */ public static StringBuilder concat(Object c, int[] vals) { StringBuilder sb = new StringBuilder(); if (null == vals || 0 == vals.length) return sb; sb.append(vals[0]); for (int i = 1; i < vals.length; i++) sb.append(c).append(vals[i]); return sb; } /** * 将一个数组的部分元素转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param offset * 开始元素的下标 * @param len * 元素数量 * @param c * 分隔符 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(int offset, int len, Object c, T[] objs) { StringBuilder sb = new StringBuilder(); if (null == objs || len < 0 || 0 == objs.length) return sb; if (offset < objs.length) { sb.append(objs[offset]); for (int i = 1; i < len && i + offset < objs.length; i++) { sb.append(c).append(objs[i + offset]); } } return sb; } /** * 将一个数组所有元素拼合成一个字符串 * * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(T[] objs) { StringBuilder sb = new StringBuilder(); for (T e : objs) sb.append(e.toString()); return sb; } /** * 将一个数组部分元素拼合成一个字符串 * * @param offset * 开始元素的下标 * @param len * 元素数量 * @param array * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(int offset, int len, T[] array) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { sb.append(array[i + offset].toString()); } return sb; } /** * 将一个集合转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param coll * 集合 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(Object c, Collection<T> coll) { StringBuilder sb = new StringBuilder(); if (null == coll || coll.isEmpty()) return sb; return concat(c, coll.iterator()); } /** * 将一个迭代器转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param it * 集合 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(Object c, Iterator<T> it) { StringBuilder sb = new StringBuilder(); if (it == null || !it.hasNext()) return sb; sb.append(it.next()); while (it.hasNext()) sb.append(c).append(it.next()); return sb; } /** * 将一个或者多个数组填入一个集合。 * * @param <C> * 集合类型 * @param <T> * 数组元素类型 * @param coll * 集合 * @param objss * 数组 (数目可变) * @return 集合对象 */ public static <C extends Collection<T>, T> C fill(C coll, T[]... objss) { for (T[] objs : objss) for (T obj : objs) coll.add(obj); return coll; } /** * 将一个集合变成 Map。 * * @param mapClass * Map 的类型 * @param coll * 集合对象 * @param keyFieldName * 采用集合中元素的哪个一个字段为键。 * @return Map 对象 */ public static <T extends Map<Object, Object>> T collection2map(Class<T> mapClass, Collection<?> coll, String keyFieldName) { if (null == coll) return null; T map = createMap(mapClass); if (coll.size() > 0) { Iterator<?> it = coll.iterator(); Object obj = it.next(); Mirror<?> mirror = Mirror.me(obj.getClass()); Object key = mirror.getValue(obj, keyFieldName); map.put(key, obj); for (; it.hasNext();) { obj = it.next(); key = mirror.getValue(obj, keyFieldName); map.put(key, obj); } } return (T) map; } /** * 将集合变成 ArrayList * * @param col * 集合对象 * @return 列表对象 */ @SuppressWarnings("unchecked") public static <E> List<E> collection2list(Collection<E> col) { if (null == col) return null; if (col.size() == 0) return new ArrayList<E>(0); Class<E> eleType = (Class<E>) col.iterator().next().getClass(); return collection2list(col, eleType); } /** * 将集合编程变成指定类型的列表 * * @param col * 集合对象 * @param eleType * 列表类型 * @return 列表对象 */ public static <E> List<E> collection2list(Collection<?> col, Class<E> eleType) { if (null == col) return null; List<E> list = new ArrayList<E>(col.size()); for (Object obj : col) list.add(Castors.me().castTo(obj, eleType)); return list; } /** * 将集合变成数组,数组的类型为集合的第一个元素的类型。如果集合为空,则返回 null * * @param coll * 集合对象 * @return 数组 */ @SuppressWarnings("unchecked") public static <E> E[] collection2array(Collection<E> coll) { if (null == coll) return null; if (coll.size() == 0) return (E[]) new Object[0]; Class<E> eleType = (Class<E>) Lang.first(coll).getClass(); return collection2array(coll, eleType); } /** * 将集合变成指定类型的数组 * * @param col * 集合对象 * @param eleType * 数组元素类型 * @return 数组 */ @SuppressWarnings("unchecked") public static <E> E[] collection2array(Collection<?> col, Class<E> eleType) { if (null == col) return null; Object re = Array.newInstance(eleType, col.size()); int i = 0; for (Iterator<?> it = col.iterator(); it.hasNext();) { Object obj = it.next(); if (null == obj) Array.set(re, i++, null); else Array.set(re, i++, Castors.me().castTo(obj, eleType)); } return (E[]) re; } /** * 将一个数组变成 Map * * @param mapClass * Map 的类型 * @param array * 数组 * @param keyFieldName * 采用集合中元素的哪个一个字段为键。 * @return Map 对象 */ public static <T extends Map<Object, Object>> T array2map(Class<T> mapClass, Object array, String keyFieldName) { if (null == array) return null; T map = createMap(mapClass); int len = Array.getLength(array); if (len > 0) { Object obj = Array.get(array, 0); Mirror<?> mirror = Mirror.me(obj.getClass()); for (int i = 0; i < len; i++) { obj = Array.get(array, i); Object key = mirror.getValue(obj, keyFieldName); map.put(key, obj); } } return map; } @SuppressWarnings("unchecked") private static <T extends Map<Object, Object>> T createMap(Class<T> mapClass) { T map; try { map = mapClass.newInstance(); } catch (Exception e) { map = (T) new HashMap<Object, Object>(); } if (!mapClass.isAssignableFrom(map.getClass())) { throw Lang.makeThrow("Fail to create map [%s]", mapClass.getName()); } return map; } /** * 将数组转换成一个列表。 * * @param array * 原始数组 * @return 新列表 * * @see org.nutz.castor.Castors */ public static <T> List<T> array2list(T[] array) { if (null == array) return null; List<T> re = new ArrayList<T>(array.length); for (T obj : array) re.add(obj); return re; } /** * 将数组转换成一个列表。将会采用 Castor 来深层转换数组元素 * * @param array * 原始数组 * @param eleType * 新列表的元素类型 * @return 新列表 * * @see org.nutz.castor.Castors */ public static <T, E> List<E> array2list(Object array, Class<E> eleType) { if (null == array) return null; int len = Array.getLength(array); List<E> re = new ArrayList<E>(len); for (int i = 0; i < len; i++) { Object obj = Array.get(array, i); re.add(Castors.me().castTo(obj, eleType)); } return re; } /** * 将数组转换成另外一种类型的数组。将会采用 Castor 来深层转换数组元素 * * @param array * 原始数组 * @param eleType * 新数组的元素类型 * @return 新数组 * @throws FailToCastObjectException * * @see org.nutz.castor.Castors */ public static Object array2array(Object array, Class<?> eleType) throws FailToCastObjectException { if (null == array) return null; int len = Array.getLength(array); Object re = Array.newInstance(eleType, len); for (int i = 0; i < len; i++) { Array.set(re, i, Castors.me().castTo(Array.get(array, i), eleType)); } return re; } /** * 将数组转换成Object[] 数组。将会采用 Castor 来深层转换数组元素 * * @param args * 原始数组 * @param pts * 新数组的元素类型 * @return 新数组 * @throws FailToCastObjectException * * @see org.nutz.castor.Castors */ public static <T> Object[] array2ObjectArray(T[] args, Class<?>[] pts) throws FailToCastObjectException { if (null == args) return null; Object[] newArgs = new Object[args.length]; for (int i = 0; i < args.length; i++) { newArgs[i] = Castors.me().castTo(args[i], pts[i]); } return newArgs; } /** * 根据一个 Map,和给定的对象类型,创建一个新的 JAVA 对象 * * @param src * Map 对象 * @param toType * JAVA 对象类型 * @return JAVA 对象 * @throws FailToCastObjectException */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T map2Object(Map<?, ?> src, Class<T> toType) throws FailToCastObjectException { if (null == toType) throw new FailToCastObjectException("target type is Null"); // 类型相同 if (toType == Map.class) return (T) src; // 也是一种 Map if (Map.class.isAssignableFrom(toType)) { Map map; try { map = (Map) toType.newInstance(); map.putAll(src); return (T) map; } catch (Exception e) { throw new FailToCastObjectException("target type fail to born!", unwrapThrow(e)); } } // 数组 if (toType.isArray()) return (T) Lang.collection2array(src.values(), toType.getComponentType()); // List if (List.class == toType) { return (T) Lang.collection2list(src.values()); } // POJO Mirror<T> mirror = Mirror.me(toType); T obj = mirror.born(); for (Field field : mirror.getFields()) { Object v = null; if (!Lang.isAndroid && field.isAnnotationPresent(Column.class)) { String cv = field.getAnnotation(Column.class).value(); v = src.get(cv); } if (null == v && src.containsKey(field.getName())) { v = src.get(field.getName()); } if (null != v) { // Class<?> ft = field.getType(); // 获取泛型基类中的字段真实类型, https://github.com/nutzam/nutz/issues/1288 Class<?> ft = ReflectTool.getGenericFieldType(toType, field); Object vv = null; // 集合 if (v instanceof Collection && (ft.isArray() || Collection.class.isAssignableFrom(ft))) { Collection c = (Collection) v; // 集合到数组 if (ft.isArray()) { vv = Lang.collection2array(c, ft.getComponentType()); } // 集合到集合 else { // 创建 Collection newCol; // Class eleType = Mirror.getGenericTypes(field, 0); Class<?> eleType = ReflectTool.getParameterRealGenericClass(toType, field.getGenericType(), 0); if (ft == List.class) { newCol = new ArrayList(c.size()); } else if (ft == Set.class) { newCol = new LinkedHashSet(); } else { try { newCol = (Collection) ft.newInstance(); } catch (Exception e) { throw Lang.wrapThrow(e); } } // 赋值 for (Object ele : c) { newCol.add(Castors.me().castTo(ele, eleType)); } vv = newCol; } } // Map else if (v instanceof Map && Map.class.isAssignableFrom(ft)) { // 创建 final Map map; // Map 接口 if (ft == Map.class) { map = new HashMap(); } // 自己特殊的 Map else { try { map = (Map) ft.newInstance(); } catch (Exception e) { throw new FailToCastObjectException("target type fail to born!", e); } } // 赋值 // final Class<?> valType = Mirror.getGenericTypes(field, // 1); // map的key和value字段类型 final Class<?> keyType = ReflectTool.getParameterRealGenericClass(toType, field.getGenericType(), 0); final Class<?> valType = ReflectTool.getParameterRealGenericClass(toType, field.getGenericType(), 1); each(v, new Each<Entry>() { public void invoke(int i, Entry en, int length) { map.put(Castors.me().castTo(en.getKey(), keyType), Castors.me().castTo(en.getValue(), valType)); } }); vv = map; } // 强制转换 else { vv = Castors.me().castTo(v, ft); } mirror.setValue(obj, field, vv); } } return obj; } /** * 根据一段字符串,生成一个 Map 对象。 * * @param str * 参照 JSON 标准的字符串,但是可以没有前后的大括号 * @return Map 对象 */ public static NutMap map(String str) { if (null == str) return null; str = Strings.trim(str); if (!Strings.isEmpty(str) && (Strings.isQuoteBy(str, '{', '}') || Strings.isQuoteBy(str, '(', ')'))) { return Json.fromJson(NutMap.class, str); } return Json.fromJson(NutMap.class, "{" + str + "}"); } /** * 将一个 Map 所有的键都按照回调进行修改 * * 本函数遇到数组或者集合,会自动处理每个元素 * * @param obj * 要转换的 Map 或者 集合或者数组 * * @param mkc * 键值修改的回调 * @param recur * 遇到 Map 是否递归 * * @see MapKeyConvertor */ @SuppressWarnings("unchecked") public static void convertMapKey(Object obj, MapKeyConvertor mkc, boolean recur) { // Map if (obj instanceof Map<?, ?>) { Map<String, Object> map = (Map<String, Object>) obj; NutMap map2 = new NutMap(); for (Map.Entry<String, Object> en : map.entrySet()) { String key = en.getKey(); Object val = en.getValue(); if (recur) convertMapKey(val, mkc, recur); String newKey = mkc.convertKey(key); map2.put(newKey, val); } map.clear(); map.putAll(map2); } // Collection else if (obj instanceof Collection<?>) { for (Object ele : (Collection<?>) obj) { convertMapKey(ele, mkc, recur); } } // Array else if (obj.getClass().isArray()) { for (Object ele : (Object[]) obj) { convertMapKey(ele, mkc, recur); } } } /** * 创建一个一个键的 Map 对象 * * @param key * 键 * @param v * 值 * @return Map 对象 */ public static NutMap map(String key, Object v) { return new NutMap().addv(key, v); } /** * 根据一个格式化字符串,生成 Map 对象 * * @param fmt * 格式化字符串 * @param args * 字符串参数 * @return Map 对象 */ public static NutMap mapf(String fmt, Object... args) { return map(String.format(fmt, args)); } /** * 创建一个新的上下文对象 * * @return 一个新创建的上下文对象 */ public static Context context() { return new SimpleContext(); } /** * 根据key,val创建一个新的上下文对象 * * @param key * @param val * @return */ public static Context context(String key, Object val) { return context().set(key, val); } /** * 根据一个 Map 包裹成一个上下文对象 * * @param map * Map 对象 * * @return 一个新创建的上下文对象 */ public static Context context(Map<String, Object> map) { return new SimpleContext(map); } /** * 根据一段 JSON 字符串,生产一个新的上下文对象 * * @param fmt * JSON 字符串模板 * @param args * 模板参数 * * @return 一个新创建的上下文对象 */ public static Context contextf(String fmt, Object... args) { return context(Lang.mapf(fmt, args)); } /** * 根据一段 JSON 字符串,生产一个新的上下文对象 * * @return 一个新创建的上下文对象 */ public static Context context(String str) { return context(map(str)); } /** * 根据一段字符串,生成一个List 对象。 * * @param str * 参照 JSON 标准的字符串,但是可以没有前后的中括号 * @return List 对象 */ @SuppressWarnings("unchecked") public static List<Object> list4(String str) { if (null == str) return null; if ((str.length() > 0 && str.charAt(0) == '[') && str.endsWith("]")) return (List<Object>) Json.fromJson(str); return (List<Object>) Json.fromJson("[" + str + "]"); } /** * 获得一个对象的长度。它可以接受: * <ul> * <li>null : 0 * <li>数组 * <li>集合 * <li>Map * <li>一般 Java 对象。 返回 1 * </ul> * 如果你想让你的 Java 对象返回不是 1 , 请在对象中声明 length() 函数 * * @param obj * @return 对象长度 * @deprecated 这玩意很脑残,为啥最后要动态调个 "length",导致字符串类很麻烦,以后用 Lang.eleSize 函数代替吧 */ @Deprecated public static int length(Object obj) { if (null == obj) return 0; if (obj.getClass().isArray()) { return Array.getLength(obj); } else if (obj instanceof Collection<?>) { return ((Collection<?>) obj).size(); } else if (obj instanceof Map<?, ?>) { return ((Map<?, ?>) obj).size(); } try { return (Integer) Mirror.me(obj.getClass()).invoke(obj, "length"); } catch (Exception e) {} return 1; } /** * 获得一个容器(Map/集合/数组)对象包含的元素数量 * <ul> * <li>null : 0 * <li>数组 * <li>集合 * <li>Map * <li>一般 Java 对象。 返回 1 * </ul> * * @param obj * @return 对象长度 * @since Nutz 1.r.62 */ public static int eleSize(Object obj) { // 空指针,就是 0 if (null == obj) return 0; // 数组 if (obj.getClass().isArray()) { return Array.getLength(obj); } // 容器 if (obj instanceof Collection<?>) { return ((Collection<?>) obj).size(); } // Map if (obj instanceof Map<?, ?>) { return ((Map<?, ?>) obj).size(); } // 其他的就是 1 咯 return 1; } /** * 如果是数组或集合取得第一个对象。 否则返回自身 * * @param obj * 任意对象 * @return 第一个代表对象 */ public static Object first(Object obj) { if (null == obj) return obj; if (obj instanceof Collection<?>) { Iterator<?> it = ((Collection<?>) obj).iterator(); return it.hasNext() ? it.next() : null; } if (obj.getClass().isArray()) return Array.getLength(obj) > 0 ? Array.get(obj, 0) : null; return obj; } /** * 获取集合中的第一个元素,如果集合为空,返回 null * * @param coll * 集合 * @return 第一个元素 */ public static <T> T first(Collection<T> coll) { if (null == coll || coll.isEmpty()) return null; return coll.iterator().next(); } /** * 获得表中的第一个名值对 * * @param map * 表 * @return 第一个名值对 */ public static <K, V> Entry<K, V> first(Map<K, V> map) { if (null == map || map.isEmpty()) return null; return map.entrySet().iterator().next(); } /** * 打断 each 循环 */ public static void Break() throws ExitLoop { throw new ExitLoop(); } /** * 继续 each 循环,如果再递归,则停止递归 */ public static void Continue() throws ContinueLoop { throw new ContinueLoop(); } /** * 用回调的方式,遍历一个对象,可以支持遍历 * <ul> * <li>数组 * <li>集合 * <li>Map * <li>单一元素 * </ul> * * @param obj * 对象 * @param callback * 回调 */ public static <T> void each(Object obj, Each<T> callback) { each(obj, true, callback); } /** * 用回调的方式,遍历一个对象,可以支持遍历 * <ul> * <li>数组 * <li>集合 * <li>Map * <li>单一元素 * </ul> * * @param obj * 对象 * @param loopMap * 是否循环 Map,如果循环 Map 则主要看 callback 的 T,如果是 Map.Entry 则循环 Entry * 否循环 value。如果本值为 false, 则将 Map 当作一个完整的对象来看待 * @param callback * 回调 */ @SuppressWarnings({"rawtypes", "unchecked"}) public static <T> void each(Object obj, boolean loopMap, Each<T> callback) { if (null == obj || null == callback) return; try { // 循环开始 if (callback instanceof Loop) if (!((Loop) callback).begin()) return; // 进行循环 if (obj.getClass().isArray()) { int len = Array.getLength(obj); for (int i = 0; i < len; i++) try { callback.invoke(i, (T) Array.get(obj, i), len); } catch (ContinueLoop e) {} catch (ExitLoop e) { break; } } else if (obj instanceof Collection) { int len = ((Collection) obj).size(); int i = 0; for (Iterator<T> it = ((Collection) obj).iterator(); it.hasNext();) try { callback.invoke(i++, it.next(), len); } catch (ContinueLoop e) {} catch (ExitLoop e) { break; } } else if (loopMap && obj instanceof Map) { Map map = (Map) obj; int len = map.size(); int i = 0; Class<T> eType = Mirror.getTypeParam(callback.getClass(), 0); if (null != eType && eType != Object.class && eType.isAssignableFrom(Entry.class)) { for (Object v : map.entrySet()) try { callback.invoke(i++, (T) v, len); } catch (ContinueLoop e) {} catch (ExitLoop e) { break; } } else { for (Object v : map.entrySet()) try { callback.invoke(i++, (T) ((Entry) v).getValue(), len); } catch (ContinueLoop e) {} catch (ExitLoop e) { break; } } } else if (obj instanceof Iterator<?>) { Iterator<?> it = (Iterator<?>) obj; int i = 0; while (it.hasNext()) { try { callback.invoke(i++, (T) it.next(), -1); } catch (ContinueLoop e) {} catch (ExitLoop e) { break; } } } else try { callback.invoke(0, (T) obj, 1); } catch (ContinueLoop e) {} catch (ExitLoop e) {} // 循环结束 if (callback instanceof Loop) ((Loop) callback).end(); } catch (LoopException e) { throw Lang.wrapThrow(e.getCause()); } } /** * 安全的从一个数组获取一个元素,容忍 null 数组,以及支持负数的 index * <p> * 如果该下标越界,则返回 null * * @param <T> * @param array * 数组,如果为 null 则直接返回 null * @param index * 下标,-1 表示倒数第一个, -2 表示倒数第二个,以此类推 * @return 数组元素 */ public static <T> T get(T[] array, int index) { if (null == array) return null; int i = index < 0 ? array.length + index : index; if (i < 0 || i >= array.length) return null; return array[i]; } /** * 将一个抛出对象的异常堆栈,显示成一个字符串 * * @param e * 抛出对象 * @return 异常堆栈文本 */ public static String getStackTrace(Throwable e) { StringBuilder sb = new StringBuilder(); StringOutputStream sbo = new StringOutputStream(sb); PrintStream ps = new PrintStream(sbo); e.printStackTrace(ps); ps.flush(); return sbo.getStringBuilder().toString(); } /** * 将字符串解析成 boolean 值,支持更多的字符串 * <ul> * <li>1 | 0 * <li>yes | no * <li>on | off * <li>true | false * </ul> * * @param s * 字符串 * @return 布尔值 */ public static boolean parseBoolean(String s) { if (null == s || s.length() == 0) return false; if (s.length() > 5) return true; if ("0".equals(s)) return false; s = s.toLowerCase(); return !"false".equals(s) && !"off".equals(s) && !"no".equals(s); } /** * 帮你快速获得一个 DocumentBuilder,方便 XML 解析。 * * @return 一个 DocumentBuilder 对象 * @throws ParserConfigurationException */ public static DocumentBuilder xmls() throws ParserConfigurationException { return Xmls.xmls(); } /** * 对Thread.sleep(long)的简单封装,不抛出任何异常 * * @param millisecond * 休眠时间 */ public static void quiteSleep(long millisecond) { try { if (millisecond > 0) Thread.sleep(millisecond); } catch (Throwable e) {} } /** * 将字符串,变成数字对象,现支持的格式为: * <ul> * <li>null - 整数 0</li> * <li>23.78 - 浮点 Float</li> * <li>0x45 - 16进制整数 Integer</li> * <li>78L - 长整数 Long</li> * <li>69 - 普通整数 Integer</li> * </ul> * * @param s * 参数 * @return 数字对象 */ public static Number str2number(String s) { // null 值 if (null == s) { return 0; } s = s.toUpperCase(); // 浮点 if (s.indexOf('.') != -1) { char c = s.charAt(s.length() - 1); if (c == 'F' || c == 'f') { return Float.valueOf(s); } return Double.valueOf(s); } // 16进制整数 if (s.startsWith("0X")) { return Integer.valueOf(s.substring(2), 16); } // 长整数 if (s.charAt(s.length() - 1) == 'L' || s.charAt(s.length() - 1) == 'l') { return Long.valueOf(s.substring(0, s.length() - 1)); } // 普通整数 Long re = Long.parseLong(s); if (Integer.MAX_VALUE >= re && re >= Integer.MIN_VALUE) return re.intValue(); return re; } @SuppressWarnings("unchecked") private static <T extends Map<String, Object>> void obj2map(Object obj, T map, final Map<Object, Object> memo) { // 已经转换过了,不要递归转换 if (null == obj || memo.containsKey(obj)) return; memo.put(obj, ""); // Fix issue #497 // 如果是 Map,就直接 putAll 一下咯 if (obj instanceof Map<?, ?>) { map.putAll(__change_map_to_nutmap((Map<String, Object>) obj, memo)); return; } // 下面是普通的 POJO Mirror<?> mirror = Mirror.me(obj.getClass()); Field[] flds = mirror.getFields(); for (Field fld : flds) { Object v = mirror.getValue(obj, fld); if (null == v) { continue; } Mirror<?> mr = Mirror.me(v); // 普通值 if (mr.isSimple()) { map.put(fld.getName(), v); } // 已经输出过了 else if (memo.containsKey(v)) { map.put(fld.getName(), null); } // 数组或者集合 else if (mr.isColl()) { final List<Object> list = new ArrayList<Object>(Lang.length(v)); Lang.each(v, new Each<Object>() { public void invoke(int index, Object ele, int length) { __join_ele_to_list_as_map(list, ele, memo); } }); map.put(fld.getName(), list); } // Map else if (mr.isMap()) { NutMap map2 = __change_map_to_nutmap((Map<String, Object>) v, memo); map.put(fld.getName(), map2); } // 看来要递归 else { T sub; try { sub = (T) map.getClass().newInstance(); } catch (Exception e) { throw Lang.wrapThrow(e); } obj2map(v, sub, memo); map.put(fld.getName(), sub); } } } @SuppressWarnings("unchecked") private static NutMap __change_map_to_nutmap(Map<String, Object> map, final Map<Object, Object> memo) { NutMap re = new NutMap(); for (Map.Entry<String, Object> en : map.entrySet()) { Object v = en.getValue(); if (null == v) continue; Mirror<?> mr = Mirror.me(v); // 普通值 if (mr.isSimple()) { re.put(en.getKey(), v); } // 已经输出过了 else if (memo.containsKey(v)) { continue; } // 数组或者集合 else if (mr.isColl()) { final List<Object> list2 = new ArrayList<Object>(Lang.length(v)); Lang.each(v, new Each<Object>() { public void invoke(int index, Object ele, int length) { __join_ele_to_list_as_map(list2, ele, memo); } }); re.put(en.getKey(), list2); } // Map else if (mr.isMap()) { NutMap map2 = __change_map_to_nutmap((Map<String, Object>) v, memo); re.put(en.getKey(), map2); } // 看来要递归 else { NutMap map2 = obj2nutmap(v); re.put(en.getKey(), map2); } } return re; } @SuppressWarnings("unchecked") private static void __join_ele_to_list_as_map(List<Object> list, Object o, final Map<Object, Object> memo) { if (null == o) { return; } // 如果是 Map,就直接 putAll 一下咯 if (o instanceof Map<?, ?>) { NutMap map2 = __change_map_to_nutmap((Map<String, Object>) o, memo); list.add(map2); return; } Mirror<?> mr = Mirror.me(o); // 普通值 if (mr.isSimple()) { list.add(o); } // 已经输出过了 else if (memo.containsKey(o)) { list.add(null); } // 数组或者集合 else if (mr.isColl()) { final List<Object> list2 = new ArrayList<Object>(Lang.length(o)); Lang.each(o, new Each<Object>() { public void invoke(int index, Object ele, int length) { __join_ele_to_list_as_map(list2, ele, memo); } }); list.add(list2); } // Map else if (mr.isMap()) { NutMap map2 = __change_map_to_nutmap((Map<String, Object>) o, memo); list.add(map2); } // 看来要递归 else { NutMap map = obj2nutmap(o); list.add(map); } } /** * 将对象转换成 Map * * @param obj * POJO 对象 * @return Map 对象 */ @SuppressWarnings("unchecked") public static Map<String, Object> obj2map(Object obj) { return obj2map(obj, HashMap.class); } /** * 将对象转为 Nutz 的标准 Map 封装 * * @param obj * POJO du对象 * @return NutMap 对象 */ public static NutMap obj2nutmap(Object obj) { return obj2map(obj, NutMap.class); } /** * 将对象转换成 Map * * @param <T> * @param obj * POJO 对象 * @param mapType * Map 的类型 * @return Map 对象 */ public static <T extends Map<String, Object>> T obj2map(Object obj, Class<T> mapType) { try { T map = mapType.newInstance(); Lang.obj2map(obj, map, new HashMap<Object, Object>()); return map; } catch (Exception e) { throw Lang.wrapThrow(e); } } /** * 返回一个集合对象的枚举对象。实际上就是对 Iterator 接口的一个封装 * * @param col * 集合对象 * @return 枚举对象 */ public static <T> Enumeration<T> enumeration(Collection<T> col) { final Iterator<T> it = col.iterator(); return new Enumeration<T>() { public boolean hasMoreElements() { return it.hasNext(); } public T nextElement() { return it.next(); } }; } /** * 将枚举对象,变成集合 * * @param enums * 枚举对象 * @param cols * 集合对象 * @return 集合对象 */ public static <T extends Collection<E>, E> T enum2collection(Enumeration<E> enums, T cols) { while (enums.hasMoreElements()) cols.add(enums.nextElement()); return cols; } /** * 将字符数组强制转换成字节数组。如果字符为双字节编码,则会丢失信息 * * @param cs * 字符数组 * @return 字节数组 */ public static byte[] toBytes(char[] cs) { byte[] bs = new byte[cs.length]; for (int i = 0; i < cs.length; i++) bs[i] = (byte) cs[i]; return bs; } /** * 将整数数组强制转换成字节数组。整数的高位将会被丢失 * * @param is * 整数数组 * @return 字节数组 */ public static byte[] toBytes(int[] is) { byte[] bs = new byte[is.length]; for (int i = 0; i < is.length; i++) bs[i] = (byte) is[i]; return bs; } /** * 判断当前系统是否为Windows * * @return true 如果当前系统为Windows系统 */ public static boolean isWin() { try { String os = System.getenv("OS"); return os != null && os.indexOf("Windows") > -1; } catch (Throwable e) { return false; } } /** * 原方法使用线程ClassLoader,各种问题,改回原版. */ public static Class<?> loadClass(String className) throws ClassNotFoundException { try { return Thread.currentThread().getContextClassLoader().loadClass(className); } catch (Throwable e) { return Class.forName(className); } } /** * 当前运行的 Java 虚拟机是 JDK6 及更高版本的话,则返回 true * * @return true 如果当前运行的 Java 虚拟机是 JDK6 */ public static boolean isJDK6() { return JdkTool.getMajorVersion() >= 6; } /** * 获取基本类型的默认值 * * @param pClass * 基本类型 * @return 0/false,如果传入的pClass不是基本类型的类,则返回null */ public static Object getPrimitiveDefaultValue(Class<?> pClass) { if (int.class.equals(pClass)) return Integer.valueOf(0); if (long.class.equals(pClass)) return Long.valueOf(0); if (short.class.equals(pClass)) return Short.valueOf((short) 0); if (float.class.equals(pClass)) return Float.valueOf(0f); if (double.class.equals(pClass)) return Double.valueOf(0); if (byte.class.equals(pClass)) return Byte.valueOf((byte) 0); if (char.class.equals(pClass)) return Character.valueOf((char) 0); if (boolean.class.equals(pClass)) return Boolean.FALSE; return null; } /** * 当一个类使用<T,K>来定义泛型时,本方法返回类的一个字段的具体类型。 * * @param me * @param field */ public static Type getFieldType(Mirror<?> me, String field) throws NoSuchFieldException { return getFieldType(me, me.getField(field)); } /** * 当一个类使用<T, K> 来定义泛型时, 本方法返回类的一个方法所有参数的具体类型 * * @param me * @param method */ public static Type[] getMethodParamTypes(Mirror<?> me, Method method) { Type[] types = method.getGenericParameterTypes(); List<Type> ts = new ArrayList<Type>(); for (Type type : types) { ts.add(getGenericsType(me, type)); } return ts.toArray(new Type[ts.size()]); } /** * 当一个类使用<T,K>来定义泛型时,本方法返回类的一个字段的具体类型。 * * @param me * @param field */ public static Type getFieldType(Mirror<?> me, Field field) { Type type = field.getGenericType(); return getGenericsType(me, type); } /** * 当一个类使用<T,K>来定义泛型时,本方法返回类的一个字段的具体类型。 * * @param me * @param type */ public static Type getGenericsType(Mirror<?> me, Type type) { Type[] types = me.getGenericsTypes(); Type t = type; if (type instanceof TypeVariable && types != null && types.length > 0) { Type[] tvs = me.getType().getTypeParameters(); for (int i = 0; i < tvs.length; i++) { if (type.equals(tvs[i])) { type = me.getGenericsType(i); break; } } } if (!type.equals(t)) { return type; } if (types != null && types.length > 0 && type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; if (pt.getActualTypeArguments().length >= 0) { NutType nt = new NutType(); nt.setOwnerType(pt.getOwnerType()); nt.setRawType(pt.getRawType()); Type[] tt = new Type[pt.getActualTypeArguments().length]; for (int i = 0; i < tt.length; i++) { tt[i] = types[i]; } nt.setActualTypeArguments(tt); return nt; } } return type; } /** * 获取一个 Type 类型实际对应的Class * * @param type * 类型 * @return 与Type类型实际对应的Class */ @SuppressWarnings("rawtypes") public static Class<?> getTypeClass(Type type) { Class<?> clazz = null; if (type instanceof Class<?>) { clazz = (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; clazz = (Class<?>) pt.getRawType(); } else if (type instanceof GenericArrayType) { GenericArrayType gat = (GenericArrayType) type; Class<?> typeClass = getTypeClass(gat.getGenericComponentType()); return Array.newInstance(typeClass, 0).getClass(); } else if (type instanceof TypeVariable) { TypeVariable tv = (TypeVariable) type; Type[] ts = tv.getBounds(); if (ts != null && ts.length > 0) return getTypeClass(ts[0]); } else if (type instanceof WildcardType) { WildcardType wt = (WildcardType) type; Type[] t_low = wt.getLowerBounds();// 取其下界 if (t_low.length > 0) return getTypeClass(t_low[0]); Type[] t_up = wt.getUpperBounds(); // 没有下界?取其上界 return getTypeClass(t_up[0]);// 最起码有Object作为上界 } return clazz; } /** * 返回一个 Type 的泛型数组, 如果没有, 则直接返回null * * @param type * 类型 * @return 一个 Type 的泛型数组, 如果没有, 则直接返回null */ public static Type[] getGenericsTypes(Type type) { if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; return pt.getActualTypeArguments(); } return null; } /** * 强制从字符串转换成一个 Class,将 ClassNotFoundException 包裹成 RuntimeException * * @param <T> * @param name * 类名 * @param type * 这个类型的边界 * @return 类对象 */ @SuppressWarnings("unchecked") public static <T> Class<T> forName(String name, Class<T> type) { Class<?> re; try { re = Lang.loadClass(name); return (Class<T>) re; } catch (ClassNotFoundException e) { throw Lang.wrapThrow(e); } } /** * 获取指定文件的 MD5 值 * * @param f * 文件 * @return 指定文件的 MD5 值 * @see #digest(String, File) */ public static String md5(File f) { return digest("MD5", f); } /** * 获取指定输入流的 MD5 值 * * @param ins * 输入流 * @return 指定输入流的 MD5 值 * @see #digest(String, InputStream) */ public static String md5(InputStream ins) { return digest("MD5", ins); } /** * 获取指定字符串的 MD5 值 * * @param cs * 字符串 * @return 指定字符串的 MD5 值 * @see #digest(String, CharSequence) */ public static String md5(CharSequence cs) { return digest("MD5", cs); } /** * 获取指定文件的 SHA1 值 * * @param f * 文件 * @return 指定文件的 SHA1 值 * @see #digest(String, File) */ public static String sha1(File f) { return digest("SHA1", f); } /** * 获取指定输入流的 SHA1 值 * * @param ins * 输入流 * @return 指定输入流的 SHA1 值 * @see #digest(String, InputStream) */ public static String sha1(InputStream ins) { return digest("SHA1", ins); } /** * 获取指定字符串的 SHA1 值 * * @param cs * 字符串 * @return 指定字符串的 SHA1 值 * @see #digest(String, CharSequence) */ public static String sha1(CharSequence cs) { return digest("SHA1", cs); } /** * 获取指定文件的 SHA256 值 * * @param f * 文件 * @return 指定文件的 SHA256 值 * @see #digest(String, File) */ public static String sha256(File f) { return digest("SHA-256", f); } /** * 获取指定输入流的 SHA256 值 * * @param ins * 输入流 * @return 指定输入流的 SHA256 值 * @see #digest(String, InputStream) */ public static String sha256(InputStream ins) { return digest("SHA-256", ins); } /** * 获取指定字符串的 SHA256 值 * * @param cs * 字符串 * @return 指定字符串的 SHA256 值 * @see #digest(String, CharSequence) */ public static String sha256(CharSequence cs) { return digest("SHA-256", cs); } /** * 从数据文件计算出数字签名 * * @param algorithm * 算法,比如 "SHA1" "SHA-256" 或者 "MD5" 等 * @param f * 文件 * @return 数字签名 */ public static String digest(String algorithm, File f) { return digest(algorithm, Streams.fileIn(f)); } /** * 从流计算出数字签名,计算完毕流会被关闭 * * @param algorithm * 算法,比如 "SHA1" 或者 "MD5" 等 * @param ins * 输入流 * @return 数字签名 */ public static String digest(String algorithm, InputStream ins) { return fixedHexString(digest2(algorithm, ins)); } public static byte[] digest2(String algorithm, InputStream ins) { try { MessageDigest md = MessageDigest.getInstance(algorithm); byte[] bs = new byte[HASH_BUFF_SIZE]; int len = 0; while ((len = ins.read(bs)) != -1) { md.update(bs, 0, len); } return md.digest(); } catch (NoSuchAlgorithmException e) { throw Lang.wrapThrow(e); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(ins); } } public static String digest(String algorithm, InputStream ins, byte[] keyBytes) { return fixedHexString(digest2(algorithm, ins, keyBytes)); } public static String digest(String algorithm, File f, byte[] keyBytes) { return fixedHexString(digest2(algorithm, Streams.fileIn(f), keyBytes)); } public static String digest(String algorithm, String str, byte[] keyBytes) { return fixedHexString(digest2(algorithm, Streams.wrap(str.getBytes()), keyBytes)); } public static byte[] digest2(String algorithm, InputStream ins, byte[] keyBytes) { try { SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "Hmac" + algorithm); Mac mac = Mac.getInstance("Hmac" + algorithm); mac.init(signingKey); byte[] bs = new byte[HASH_BUFF_SIZE]; int len = 0; while ((len = ins.read(bs)) != -1) { mac.update(bs, 0, len); } return mac.doFinal(); } catch (NoSuchAlgorithmException e) { throw Lang.wrapThrow(e); } catch (IOException e) { throw Lang.wrapThrow(e); } catch (InvalidKeyException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(ins); } } /** * 从字符串计算出数字签名 * * @param algorithm * 算法,比如 "SHA1" 或者 "MD5" 等 * @param cs * 字符串 * @return 数字签名 */ public static String digest(String algorithm, CharSequence cs) { return digest(algorithm, Strings.getBytesUTF8(null == cs ? "" : cs), null, 1); } /** * 从字节数组计算出数字签名 * * @param algorithm * 算法,比如 "SHA1" 或者 "MD5" 等 * @param bytes * 字节数组 * @param salt * 随机字节数组 * @param iterations * 迭代次数 * @return 数字签名 */ public static String digest(String algorithm, byte[] bytes, byte[] salt, int iterations) { try { MessageDigest md = MessageDigest.getInstance(algorithm); if (salt != null) { md.update(salt); } byte[] hashBytes = md.digest(bytes); for (int i = 1; i < iterations; i++) { md.reset(); hashBytes = md.digest(hashBytes); } return fixedHexString(hashBytes); } catch (NoSuchAlgorithmException e) { throw Lang.wrapThrow(e); } } /** 当前运行的 Java 虚拟机是否是在安卓环境 */ public static final boolean isAndroid; static { boolean flag = false; try { Class.forName("android.Manifest"); flag = true; } catch (Throwable e) {} isAndroid = flag; } /** * 将指定的数组的内容倒序排序。注意,这会破坏原数组的内容 * * @param arrays * 指定的数组 */ public static <T> void reverse(T[] arrays) { int size = arrays.length; for (int i = 0; i < size; i++) { int ih = i; int it = size - 1 - i; if (ih == it || ih > it) { break; } T ah = arrays[ih]; T swap = arrays[it]; arrays[ih] = swap; arrays[it] = ah; } } @Deprecated public static String simpleMetodDesc(Method method) { return simpleMethodDesc(method); } public static String simpleMethodDesc(Method method) { return String.format("%s.%s(...)", method.getDeclaringClass().getSimpleName(), method.getName()); } public static String fixedHexString(byte[] hashBytes) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < hashBytes.length; i++) { sb.append(Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } /** * 一个便利的方法,将当前线程睡眠一段时间 * * @param ms * 要睡眠的时间 ms */ public static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { throw Lang.wrapThrow(e); } } /** * 一个便利的等待方法同步一个对象 * * @param lock * 锁对象 * @param ms * 要等待的时间 ms */ public static void wait(Object lock, long ms) { if (null != lock) synchronized (lock) { try { lock.wait(ms); } catch (InterruptedException e) { throw Lang.wrapThrow(e); } } } /** * 通知对象的同步锁 * * @param lock * 锁对象 */ public static void notifyAll(Object lock) { if (null != lock) synchronized (lock) { lock.notifyAll(); } } public static void runInAnThread(Runnable runnable) { new Thread(runnable).start(); } /** * map对象浅过滤,返回值是一个新的map * * @param source * 原始的map对象 * @param prefix * 包含什么前缀,并移除前缀 * @param include * 正则表达式 仅包含哪些key(如果有前缀要求,则已经移除了前缀) * @param exclude * 正则表达式 排除哪些key(如果有前缀要求,则已经移除了前缀) * @param keyMap * 映射map, 原始key--目标key (如果有前缀要求,则已经移除了前缀) * @return 经过过滤的map,与原始map不是同一个对象 */ public static Map<String, Object> filter(Map<String, Object> source, String prefix, String include, String exclude, Map<String, String> keyMap) { LinkedHashMap<String, Object> dst = new LinkedHashMap<String, Object>(); if (source == null || source.isEmpty()) return dst; Pattern includePattern = include == null ? null : Regex.getPattern(include); Pattern excludePattern = exclude == null ? null : Regex.getPattern(exclude); for (Entry<String, Object> en : source.entrySet()) { String key = en.getKey(); if (prefix != null) { if (key.startsWith(prefix)) key = key.substring(prefix.length()); else continue; } if (includePattern != null && !includePattern.matcher(key).find()) continue; if (excludePattern != null && excludePattern.matcher(key).find()) continue; if (keyMap != null && keyMap.containsKey(key)) dst.put(keyMap.get(key), en.getValue()); else dst.put(key, en.getValue()); } return dst; } /** * 获得访问者的IP地址, 反向代理过的也可以获得 * * @param request * 请求的req对象 * @return 来源ip */ public static String getIP(HttpServletRequest request) { if (request == null) return ""; String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } if (Strings.isBlank(ip)) return ""; if (isIPv4Address(ip) || isIPv6Address(ip)) { return ip; } return ""; } /** * @return 返回当前程序运行的根目录 */ public static String runRootPath() { String cp = Lang.class.getClassLoader().getResource("").toExternalForm(); if (cp.startsWith("file:")) { cp = cp.substring("file:".length()); } return cp; } public static <T> T copyProperties(Object origin, T target) { return copyProperties(origin, target, null, null, false, true); } public static <T> T copyProperties(Object origin, T target, String active, String lock, boolean ignoreNull, boolean ignoreStatic) { if (origin == null) throw new IllegalArgumentException("origin is null"); if (target == null) throw new IllegalArgumentException("target is null"); Pattern at = active == null ? null : Regex.getPattern(active); Pattern lo = lock == null ? null : Regex.getPattern(lock); Mirror<Object> originMirror = Mirror.me(origin); Mirror<T> targetMirror = Mirror.me(target); Field[] fields = targetMirror.getFields(); for (Field field : originMirror.getFields()) { String name = field.getName(); if (at != null && !at.matcher(name).find()) continue; if (lo != null && lo.matcher(name).find()) continue; if (ignoreStatic && Modifier.isStatic(field.getModifiers())) continue; Object val = originMirror.getValue(origin, field); if (ignoreNull && val == null) continue; for (Field _field : fields) { if (_field.getName().equals(field.getName())) { targetMirror.setValue(target, _field, val); } } // TODO 支持getter/setter比对 } return target; } public static StringBuilder execOutput(String cmd) throws IOException { return execOutput(Strings.splitIgnoreBlank(cmd, " "), Encoding.CHARSET_UTF8); } public static StringBuilder execOutput(String cmd, Charset charset) throws IOException { return execOutput(Strings.splitIgnoreBlank(cmd, " "), charset); } public static StringBuilder execOutput(String cmd[]) throws IOException { return execOutput(cmd, Encoding.CHARSET_UTF8); } public static StringBuilder execOutput(String[] cmd, Charset charset) throws IOException { Process p = Runtime.getRuntime().exec(cmd); p.getOutputStream().close(); InputStreamReader r = new InputStreamReader(p.getInputStream(), charset); StringBuilder sb = new StringBuilder(); Streams.readAndClose(r, sb); return sb; } public static void exec(String cmd, StringBuilder out, StringBuilder err) throws IOException { exec(Strings.splitIgnoreBlank(cmd, " "), Encoding.CHARSET_UTF8, out, err); } public static void exec(String[] cmd, StringBuilder out, StringBuilder err) throws IOException { exec(cmd, Encoding.CHARSET_UTF8, out, err); } public static void exec(String[] cmd, Charset charset, StringBuilder out, StringBuilder err) throws IOException { Process p = Runtime.getRuntime().exec(cmd); p.getOutputStream().close(); InputStreamReader sOut = new InputStreamReader(p.getInputStream(), charset); Streams.readAndClose(sOut, out); InputStreamReader sErr = new InputStreamReader(p.getErrorStream(), charset); Streams.readAndClose(sErr, err); } public static Class<?> loadClassQuite(String className) { try { return loadClass(className); } catch (ClassNotFoundException e) { return null; } } public static byte[] toBytes(Object obj) { try { ByteArrayOutputStream bao = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bao); oos.writeObject(obj); return bao.toByteArray(); } catch (IOException e) { return null; } } @SuppressWarnings("unchecked") public static <T> T fromBytes(byte[] buf, Class<T> klass) { try { return (T) new ObjectInputStream(new ByteArrayInputStream(buf)).readObject(); } catch (ClassNotFoundException e) { return null; } catch (IOException e) { return null; } } public static class JdkTool { public static String getVersionLong() { Properties sys = System.getProperties(); return sys.getProperty("java.version"); } public static int getMajorVersion() { String ver = getVersionLong(); if (Strings.isBlank(ver)) return 6; String[] tmp = ver.split("\\."); if (tmp.length < 2) return 6; int t = Integer.parseInt(tmp[0]); if (t > 1) return t; return Integer.parseInt(tmp[1]); } public static boolean isEarlyAccess() { String ver = getVersionLong(); if (Strings.isBlank(ver)) return false; return ver.contains("-ea"); } /** * 获取进程id * * @param fallback * 如果获取失败,返回什么呢? * @return 进程id */ public static String getProcessId(final String fallback) { final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); final int index = jvmName.indexOf('@'); if (index < 1) { return fallback; } try { return Long.toString(Long.parseLong(jvmName.substring(0, index))); } catch (NumberFormatException e) {} return fallback; } } /** * 判断一个对象是否不为空。它支持如下对象类型: * <ul> * <li>null : 一定为空 * <li>数组 * <li>集合 * <li>Map * <li>其他对象 : 一定不为空 * </ul> * * @param obj * 任意对象 * @return 是否为空 */ public static boolean isNotEmpty(Object obj) { return !isEmpty(obj); } /** * 获取指定字符串的 HmacMD5 值 * * @param data * 字符串 * @param secret * 密钥 * @return 指定字符串的 HmacMD5 值 */ public static String hmacmd5(String data, String secret) { if (isEmpty(data)) throw new NullPointerException("data is null"); if (isEmpty(secret)) throw new NullPointerException("secret is null"); byte[] bytes = null; try { SecretKey secretKey = new SecretKeySpec(secret.getBytes(Encoding.UTF8), "HmacMD5"); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); bytes = mac.doFinal(data.getBytes(Encoding.UTF8)); } catch (Exception e) { e.printStackTrace(); throw Lang.wrapThrow(e); } return fixedHexString(bytes); } /** * 获取指定字符串的 HmacSHA256 值 * * @param data * 字符串 * @param secret * 密钥 * @return 指定字符串的 HmacSHA256 值 */ public static String hmacSHA256(String data, String secret) { if (isEmpty(data)) throw new NullPointerException("data is null"); if (isEmpty(secret)) throw new NullPointerException("secret is null"); byte[] bytes = null; try { SecretKey secretKey = new SecretKeySpec(secret.getBytes(Encoding.UTF8), "HmacSHA256"); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); bytes = mac.doFinal(data.getBytes(Encoding.UTF8)); } catch (Exception e) { e.printStackTrace(); throw Lang.wrapThrow(e); } return fixedHexString(bytes); } /** * 获取指定字符串的 HmacSHA256 值 * * @param data * 字符串 * @param secret * 密钥 * @return 指定字符串的 HmacSHA256 值 */ public static String hmacSHA1(String data, String secret) { if (isEmpty(data)) throw new NullPointerException("data is null"); if (isEmpty(secret)) throw new NullPointerException("secret is null"); byte[] bytes = null; try { SecretKey secretKey = new SecretKeySpec(secret.getBytes(Encoding.UTF8), "HmacSHA1"); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); bytes = mac.doFinal(data.getBytes(Encoding.UTF8)); } catch (Exception e) { e.printStackTrace(); throw Lang.wrapThrow(e); } return fixedHexString(bytes); } }
nutzam/nutz
src/org/nutz/lang/Lang.java
360
package com.vip.vjtools.vjmap; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.List; import com.sun.tools.attach.VirtualMachine; import com.vip.vjtools.vjmap.oops.GenAddressAccessor; import com.vip.vjtools.vjmap.oops.HeapHistogramVisitor; import com.vip.vjtools.vjmap.oops.HeapUtils; import com.vip.vjtools.vjmap.oops.LoadedClassAccessor; import com.vip.vjtools.vjmap.oops.OldgenAccessor; import com.vip.vjtools.vjmap.oops.SurvivorAccessor; import com.vip.vjtools.vjmap.utils.TimeController.TimeoutException; import sun.jvm.hotspot.HotSpotAgent; import sun.jvm.hotspot.oops.ObjectHeap; import sun.jvm.hotspot.runtime.VM; import sun.tools.attach.HotSpotVirtualMachine;; public class VJMap { public static final String VERSION = "1.0.9"; private static PrintStream tty = System.out; // 用于ctrl-C退出时仍然打印结果 private static OldGenProcessor oldGenProcessor; private static HeapProcessor heapProcessor; public static void runHeapVisitor(int pid, boolean orderByName, long minSize) { ObjectHeap heap = VM.getVM().getObjectHeap(); heapProcessor = new HeapProcessor(orderByName, minSize); tty.println("Iterating over heap. This may take a while..."); tty.println("Geting live regions..."); heap.iterate(heapProcessor.visitor); heapProcessor.printResult(); heapProcessor = null; } public static class HeapProcessor { HeapHistogramVisitor visitor = new HeapHistogramVisitor(); boolean orderByName; long minSize; public HeapProcessor(boolean orderByName, long minSize) { this.orderByName = orderByName; this.minSize = minSize; } public void printResult() { List<ClassStats> list = HeapUtils.getClassStatsList(visitor.getClassStatsMap()); ResultPrinter resultPrinter = new ResultPrinter(); resultPrinter.printAllGens(tty, list, orderByName, minSize); } } public static void runSurviorAccessor(int age, int minAge, boolean orderByName, long minSize) { SurvivorAccessor accessor = new SurvivorAccessor(); tty.println("Iterating over survivor area. This may take a while..."); List<ClassStats> list = accessor.caculateHistogram(age, minAge); ResultPrinter resultPrinter = new ResultPrinter(); resultPrinter.printSurvivor(tty, list, orderByName, minSize, age, minAge); } public static void runOldGenAccessor(boolean orderByName, long minSize) { oldGenProcessor = new OldGenProcessor(orderByName, minSize); tty.println("Iterating over oldgen area. This may take a while..."); oldGenProcessor.accessor.caculateHistogram(); oldGenProcessor.printResult(); oldGenProcessor = null; } public static class OldGenProcessor { OldgenAccessor accessor = new OldgenAccessor(); boolean orderByName; long minSize; public OldGenProcessor(boolean orderByName, long minSize) { this.orderByName = orderByName; this.minSize = minSize; } public void printResult() { List<ClassStats> list = HeapUtils.getClassStatsList(accessor.getClassStatsMap()); ResultPrinter resultPrinter = new ResultPrinter(); resultPrinter.printOldGen(tty, list, orderByName, minSize); } } public static void printGenAddress() { GenAddressAccessor accessor = new GenAddressAccessor(); accessor.printHeapAddress(); } public static void printLoadedClass() { LoadedClassAccessor accessor = new LoadedClassAccessor(); accessor.pringLoadedClass(); } public static void main(String[] args) { // 分析参数 boolean orderByName = false; long minSize = -1; int minAge = 2; int age = -1; boolean live = false; // boolean dead = false; if (!(args.length == 2 || args.length == 3)) { printHelp(); return; } String modeFlag = args[0]; String[] modeFlags = modeFlag.split(":"); if (modeFlags.length > 1) { String[] addtionalFlags = modeFlags[1].split(","); for (String addtionalFlag : addtionalFlags) { if ("byname".equalsIgnoreCase(addtionalFlag)) { orderByName = true; } else if (addtionalFlag.toLowerCase().startsWith("minsize")) { String[] values = addtionalFlag.split("="); if (values.length == 1) { tty.println("parameter " + addtionalFlag + " is wrong"); return; } minSize = Long.parseLong(values[1]); } else if (addtionalFlag.toLowerCase().startsWith("minage")) { String[] values = addtionalFlag.split("="); if (values.length == 1) { tty.println("parameter " + addtionalFlag + " is wrong"); return; } minAge = Integer.parseInt(values[1]); } else if (addtionalFlag.toLowerCase().startsWith("age")) { String[] values = addtionalFlag.split("="); if (values.length == 1) { tty.println("parameter " + addtionalFlag + " is wrong"); return; } age = Integer.parseInt(values[1]); } else if (addtionalFlag.toLowerCase().startsWith("live")) { live = true; } } } Integer pid = null; String executablePath = null; String coredumpPath = null; if (args.length == 2) { pid = Integer.valueOf(args[1]); } else { executablePath = args[1]; coredumpPath = args[2]; } // 如有需要,执行GC if (live) { if (pid == null) { tty.println("only a running vm can be attached when live option is on"); return; } triggerGc(pid); } //// 正式执行 HotSpotAgent agent = new HotSpotAgent(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // 如果ctrl+C退出,仍尽量打印结果 if (oldGenProcessor != null) { tty.println("VJMap aborted. Below is the incomplete summary: "); oldGenProcessor.printResult(); } if (heapProcessor != null) { tty.println("VJMap aborted. Below is the incomplete summary: "); heapProcessor.printResult(); } tty.flush(); } }); try { if (args.length == 2) { agent.attach(pid); } else { agent.attach(executablePath, coredumpPath); } long startTime = System.currentTimeMillis(); if (modeFlag.startsWith("-all")) { runHeapVisitor(pid, orderByName, minSize); } else if (modeFlag.startsWith("-sur")) { runSurviorAccessor(age, minAge, orderByName, minSize); } else if (modeFlag.startsWith("-old")) { runOldGenAccessor(orderByName, minSize); } else if (modeFlag.startsWith("-address")) { printGenAddress(); } else if (modeFlag.startsWith("-class")) { printLoadedClass(); } else if (modeFlag.startsWith("-version")) { tty.println("vjmap version:" + VERSION); return; } else { printHelp(); return; } long endTime = System.currentTimeMillis(); double secs = (endTime - startTime) / 1000.0d; tty.printf("%n Heap traversal took %.1f seconds.%n", secs); tty.flush(); } catch (TimeoutException e) { tty.println("\n\nVJMap aborted by timeout."); tty.println("Try to use live option to reduce the fragments which make progress very slow."); tty.println("./vjmap.sh -old:live PID\n\n"); } catch (Exception e) { tty.println("Error Happen:" + e.getMessage()); if (e.getMessage() != null && e.getMessage().contains("Can't attach to the process")) { tty.println( "Please use the same user of the target JVM to run vjmap, or use root user to run it (sudo -E vjmap.sh ...)"); } } finally { agent.detach(); } } /** * Trigger a remote gc using HotSpotVirtualMachine, inspired by jcmd's source code. * * @param pid */ private static void triggerGc(Integer pid) { VirtualMachine vm = null; try { vm = VirtualMachine.attach(String.valueOf(pid)); HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm; try (InputStream in = hvm.executeJCmd("GC.run");) { byte b[] = new byte[256]; int n; do { n = in.read(b); if (n > 0) { String s = new String(b, 0, n, "UTF-8"); tty.print(s); } } while (n > 0); tty.println(); } } catch (Exception e) { tty.println(e.getMessage()); } finally { if (vm != null) { try { vm.detach(); } catch (IOException e) { tty.println(e.getMessage()); } } } } private static void printHelp() { int leftLength = "-all:minsize=1024,byname".length(); String format = " %-" + leftLength + "s %s%n"; tty.println("vjmap " + VERSION + " - prints per GC generation (Eden, Survivor, OldGen) object details of a given process."); tty.println("Usage: vjmap.sh <options> <PID>"); tty.println("Usage: vjmap.sh <options> <executable java path> <coredump file path>"); tty.println(""); tty.printf(format, "-all", "print all gens histogram, order by total size"); tty.printf(format, "-all:live", "print all gens histogram, live objects only"); tty.printf(format, "-all:minsize=1024", "print all gens histogram, total size>=1024"); tty.printf(format, "-all:minsize=1024,byname", "print all gens histogram, total size>=1024, order by class name"); tty.printf(format, "-old", "print oldgen histogram, order by oldgen size"); tty.printf(format, "-old:live", "print oldgen histogram, live objects only"); tty.printf(format, "-old:minsize=1024", "print oldgen histogram, oldgen size>=1024"); tty.printf(format, "-old:minsize=1024,byname", "print oldgen histogram, oldgen size>=1024, order by class name"); tty.printf(format, "-sur", "print survivor histogram, age>=2"); tty.printf(format, "-sur:age=4", "print survivor histogram, age==4"); tty.printf(format, "-sur:minage=4", "print survivor histogram, age>=4, default is 2"); tty.printf(format, "-sur:minsize=1024,byname", "print survivor histogram, age>=3, survivor size>=1024, order by class name"); tty.printf(format, "-address", "print address for all gens"); tty.printf(format, "-class", "print all loaded classes"); } }
vipshop/vjtools
vjmap/src/main/java/com/vip/vjtools/vjmap/VJMap.java
361
package org.nutz.lang; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.nutz.lang.util.Callback2; import org.nutz.lang.util.NutMap; import org.nutz.lang.util.Regex; import org.nutz.lang.util.Tag; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * XML 的快捷帮助函数 * * @author zozoh([email protected]) */ public abstract class Xmls { /** * 帮你快速获得一个 DocumentBuilder,方便 XML 解析。 * * @return 一个 DocumentBuilder 对象 * @throws ParserConfigurationException */ public static DocumentBuilder xmls() throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); String FEATURE = null; // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl FEATURE = "http://apache.org/xml/features/disallow-doctype-decl"; dbf.setFeature(FEATURE, true); // If you can't completely disable DTDs, then at least do the following: // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities // JDK7+ - http://xml.org/sax/features/external-general-entities FEATURE = "http://xml.org/sax/features/external-general-entities"; dbf.setFeature(FEATURE, false); // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities // JDK7+ - http://xml.org/sax/features/external-parameter-entities FEATURE = "http://xml.org/sax/features/external-parameter-entities"; dbf.setFeature(FEATURE, false); // Disable external DTDs as well FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; dbf.setFeature(FEATURE, false); // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); return dbf.newDocumentBuilder(); } public static Document xml(InputStream ins) { return xml(ins, null); } /** * 快捷的解析 XML 文件的帮助方法,它会主动关闭输入流 * * @param ins * XML 文件输入流 * @return Document 对象 */ public static Document xml(InputStream ins, Charset charset) { try { if (charset == null) charset = Encoding.CHARSET_UTF8; return xmls().parse(new InputSource(new InputStreamReader(ins, charset))); } catch (SAXException e) { throw Lang.wrapThrow(e); } catch (IOException e) { throw Lang.wrapThrow(e); } catch (ParserConfigurationException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(ins); } } public static Document xml(File xmlFile) { return xml(xmlFile, null); } /** * 快捷的解析 XML 文件的帮助方法 * * @param xmlFile * XML 文件 * @return Document 对象 */ public static Document xml(File xmlFile, Charset charset) { InputStream ins = null; try { ins = new FileInputStream(xmlFile); return xml(ins, charset); } catch (Exception e) { throw Lang.wrapThrow(e); } } /** * 获取某元素下某节点的全部文本内容(去掉左右空白) * * @param ele * 元素 * @param subTagName * 子元素名 * @return 内容,null 表示子元素不存在, 空串表示元素没有对应文本内容 */ public static String get(Element ele, String subTagName) { Element sub = firstChild(ele, subTagName); if (null == sub) return null; return getText(sub); } public static String getText(Element ele) { StringBuilder sb = new StringBuilder(); joinText(ele, sb); return Strings.trim(sb); } public static void joinText(Element ele, StringBuilder sb) { if (null == ele) return; NodeList nl = ele.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node nd = nl.item(i); switch (nd.getNodeType()) { case Node.TEXT_NODE: sb.append(nd.getNodeValue()); break; case Node.CDATA_SECTION_NODE: sb.append(nd.getNodeValue()); break; case Node.ELEMENT_NODE: joinText((Element) nd, sb); break; default: break; } } } /** * 获取 XML 元素内第一个子元素 * * @param ele * XML 元素 * @return 子元素,null 表示不存在 */ public static Element firstChild(Element ele) { final Element[] tag = new Element[1]; eachChildren(ele, null, new Each<Element>() { public void invoke(int index, Element cld, int length) { tag[0] = cld; Lang.Break(); } }); return tag[0]; } /** * 获取 XML 元素内第一个名字所有符合一个正则表达式的子元素 * * @param ele * XML 元素 * @param regex * 元素名称正则表达式 * @return 子元素,null 表示不存在 */ public static Element firstChild(Element ele, String regex) { final Element[] tag = new Element[1]; eachChildren(ele, regex, new Each<Element>() { public void invoke(int index, Element cld, int length) { tag[0] = cld; Lang.Break(); } }); return tag[0]; } /** * 从一个 XML 元素开始,根据一条 XPath 获取一个元素 * * @param ele * XML 元素 * @param xpath * 要获取的元素的 XPath * @return 元素,null 表示不存在 */ public static Element getEle(Element ele, String xpath) { XPathFactory factory = XPathFactory.newInstance(); XPath xp = factory.newXPath(); try { XPathExpression expression = xp.compile(xpath); return (Element) expression.evaluate(ele, XPathConstants.NODE); } catch (XPathExpressionException e) { throw Lang.wrapThrow(e); } } /** * 从某个元素里获取一个指定下标的子元素 * * @param ele * XML 元素 * @param index * 子元素下标(0 base) * @return 子元素 */ public static Element getChild(Element ele, int index) { return getChild(ele, index, null); } /** * 从某个元素里获取一个指定下标且指定名称的子元素 * * @param ele * XML 元素 * @param index * 子元素下标(0 base) * @param regex * 元素名称的正则表达式 * @return 子元素 */ public static Element getChild(Element ele, final int index, String regex) { final int pos = index; final Element[] tag = new Element[1]; eachChildren(ele, null, new Each<Element>() { public void invoke(int index, Element cld, int length) { if (index >= pos) { tag[0] = cld; Lang.Break(); } } }); return tag[0]; } /** * 获取 XML 元素内最后一个子元素 * * @param ele * XML 元素 * @return 子元素,null 表示不存在 */ public static Element lastChild(Element ele) { final Element[] tag = new Element[1]; eachChildren(ele, null, new Each<Element>() { public void invoke(int index, Element cld, int length) { tag[0] = cld; Lang.Break(); } }, -1); return tag[0]; } /** * 获取 XML 元素内最后一个名字所有符合一个正则表达式的子元素 * * @param ele * XML 元素 * @param regex * 元素名称正则表达式 * @return 子元素,null 表示不存在 */ public static Element lastChild(Element ele, String regex) { final Element[] tag = new Element[1]; eachChildren(ele, regex, new Each<Element>() { public void invoke(int index, Element cld, int length) { tag[0] = cld; Lang.Break(); } }, -1); return tag[0]; } /** * 获取 XML 元素内所有子元素 * * @param ele * XML 元素 * @return 一个子元素的列表 */ public static List<Element> children(Element ele) { return children(ele, null); } /** * 获取 XML 元素内名字符合一个正则表达式的元素 * * @param ele * XML 元素 * @param regex * 元素名称正则表达式 * @return 一个子元素的列表 */ public static List<Element> children(Element ele, String regex) { final List<Element> list = new ArrayList<Element>(ele.getChildNodes().getLength()); eachChildren(ele, regex, new Each<Element>() { public void invoke(int index, Element cld, int length) { list.add(cld); } }); return list; } /** * 迭代 XML 元素内所有子元素 * * @param ele * XML 元素 * @param callback * 回调 */ public static void eachChildren(Element ele, Each<Element> callback) { eachChildren(ele, null, callback); } /** * 迭代 XML 元素内名字符合一个正则表达式的子元素 * * @param ele * XML 元素 * @param regex * 元素名称正则表达式 * @param callback * 回调 */ public static void eachChildren(Element ele, String regex, final Each<Element> callback) { Xmls.eachChildren(ele, regex, callback, 0); } /** * 判断某个元素下是否有子元素 * * @param ele * 元素 * @param regex * 子元素名称的正则表达式,如果为 null,则元素内如果有任意元素都会返回 false * @return 是否有子元素 */ public static boolean hasChild(Element ele, String regex) { NodeList nl = ele.getChildNodes(); int len = nl.getLength(); for (int i = 0; i < len; i++) { Node nd = nl.item(i); if (nd instanceof Element) { if (null == regex) return false; if (Regex.match(regex, ((Element) nd).getTagName())) return true; } } return false; } /** * 迭代 XML 元素内名字符合一个正则表达式的子元素 * * @param ele * XML 元素 * @param regex * 元素名称正则表达式 * @param callback * 回调 * @param off * 偏移量。0 表示从第一个迭代。 -1 表示从最后一个迭代。-2表示从倒数第二个迭代 */ public static void eachChildren(Element ele, String regex, final Each<Element> callback, int off) { if (null == ele || null == callback) return; // 正则式 final Pattern p = null == regex ? null : Pattern.compile(regex); NodeList nl = ele.getChildNodes(); // 循环子 final int len = nl.getLength(); // 每次循环执行 Callback2<Integer, Node> eachInvoke = new Callback2<Integer, Node>() { public void invoke(Integer index, Node nd) { if (nd instanceof Element) try { Element tag = (Element) nd; if (null == p || p.matcher(tag.getTagName()).find()) callback.invoke(index, tag, len); } catch (ExitLoop e) { throw Lang.wrapThrow(e); } catch (ContinueLoop e) {} catch (LoopException e) { throw Lang.wrapThrow(e); } } }; try { // 负向迭代 if (off < 0) { for (int i = len + off; i >= 0; i--) { eachInvoke.invoke(i, nl.item(i)); } } // 正向迭代 else { for (int i = off; i < len; i++) { eachInvoke.invoke(i, nl.item(i)); } } } catch (ExitLoop e) {} catch (RuntimeException e) { if (e.getCause() instanceof ExitLoop) return; else throw e; } } /** * 获取该 XML 元素内所有的属性的值,按照Map的形式返回 * * @param ele * XML 元素 * @return 所有属性的值 */ public static Map<String, String> getAttrs(Element ele) { NamedNodeMap nodeMap = ele.getAttributes(); Map<String, String> attrs = new HashMap<String, String>(nodeMap.getLength()); for (int i = 0; i < nodeMap.getLength(); i++) { attrs.put(nodeMap.item(i).getNodeName(), nodeMap.item(i).getNodeValue()); } return attrs; } /** * 从 XML 元素中得到指定属性的值,如该指定属性不存在,则返回Null * * @param ele * XML 元素 * @return 该指定属性的值 */ public static String getAttr(Element ele, String attrName) { Node node = ele.getAttributes().getNamedItem(attrName); return node != null ? node.getNodeValue() : null; } /** * 根据一个 XML 节点,将其变成一个 Map。 * <p/> * <b>注意: 不支持混合节点</b> * * @param ele * 元素 * * @return 一个 Map 对象 */ public static NutMap asMap(Element ele) { return asMap(ele, false); } /** * 根据一个 XML 节点,将其变成一个 Map。 * <p/> * <b>注意: 不支持混合节点</b> * * @param ele * 元素 * @param lowFirst * 是否把所有key的首字母都小写 * * @return 一个 Map 对象 */ public static NutMap asMap(Element ele, final boolean lowFirst) { return asMap(ele, lowFirst, false); } public static NutMap asMap(Element ele, final boolean lowFirst, final boolean dupAsList) { return asMap(ele, lowFirst, dupAsList, null); } public static NutMap asMap(Element ele, final boolean lowerFirst, final boolean dupAsList, final List<String> alwaysAsList) { return asMap(ele, new XmlParserOpts(lowerFirst, dupAsList, alwaysAsList, false)); } public static NutMap asMap(Element ele, final XmlParserOpts opts) { final NutMap map = new NutMap(); if (opts.isAttrAsKeyValue()) { NamedNodeMap attrs = ele.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { map.put(attrs.item(i).getNodeName(), attrs.item(i).getNodeValue()); } } eachChildren(ele, new Each<Element>() { public void invoke(int index, Element _ele, int length) throws ExitLoop, ContinueLoop, LoopException { String key = _ele.getNodeName(); if (opts.lowerFirst) key = Strings.lowerFirst(key); Map<String, Object> tmp = asMap(_ele, opts); if (!tmp.isEmpty()) { if (opts.alwaysAsList != null && opts.alwaysAsList.contains(key)) { map.addv2(key, tmp); } else if (opts.dupAsList) { map.addv(key, tmp); } else { map.setv(key, tmp); } return; } String val = getText(_ele); if (opts.keeyBlankNode || !Strings.isBlank(val)) { if (opts.alwaysAsList != null && opts.alwaysAsList.contains(key)) { map.addv2(key, val); } else if (opts.dupAsList) map.addv(key, val); else map.setv(key, val); } } }); return map; } /** * 将一个下面格式的 XML: * * <pre> * &lt;xml&gt; * &lt;key1&gt;value1&lt;/key1&gt; * &lt;key2&gt;value2&lt;/key2&gt; * &lt;/xml&gt; * </pre> * * 转换成一个 Map * * @param xml * XML 字符串 * * @return Map */ public static NutMap xmlToMap(String xml) { return Xmls.asMap(Xmls.xml(Lang.ins(xml)).getDocumentElement()); } public static NutMap xmlToMap(InputStream ins) { return Xmls.asMap(Xmls.xml(ins).getDocumentElement()); } public static NutMap xmlToMap(InputStream ins, final boolean lowerFirst, final boolean dupAsList, final List<String> alwaysAsList) { return Xmls.asMap(Xmls.xml(ins).getDocumentElement(), lowerFirst, dupAsList, alwaysAsList); } /** * 将一个 Map 转换成 XML 类似: * * <pre> * &lt;xml&gt; * &lt;key1&gt;value1&lt;/key1&gt; * &lt;key2&gt;value2&lt;/key2&gt; * &lt;/xml&gt; * </pre> * * @param map * Map * @return XML 字符串 */ public static String mapToXml(Map<String, Object> map) { return mapToXml("xml", map); } public static String mapToXml(String root, Map<String, Object> map) { StringBuilder sb = new StringBuilder(); map2Tag(root, map).toXml(sb, 0); return sb.toString(); } protected static Tag map2Tag(String rootName, Map<String, Object> map) { Tag rootTag = Tag.tag(rootName); for (Map.Entry<String, Object> en : map.entrySet()) { String key = en.getKey(); Object val = en.getValue(); List<Tag> children = obj2tag(key, val); for (Tag child : children) { rootTag.add(child); } } return rootTag; } @SuppressWarnings({"unchecked", "rawtypes"}) public static List<Tag> obj2tag(String nodeName, Object val) { List<Tag> tags = new ArrayList<Tag>(); if (null == val) return tags; if (val instanceof Map) { tags.add(map2Tag(nodeName, (Map<String, Object>) val)); } else if (val instanceof Collection) { for (Object object : (Collection)val) { for (Tag tag : obj2tag(nodeName, object)) { tags.add(tag); } } } else { tags.add(Tag.tag(nodeName).setText(val.toString())); } return tags; } /** * 从一个 XML 元素开始,根据一条 XPath 获取一组元素 * * @param ele * XML 元素 * @param xpath * 要获取的元素的 XPath * @return 元素列表 */ public static List<Element> getEles(Element ele, String xpath) { XPathFactory factory = XPathFactory.newInstance(); XPath xp = factory.newXPath(); try { XPathExpression expression = xp.compile(xpath); NodeList nodes = (NodeList) expression.evaluate(ele, XPathConstants.NODESET); List<Element> list = new ArrayList<Element>(); int len = nodes.getLength(); for (int i = 0; i < len; i++) { Node node = nodes.item(i); if (node instanceof Element) { list.add((Element)node); } } return list; } catch (XPathExpressionException e) { throw Lang.wrapThrow(e); } } public static String HEAD = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; public static class XmlParserOpts { private boolean lowerFirst; private boolean dupAsList; private List<String> alwaysAsList; private boolean keeyBlankNode; private boolean attrAsKeyValue; public XmlParserOpts() { } public XmlParserOpts(boolean lowerFirst, boolean dupAsList, List<String> alwaysAsList, boolean keeyBlankNode) { super(); this.lowerFirst = lowerFirst; this.dupAsList = dupAsList; this.alwaysAsList = alwaysAsList; this.keeyBlankNode = keeyBlankNode; } public boolean isLowerFirst() { return lowerFirst; } public void setLowerFirst(boolean lowerFirst) { this.lowerFirst = lowerFirst; } public boolean isDupAsList() { return dupAsList; } public void setDupAsList(boolean dupAsList) { this.dupAsList = dupAsList; } public List<String> getAlwaysAsList() { return alwaysAsList; } public void setAlwaysAsList(List<String> alwaysAsList) { this.alwaysAsList = alwaysAsList; } public boolean isKeeyBlankNode() { return keeyBlankNode; } public void setKeeyBlankNode(boolean keeyBlankNode) { this.keeyBlankNode = keeyBlankNode; } public boolean isAttrAsKeyValue() { return attrAsKeyValue; } public void setAttrAsKeyValue(boolean attrAsKeyValue) { this.attrAsKeyValue = attrAsKeyValue; } } }
nutzam/nutz
src/org/nutz/lang/Xmls.java
363
/** * 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.util.List; /** * Created by lfh on 2016/8/15. */ public class BookListDetail extends Base{ /** * _id : 57c3ffcabbba8a463aab9959 * updated : 2016-08-29T09:49:09.726Z * title : 发现一大批免费精品,好赞! * author : {"_id":"576680476fc4bac56b03e67c", * "avatar":"/avatar/b0/df/b0df89144226ec91bf3a68bba32431cd","nickname":"书荒终结者", * "type":"normal","lv":6} * desc : 统统都是大神的书,简直赚到了,看书不用愁没钱了! * gender : female * created : 2016-08-29T09:26:34.832Z * tags : ["宠文","总裁","古代言情"] * stickStopTime : null * isDraft : false * isDistillate : null * collectorCount : 3194 * books : [{"book":{"_id":"57a7ec3c8083239c141b5207","title":"强势夺爱:顾先生请自重","author":"金佑木木", * "longIntro":"\"秦阮阮\u201c分手大师\u201d的名号打得响,却一脚踩在了\u201c天王老子\u201d顾临泫的脚上。\r\n\r\n * 一毛钱没赚到不说,还被逼倒欠三百万!\r\n\r\n没办法,为了还债,她不得不以身犯险,这险套路太深,她防不胜防。\r\n\r\n最后逼得日日夜夜被压着\u201c还债\u201d * ,赔了夫人又折兵。\r\n\r\n顾临泫最擅长的事就是翻手为云覆手为雨,以前是用在商场上,后来是用在秦阮阮身上,秦阮阮是他的云,是他的雨,把她扔床上翻来覆去,不知疲惫\u2026 * \u2026\"\r\n","cover":"/cover/147132509933927","site":"zhuishuvip","banned":0, * "latelyFollower":4392,"latelyFollowerBase":0,"wordCount":146559,"minRetentionRatio":0, * "retentionRatio":27.35},"comment":"秦阮阮\u201c分手大师\u201d的名号打得响,却一脚踩在了\u201c天王老子\u201d顾临泫的脚上。 * 一毛钱没赚到不说,还被逼倒欠三百万! 没办法,为了还债,她不得不以身犯险,这险套路太深,她防不胜防。 最后逼得日日夜夜被压着\u201c还债\u201d,赔了夫人又折兵。 * 顾临泫最擅长的事就是翻手为云覆手为雨,以前是用在商场上,后来是用在秦阮阮身上,秦阮阮是他的云,是他的雨,把她扔床上翻来覆去,不知疲惫\u2026\u2026"}, * {"book":{"_id":"573d3e7e608bed4124524223","title":"鲜妻惹火:腹黑总裁太凶猛","author":"落雪", * "longIntro":"她只是想拿回父亲的遗物,却硬是被这个男人扣留在身边。\r\n他本想把她训练成供自己利用的间谍,不成想自己竟会沉溺于这样一个看起来平凡无奇的女人身上。\r * \n阴谋,陷害,被人冒充,甚至失去了孩子\u2026\u2026","cover":"/cover/147131956928013","site":"zhuishuvip", * "banned":0,"latelyFollower":3641,"latelyFollowerBase":0,"wordCount":582513, * "minRetentionRatio":0,"retentionRatio":30.11},"comment":"她夜探陆氏城堡,本只想拿回属于父亲的遗物, * 谁知看到了不该看的现代版春宫图,差点让她流鼻血长针眼\u2026\u2026 腹黑总裁非要冤枉她是个偷窥狂,毫不客气的将她扑倒,她求饶,喊\u201c不要\u201d * 他邪魅一笑:\u201c我不要听你上面这张嘴,我要听你下面这张嘴的!\u201d \u201c\u2026\u2026\u201d * 于是,日日缠绵,夜夜索取,终于有一日,小绵羊爆发了\u2026\u2026"},{"book":{"_id":"5757c4c197dd36c7423fdad4", * "title":"盛世女医:冷王宠妃","author":"墨如歌", * "longIntro":"一朝穿越,她成了女扮男装的柳靖澜。好吧!为了完成身体原主心愿她继续留在军营。可是这洗澡\u2026\u2026 * 如何解决?半夜三更去河里洗澡被人看的光光不算,还被吃了豆腐。尼玛!吃了豆腐还不算,还要她去医治他?治好了还要陪睡?天理何在?片段:某女上完如厕出来掉了一块布袋。某男问:\u201c * 这是何物?\u201d某女囧然,尴尬道:\u201c此物名曰苏菲。\u201d某男继续问:\u201c有何用?\u201d某女笑着回答:\u201c * 此物瞬吸干爽,丝柔如绸,超薄不漏,一片苏菲让整个夏季不再惧怕流汗,有了它,男人再也不怕盗汗。\u201d某男疑惑的捡起苏菲,\u201c那这块本王要了。\u201c", * "cover":"/cover/146666376301235","site":"zhuishuvip","banned":0,"latelyFollower":4768, * "latelyFollowerBase":0,"wordCount":766125,"minRetentionRatio":0,"retentionRatio":28.58}, * "comment":"某女上完如厕出来掉了一块布袋。 某男问:\u201c这是何物?\u201d 某女囧然,尴尬道:\u201c此物名曰苏菲。\u201d * 某男继续问:\u201c有何用?\u201d 某女笑着回答:\u201c此物瞬吸干爽,丝柔如绸,超薄不漏,一片苏菲让整个夏季不再惧怕流汗,有了它,男人再也不怕盗汗。\u201d * 某男疑惑的捡起苏菲,\u201c那这块本王要了。\u201c"},{"book":{"_id":"57bec945f2ab9d805babd0ba", * "title":"总裁前夫:本老婆要跑了!","author":"傲娇小公举", * "longIntro":"三年前,他扔给她一份离婚协议书,逼她离婚。\n三年后,他费尽心机的,又想把她找回来。\n陆小雪表示:爱情不是你想买,想买就能买!\n * 老娘还有整片森林要宠幸,何必单恋前夫这颗回头草!\n这只老污龟,臭流氓,她才不要再看他一眼咧!\n某总裁表示:大家都睡得这么熟了,懒得再换一个了,老婆还是原装的好。\n\u2026 * \u2026\u2026\u2026\u2026\u2026\n记者:请问陆小雪小姐,为什么会选择复婚呢?\n陆小雪:他逼我的!\n记者:那孩子\u2026\u2026\n * 陆小雪:他逼我生的!\n记者:有什么想对顾先生说的?\n陆小雪:老污龟,咱俩走着瞧!","cover":"/agent/http://rm2.kingreader * .com/book/1174752%2Fm%2F%5B640%5D_%E6%80%BB%E8%A3%81%E5%89%8D%E5%A4%AB%EF%BC%9A%E6%9C%AC * %E8%80%81%E5%A9%86%E8%A6%81%E8%B7%91%E4%BA%86%EF%BC%81.jpg","site":"zhuishuvip", * "banned":0,"latelyFollower":1048,"latelyFollowerBase":0,"wordCount":19763, * "minRetentionRatio":0,"retentionRatio":null},"comment":"三年前,他扔给她一份离婚协议书,逼她离婚。 * 三年后,他费尽心机的,又想把她找回来。 陆小雪表示:爱情不是你想买,想买就能买! 老娘还有整片森林要宠幸,何必单恋前夫这颗回头草! 这只老污龟,臭流氓,她才不要再看他一眼咧! * 某总裁表示:大家都睡得这么熟了,懒得再换一个了,老婆还是原装的好。"},{"book":{"_id":"55de7ad2a6b9f7203be2d2b8", * "title":"鬼王盛宠:纨绔医妃有点野","author":"听禅", * "longIntro":"楚国左相府大小姐其丑无比,却嫁给了风华绝代的晋王为妃。\n众人嗟叹,暴殄天物啊!\n所以成婚当日,左右两侧妃同时进门,丑女正妃独守空房半年之久!\n * 顾容裳听着各种传言,掏掏耳朵,淡定拿着休书调戏各路小鲜肉!\n当有一天,她露出那绝世容颜\u2026\u2026\n\u201c顾容裳,你是本王的女人!\u201d * 晋王邪气侧漏,霸道宣称。\n某女无谓撇撇嘴,左手小鲜肉,右手美型男。\u201c * 抱歉啊王爷,古人云,金钱如粪土,男人如底裤,你这条别人穿过的底裤,在本小姐看来,连粪土都不如!\u201d","cover":"/agent/http://img1 * .chuangshi.qq.com/upload/cover/20150728/cb_55b7164f7fc6b.jpg","cat":"穿越", * "site":"zhuishuvip","banned":0,"latelyFollower":2630,"latelyFollowerBase":0, * "wordCount":1974141,"minRetentionRatio":0,"retentionRatio":29.22}, * "comment":"楚国左相府大小姐其丑无比,却嫁给了风华绝代的晋王为妃。众人嗟叹,暴殄天物啊!所以成婚当日,左右两侧妃同时进门,丑女正妃独守空房半年之久!顾容裳听着各种传言,掏掏耳朵,淡定拿着休书调戏各路小鲜肉!当有一天,她露出那绝世容颜\u2026\u2026\u201c顾容裳,你是本王的女人!\u201d晋王邪气侧漏,霸道宣称。某女无谓撇撇嘴,左手小鲜肉,右手美型男。\u201c抱歉啊王爷,古人云,金钱如粪土,男人如底裤,你这条别人穿过的底裤,在本小姐看来,连粪土都不如!\u201d"},{"book":{"_id":"546f6d27431d28897c83dd9f","title":"迷糊俏医妃","author":"听禅","longIntro":"身为东晋被遗弃山林变成野人的宰相嫡女,凤亦禅表示无压力。\n只是你们一抢嫁妆二嘲讽三还让姐替嫁的,是要闹哪样?\n更有莫名其妙跑出来的熊孩子叫她娘?\n\u201c娘,我想吃奶奶\u2026\u2026\u201d粉雕玉琢的奶娃一脸的期待望着某个隆起的部位咬着手指可怜巴巴的道。\n\u201c谁是你娘?\u201d没看见小姐我是青春貌美的黄花大闺女一枚吗?\n\u201c你呀,爹说的\u2026\u2026\u201d麋鹿般的大眼用力的眨了眨奶声奶气的回答。\n凤亦禅怒!你爹谁!让他过来裤脱我看!我要验明正身!\n老书《腹黑嫡女:绝色小医妃》已完结,坑品保证,大家放心跳坑吧!","cover":"/agent/http://img1.chuangshi.qq.com/upload/cover/20141117/cb_54696d6705b56.jpg","site":"zhuishuvip","cat":"女尊","banned":0,"latelyFollower":1453,"latelyFollowerBase":0,"wordCount":1892171,"minRetentionRatio":0,"retentionRatio":null},"comment":"身为东晋被遗弃山林变成野人的宰相嫡女,凤亦禅表示无压力。 只是你们一抢嫁妆二嘲讽三还让姐替嫁的,是要闹哪样? 更有莫名其妙跑出来的熊孩子叫她娘? \u201c娘,我想吃奶奶\u2026\u2026\u201d粉雕玉琢的奶娃一脸的期待望着某个隆起的部位咬着手指可怜巴巴的道。 \u201c谁是你娘?\u201d没看见小姐我是青春貌美的黄花大闺女一枚吗? \u201c你呀,爹说的\u2026\u2026\u201d麋鹿般的大眼用力的眨了眨奶声奶气的回答。 凤亦禅怒!你爹谁!让他过来裤脱我看!我要验明正身!"},{"book":{"_id":"5448e33477ee09b00c6f4b9f","title":"腹黑嫡女:绝色小医妃","author":"听禅","longIntro":"一朝穿越,她成了懦弱无能的嫡出三小姐?爹不疼娘重病还带了个奶包小妹?\n没关系,她一身医术在手,还怕找不到出路么?\n什么?大人,你那方面无能?这个\u2026\u2026民女,也能治!\n某个夜深人静的晚上,中了那春药的某王眼神迷离\u2026\u2026\n那个,王爷,春药什么的,民女不可解!\n某王眼神妖娆拉过来强行扑倒之\u2026\u2026\u201c本王自可解!\u201d\n这是一个外冷内狂的医女扑倒某强大男神的故事\u2026\u2026","cover":"/agent/http://img1.chuangshi.qq.com/upload/cover/20140812/cb_53e9d1448dfde.jpg","site":"zhuishuvip","cat":"种田","banned":0,"latelyFollower":1263,"latelyFollowerBase":0,"wordCount":1714346,"minRetentionRatio":0,"retentionRatio":13.08},"comment":"一朝穿越,她成了懦弱无能的嫡出三小姐?爹不疼娘重病还带了个奶包小妹? 没关系,她一身医术在手,还怕找不到出路么? 什么?大人,你那方面无能?这个\u2026\u2026民女,也能治! 某个夜深人静的晚上,中了那春药的某王眼神迷离\u2026\u2026 那个,王爷,春药什么的,民女不可解! 某王眼神妖娆拉过来强行扑倒之\u2026\u2026\u201c本王自可解!\u201d 这是一个外冷内狂的医女扑倒某强大男神的故事\u2026\u2026"},{"book":{"_id":"57640044fdb169cb79d317e3","title":"悠哉兽世:种种田,生生崽","author":"白头梦","longIntro":"一跤跌到兽人世界,被一头花豹强掳回家,白箐箐的心情是崩溃的。\n这个世界的雄性各各长的跟花孔雀一样华丽英俊,雌性却都是丑女无敌,长的丑还被雄性宠上天。\n她本来只能算清秀的高中生,在这里却成了绝美尤物,迷死兽了。\n最最最恶搞的是,这里还是母系社会,姐可不想三夫四侍啊!\n撩花豹,逗猛虎,诱毒蛇,擒雄鹰。后宫充实的白箐箐欲哭无泪,她真的不是故意的啊:\u201d哎哎哎,豹兄,虎哥,蛇鹰兄,你们做什么?别过来啊!\"\n四个有男主:年轻气盛豹、阴郁沉默蛇、强势大佬虎、冷漠正义鹰。\n【我的读者群:246177071,群名\u201c一梦白头\u201d。验证请填人名或作者名。】","cover":"/agent/http://img1.write.qq.com/upload/cover/2016-06-15/cb_5761104819c96.jpg","cat":"种田","site":"chuangshi","banned":0,"latelyFollower":25870,"latelyFollowerBase":0,"wordCount":366612,"minRetentionRatio":0,"retentionRatio":60.32},"comment":"一跤跌到兽人世界,被一头花豹强掳回家,白箐箐的心情是崩溃的。 这个世界的雄性个个长的跟花孔雀一样华丽英俊,雌性却都是丑女无敌,长的丑还被雄性宠上天。 她本来只能算清秀的高中生,在这里却成了绝美尤物,迷死兽了。 最最最恶搞的是,这里还是母系社会,她可不想三夫四侍啊! 撩花豹,逗猛虎,诱毒蛇,擒雄鹰。后宫充实的白箐箐欲哭无泪,她真的不是故意的啊:\u201c哎哎哎,豹兄,虎哥,蛇鹰兄,你们做什么?别过来啊!\u201d"},{"book":{"_id":"52a163a2bcab3387320018f6","author":"九月如歌","cover":"/agent/http://fm2.xs8xs8.cn/data/cover/10/190184.jpg","longIntro":"【言情大赛赛季冠军】【结局+出版】\r\n\r\n 三年前,她携一纸千亿婚契嫁入G城第一豪门,而她的丈夫却是一个植物人。\r\n  三年后,丈夫苏醒,却将始作甬者的她恨之入骨。\r\n  为了和妻子离婚,他不惜重金聘用娱乐圈王子勾 引自己的太太,誓要制造一场惊天丑闻让她不得不净身出户。\r\n\r\n  他抱着血肉模糊的初恋,放下在她面前高高在上的姿态,悲恸痛苦的跪在手术室外求医生施救,却对同样满身血污的她视若无睹。\r\n  那一刻,她的心房陡然坍塌,不堪一击的内心再也无力支撑那件虚伪强悍的外衣,转身才落泪\u2026\u2026\r\n\r\n  主动将一组与其他男人在一起纠缠的不雅照推到他面前,心口开裂却明眸含笑,\u201c这是我出轨的证据,你拿去提起诉讼,我是过错方,可以净身出户\u2026\u2026\u201d\r\n  翌日清晨,娱乐圈王子和她的头版桃色绯闻赫然出现在他面前\u2026\u2026\r\n  \u2014\u2014他冷眼看着那一对笑靥如花的亲密男女,缓缓攥紧了拳,心尖儿上却蓦地一疼!\r\n【披着虐文外衣的宠文,男不渣,女不贱】","site":"xs8","title":"总裁的绯闻妻","cat":"总裁","banned":0,"latelyFollower":1628,"latelyFollowerBase":0,"wordCount":2929921,"minRetentionRatio":0,"retentionRatio":39.93},"comment":" \u201c难怪你是我睡过的女人中最没味道的,原来还是个雏儿~\u201d他意有鄙薄。 \u201c你才是我睡过的男人技术最差的,根本满足不了我。\u201d她立时反驳。 他眸色一沉,瞬时将她反扑,360度全方位无死角狠狠的满足了她,并扬言以后每天继续\u2026\u2026 \u2026\u2026 三年前,她携一纸千亿婚契嫁入G城第一豪门,而她的丈夫却是一个植物人。 三年后,丈夫苏醒,却将始作甬者的她恨之入骨。"},{"book":{"_id":"55d27e787c12f45b222463c2","title":"乱了流年伤了婚","author":"玉面小七郎","longIntro":"《乱了流年伤了婚》实体书终于上市啦,当当网,全国书店陆续上货中,实体书名字《爱情很远,婚姻很险》附当当网地址:http://product.dangdang.com/23563348.html#\n卷一:陈恋清篇\n我是城市娇娇女,他是寒门凤凰男。\n我和熊跃的结合就是典型的城市女嫁给了凤凰男。\n嫁给熊跃那会,他深情款款的说:也许我给不了你最好的物质生活,但我一定给你一颗最真的心。\n那时,我和大部分女人一样是相信天长地久的。\n然而\n三年五载的光阴,他的真心就移植到了另一个女人身上。\n誓言变成了谎言。\n家庭变成了战场。\n随着真相一点一点揭露,一个丧心病狂的渣男浮出水面。\n天真单纯的娇娇女在现实的逼迫下不得不化身钢铁侠女战士和渣男小三斗智斗勇。\n且看我如何虐死狡猾的渣男与无耻的小三。\n卷二:华琳篇\n出轨的老爸,柔弱的老妈,抗婚的哥哥\n生于这样的极品家庭\n想不彪悍都不行\n前男友,前女友,各路妖魔兴风作浪\n纷扰扰,乱糟糟\n温馨平静的小家掀起大浪。\n如果幸福是一把钥匙,那么华琳曾两度拿到了钥匙\n第一回,新郎结婚了新娘不是自己。\n第二回,一见钟情喜结良缘,本以为瓜熟蒂落,百年好合。后来的日子,狗血洒了一地又一地。\n难道三嫁才能定终生?\n且看华琳的彪悍人生\n卷三:宋溪篇\n宋溪的故事是平实的\n没有那么多的变故,狗血事件,也没有惊天动地的大事情\n但生活就是这样,总有各种各样的小纠结\n于是,总有那么多的不快乐\n关于婚姻,且看宋溪的选择","cover":"/agent/http://gocache.3g.cn/bookimage/bookpic/58/410958/410958_210_280.jpg?v=20140124","cat":"其它","site":"w3gsc","banned":0,"latelyFollower":13891,"latelyFollowerBase":0,"wordCount":512000,"minRetentionRatio":0,"retentionRatio":9.7},"comment":"当有一天,我穿上婚纱成为别人的新娘\r 你依旧是我最初的梦想 今夜,在日志里写下这句话 没来由的突然就哭了 "},{"book":{"_id":"571dbf69bd7cc02728a98040","title":"强势缠绵:总裁大人,你轻点!","author":"南小雅","longIntro":"雅蠛蝶!!!心仪的男神没睡到,却上了男神堂哥的床?!\r\n顾心艾从来没想过,酒后乱性这四个字会像一道晴天霹雳一样打中自己。\r\n而且对方还是赫连池,尊贵无比的财阀继承人,绝对属于她招惹不起的高冷大人物。\r\n隔天醒来,顾心艾唯一想做的就是把他忘记!忘记!彻底忘记!\r\n谁知噩梦还没结束,两天后,她就被迫成为这位男人贴身小看护。\r\n几番纠缠,赫连池将她摁在身下,\u201c我有点不舒服。\u201d\r\n\u201c哪里?\u201d顾心艾气息不稳。\r\n\u201c有个地方,越来越粗,越来越大,只有你才能帮我消肿。\u201d\r\n顾心艾被他抵得退无可退,\u201c对不起,我不喜欢你这种高冷款!\u201d\r\n赫连池拨开皮带,往前一顶,\u201c现在,够热了吗?\u201d\r\n\u2026\u2026\u2026\u2026\u2026\u2026\r\n[宠文,专情,豪门,总裁,可爱,逗趣]","cover":"/agent/http://rm2.kingreader.com/book/1019149/m/%5B640%5D_%E5%BC%BA%E5%8A%BF%E7%BC%A0%E7%BB%B5%EF%BC%9A%E6%80%BB%E8%A3%81%E5%A4%A7%E4%BA%BA%EF%BC%8C%E4%BD%A0%E8%BD%BB%E7%82%B9%EF%BC%81.jpg","site":"zhuishuvip","banned":0,"latelyFollower":28917,"latelyFollowerBase":0,"wordCount":71472,"minRetentionRatio":0,"retentionRatio":45.77},"comment":"楼主被闺密陷害,喝醉被推入陌生人的房间,天呐鲁,还是个男人,她今年才十八岁啊。"},{"book":{"_id":"571dbfafc6b160f9251c5402","title":"影中仙","author":"上殿","longIntro":"我从洪水中捞上来一幅古画,画中有一位绝世容颜般女子\u2026\u2026     第二天醒来,古画变成了空白,画中仙一样的女子消失不见,但,从此之后我的影子中多了一个人。\r\n上殿读者群 435495368 欢迎每一位朋友进群交流!","cover":"/agent/http://rm2.kingreader.com/book/1019150/m/%5B640%5D_%E5%BD%B1%E4%B8%AD%E4%BB%99.jpg","site":"zhuishuvip","banned":0,"latelyFollower":432,"latelyFollowerBase":0,"wordCount":162371,"minRetentionRatio":0,"retentionRatio":null},"comment":" 我从洪水中捞上来一幅古画,画中有一位绝世容颜般女子\u2026\u2026 第二天醒来,古画变成了空白,画中仙一样的女子消失不见,但,从此之后我的影子中多了一个人。 "},{"book":{"_id":"54c1f8878dd1d8b76be7b0da","title":"我家徒弟又挂了","author":"尤前","longIntro":"被称为修仙界第一人的玉言尊上,等了一万六千年,终于收到了一个徒弟,细心教导,认真呵护。\r\n看着她渐渐领悟,慢慢强大,眼看要一飞冲天的时候\u2026\u2026她挂了!\r\n于是他又收了一徒弟,细心教导,认真呵护,然后\u2026\u2026她又挂了!\r\n于于是他再收了一个徒弟,接着\u2026\u2026她还是挂了!\r\n玉言:\u2026\u2026\r\n徒弟:\u2026\u2026\r\n(为什么每次重生,都会被同一个人捡回去啊,摔~~~~)","cover":"/agent/http://image.cmfu.com/books/3378072/3378072.jpg","cat":"幻想言情","site":"zhuishuvip","banned":0,"latelyFollower":52176,"latelyFollowerBase":0,"wordCount":1259011,"minRetentionRatio":0,"retentionRatio":27.95},"comment":"被称为修仙界第一人的玉言尊上,等了一万六千年,终于收到了一个徒弟,细心教导,认真呵护。 看着她渐渐领悟,慢慢强大,眼看要一飞冲天的时候\u2026\u2026她挂了! 于是他又收了一徒弟,细心教导,认真呵护,然后\u2026\u2026她又挂了! 于于是他再收了一个徒弟,接着\u2026\u2026她还是挂了!"},{"book":{"_id":"53e2ec85c67c51f35a447a47","title":"炮灰攻略","author":"莞尔wr","longIntro":"意外死亡后百合得到了生存的机会,为了保持现状,她不得不穿越各式各样的奇葩文中完成任务。\r\n简介有点无能,但是绝对不欢迎任何吐糟,是任何,只要夸奖,吐糟的不要怪作者不留任何情面,作者的胸怀包容绝对没有圣母大。","cover":"/agent/http://image.cmfu.com/books/3222161/3222161.jpg","site":"zhuishuvip","cat":"穿越","banned":-1,"latelyFollower":7613,"latelyFollowerBase":0,"wordCount":3097279,"minRetentionRatio":0,"retentionRatio":35.96},"comment":"快穿攻略守则\u2026\u2026"},{"book":{"_id":"53db22db3bd4cd3b76f85027","title":"嫡女重生记","author":"六月浩雪","longIntro":"在家是小透明,嫁人后是摆设,最后葬身火海尸骨无存,这是韩玉熙上辈子的写照。\n重活一世,韩玉熙努力上进,只愿不再做陪衬与花瓶,然后觅得如意郎君,平安富贵过一生。\n可惜事与愿违,嫁了个身负血海深仇的郎君,韩玉熙的人生开始翻天覆地,但她新的人生却是好事多磨,苦尽甘来。\n六月已完本小说:《重生之温婉》、《世家》。","cover":"/agent/http://img1.chuangshi.qq.com/upload/cover/20140716/cb_53c624ecbe098.jpg","site":"zhuishuvip","cat":"宫廷","banned":0,"latelyFollower":14104,"latelyFollowerBase":0,"wordCount":4458393,"minRetentionRatio":0,"retentionRatio":56.28},"comment":"起点女生网大神畅销作品\u2026\u2026"},{"book":{"_id":"508785dfedc8f2b34c00001d","author":"六月浩雪","cover":"/agent/http://image.cmfu.com/books/2134262/2134262.jpg","longIntro":"重生到古代,不仅成为口不能言的哑巴;还是祖母不喜,爹不疼,后母恶毒,克父克母克全家的不祥人。\n面对种种艰辛,各种刁难,她迎难而上,一一化解。中毒、暗杀、陷害接踵而来,她也无所畏惧。\n她本只想平淡,安静地过一生,可是时不待人。既如此,她再不愿如上辈子一样黯然伤逝,这世,她定要活出风采,创造属于她的传奇。","title":"重生之温婉","cat":"古代言情","site":"zhuishuvip","banned":0,"latelyFollower":3111,"latelyFollowerBase":0,"wordCount":-1,"minRetentionRatio":0,"retentionRatio":42.97},"comment":""},{"book":{"_id":"563215f701127caa14bd9667","title":"豪门隐婚:腹黑总裁专宠妻","author":"夏青衫","longIntro":"刚刚走马上任的景盛集团总裁助理,正在向同样刚刚走马上任的总裁汇报工作行程。\r\n\u201c明天上午的会见全部推迟,九点跟我去民政局领证!\u201d\r\n上班第一天就遇到霸道总裁逼领证,她是该反抗还是顺从?\r\n夜晚,某人把她剥光压在身下,邪气而暧昧:\u201c反抗和顺从我都喜欢,长夜漫漫,咱们可以都试试\u2026\u2026\u201d\r\n早晨,他神采奕奕:今晚继续,乖乖在家里等我回来,哪儿都不许去!\r\n她浑身酸痛的要命,想出去也没有力气啊!","cover":"/agent/http://img1.chuangshi.qq.com/upload/cover/20150924/cb_5603c464d037e.jpg","cat":"总裁","site":"zhuishuvip","banned":0,"latelyFollower":16484,"latelyFollowerBase":0,"wordCount":2411082,"minRetentionRatio":0,"retentionRatio":43.6},"comment":"具体环环相扣,爆点十足,强烈推荐\u2026\u2026"},{"book":{"_id":"54965f10653cae733dea8456","title":"豪门隐婚:老婆别闹了","author":"桃花朵朵香","longIntro":"他是权势倾天的高冷贵。\n她是婚前被抛弃的苦逼女。\n一个阳光明媚的下午,她走到他面前。\n\u201c娶我可好?\u201d\n他微怔,随即薄唇轻启,\u201c好。\u201d\n她傻住。\n\u201c走吧。\u201d\n\u201c去那?\u201d\n\u201c民政局。\u201d\n原本她以为自己也就是嫁了个总裁,却在前男友的婚礼上,发现他不止是总裁,还是\u2026\u2026","cover":"/agent/http://img1.chuangshi.qq.com/upload/cover/20150316/cb_5506ea3480738.jpg","site":"zhuishuvip","cat":"总裁","banned":0,"latelyFollower":3887,"latelyFollowerBase":0,"wordCount":2298091,"minRetentionRatio":0,"retentionRatio":32.51},"comment":"暖死人不偿命,霸道总裁,宠你没商量!"},{"book":{"_id":"56cd3e5a797842f76f6fa18a","title":"错吻男神99次","author":"千羽兮","longIntro":"不过是醉酒后误入男厕对某男耍了个流氓而已,却没想到会给自己招来那么大的麻烦,甚至还被警察扫黄扫进了局子。丢人现眼后以为从此老死不相往来,可这男人却偏偏在她的生活中阴魂不散,还多带了个小麻烦。小麻烦一次次卖萌耍宝一次次成功。\u201c做我妈妈好不好?\u201d\u201c好!\u201d当她抓着红本子从民政局出来的时候,看到一大一小两只麻邪魅轻狂的笑后,悔得肠子都青了。而下一秒,自己便落入了某只饥渴已久的雄狮手中\u2026\u2026","cover":"/agent/http://wfqqreader.3g.qq.com/cover/204/809204/t7_809204.jpg","cat":"其它","site":"chuangshi","banned":0,"latelyFollower":284,"latelyFollowerBase":0,"wordCount":1450000,"minRetentionRatio":0,"retentionRatio":null},"comment":""}] * shareLink : http://share.zhuishushenqi.com/booklist/57c3ffcabbba8a463aab9959 * id : 57c3ffcabbba8a463aab9959 */ private BookListBean bookList; public BookListBean getBookList() { return bookList; } public void setBookList(BookListBean bookList) { this.bookList = bookList; } public static class BookListBean { private String _id; private String updated; private String title; /** * _id : 576680476fc4bac56b03e67c * avatar : /avatar/b0/df/b0df89144226ec91bf3a68bba32431cd * nickname : 书荒终结者 * type : normal * lv : 6 */ private AuthorBean author; private String desc; private String gender; private String created; private Object stickStopTime; private boolean isDraft; private Object isDistillate; private int collectorCount; private String shareLink; private String id; private List<String> tags; /** * book : {"_id":"57a7ec3c8083239c141b5207","title":"强势夺爱:顾先生请自重","author":"金佑木木", * "longIntro":"\"秦阮阮\u201c分手大师\u201d的名号打得响,却一脚踩在了\u201c天王老子\u201d顾临泫的脚上。\r\n\r\n * 一毛钱没赚到不说,还被逼倒欠三百万!\r\n\r\n没办法,为了还债,她不得不以身犯险,这险套路太深,她防不胜防。\r\n\r\n最后逼得日日夜夜被压着\u201c * 还债\u201d,赔了夫人又折兵。\r\n\r\n * 顾临泫最擅长的事就是翻手为云覆手为雨,以前是用在商场上,后来是用在秦阮阮身上,秦阮阮是他的云,是他的雨,把她扔床上翻来覆去,不知疲惫\u2026\u2026\"\r\n", * "cover":"/cover/147132509933927","site":"zhuishuvip","banned":0,"latelyFollower":4392, * "latelyFollowerBase":0,"wordCount":146559,"minRetentionRatio":0,"retentionRatio":27.35} * comment : 秦阮阮“分手大师”的名号打得响,却一脚踩在了“天王老子”顾临泫的脚上。 一毛钱没赚到不说,还被逼倒欠三百万! * 没办法,为了还债,她不得不以身犯险,这险套路太深,她防不胜防。 最后逼得日日夜夜被压着“还债”,赔了夫人又折兵。 * 顾临泫最擅长的事就是翻手为云覆手为雨,以前是用在商场上,后来是用在秦阮阮身上,秦阮阮是他的云,是他的雨,把她扔床上翻来覆去,不知疲惫…… */ private List<BooksBean> books; public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getUpdated() { return updated; } public void setUpdated(String updated) { this.updated = updated; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public AuthorBean getAuthor() { return author; } public void setAuthor(AuthorBean author) { this.author = author; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public Object getStickStopTime() { return stickStopTime; } public void setStickStopTime(Object stickStopTime) { this.stickStopTime = stickStopTime; } public boolean isIsDraft() { return isDraft; } public void setIsDraft(boolean isDraft) { this.isDraft = isDraft; } public Object getIsDistillate() { return isDistillate; } public void setIsDistillate(Object isDistillate) { this.isDistillate = isDistillate; } public int getCollectorCount() { return collectorCount; } public void setCollectorCount(int collectorCount) { this.collectorCount = collectorCount; } public String getShareLink() { return shareLink; } public void setShareLink(String shareLink) { this.shareLink = shareLink; } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public List<BooksBean> getBooks() { return books; } public void setBooks(List<BooksBean> books) { this.books = books; } public static class AuthorBean { private String _id; private String avatar; private String nickname; private String type; private int lv; public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getLv() { return lv; } public void setLv(int lv) { this.lv = lv; } } public static class BooksBean { /** * _id : 57a7ec3c8083239c141b5207 * title : 强势夺爱:顾先生请自重 * author : 金佑木木 * longIntro : "秦阮阮“分手大师”的名号打得响,却一脚踩在了“天王老子”顾临泫的脚上。 一毛钱没赚到不说,还被逼倒欠三百万! 没办法,为了还债,她不得不以身犯险,这险套路太深,她防不胜防。 最后逼得日日夜夜被压着“还债”,赔了夫人又折兵。 顾临泫最擅长的事就是翻手为云覆手为雨,以前是用在商场上,后来是用在秦阮阮身上,秦阮阮是他的云,是他的雨,把她扔床上翻来覆去,不知疲惫……" * cover : /cover/147132509933927 * site : zhuishuvip * banned : 0 * latelyFollower : 4392 * latelyFollowerBase : 0 * wordCount : 146559 * minRetentionRatio : 0 * retentionRatio : 27.35 */ private BookBean book; private String comment; public BookBean getBook() { return book; } public void setBook(BookBean book) { this.book = book; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public static class BookBean { private String _id; private String title; private String author; private String longIntro; private String cover; private String site; private int banned; private int latelyFollower; private int latelyFollowerBase; private int wordCount; private String minRetentionRatio; private double retentionRatio; public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getLongIntro() { return longIntro; } public void setLongIntro(String longIntro) { this.longIntro = longIntro; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public int getBanned() { return banned; } public void setBanned(int banned) { this.banned = banned; } public int getLatelyFollower() { return latelyFollower; } public void setLatelyFollower(int latelyFollower) { this.latelyFollower = latelyFollower; } public int getLatelyFollowerBase() { return latelyFollowerBase; } public void setLatelyFollowerBase(int latelyFollowerBase) { this.latelyFollowerBase = latelyFollowerBase; } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } public String getMinRetentionRatio() { return minRetentionRatio; } public void setMinRetentionRatio(String minRetentionRatio) { this.minRetentionRatio = minRetentionRatio; } public double getRetentionRatio() { return retentionRatio; } public void setRetenStringtio(double retentionRatio) { this.retentionRatio = retentionRatio; } } } } }
smuyyh/BookReader
app/src/main/java/com/justwayward/reader/bean/BookListDetail.java
365
package cn.hutool.core.io; import java.io.IOException; import java.io.OutputStream; /** * 此OutputStream写出数据到<b>/dev/null</b>,即忽略所有数据<br> * 来自 Apache Commons io * * @author looly * @since 4.0.6 */ public class NullOutputStream extends OutputStream { /** * 单例 */ public static final NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream(); /** * 什么也不做,写出到<code>/dev/null</code>. * * @param b 写出的数据 * @param off 开始位置 * @param len 长度 */ @Override public void write(byte[] b, int off, int len) { // to /dev/null } /** * 什么也不做,写出到 <code>/dev/null</code>. * * @param b 写出的数据 */ @Override public void write(int b) { // to /dev/null } /** * 什么也不做,写出到 <code>/dev/null</code>. * * @param b 写出的数据 * @throws IOException 不抛出 */ @Override public void write(byte[] b) throws IOException { // to /dev/null } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/io/NullOutputStream.java
366
package linkedlist; /** * 1)单链表的插入、删除、查找操作; * 2)链表中存储的是int类型的数据; * * Author:Zheng */ public class SinglyLinkedList { private Node head = null; public Node findByValue(int value) { Node p = head; while (p != null && p.data != value) { p = p.next; } return p; } public Node findByIndex(int index) { Node p = head; int pos = 0; while (p != null && pos != index) { p = p.next; ++pos; } return p; } //无头结点 //表头部插入 //这种操作将于输入的顺序相反,逆序 public void insertToHead(int value) { Node newNode = new Node(value, null); insertToHead(newNode); } public void insertToHead(Node newNode) { if (head == null) { head = newNode; } else { newNode.next = head; head = newNode; } } //顺序插入 //链表尾部插入 public void insertTail(int value){ Node newNode = new Node(value, null); //空链表,可以插入新节点作为head,也可以不操作 if (head == null){ head = newNode; }else{ Node q = head; while(q.next != null){ q = q.next; } newNode.next = q.next; q.next = newNode; } } public void insertAfter(Node p, int value) { Node newNode = new Node(value, null); insertAfter(p, newNode); } public void insertAfter(Node p, Node newNode) { if (p == null) return; newNode.next = p.next; p.next = newNode; } public void insertBefore(Node p, int value) { Node newNode = new Node(value, null); insertBefore(p, newNode); } public void insertBefore(Node p, Node newNode) { if (p == null) return; if (head == p) { insertToHead(newNode); return; } Node q = head; while (q != null && q.next != p) { q = q.next; } if (q == null) { return; } newNode.next = p; q.next = newNode; } public void deleteByNode(Node p) { if (p == null || head == null) return; if (p == head) { head = head.next; return; } Node q = head; while (q != null && q.next != p) { q = q.next; } if (q == null) { return; } q.next = q.next.next; } public void deleteByValue(int value) { if (head == null) return; Node p = head; Node q = null; while (p != null && p.data != value) { q = p; p = p.next; } if (p == null) return; if (q == null) { head = head.next; } else { q.next = q.next.next; } // 可重复删除指定value的代码 /* if (head != null && head.data == value) { head = head.next; } Node pNode = head; while (pNode != null) { if (pNode.next.data == data) { pNode.next = pNode.next.next; continue; } pNode = pNode.next; } */ } public void printAll() { Node p = head; while (p != null) { System.out.print(p.data + " "); p = p.next; } System.out.println(); } //判断true or false public boolean TFResult(Node left, Node right){ Node l = left; Node r = right; boolean flag=true; System.out.println("left_:"+l.data); System.out.println("right_:"+r.data); while(l != null && r != null){ if (l.data == r.data){ l = l.next; r = r.next; continue; }else{ flag=false; break; } } System.out.println("什么结果"); return flag; /* if (l==null && r==null){ System.out.println("什么结果"); return true; }else{ return false; }*/ } // 判断是否为回文 public boolean palindrome(){ if (head == null){ return false; }else{ System.out.println("开始执行找到中间节点"); Node p = head; Node q = head; if (p.next == null){ System.out.println("只有一个元素"); return true; } while( q.next != null && q.next.next != null){ p = p.next; q = q.next.next; } System.out.println("中间节点" + p.data); System.out.println("开始执行奇数节点的回文判断"); Node leftLink = null; Node rightLink = null; if(q.next == null){ // p 一定为整个链表的中点,且节点数目为奇数 rightLink = p.next; leftLink = inverseLinkList(p).next; System.out.println("左边第一个节点"+leftLink.data); System.out.println("右边第一个节点"+rightLink.data); }else{ //p q 均为中点 rightLink = p.next; leftLink = inverseLinkList(p); } return TFResult(leftLink, rightLink); } } //带结点的链表翻转 public Node inverseLinkList_head(Node p){ // Head 为新建的一个头结点 Node Head = new Node(9999,null); // p 为原来整个链表的头结点,现在Head指向 整个链表 Head.next = p; /* 带头结点的链表翻转等价于 从第二个元素开始重新头插法建立链表 */ Node Cur = p.next; p.next = null; Node next = null; while(Cur != null){ next = Cur.next; Cur.next = Head.next; Head.next = Cur; System.out.println("first " + Head.data); Cur = next; } // 返回左半部分的中点之前的那个节点 // 从此处开始同步像两边比较 return Head; } //无头结点的链表翻转 public Node inverseLinkList(Node p){ Node pre = null; Node r = head; System.out.println("z---" + r.data); Node next= null; while(r !=p){ next = r.next; r.next = pre; pre = r; r = next; } r.next = pre; // 返回左半部分的中点之前的那个节点 // 从此处开始同步像两边比较 return r; } public static Node createNode(int value) { return new Node(value, null); } public static class Node { private int data; private Node next; public Node(int data, Node next) { this.data = data; this.next = next; } public int getData() { return data; } } public static void main(String[]args){ SinglyLinkedList link = new SinglyLinkedList(); System.out.println("hello"); //int data[] = {1}; //int data[] = {1,2}; //int data[] = {1,2,3,1}; //int data[] = {1,2,5}; //int data[] = {1,2,2,1}; // int data[] = {1,2,5,2,1}; int data[] = {1,2,5,3,1}; for(int i =0; i < data.length; i++){ //link.insertToHead(data[i]); link.insertTail(data[i]); } // link.printAll(); // Node p = link.inverseLinkList_head(link.head); // while(p != null){ // System.out.println("aa"+p.data); // p = p.next; // } System.out.println("打印原始:"); link.printAll(); if (link.palindrome()){ System.out.println("回文"); }else{ System.out.println("不是回文"); } } }
wangzheng0822/algo
java/06_linkedlist/SinglyLinkedList.java
368
/** * Ioc 容器 * <p> * 提供 Nutz.Ioc 所有的功能,什么是 Ioc 都不知道?您自己 G 吧。 * <p> * 详细的介绍请看文档,总之,它的接口是很容易使用滴~~~,扩展性也是很强悍滴~~~ * */ package org.nutz.ioc;
nutzam/nutz
src/org/nutz/ioc/package-info.java
369
package com.mysiteforme.admin.lucene; import com.baomidou.mybatisplus.plugins.Page; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.mysiteforme.admin.entity.BlogArticle; import com.xiaoleilu.hutool.date.DateUtil; import com.xiaoleilu.hutool.date.TimeInterval; import com.xiaoleilu.hutool.log.Log; import com.xiaoleilu.hutool.log.LogFactory; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.document.*; import org.apache.lucene.index.*; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.*; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.wltea.analyzer.lucene.IKAnalyzer; import java.io.IOException; import java.io.StringReader; import java.nio.file.Paths; import java.text.DecimalFormat; import java.util.List; import java.util.Map; /** * Created by wangl on 2018/1/28. * todo: */ @Component public class LuceneSearch { private static Log log = LogFactory.get(); //Lucene索引文件路径 public static String dir; @Value("${lucence-dic}") public void setDir(String lucenceDir) { dir = lucenceDir; } //定义分词器 static Analyzer analyzer = new IKAnalyzer(); /** * 封裝一个方法,用于将数据库中的数据解析为一个个关键字词存储到索引文件中 * @param document * @throws IOException */ public static void write(Document document) throws IOException { //索引库的存储目录 Directory directory = FSDirectory.open(Paths.get(dir)); //在 6.6 以上版本中 version 不再是必要的,并且,存在无参构造方法,可以直接使用默认的 StandardAnalyzer 分词器。 //创建索引写入配置 Analyzer analyzer = new IKAnalyzer(); IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); //创建索引写入对象 IndexWriter indexWriter = new IndexWriter(directory,indexWriterConfig); //写入到目录文件中 indexWriter.addDocument(document); //提交事务 indexWriter.commit(); //关闭流 indexWriter.close(); } /** * 根据ID删除索引 * @param id * @throws IOException */ public static void deleteIndexById(String id) throws IOException{ Directory directory = FSDirectory.open(Paths.get(dir));// 打开文件索引目录 Analyzer analyzer = new IKAnalyzer(); IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); //创建索引写入对象 IndexWriter writer = new IndexWriter(directory,indexWriterConfig); IndexReader reader = DirectoryReader.open(directory);// 读取目 Query q = new TermQuery(new Term("id", id)); writer.deleteDocuments(q);// 删除指定ID的Document writer.commit();// 提交 writer.close();// 关闭 reader.close();// 关闭 } /** * 根据ID更新搜索内容 * @param blogArticle * @throws IOException */ public static void updateIndexById(BlogArticle blogArticle) throws IOException{ Directory directory = FSDirectory.open(Paths.get(dir));// 打开文件索引目录 Analyzer analyzer = new IKAnalyzer(); IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); //创建索引写入对象 IndexWriter writer = new IndexWriter(directory,indexWriterConfig); Document doc = new Document(); doc.add(new LongPoint("id",blogArticle.getId())); doc.add(new TextField("title",blogArticle.getTitle(), Field.Store.YES)); doc.add(new TextField("marks",blogArticle.getMarks()==null?"":blogArticle.getMarks(),Field.Store.YES)); doc.add(new TextField("text",blogArticle.getText()==null?"":blogArticle.getText(),Field.Store.YES)); doc.add(new StoredField("href",blogArticle.getBlogChannel().getHref())); doc.add(new StoredField("show_pic",blogArticle.getShowPic()==null?"":blogArticle.getShowPic())); writer.updateDocument(new Term("id", blogArticle.getId().toString()), doc); writer.commit();// 提交 writer.close();// 关闭 } /** * 搜索 * @param field 字段名称 * @param value 搜索内容 * @return * @throws Exception */ public Map<String,Object> search(String[] field, String value,Page page) throws Exception{ Map<String,Object> dataMap = Maps.newHashMap(); //索引库的存储目录 Directory directory = FSDirectory.open(Paths.get(dir)); //读取索引库的存储目录 DirectoryReader directoryReader = DirectoryReader.open(directory); //创建一个索引的查找器,来检索索引库 IndexSearcher indexSearcher = new IndexSearcher(directoryReader); //“与或”搜索 /** * 1.和: MUST与MUST_NOT 2.或: SHOULD与SHOULD 3.A与B的并集-B MUST与MUST_NOT */ BooleanQuery.Builder builder=new BooleanQuery.Builder(); //lucence查询解析器,用于指定查询的属性名和分词器 Analyzer analyzer = new IKAnalyzer(); QueryParser parser = new MultiFieldQueryParser(field,analyzer); //使用特定的分析器搜索 Query query = parser.parse(value); builder.add(query,BooleanClause.Occur.SHOULD); for(int i=0;i<field.length;i++){ //按词条搜索 Query q = new TermQuery(new Term(field[i],value)); builder.add(q,BooleanClause.Occur.SHOULD); } BooleanQuery finalquery = builder.build(); //TopDocs 搜索返回的结果 TopDocs topDocs = indexSearcher.search(finalquery, 100); log.info(topDocs.scoreDocs.length+""); //最终被分词后添加的前缀和后缀处理器,默认是粗体<B></B> SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter("<span style='color: #FF5722;'>","</span>"); //高亮搜索的词添加到高亮处理器中 Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query)); // 搜索返回的结果集合 ScoreDoc[] scoreDocs = topDocs.scoreDocs; //查询起始记录位置 int begin = page.getSize() * (page.getCurrent() - 1) ; //查询终止记录位置 int end = Math.min(begin + page.getSize(), scoreDocs.length); List<Map> list = Lists.newArrayList(); //进行分页查询 for(int i=begin;i<end;i++) { Map<String ,Object> map = Maps.newHashMap(); int docID = scoreDocs[i].doc; Document doc = indexSearcher.doc(docID); Long id = Long.valueOf(doc.get("id")); String title = doc.get("title"); if(StringUtils.isNotBlank(title)){ TokenStream tokenStream = analyzer.tokenStream("title", new StringReader(title)); title = highlighter.getBestFragment(tokenStream, title); } String text = doc.get("text"); if(StringUtils.isNotBlank(text)){ TokenStream tokenStream = analyzer.tokenStream("text", new StringReader(text)); text = highlighter.getBestFragment(tokenStream, text); } String marks = doc.get("marks"); if(StringUtils.isNotBlank(marks)){ TokenStream tokenStream = analyzer.tokenStream("marks", new StringReader(marks)); marks = highlighter.getBestFragment(tokenStream, marks); } String href=doc.get("href"); String showPic=doc.get("showPic"); //评分 Explanation explanation = indexSearcher.explain(query, docID); map.put("id",id); map.put("href",href); map.put("showPic",showPic); map.put("title",title); map.put("text",text); map.put("marks",marks); DecimalFormat fnum = new DecimalFormat("##0.00"); map.put("percent",fnum.format(explanation.getValue())); list.add(map); dataMap.put("data",list); dataMap.put("count",list.size()); } directoryReader.close(); directory.close(); TimeInterval timer = DateUtil.timer(); dataMap.put("time", DateUtil.formatBetween(timer.intervalRestart())); dataMap.put("key",value); return dataMap; } public static void main(String args[]) { String text="什么"; // Document doc = new Document(); // int id = 1; // doc.add(new IntPoint("id", id)); // doc.add(new TextField("content", "文章标题非常非常的复杂我不知道该怎么办才好你说究竟需要做什么才能弥补犯下的过错呢?", Field.Store.YES)); // try { // write(doc); // } catch (IOException e) { // e.printStackTrace(); // } // TokenStream tokenStream = analyzer.tokenStream("content", new StringReader(text)); // CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class); // try { // tokenStream.reset(); // while (tokenStream.incrementToken()) { // System.out.println(charTermAttribute.toString()); // } // tokenStream.end(); // } finally { // tokenStream.close(); // analyzer.close(); // } // String[] field = {"content"}; // List<Map> list = (List<Map>) new LuceneSearch().search(field,"复杂",new Page(1,10)).get("data"); // log.info(JSONObject.toJSONString(list)); } }
wangl1989/mysiteforme
src/main/java/com/mysiteforme/admin/lucene/LuceneSearch.java
370
H 1520813180 tags: Array, Stack, Monotonous Stack 给n个bar,组成柱状图histogram. 求在这一排柱状图里面可以找到的面积最大的长方形. 思考: 找长方形面积, 无非是找两个index, 然后底边长度 * height. #### Monotonous Stack - 重点是根据找Histogram里面rectangle的性质, 维持一个单调递增的Stack - 在loop over indexes的时候: - 如果高度>= previous peek(), 那么对于那个peek, 就意味着, 往下走, 一直走高嘛, 之前的peek总可以继续抄底 - 什么时候不能抄底了呢? 就是有一个下降趋势的时候 - 这时候并不是calculate所有前面的peek, 而是考虑 大于 current height的之前所有的peek. - 把这些peek到 current height 前一格的rectangle全部找出来: stack.pop() - 这个stack.pop()的过程里面, 其实没有算上 current height, 因为需要留到下一轮, 把current index加进stack 再说 - 为什么用stack? 因为需要知道连续递增的peek, stack.peek() O(1), 好用 而其实不用stack, 也可以用其他方式记录所有height, 只不过要 O(n)去找peek不方便 #### 知识点 - 理解monotonous stack 是如何被维护的 - 维护monotonous stack 是题目需要, 而不是stack本身性质, 是一种借助 stack.peek() O(1)的巧妙用法. ``` /* LeetCode: https://leetcode.com/problems/largest-rectangle-in-histogram/description/ Given n non-negative integers representing the histogram's bar height, where the width of each bar is 1, find the area of largest rectangle in the histogram. [missing image] Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. [missing image] The largest rectangle is shown in the shaded area, which has area = 10 unit. For example, Given heights = [2,1,5,6,2,3], return 10. */ /* Thoughts: Maintain monotonous stack: whenever seeing a decreasing element, process. Some characteristics when calculating rectangle in histogram - You turn to think: I have to loop over all indexes then I know for any specific height, for example, 1, occurs across [0 ~ n]. That's partially true - We should make be best efforts on calculating: up to certain index, what's maximum we could get. As we maintain the monotonous ascending stack, stack.peek() element is always the starting point of the rectangle - [important] Only need to stop and calculate rectangle when seeing a descending element - It's like, keep climbing the mountain; when it descreases at a point, trace back to use all previous peeks and form rectangle with current position */ class Solution { public int largestRectangleArea(int[] heights) { if (heights == null || heights.length == 0) { return 0; } int n = heights.length; int max = 0; Stack<Integer> stack = new Stack<>(); // Use stack to store the index for (int i = 0; i <= n; i++) { int currHeight = i == n ? -1 : heights[i]; // Keep stack monotonous; if not, process && calculate rectangle while (!stack.isEmpty() && currHeight <= heights[stack.peek()]) { int currPeekHeight = heights[stack.pop()]; // exclude current position; it'll be calculate in next round. int width = stack.isEmpty() ? i : i - stack.peek() - 1; max = Math.max(max, currPeekHeight * width); } stack.push(i); } return max; } } /** * @param {number[]} heights * @return {number} */ // javascript version var largestRectangleArea = function(heights) { if(heights == null || heights.length == 0) { return 0; } let n = heights.length; let max = 0; let stack = []; // use it as stack, with index 0 being the top for (let i = 0; i <= n; i++) { let currHeight = i == n ? -1 : heights[i]; while (stack.length > 0 && currHeight <= heights[stack[0]]) { let currPeekHeight = heights[stack[0]]; stack.splice(0, 1); let width = stack.length == 0 ? i : i - stack[0] - 1; max = Math.max(max, currPeekHeight * width); } stack.unshift(i); } return max; }; ```
awangdev/leet-code
Java/Largest Rectangle in Histogram.java
371
package cc.mrbird.socket.handler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; /** * @author MrBird */ @Component public class MyStringWebSocketHandler extends TextWebSocketHandler { private Logger log = LoggerFactory.getLogger(this.getClass()); @Override public void afterConnectionEstablished(WebSocketSession session) { log.info("和客户端建立连接"); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { session.close(CloseStatus.SERVER_ERROR); log.error("连接异常", exception); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { super.afterConnectionClosed(session, status); log.info("和客户端断开连接"); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // 获取到客户端发送过来的消息 String receiveMessage = message.getPayload(); log.info(receiveMessage); // 发送消息给客户端 session.sendMessage(new TextMessage(fakeAi(receiveMessage))); // 关闭连接 // session.close(CloseStatus.NORMAL); } private static String fakeAi(String input) { if (input == null || "".equals(input)) { return "你说什么?没听清︎"; } return input.replace('你', '我') .replace("吗", "") .replace('?', '!') .replace('?', '!'); } }
wuyouzhuguli/SpringAll
76.spring-boot-websocket-socketjs/src/main/java/cc/mrbird/socket/handler/MyStringWebSocketHandler.java
372
/* * Copyright 2019 Zhou Pengfei * SPDX-License-Identifier: Apache-2.0 */ package org.signal.glide.apng.decode; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.Rect; import org.signal.core.util.logging.Log; import org.signal.glide.apng.io.APNGReader; import org.signal.glide.apng.io.APNGWriter; import org.signal.glide.common.decode.Frame; import org.signal.glide.common.decode.FrameSeqDecoder; import org.signal.glide.common.io.Reader; import org.signal.glide.common.loader.Loader; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * @Description: APNG4Android * @Author: pengfei.zhou * @CreateDate: 2019-05-13 */ public class APNGDecoder extends FrameSeqDecoder<APNGReader, APNGWriter> { private static final String TAG = Log.tag(APNGDecoder.class); private APNGWriter apngWriter; private int mLoopCount; private final Paint paint = new Paint(); private class SnapShot { byte dispose_op; Rect dstRect = new Rect(); ByteBuffer byteBuffer; } private SnapShot snapShot = new SnapShot(); /** * @param loader webp的reader * @param renderListener 渲染的回调 */ public APNGDecoder(Loader loader, FrameSeqDecoder.RenderListener renderListener) { super(loader, renderListener); paint.setAntiAlias(true); } @Override protected APNGWriter getWriter() { if (apngWriter == null) { apngWriter = new APNGWriter(); } return apngWriter; } @Override protected APNGReader getReader(Reader reader) { return new APNGReader(reader); } @Override protected int getLoopCount() { return mLoopCount; } @Override protected void release() { snapShot.byteBuffer = null; apngWriter = null; } @Override protected Rect read(APNGReader reader) throws IOException { List<Chunk> chunks = APNGParser.parse(reader); List<Chunk> otherChunks = new ArrayList<>(); boolean actl = false; APNGFrame lastFrame = null; byte[] ihdrData = new byte[0]; int canvasWidth = 0, canvasHeight = 0; for (Chunk chunk : chunks) { if (chunk instanceof ACTLChunk) { mLoopCount = ((ACTLChunk) chunk).num_plays; actl = true; } else if (chunk instanceof FCTLChunk) { APNGFrame frame = new APNGFrame(reader, (FCTLChunk) chunk); frame.prefixChunks = otherChunks; frame.ihdrData = ihdrData; frames.add(frame); lastFrame = frame; } else if (chunk instanceof FDATChunk) { if (lastFrame != null) { lastFrame.imageChunks.add(chunk); } } else if (chunk instanceof IDATChunk) { if (!actl) { //如果为非APNG图片,则只解码PNG Frame frame = new StillFrame(reader); frame.frameWidth = canvasWidth; frame.frameHeight = canvasHeight; frames.add(frame); mLoopCount = 1; break; } if (lastFrame != null) { lastFrame.imageChunks.add(chunk); } } else if (chunk instanceof IHDRChunk) { canvasWidth = ((IHDRChunk) chunk).width; canvasHeight = ((IHDRChunk) chunk).height; ihdrData = ((IHDRChunk) chunk).data; } else if (!(chunk instanceof IENDChunk)) { otherChunks.add(chunk); } } frameBuffer = ByteBuffer.allocate((canvasWidth * canvasHeight / (sampleSize * sampleSize) + 1) * 4); snapShot.byteBuffer = ByteBuffer.allocate((canvasWidth * canvasHeight / (sampleSize * sampleSize) + 1) * 4); return new Rect(0, 0, canvasWidth, canvasHeight); } @Override protected void renderFrame(Frame frame) { if (frame == null || fullRect == null) { return; } try { Bitmap bitmap = obtainBitmap(fullRect.width() / sampleSize, fullRect.height() / sampleSize); Canvas canvas = cachedCanvas.get(bitmap); if (canvas == null) { canvas = new Canvas(bitmap); cachedCanvas.put(bitmap, canvas); } if (frame instanceof APNGFrame) { // 从缓存中恢复当前帧 frameBuffer.rewind(); bitmap.copyPixelsFromBuffer(frameBuffer); // 开始绘制前,处理快照中的设定 if (this.frameIndex == 0) { canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); } else { canvas.save(); canvas.clipRect(snapShot.dstRect); switch (snapShot.dispose_op) { // 从快照中恢复上一帧之前的显示内容 case FCTLChunk.APNG_DISPOSE_OP_PREVIOUS: snapShot.byteBuffer.rewind(); bitmap.copyPixelsFromBuffer(snapShot.byteBuffer); break; // 清空上一帧所画区域 case FCTLChunk.APNG_DISPOSE_OP_BACKGROUND: canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); break; // 什么都不做 case FCTLChunk.APNG_DISPOSE_OP_NON: default: break; } canvas.restore(); } // 然后根据dispose设定传递到快照信息中 if (((APNGFrame) frame).dispose_op == FCTLChunk.APNG_DISPOSE_OP_PREVIOUS) { if (snapShot.dispose_op != FCTLChunk.APNG_DISPOSE_OP_PREVIOUS) { snapShot.byteBuffer.rewind(); bitmap.copyPixelsToBuffer(snapShot.byteBuffer); } } snapShot.dispose_op = ((APNGFrame) frame).dispose_op; canvas.save(); if (((APNGFrame) frame).blend_op == FCTLChunk.APNG_BLEND_OP_SOURCE) { canvas.clipRect( frame.frameX / sampleSize, frame.frameY / sampleSize, (frame.frameX + frame.frameWidth) / sampleSize, (frame.frameY + frame.frameHeight) / sampleSize); canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); } snapShot.dstRect.set(frame.frameX / sampleSize, frame.frameY / sampleSize, (frame.frameX + frame.frameWidth) / sampleSize, (frame.frameY + frame.frameHeight) / sampleSize); canvas.restore(); } //开始真正绘制当前帧的内容 Bitmap inBitmap = obtainBitmap(frame.frameWidth, frame.frameHeight); recycleBitmap(frame.draw(canvas, paint, sampleSize, inBitmap, getWriter())); recycleBitmap(inBitmap); frameBuffer.rewind(); bitmap.copyPixelsToBuffer(frameBuffer); recycleBitmap(bitmap); } catch (Throwable t) { Log.e(TAG, "Failed to render!", t); } } }
signalapp/Signal-Android
app/src/main/java/org/signal/glide/apng/decode/APNGDecoder.java
374
package app.hanks.com.conquer.util; public class Tasks { public static String[] tasks = new String[] { "跑步", "购物", "Shopping", "回家", "上班", "睡觉", "喝水", "做饭", "论文", "淘宝", "京东", "天猫", "1号店", "聚美优品", "工作", "篮球", "足球", "羽毛球", "乒乓球", "棒球", "网球", "游戏", "买菜", "步行", "炒菜", "休息", "起床", "背单词", "运动", "夕颜", "秋恋", "蝉羽", "浴兰", "沉鱼", "落雁", "闭月", "羞花", "幽然", "静微", "艺雅", "卉馨", "轩然", "子茹", "萦绕", "流萤", "静谧", "流凨", "羽翼", "蔓延", "浅唱", "轻盈", "清芳", "黯淡", "纯洁", "涤荡", "皓月", "思琪", "绚烂", "郁葱", "寂寞", "尘世", "词语", "疼痛", "猜测", "奔腾", "丑陋", "长久", "模仿", "固定", "寒冷", "恐惧", "奇怪", "整齐", "漂浮", "特殊", "虚假", "遥望", "微弱", "消灭", "珍贵", "祝愿", "缠绕", "颤抖", "抚摩", "拉扯", "柔软", "明亮", "宽敞", "黑暗", "破旧", "美好", "飞翔", "挖掘", "搜索", "期待", "盼望", "祈祷", "微小", "捕捉", "思忖", "思量", "思想", "思念", "思绪", "思索", "思维", "思考", "思辨", "思路", "思慕", "思逸", "思齐", "思远", "思春", "思韵", "思虑", "思辩", "思玄", "思恋", "思凡", "思致", "思惟", "思潮", "思忆", "思元", "思绎", "思域", "思永", "思怀", "思越", "思纬", "思理", "思莼", "思服", "思咏", "思愆", "思议", "思秋", "思言", "馨香", "飘散", "舒展", "娇美", "神韵", "恬静", "醉人", "素雅", "娇嫩", "幽香", "淡雅", "朴素", "花瓣", "花蕊", "花粉", "鲜花", "怒放", "含苞", "孤单", "寥寂", "寂寥", "落寞", "孤寂寂寞", "孤独", "寂静", "僻静", "宁静", "寂然", "清静", "沉寂", "沉静", "安静", "孤立", "伶仃", "孤单", "零落", "落莫", "动静", "呼吸", "朝夕", "取舍", "善恶", "兴衰", "祸福", "甘苦", "彼此", "首尾", "褒贬", "吞吐", "黑白", "是非", "多少", "真假", "虚实", "反正", "生死", "悲欢", "前后", "始末", "早晚", "昼夜", "曲直", "东西", "善恶", "南北", "开关", "左右", "眷恋", "留恋", "依恋", "迷恋", "自恋", "爱恋", "失恋", "贪恋", "思恋", "热恋", "怀恋", "初恋", "顾恋", "流恋", "恋恋", "悲恋", "相恋", "婉恋", "忆恋", "积恋", "恳恋", "情恋", "凝恋", "耽恋", "欣恋", "绻恋", "感恋", "单恋", "遐恋", "嫪恋", "安恋", "慕恋", "兴奋", "快乐", "喜悦", "愉快", "畅快", "欢畅", "欢喜", "欢腾", "欢快", "欣喜", "激奋", "激昂", "激情", "敬佩", "佩服", "崇拜", "钦仰", "惊恐", "惊慌", "惊吓", "惧怕", "恐惧", "胆怯", "畏缩", "发慌", "心慌", "恐慌", "激怒", "恼火", "怒斥", "怒吼", "震怒", "气愤", "担忧", "发愁", "犯愁", "忧伤", "忧愁", "忧心", "愁闷", "悲伤", "悲痛", "悲惨", "悲凉", "哀伤", "哀怨", "忧伤", "伤感", "瘦削", "憔悴", "俊美", "恬静", "慈祥", "苍白", "白皙", "清秀", "光滑", "英俊", "红润", "挺直", "扁平", "小巧", "笔直", "端庄", "秀气", "秀美", "巧嘴", "朱唇", "苍白", "红润", "干裂", "娇嫩", "整齐", "整洁", "雪白", "焦黄", "洁净", "蓬松", "鲜嫩", "粉红", "通红", "红嫩", "滑润", "滋润", "干巴", "干裂", "干燥", "蜡黄", "洁白", "炭黑", "瘦弱", "矮小", "苗条", "丰满", "强壮", "清秀", "单薄", "文弱", "干瘦", "轩昂", "文辞", "短语", "单词", "词组", "词汇", "字眼", "范例", "语素", "丰富", "信息", "组成", "最小", "最大", "造句", "单位", "构成", "方式", "可以", "神奇", "单纯", "自由", "单音", "双音", "多音", "可以", "山高", "水深", "天高", "地厚", "拥有", "凑整", "仿佛", "苍茫", "参差", "上面", "前方", "内部", "中间", "方位", "名词", "学生", "老师", "群众", "老头", "妇女", "同志", "叔叔", "婶婶", "爸爸", "妈妈", "哥哥", "弟弟", "姐姐", "妹妹", "事物", "蜗牛", "猎豹", "棒球", "足球", "蓝求", "战机", "飞机", "地球", "思想", "中学", "物理", "科穴", "碗盘", "竹筷", "上午", "下午", "过去", "将来", "早晨", "午夜", "三更", "甲戊", "世纪", "今天", "昨天", "动词", "行为", "跑步", "唱歌", "喝水", "敲门", "吆喝", "踢求", "生长", "枯萎", "发芽", "结果", "产卵", "喜欢", "气愤", "觉得", "思考", "厌恶", "存现", "消失", "显现", "丢失", "幻灭", "使令", "使人", "让座", "命令", "禁止", "勒令", "能愿", "如会", "愿意", "能够", "宁可", "表示", "状貌", "特征", "状态", "气急", "怒火", "高兴", "形容", "高大", "高瘦", "矮胖", "粗细", "强壮", "性质", "香甜", "漂亮", "圆滑", "机智", "单调", "快速", "浓厚", "肥满", "许多", "迅速", "悄悄", "量词", "单位", "公尺", "分寸", "公里", "公斤", "一两", "一辆", "一角", "一元", "一次", "一趟", "一下", "回声", "一幢", "一座", "代词", "代替", "我们", "你们", "它们", "她们", "大家", "咱们", "疑问", "谁的", "什么", "怎么", "哪里", "何以", "这里", "那里", "那边", "拟声", "模拟", "声音", "轰隆", "淅沥", "噼里", "啪啦", "哗啦", "叽喳", "啪拉", "哄堂", "开怀", "笑颜", "笑容", "喜笑", "欢声", "笑语", "眉开", "生气", "火冒", "雷霆", "欣喜", "心情", "词汇", "忧愁", "丧气", "雾气", "满腹", "满腔", "愁肠", "百结", "欲断", "寸断", "九转", "百愁", "心事", "阴郁", "忧心", "如焚", "愁绪", }; }
hanks-zyh/Conquer
app/src/main/java/app/hanks/com/conquer/util/Tasks.java
375
package org.hswebframework.web.bean; import org.springframework.util.ClassUtils; import java.lang.annotation.*; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author zhouhao * @since 3.0.0-RC */ public class ToString { public static long DEFAULT_FEATURE = Feature.createFeatures( Feature.coverIgnoreProperty , Feature.nullPropertyToEmpty // , Feature.jsonFormat ); public static final Map<Class, ToStringOperator> cache = new ConcurrentHashMap<>(); @SuppressWarnings("all") public static <T> ToStringOperator<T> getOperator(Class<T> type) { return cache.computeIfAbsent(type, DefaultToStringOperator::new); } @SuppressWarnings("all") public static <T> String toString(T target) { return getOperator((Class<T>) ClassUtils.getUserClass(target)).toString(target); } @SuppressWarnings("all") public static <T> String toString(T target, String... ignoreProperty) { return getOperator((Class<T>) ClassUtils.getUserClass(target)).toString(target, ignoreProperty); } @Target({ElementType.TYPE, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Ignore { String[] value() default {}; boolean cover() default true; } @Target({ElementType.TYPE, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Features { Feature[] value() default {}; } public enum Feature { /** * 什么也不配置 * * @since 3.0.0-RC */ empty, /** * 忽略为null的字段 * * @since 3.0.0-RC */ ignoreNullProperty, /** * null的字段转为空,如null字符串转为"", null的list转为[] * * @since 3.0.0-RC */ nullPropertyToEmpty, /** * 排除的字段使用*进行遮盖,如: 张三 =? 张* , 18502314087 => 185****087 * * @since 3.0.0-RC */ coverIgnoreProperty, /** * 是否关闭嵌套属性toString * * @since 3.0.0-RC */ disableNestProperty, /** * 以json方式进行格式化 * * @since 3.0.0-RC */ jsonFormat, /** * 是否写出类名 * * @since 3.0.0-RC */ writeClassname; public long getMask() { return 1L << ordinal(); } public static boolean hasFeature(long features, Feature feature) { long mast = feature.getMask(); return (features & mast) == mast; } public static long removeFeatures(long oldFeature, Feature... features) { if (features == null) { return 0L; } long value = oldFeature; for (Feature feature : features) { value &= ~feature.getMask(); } return value; } public static long createFeatures(Feature... features) { if (features == null) { return 0L; } long value = 0L; for (Feature feature : features) { value |= feature.getMask(); } return value; } } }
hs-web/hsweb-framework
hsweb-core/src/main/java/org/hswebframework/web/bean/ToString.java
376
package com.ysj.tinySpring.beans; /** * Bean在 IoC 容器中的定义, IoC 容器可以根据这个定义来生成实例 的问题 * * 以 BeanDefinition 类为核心发散出的几个类,都是用于解决 Bean 的具体定义问题,包括 Bean 的名字是什么、 * 它的类型是什么,它的属性赋予了哪些值或者引用 * */ public class BeanDefinition { private Object bean; /** * bean的类型 * 根据其 类型 可以生成一个类实例,然后可以把 属性 注入进去。 */ private Class beanClass; /** * bean的名字 */ private String beanClassName; /** * bean的属性集合 * 每个属性都是键值对 String - Object */ private PropertyValues propertyValues = new PropertyValues(); public BeanDefinition() { } public Object getBean() { return bean; } public void setBean(Object bean) { this.bean = bean; } public Class getBeanClass() { return beanClass; } public void setBeanClass(Class beanClass) { this.beanClass = beanClass; } public String getBeanClassName() { return beanClassName; } public void setBeanClassName(String beanClassName) { this.beanClassName = beanClassName; try { this.beanClass = Class.forName(beanClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public PropertyValues getPropertyValues() { return propertyValues; } public void setPropertyValues(PropertyValues propertyValues) { this.propertyValues = propertyValues; } }
code4craft/tiny-spring
src+/main/java/com/ysj/tinySpring/beans/BeanDefinition.java
377
/* * Copyright Lealone Database Group. * Licensed under the Server Side Public License, v 1. * Initial Developer: zhh */ package com.lealone.sql.query; import com.lealone.db.result.LocalResult; // 直接基于缓存中的结果集 class QCache extends QOperator { QCache(Select select, LocalResult result) { super(select); this.result = result; localResult = result; } @Override public void start() { // 什么都不做 } @Override public void run() { loopEnd = true; } @Override public void stop() { // 忽略limit和offset handleLocalResult(); } }
lealone/Lealone
lealone-sql/src/main/java/com/lealone/sql/query/QCache.java
378
package com.bolingcavalry.dto; import com.bolingcavalry.bean.Student; /** * @author willzhao * @version V1.0 * @Description: 用一句话描述该文件做什么 * @email [email protected] * @Date 2017/10/5 上午9:31 */ public class StudentDTO { /** * 返回的错误信息 */ String errorStr; /** * 查找结果 */ Student student; public String getErrorStr() { return errorStr; } public void setErrorStr(String errorStr) { this.errorStr = errorStr; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } }
zq2599/blog_demos
hbasedemo/src/main/java/com/bolingcavalry/dto/StudentDTO.java
379
package cn.exrick.manager.shiro; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.authz.AuthorizationFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.util.HashMap; import java.util.Map; /** * @author Exrickx */ public class MyPermissionFilter extends AuthorizationFilter { private static final Logger log= LoggerFactory.getLogger(MyPermissionFilter.class); @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception { Subject subject = this.getSubject(request, response); String[] perms = (String[]) ((String[]) o); boolean isPermitted = true; if (subject.getPrincipal() == null) { if(FilterUtil.isAjax(request)){ log.info("未登录或登录时间过长,是ajax!"); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("success", false); resultMap.put("message", "您还未登录或登录时间过长,请重新登录!"); FilterUtil.out(response, resultMap); }else{ log.info("未登录或登录时间过长,不是ajax!"); this.saveRequestAndRedirectToLogin(request, response); } //isPermitted = false; } else { if (perms != null && perms.length > 0) { if (perms.length == 1) { if (!subject.isPermitted(perms[0])) { isPermitted = false; } } else if (!subject.isPermittedAll(perms)) { isPermitted = false; } } if (!isPermitted) { if (FilterUtil.isAjax(request)) { log.info("没有该权限,并且是Ajax请求"); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("success", false); resultMap.put("message", "抱歉,您没有该权限!看就看,你点它干什么..."); FilterUtil.out(response, resultMap); } else { return isPermitted; } } } return isPermitted; } }
Exrick/xmall
xmall-manager-web/src/main/java/cn/exrick/manager/shiro/MyPermissionFilter.java
380
package com.iguigui.maaj.easySample; import com.sun.jna.Pointer; import com.sun.jna.win32.StdCallLibrary; //本质上是对C接口的抽象层 //请参考C接口 https://github.com/MaaAssistantArknights/MaaAssistantArknights/blob/master/include/AsstCaller.h public interface MaaCore extends StdCallLibrary { //回调接口定义 interface AsstApiCallback extends StdCallCallback { void callback(int msg, String detail_json, String custom_arg); } //第一步,加载资源 boolean AsstLoadResource(String path); //选一个你喜欢的create,搞不定回调就用普通create,又不是不能用 Pointer AsstCreate(); /** * 带回调的实例创建 * @param callback 回调方法实例 * @param custom_arg 用户参数,塞什么进去回头就给你回调的时候返回什么,例如填入自己生成的实例ID,回调回来就可以用于查询是哪个实例的回调信息 * @return */ Pointer AsstCreateEx(AsstApiCallback callback, String custom_arg); //销毁实例释放连接 void AsstDestroy(Pointer handle); //连接安卓 boolean AsstConnect(Pointer handle, String adb, String host, String config); //添加任务链 //参考集成文档 https://github.com/MaaAssistantArknights/MaaAssistantArknights/blob/master/docs/3.1-%E9%9B%86%E6%88%90%E6%96%87%E6%A1%A3.md int AsstAppendTask(Pointer handle, String type, String params); //运行时修改参数 boolean AsstSetTaskParams(Pointer handle, int taskId, String params); //开跑! boolean AsstStart(Pointer handle); //爷不想跑了爷要自己玩 boolean AsstStop(Pointer handle); /** * 获取最后一次截图的内容 * (但是这个接口我就没成功用上过 * @param handle Maa实例 * @param buff 图片PNG格式编码内容 * @param buff_size byte[]的长度 * @return 图片长度 */ long AsstGetImage(Pointer handle, byte[] buff, long buff_size); //模拟点击 boolean AsstCtrlerClick(Pointer handle, int x, int y, boolean block); //获取版本号 String AsstGetVersion(); //向maa注入日志 void AsstLog(String level, String message); }
MaaAssistantArknights/MaaAssistantArknights
src/Java/src/main/java/com/iguigui/maaj/easySample/MaaCore.java
381
package org.apdplat.word.analysis; import org.apdplat.word.WordSegmenter; import org.apdplat.word.corpus.Bigram; import org.apdplat.word.segmentation.Word; import org.apdplat.word.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** * 判定句子是有意义的人话的可能性 * 假设使用有限集合的字符随机生成一句话,如何来判断这句话是有意义的人话的可能性呢? * 为了降低难度,可以把“有限集合的字符”降低难度变成“有限集合的词”。 * 假设常用汉字有3000,随机生成的句子长度为10,则可生成的总的句子数目为: * 3000*3000... 也就是3000自乘10次。 * 所谓智能,是指人的智慧和行动能力,如果计算机不能真正解决这个问题,怎么能谈得上智能呢? * 随处可以见到的什么什么智能,什么什么又通过图灵测试,浮躁之风让人目不暇接。 * Created by ysc on 12/21/15. */ public class SentenceIdentify { private static final Logger LOGGER = LoggerFactory.getLogger(SentenceIdentify.class); private static final List<String> WORDS = new ArrayList<>(); static { try { Utils.readResource("/dic.txt").forEach(WORDS::add); }catch (Exception e){ LOGGER.error("load words failed", e); } } public static float identify(String sentence){ List<Word> words = WordSegmenter.segWithStopWords(sentence); System.out.println("随机单词: "+words); System.out.println("生成句子: "+sentence); return Bigram.sentenceScore(words); } public static List<String> generateRandomSentences(int count){ List<String> sentences = new ArrayList<>(); for(int i=0; i<count; i++){ StringBuilder sentence = new StringBuilder(); int len = new Random(System.nanoTime()).nextInt(5)+5; for(int j=0; j<len; j++){ sentence.append(WORDS.get(new Random(System.nanoTime()).nextInt(WORDS.size()))); } sentences.add(sentence.toString()); sentence.setLength(0); } return sentences; } private static void run(String encoding) { try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, encoding))){ String line = null; while((line = reader.readLine()) != null){ if("exit".equals(line)){ System.exit(0); LOGGER.info("退出"); return; } if(line.trim().equals("")){ continue; } processSentence(line.split(" ")); showUsage(); } } catch (IOException ex) { LOGGER.error("程序中断:", ex); } } private static void showUsage() { System.out.println(""); System.out.println("********************************************"); System.out.println("用法: 输入句子并回车"); System.out.println("输入exit退出程序"); System.out.println("********************************************"); } private static void processSentence(String[] args) { for (String item : args){ System.out.println("句子概率: " + identify(item)); } } public static List<Map.Entry<String, Float>> evaluation(List<String> sentences){ Map<String, Float> map = new ConcurrentHashMap<>(); sentences.parallelStream().forEach(sentence -> { float score = identify(sentence); map.put(sentence, score); }); return map.entrySet().stream().sorted((a,b)->b.getValue().compareTo(a.getValue())).collect(Collectors.toList()); } public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("我爱读书"); list.add("我爱学习"); list.add("我是一个人"); list.add("我是一个男人你是一个女人"); list.add("中话眼录学打了啊一有"); list.add("天我滑去人够"); list.addAll(generateRandomSentences(94)); AtomicInteger i = new AtomicInteger(); evaluation(list).forEach(entry->{ System.out.println(i.incrementAndGet() + ". 句子: " + entry.getKey() + ", 概率: " + entry.getValue()); }); String encoding = "utf-8"; if(args==null || args.length == 0){ showUsage(); run(encoding); }else if(Charset.isSupported(args[0])){ showUsage(); run(args[0]); }else{ processSentence(args); //非交互模式,退出JVM System.exit(0); } } }
ysc/word
src/main/java/org/apdplat/word/analysis/SentenceIdentify.java
383
/* * Copyright (c) 2018. paascloud.net All Rights Reserved. * 项目名称:paascloud快速搭建企业级分布式微服务平台 * 类名称:MenuVo.java * 创建人:刘兆明 * 联系方式:[email protected] * 开源地址: https://github.com/paascloud * 博客地址: http://blog.paascloud.net * 项目官网: http://paascloud.net */ package com.paascloud.provider.model.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.util.List; /** * The class Menu vo. * * @author [email protected] */ @Data @ApiModel("菜单") public class MenuVo implements Serializable { /** * serialVersionUID:用一句话描述这个变量表示什么. * * @since JDK 1.7 */ private static final long serialVersionUID = -2099147126084213856L; /** * menu.id; */ @ApiModelProperty("菜单编号") private Long id; /** * 父id */ @ApiModelProperty("父id") private Long pid; /** * 菜单编码 */ @ApiModelProperty("菜单编码") private String menuCode; /** * 菜单名称 */ @ApiModelProperty("菜单名称") private String menuName; /** * 菜单URL */ @ApiModelProperty("菜单URL") private String url; /** * 图标 */ @ApiModelProperty("图标") private String icon; /** * 序号 */ @ApiModelProperty("序号") private String number; /** * 备注(研发中心) */ @ApiModelProperty("备注(研发中心)") private String remark; /** * 删除标识 */ @ApiModelProperty("删除标识") private Short yn; private MenuVo parentMenu; private List<MenuVo> subMenu; private boolean hasMenu = false; }
paascloud/paascloud-master
paascloud-provider-api/paascloud-provider-uac-api/src/main/java/com/paascloud/provider/model/vo/MenuVo.java
384
package bobo.algo; import java.util.*; public class QuickSort2Ways { // 我们的算法类不允许产生任何实例 private QuickSort2Ways(){} // 双路快速排序的partition // 返回p, 使得arr[l...p-1] < arr[p] ; arr[p+1...r] > arr[p] private static int partition(Comparable[] arr, int l, int r){ // 随机在arr[l...r]的范围中, 选择一个数值作为标定点pivot swap( arr, l , (int)(Math.random()*(r-l+1))+l ); Comparable v = arr[l]; // arr[l+1...i) <= v; arr(j...r] >= v int i = l+1, j = r; while( true ){ // 注意这里的边界, arr[i].compareTo(v) < 0, 不能是arr[i].compareTo(v) <= 0 // 思考一下为什么? while( i <= r && arr[i].compareTo(v) < 0 ) i ++; // 注意这里的边界, arr[j].compareTo(v) > 0, 不能是arr[j].compareTo(v) >= 0 // 思考一下为什么? while( j >= l+1 && arr[j].compareTo(v) > 0 ) j --; // 对于上面的两个边界的设定, 有的同学在课程的问答区有很好的回答:) // 大家可以参考: http://coding.imooc.com/learn/questiondetail/4920.html if( i > j ) break; swap( arr, i, j ); i ++; j --; } swap(arr, l, j); return j; } // 递归使用快速排序,对arr[l...r]的范围进行排序 private static void sort(Comparable[] arr, int l, int r){ // 对于小规模数组, 使用插入排序 if( r - l <= 15 ){ InsertionSort.sort(arr, l, r); return; } int p = partition(arr, l, r); sort(arr, l, p-1 ); sort(arr, p+1, r); } public static void sort(Comparable[] arr){ int n = arr.length; sort(arr, 0, n-1); } private static void swap(Object[] arr, int i, int j) { Object t = arr[i]; arr[i] = arr[j]; arr[j] = t; } // 测试 Quick Sort 2 Ways public static void main(String[] args) { // 双路快速排序算法也是一个O(nlogn)复杂度的算法 // 可以在1秒之内轻松处理100万数量级的数据 int N = 1000000; Integer[] arr = SortTestHelper.generateRandomArray(N, 0, 100000); SortTestHelper.testSort("bobo.algo.QuickSort2Ways", arr); return; } }
liuyubobobo/Play-with-Algorithms
04-Heap/Course Code (Java)/05-Heapify/src/bobo/algo/QuickSort2Ways.java
385
package org.nlpcn.es4sql.query.maker; import com.alibaba.druid.util.StringUtils; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.join.aggregations.ChildrenAggregationBuilder; import org.elasticsearch.search.aggregations.PipelineAggregationBuilder; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.XContentParserConfiguration; import org.elasticsearch.xcontent.json.JsonXContent; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.InternalOrder; import org.elasticsearch.search.aggregations.bucket.filter.FiltersAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.filter.FiltersAggregator; import org.elasticsearch.search.aggregations.bucket.geogrid.GeoGridAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.histogram.LongBounds; import org.elasticsearch.search.aggregations.bucket.nested.ReverseNestedAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.range.DateRangeAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.SignificantTextAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.IncludeExclude; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.GeoBoundsAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.PercentilesAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.ScriptedMetricAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.TopHitsAggregationBuilder; import org.elasticsearch.aggregations.pipeline.BucketSelectorPipelineAggregationBuilder; import org.elasticsearch.aggregations.pipeline.MovFnPipelineAggregationBuilder; import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder; import org.elasticsearch.search.sort.SortOrder; import org.nlpcn.es4sql.Util; import org.nlpcn.es4sql.domain.Field; import org.nlpcn.es4sql.domain.KVValue; import org.nlpcn.es4sql.domain.MethodField; import org.nlpcn.es4sql.domain.Select; import org.nlpcn.es4sql.domain.Where; import org.nlpcn.es4sql.exception.SqlParseException; import org.nlpcn.es4sql.parse.ChildrenType; import org.nlpcn.es4sql.parse.NestedType; import java.io.IOException; import java.math.BigDecimal; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class AggMaker { //question 这个groupMap用来干嘛?? private Map<String, KVValue> groupMap = new HashMap<>(); /** * 分组查的聚合函数 * * @param field * @return * @throws SqlParseException */ public AggregationBuilder makeGroupAgg(Field field, Select select) throws SqlParseException { AggregationBuilder aggsBuilder = null; //zhongshu-comment script类型的MethodField /* TermsAggregationBuilder termsBuilder的样例: 来自这条sql的group by子句的gg字段解析结果: select a,case when c='1' then 'haha' when c='2' then 'book' else 'hbhb' end as gg from tbl_a group by a,gg */ if (field instanceof MethodField && field.getName().equals("script")) { MethodField methodField = (MethodField) field; TermsAggregationBuilder termsBuilder = AggregationBuilders.terms(methodField.getAlias()).script(new Script(methodField.getParams().get(1).value.toString())); //question 这里为什么要将这些信息加到groupMap中? groupMap.put(methodField.getAlias(), new KVValue("KEY", termsBuilder)); aggsBuilder = termsBuilder; } else if (field instanceof MethodField) { //zhongshu-comment filter类型的MethodField MethodField methodField = (MethodField) field; if (methodField.getName().equals("filter")) { Map<String, Object> paramsAsMap = methodField.getParamsAsMap(); Where where = (Where) paramsAsMap.get("where"); return AggregationBuilders.filter(paramsAsMap.get("alias").toString(), QueryMaker.explan(where)); } else if ("filters".equals(methodField.getName())) { Map<String, Object> paramsAsMap = methodField.getParamsAsMap(); List<FiltersAggregator.KeyedFilter> filters = new ArrayList<>(); @SuppressWarnings("unchecked") List<Field> filterFields = (List<Field>) paramsAsMap.get("filters"); for (Field f : filterFields) { Map<String, Object> params = ((MethodField) f).getParamsAsMap(); filters.add(new FiltersAggregator.KeyedFilter(params.get("alias").toString(), QueryMaker.explan((Where) params.get("where")))); } FiltersAggregationBuilder filtersAggBuilder = AggregationBuilders.filters(paramsAsMap.get("alias").toString(), filters.toArray(new FiltersAggregator.KeyedFilter[0])); Object otherBucketKey = paramsAsMap.get("otherBucketKey"); if (Objects.nonNull(otherBucketKey)) { filtersAggBuilder.otherBucketKey(otherBucketKey.toString()); } return filtersAggBuilder; } aggsBuilder = makeRangeGroup(methodField); } else { TermsAggregationBuilder termsBuilder = AggregationBuilders.terms(field.getName()).field(field.getName()); groupMap.put(field.getName(), new KVValue("KEY", termsBuilder)); aggsBuilder = termsBuilder; } //added by xzb 如果 group by 后面有having 条件,则创建BucketSelector String having = select.getHaving(); if (!StringUtils.isEmpty(having)) { String kvRegex = "\\s*(?<key>[^><=!\\s&|]+)\\s*(?<oprator>>=|>|<=|<|==|!=)\\s*(?<value>[^><=!\\s&|]+)\\s*"; List<String> havingFields = new ArrayList<>(); Pattern pattern = Pattern.compile(kvRegex); Matcher matcher = pattern.matcher(having); while (matcher.find()) { havingFields.add(matcher.group("key")); } //声明BucketPath,用于后面的bucket筛选 Map<String, String> bucketsPathsMap = new HashMap<>(); for (String key : havingFields) { bucketsPathsMap.put(key, key); //将key前面加上 param.参数 having = having.replace(key, "params." + key); } //将having语句中的 AND 和 OR 替换为&& 和 || ,painless 脚本只支持程序中的 && 和 || 逻辑判断 having = having.replace("AND", "&&").replace("OR", "||").replace("\\n", " "); //设置脚本 Script script = new Script(having); //构建bucket选择器 PipelineAggregationBuilder bs = Util.parsePipelineAggregationBuilder(new BucketSelectorPipelineAggregationBuilder("having", bucketsPathsMap, script)); aggsBuilder.subAggregation(bs); } return aggsBuilder; } public PipelineAggregationBuilder makeMovingFieldAgg(MethodField field, AggregationBuilder parent) throws SqlParseException { //question 加到groupMap里是为了什么 groupMap.put(field.getAlias(), new KVValue("FIELD", parent)); String bucketPath = field.getParams().get(0).value.toString(); int window = Integer.parseInt(field.getParams().get(1).value.toString()); ValuesSourceAggregationBuilder builder; field.setAlias(fixAlias(field.getAlias())); switch (field.getName().toUpperCase()) { //added by xzb 增加 movingavg和rollingstd case "MOVINGAVG": PipelineAggregationBuilder mvAvg = //PipelineAggregatorBuilders.movingFunction("movingAvgIncome", new Script("MovingFunctions.unweightedAvg(values)"), "incomeSum", 2); Util.parsePipelineAggregationBuilder(new MovFnPipelineAggregationBuilder(field.getAlias(), bucketPath, new Script("MovingFunctions.unweightedAvg(values)"), window)); return mvAvg; case "ROLLINGSTD": PipelineAggregationBuilder stdDev = //PipelineAggregatorBuilders.movingFunction("stdDevIncome", new Script("MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))"), "incomeSum", 2); Util.parsePipelineAggregationBuilder(new MovFnPipelineAggregationBuilder(field.getAlias(), bucketPath, new Script("MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))"), window)); return stdDev; } return null; } /** * Create aggregation according to the SQL function. * zhongshu-comment 根据sql中的函数来生成一些agg,例如sql中的count()、sum()函数,这是agg链中最里边的那个agg了,eg: * select a,b,count(c),sum(d) from tbl group by a,b * @param field SQL function * @param parent parentAggregation * @return AggregationBuilder represents the SQL function * @throws SqlParseException in case of unrecognized function */ public AggregationBuilder makeFieldAgg(MethodField field, AggregationBuilder parent) throws SqlParseException { //question 加到groupMap里是为了什么 groupMap.put(field.getAlias(), new KVValue("FIELD", parent)); ValuesSourceAggregationBuilder builder; field.setAlias(fixAlias(field.getAlias())); switch (field.getName().toUpperCase()) { case "SUM": builder = AggregationBuilders.sum(field.getAlias()); return addFieldToAgg(field, builder); case "MAX": builder = AggregationBuilders.max(field.getAlias()); return addFieldToAgg(field, builder); case "MIN": builder = AggregationBuilders.min(field.getAlias()); return addFieldToAgg(field, builder); case "AVG": builder = AggregationBuilders.avg(field.getAlias()); return addFieldToAgg(field, builder); case "STATS": builder = AggregationBuilders.stats(field.getAlias()); return addFieldToAgg(field, builder); case "EXTENDED_STATS": builder = AggregationBuilders.extendedStats(field.getAlias()); return addFieldToAgg(field, builder); case "PERCENTILES": builder = AggregationBuilders.percentiles(field.getAlias()); addSpecificPercentiles((PercentilesAggregationBuilder) builder, field.getParams()); return addFieldToAgg(field, builder); case "PERCENTILE_RANKS": double[] rankVals = getSpecificPercentileRankVals(field.getParams()); builder = AggregationBuilders.percentileRanks(field.getAlias(), rankVals); return addFieldToAgg(field, builder); case "TOPHITS": return makeTopHitsAgg(field); case "SCRIPTED_METRIC": return scriptedMetric(field); case "COUNT": groupMap.put(field.getAlias(), new KVValue("COUNT", parent)); return addFieldToAgg(field, makeCountAgg(field)); default: throw new SqlParseException("the agg function not to define !"); } } private void addSpecificPercentiles(PercentilesAggregationBuilder percentilesBuilder, List<KVValue> params) { List<Double> percentiles = new ArrayList<>(); for (KVValue kValue : params) { if (kValue.value.getClass().equals(BigDecimal.class)) { BigDecimal percentile = (BigDecimal) kValue.value; percentiles.add(percentile.doubleValue()); } else if (kValue.value instanceof Integer) { percentiles.add(((Integer) kValue.value).doubleValue()); } } if (percentiles.size() > 0) { double[] percentilesArr = new double[percentiles.size()]; int i = 0; for (Double percentile : percentiles) { percentilesArr[i] = percentile; i++; } percentilesBuilder.percentiles(percentilesArr); } } private double[] getSpecificPercentileRankVals(List<KVValue> params) { List<Double> rankVals = new ArrayList<>(); //added by xzb 找出 percentile_ranks 类型的MethodField 中要求取百分位的值 for (KVValue kValue : params) { if (kValue.value.getClass().equals(BigDecimal.class)) { BigDecimal percentile = (BigDecimal) kValue.value; rankVals.add(percentile.doubleValue()); } else if (kValue.value instanceof Integer) { rankVals.add(((Integer) kValue.value).doubleValue()); } } double[] _rankVals = new double[rankVals.size()]; for (int i = 0; i < rankVals.size(); i++) { _rankVals[i] = rankVals.get(i); } return _rankVals; } private String fixAlias(String alias) { //because [ is not legal as alias return alias.replaceAll("\\[", "(").replaceAll("\\]", ")"); } private AggregationBuilder addFieldToAgg(MethodField field, ValuesSourceAggregationBuilder builder) { KVValue kvValue = field.getParams().get(0); if (kvValue.key != null && kvValue.key.equals("script")) { if (kvValue.value instanceof MethodField) { return builder.script(new Script(((MethodField) kvValue.value).getParams().get(1).toString())); } else { return builder.script(new Script(kvValue.value.toString())); } } else if (kvValue.key != null && kvValue.value.toString().trim().startsWith("def")) { return builder.script(new Script(kvValue.value.toString())); } else if (kvValue.key != null && (kvValue.key.equals("nested") || kvValue.key.equals("reverse_nested"))) { NestedType nestedType = (NestedType) kvValue.value; builder.field(nestedType.field); AggregationBuilder nestedBuilder; String nestedAggName = nestedType.field + "@NESTED"; if (nestedType.isReverse()) { if (nestedType.path != null && nestedType.path.startsWith("~")) { String realPath = nestedType.path.substring(1); nestedBuilder = AggregationBuilders.nested(nestedAggName,realPath); nestedBuilder = nestedBuilder.subAggregation(builder); return AggregationBuilders.reverseNested(nestedAggName + "_REVERSED").subAggregation(nestedBuilder); } else { ReverseNestedAggregationBuilder reverseNestedAggregationBuilder = AggregationBuilders.reverseNested(nestedAggName); if (nestedType.path!=null){ reverseNestedAggregationBuilder.path(nestedType.path); } nestedBuilder = reverseNestedAggregationBuilder; } } else { nestedBuilder = AggregationBuilders.nested(nestedAggName,nestedType.path); } return nestedBuilder.subAggregation(builder); } else if (kvValue.key != null && (kvValue.key.equals("children"))) { ChildrenType childrenType = (ChildrenType) kvValue.value; builder.field(childrenType.field); AggregationBuilder childrenBuilder; String childrenAggName = childrenType.field + "@CHILDREN"; childrenBuilder = Util.parseAggregationBuilder(new ChildrenAggregationBuilder(childrenAggName, childrenType.childType)); return childrenBuilder; } return builder.field(kvValue.toString()); } private AggregationBuilder makeRangeGroup(MethodField field) throws SqlParseException { switch (field.getName().toLowerCase()) { case "range": return rangeBuilder(field); case "date_histogram": case "dhg": return dateHistogram(field); case "date_range": return dateRange(field); case "month": return dateRange(field); case "histogram": case "hg": return histogram(field); case "geohash_grid": return geohashGrid(field); case "geo_bounds": return geoBounds(field); case "terms": return termsAgg(field); case "significant_text": return significantTextAgg(field); default: throw new SqlParseException("can define this method " + field); } } private AggregationBuilder geoBounds(MethodField field) throws SqlParseException { String aggName = gettAggNameFromParamsOrAlias(field); GeoBoundsAggregationBuilder boundsBuilder = AggregationBuilders.geoBounds(aggName); String value = null; for (KVValue kv : field.getParams()) { value = kv.value.toString(); switch (kv.key.toLowerCase()) { case "field": boundsBuilder.field(value); break; case "wrap_longitude": boundsBuilder.wrapLongitude(Boolean.getBoolean(value)); break; case "alias": case "nested": case "reverse_nested": case "children": break; default: throw new SqlParseException("geo_bounds err or not define field " + kv.toString()); } } return boundsBuilder; } private AggregationBuilder termsAgg(MethodField field) throws SqlParseException { String aggName = gettAggNameFromParamsOrAlias(field); TermsAggregationBuilder terms = AggregationBuilders.terms(aggName); String value = null; IncludeExclude include = null, exclude = null; for (KVValue kv : field.getParams()) { if(kv.value.toString().contains("doc[")) { String script = kv.value + "; return " + kv.key; terms.script(new Script(script)); } else { value = kv.value.toString(); switch (kv.key.toLowerCase()) { case "field": terms.field(value); break; case "size": terms.size(Integer.parseInt(value)); break; case "shard_size": terms.shardSize(Integer.parseInt(value)); break; case "min_doc_count": terms.minDocCount(Integer.parseInt(value)); break; case "missing": terms.missing(value); break; case "order": if ("asc".equalsIgnoreCase(value)) { terms.order(BucketOrder.key(true)); } else if ("desc".equalsIgnoreCase(value)) { terms.order(BucketOrder.key(false)); } else { List<BucketOrder> orderElements = new ArrayList<>(); try (XContentParser parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE), value)) { XContentParser.Token currentToken = parser.nextToken(); if (currentToken == XContentParser.Token.START_OBJECT) { orderElements.add(InternalOrder.Parser.parseOrderParam(parser)); } else if (currentToken == XContentParser.Token.START_ARRAY) { for (currentToken = parser.nextToken(); currentToken != XContentParser.Token.END_ARRAY; currentToken = parser.nextToken()) { if (currentToken == XContentParser.Token.START_OBJECT) { orderElements.add(InternalOrder.Parser.parseOrderParam(parser)); } else { throw new ParsingException(parser.getTokenLocation(), "Invalid token in order array"); } } } } catch (IOException e) { throw new SqlParseException("couldn't parse order: " + e.getMessage()); } terms.order(orderElements); } break; case "alias": case "nested": case "reverse_nested": case "children": break; case "execution_hint": terms.executionHint(value); break; case "include": try (XContentParser parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE), value)) { parser.nextToken(); include = IncludeExclude.parseInclude(parser); } catch (IOException e) { throw new SqlParseException("parse include[" + value + "] error: " + e.getMessage()); } break; case "exclude": try (XContentParser parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE), value)) { parser.nextToken(); exclude = IncludeExclude.parseExclude(parser); } catch (IOException e) { throw new SqlParseException("parse exclude[" + value + "] error: " + e.getMessage()); } break; default: throw new SqlParseException("terms aggregation err or not define field " + kv.toString()); } } } terms.includeExclude(IncludeExclude.merge(include, exclude)); return terms; } private AggregationBuilder significantTextAgg(MethodField field) throws SqlParseException { String aggName = gettAggNameFromParamsOrAlias(field); SignificantTextAggregationBuilder significantText = AggregationBuilders.significantText(aggName, null); String value; IncludeExclude include = null, exclude = null; for (KVValue kv : field.getParams()) { value = kv.value.toString(); switch (kv.key.toLowerCase()) { case "field": significantText.fieldName(value); break; case "size": significantText.size(Integer.parseInt(value)); break; case "shard_size": significantText.shardSize(Integer.parseInt(value)); break; case "min_doc_count": significantText.minDocCount(Integer.parseInt(value)); break; case "include": try (XContentParser parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE), value)) { parser.nextToken(); include = IncludeExclude.parseInclude(parser); } catch (IOException e) { throw new SqlParseException("parse include[" + value + "] error: " + e.getMessage()); } break; case "exclude": try (XContentParser parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE), value)) { parser.nextToken(); exclude = IncludeExclude.parseExclude(parser); } catch (IOException e) { throw new SqlParseException("parse exclude[" + value + "] error: " + e.getMessage()); } break; case "alias": case "nested": case "reverse_nested": case "children": break; default: throw new SqlParseException("significant_text aggregation err or not define field " + kv.toString()); } } significantText.includeExclude(IncludeExclude.merge(include, exclude)); return significantText; } private AbstractAggregationBuilder scriptedMetric(MethodField field) throws SqlParseException { String aggName = gettAggNameFromParamsOrAlias(field); ScriptedMetricAggregationBuilder scriptedMetricBuilder = AggregationBuilders.scriptedMetric(aggName); Map<String, Object> scriptedMetricParams = field.getParamsAsMap(); if (!scriptedMetricParams.containsKey("map_script") && !scriptedMetricParams.containsKey("map_script_id") && !scriptedMetricParams.containsKey("map_script_file")) { throw new SqlParseException("scripted metric parameters must contain map_script/map_script_id/map_script_file parameter"); } HashMap<String, Object> scriptAdditionalParams = new HashMap<>(); HashMap<String, Object> reduceScriptAdditionalParams = new HashMap<>(); for (Map.Entry<String, Object> param : scriptedMetricParams.entrySet()) { String paramValue = param.getValue().toString(); if (param.getKey().startsWith("@")) { if (param.getKey().startsWith("@reduce_")) { reduceScriptAdditionalParams.put(param.getKey().replace("@reduce_", ""), param.getValue()); } else { scriptAdditionalParams.put(param.getKey().replace("@", ""), param.getValue()); } continue; } switch (param.getKey().toLowerCase()) { case "map_script": scriptedMetricBuilder.mapScript(new Script(paramValue)); break; case "map_script_id": scriptedMetricBuilder.mapScript(new Script(ScriptType.STORED, Script.DEFAULT_SCRIPT_LANG,paramValue, new HashMap<String, Object>())); break; case "init_script": scriptedMetricBuilder.initScript(new Script(paramValue)); break; case "init_script_id": scriptedMetricBuilder.initScript(new Script(ScriptType.STORED,Script.DEFAULT_SCRIPT_LANG,paramValue, new HashMap<String, Object>())); break; case "combine_script": scriptedMetricBuilder.combineScript(new Script(paramValue)); break; case "combine_script_id": scriptedMetricBuilder.combineScript(new Script(ScriptType.STORED, Script.DEFAULT_SCRIPT_LANG,paramValue, new HashMap<String, Object>())); break; case "reduce_script": scriptedMetricBuilder.reduceScript(new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG , paramValue, reduceScriptAdditionalParams)); break; case "reduce_script_id": scriptedMetricBuilder.reduceScript(new Script(ScriptType.STORED, Script.DEFAULT_SCRIPT_LANG,paramValue, reduceScriptAdditionalParams)); break; case "alias": case "nested": case "reverse_nested": case "children": break; default: throw new SqlParseException("scripted_metric err or not define field " + param.getKey()); } } if (scriptAdditionalParams.size() > 0) { scriptAdditionalParams.put("_agg", new HashMap<>()); scriptedMetricBuilder.params(scriptAdditionalParams); } return scriptedMetricBuilder; } private AggregationBuilder geohashGrid(MethodField field) throws SqlParseException { String aggName = gettAggNameFromParamsOrAlias(field); GeoGridAggregationBuilder geoHashGrid = AggregationBuilders.geohashGrid(aggName); String value = null; for (KVValue kv : field.getParams()) { value = kv.value.toString(); switch (kv.key.toLowerCase()) { case "precision": geoHashGrid.precision(Integer.parseInt(value)); break; case "field": geoHashGrid.field(value); break; case "size": geoHashGrid.size(Integer.parseInt(value)); break; case "shard_size": geoHashGrid.shardSize(Integer.parseInt(value)); break; case "alias": case "nested": case "reverse_nested": case "children": break; default: throw new SqlParseException("geohash grid err or not define field " + kv.toString()); } } return geoHashGrid; } private static final String TIME_FARMAT = "yyyy-MM-dd HH:mm:ss"; private ValuesSourceAggregationBuilder dateRange(MethodField field) { String alias = gettAggNameFromParamsOrAlias(field); DateRangeAggregationBuilder dateRange = AggregationBuilders.dateRange(alias).format(TIME_FARMAT); String value = null; List<String> ranges = new ArrayList<>(); for (KVValue kv : field.getParams()) { value = kv.value.toString(); if ("field".equals(kv.key)) { dateRange.field(value); continue; } else if ("format".equals(kv.key)) { dateRange.format(value); continue; } else if ("time_zone".equals(kv.key)) { dateRange.timeZone(ZoneOffset.of(value)); continue; } else if ("from".equals(kv.key)) { dateRange.addUnboundedFrom(kv.value.toString()); continue; } else if ("to".equals(kv.key)) { dateRange.addUnboundedTo(kv.value.toString()); continue; } else if ("alias".equals(kv.key) || "nested".equals(kv.key) || "children".equals(kv.key)) { continue; } else { ranges.add(value); } } for (int i = 1; i < ranges.size(); i++) { dateRange.addRange(ranges.get(i - 1), ranges.get(i)); } return dateRange; } /** * 按照时间范围分组 * * @param field * @return * @throws SqlParseException */ private DateHistogramAggregationBuilder dateHistogram(MethodField field) throws SqlParseException { String alias = gettAggNameFromParamsOrAlias(field); DateHistogramAggregationBuilder dateHistogram = AggregationBuilders.dateHistogram(alias).format(TIME_FARMAT); String value = null; for (KVValue kv : field.getParams()) { if(kv.value.toString().contains("doc[")) { String script = kv.value + "; return " + kv.key; dateHistogram.script(new Script(script)); } else { value = kv.value.toString(); switch (kv.key.toLowerCase()) { case "interval": String interval = kv.value.toString(); if (DateHistogramAggregationBuilder.DATE_FIELD_UNITS.containsKey(interval)) { dateHistogram.calendarInterval(new DateHistogramInterval(interval)); } else { dateHistogram.fixedInterval(new DateHistogramInterval(interval)); } break; case "calendar_interval": dateHistogram.calendarInterval(new DateHistogramInterval(kv.value.toString())); break; case "fixed_interval": dateHistogram.fixedInterval(new DateHistogramInterval(kv.value.toString())); break; case "field": dateHistogram.field(value); break; case "format": dateHistogram.format(value); break; case "time_zone": dateHistogram.timeZone(ZoneOffset.of(value)); break; case "min_doc_count": dateHistogram.minDocCount(Long.parseLong(value)); break; case "order": dateHistogram.order("desc".equalsIgnoreCase(value) ? BucketOrder.key(false) : BucketOrder.key(true)); break; case "extended_bounds": LongBounds extendedBounds = null; try (XContentParser parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE), value)) { extendedBounds = LongBounds.PARSER.parse(parser, null); } catch (IOException ex) { List<Integer> indexList = new LinkedList<>(); int index = -1; while ((index = value.indexOf(':', index + 1)) != -1) { indexList.add(index); } if (!indexList.isEmpty()) { index = indexList.get(indexList.size() / 2); extendedBounds = new LongBounds(value.substring(0, index), value.substring(index + 1)); } } if (extendedBounds != null) { dateHistogram.extendedBounds(extendedBounds); } break; case "offset": dateHistogram.offset(value); break; case "alias": case "nested": case "reverse_nested": case "children": break; default: throw new SqlParseException("date range err or not define field " + kv.toString()); } } } return dateHistogram; } private String gettAggNameFromParamsOrAlias(MethodField field) { String alias = field.getAlias(); for (KVValue kv : field.getParams()) { if (kv.key != null && kv.key.equals("alias")) alias = kv.value.toString(); } return alias; } private HistogramAggregationBuilder histogram(MethodField field) throws SqlParseException { String aggName = gettAggNameFromParamsOrAlias(field); HistogramAggregationBuilder histogram = AggregationBuilders.histogram(aggName); String value = null; for (KVValue kv : field.getParams()) { if(kv.value.toString().contains("doc[")) { String script = kv.value + "; return " + kv.key; histogram.script(new Script(script)); } else { value = kv.value.toString(); switch (kv.key.toLowerCase()) { case "interval": //modified by xzb histogram聚合, interval必须为数值 histogram.interval(Long.parseLong(value.replace("'", ""))); break; case "field": histogram.field(value); break; case "min_doc_count": histogram.minDocCount(Long.parseLong(value)); break; case "extended_bounds": String[] bounds = value.split(":"); if (bounds.length == 2) histogram.extendedBounds(Double.parseDouble(bounds[0]), Double.parseDouble(bounds[1])); break; case "alias": case "nested": case "reverse_nested": case "children": break; case "order": BucketOrder order = null; switch (value) { case "key_desc": order = BucketOrder.key(false); break; case "count_asc": order = BucketOrder.count(true); break; case "count_desc": order = BucketOrder.count(false); break; case "key_asc": default: order = BucketOrder.key(true); break; } histogram.order(order); break; default: throw new SqlParseException("histogram err or not define field " + kv.toString()); } } } return histogram; } /** * 构建范围查询 * * @param field * @return */ private RangeAggregationBuilder rangeBuilder(MethodField field) { // ignore alias param LinkedList<KVValue> params = field.getParams().stream().filter(kv -> !"alias".equals(kv.key)).collect(Collectors.toCollection(LinkedList::new)); KVValue param = Objects.requireNonNull(params.poll()); String fieldName; if (param.value instanceof NestedType) { fieldName = ((NestedType) param.value).field; } else { fieldName = param.toString(); } double[] ds = Util.KV2DoubleArr(params); RangeAggregationBuilder range = AggregationBuilders.range(field.getAlias()).field(fieldName); for (int i = 1; i < ds.length; i++) { range.addRange(ds[i - 1], ds[i]); } return range; } /** * Create count aggregation. * * @param field The count function * @return AggregationBuilder use to count result */ private ValuesSourceAggregationBuilder makeCountAgg(MethodField field) { // Cardinality is approximate DISTINCT. if ("DISTINCT".equals(field.getOption())) { if (field.getParams().size() == 1) { String fieldValue = field.getParams().get(0).value.toString(); //modified by xzb 去除 cardinality 下面的 fields字段,否则会导致计算结果为 0 //防止 SELECT count(distinct age%2) as distCnt FROM bank group by gender 出现计算错误问题 if (fieldValue.contains("def") && fieldValue.contains("return") || fieldValue.contains("doc[")) { return AggregationBuilders.cardinality(field.getAlias()); } else { return AggregationBuilders.cardinality(field.getAlias()).field(field.getParams().get(0).value.toString()); } } else { Integer precision_threshold = (Integer) (field.getParams().get(1).value); return AggregationBuilders.cardinality(field.getAlias()).precisionThreshold(precision_threshold).field(field.getParams().get(0).value.toString()); } } String fieldName = field.getParams().get(0).value.toString(); /* zhongshu-comment count(1) count(0)这种应该是查不到东西的,除非你的字段名就叫做1、0这样 es的count是针对某个字段做count的,见下面的dsl,对os这个字段做count "aggregations": { "COUNT(os)": { "value_count": { "field": "os" } } } 假如你是写count(*),那es-sql就帮你转成对"_index"字段做count,每一条数据都会有"_index"字段,该字段存储的是索引的名字 */ // In case of count(*) we use '_index' as field parameter to count all documents if ("*".equals(fieldName)) { KVValue kvValue = new KVValue(null, "_index"); field.getParams().set(0, kvValue); /* zhongshu-comment 这个看起来有点多此一举:先将"_index"字符串封装到KVValue中,然后再kv.toString()得到"_index"字符串,还不如直接将"_index"传进去AggregationBuilders.count(field.getAlias()).field("_index"); 其实目的是为了改变形参MethodField field的params参数中的值,由"*"改为"_index" */ return AggregationBuilders.count(field.getAlias()).field(kvValue.toString()); } else { String fieldValue = field.getParams().get(0).value.toString(); //modified by xzb 去除 cardinality 下面的 fields字段,否则会导致计算结果为 0 //防止 SELECT count(distinct age%2) as distCnt FROM bank group by gender 出现计算错误问题 if (fieldValue.contains("def") && fieldValue.contains("return") || fieldValue.contains("doc[")) { return AggregationBuilders.count(field.getAlias()); } else { return AggregationBuilders.count(field.getAlias()).field(fieldName); } } } /** * TOPHITS查询 * * @param field * @return */ private AbstractAggregationBuilder makeTopHitsAgg(MethodField field) { String alias = gettAggNameFromParamsOrAlias(field); TopHitsAggregationBuilder topHits = AggregationBuilders.topHits(alias); List<KVValue> params = field.getParams(); String[] include = null; String[] exclude = null; for (KVValue kv : params) { switch (kv.key) { case "from": topHits.from((int) kv.value); break; case "size": topHits.size((int) kv.value); break; case "include": include = kv.value.toString().split(","); break; case "exclude": exclude = kv.value.toString().split(","); break; case "alias": case "nested": case "reverse_nested": case "children": break; default: topHits.sort(kv.key, SortOrder.valueOf(kv.value.toString().toUpperCase())); break; } } if (include != null || exclude != null) { topHits.fetchSource(include, exclude); } return topHits; } public Map<String, KVValue> getGroupMap() { return this.groupMap; } }
NLPchina/elasticsearch-sql
src/main/java/org/nlpcn/es4sql/query/maker/AggMaker.java
387
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 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.tencent.wstt.gt.data; import java.util.concurrent.LinkedBlockingQueue; public class LogCache { private static final int MAC_CAP = 1000; private LinkedBlockingQueue<String[]> queue; public LogCache() { queue = new LinkedBlockingQueue<String[]>(MAC_CAP); } public boolean offer(String[] content) { return queue.offer(content); } public String[] take() throws InterruptedException { return queue.take(); } public void clear() { // TODO 日志之前不清理,不知道是为什么 queue.clear(); } }
Tencent/GT
android/GT_SDK/gtrsdk/src/main/java/com/tencent/wstt/gt/data/LogCache.java
388
import java.util.Collections; import java.util.Comparator; import java.util.List; public class Solution { public String replaceWords(List<String> dictionary, String sentence) { // 按照单词的长度从小到大排序(为什么) // Collections.sort(dictionary, (s1, s2) -> s1.length() - s2.length()); Collections.sort(dictionary, Comparator.comparingInt(String::length)); // 建树 Trie trie = new Trie(); for (String word : dictionary) { trie.insert(word); } String[] words = sentence.split(" "); StringBuilder stringBuilder = new StringBuilder(); for (String word : words) { // 这句话是核心,搜到前缀停下 stringBuilder.append(trie.search(word)).append(" "); } int len = stringBuilder.length(); stringBuilder.deleteCharAt(len - 1); return stringBuilder.toString(); } private class Trie { private class TrieNode { private boolean isWord; private TrieNode[] children = new TrieNode[26]; public TrieNode() { this.isWord = false; } } private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String s) { TrieNode currNode = root; for (char c : s.toCharArray()) { int index = c - 'a'; if (currNode.children[index] == null) { currNode.children[index] = new TrieNode(); } currNode = currNode.children[index]; } currNode.isWord = true; } public String search(String s) { TrieNode currNode = root; StringBuilder stringBuilder = new StringBuilder(); char[] charArray = s.toCharArray(); for (char c : charArray) { int index = c - 'a'; if (currNode.children[index] == null) { return s; } stringBuilder.append(c); currNode = currNode.children[index]; if (currNode.isWord) { return stringBuilder.toString(); } } return s; } } }
liweiwei1419/LeetCode-Solutions-in-Good-Style
23-trie/0648-replace-words-2/src/Solution.java
389
package com.juns.wechat.adpter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.juns.wechat.R; import com.juns.wechat.common.ViewHolder; public class PublishMsgAdpter extends BaseAdapter { protected Context context; LayoutInflater mInflater; public PublishMsgAdpter(Context ctx) { context = ctx; } @Override public int getCount() { return 5; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate( R.layout.layout_item_msg, parent, false); } ImageView img_avar = ViewHolder.get(convertView, R.id.contactitem_avatar_iv); TextView txt_name = ViewHolder.get(convertView, R.id.txt_name); TextView txt_del = ViewHolder.get(convertView, R.id.txt_del); TextView txt_content = ViewHolder.get(convertView, R.id.txt_content); TextView txt_time = ViewHolder.get(convertView, R.id.txt_time); TextView unreadLabel = ViewHolder.get(convertView, R.id.unread_msg_number); img_avar.setImageResource(R.drawable.icon_public); txt_name.setText("人人都是产品经理"); txt_content.setText("什么是用户?90%的人不知道"); txt_time.setText("昨天"); if (position == 0) { unreadLabel.setText("3"); unreadLabel.setVisibility(View.VISIBLE); } else { unreadLabel.setVisibility(View.GONE); } return convertView; } }
motianhuo/wechat
WeChat For Android Studio/app/src/main/java/com/juns/wechat/adpter/PublishMsgAdpter.java
390
/* * Copyright (C) 2020 The zfoo Authors * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package com.zfoo.net.util; /** * 改进的hash算法虽然发布比较均匀,但是没有Java自带的hash算法速度快,所以需要知道自己需要什么 * * @author godotg */ public abstract class HashUtils { private static final int P = 16777619; private static final int INIT_HASH = (int) 2166136261L; /** * 改进的32位FNV算法1 * * @param data 数组 * @return hash结果 */ public static int fnvHash(byte[] data) { var hash = INIT_HASH; for (byte b : data) { hash = (hash ^ b) * P; } hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; return Math.abs(hash); } /** * 改进的32位FNV算法1 * * @param object 计算hash的对象,会调用toString方法 * @return hash结果 */ public static int fnvHash(Object object) { var hash = object.toString().chars().reduce(INIT_HASH, (left, right) -> (left ^ right) * P); hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; return Math.abs(hash); } }
zfoo-project/zfoo
net/src/main/java/com/zfoo/net/util/HashUtils.java
391
package com.codeest.geeknews.model.bean; import java.util.List; /** * Created by codeest on 16/8/12. */ public class DailyListBean { /** * date : 20160811 * stories : [{"images":["http://pic4.zhimg.com/95625b7bacfff0f6b1105ff3e71f37cb.jpg"],"type":0,"id":8675619,"ga_prefix":"081122","title":"小事 · 我在戒网瘾学校里经历了什么"},{"title":"有人看到情欲,有人看到暗黑,有人认为这是年度最值得期待的佳作","ga_prefix":"081121","images":["http://pic4.zhimg.com/67cbc856dbed2503dffe5afbdcccfc57.jpg"],"multipic":true,"type":0,"id":8675273},{"title":"整点儿奥运 · 别走啊,我用锅铲跟你打,行吗?","ga_prefix":"081120","images":["http://pic4.zhimg.com/af18477180b614d5f438c2dd06496bb3.jpg"],"multipic":true,"type":0,"id":8673847},{"title":"照片调色加俩黑条 = 电影感?一群导演和摄影师哭瞎","ga_prefix":"081119","images":["http://pic1.zhimg.com/6555bcf2b733a3cb0e26225ea5dcc548.jpg"],"multipic":true,"type":0,"id":8675601},{"images":["http://pic4.zhimg.com/c3fd1923a8f012b2a7770cffa6c8a0c3.jpg"],"type":0,"id":8675582,"ga_prefix":"081118","title":"性别不同,更有可能站在不同的「政」营?"},{"images":["http://pic2.zhimg.com/dc11586a263af5bbcfa27d7fd80bd835.jpg"],"type":0,"id":8671349,"ga_prefix":"081117","title":"知乎好问题 · 低学历是否比高学历更加会赚钱?"},{"title":"整个彩虹合唱团都出动了,只为让你唱好合唱","ga_prefix":"081116","images":["http://pic3.zhimg.com/d530aaba3304e52c8543a416e6d4670e.jpg"],"multipic":true,"type":0,"id":8664572},{"title":"柠檬 + 酸奶 + 冰淇淋,每一样都能让被蒸熟的我复活","ga_prefix":"081114","images":["http://pic2.zhimg.com/272d4bcd106271178620c864490c6039.jpg"],"multipic":true,"type":0,"id":8671431},{"images":["http://pic4.zhimg.com/944d3062d9709285763b276894679443.jpg"],"type":0,"id":8665792,"ga_prefix":"081112","title":"大误 · 我无法砸了我的手机"},{"images":["http://pic3.zhimg.com/92d67149451bfc24228e84b00dcdd316.jpg"],"type":0,"id":8673963,"ga_prefix":"081111","title":"有大公司 offer 却选择了小公司是为什么?"},{"images":["http://pic3.zhimg.com/3f734ae8eaa2c919f9df7bdadb258572.jpg"],"type":0,"id":8672587,"ga_prefix":"081110","title":"把加密算法本身保密起来,不就是绝对安全了?"},{"images":["http://pic4.zhimg.com/1818c8c204592c03d2322ee958261d4b.jpg"],"type":0,"id":8671284,"ga_prefix":"081109","title":"「孙杨夺冠把泳帽误扔泳池里以后,我发现我更喜欢他了」"},{"images":["http://pic4.zhimg.com/d2d586e6b82902c30a17605cdfb894ef.jpg"],"type":0,"id":8672664,"ga_prefix":"081108","title":"只是寄个快递,结果律师被「坑惨」了"},{"images":["http://pic4.zhimg.com/8adbdaad1daaad81e09cc55eb3a6b553.jpg"],"type":0,"id":8652559,"ga_prefix":"081107","title":"还在比较「唱功」的人,听不懂李宗盛"},{"images":["http://pic2.zhimg.com/efa0c4d9b0dba8d1b45fb9161bb9c9b1.jpg"],"type":0,"id":8672657,"ga_prefix":"081107","title":"有时也会迷惑,我到底是来种地,还是来读硕士的"},{"title":"吃河豚会死吗?不吃河豚会死吗?","ga_prefix":"081107","images":["http://pic4.zhimg.com/c11e628e679fa30b30a0103f757edadf.jpg"],"multipic":true,"type":0,"id":8655025},{"images":["http://pic4.zhimg.com/7eabe3ce21a0728cc7e149d7f92865f7.jpg"],"type":0,"id":8672907,"ga_prefix":"081107","title":"读读日报 24 小时热门 TOP 5 · 为什么孙杨总会被别人质疑「服药」"},{"images":["http://pic1.zhimg.com/00da4103ad41aa4f39118004a4dd7078.jpg"],"type":0,"id":8670451,"ga_prefix":"081106","title":"瞎扯 · 如何正确地吐槽"}] * top_stories : [{"image":"http://pic4.zhimg.com/1f45c1ed56116f21955878dff00e8c37.jpg","type":0,"id":8673847,"ga_prefix":"081120","title":"整点儿奥运 · 别走啊,我用锅铲跟你打,行吗?"},{"image":"http://pic4.zhimg.com/8d962d0d877d42518a9e6f73fe35ac8b.jpg","type":0,"id":8664572,"ga_prefix":"081116","title":"整个彩虹合唱团都出动了,只为让你唱好合唱"},{"image":"http://pic1.zhimg.com/e73a48ac3c95f55c715d8625957808a4.jpg","type":0,"id":8671349,"ga_prefix":"081117","title":"知乎好问题 · 低学历是否比高学历更加会赚钱?"},{"image":"http://pic3.zhimg.com/eca053868591893a70e8a48a05979d46.jpg","type":0,"id":8671431,"ga_prefix":"081114","title":"柠檬 + 酸奶 + 冰淇淋,每一样都能让被蒸熟的我复活"},{"image":"http://pic1.zhimg.com/8504a2e5046bd33ca556daaaeb3981e8.jpg","type":0,"id":8671284,"ga_prefix":"081109","title":"「孙杨夺冠把泳帽误扔泳池里以后,我发现我更喜欢他了」"}] */ private String date; /** * images : ["http://pic4.zhimg.com/95625b7bacfff0f6b1105ff3e71f37cb.jpg"] * type : 0 * id : 8675619 * ga_prefix : 081122 * title : 小事 · 我在戒网瘾学校里经历了什么 */ private List<StoriesBean> stories; /** * image : http://pic4.zhimg.com/1f45c1ed56116f21955878dff00e8c37.jpg * type : 0 * id : 8673847 * ga_prefix : 081120 * title : 整点儿奥运 · 别走啊,我用锅铲跟你打,行吗? */ private List<TopStoriesBean> top_stories; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public List<StoriesBean> getStories() { return stories; } public void setStories(List<StoriesBean> stories) { this.stories = stories; } public List<TopStoriesBean> getTop_stories() { return top_stories; } public void setTop_stories(List<TopStoriesBean> top_stories) { this.top_stories = top_stories; } public static class StoriesBean { private int type; private int id; private String ga_prefix; private String title; private List<String> images; private boolean readState; public boolean getReadState() { return readState; } public void setReadState(boolean readState) { this.readState = readState; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getGa_prefix() { return ga_prefix; } public void setGa_prefix(String ga_prefix) { this.ga_prefix = ga_prefix; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<String> getImages() { return images; } public void setImages(List<String> images) { this.images = images; } } public static class TopStoriesBean { private String image; private int type; private int id; private String ga_prefix; private String title; public String getImage() { return image; } public void setImage(String image) { this.image = image; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getGa_prefix() { return ga_prefix; } public void setGa_prefix(String ga_prefix) { this.ga_prefix = ga_prefix; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } }
codeestX/GeekNews
app/src/main/java/com/codeest/geeknews/model/bean/DailyListBean.java
392
package cn.hutool.core.date; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ArrayUtil; import java.time.DayOfWeek; import java.util.Calendar; /** * 星期枚举<br> * 与Calendar中的星期int值对应 * * @author Looly * @see #SUNDAY * @see #MONDAY * @see #TUESDAY * @see #WEDNESDAY * @see #THURSDAY * @see #FRIDAY * @see #SATURDAY */ public enum Week { /** * 周日 */ SUNDAY(Calendar.SUNDAY), /** * 周一 */ MONDAY(Calendar.MONDAY), /** * 周二 */ TUESDAY(Calendar.TUESDAY), /** * 周三 */ WEDNESDAY(Calendar.WEDNESDAY), /** * 周四 */ THURSDAY(Calendar.THURSDAY), /** * 周五 */ FRIDAY(Calendar.FRIDAY), /** * 周六 */ SATURDAY(Calendar.SATURDAY); // --------------------------------------------------------------- /** * Weeks aliases. */ private static final String[] ALIASES = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"}; private static final Week[] ENUMS = Week.values(); /** * 星期对应{@link Calendar} 中的Week值 */ private final int value; /** * 构造 * * @param value 星期对应{@link Calendar} 中的Week值 */ Week(int value) { this.value = value; } /** * 获得星期对应{@link Calendar} 中的Week值 * * @return 星期对应 {@link Calendar} 中的Week值 */ public int getValue() { return this.value; } /** * 获取ISO8601规范的int值,from 1 (Monday) to 7 (Sunday). * * @return ISO8601规范的int值 * @since 5.8.0 */ public int getIso8601Value(){ int iso8601IntValue = getValue() -1; if(0 == iso8601IntValue){ iso8601IntValue = 7; } return iso8601IntValue; } /** * 转换为中文名 * * @return 星期的中文名 * @since 3.3.0 */ public String toChinese() { return toChinese("星期"); } /** * 转换为中文名 * * @param weekNamePre 表示星期的前缀,例如前缀为“星期”,则返回结果为“星期一”;前缀为”周“,结果为“周一” * @return 星期的中文名 * @since 4.0.11 */ public String toChinese(String weekNamePre) { switch (this) { case SUNDAY: return weekNamePre + "日"; case MONDAY: return weekNamePre + "一"; case TUESDAY: return weekNamePre + "二"; case WEDNESDAY: return weekNamePre + "三"; case THURSDAY: return weekNamePre + "四"; case FRIDAY: return weekNamePre + "五"; case SATURDAY: return weekNamePre + "六"; default: return null; } } /** * 转换为{@link DayOfWeek} * * @return {@link DayOfWeek} * @since 5.8.0 */ public DayOfWeek toJdkDayOfWeek() { return DayOfWeek.of(getIso8601Value()); } /** * 将 {@link Calendar}星期相关值转换为Week枚举对象<br> * * @param calendarWeekIntValue Calendar中关于Week的int值,1表示Sunday * @return Week * @see #SUNDAY * @see #MONDAY * @see #TUESDAY * @see #WEDNESDAY * @see #THURSDAY * @see #FRIDAY * @see #SATURDAY */ public static Week of(int calendarWeekIntValue) { if (calendarWeekIntValue > ENUMS.length || calendarWeekIntValue < 1) { return null; } return ENUMS[calendarWeekIntValue - 1]; } /** * 解析别名为Week对象,别名如:sun或者SUNDAY,不区分大小写 * * @param name 别名值 * @return 周枚举Week,非空 * @throws IllegalArgumentException 如果别名无对应的枚举,抛出此异常 * @since 5.8.0 */ public static Week of(String name) throws IllegalArgumentException { Assert.notBlank(name); Week of = of(ArrayUtil.indexOfIgnoreCase(ALIASES, name) + 1); if (null == of) { of = Week.valueOf(name.toUpperCase()); } return of; } /** * 将 {@link DayOfWeek}星期相关值转换为Week枚举对象<br> * * @param dayOfWeek DayOfWeek星期值 * @return Week * @see #SUNDAY * @see #MONDAY * @see #TUESDAY * @see #WEDNESDAY * @see #THURSDAY * @see #FRIDAY * @see #SATURDAY * @since 5.7.14 */ public static Week of(DayOfWeek dayOfWeek) { Assert.notNull(dayOfWeek); int week = dayOfWeek.getValue() + 1; if(8 == week){ // 周日 week = 1; } return of(week); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/date/Week.java
394
package array; /** * 1) 数组的插入、删除、按照下标随机访问操作; * 2)数组中的数据是int类型的; * * Author: Zheng * modify: xing, Gsealy */ public class Array { //定义整型数据data保存数据 public int data[]; //定义数组长度 private int n; //定义中实际个数 private int count; //构造方法,定义数组大小 public Array(int capacity){ this.data = new int[capacity]; this.n = capacity; this.count=0;//一开始一个数都没有存所以为0 } //根据索引,找到数据中的元素并返回 public int find(int index){ if (index<0 || index>=count) return -1; return data[index]; } //插入元素:头部插入,尾部插入 public boolean insert(int index, int value){ //数组中无元素 //if (index == count && count == 0) { // data[index] = value; // ++count; // return true; //} // 数组空间已满 if (count == n) { System.out.println("没有可插入的位置"); return false; } // 如果count还没满,那么就可以插入数据到数组中 // 位置不合法 if (index < 0||index > count ) { System.out.println("位置不合法"); return false; } // 位置合法 for( int i = count; i > index; --i){ data[i] = data[i - 1]; } data[index] = value; ++count; return true; } //根据索引,删除数组中元素 public boolean delete(int index){ if (index<0 || index >=count) return false; //从删除位置开始,将后面的元素向前移动一位 for (int i=index+1; i<count; ++i){ data[i-1] = data[i]; } //删除数组末尾元素 这段代码不需要也可以 /*int[] arr = new int[count-1]; for (int i=0; i<count-1;i++){ arr[i] = data[i]; } this.data = arr;*/ --count; return true; } public void printAll() { for (int i = 0; i < count; ++i) { System.out.print(data[i] + " "); } System.out.println(); } public static void main(String[] args) { Array array = new Array(5); array.printAll(); array.insert(0, 3); array.insert(0, 4); array.insert(1, 5); array.insert(3, 9); array.insert(3, 10); //array.insert(3, 11); array.printAll(); } }
wangzheng0822/algo
java/05_array/Array.java
396
/** * File: two_sum.java * Created Time: 2022-11-25 * Author: krahets ([email protected]) */ package chapter_searching; import java.util.*; public class two_sum { /* 方法一:暴力枚举 */ static int[] twoSumBruteForce(int[] nums, int target) { int size = nums.length; // 两层循环,时间复杂度为 O(n^2) for (int i = 0; i < size - 1; i++) { for (int j = i + 1; j < size; j++) { if (nums[i] + nums[j] == target) return new int[] { i, j }; } } return new int[0]; } /* 方法二:辅助哈希表 */ static int[] twoSumHashTable(int[] nums, int target) { int size = nums.length; // 辅助哈希表,空间复杂度为 O(n) Map<Integer, Integer> dic = new HashMap<>(); // 单层循环,时间复杂度为 O(n) for (int i = 0; i < size; i++) { if (dic.containsKey(target - nums[i])) { return new int[] { dic.get(target - nums[i]), i }; } dic.put(nums[i], i); } return new int[0]; } public static void main(String[] args) { // ======= Test Case ======= int[] nums = { 2, 7, 11, 15 }; int target = 13; // ====== Driver Code ====== // 方法一 int[] res = twoSumBruteForce(nums, target); System.out.println("方法一 res = " + Arrays.toString(res)); // 方法二 res = twoSumHashTable(nums, target); System.out.println("方法二 res = " + Arrays.toString(res)); } }
krahets/hello-algo
codes/java/chapter_searching/two_sum.java
397
package com.crossoverjie.actual; /** * Function: * * @author crossoverJie * Date: 2018/10/13 20:00 * @since JDK 1.8 */ import org.junit.Assert; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Function: * 一个“.”代表一个任意字母。 注意事项:可以假设所有的单词只包含小写字母“a-z” 样例: addWord(“bad”); addWord(“dad”); addWord(“mad”); search(“pad”); // return false; search(“bad”); // return true; search(“.ad”); // return true; search(“b..”); // return true; 如果有并发的情况下,addword() 怎么处理? * * @author crossoverJie * @since JDK 1.8 */ public class Search { private static Map<String,String> ALL_MAP = new ConcurrentHashMap<>(50000) ; /** * 换成 ascii码 更省事 */ private static final char[] dictionary = {'a','b','c','d','m','p'} ; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "ad"); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "bd"); } } }); Thread t3 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "cd"); } } }); Thread t4 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "dd"); } } }); Thread t5 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { addWord(i + "ed"); } } }); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); System.out.println(ALL_MAP.size()); Assert.assertEquals(50000,ALL_MAP.size()); addWord("bad"); addWord("dad"); addWord("mad"); boolean pad = search("pad"); System.out.println(pad); Assert.assertFalse(pad); boolean bad = search("bad"); System.out.println(bad); Assert.assertTrue(bad); boolean ad = search(".ad"); System.out.println(ad); Assert.assertTrue(ad); boolean bsearch = search("b.."); System.out.println(bsearch); Assert.assertTrue(bsearch); boolean asearch = search(".a."); System.out.println(asearch); boolean search = search(".af"); System.out.println(search); boolean search1 = search(null); System.out.println(search1); } public static boolean search(String keyWord){ boolean result = false ; if (null == keyWord || keyWord.trim().equals("")){ return result ; } //做一次完整匹配 String whole = ALL_MAP.get(keyWord) ; if (whole != null){ return true ; } char[] wordChars = keyWord.toCharArray() ; for (int i = 0; i < wordChars.length; i++) { char wordChar = wordChars[i] ; if (46 != (int)wordChar){ continue ; } for (char dic : dictionary) { wordChars[i] = dic ; boolean search = search(String.valueOf(wordChars)); if (search){ return search ; } String value = ALL_MAP.get(String.valueOf(wordChars)); if (value != null){ return true ; } } } return result ; } public static void addWord(String word){ ALL_MAP.put(word,word) ; } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/actual/Search.java
398
package com.macro.mall.dto; import com.macro.mall.validator.FlagValidator; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import javax.validation.constraints.NotEmpty; /** * 商品属性参数 * Created by macro on 2018/4/26. */ @Data @EqualsAndHashCode public class PmsProductAttributeParam { @NotEmpty @ApiModelProperty("属性分类ID") private Long productAttributeCategoryId; @NotEmpty @ApiModelProperty("属性名称") private String name; @FlagValidator({"0","1","2"}) @ApiModelProperty("属性选择类型:0->唯一;1->单选;2->多选") private Integer selectType; @FlagValidator({"0","1"}) @ApiModelProperty("属性录入方式:0->手工录入;1->从列表中选取") private Integer inputType; @ApiModelProperty("可选值列表,以逗号隔开") private String inputList; private Integer sort; @ApiModelProperty("分类筛选样式:0->普通;1->颜色") @FlagValidator({"0","1"}) private Integer filterType; @ApiModelProperty("检索类型;0->不需要进行检索;1->关键字检索;2->范围检索") @FlagValidator({"0","1","2"}) private Integer searchType; @ApiModelProperty("相同属性商品是否关联;0->不关联;1->关联") @FlagValidator({"0","1"}) private Integer relatedStatus; @ApiModelProperty("是否支持手动新增;0->不支持;1->支持") @FlagValidator({"0","1"}) private Integer handAddStatus; @ApiModelProperty("属性的类型;0->规格;1->参数") @FlagValidator({"0","1"}) private Integer type; }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/dto/PmsProductAttributeParam.java
401
package run.halo.app.infra; import static io.swagger.v3.oas.annotations.media.Schema.RequiredMode.REQUIRED; import io.swagger.v3.oas.annotations.media.Schema; import java.time.Instant; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * EqualsAndHashCode 排除了lastTransitionTime否则失败时,lastTransitionTime 会被更新 * 导致 equals 为 false,一直被加入队列. * * @author guqing * @see * <a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-conditions">pod-conditions</a> * @since 2.0.0 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(exclude = "lastTransitionTime") public class Condition { /** * type of condition in CamelCase or in foo.example.com/CamelCase. * example: Ready, Initialized. * maxLength: 316. */ @Schema(requiredMode = REQUIRED, maxLength = 316, pattern = "^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(" + "([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$") private String type; /** * Status is the status of the condition. Can be True, False, Unknown. */ @Schema(requiredMode = REQUIRED) private ConditionStatus status; /** * Last time the condition transitioned from one status to another. */ @Schema(requiredMode = REQUIRED) private Instant lastTransitionTime; /** * Human-readable message indicating details about last transition. * This may be an empty string. */ @Schema(requiredMode = REQUIRED, maxLength = 32768) private String message; /** * Unique, one-word, CamelCase reason for the condition's last transition. */ @Schema(requiredMode = REQUIRED, maxLength = 1024, pattern = "^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$") private String reason; }
halo-dev/halo
api/src/main/java/run/halo/app/infra/Condition.java
403
package org.pdown.gui.entity; import java.io.Serializable; import java.util.List; import org.pdown.core.proxy.ProxyConfig; public class PDownConfigInfo implements Serializable { private static final long serialVersionUID = 250452934883002540L; //客户端语言 private String locale; //UI模式 0.浏览器模式 1.GUI模式 private int uiMode = 1; //代理模式 0.不接管系统代理 1.由pdown接管系统代理 private int proxyMode; //插件文件服务器(用于下载插件相关文件) private List<String> extFileServers; //检测更新频率 0.从不 1.一周检查一次 2.每次打开检查 private int updateCheckRate = 2; //启动时是否自动打开窗口 private boolean autoOpen = true; //最后一次检查更新时间 private long lastUpdateCheck; //前置代理 private ProxyConfig proxyConfig; public String getLocale() { return locale; } public PDownConfigInfo setLocale(String locale) { this.locale = locale; return this; } public int getUiMode() { return uiMode; } public PDownConfigInfo setUiMode(int uiMode) { this.uiMode = uiMode; return this; } public int getProxyMode() { return proxyMode; } public PDownConfigInfo setProxyMode(int proxyMode) { this.proxyMode = proxyMode; return this; } public List<String> getExtFileServers() { return extFileServers; } public PDownConfigInfo setExtFileServers(List<String> extFileServers) { this.extFileServers = extFileServers; return this; } public int getUpdateCheckRate() { return updateCheckRate; } public PDownConfigInfo setUpdateCheckRate(int updateCheckRate) { this.updateCheckRate = updateCheckRate; return this; } public long getLastUpdateCheck() { return lastUpdateCheck; } public PDownConfigInfo setLastUpdateCheck(long lastUpdateCheck) { this.lastUpdateCheck = lastUpdateCheck; return this; } public ProxyConfig getProxyConfig() { return proxyConfig; } public PDownConfigInfo setProxyConfig(ProxyConfig proxyConfig) { this.proxyConfig = proxyConfig; return this; } public boolean isAutoOpen() { return autoOpen; } public PDownConfigInfo setAutoOpen(boolean autoOpen) { this.autoOpen = autoOpen; return this; } public static com.github.monkeywie.proxyee.proxy.ProxyConfig convert(ProxyConfig proxyConfig) { if (proxyConfig == null) { return null; } return new com.github.monkeywie.proxyee.proxy.ProxyConfig( com.github.monkeywie.proxyee.proxy.ProxyType.valueOf(proxyConfig.getProxyType().name()), proxyConfig.getHost(), proxyConfig.getPort(), proxyConfig.getUser(), proxyConfig.getPwd()); } }
proxyee-down-org/proxyee-down
main/src/main/java/org/pdown/gui/entity/PDownConfigInfo.java
407
package org.wltea.analyzer.help; import org.apache.logging.log4j.Logger; public class Sleep { private static final Logger logger = ESPluginLoggerFactory.getLogger(Sleep.class.getName()); public enum Type {MSEC, SEC, MIN, HOUR} ; public static void sleep(Type type, int num) { try { switch (type) { case MSEC: Thread.sleep(num); return; case SEC: Thread.sleep(num * 1000); return; case MIN: Thread.sleep(num * 60 * 1000); return; case HOUR: Thread.sleep(num * 60 * 60 * 1000); return; default: System.err.println("输入类型错误,应为MSEC,SEC,MIN,HOUR之一"); return; } } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } }
infinilabs/analysis-ik
core/src/main/java/org/wltea/analyzer/help/Sleep.java
408
M tags: Array, Sort, Two Pointers time: O(n^2) #### sort array, for loop + two pointer - 处理duplicate wthin triplets: - 如果最外圈的移动点i重复, 一直顺到结尾的最后一个再用. - 如果是triplet内有重复, 用完start point, 移动到结尾. - Note: - 1. 找 value triplets, 多个结果。注意,并非找index。 - 2. 要升序, 第一层for loop 从最后一个元素挑起, 保证了顺序。 - 3. 去掉duplicate: check用过的同样的数字,都跳掉。不需要用同样的数字再计算一边已有结果。 - 时间 O(n^2), 两个nested loop #### For loop + 2Sum - HashMap 2Sum. Remember to handle duplicates - 1. For loop 挑个数字A - 2. 2Sum 出一堆2个数字的结果 - 3. Cross match 步骤1里面的A ``` /* Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Example For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2) Note Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets. Tags Expand Two Pointers Sort Array Facebook *//* Thoughts: Sort the list, do a for loop and two pointer within. Make sure to skip duplicated index value: when 'start' is duplicated, start++ until no duplicates. when i is duplicated, continue in for loop and get to end of last duplicate and use that as i. O(n) * O(n) -> O(n^2) */ // Simplified solution class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums);// O(nlogn) int n = nums.length; for (int i = 0; i < n - 2; i++) { // check lo/hi after i if (i > 0 && nums[i] == nums[i - 1]) continue; // check duplicate int lo = i + 1, hi = n - 1; while (lo < hi) { int sum = nums[i] + nums[lo] + nums[hi]; if (sum == 0) { result.add(Arrays.asList(nums[i], nums[lo], nums[hi])); while (lo < hi && nums[lo] == nums[lo + 1]) lo++; while (lo < hi && nums[hi] == nums[hi - 1]) hi--; lo++; hi--; } else if (sum < 0) { lo++; } else { hi--; } } } return result; } } /* Thoughts: use HashMap with 2Sum */ //With HashMap 2Sum public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) { ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>(); if (numbers == null && numbers.length <= 2) {// Length at least >= 3 return rst; } Arrays.sort(numbers);//Sort in order to handle duplicates for (int i = numbers.length - 1; i >= 2; i--) {// i >=2 because at least 3 element in result; starting from end, ensures non-descending order if (i < numbers.length - 1 && numbers[i] == numbers[i + 1]) { continue;//The case of numbers[i + 1]: should have already covered all possibilities of the case numbers[i], so safe to skip } ArrayList<ArrayList<Integer>> twoSum = calTwoSum(numbers, i - 1, 0 - numbers[i]);//Pick the 3rd element numbers[i] for (int j = 0; j < twoSum.size(); j++) {//Find two sum of rest-front elements. Cross add them with numbers[i] twoSum.get(j).add(numbers[i]); } rst.addAll(twoSum); } return rst; } //Two Sum. Multiple answer, with HashMap public ArrayList<ArrayList<Integer>> calTwoSum(int[] num, int end, int target) { ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> match; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i <= end; i++) { if (map.containsKey(num[i])) { match = new ArrayList<Integer>(); match.add(num[map.get(num[i])]); match.add(num[i]); if (!rst.contains(match)) { rst.add(new ArrayList<Integer>(match)); } } else { map.put(target - num[i], i); } //Skip duplicate if (i < end && num[i] == num[i + 1]) { continue; } } return rst; } } ```
awangdev/leet-code
Java/15. 3Sum.java
409
package org.ansj.domain; import org.ansj.library.NatureLibrary; import java.io.Serializable; /** * 一个词里面会有一些词性 * * @author ansj */ public class TermNature implements Serializable{ /** * */ private static final long serialVersionUID = 5538058744208591381L; /** * 系统内置的几个 */ public static final TermNature M = new TermNature("m", 1); public static final TermNature EN = new TermNature("en", 1); public static final TermNature BEGIN = new TermNature("始##始", 1); public static final TermNature END = new TermNature("末##末", 1); public static final TermNature USER_DEFINE = new TermNature("userDefine", 1); public static final TermNature NR = new TermNature("nr", 1); public static final TermNature NT = new TermNature("nt", 1); public static final TermNature NS = new TermNature("ns", 1); public static final TermNature NW = new TermNature("nw", 1); public static final TermNature NRF = new TermNature("nrf", 1); public static final TermNature NULL = new TermNature("null", 1); public Nature nature; public int frequency; public TermNature(String natureStr, int frequency) { this.nature = NatureLibrary.getNature(natureStr); this.frequency = frequency; } @Override public String toString() { return nature.natureStr + "/" + frequency; } }
NLPchina/ansj_seg
src/main/java/org/ansj/domain/TermNature.java
410
package me.zhyd.oauth.utils; import me.zhyd.oauth.cache.AuthStateCache; import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthDefaultSource; import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.enums.AuthResponseStatus; import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.model.AuthCallback; /** * 授权配置类的校验器 * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @since 1.6.1-beta */ public class AuthChecker { /** * 是否支持第三方登录 * * @param config config * @param source source * @return true or false * @since 1.6.1-beta */ public static boolean isSupportedAuth(AuthConfig config, AuthSource source) { boolean isSupported = StringUtils.isNotEmpty(config.getClientId()) && StringUtils.isNotEmpty(config.getClientSecret()); if (isSupported && AuthDefaultSource.STACK_OVERFLOW == source) { isSupported = StringUtils.isNotEmpty(config.getStackOverflowKey()); } if (isSupported && AuthDefaultSource.WECHAT_ENTERPRISE == source) { isSupported = StringUtils.isNotEmpty(config.getAgentId()); } if (isSupported && (AuthDefaultSource.CODING == source || AuthDefaultSource.OKTA == source)) { isSupported = StringUtils.isNotEmpty(config.getDomainPrefix()); } if (isSupported && AuthDefaultSource.XMLY == source) { isSupported = StringUtils.isNotEmpty(config.getDeviceId()) && null != config.getClientOsType(); if (isSupported) { isSupported = config.getClientOsType() == 3 || StringUtils.isNotEmpty(config.getPackId()); } } return isSupported; } /** * 检查配置合法性。针对部分平台, 对redirect uri有特定要求。一般来说redirect uri都是http://,而对于facebook平台, redirect uri 必须是https的链接 * * @param config config * @param source source * @since 1.6.1-beta */ public static void checkConfig(AuthConfig config, AuthSource source) { String redirectUri = config.getRedirectUri(); if (config.isIgnoreCheckRedirectUri()) { return; } if (StringUtils.isEmpty(redirectUri)) { throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source); } if (!GlobalAuthUtils.isHttpProtocol(redirectUri) && !GlobalAuthUtils.isHttpsProtocol(redirectUri)) { throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source); } // facebook的回调地址必须为https的链接 if (AuthDefaultSource.FACEBOOK == source && !GlobalAuthUtils.isHttpsProtocol(redirectUri)) { // Facebook's redirect uri must use the HTTPS protocol throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source); } // 微软的回调地址必须为https的链接或者localhost,不允许使用http if (AuthDefaultSource.MICROSOFT == source && !GlobalAuthUtils.isHttpsProtocolOrLocalHost(redirectUri)) { // Microsoft's redirect uri must use the HTTPS or localhost throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source); } // 微软中国的回调地址必须为https的链接或者localhost,不允许使用http if (AuthDefaultSource.MICROSOFT_CN == source && !GlobalAuthUtils.isHttpsProtocolOrLocalHost(redirectUri)) { // Microsoft's redirect uri must use the HTTPS or localhost throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source); } } /** * 校验回调传回的code * <p> * {@code v1.10.0}版本中改为传入{@code source}和{@code callback},对于不同平台使用不同参数接受code的情况统一做处理 * * @param source 当前授权平台 * @param callback 从第三方授权回调回来时传入的参数集合 * @since 1.8.0 */ public static void checkCode(AuthSource source, AuthCallback callback) { // 推特平台不支持回调 code 和 state if (source == AuthDefaultSource.TWITTER) { return; } String code = callback.getCode(); if (source == AuthDefaultSource.HUAWEI) { code = callback.getAuthorization_code(); } if (StringUtils.isEmpty(code)) { throw new AuthException(AuthResponseStatus.ILLEGAL_CODE, source); } } /** * 校验回调传回的{@code state},为空或者不存在 * <p> * {@code state}不存在的情况只有两种: * 1. {@code state}已使用,被正常清除 * 2. {@code state}为前端伪造,本身就不存在 * * @param state {@code state}一定不为空 * @param source {@code source}当前授权平台 * @param authStateCache {@code authStateCache} state缓存实现 */ public static void checkState(String state, AuthSource source, AuthStateCache authStateCache) { // 推特平台不支持回调 code 和 state if (source == AuthDefaultSource.TWITTER) { return; } if (StringUtils.isEmpty(state) || !authStateCache.containsKey(state)) { throw new AuthException(AuthResponseStatus.ILLEGAL_STATUS, source); } } }
justauth/JustAuth
src/main/java/me/zhyd/oauth/utils/AuthChecker.java
411
package cc.mrbird.batch.job; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.JobStepBuilder; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; /** * @author MrBird */ @Component public class NestedJobDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private JobLauncher jobLauncher; @Autowired private JobRepository jobRepository; @Autowired private PlatformTransactionManager platformTransactionManager; // 父任务 @Bean public Job parentJob() { return jobBuilderFactory.get("parentJob") .start(childJobOneStep()) .next(childJobTwoStep()) .build(); } // 将任务转换为特殊的步骤 private Step childJobOneStep() { return new JobStepBuilder(new StepBuilder("childJobOneStep")) .job(childJobOne()) .launcher(jobLauncher) .repository(jobRepository) .transactionManager(platformTransactionManager) .build(); } // 将任务转换为特殊的步骤 private Step childJobTwoStep() { return new JobStepBuilder(new StepBuilder("childJobTwoStep")) .job(childJobTwo()) .launcher(jobLauncher) .repository(jobRepository) .transactionManager(platformTransactionManager) .build(); } // 子任务一 private Job childJobOne() { return jobBuilderFactory.get("childJobOne") .start( stepBuilderFactory.get("childJobOneStep") .tasklet((stepContribution, chunkContext) -> { System.out.println("子任务一执行步骤。。。"); return RepeatStatus.FINISHED; }).build() ).build(); } // 子任务二 private Job childJobTwo() { return jobBuilderFactory.get("childJobTwo") .start( stepBuilderFactory.get("childJobTwoStep") .tasklet((stepContribution, chunkContext) -> { System.out.println("子任务二执行步骤。。。"); return RepeatStatus.FINISHED; }).build() ).build(); } }
wuyouzhuguli/SpringAll
67.spring-batch-start/src/main/java/cc/mrbird/batch/job/NestedJobDemo.java
412
package org.jeecg.common.aspect; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.Feature; import com.baomidou.mybatisplus.core.metadata.IPage; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.jeecg.common.api.CommonAPI; import org.jeecg.common.api.vo.Result; import org.jeecg.common.aspect.annotation.Dict; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.system.vo.DictModel; import org.jeecg.common.util.oConvertUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * @Description: 字典aop类 * @Author: dangzhenghui * @Date: 2019-3-17 21:50 * @Version: 1.0 */ @Aspect @Component @Slf4j public class DictAspect { @Lazy @Autowired private CommonAPI commonApi; @Autowired public RedisTemplate redisTemplate; @Autowired private ObjectMapper objectMapper; private static final String JAVA_UTIL_DATE = "java.util.Date"; /** * 定义切点Pointcut */ @Pointcut("execution(public * org.jeecg.modules..*.*Controller.*(..)) || @annotation(org.jeecg.common.aspect.annotation.AutoDict)") public void excudeService() { } @Around("excudeService()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { long time1=System.currentTimeMillis(); Object result = pjp.proceed(); long time2=System.currentTimeMillis(); log.debug("获取JSON数据 耗时:"+(time2-time1)+"ms"); long start=System.currentTimeMillis(); result=this.parseDictText(result); long end=System.currentTimeMillis(); log.debug("注入字典到JSON数据 耗时"+(end-start)+"ms"); return result; } /** * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入 * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ,table字典 code table text配合使用与原来jeecg的用法相同 * 示例为SysUser 字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dictText形式返回到前端 * 例输入当前返回值的就会多出一个sex_dictText字段 * { * sex:1, * sex_dictText:"男" * } * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了 * customRender:function (text) { * if(text==1){ * return "男"; * }else if(text==2){ * return "女"; * }else{ * return text; * } * } * 目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用 * @param result */ private Object parseDictText(Object result) { if (result instanceof Result) { if (((Result) result).getResult() instanceof IPage) { List<JSONObject> items = new ArrayList<>(); //step.1 筛选出加了 Dict 注解的字段列表 List<Field> dictFieldList = new ArrayList<>(); // 字典数据列表, key = 字典code,value=数据列表 Map<String, List<String>> dataListMap = new HashMap<>(5); //取出结果集 List<Object> records=((IPage) ((Result) result).getResult()).getRecords(); //update-begin--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回----- Boolean hasDict= checkHasDict(records); if(!hasDict){ return result; } log.debug(" __ 进入字典翻译切面 DictAspect —— " ); //update-end--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回----- for (Object record : records) { String json="{}"; try { //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错----- //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat json = objectMapper.writeValueAsString(record); //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错----- } catch (JsonProcessingException e) { log.error("json解析失败"+e.getMessage(),e); } //update-begin--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 ----- JSONObject item = JSONObject.parseObject(json, Feature.OrderedField); //update-end--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 ----- //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------ //for (Field field : record.getClass().getDeclaredFields()) { // 遍历所有字段,把字典Code取出来,放到 map 里 for (Field field : oConvertUtils.getAllFields(record)) { String value = item.getString(field.getName()); if (oConvertUtils.isEmpty(value)) { continue; } //update-end--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------ if (field.getAnnotation(Dict.class) != null) { if (!dictFieldList.contains(field)) { dictFieldList.add(field); } String code = field.getAnnotation(Dict.class).dicCode(); String text = field.getAnnotation(Dict.class).dicText(); String table = field.getAnnotation(Dict.class).dictTable(); //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ String dataSource = field.getAnnotation(Dict.class).ds(); //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ List<String> dataList; String dictCode = code; if (!StringUtils.isEmpty(table)) { //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ dictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource); //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ } dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>()); this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(","))); } //date类型默认转换string格式化日期 //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错----- //if (JAVA_UTIL_DATE.equals(field.getType().getName())&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){ //SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName())))); //} //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错----- } items.add(item); } //step.2 调用翻译方法,一次性翻译 Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap); //step.3 将翻译结果填充到返回结果里 for (JSONObject record : items) { for (Field field : dictFieldList) { String code = field.getAnnotation(Dict.class).dicCode(); String text = field.getAnnotation(Dict.class).dicText(); String table = field.getAnnotation(Dict.class).dictTable(); //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ // 自定义的字典表数据源 String dataSource = field.getAnnotation(Dict.class).ds(); //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ String fieldDictCode = code; if (!StringUtils.isEmpty(table)) { //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ fieldDictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource); //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ } String value = record.getString(field.getName()); if (oConvertUtils.isNotEmpty(value)) { List<DictModel> dictModels = translText.get(fieldDictCode); if(dictModels==null || dictModels.size()==0){ continue; } String textValue = this.translDictText(dictModels, value); log.debug(" 字典Val : " + textValue); log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue); // TODO-sun 测试输出,待删 log.debug(" ---- dictCode: " + fieldDictCode); log.debug(" ---- value: " + value); log.debug(" ----- text: " + textValue); log.debug(" ---- dictModels: " + JSON.toJSONString(dictModels)); record.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue); } } } ((IPage) ((Result) result).getResult()).setRecords(items); } } return result; } /** * list 去重添加 */ private void listAddAllDeduplicate(List<String> dataList, List<String> addList) { // 筛选出dataList中没有的数据 List<String> filterList = addList.stream().filter(i -> !dataList.contains(i)).collect(Collectors.toList()); dataList.addAll(filterList); } /** * 一次性把所有的字典都翻译了 * 1. 所有的普通数据字典的所有数据只执行一次SQL * 2. 表字典相同的所有数据只执行一次SQL * @param dataListMap * @return */ private Map<String, List<DictModel>> translateAllDict(Map<String, List<String>> dataListMap) { // 翻译后的字典文本,key=dictCode Map<String, List<DictModel>> translText = new HashMap<>(5); // 需要翻译的数据(有些可以从redis缓存中获取,就不走数据库查询) List<String> needTranslData = new ArrayList<>(); //step.1 先通过redis中获取缓存字典数据 for (String dictCode : dataListMap.keySet()) { List<String> dataList = dataListMap.get(dictCode); if (dataList.size() == 0) { continue; } // 表字典需要翻译的数据 List<String> needTranslDataTable = new ArrayList<>(); for (String s : dataList) { String data = s.trim(); if (data.length() == 0) { continue; //跳过循环 } if (dictCode.contains(",")) { String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, data); if (redisTemplate.hasKey(keyString)) { try { String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString)); List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>()); list.add(new DictModel(data, text)); } catch (Exception e) { log.warn(e.getMessage()); } } else if (!needTranslDataTable.contains(data)) { // 去重添加 needTranslDataTable.add(data); } } else { String keyString = String.format("sys:cache:dict::%s:%s", dictCode, data); if (redisTemplate.hasKey(keyString)) { try { String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString)); List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>()); list.add(new DictModel(data, text)); } catch (Exception e) { log.warn(e.getMessage()); } } else if (!needTranslData.contains(data)) { // 去重添加 needTranslData.add(data); } } } //step.2 调用数据库翻译表字典 if (needTranslDataTable.size() > 0) { String[] arr = dictCode.split(","); String table = arr[0], text = arr[1], code = arr[2]; String values = String.join(",", needTranslDataTable); //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ // 自定义的数据源 String dataSource = null; if (arr.length > 3) { dataSource = arr[3]; } //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ log.debug("translateDictFromTableByKeys.dictCode:" + dictCode); log.debug("translateDictFromTableByKeys.values:" + values); //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ //update-begin---author:wangshuai---date:2024-01-09---for:微服务下为空报错没有参数需要传递空字符串--- if(null == dataSource){ dataSource = ""; } //update-end---author:wangshuai---date:2024-01-09---for:微服务下为空报错没有参数需要传递空字符串--- List<DictModel> texts = commonApi.translateDictFromTableByKeys(table, text, code, values, dataSource); //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------ log.debug("translateDictFromTableByKeys.result:" + texts); List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>()); list.addAll(texts); // 做 redis 缓存 for (DictModel dict : texts) { String redisKey = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, dict.getValue()); try { // update-begin-author:taoyan date:20211012 for: 字典表翻译注解缓存未更新 issues/3061 // 保留5分钟 redisTemplate.opsForValue().set(redisKey, dict.getText(), 300, TimeUnit.SECONDS); // update-end-author:taoyan date:20211012 for: 字典表翻译注解缓存未更新 issues/3061 } catch (Exception e) { log.warn(e.getMessage(), e); } } } } //step.3 调用数据库进行翻译普通字典 if (needTranslData.size() > 0) { List<String> dictCodeList = Arrays.asList(dataListMap.keySet().toArray(new String[]{})); // 将不包含逗号的字典code筛选出来,因为带逗号的是表字典,而不是普通的数据字典 List<String> filterDictCodes = dictCodeList.stream().filter(key -> !key.contains(",")).collect(Collectors.toList()); String dictCodes = String.join(",", filterDictCodes); String values = String.join(",", needTranslData); log.debug("translateManyDict.dictCodes:" + dictCodes); log.debug("translateManyDict.values:" + values); Map<String, List<DictModel>> manyDict = commonApi.translateManyDict(dictCodes, values); log.debug("translateManyDict.result:" + manyDict); for (String dictCode : manyDict.keySet()) { List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>()); List<DictModel> newList = manyDict.get(dictCode); list.addAll(newList); // 做 redis 缓存 for (DictModel dict : newList) { String redisKey = String.format("sys:cache:dict::%s:%s", dictCode, dict.getValue()); try { redisTemplate.opsForValue().set(redisKey, dict.getText()); } catch (Exception e) { log.warn(e.getMessage(), e); } } } } return translText; } /** * 字典值替换文本 * * @param dictModels * @param values * @return */ private String translDictText(List<DictModel> dictModels, String values) { List<String> result = new ArrayList<>(); // 允许多个逗号分隔,允许传数组对象 String[] splitVal = values.split(","); for (String val : splitVal) { String dictText = val; for (DictModel dict : dictModels) { if (val.equals(dict.getValue())) { dictText = dict.getText(); break; } } result.add(dictText); } return String.join(",", result); } /** * 翻译字典文本 * @param code * @param text * @param table * @param key * @return */ @Deprecated private String translateDictValue(String code, String text, String table, String key) { if(oConvertUtils.isEmpty(key)) { return null; } StringBuffer textValue=new StringBuffer(); String[] keys = key.split(","); for (String k : keys) { String tmpValue = null; log.debug(" 字典 key : "+ k); if (k.trim().length() == 0) { continue; //跳过循环 } //update-begin--Author:scott -- Date:20210531 ----for: !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题----- if (!StringUtils.isEmpty(table)){ log.debug("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code); String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s,%s,%s]",table,text,code,k.trim()); if (redisTemplate.hasKey(keyString)){ try { tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString)); } catch (Exception e) { log.warn(e.getMessage()); } }else { tmpValue= commonApi.translateDictFromTable(table,text,code,k.trim()); } }else { String keyString = String.format("sys:cache:dict::%s:%s",code,k.trim()); if (redisTemplate.hasKey(keyString)){ try { tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString)); } catch (Exception e) { log.warn(e.getMessage()); } }else { tmpValue = commonApi.translateDict(code, k.trim()); } } //update-end--Author:scott -- Date:20210531 ----for: !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题----- if (tmpValue != null) { if (!"".equals(textValue.toString())) { textValue.append(","); } textValue.append(tmpValue); } } return textValue.toString(); } /** * 检测返回结果集中是否包含Dict注解 * @param records * @return */ private Boolean checkHasDict(List<Object> records){ if(oConvertUtils.isNotEmpty(records) && records.size()>0){ for (Field field : oConvertUtils.getAllFields(records.get(0))) { if (oConvertUtils.isNotEmpty(field.getAnnotation(Dict.class))) { return true; } } } return false; } }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/common/aspect/DictAspect.java
414
package com.dianping.cat.context.context; import com.dianping.cat.CatConstants; /** * 1、继承、扩展CatConstants常量类,添加一些常用的Type * 2、添加header常量,用于http协议传输rootId、parentId、childId三个context属性 * @author soar * @date 2019-01-10 */ public class CatConstantsExt extends CatConstants { /** * Type 常量 */ public static final String Type_URL_METHOD = "URL.method"; public static final String Type_URL_CLIENT = "URL.client"; public static final String Type_URL_FORWORD = "URL.forword"; public static final String Type_Service = "Service"; public static final String Type_Service_METHOD= "Service.method"; public static final String Type_Service_CLIENT = "Service.client"; public static final String Type_SQL = "SQL"; public static final String Type_SQL_METHOD= "SQL.method"; public static final String Type_SQL_CLIENT = "SQL.client"; public static final String Type_Cache = "Cache"; public static final String Type_Cache_METHOD= "Cache.method"; public static final String Type_Cache_CLIENT = "Cache.client"; public static final String Type_Call = "Call"; public static final String Type_Call_METHOD= "Call.method"; public static final String Type_Call_CLIENT = "Call.client"; /** * http header 常量 */ public static final String CAT_HTTP_HEADER_ROOT_MESSAGE_ID = "X-CAT-ROOT-MESSAGE-ID"; public static final String CAT_HTTP_HEADER_PARENT_MESSAGE_ID = "X-CAT-ROOT-PARENT-ID"; public static final String CAT_HTTP_HEADER_CHILD_MESSAGE_ID = "X-CAT-ROOT-CHILD-ID"; }
dianping/cat
integration/context/CatConstantsExt.java
416
/* * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.fastjson.parser; import java.io.CharArrayReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.math.MathContext; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.util.IOUtils; //这个类,为了性能优化做了很多特别处理,一切都是为了性能!!! /** * @author wenshao[[email protected]] */ public final class JSONReaderScanner extends JSONLexerBase { private final static ThreadLocal<char[]> BUF_LOCAL = new ThreadLocal<char[]>(); private Reader reader; private char[] buf; private int bufLength; public JSONReaderScanner(String input){ this(input, JSON.DEFAULT_PARSER_FEATURE); } public JSONReaderScanner(String input, int features){ this(new StringReader(input), features); } public JSONReaderScanner(char[] input, int inputLength){ this(input, inputLength, JSON.DEFAULT_PARSER_FEATURE); } public JSONReaderScanner(Reader reader){ this(reader, JSON.DEFAULT_PARSER_FEATURE); } public JSONReaderScanner(Reader reader, int features){ super(features); this.reader = reader; buf = BUF_LOCAL.get(); if (buf != null) { BUF_LOCAL.set(null); } if (buf == null) { buf = new char[1024 * 16]; } try { bufLength = reader.read(buf); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } bp = -1; next(); if (ch == 65279) { // utf8 bom next(); } } public JSONReaderScanner(char[] input, int inputLength, int features){ this(new CharArrayReader(input, 0, inputLength), features); } public final char charAt(int index) { if (index >= bufLength) { if (bufLength == -1) { if (index < sp) { return buf[index]; } return EOI; } if (bp == 0) { char[] buf = new char[(this.buf.length * 3) / 2]; System.arraycopy(this.buf, bp, buf, 0, bufLength); int rest = buf.length - bufLength; try { int len = reader.read(buf, bufLength, rest); bufLength += len; this.buf = buf; } catch (IOException e) { throw new JSONException(e.getMessage(), e); } } else { int rest = bufLength - bp; if (rest > 0) { System.arraycopy(buf, bp, buf, 0, rest); } try { bufLength = reader.read(buf, rest, buf.length - rest); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } if (bufLength == 0) { throw new JSONException("illegal state, textLength is zero"); } if (bufLength == -1) { return EOI; } bufLength += rest; index -= bp; np -= bp; bp = 0; } } return buf[index]; } public final int indexOf(char ch, int startIndex) { int offset = startIndex - bp; for (;; ++offset) { final int index = bp + offset; char chLoal = charAt(index); if (ch == chLoal) { return offset + bp; } if (chLoal == EOI) { return -1; } } } public final String addSymbol(int offset, int len, int hash, final SymbolTable symbolTable) { return symbolTable.addSymbol(buf, offset, len, hash); } public final char next() { int index = ++bp; if (index >= bufLength) { if (bufLength == -1) { return EOI; } if (sp > 0) { int offset; offset = bufLength - sp; if (ch == '"' && offset > 0) { offset--; } System.arraycopy(buf, offset, buf, 0, sp); } np = -1; index = bp = sp; try { int startPos = bp; int readLength = buf.length - startPos; if (readLength == 0) { char[] newBuf = new char[buf.length * 2]; System.arraycopy(buf, 0, newBuf, 0, buf.length); buf = newBuf; readLength = buf.length - startPos; } bufLength = reader.read(buf, bp, readLength); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } if (bufLength == 0) { throw new JSONException("illegal stat, textLength is zero"); } if (bufLength == -1) { return ch = EOI; } bufLength += bp; } return ch = buf[index]; } protected final void copyTo(int offset, int count, char[] dest) { System.arraycopy(buf, offset, dest, 0, count); } public final boolean charArrayCompare(char[] chars) { for (int i = 0; i < chars.length; ++i) { if (charAt(bp + i) != chars[i]) { return false; } } return true; } public byte[] bytesValue() { if (token == JSONToken.HEX) { throw new JSONException("TODO"); } return IOUtils.decodeBase64(buf, np + 1, sp); } protected final void arrayCopy(int srcPos, char[] dest, int destPos, int length) { System.arraycopy(buf, srcPos, dest, destPos, length); } /** * The value of a literal token, recorded as a string. For integers, leading 0x and 'l' suffixes are suppressed. */ public final String stringVal() { if (!hasSpecial) { int offset = np + 1; if (offset < 0) { throw new IllegalStateException(); } if (offset > buf.length - sp) { throw new IllegalStateException(); } return new String(buf, offset, sp); // return text.substring(np + 1, np + 1 + sp); } else { return new String(sbuf, 0, sp); } } public final String subString(int offset, int count) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } return new String(buf, offset, count); // return text.substring(offset, offset + count); } public final char[] sub_chars(int offset, int count) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } if (offset == 0) { return buf; } char[] chars = new char[count]; System.arraycopy(buf, offset, chars, 0, count); return chars; } public final String numberString() { int offset = np; if (offset == -1) { offset = 0; } char chLocal = charAt(offset + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } String value = new String(buf, offset, sp); return value; } public final BigDecimal decimalValue() { int offset = np; if (offset == -1) { offset = 0; } char chLocal = charAt(offset + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } if (sp > 65535) { throw new JSONException("decimal overflow"); } return new BigDecimal(buf, offset, sp, MathContext.UNLIMITED); } public void close() { super.close(); if (buf.length <= 1024 * 64) { BUF_LOCAL.set(buf); } this.buf = null; IOUtils.close(reader); } @Override public boolean isEOF() { return bufLength == -1 || bp == buf.length || ch == EOI && bp + 1 >= buf.length; } public final boolean isBlankInput() { for (int i = 0;; ++i) { char chLocal = buf[i]; if (chLocal == EOI) { token = JSONToken.EOF; break; } if (!isWhitespace(chLocal)) { return false; } } return true; } }
alibaba/fastjson
src/main/java/com/alibaba/fastjson/parser/JSONReaderScanner.java
417
package cn.hutool.core.date.chinese; /** * 农历月份表示 * * @author looly * @since 5.4.1 */ public class ChineseMonth { private static final String[] MONTH_NAME = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"}; private static final String[] MONTH_NAME_TRADITIONAL = {"正", "二", "三", "四", "五", "六", "七", "八", "九", "寒", "冬", "腊"}; /** * 当前农历月份是否为闰月 * * @param year 农历年 * @param month 农历月 * @return 是否为闰月 * @since 5.4.2 */ public static boolean isLeapMonth(int year, int month) { return month == LunarInfo.leapMonth(year); } /** * 获得农历月称呼<br> * 当为传统表示时,表示为二月,腊月,或者润正月等 * 当为非传统表示时,二月,十二月,或者润一月等 * * @param isLeapMonth 是否闰月 * @param month 月份,从1开始,如果是闰月,应传入需要显示的月份 * @param isTraditional 是否传统表示,例如一月传统表示为正月 * @return 返回农历月份称呼 */ public static String getChineseMonthName(boolean isLeapMonth, int month, boolean isTraditional) { return (isLeapMonth ? "闰" : "") + (isTraditional ? MONTH_NAME_TRADITIONAL : MONTH_NAME)[month - 1] + "月"; } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/date/chinese/ChineseMonth.java
420
package com.xkcoding.task.job; import cn.hutool.core.date.DateUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; /** * <p> * 定时任务 * </p> * * @author yangkai.shen * @date Created in 2018-11-22 19:09 */ @Component @Slf4j public class TaskJob { /** * 按照标准时间来算,每隔 10s 执行一次 */ @Scheduled(cron = "0/10 * * * * ?") public void job1() { log.info("【job1】开始执行:{}", DateUtil.formatDateTime(new Date())); } /** * 从启动时间开始,间隔 2s 执行 * 固定间隔时间 */ @Scheduled(fixedRate = 2000) public void job2() { log.info("【job2】开始执行:{}", DateUtil.formatDateTime(new Date())); } /** * 从启动时间开始,延迟 5s 后间隔 4s 执行 * 固定等待时间 */ @Scheduled(fixedDelay = 4000, initialDelay = 5000) public void job3() { log.info("【job3】开始执行:{}", DateUtil.formatDateTime(new Date())); } }
xkcoding/spring-boot-demo
demo-task/src/main/java/com/xkcoding/task/job/TaskJob.java
422
E tags: String, Lint 看StringA是不是包括所有 StringB的字符. Anagram #### Basic Implementation - 比较一下大小, null. - 然后用int[]来count chars from A, count[x]++. 再对照chars in B, count[x]-- - 如果 count[c] < 0, 就 false. - O(n) ``` /* Compare two strings A and B, determine whether A contains all of the characters in B. The characters in string A and B are all Upper Case letters. Example For A = "ABCD", B = "ABC", return true. For A = "ABCD" B = "AABC", return false. Tags Expand Basic Implementation String LintCode Copyright */ /* Thoughts: Loop over A, B and ++/-- chars count arr should have no negative results */ public class Solution { public boolean compareStrings(String A, String B) { if (A == null || B == null || A.length() < B.length()) { return false; } int[] count = new int[26]; for (char c : A.toCharArray()) { count[c - 'A']++; } for (char c : B.toCharArray()) { count[c - 'A']--; if (count[c - 'A'] < 0) { return false; } } return true; } } /* Previous notes Thinking process: Count the number of occurance for StringA. Count the number of occurance for StringB. Check if all of StringB's char# <= StringA's char# at each index. */ public class Solution { public boolean compareStrings(String A, String B) { if (A == null || B == null || A.length() < B.length()) { return false; } int[] countA = new int[26]; int[] countB = new int[26]; for (int i = 0; i < A.length(); i++) { countA[A.charAt(i) - 'A']++; } for (int i = 0; i < B.length(); i++) { countB[B.charAt(i) - 'A']++; if (countB[B.charAt(i) - 'A'] > countA[B.charAt(i) - 'A']) { return false; } } return true; } } ```
awangdev/leet-code
Java/[lint]. Compare Strings.java