file_id
int64 1
66.7k
| content
stringlengths 14
343k
| repo
stringlengths 6
92
| path
stringlengths 5
169
|
---|---|---|---|
425 | package cn.hutool.core.lang;
import cn.hutool.core.lang.func.Func0;
import cn.hutool.core.lang.func.VoidFunc0;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* 复制jdk16中的Optional,以及自己进行了一点调整和新增,比jdk8中的Optional多了几个实用的函数<br>
* 详细见:<a href="https://gitee.com/dromara/hutool/pulls/426">https://gitee.com/dromara/hutool/pulls/426</a>
*
* @param <T> 包裹里元素的类型
* @author VampireAchao
* @see java.util.Optional
*/
public class Opt<T> {
/**
* 一个空的{@code Opt}
*/
private static final Opt<?> EMPTY = new Opt<>(null);
/**
* 返回一个空的{@code Opt}
*
* @param <T> 包裹里元素的类型
* @return Opt
*/
@SuppressWarnings("unchecked")
public static <T> Opt<T> empty() {
return (Opt<T>) EMPTY;
}
/**
* 返回一个包裹里元素不可能为空的{@code Opt}
*
* @param value 包裹里的元素
* @param <T> 包裹里元素的类型
* @return 一个包裹里元素不可能为空的 {@code Opt}
* @throws NullPointerException 如果传入的元素为空,抛出 {@code NPE}
*/
public static <T> Opt<T> of(T value) {
return new Opt<>(Objects.requireNonNull(value));
}
/**
* 返回一个包裹里元素可能为空的{@code Opt}
*
* @param value 传入需要包裹的元素
* @param <T> 包裹里元素的类型
* @return 一个包裹里元素可能为空的 {@code Opt}
*/
public static <T> Opt<T> ofNullable(T value) {
return value == null ? empty()
: new Opt<>(value);
}
/**
* 返回一个包裹里元素可能为空的{@code Opt},额外判断了空字符串的情况
*
* @param value 传入需要包裹的元素
* @param <T> 包裹里元素的类型
* @return 一个包裹里元素可能为空,或者为空字符串的 {@code Opt}
*/
public static <T> Opt<T> ofBlankAble(T value) {
return StrUtil.isBlankIfStr(value) ? empty() : new Opt<>(value);
}
/**
* 返回一个包裹里{@code List}集合可能为空的{@code Opt},额外判断了集合内元素为空的情况
*
* @param <T> 包裹里元素的类型
* @param <R> 集合值类型
* @param value 传入需要包裹的元素,支持CharSequence、Map、Iterable、Iterator、Array类型
* @return 一个包裹里元素可能为空的 {@code Opt}
* @since 5.7.17
*/
public static <T, R extends Collection<T>> Opt<R> ofEmptyAble(R value) {
return ObjectUtil.isEmpty(value) ? empty() : new Opt<>(value);
}
/**
* @param supplier 操作
* @param <T> 类型
* @return 操作执行后的值
*/
public static <T> Opt<T> ofTry(Func0<T> supplier) {
try {
return Opt.ofNullable(supplier.call());
} catch (Exception e) {
final Opt<T> empty = new Opt<>(null);
empty.exception = e;
return empty;
}
}
/**
* 包裹里实际的元素
*/
private final T value;
private Exception exception;
/**
* {@code Opt}的构造函数
*
* @param value 包裹里的元素
*/
private Opt(T value) {
this.value = value;
}
/**
* 返回包裹里的元素,取不到则为{@code null},注意!!!此处和{@link java.util.Optional#get()}不同的一点是本方法并不会抛出{@code NoSuchElementException}
* 如果元素为空,则返回{@code null},如果需要一个绝对不能为{@code null}的值,则使用{@link #orElseThrow()}
*
* <p>
* 如果需要一个绝对不能为 {@code null}的值,则使用{@link #orElseThrow()}
* 做此处修改的原因是,有时候我们确实需要返回一个null给前端,并且这样的时候并不少见
* 而使用 {@code .orElse(null)}需要写整整12个字符,用{@code .get()}就只需要6个啦
*
* @return 包裹里的元素,有可能为{@code null}
*/
public T get() {
return this.value;
}
/**
* 判断包裹里元素的值是否不存在,不存在为 {@code true},否则为{@code false}
*
* @return 包裹里元素的值不存在 则为 {@code true},否则为{@code false}
* @since 11 这是jdk11{@link java.util.Optional}中的新函数
*/
public boolean isEmpty() {
return value == null;
}
/**
* 获取异常<br>
* 当调用 {@link #ofTry(Func0)}时,异常信息不会抛出,而是保存,调用此方法获取抛出的异常
*
* @return 异常
* @since 5.7.17
*/
public Exception getException() {
return this.exception;
}
/**
* 是否失败<br>
* 当调用 {@link #ofTry(Func0)}时,抛出异常则表示失败
*
* @return 是否失败
* @since 5.7.17
*/
public boolean isFail() {
return null != this.exception;
}
/**
* 判断包裹里元素的值是否存在,存在为 {@code true},否则为{@code false}
*
* @return 包裹里元素的值存在为 {@code true},否则为{@code false}
*/
public boolean isPresent() {
return value != null;
}
/**
* 如果包裹里的值存在,就执行传入的操作({@link Consumer#accept})
*
* <p> 例如如果值存在就打印结果
* <pre>{@code
* Opt.ofNullable("Hello Hutool!").ifPresent(Console::log);
* }</pre>
*
* @param action 你想要执行的操作
* @return this
* @throws NullPointerException 如果包裹里的值存在,但你传入的操作为{@code null}时抛出
*/
public Opt<T> ifPresent(Consumer<? super T> action) {
if (isPresent()) {
action.accept(value);
}
return this;
}
/**
* 如果包裹里的值存在,就执行传入的值存在时的操作({@link Consumer#accept})
* 否则执行传入的值不存在时的操作({@link VoidFunc0}中的{@link VoidFunc0#call()})
*
* <p>
* 例如值存在就打印对应的值,不存在则用{@code Console.error}打印另一句字符串
* <pre>{@code
* Opt.ofNullable("Hello Hutool!").ifPresentOrElse(Console::log, () -> Console.error("Ops!Something is wrong!"));
* }</pre>
*
* @param action 包裹里的值存在时的操作
* @param emptyAction 包裹里的值不存在时的操作
* @return this;
* @throws NullPointerException 如果包裹里的值存在时,执行的操作为 {@code null}, 或者包裹里的值不存在时的操作为 {@code null},则抛出{@code NPE}
*/
public Opt<T> ifPresentOrElse(Consumer<? super T> action, VoidFunc0 emptyAction) {
if (isPresent()) {
action.accept(value);
} else {
emptyAction.callWithRuntimeException();
}
return this;
}
/**
* 如果包裹里的值存在,就执行传入的值存在时的操作({@link Function#apply(Object)})支持链式调用、转换为其他类型
* 否则执行传入的值不存在时的操作({@link VoidFunc0}中的{@link VoidFunc0#call()})
*
* <p>
* 如果值存在就转换为大写,否则用{@code Console.error}打印另一句字符串
* <pre>{@code
* String hutool = Opt.ofBlankAble("hutool").mapOrElse(String::toUpperCase, () -> Console.log("yes")).mapOrElse(String::intern, () -> Console.log("Value is not present~")).get();
* }</pre>
*
* @param <U> map后新的类型
* @param mapper 包裹里的值存在时的操作
* @param emptyAction 包裹里的值不存在时的操作
* @return 新的类型的Opt
* @throws NullPointerException 如果包裹里的值存在时,执行的操作为 {@code null}, 或者包裹里的值不存在时的操作为 {@code null},则抛出{@code NPE}
*/
public <U> Opt<U> mapOrElse(Function<? super T, ? extends U> mapper, VoidFunc0 emptyAction) {
if (isPresent()) {
return ofNullable(mapper.apply(value));
} else {
emptyAction.callWithRuntimeException();
return empty();
}
}
/**
* 判断包裹里的值存在并且与给定的条件是否满足 ({@link Predicate#test}执行结果是否为true)
* 如果满足条件则返回本身
* 不满足条件或者元素本身为空时返回一个返回一个空的{@code Opt}
*
* @param predicate 给定的条件
* @return 如果满足条件则返回本身, 不满足条件或者元素本身为空时返回一个空的{@code Opt}
* @throws NullPointerException 如果给定的条件为 {@code null},抛出{@code NPE}
*/
public Opt<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (isEmpty()) {
return this;
} else {
return predicate.test(value) ? this : empty();
}
}
/**
* 如果包裹里的值存在,就执行传入的操作({@link Function#apply})并返回一个包裹了该操作返回值的{@code Opt}
* 如果不存在,返回一个空的{@code Opt}
*
* @param mapper 值存在时执行的操作
* @param <U> 操作返回值的类型
* @return 如果包裹里的值存在,就执行传入的操作({@link Function#apply})并返回一个包裹了该操作返回值的{@code Opt},
* 如果不存在,返回一个空的{@code Opt}
* @throws NullPointerException 如果给定的操作为 {@code null},抛出 {@code NPE}
*/
public <U> Opt<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (isEmpty()) {
return empty();
} else {
return Opt.ofNullable(mapper.apply(value));
}
}
/**
* 如果包裹里的值存在,就执行传入的操作({@link Function#apply})并返回该操作返回值
* 如果不存在,返回一个空的{@code Opt}
* 和 {@link Opt#map}的区别为 传入的操作返回值必须为 Opt
*
* @param mapper 值存在时执行的操作
* @param <U> 操作返回值的类型
* @return 如果包裹里的值存在,就执行传入的操作({@link Function#apply})并返回该操作返回值
* 如果不存在,返回一个空的{@code Opt}
* @throws NullPointerException 如果给定的操作为 {@code null}或者给定的操作执行结果为 {@code null},抛出 {@code NPE}
*/
public <U> Opt<U> flatMap(Function<? super T, ? extends Opt<? extends U>> mapper) {
Objects.requireNonNull(mapper);
if (isEmpty()) {
return empty();
} else {
@SuppressWarnings("unchecked")
final Opt<U> r = (Opt<U>) mapper.apply(value);
return Objects.requireNonNull(r);
}
}
/**
* 如果包裹里的值存在,就执行传入的操作({@link Function#apply})并返回该操作返回值
* 如果不存在,返回一个空的{@code Opt}
* 和 {@link Opt#map}的区别为 传入的操作返回值必须为 {@link Optional}
*
* @param mapper 值存在时执行的操作
* @param <U> 操作返回值的类型
* @return 如果包裹里的值存在,就执行传入的操作({@link Function#apply})并返回该操作返回值
* 如果不存在,返回一个空的{@code Opt}
* @throws NullPointerException 如果给定的操作为 {@code null}或者给定的操作执行结果为 {@code null},抛出 {@code NPE}
* @see Optional#flatMap(Function)
* @since 5.7.16
*/
public <U> Opt<U> flattedMap(Function<? super T, ? extends Optional<? extends U>> mapper) {
Objects.requireNonNull(mapper);
if (isEmpty()) {
return empty();
} else {
return ofNullable(mapper.apply(value).orElse(null));
}
}
/**
* 如果包裹里元素的值存在,就执行对应的操作,并返回本身
* 如果不存在,返回一个空的{@code Opt}
*
* <p>属于 {@link #ifPresent}的链式拓展
*
* @param action 值存在时执行的操作
* @return this
* @throws NullPointerException 如果值存在,并且传入的操作为 {@code null}
* @author VampireAchao
*/
public Opt<T> peek(Consumer<T> action) throws NullPointerException {
Objects.requireNonNull(action);
if (isEmpty()) {
return Opt.empty();
}
action.accept(value);
return this;
}
/**
* 如果包裹里元素的值存在,就执行对应的操作集,并返回本身
* 如果不存在,返回一个空的{@code Opt}
*
* <p>属于 {@link #ifPresent}的链式拓展
* <p>属于 {@link #peek(Consumer)}的动态拓展
*
* @param actions 值存在时执行的操作,动态参数,可传入数组,当数组为一个空数组时并不会抛出 {@code NPE}
* @return this
* @throws NullPointerException 如果值存在,并且传入的操作集中的元素为 {@code null}
* @author VampireAchao
*/
@SafeVarargs
public final Opt<T> peeks(Consumer<T>... actions) throws NullPointerException {
// 第三个参数 (opts, opt) -> null其实并不会执行到该函数式接口所以直接返回了个null
return Stream.of(actions).reduce(this, Opt<T>::peek, (opts, opt) -> null);
}
/**
* 如果包裹里元素的值存在,就返回本身,如果不存在,则使用传入的操作执行后获得的 {@code Opt}
*
* @param supplier 不存在时的操作
* @return 如果包裹里元素的值存在,就返回本身,如果不存在,则使用传入的函数执行后获得的 {@code Opt}
* @throws NullPointerException 如果传入的操作为空,或者传入的操作执行后返回值为空,则抛出 {@code NPE}
*/
public Opt<T> or(Supplier<? extends Opt<? extends T>> supplier) {
Objects.requireNonNull(supplier);
if (isPresent()) {
return this;
} else {
@SuppressWarnings("unchecked") final Opt<T> r = (Opt<T>) supplier.get();
return Objects.requireNonNull(r);
}
}
/**
* 如果包裹里元素的值存在,就返回一个包含该元素的 {@link Stream},
* 否则返回一个空元素的 {@link Stream}
*
* <p> 该方法能将 Opt 中的元素传递给 {@link Stream}
* <pre>{@code
* Stream<Opt<T>> os = ..
* Stream<T> s = os.flatMap(Opt::stream)
* }</pre>
*
* @return 返回一个包含该元素的 {@link Stream}或空的 {@link Stream}
*/
public Stream<T> stream() {
if (isEmpty()) {
return Stream.empty();
} else {
return Stream.of(value);
}
}
/**
* 如果包裹里元素的值存在,则返回该值,否则返回传入的{@code other}
*
* @param other 元素为空时返回的值,有可能为 {@code null}.
* @return 如果包裹里元素的值存在,则返回该值,否则返回传入的{@code other}
*/
public T orElse(T other) {
return isPresent() ? value : other;
}
/**
* 异常则返回另一个可选值
*
* @param other 可选值
* @return 如果未发生异常,则返回该值,否则返回传入的{@code other}
* @since 5.7.17
*/
public T exceptionOrElse(T other) {
return isFail() ? other : value;
}
/**
* 如果包裹里元素的值存在,则返回该值,否则返回传入的操作执行后的返回值
*
* @param supplier 值不存在时需要执行的操作,返回一个类型与 包裹里元素类型 相同的元素
* @return 如果包裹里元素的值存在,则返回该值,否则返回传入的操作执行后的返回值
* @throws NullPointerException 如果之不存在,并且传入的操作为空,则抛出 {@code NPE}
*/
public T orElseGet(Supplier<? extends T> supplier) {
return isPresent() ? value : supplier.get();
}
/**
* 如果包裹里的值存在,则返回该值,否则抛出 {@code NoSuchElementException}
*
* @return 返回一个不为 {@code null} 的包裹里的值
* @throws NoSuchElementException 如果包裹里的值不存在则抛出该异常
*/
public T orElseThrow() {
return orElseThrow(NoSuchElementException::new, "No value present");
}
/**
* 如果包裹里的值存在,则返回该值,否则执行传入的操作,获取异常类型的返回值并抛出
* <p>往往是一个包含无参构造器的异常 例如传入{@code IllegalStateException::new}
*
* @param <X> 异常类型
* @param exceptionSupplier 值不存在时执行的操作,返回值继承 {@link Throwable}
* @return 包裹里不能为空的值
* @throws X 如果值不存在
* @throws NullPointerException 如果值不存在并且 传入的操作为 {@code null}或者操作执行后的返回值为{@code null}
*/
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (isPresent()) {
return value;
} else {
throw exceptionSupplier.get();
}
}
/**
* 如果包裹里的值存在,则返回该值,否则执行传入的操作,获取异常类型的返回值并抛出
*
* <p>往往是一个包含 自定义消息 构造器的异常 例如
* <pre>{@code
* Opt.ofNullable(null).orElseThrow(IllegalStateException::new, "Ops!Something is wrong!");
* }</pre>
*
* @param <X> 异常类型
* @param exceptionFunction 值不存在时执行的操作,返回值继承 {@link Throwable}
* @param message 作为传入操作执行时的参数,一般作为异常自定义提示语
* @return 包裹里不能为空的值
* @throws X 如果值不存在
* @throws NullPointerException 如果值不存在并且 传入的操作为 {@code null}或者操作执行后的返回值为{@code null}
* @author VampireAchao
*/
public <X extends Throwable> T orElseThrow(Function<String, ? extends X> exceptionFunction, String message) throws X {
if (isPresent()) {
return value;
} else {
throw exceptionFunction.apply(message);
}
}
/**
* 转换为 {@link Optional}对象
*
* @return {@link Optional}对象
* @since 5.7.16
*/
public Optional<T> toOptional() {
return Optional.ofNullable(this.value);
}
/**
* 判断传入参数是否与 {@code Opt}相等
* 在以下情况下返回true
* <ul>
* <li>它也是一个 {@code Opt} 并且
* <li>它们包裹住的元素都为空 或者
* <li>它们包裹住的元素之间相互 {@code equals()}
* </ul>
*
* @param obj 一个要用来判断是否相等的参数
* @return 如果传入的参数也是一个 {@code Opt}并且它们包裹住的元素都为空
* 或者它们包裹住的元素之间相互 {@code equals()} 就返回{@code true}
* 否则返回 {@code false}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Opt)) {
return false;
}
final Opt<?> other = (Opt<?>) obj;
return Objects.equals(value, other.value);
}
/**
* 如果包裹内元素为空,则返回0,否则返回元素的 {@code hashcode}
*
* @return 如果包裹内元素为空,则返回0,否则返回元素的 {@code hashcode}
*/
@Override
public int hashCode() {
return Objects.hashCode(value);
}
/**
* 返回包裹内元素调用{@code toString()}的结果,不存在则返回{@code null}
*
* @return 包裹内元素调用{@code toString()}的结果,不存在则返回{@code null}
*/
@Override
public String toString() {
return StrUtil.toStringOrNull(this.value);
}
}
| dromara/hutool | hutool-core/src/main/java/cn/hutool/core/lang/Opt.java |
427 | package com.neo.web;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@Controller
public class HomeController {
@RequestMapping({"/","/index"})
public String index(){
return"/index";
}
@RequestMapping("/login")
public String login(HttpServletRequest request, Map<String, Object> map) throws Exception{
System.out.println("HomeController.login()");
// 登录失败从request中获取shiro处理的异常信息。
// shiroLoginFailure:就是shiro异常类的全类名.
String exception = (String) request.getAttribute("shiroLoginFailure");
System.out.println("exception=" + exception);
String msg = "";
if (exception != null) {
if (UnknownAccountException.class.getName().equals(exception)) {
System.out.println("UnknownAccountException -- > 账号不存在:");
msg = "UnknownAccountException -- > 账号不存在:";
} else if (IncorrectCredentialsException.class.getName().equals(exception)) {
System.out.println("IncorrectCredentialsException -- > 密码不正确:");
msg = "IncorrectCredentialsException -- > 密码不正确:";
} else if ("kaptchaValidateFailed".equals(exception)) {
System.out.println("kaptchaValidateFailed -- > 验证码错误");
msg = "kaptchaValidateFailed -- > 验证码错误";
} else {
msg = "else >> "+exception;
System.out.println("else -- >" + exception);
}
}
map.put("msg", msg);
// 此方法不处理登录成功,由shiro进行处理
return "/login";
}
@RequestMapping("/403")
public String unauthorizedRole(){
System.out.println("------没有权限-------");
return "403";
}
} | ityouknow/spring-boot-examples | 2.x/spring-boot-shiro/src/main/java/com/neo/web/HomeController.java |
429 | package io.mycat.route.parser.druid;
import java.sql.SQLNonTransientException;
import com.alibaba.druid.sql.ast.SQLStatement;
import io.mycat.cache.LayerCachePool;
import io.mycat.config.model.SchemaConfig;
import io.mycat.route.RouteResultset;
/**
* 对SQLStatement解析
* 主要通过visitor解析和statement解析:有些类型的SQLStatement通过visitor解析足够了,
* 有些只能通过statement解析才能得到所有信息
* 有些需要通过两种方式解析才能得到完整信息
* @author wang.dw
*
*/
public interface DruidParser {
/**
* 使用MycatSchemaStatVisitor解析,得到tables、tableAliasMap、conditions等
* @param schema
* @param stmt
*/
public void parser(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt, String originSql,LayerCachePool cachePool,MycatSchemaStatVisitor schemaStatVisitor) throws SQLNonTransientException;
/**
* statement方式解析
* 子类可覆盖(如果visitorParse解析得不到表名、字段等信息的,就通过覆盖该方法来解析)
* 子类覆盖该方法一般是将SQLStatement转型后再解析(如转型为MySqlInsertStatement)
*/
public void statementParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt) throws SQLNonTransientException;
/**
* 子类可覆盖(如果该方法解析得不到表名、字段等信息的,就覆盖该方法,覆盖成空方法,然后通过statementPparse去解析)
* 通过visitor解析:有些类型的Statement通过visitor解析得不到表名、
* @param stmt
*/
public void visitorParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt, MycatSchemaStatVisitor visitor)
throws SQLNonTransientException;
/**
* 改写sql:加limit,加group by、加order by如有些没有加limit的可以通过该方法增加
* @param schema
* @param rrs
* @param stmt
* @throws SQLNonTransientException
*/
public void changeSql(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt,LayerCachePool cachePool) throws SQLNonTransientException;
/**
* 获取解析到的信息
* @return
*/
public DruidShardingParseInfo getCtx();
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/route/parser/druid/DruidParser.java |
430 | package org.nutz.log;
import org.nutz.lang.Lang;
import org.nutz.log.impl.Log4jLogAdapter;
import org.nutz.log.impl.NopLog;
import org.nutz.log.impl.SystemLogAdapter;
import org.nutz.plugin.SimplePluginManager;
/**
* 获取 Log 的静态工厂方法
* @author Young([email protected])
* @author zozoh([email protected])
* @author Wendal([email protected])
*/
public final class Logs {
private static LogAdapter adapter;
static {
init();
}
/**
* Get a Log by Class
*
* @param clazz
* your class
* @return Log
*/
public static Log getLog(Class<?> clazz) {
return getLog(clazz.getName());
}
/**
* Get a Log by name
*
* @param className
* the name of Log
* @return Log
*/
public static Log getLog(String className) {
return adapter.getLogger(className);
}
/**
* 返回以调用者的类命名的Log,是获取Log对象最简单的方法!
*/
public static Log get() {
StackTraceElement[] sts = Thread.currentThread().getStackTrace();
if (Lang.isAndroid) {
for (int i = 0; i < sts.length; i++) {
if (sts[i].getClassName().equals(Logs.class.getName())) {
return adapter.getLogger(sts[i+1].getClassName());
}
}
}
return adapter.getLogger(sts[2].getClassName());
}
/**
* 初始化NutLog,检查全部Log的可用性,选择可用的Log适配器
* <p/>
* <b>加载本类时,该方法已经在静态构造函数中调用,用户无需主动调用.</b>
* <p/>
* <b>除非迫不得已,请不要调用本方法<b/>
* <p/>
*/
public static void init() {
try {
String packageName = Logs.class.getPackage().getName() + ".impl.";
adapter = new SimplePluginManager<LogAdapter>(
packageName + "CustomLogAdapter",
packageName + "Slf4jLogAdapter",
packageName + "Log4jLogAdapter",
packageName + "SystemLogAdapter").get();
}
catch (Throwable e) {
try {
Log4jLogAdapter tmp = new Log4jLogAdapter();
if (tmp.canWork())
adapter = tmp;
else
adapter = new SystemLogAdapter();
} catch (Throwable _e) {
adapter = new SystemLogAdapter();
}
}
}
/**
* 开放自定义设置LogAdapter,注意,不能设置为null!! 如果你打算完全禁用Nutz的log,可以设置为NOP_ADAPTER
* @param adapter 你所偏好的LogAdapter
*/
public static void setAdapter(LogAdapter adapter) {
Logs.adapter = adapter;
}
/**
* 什么都不做的适配器,无任何输出,某些人就想完全禁用掉NutzLog,就可以用上它了
*/
public static LogAdapter NOP_ADAPTER = NopLog.NOP;
}
| nutzam/nutz | src/org/nutz/log/Logs.java |
431 | /*
* 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.base;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* 若把初始化内容放到initData实现,就是采用Lazy方式加载的Fragment
* 若不需要Lazy加载则initData方法内留空,初始化内容放到initViews即可
* -
* -注1: 如果是与ViewPager一起使用,调用的是setUserVisibleHint。
* ------可以调用mViewPager.setOffscreenPageLimit(size),若设置了该属性 则viewpager会缓存指定数量的Fragment
* -注2: 如果是通过FragmentTransaction的show和hide的方法来控制显示,调用的是onHiddenChanged.
* -注3: 针对初始就show的Fragment 为了触发onHiddenChanged事件 达到lazy效果 需要先hide再show
*/
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public abstract class BaseFragment extends Fragment {
protected String fragmentTitle; //fragment标题
private boolean isVisible; //是否可见状态
private boolean isPrepared; //标志位,View已经初始化完成。
private boolean isFirstLoad = true; //是否第一次加载
protected LayoutInflater inflater;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.inflater = inflater;
isFirstLoad = true;
View view = initView(inflater, container, savedInstanceState);
isPrepared = true;
lazyLoad();
return view;
}
/** 如果是与ViewPager一起使用,调用的是setUserVisibleHint */
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getUserVisibleHint()) {
isVisible = true;
onVisible();
} else {
isVisible = false;
onInvisible();
}
}
/**
* 如果是通过FragmentTransaction的show和hide的方法来控制显示,调用的是onHiddenChanged.
* 若是初始就show的Fragment 为了触发该事件 需要先hide再show
*/
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden) {
isVisible = true;
onVisible();
} else {
isVisible = false;
onInvisible();
}
}
protected void onVisible() {
lazyLoad();
}
protected void onInvisible() {
}
protected void lazyLoad() {
if (!isPrepared || !isVisible || !isFirstLoad) {
return;
}
isFirstLoad = false;
initData();
}
protected abstract View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
protected abstract void initData();
public String getTitle() {
return TextUtils.isEmpty(fragmentTitle) ? "" : fragmentTitle;
}
public void setTitle(String title) {
fragmentTitle = title;
}
}
| jeasonlzy/okhttp-OkGo | demo/src/main/java/com/lzy/demo/base/BaseFragment.java |
432 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2023 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.pagehelper.page;
import com.github.pagehelper.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageRowBounds;
import com.github.pagehelper.util.PageObjectUtil;
import com.github.pagehelper.util.StringUtil;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;
/**
* Page 参数信息
*
* @author liuzh
*/
public class PageParams {
/**
* RowBounds参数offset作为PageNum使用 - 默认不使用
*/
protected boolean offsetAsPageNum = false;
/**
* RowBounds是否进行count查询 - 默认不查询
*/
protected boolean rowBoundsWithCount = false;
/**
* 当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
*/
protected boolean pageSizeZero = false;
/**
* 分页合理化
*/
protected boolean reasonable = false;
/**
* 是否支持接口参数来传递分页参数,默认false
*/
protected boolean supportMethodsArguments = false;
/**
* 默认count(0)
*/
protected String countColumn = "0";
/**
* 转换count查询时保留 order by 排序
*/
private boolean keepOrderBy = false;
/**
* 转换count查询时保留子查询的 order by 排序
*/
private boolean keepSubSelectOrderBy = false;
/**
* 异步count查询
*/
private boolean asyncCount = false;
/**
* 获取分页参数
*
* @param parameterObject
* @param rowBounds
* @return
*/
public Page getPage(Object parameterObject, RowBounds rowBounds) {
Page page = PageHelper.getLocalPage();
if (page == null) {
if (rowBounds != RowBounds.DEFAULT) {
if (offsetAsPageNum) {
page = new Page(rowBounds.getOffset(), rowBounds.getLimit(), rowBoundsWithCount);
} else {
page = new Page(new int[]{rowBounds.getOffset(), rowBounds.getLimit()}, rowBoundsWithCount);
//offsetAsPageNum=false的时候,由于PageNum问题,不能使用reasonable,这里会强制为false
page.setReasonable(false);
}
if (rowBounds instanceof PageRowBounds) {
PageRowBounds pageRowBounds = (PageRowBounds) rowBounds;
page.setCount(pageRowBounds.getCount() == null || pageRowBounds.getCount());
}
} else if (parameterObject instanceof IPage || supportMethodsArguments) {
try {
page = PageObjectUtil.getPageFromObject(parameterObject, false);
} catch (Exception e) {
return null;
}
}
if (page == null) {
return null;
}
PageHelper.setLocalPage(page);
}
//分页合理化
if (page.getReasonable() == null) {
page.setReasonable(reasonable);
}
//当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
if (page.getPageSizeZero() == null) {
page.setPageSizeZero(pageSizeZero);
}
if (page.getKeepOrderBy() == null) {
page.setKeepOrderBy(keepOrderBy);
}
if (page.getKeepSubSelectOrderBy() == null) {
page.setKeepSubSelectOrderBy(keepSubSelectOrderBy);
}
return page;
}
public void setProperties(Properties properties) {
//offset作为PageNum使用
String offsetAsPageNum = properties.getProperty("offsetAsPageNum");
this.offsetAsPageNum = Boolean.parseBoolean(offsetAsPageNum);
//RowBounds方式是否做count查询
String rowBoundsWithCount = properties.getProperty("rowBoundsWithCount");
this.rowBoundsWithCount = Boolean.parseBoolean(rowBoundsWithCount);
//当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页
String pageSizeZero = properties.getProperty("pageSizeZero");
this.pageSizeZero = Boolean.parseBoolean(pageSizeZero);
//分页合理化,true开启,如果分页参数不合理会自动修正。默认false不启用
String reasonable = properties.getProperty("reasonable");
this.reasonable = Boolean.parseBoolean(reasonable);
//是否支持接口参数来传递分页参数,默认false
String supportMethodsArguments = properties.getProperty("supportMethodsArguments");
this.supportMethodsArguments = Boolean.parseBoolean(supportMethodsArguments);
//默认count列
String countColumn = properties.getProperty("countColumn");
if (StringUtil.isNotEmpty(countColumn)) {
this.countColumn = countColumn;
}
//当offsetAsPageNum=false的时候,不能
//参数映射
PageObjectUtil.setParams(properties.getProperty("params"));
// count查询时,是否保留查询中的 order by
keepOrderBy = Boolean.parseBoolean(properties.getProperty("keepOrderBy"));
// count查询时,是否保留子查询中的 order by
keepSubSelectOrderBy = Boolean.parseBoolean(properties.getProperty("keepSubSelectOrderBy"));
// 异步count查询
asyncCount = Boolean.parseBoolean(properties.getProperty("asyncCount"));
}
public boolean isOffsetAsPageNum() {
return offsetAsPageNum;
}
public boolean isRowBoundsWithCount() {
return rowBoundsWithCount;
}
public boolean isPageSizeZero() {
return pageSizeZero;
}
public boolean isReasonable() {
return reasonable;
}
public boolean isSupportMethodsArguments() {
return supportMethodsArguments;
}
public String getCountColumn() {
return countColumn;
}
public boolean isAsyncCount() {
return asyncCount;
}
}
| pagehelper/Mybatis-PageHelper | src/main/java/com/github/pagehelper/page/PageParams.java |
434 | package com.example.gsyvideoplayer;
import androidx.annotation.Nullable;
import androidx.media3.datasource.DataSink;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.TransferListener;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.multidex.MultiDexApplication;
import com.example.gsyvideoplayer.exosource.GSYExoHttpDataSourceFactory;
import java.io.File;
import java.util.Map;
import tv.danmaku.ijk.media.exo2.ExoMediaSourceInterceptListener;
import tv.danmaku.ijk.media.exo2.ExoPlayerCacheManager;
import tv.danmaku.ijk.media.exo2.ExoSourceManager;
/**
* Created by shuyu on 2016/11/11.
*/
public class GSYApplication extends MultiDexApplication {
@Override
public void onCreate() {
super.onCreate();
/*if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}*/
//LeakCanary.install(this);
//GSYVideoType.enableMediaCodec();
//GSYVideoType.enableMediaCodecTexture();
//PlayerFactory.setPlayManager(Exo2PlayerManager.class);//EXO模式
//ExoSourceManager.setSkipSSLChain(true);
//PlayerFactory.setPlayManager(SystemPlayerManager.class);//系统模式
//PlayerFactory.setPlayManager(IjkPlayerManager.class);//ijk模式
//PlayerFactory.setPlayManager(AliPlayerManager.class);//aliplay模式
//CacheFactory.setCacheManager(ExoPlayerCacheManager.class);//exo缓存模式,支持m3u8,只支持exo
//CacheFactory.setCacheManager(ProxyCacheManager.class);//代理缓存模式,支持所有模式,不支持m3u8等
//GSYVideoType.setShowType(GSYVideoType.SCREEN_MATCH_FULL);
//GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL);
//GSYVideoType.setShowType(GSYVideoType.SCREEN_MATCH_FULL);
//GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_CUSTOM);
//GSYVideoType.setScreenScaleRatio(9.0f/16);
//GSYVideoType.setRenderType(GSYVideoType.SUFRACE);
//GSYVideoType.setRenderType(GSYVideoType.GLSURFACE);
//IjkPlayerManager.setLogLevel(IjkMediaPlayer.IJK_LOG_SILENT);
//GSYVideoType.setRenderType(GSYVideoType.SUFRACE);
ExoSourceManager.setExoMediaSourceInterceptListener(new ExoMediaSourceInterceptListener() {
@Override
public MediaSource getMediaSource(String dataSource, boolean preview, boolean cacheEnable, boolean isLooping, File cacheDir) {
//如果返回 null,就使用默认的
return null;
}
/**
* 通过自定义的 HttpDataSource ,可以设置自签证书或者忽略证书
* demo 里的 GSYExoHttpDataSourceFactory 使用的是忽略证书
* */
@Override
public DataSource.Factory getHttpDataSourceFactory(String userAgent, @Nullable TransferListener listener, int connectTimeoutMillis, int readTimeoutMillis,
Map<String, String> mapHeadData, boolean allowCrossProtocolRedirects) {
//如果返回 null,就使用默认的
GSYExoHttpDataSourceFactory factory = new GSYExoHttpDataSourceFactory(userAgent, listener,
connectTimeoutMillis,
readTimeoutMillis, allowCrossProtocolRedirects);
factory.setDefaultRequestProperties(mapHeadData);
return factory;
}
@Override
public DataSink.Factory cacheWriteDataSinkFactory(String CachePath, String url) {
return null;
}
});
/*GSYVideoManager.instance().setPlayerInitSuccessListener(new IPlayerInitSuccessListener() {
///播放器初始化成果回调
@Override
public void onPlayerInitSuccess(IMediaPlayer player, GSYModel model) {
if (player instanceof IjkExo2MediaPlayer) {
/// 自定义你的
((IjkExo2MediaPlayer) player).setTrackSelector(new DefaultTrackSelector());
// DefaultTrackSelector.Parameters parameters = trackSelector.buildUponParameters()
// .setMaxVideoBitrate(LO_BITRATE)
// .setForceHighestSupportedBitrate(true)
// .build();
// trackSelector.setParameters(parameters);
((IjkExo2MediaPlayer) player).setLoadControl(new DefaultLoadControl());
}
}
});*/
/*ProxyCacheManager.instance().setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
ProxyCacheManager.instance().setTrustAllCerts(trustAllCerts);*/
}
}
| CarGuo/GSYVideoPlayer | app/src/main/java/com/example/gsyvideoplayer/GSYApplication.java |
438 | /**
* Copyright (c) 2011-2023, James Zhan 詹波 ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jfinal.kit;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import com.jfinal.core.Const;
/**
* Prop. Prop can load properties file from CLASSPATH or File object.
*/
public class Prop {
protected Properties properties;
/**
* 支持 new Prop().appendIfExists(...)
*/
public Prop() {
properties = new Properties();
}
/**
* Prop constructor.
* @see #Prop(String, String)
*/
public Prop(String fileName) {
this(fileName, Const.DEFAULT_ENCODING);
}
/**
* Prop constructor
* <p>
* Example:<br>
* Prop prop = new Prop("my_config.txt", "UTF-8");<br>
* String userName = prop.get("userName");<br><br>
*
* prop = new Prop("com/jfinal/file_in_sub_path_of_classpath.txt", "UTF-8");<br>
* String value = prop.get("key");
*
* @param fileName the properties file's name in classpath or the sub directory of classpath
* @param encoding the encoding
*/
public Prop(String fileName, String encoding) {
InputStream inputStream = null;
try {
inputStream = getClassLoader().getResourceAsStream(fileName); // properties.load(Prop.class.getResourceAsStream(fileName));
if (inputStream == null) {
throw new IllegalArgumentException("Properties file not found in classpath: " + fileName);
}
properties = new Properties();
properties.load(new InputStreamReader(inputStream, encoding));
} catch (IOException e) {
throw new RuntimeException("Error loading properties file.", e);
}
finally {
if (inputStream != null) try {inputStream.close();} catch (IOException e) {LogKit.error(e.getMessage(), e);}
}
}
private ClassLoader getClassLoader() {
ClassLoader ret = Thread.currentThread().getContextClassLoader();
return ret != null ? ret : getClass().getClassLoader();
}
/**
* Prop constructor.
* @see #Prop(File, String)
*/
public Prop(File file) {
this(file, Const.DEFAULT_ENCODING);
}
/**
* Prop constructor
* <p>
* Example:<br>
* Prop prop = new Prop(new File("/var/config/my_config.txt"), "UTF-8");<br>
* String userName = prop.get("userName");
*
* @param file the properties File object
* @param encoding the encoding
*/
public Prop(File file, String encoding) {
if (file == null) {
throw new IllegalArgumentException("File can not be null.");
}
if (!file.isFile()) {
throw new IllegalArgumentException("File not found : " + file.getName());
}
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
properties = new Properties();
properties.load(new InputStreamReader(inputStream, encoding));
} catch (IOException e) {
throw new RuntimeException("Error loading properties file.", e);
}
finally {
if (inputStream != null) try {inputStream.close();} catch (IOException e) {LogKit.error(e.getMessage(), e);}
}
}
public Prop append(Prop prop) {
if (prop == null) {
throw new IllegalArgumentException("prop can not be null");
}
properties.putAll(prop.getProperties());
return this;
}
public Prop append(String fileName, String encoding) {
return append(new Prop(fileName, encoding));
}
public Prop append(String fileName) {
return append(fileName, Const.DEFAULT_ENCODING);
}
public Prop appendIfExists(String fileName, String encoding) {
try {
return append(new Prop(fileName, encoding));
} catch (Exception e) {
return this;
}
}
public Prop appendIfExists(String fileName) {
return appendIfExists(fileName, Const.DEFAULT_ENCODING);
}
public Prop append(File file, String encoding) {
return append(new Prop(file, encoding));
}
public Prop append(File file) {
return append(file, Const.DEFAULT_ENCODING);
}
public Prop appendIfExists(File file, String encoding) {
if (file.isFile()) {
append(new Prop(file, encoding));
}
return this;
}
public Prop appendIfExists(File file) {
return appendIfExists(file, Const.DEFAULT_ENCODING);
}
public String get(String key) {
// 下面这行代码只要 key 存在,就不会返回 null。未给定 value 或者给定一个或多个空格都将返回 ""
String value = properties.getProperty(key);
return value != null && value.length() != 0 ? value.trim() : null;
}
public String get(String key, String defaultValue) {
String value = properties.getProperty(key);
return value != null && value.length() != 0 ? value.trim() : defaultValue;
}
public Integer getInt(String key) {
return getInt(key, null);
}
public Integer getInt(String key, Integer defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
return Integer.parseInt(value.trim());
}
return defaultValue;
}
public Long getLong(String key) {
return getLong(key, null);
}
public Long getLong(String key, Long defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
return Long.parseLong(value.trim());
}
return defaultValue;
}
public Double getDouble(String key) {
return getDouble(key, null);
}
public Double getDouble(String key, Double defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
return Double.parseDouble(value.trim());
}
return defaultValue;
}
public Boolean getBoolean(String key) {
return getBoolean(key, null);
}
public Boolean getBoolean(String key, Boolean defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
value = value.toLowerCase().trim();
if ("true".equals(value)) {
return true;
} else if ("false".equals(value)) {
return false;
}
throw new RuntimeException("The value can not parse to Boolean : " + value);
}
return defaultValue;
}
public boolean containsKey(String key) {
return properties.containsKey(key);
}
public boolean isEmpty() {
return properties.isEmpty();
}
public boolean notEmpty() {
return ! properties.isEmpty();
}
public Properties getProperties() {
return properties;
}
}
| jfinal/jfinal | src/main/java/com/jfinal/kit/Prop.java |
439 | /*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 static apijson.RequestMethod.DELETE;
import static apijson.RequestMethod.GET;
import static apijson.RequestMethod.GETS;
import static apijson.RequestMethod.HEAD;
import static apijson.RequestMethod.HEADS;
import static apijson.RequestMethod.POST;
import static apijson.RequestMethod.PUT;
import static apijson.orm.Operation.ALLOW_PARTIAL_UPDATE_FAIL;
import static apijson.orm.Operation.EXIST;
import static apijson.orm.Operation.INSERT;
import static apijson.orm.Operation.MUST;
import static apijson.orm.Operation.REFUSE;
import static apijson.orm.Operation.REMOVE;
import static apijson.orm.Operation.REPLACE;
import static apijson.orm.Operation.TYPE;
import static apijson.orm.Operation.UNIQUE;
import static apijson.orm.Operation.UPDATE;
import static apijson.orm.Operation.VERIFY;
import static apijson.orm.Operation.IF;
//import static apijson.orm.Operation.CODE;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import apijson.orm.script.JavaScriptExecutor;
import apijson.orm.script.ScriptExecutor;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import apijson.JSON;
import apijson.JSONResponse;
import apijson.Log;
import apijson.MethodAccess;
import apijson.NotNull;
import apijson.RequestMethod;
import apijson.StringUtil;
import apijson.orm.AbstractSQLConfig.IdCallback;
import apijson.orm.exception.ConflictException;
import apijson.orm.exception.NotLoggedInException;
import apijson.orm.exception.UnsupportedDataTypeException;
import apijson.orm.model.Access;
import apijson.orm.model.Column;
import apijson.orm.model.Document;
import apijson.orm.model.ExtendedProperty;
import apijson.orm.model.Function;
import apijson.orm.model.Script;
import apijson.orm.model.PgAttribute;
import apijson.orm.model.PgClass;
import apijson.orm.model.Request;
import apijson.orm.model.SysColumn;
import apijson.orm.model.SysTable;
import apijson.orm.model.Table;
import apijson.orm.model.AllTable;
import apijson.orm.model.AllColumn;
import apijson.orm.model.AllTableComment;
import apijson.orm.model.AllColumnComment;
import apijson.orm.model.TestRecord;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
/**校验器(权限、请求参数、返回结果等)
* TODO 合并 Structure 的代码
* @author Lemon
* @param <T> id 与 userId 的类型,一般为 Long
*/
public abstract class AbstractVerifier<T extends Object> implements Verifier<T>, IdCallback<T> {
private static final String TAG = "AbstractVerifier";
/**为 PUT, DELETE 强制要求必须有 id/id{}/id{}@ 条件
*/
public static boolean IS_UPDATE_MUST_HAVE_ID_CONDITION = true;
/**开启校验请求角色权限
*/
public static boolean ENABLE_VERIFY_ROLE = true;
/**开启校验请求传参内容
*/
public static boolean ENABLE_VERIFY_CONTENT = true;
/**未登录,不明身份的用户
*/
public static final String UNKNOWN = "UNKNOWN";
/**已登录的用户
*/
public static final String LOGIN = "LOGIN";
/**联系人,必须已登录
*/
public static final String CONTACT = "CONTACT";
/**圈子成员(CONTACT + OWNER),必须已登录
*/
public static final String CIRCLE = "CIRCLE";
/**拥有者,必须已登录
*/
public static final String OWNER = "OWNER";
/**管理员,必须已登录
*/
public static final String ADMIN = "ADMIN";
public static ParserCreator PARSER_CREATOR;
public static ScriptEngineManager SCRIPT_ENGINE_MANAGER;
public static ScriptEngine SCRIPT_ENGINE;
// 共享 STRUCTURE_MAP 则不能 remove 等做任何变更,否则在并发情况下可能会出错,加锁效率又低,所以这里改为忽略对应的 key
public static Map<String, Entry<String, Object>> ROLE_MAP;
public static List<String> OPERATION_KEY_LIST;
// <TableName, <METHOD, allowRoles>>
// <User, <GET, [OWNER, ADMIN]>>
@NotNull
public static Map<String, Map<RequestMethod, String[]>> SYSTEM_ACCESS_MAP;
@NotNull
public static Map<String, Map<RequestMethod, String[]>> ACCESS_MAP;
@NotNull
public static Map<String, Map<String, Object>> ACCESS_FAKE_DELETE_MAP;
// <method tag, <version, Request>>
// <PUT Comment, <1, { "method":"PUT", "tag":"Comment", "structure":{ "MUST":"id"... }... }>>
@NotNull
public static Map<String, SortedMap<Integer, JSONObject>> REQUEST_MAP;
private static String VERIFY_LENGTH_RULE = "(?<first>[>=<]*)(?<second>[0-9]*)";
private static Pattern VERIFY_LENGTH_PATTERN = Pattern.compile(VERIFY_LENGTH_RULE);
// 正则匹配的别名快捷方式,例如用 "PHONE" 代替 "^((13[0-9])|(15[^4,\\D])|(18[0-2,5-9])|(17[0-9]))\\d{8}$"
@NotNull
public static final Map<String, Pattern> COMPILE_MAP;
static {
SCRIPT_ENGINE_MANAGER = new ScriptEngineManager();
SCRIPT_ENGINE = SCRIPT_ENGINE_MANAGER.getEngineByName("js");
ROLE_MAP = new LinkedHashMap<>();
ROLE_MAP.put(UNKNOWN, new Entry<String, Object>());
ROLE_MAP.put(LOGIN, new Entry<String, Object>("userId>", 0));
ROLE_MAP.put(CONTACT, new Entry<String, Object>("userId{}", "contactIdList"));
ROLE_MAP.put(CIRCLE, new Entry<String, Object>("userId-()", "verifyCircle()")); // "userId{}", "circleIdList")); // 还是 {"userId":"currentUserId", "userId{}": "contactIdList", "@combine": "userId,userId{}" } ?
ROLE_MAP.put(OWNER, new Entry<String, Object>("userId", "userId"));
ROLE_MAP.put(ADMIN, new Entry<String, Object>("userId-()", "verifyAdmin()"));
OPERATION_KEY_LIST = new ArrayList<>();
OPERATION_KEY_LIST.add(TYPE.name());
OPERATION_KEY_LIST.add(VERIFY.name());
OPERATION_KEY_LIST.add(INSERT.name());
OPERATION_KEY_LIST.add(UPDATE.name());
OPERATION_KEY_LIST.add(REPLACE.name());
OPERATION_KEY_LIST.add(EXIST.name());
OPERATION_KEY_LIST.add(UNIQUE.name());
OPERATION_KEY_LIST.add(REMOVE.name());
OPERATION_KEY_LIST.add(MUST.name());
OPERATION_KEY_LIST.add(REFUSE.name());
OPERATION_KEY_LIST.add(IF.name());
// OPERATION_KEY_LIST.add(CODE.name());
OPERATION_KEY_LIST.add(ALLOW_PARTIAL_UPDATE_FAIL.name());
SYSTEM_ACCESS_MAP = new HashMap<String, Map<RequestMethod, String[]>>();
SYSTEM_ACCESS_MAP.put(Access.class.getSimpleName(), getAccessMap(Access.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(Function.class.getSimpleName(), getAccessMap(Function.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(Script.class.getSimpleName(), getAccessMap(Script.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(Request.class.getSimpleName(), getAccessMap(Request.class.getAnnotation(MethodAccess.class)));
if (Log.DEBUG) {
SYSTEM_ACCESS_MAP.put(Table.class.getSimpleName(), getAccessMap(Table.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(Column.class.getSimpleName(), getAccessMap(Column.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(PgAttribute.class.getSimpleName(), getAccessMap(PgAttribute.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(PgClass.class.getSimpleName(), getAccessMap(PgClass.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(AllTable.class.getSimpleName(), getAccessMap(AllTable.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(AllTableComment.class.getSimpleName(), getAccessMap(AllTableComment.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(AllColumn.class.getSimpleName(), getAccessMap(AllColumn.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(AllColumnComment.class.getSimpleName(), getAccessMap(AllColumnComment.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(SysTable.class.getSimpleName(), getAccessMap(SysTable.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(SysColumn.class.getSimpleName(), getAccessMap(SysColumn.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(ExtendedProperty.class.getSimpleName(), getAccessMap(ExtendedProperty.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(Document.class.getSimpleName(), getAccessMap(Document.class.getAnnotation(MethodAccess.class)));
SYSTEM_ACCESS_MAP.put(TestRecord.class.getSimpleName(), getAccessMap(TestRecord.class.getAnnotation(MethodAccess.class)));
}
ACCESS_MAP = new HashMap<>(SYSTEM_ACCESS_MAP);
REQUEST_MAP = new HashMap<>(ACCESS_MAP.size()*7); // 单个与批量增删改
COMPILE_MAP = new HashMap<String, Pattern>();
}
/**获取权限Map,每种操作都只允许对应的角色
* @param access
* @return
*/
public static HashMap<RequestMethod, String[]> getAccessMap(MethodAccess access) {
if (access == null) {
return null;
}
HashMap<RequestMethod, String[]> map = new HashMap<>();
map.put(GET, access.GET());
map.put(HEAD, access.HEAD());
map.put(GETS, access.GETS());
map.put(HEADS, access.HEADS());
map.put(POST, access.POST());
map.put(PUT, access.PUT());
map.put(DELETE, access.DELETE());
return map;
}
@Override
public String getVisitorIdKey(SQLConfig config) {
return config.getUserIdKey();
}
@Override
public String getIdKey(String database, String schema, String datasource, String table) {
return apijson.JSONObject.KEY_ID;
}
@Override
public String getUserIdKey(String database, String schema, String datasource, String table) {
return apijson.JSONObject.KEY_USER_ID;
}
@SuppressWarnings("unchecked")
@Override
public T newId(RequestMethod method, String database, String schema, String datasource, String table) {
return (T) Long.valueOf(System.currentTimeMillis());
}
@NotNull
protected Visitor<T> visitor;
protected Object visitorId;
@NotNull
@Override
public Visitor<T> getVisitor() {
return visitor;
}
@Override
public AbstractVerifier<T> setVisitor(Visitor<T> visitor) {
this.visitor = visitor;
this.visitorId = visitor == null ? null : visitor.getId();
//导致内部调用且放行校验(needVerifyLogin, needVerifyRole)也抛异常
// if (visitorId == null) {
// throw new NullPointerException(TAG + ".setVisitor visitorId == null !!! 可能导致权限校验失效,引发安全问题!");
// }
return this;
}
/**验证权限是否通过
* @param config
* @return
* @throws Exception
*/
@Override
public boolean verifyAccess(SQLConfig config) throws Exception {
if (ENABLE_VERIFY_ROLE == false) {
throw new UnsupportedOperationException("AbstractVerifier.ENABLE_VERIFY_ROLE == false " +
"时不支持校验角色权限!如需支持则设置 AbstractVerifier.ENABLE_VERIFY_ROLE = true !");
}
String table = config == null ? null : config.getTable();
if (table == null) {
return true;
}
String role = config.getRole();
if (role == null) {
role = UNKNOWN;
}
else {
if (ROLE_MAP.containsKey(role) == false) {
Set<String> NAMES = ROLE_MAP.keySet();
throw new IllegalArgumentException("角色 " + role + " 不存在!" +
"只能是[" + StringUtil.getString(NAMES.toArray()) + "]中的一种!");
}
if (role.equals(UNKNOWN) == false) { //未登录的角色
verifyLogin();
}
}
RequestMethod method = config.getMethod();
verifyRole(config, table, method, role);
return true;
}
@Override
public void verifyRole(SQLConfig config, String table, RequestMethod method, String role) throws Exception {
verifyAllowRole(config, table, method, role); //验证允许的角色
verifyUseRole(config, table, method, role); //验证使用的角色
}
/**允许请求使用的所以可能角色
* @param config
* @param table
* @param method
* @param role
* @return
* @throws Exception
* @see {@link apijson.JSONObject#KEY_ROLE}
*/
public void verifyAllowRole(SQLConfig config, String table, RequestMethod method, String role) throws Exception {
Log.d(TAG, "verifyAllowRole table = " + table + "; method = " + method + "; role = " + role);
if (table == null) {
table = config == null ? null : config.getTable();
}
if (table != null) {
if (method == null) {
method = config == null ? GET : config.getMethod();
}
if (role == null) {
role = config == null ? UNKNOWN : config.getRole();
}
Map<RequestMethod, String[]> map = ACCESS_MAP.get(table);
if (map == null || Arrays.asList(map.get(method)).contains(role) == false) {
throw new IllegalAccessException(table + " 不允许 " + role + " 用户的 " + method.name() + " 请求!");
}
}
}
/**校验请求使用的角色,角色不好判断,让访问者发过来角色名,OWNER,CONTACT,ADMIN等
* @param config
* @param table
* @param method
* @param role
* @return
* @throws Exception
* @see {@link apijson.JSONObject#KEY_ROLE}
*/
public void verifyUseRole(SQLConfig config, String table, RequestMethod method, String role) throws Exception {
Log.d(TAG, "verifyUseRole table = " + table + "; method = " + method + "; role = " + role);
//验证角色,假定真实强制匹配<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
String visitorIdKey = getVisitorIdKey(config);
if (table == null) {
table = config == null ? null : config.getTable();
}
if (method == null) {
method = config == null ? GET : config.getMethod();
}
if (role == null) {
role = config == null ? UNKNOWN : config.getRole();
}
Object requestId;
switch (role) {
case LOGIN://verifyRole通过就行
break;
case CONTACT:
case CIRCLE:
// TODO 做一个缓存contactMap<visitorId, contactArray>,提高[]:{}查询性能, removeAccessInfo时map.remove(visitorId)
// 不能在 Visitor内null -> [] ! 否则会导致某些查询加上不需要的条件!
List<Object> list = visitor.getContactIdList() == null
? new ArrayList<Object>() : new ArrayList<Object>(visitor.getContactIdList());
if (CIRCLE.equals(role)) {
list.add(visitorId);
}
// key!{}:[] 或 其它没有明确id的条件 等 可以和 key{}:[] 组合。类型错误就报错
requestId = config.getWhere(visitorIdKey, true); // JSON 里数值不能保证是 Long,可能是 Integer
@SuppressWarnings("unchecked")
Collection<Object> requestIdArray = (Collection<Object>) config.getWhere(visitorIdKey + "{}", true); // 不能是 &{}, |{} 不要传,直接 {}
if (requestId != null) {
if (requestIdArray == null) {
requestIdArray = new JSONArray();
}
requestIdArray.add(requestId);
}
if (requestIdArray == null) { // 可能是 @ 得到 || requestIdArray.isEmpty()) { // 请求未声明 key:id 或 key{}:[...] 条件,自动补全
config.putWhere(visitorIdKey+"{}", JSON.parseArray(list), true); // key{}:[] 有效,SQLConfig 里 throw NotExistException
}
else { // 请求已声明 key:id 或 key{}:[] 条件,直接验证
for (Object id : requestIdArray) {
if (id == null) {
continue;
}
if (id instanceof Number) { // 不能准确地判断 Long,可能是 Integer
if (((Number) id).longValue() <= 0 || list.contains(Long.valueOf("" + id)) == false) { // Integer等转为 Long 才能正确判断,强转崩溃
throw new IllegalAccessException(visitorIdKey + " = " + id + " 的 " + table
+ " 不允许 " + role + " 用户的 " + method.name() + " 请求!");
}
}
else if (id instanceof String) {
if (StringUtil.isEmpty(id) || list.contains(id) == false) {
throw new IllegalAccessException(visitorIdKey + " = " + id + " 的 " + table
+ " 不允许 " + role + " 用户的 " + method.name() + " 请求!");
}
}
else {
throw new UnsupportedDataTypeException(table + ".id 类型错误,类型必须是 Long/String!");
}
}
}
break;
case OWNER:
if (config.getMethod() == RequestMethod.POST) {
List<String> c = config.getColumn();
List<List<Object>> ovs = config.getValues();
if ( (c == null || c.isEmpty()) || (ovs == null || ovs.isEmpty()) ) {
throw new IllegalArgumentException("POST 请求必须在Table内设置要保存的 key:value !");
}
int index = c.indexOf(visitorIdKey);
if (index >= 0) {
Object oid;
for (List<Object> ovl : ovs) {
oid = ovl == null || index >= ovl.size() ? null : ovl.get(index);
if (oid == null || StringUtil.getString(oid).equals("" + visitorId) == false) {
throw new IllegalAccessException(visitorIdKey + " = " + oid + " 的 " + table
+ " 不允许 " + role + " 用户的 " + method.name() + " 请求!");
}
}
}
else {
List<String> nc = new ArrayList<>(c);
nc.add(visitorIdKey);
config.setColumn(nc);
List<List<Object>> nvs = new ArrayList<>();
List<Object> nvl;
for (List<Object> ovl : ovs) {
nvl = ovl == null || ovl.isEmpty() ? new ArrayList<>() : new ArrayList<>(ovl);
nvl.add(visitorId);
nvs.add(nvl);
}
config.setValues(nvs);
}
}
else {
requestId = config.getWhere(visitorIdKey, true);//JSON里数值不能保证是Long,可能是Integer
if (requestId != null && StringUtil.getString(requestId).equals(StringUtil.getString(visitorId)) == false) {
throw new IllegalAccessException(visitorIdKey + " = " + requestId + " 的 " + table
+ " 不允许 " + role + " 用户的 " + method.name() + " 请求!");
}
config.putWhere(visitorIdKey, visitorId, true);
}
break;
case ADMIN://这里不好做,在特定接口内部判。 可以是 /get/admin + 固定秘钥 Parser#needVerify,之后全局跳过验证
verifyAdmin();
break;
default://unknown,verifyRole通过就行
break;
}
//验证角色,假定真实强制匹配>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}
/**登录校验
*/
@Override
public void verifyLogin() throws Exception {
//未登录没有权限操作
if (visitorId == null) {
throw new NotLoggedInException("未登录或登录过期,请登录后再操作!");
}
if (visitorId instanceof Number) {
if (((Number) visitorId).longValue() <= 0) {
throw new NotLoggedInException("未登录或登录过期,请登录后再操作!");
}
}
else if (visitorId instanceof String) {
if (StringUtil.isEmpty(visitorId, true)) {
throw new NotLoggedInException("未登录或登录过期,请登录后再操作!");
}
}
else {
throw new UnsupportedDataTypeException("visitorId 只能是 Long 或 String 类型!");
}
}
@Override
public void verifyAdmin() throws Exception {
throw new UnsupportedOperationException("不支持 ADMIN 角色!如果要支持就在子类重写这个方法" +
"来校验 ADMIN 角色,不通过则 throw IllegalAccessException!");
}
/**验证是否重复
* FIXME 这个方法实际上没有被使用
* @param table
* @param key
* @param value
* @throws Exception
*/
@Override
public void verifyRepeat(String table, String key, Object value) throws Exception {
verifyRepeat(table, key, value, 0);
}
/**验证是否重复
* FIXME 这个方法实际上没有被使用,而且与 Structure.verifyRepeat 代码重复度比较高,需要简化
* @param table
* @param key
* @param value
* @param exceptId 不包含id
* @throws Exception
*/
@Override
public void verifyRepeat(String table, String key, Object value, long exceptId) throws Exception {
if (key == null || value == null) {
Log.e(TAG, "verifyRepeat key == null || value == null >> return;");
return;
}
if (value instanceof JSON) {
throw new UnsupportedDataTypeException(key + ":value 中value的类型不能为JSON!");
}
JSONRequest request = new JSONRequest(key, value);
if (exceptId > 0) {//允许修改自己的属性为该属性原来的值
request.put(JSONRequest.KEY_ID + "!", exceptId); // FIXME 这里 id 写死了,不支持自定义
}
JSONObject repeat = createParser().setMethod(HEAD).setNeedVerify(true).parseResponse(
new JSONRequest(table, request)
);
repeat = repeat == null ? null : repeat.getJSONObject(table);
if (repeat == null) {
throw new Exception("服务器内部错误 verifyRepeat repeat == null");
}
if (repeat.getIntValue(JSONResponse.KEY_COUNT) > 0) {
throw new ConflictException(key + ": " + value + " 已经存在,不能重复!");
}
}
/**从request提取target指定的内容
* @param method
* @param name
* @param target
* @param request
* @param maxUpdateCount
* @param database
* @param schema
* @param creator
* @return
* @throws Exception
*/
@Override
public JSONObject verifyRequest(@NotNull final RequestMethod method, final String name
, final JSONObject target, final JSONObject request, final int maxUpdateCount
, final String database, final String schema, final SQLCreator creator) throws Exception {
return verifyRequest(method, name, target, request, maxUpdateCount, database, schema, this, creator);
}
/**从request提取target指定的内容
* @param method
* @param name
* @param target
* @param request
* @param creator
* @return
* @throws Exception
*/
public static JSONObject verifyRequest(@NotNull final RequestMethod method, final String name
, final JSONObject target, final JSONObject request, final SQLCreator creator) throws Exception {
return verifyRequest(method, name, target, request, AbstractParser.MAX_UPDATE_COUNT, creator);
}
/**从request提取target指定的内容
* @param method
* @param name
* @param target
* @param request
* @param maxUpdateCount
* @param creator
* @return
* @throws Exception
*/
public static JSONObject verifyRequest(@NotNull final RequestMethod method, final String name
, final JSONObject target, final JSONObject request
, final int maxUpdateCount, final SQLCreator creator) throws Exception {
return verifyRequest(method, name, target, request, maxUpdateCount
, null, null, null, creator);
}
/**从request提取target指定的内容
* @param method
* @param name
* @param target
* @param request
* @param maxUpdateCount
* @param database
* @param schema
* @param idCallback
* @param creator
* @return
* @param <T>
* @throws Exception
*/
public static <T extends Object> JSONObject verifyRequest(@NotNull final RequestMethod method
, final String name, final JSONObject target, final JSONObject request
, final int maxUpdateCount, final String database, final String schema
, final IdCallback<T> idCallback, final SQLCreator creator) throws Exception {
return verifyRequest(method, name, target, request, maxUpdateCount, database, schema
, null, idCallback, creator);
}
/**从request提取target指定的内容
* @param method
* @param name
* @param target
* @param request
* @param maxUpdateCount
* @param database
* @param schema
* @param datasource
* @param idCallback
* @param creator
* @return
* @param <T>
* @throws Exception
*/
public static <T extends Object> JSONObject verifyRequest(@NotNull final RequestMethod method
, final String name, final JSONObject target, final JSONObject request
, final int maxUpdateCount, final String database, final String schema, final String datasource
, final IdCallback<T> idCallback, final SQLCreator creator) throws Exception {
if (ENABLE_VERIFY_CONTENT == false) {
throw new UnsupportedOperationException("AbstractVerifier.ENABLE_VERIFY_CONTENT == false" +
" 时不支持校验请求传参内容!如需支持则设置 AbstractVerifier.ENABLE_VERIFY_CONTENT = true !");
}
Log.i(TAG, "verifyRequest method = " + method + "; name = " + name
+ "; target = \n" + JSON.toJSONString(target)
+ "\n request = \n" + JSON.toJSONString(request));
if (target == null || request == null) {// || request.isEmpty()) {
Log.i(TAG, "verifyRequest target == null || request == null >> return null;");
return null;
}
//已在 Verifier 中处理
// if (get(request.getString(JSONRequest.KEY_ROLE)) == ADMIN) {
// throw new IllegalArgumentException("角色设置错误!不允许在写操作Request中传 " + name +
// ":{ " + JSONRequest.KEY_ROLE + ":admin } !");
// }
//解析
return parse(method, name, target, request, database, schema, idCallback, creator, new OnParseCallback() {
@Override
public JSONObject onParseJSONObject(String key, JSONObject tobj, JSONObject robj) throws Exception {
// Log.i(TAG, "verifyRequest.parse.onParseJSONObject key = " + key + "; robj = " + robj);
if (robj == null) {
if (tobj != null) {//不允许不传Target中指定的Table
throw new IllegalArgumentException(method + "请求,请在 " + name + " 内传 " + key + ":{} !");
}
} else if (apijson.JSONObject.isTableKey(key)) {
String db = request.getString(apijson.JSONObject.KEY_DATABASE);
String sh = request.getString(apijson.JSONObject.KEY_SCHEMA);
String ds = request.getString(apijson.JSONObject.KEY_DATASOURCE);
if (StringUtil.isEmpty(db, false)) {
db = database;
}
if (StringUtil.isEmpty(sh, false)) {
sh = schema;
}
if (StringUtil.isEmpty(ds, false)) {
ds = datasource;
}
String idKey = idCallback == null ? null : idCallback.getIdKey(db, sh, ds, key);
String finalIdKey = StringUtil.isEmpty(idKey, false) ? apijson.JSONObject.KEY_ID : idKey;
if (method == RequestMethod.POST) {
if (robj.containsKey(finalIdKey)) {
throw new IllegalArgumentException(method + "请求," + name + "/" + key + " 不能传 " + finalIdKey + " !");
}
} else {
Boolean atLeastOne = tobj == null ? null : tobj.getBoolean(Operation.IS_ID_CONDITION_MUST.name());
if (Boolean.TRUE.equals(atLeastOne) || RequestMethod.isUpdateMethod(method)) {
verifyId(method.name(), name, key, robj, finalIdKey, maxUpdateCount, atLeastOne != null ? atLeastOne : IS_UPDATE_MUST_HAVE_ID_CONDITION);
String userIdKey = idCallback == null ? null : idCallback.getUserIdKey(db, sh, ds, key);
String finalUserIdKey = StringUtil.isEmpty(userIdKey, false) ? apijson.JSONObject.KEY_USER_ID : userIdKey;
verifyId(method.name(), name, key, robj, finalUserIdKey, maxUpdateCount, false);
}
}
}
return verifyRequest(method, key, tobj, robj, maxUpdateCount, database, schema, idCallback, creator);
}
@Override
protected JSONArray onParseJSONArray(String key, JSONArray tarray, JSONArray rarray) throws Exception {
if ((method == RequestMethod.POST || method == RequestMethod.PUT) && JSONRequest.isArrayKey(key)) {
if (rarray == null || rarray.isEmpty()) {
throw new IllegalArgumentException(method + "请求,请在 " + name + " 内传 " + key + ":[{ ... }] "
+ ",批量新增 Table[]:value 中 value 必须是包含表对象的非空数组!其中每个子项 { ... } 都是"
+ " tag:" + key.substring(0, key.length() - 2) + " 对应单个新增的 structure !");
}
if (rarray.size() > maxUpdateCount) {
throw new IllegalArgumentException(method + "请求," + name + "/" + key
+ " 里面的 " + key + ":[{ ... }] 中 [] 的长度不能超过 " + maxUpdateCount + " !");
}
}
return super.onParseJSONArray(key, tarray, rarray);
}
});
}
/**
* @param method
* @param name
* @param key
* @param robj
* @param idKey
* @param atLeastOne 至少有一个不为null
*/
private static void verifyId(@NotNull String method, @NotNull String name, @NotNull String key
, @NotNull JSONObject robj, @NotNull String idKey, final int maxUpdateCount, boolean atLeastOne) {
//单个修改或删除
Object id = robj.get(idKey); //如果必须传 id ,可在Request表中配置NECESSARY
if (id != null && id instanceof Number == false && id instanceof String == false) {
throw new IllegalArgumentException(method + "请求," + name + "/" + key
+ " 里面的 " + idKey + ":value 中value的类型只能是 Long 或 String !");
}
//批量修改或删除
String idInKey = idKey + "{}";
// id引用, 格式: "id{}@": "sql"
String idRefInKey = robj.getString(idKey + "{}@");
JSONArray idIn = null;
try {
idIn = robj.getJSONArray(idInKey); //如果必须传 id{} ,可在Request表中配置NECESSARY
} catch (Exception e) {
throw new IllegalArgumentException(method + "请求," + name + "/" + key
+ " 里面的 " + idInKey + ":value 中value的类型只能是 [Long] !");
}
if (idIn == null) {
if (atLeastOne && id == null && idRefInKey == null) {
throw new IllegalArgumentException(method + "请求," + name + "/" + key
+ " 里面 " + idKey + "," + idInKey + "," + (idKey + "{}@") + " 至少传其中一个!");
}
} else {
if (idIn.size() > maxUpdateCount) { //不允许一次操作 maxUpdateCount 条以上记录
throw new IllegalArgumentException(method + "请求," + name + "/" + key
+ " 里面的 " + idInKey + ":[] 中[]的长度不能超过 " + maxUpdateCount + " !");
}
//解决 id{}: ["1' OR 1='1'))--"] 绕过id{}限制
//new ArrayList<Long>(idIn) 不能检查类型,Java泛型擦除问题,居然能把 ["a"] 赋值进去还不报错
for (int i = 0; i < idIn.size(); i++) {
Object o = idIn.get(i);
if (o == null) {
throw new IllegalArgumentException(method + "请求," + name + "/" + key
+ " 里面的 " + idInKey + ":[] 中所有项都不能为 [ null, <= 0 的数字, 空字符串 \"\" ] 中任何一个 !");
}
if (o instanceof Number) {
//解决 Windows mysql-5.6.26-winx64 等低于 5.7 的 MySQL 可能 id{}: [0] 生成 id IN(0) 触发 MySQL bug 导致忽略 IN 条件
//例如 UPDATE `apijson`.`TestRecord` SET `testAccountId` = -1 WHERE ( (`id` IN (0)) AND (`userId`= 82001) )
if (((Number) o).longValue() <= 0) {
throw new IllegalArgumentException(method + "请求," + name + "/" + key
+ " 里面的 " + idInKey + ":[] 中所有项都不能为 [ null, <= 0 的数字, 空字符串 \"\" ] 中任何一个 !");
}
}
else if (o instanceof String) {
if (StringUtil.isEmpty(o, true)) {
throw new IllegalArgumentException(method + "请求," + name + "/" + key
+ " 里面的 " + idInKey + ":[] 中所有项都不能为 [ null, <= 0 的数字, 空字符串 \"\" ] 中任何一个 !");
}
}
else {
throw new IllegalArgumentException(method + "请求," + name + "/" + key
+ " 里面的 " + idInKey + ":[] 中所有项的类型都只能是 Long 或 String !");
}
}
}
}
/**校验并将response转换为指定的内容和结构
* @param method
* @param name
* @param target
* @param response
* @param database
* @param schema
* @param creator
* @param callback
* @return
* @throws Exception
*/
@Override
public JSONObject verifyResponse(@NotNull final RequestMethod method, final String name
, final JSONObject target, final JSONObject response, final String database, final String schema
, SQLCreator creator, OnParseCallback callback) throws Exception {
return verifyResponse(method, name, target, response, database, schema, this, creator, callback);
}
/**校验并将response转换为指定的内容和结构
* @param method
* @param name
* @param target
* @param response
* @param creator
* @param callback
* @return
* @throws Exception
*/
public static JSONObject verifyResponse(@NotNull final RequestMethod method, final String name
, final JSONObject target, final JSONObject response, SQLCreator creator, OnParseCallback callback) throws Exception {
return verifyResponse(method, name, target, response, null, null, null, creator, callback);
}
/**校验并将response转换为指定的内容和结构
* @param method
* @param name
* @param target
* @param response
* @param database
* @param schema
* @param idKeyCallback
* @param creator
* @param callback
* @return
* @param <T>
* @throws Exception
*/
public static <T extends Object> JSONObject verifyResponse(@NotNull final RequestMethod method, final String name
, final JSONObject target, final JSONObject response, final String database, final String schema
, final IdCallback<T> idKeyCallback, SQLCreator creator, OnParseCallback callback) throws Exception {
Log.i(TAG, "verifyResponse method = " + method + "; name = " + name
+ "; target = \n" + JSON.toJSONString(target)
+ "\n response = \n" + JSON.toJSONString(response));
if (target == null || response == null) {// || target.isEmpty() {
Log.i(TAG, "verifyResponse target == null || response == null >> return response;");
return response;
}
//解析
return parse(method, name, target, response, database, schema
, idKeyCallback, creator, callback != null ? callback : new OnParseCallback() {
@Override
protected JSONObject onParseJSONObject(String key, JSONObject tobj, JSONObject robj) throws Exception {
return verifyResponse(method, key, tobj, robj, database, schema, idKeyCallback, creator, callback);
}
});
}
/**对request和response不同的解析用callback返回
* @param method
* @param name
* @param target
* @param real
* @param creator
* @param callback
* @return
* @throws Exception
*/
public static JSONObject parse(@NotNull final RequestMethod method, String name, JSONObject target, JSONObject real
, SQLCreator creator, @NotNull OnParseCallback callback) throws Exception {
return parse(method, name, target, real, null, null, null, creator, callback);
}
/**对request和response不同的解析用callback返回
* @param method
* @param name
* @param target
* @param real
* @param database
* @param schema
* @param idCallback
* @param creator
* @param callback
* @return
* @throws Exception
*/
public static <T extends Object> JSONObject parse(@NotNull final RequestMethod method, String name
, JSONObject target, JSONObject real, final String database, final String schema
, final IdCallback<T> idCallback, SQLCreator creator, @NotNull OnParseCallback callback) throws Exception {
return parse(method, name, target, real, database, schema, null, idCallback, creator, callback);
}
/**对request和response不同的解析用callback返回
* @param method
* @param name
* @param target
* @param real
* @param database
* @param schema
* @param datasource
* @param idCallback
* @param creator
* @param callback
* @return
* @throws Exception
*/
public static <T extends Object> JSONObject parse(@NotNull final RequestMethod method, String name
, JSONObject target, JSONObject real, final String database, final String schema, final String datasource
, final IdCallback<T> idCallback, SQLCreator creator, @NotNull OnParseCallback callback) throws Exception {
if (target == null) {
return null;
}
// 获取配置<<<<<<<<<<<<<<<<<<<<<<<<<<<<
JSONObject type = target.getJSONObject(TYPE.name());
JSONObject verify = target.getJSONObject(VERIFY.name());
JSONObject insert = target.getJSONObject(INSERT.name());
JSONObject update = target.getJSONObject(UPDATE.name());
JSONObject replace = target.getJSONObject(REPLACE.name());
String exist = StringUtil.getString(target.getString(EXIST.name()));
String unique = StringUtil.getString(target.getString(UNIQUE.name()));
String remove = StringUtil.getString(target.getString(REMOVE.name()));
String must = StringUtil.getString(target.getString(MUST.name()));
String refuse = StringUtil.getString(target.getString(REFUSE.name()));
Object _if = target.get(IF.name());
boolean ifIsStr = _if instanceof String && StringUtil.isNotEmpty(_if, true);
JSONObject ifObj = ifIsStr == false && _if instanceof JSONObject ? (JSONObject) _if : null;
// : (_if instanceof String ? new apijson.JSONRequest((String) _if, "" /* "throw new Error('')" */ ) : null);
if (ifObj == null && _if != null && ifIsStr == false) {
// if (_if instanceof JSONArray) {
// }
throw new IllegalArgumentException(name + ": { " + IF.name() + ": value } 中 value 类型错误!只允许 String, JSONObject!");
}
// Object code = target.get(CODE.name());
String allowPartialUpdateFail = StringUtil.getString(target.getString(ALLOW_PARTIAL_UPDATE_FAIL.name()));
// 移除字段<<<<<<<<<<<<<<<<<<<
String[] removes = StringUtil.split(remove);
if (removes != null && removes.length > 0) {
for (String r : removes) {
real.remove(r);
}
}
// 移除字段>>>>>>>>>>>>>>>>>>>
// 判断必要字段是否都有<<<<<<<<<<<<<<<<<<<
String[] musts = StringUtil.split(must);
Set<String> mustSet = new HashSet<String>();
if (musts != null && musts.length > 0) {
for (String s : musts) {
if (real.get(s) == null && real.get(s+"@") == null) { // 可能传null进来,这里还会通过 real.containsKey(s) == false) {
throw new IllegalArgumentException(method + "请求,"
+ name + " 里面不能缺少 " + s + " 等[" + must + "]内的任何字段!");
}
mustSet.add(s);
}
}
// 判断必要字段是否都有>>>>>>>>>>>>>>>>>>>
Set<String> objKeySet = new HashSet<String>(); // 不能用tableKeySet,仅判断 Table:{} 会导致 key:{ Table:{} } 绕过判断
// 解析内容<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Set<Map.Entry<String, Object>> set = new LinkedHashSet<>(target.entrySet());
if (set.isEmpty() == false) {
for (Map.Entry<String, Object> entry : set) {
String key = entry == null ? null : entry.getKey();
if (key == null || OPERATION_KEY_LIST.contains(key)) {
continue;
}
Object tvalue = entry.getValue();
Object rvalue = real.get(key);
if (callback.onParse(key, tvalue, rvalue) == false) {
continue;
}
if (tvalue instanceof JSONObject) { // JSONObject,往下一级提取
if (rvalue != null && rvalue instanceof JSONObject == false) {
throw new UnsupportedDataTypeException(key + ":value 的 value 不合法!类型必须是 OBJECT ,结构为 {} !");
}
tvalue = callback.onParseJSONObject(key, (JSONObject) tvalue, (JSONObject) rvalue);
objKeySet.add(key);
} else if (tvalue instanceof JSONArray) { // JSONArray
if (rvalue != null && rvalue instanceof JSONArray == false) {
throw new UnsupportedDataTypeException(key + ":value 的 value 不合法!类型必须是 ARRAY ,结构为 [] !");
}
tvalue = callback.onParseJSONArray(key, (JSONArray) tvalue, (JSONArray) rvalue);
if ((method == RequestMethod.POST || method == RequestMethod.PUT) && JSONRequest.isArrayKey(key)) {
objKeySet.add(key);
}
} else { // 其它Object
tvalue = callback.onParseObject(key, tvalue, rvalue);
}
if (tvalue != null) { // 可以在target中加上一些不需要客户端传的键值对
real.put(key, tvalue);
}
}
}
// 解析内容>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Set<String> rkset = real.keySet(); // 解析内容并没有改变rkset
// 解析不允许的字段<<<<<<<<<<<<<<<<<<<
String[] refuses = StringUtil.split(refuse);
Set<String> refuseSet = new HashSet<String>();
if (refuses != null && refuses.length > 0) {
Set<String> notRefuseSet = new HashSet<String>();
for (String rfs : refuses) {
if (rfs == null) { // StringUtil.isEmpty(rfs, true) {
continue;
}
if (rfs.startsWith("!")) {
rfs = rfs.substring(1);
if (notRefuseSet.contains(rfs)) {
throw new ConflictException(REFUSE.name() + ":value 中出现了重复的 !"
+ rfs + " !不允许重复,也不允许一个 key 和取反 !key 同时使用!");
}
if (refuseSet.contains(rfs)) {
throw new ConflictException(REFUSE.name() + ":value 中同时出现了 "
+ rfs + " 和 !" + rfs + " !不允许重复,也不允许一个 key 和取反 !key 同时使用!");
}
if (rfs.equals("")) { // 所有非 MUST
// 对@key放行,@role,@column,自定义@position等, @key:{ "Table":{} } 不会解析内部
for (String key : rkset) {
if (key == null || key.startsWith("@") || notRefuseSet.contains(key)
|| mustSet.contains(key) || objKeySet.contains(key)) {
continue;
}
// 支持id ref: id{}@
if (key.endsWith("@") && mustSet.contains(key.substring(0, key.length() - 1))) {
continue;
}
refuseSet.add(key);
}
}
else { // 排除 !key 后再禁传其它的
notRefuseSet.add(rfs);
}
}
else {
if (refuseSet.contains(rfs)) {
throw new ConflictException(REFUSE.name() + ":value 中出现了重复的 " + rfs + " !" +
"不允许重复,也不允许一个 key 和取反 !key 同时使用!");
}
if (notRefuseSet.contains(rfs)) {
throw new ConflictException(REFUSE.name() + ":value 中同时出现了 " + rfs + " 和 !" + rfs + " !" +
"不允许重复,也不允许一个 key 和取反 !key 同时使用!");
}
refuseSet.add(rfs);
}
}
}
// 解析不允许的字段>>>>>>>>>>>>>>>>>>>
Set<String> onKeys = new LinkedHashSet<>();
// 判断不允许传的key<<<<<<<<<<<<<<<<<<<<<<<<<
for (String rk : rkset) {
if (refuseSet.contains(rk)) { // 不允许的字段
throw new IllegalArgumentException(method + "请求," + name
+ " 里面不允许传 " + rk + " 等" + StringUtil.getString(refuseSet) + "内的任何字段!");
}
if (rk == null) { // 无效的key
real.remove(rk);
continue;
}
Object rv = real.get(rk);
// 不允许传远程函数,只能后端配置
if (rk.endsWith("()") && rv instanceof String) {
throw new UnsupportedOperationException(method + " 请求," + rk + " 不合法!" +
"非开放请求不允许传远程函数 key():\"fun()\" !");
}
// 不在target内的 key:{}
if (rk.startsWith("@") == false && rk.endsWith("@") == false && objKeySet.contains(rk) == false) {
if (rv instanceof JSONObject) {
throw new UnsupportedOperationException(method + " 请求,"
+ name + " 里面不允许传 " + rk + ":{} !");
}
if ((method == RequestMethod.POST || method == RequestMethod.PUT)
&& rv instanceof JSONArray && JSONRequest.isArrayKey(rk)) {
throw new UnsupportedOperationException(method + " 请求," + name + " 里面不允许 "
+ rk + ":[] 等未定义的 Table[]:[{}] 批量操作键值对!");
}
}
// 先让其它操作符完成
// if (rv != null) { // || nulls.contains(rk)) {
// onKeys.add(rk);
// }
}
// 判断不允许传的key>>>>>>>>>>>>>>>>>>>>>>>>>
// 校验与修改Request<<<<<<<<<<<<<<<<<
// 在tableKeySet校验后操作,避免 导致put/add进去的Table 被当成原Request的内容
real = operate(TYPE, type, real, creator);
real = operate(VERIFY, verify, real, creator);
real = operate(INSERT, insert, real, creator);
real = operate(UPDATE, update, real, creator);
real = operate(REPLACE, replace, real, creator);
// 校验与修改Request>>>>>>>>>>>>>>>>>
String db = real.getString(apijson.JSONObject.KEY_DATABASE);
String sh = real.getString(apijson.JSONObject.KEY_SCHEMA);
String ds = real.getString(apijson.JSONObject.KEY_DATASOURCE);
if (StringUtil.isEmpty(db, false)) {
db = database;
}
if (StringUtil.isEmpty(sh, false)) {
sh = schema;
}
if (StringUtil.isEmpty(ds, false)) {
ds = datasource;
}
String idKey = idCallback == null ? null : idCallback.getIdKey(db, sh, ds, name);
String finalIdKey = StringUtil.isEmpty(idKey, false) ? apijson.JSONObject.KEY_ID : idKey;
// TODO 放在operate前?考虑性能、operate修改后再验证的值是否和原来一样
// 校验存在<<<<<<<<<<<<<<<<<<<
String[] exists = StringUtil.split(exist);
if (exists != null && exists.length > 0) {
long exceptId = real.getLongValue(finalIdKey);
Map<String,Object> map = new HashMap<>();
for (String e : exists) {
map.put(e,real.get(e));
}
verifyExist(name, map, exceptId, creator);
}
// 校验存在>>>>>>>>>>>>>>>>>>>
// TODO 放在operate前?考虑性能、operate修改后再验证的值是否和原来一样
// 校验重复<<<<<<<<<<<<<<<<<<<
String[] uniques = StringUtil.split(unique);
if (uniques != null && uniques.length > 0) {
long exceptId = real.getLongValue(finalIdKey);
Map<String,Object> map = new HashMap<>();
for (String u : uniques) {
map.put(u, real.get(u));
}
verifyRepeat(name, map, exceptId, finalIdKey, creator);
}
// 校验重复>>>>>>>>>>>>>>>>>>>
// 校验并配置允许批量增删改部分失败<<<<<<<<<<<<<<<<<<<
String[] partialFails = StringUtil.split(allowPartialUpdateFail);
if (partialFails != null && partialFails.length > 0) {
for (String key : partialFails) {
if (apijson.JSONObject.isArrayKey(key) == false) {
throw new IllegalArgumentException("后端 Request 表中 " + ALLOW_PARTIAL_UPDATE_FAIL.name()
+ ":value 中 " + key + " 不合法!必须以 [] 结尾!");
}
if (target.get(key) instanceof Collection == false) {
throw new IllegalArgumentException("后端 Request 表中 " + ALLOW_PARTIAL_UPDATE_FAIL.name()
+ ":value 中 " + key + " 对应的 " + key + ":[] 不存在!");
}
// 可能 Table[] 和 Table:alias[] 冲突 int index = key.indexOf(":");
// String k = index < 0 ? key.substring(0, key.length() - 2) : key.substring(0, index);
String k = key.substring(0, key.length() - 2);
if (k.isEmpty()) {
throw new IllegalArgumentException("后端 Request 表中 " + ALLOW_PARTIAL_UPDATE_FAIL.name()
+ ":value 中 " + key + " 不合法![] 前必须有名字!");
}
AbstractSQLConfig.ALLOW_PARTIAL_UPDATE_FAIL_TABLE_MAP.putIfAbsent(k, "");
}
}
// 校验并配置允许部分批量增删改失败>>>>>>>>>>>>>>>>>>>
String[] nks = ifObj == null ? null : StringUtil.split(real.getString(JSONRequest.KEY_NULL));
Collection<?> nkl = nks == null || nks.length <= 0 ? new HashSet<>() : Arrays.asList(nks);
Set<Map.Entry<String, Object>> ifSet = ifObj == null ? null : ifObj.entrySet();
if (ifIsStr || (ifSet != null && ifSet.isEmpty() == false)) {
// 没必要限制,都是后端配置的,安全可控,而且可能确实有特殊需求,需要 id, @column 等
// List<String> condKeys = new ArrayList<>(Arrays.asList(apijson.JSONRequest.KEY_ID, apijson.JSONRequest.KEY_ID_IN
// , apijson.JSONRequest.KEY_USER_ID, apijson.JSONRequest.KEY_USER_ID_IN));
// condKeys.addAll(JSONRequest.TABLE_KEY_LIST);
String preCode = "var curObj = " + JSON.format(real) + ";";
// 未传的 key 在后面 eval 时总是报错 undefined,而且可能有冲突,例如对象里有 "curObj": val 键值对,就会覆盖当前对象定义,还不如都是 curObj.sex 这样取值
// Set<Map.Entry<String, Object>> rset = real.entrySet();
// for (Map.Entry<String, Object> entry : rset) {
// String k = entry == null ? null : entry.getKey();
// if (StringUtil.isEmpty(k)) {
// continue;
// }
// String vn = JSONResponse.formatOtherKey(k);
// if (StringUtil.isName(vn) == false) { // 通过 curObj['id@'] 这样取值,写在 IF 配置里
// continue;
// }
//
// Object v = entry.getValue();
// String vs = v instanceof String ? "\"" + ((String) v).replaceAll("\"", "\\\"") + "\""
// : (JSON.isBooleanOrNumberOrString(v) ? v.toString() : JSON.format(v));
// preCode += "\nvar " + vn + " = " + vs + ";";
// }
if (ifIsStr) {
String ifStr = (String) _if;
int ind = ifStr.indexOf(":");
String lang = ind < 0 || ind > 20 ? null : ifStr.substring(0, ind);
boolean isName = StringUtil.isName(lang);
ScriptEngine engine = getScriptEngine(isName ? lang : null);
engine.eval(preCode + "\n" + (isName ? ifStr.substring(ind + 1) : ifStr));
}
else {
for (Map.Entry<String, Object> entry : ifSet) {
String k = entry == null ? null : entry.getKey();
// if (condKeys.contains(k)) {
// throw new IllegalArgumentException("Request 表 structure 配置的 " + ON.name()
// + ":{ " + k + ":value } 中 key 不合法,不允许传 [" + StringUtil.join(condKeys.toArray(new String[]{})) + "] 中的任何一个 !");
// }
Object v = k == null ? null : entry.getValue();
if (v instanceof String) {
int ind = k.indexOf(":");
String lang = ind < 0 || ind > 20 ? null : k.substring(0, ind);
boolean isName = StringUtil.isName(lang);
ScriptEngine engine = getScriptEngine(isName ? lang : null);
k = isName ? k.substring(ind + 1) : k;
boolean isElse = StringUtil.isEmpty(k, false); // 其它直接报错,不允许传 StringUtil.isEmpty(k, true) || "ELSE".equals(k);
// String code = preCode + "\n\n" + (StringUtil.isEmpty(v, false) ? k : (isElse ? v : "if (" + k + ") {\n " + v + "\n}"));
String code = preCode + "\n\n" + (isElse ? v : "if (" + k + ") {\n " + v + "\n}");
// ScriptExecutor executor = new JavaScriptExecutor();
// executor.execute(null, real, )
engine.eval(code);
// PARSER_CREATOR.createFunctionParser()
// .setCurrentObject(real)
// .setKey(k)
// .setMethod(method)
// .invoke()
continue;
}
if (v instanceof JSONObject == false) {
throw new IllegalArgumentException("Request 表 structure 配置的 " + IF.name()
+ ":{ " + k + ":value } 中 value 不合法,必须是 JSONObject {} !");
}
if (nkl.contains(k) || real.get(k) != null) {
real = parse(method, name, (JSONObject) v, real, database, schema, datasource, idCallback, creator, callback);
}
}
}
}
Log.i(TAG, "parse return real = " + JSON.toJSONString(real));
return real;
}
public static ScriptEngine getScriptEngine(String lang) {
boolean isEmpty = StringUtil.isEmpty(lang, true);
ScriptEngine engine = isEmpty ? SCRIPT_ENGINE : SCRIPT_ENGINE_MANAGER.getEngineByName(lang);
if (engine == null) {
throw new NullPointerException("找不到可执行 " + (isEmpty ? "js" : lang) + " 脚本的引擎!engine == null!");
}
return engine;
}
/**执行操作
* @param opt
* @param targetChild
* @param real
* @param creator
* @return
* @throws Exception
*/
private static JSONObject operate(Operation opt, JSONObject targetChild
, JSONObject real, SQLCreator creator) throws Exception {
if (targetChild == null) {
return real;
}
if (real == null) {
throw new IllegalArgumentException("operate real == null!!!");
}
Set<Map.Entry<String, Object>> set = new LinkedHashSet<>(targetChild.entrySet());
for (Map.Entry<String, Object> e : set) {
String tk = e == null ? null : e.getKey();
if (tk == null || OPERATION_KEY_LIST.contains(tk)) {
continue;
}
Object tv = e.getValue();
if (opt == TYPE) {
verifyType(tk, tv, real);
}
else if (opt == VERIFY) {
verifyValue(tk, tv, real, creator);
}
else if (opt == UPDATE) {
real.put(tk, tv);
}
else {
if (real.containsKey(tk)) {
if (opt == REPLACE) {
real.put(tk, tv);
}
}
else {
if (opt == INSERT) {
real.put(tk, tv);
}
}
}
}
return real;
}
/**验证值类型
* @param tk
* @param tv {@link Operation}
* @param real
* @throws Exception
*/
public static void verifyType(@NotNull String tk, Object tv, @NotNull JSONObject real)
throws UnsupportedDataTypeException {
if (tv instanceof String == false) {
throw new UnsupportedDataTypeException("服务器内部错误," + tk + ":value 的value不合法!"
+ "Request表校验规则中 TYPE:{ key:value } 中的value只能是String类型!");
}
verifyType(tk, (String) tv, real.get(tk));
}
/**验证值类型
* @param tk
* @param tv {@link Operation}
* @param rv
* @throws Exception
*/
public static void verifyType(@NotNull String tk, @NotNull String tv, Object rv)
throws UnsupportedDataTypeException {
verifyType(tk, tv, rv, false);
}
/**验证值类型
* @param tk
* @param tv {@link Operation}
* @param rv
* @param isInArray
* @throws Exception
*/
public static void verifyType(@NotNull String tk, @NotNull String tv, Object rv, boolean isInArray)
throws UnsupportedDataTypeException {
if (rv == null) {
return;
}
if (tv.endsWith("[]")) {
verifyType(tk, "ARRAY", rv);
for (Object o : (Collection<?>) rv) {
verifyType(tk, tv.substring(0, tv.length() - 2), o, true);
}
return;
}
//这里不抽取 enum,因为 enum 不能满足扩展需求,子类需要可以自定义,而且 URL[] 这种也不符合命名要求,得用 constructor + getter + setter
switch (tv) {
case "BOOLEAN": //Boolean.parseBoolean(real.getString(tk)); 只会判断null和true
if (rv instanceof Boolean == false) { //JSONObject.getBoolean 可转换Number类型
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!类型必须是 BOOLEAN" + (isInArray ? "[] !" : " !"));
}
break;
case "NUMBER": //整数
try {
Long.parseLong(rv.toString()); //1.23会转换为1 real.getLong(tk);
} catch (Exception e) {
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!类型必须是 NUMBER" + (isInArray ? "[] !" : " !"));
}
break;
case "DECIMAL": //小数
try {
Double.parseDouble(rv.toString());
} catch (Exception e) {
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!" +
"类型必须是 DECIMAL" + (isInArray ? "[] !" : " !"));
}
break;
case "STRING":
if (rv instanceof String == false) { //JSONObject.getString 可转换任何类型
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!" +
"类型必须是 STRING" + (isInArray ? "[] !" : " !"));
}
break;
case "URL": //网址,格式为 http://www.apijson.org, https://www.google.com 等
try {
new URL((String) rv);
} catch (Exception e) {
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!" +
"类型必须是 URL" + (isInArray ? "[] !" : " !"));
}
break;
case "DATE": //日期,格式为 YYYY-MM-DD(例如 2020-02-20)的 STRING
try {
LocalDate.parse((String) rv);
} catch (Exception e) {
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!" +
"类型必须是格式为 YYYY-MM-DD(例如 2020-02-20)的 DATE" + (isInArray ? "[] !" : " !"));
}
break;
case "TIME": //时间,格式为 HH:mm:ss(例如 12:01:30)的 STRING
try {
LocalTime.parse((String) rv);
} catch (Exception e) {
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!" +
"类型必须是格式为 HH:mm:ss(例如 12:01:30)的 TIME" + (isInArray ? "[] !" : " !"));
}
break;
case "DATETIME": //日期+时间,格式为 YYYY-MM-DDTHH:mm:ss(例如 2020-02-20T12:01:30)的 STRING
try {
LocalDateTime.parse((String) rv);
} catch (Exception e) {
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!类型必须是格式为 " +
"YYYY-MM-DDTHH:mm:ss(例如 2020-02-20T12:01:30)的 DATETIME" + (isInArray ? "[] !" : " !"));
}
break;
case "OBJECT":
if (rv instanceof Map == false) { //JSONObject.getJSONObject 可转换String类型
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!" +
"类型必须是 OBJECT" + (isInArray ? "[] !" : " !") + " OBJECT 结构为 {} !");
}
break;
case "ARRAY":
if (rv instanceof Collection == false) { //JSONObject.getJSONArray 可转换String类型
throw new UnsupportedDataTypeException(tk + ":value 的value不合法!" +
"类型必须是 ARRAY" + (isInArray ? "[] !" : " !") + " ARRAY 结构为 [] !");
}
break;
//目前在业务表中还用不上,单一的类型校验已经够用
// case "JSON":
// try {
// com.alibaba.fastjson.JSON.parse(rv.toString());
// } catch (Exception e) {
// throw new UnsupportedDataTypeException(tk + ":value 的value不合法!类型必须是 JSON !"
// + "也就是 {Object}, [Array] 或 它们对应的字符串 '{Object}', '[Array]' 4种中的一个 !");
// }
// break;
default:
throw new UnsupportedDataTypeException(
"服务器内部错误,类型 " + tv + " 不合法!Request表校验规则中 TYPE:{ key:value } 中的 value 必须是"
+ " [ BOOLEAN, NUMBER, DECIMAL, STRING, URL, DATE, TIME, DATETIME, OBJECT, ARRAY ] 或它们的数组"
+ " [ BOOLEAN[], NUMBER[], DECIMAL[], STRING[], URL[], DATE[], TIME[], DATETIME[], OBJECT[], ARRAY[] ] 中的一个!");
}
}
/**验证值
* @param tk
* @param tv
* @param real
* @param creator
* @throws Exception
*/
private static void verifyValue(@NotNull String tk, @NotNull Object tv, @NotNull JSONObject real, SQLCreator creator) throws Exception {
if (tv == null) {
throw new IllegalArgumentException("operate operate == VERIFY " + tk + ":" + tv + " , >> tv == null!!!");
}
String rk;
Object rv;
Logic logic;
if (tk.endsWith("$")) { // 模糊搜索
verifyCondition("$", real, tk, tv, creator);
}
else if (tk.endsWith("~")) { // 正则匹配
logic = new Logic(tk.substring(0, tk.length() - 1));
rk = logic.getKey();
rv = real.get(rk);
if (rv == null) {
return;
}
JSONArray array = AbstractSQLConfig.newJSONArray(tv);
boolean m;
boolean isOr = false;
Pattern reg;
for (Object r : array) {
if (r instanceof String == false) {
throw new UnsupportedDataTypeException(rk + ":" + rv + " 中value只支持 String 或 [String] 类型!");
}
reg = COMPILE_MAP.get(r);
if (reg == null) {
reg = Pattern.compile((String) r);
}
m = reg.matcher("" + rv).matches();
if (m) {
if (logic.isNot()) {
throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !");
}
if (logic.isOr()) {
isOr = true;
break;
}
} else {
if (logic.isAnd()) {
throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !");
}
}
}
if (isOr == false && logic.isOr()) {
throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !");
}
}
else if (tk.endsWith("{}")) { //rv符合tv条件或在tv内
if (tv instanceof String) {//TODO >= 0, < 10
verifyCondition("{}", real, tk, tv, creator);
}
else if (tv instanceof JSONArray) {
logic = new Logic(tk.substring(0, tk.length() - 2));
rk = logic.getKey();
rv = real.get(rk);
if (rv == null) {
return;
}
if (((JSONArray) tv).contains(rv) == logic.isNot()) {
throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !");
}
}
else {
throw new UnsupportedDataTypeException("服务器Request表verify配置错误!");
}
}
else if (tk.endsWith("{L}")) { //字符串长度
if (tv instanceof String) {
logic = new Logic(tk.substring(0, tk.length() - 3));
rk = logic.getKey();
rv = real.get(rk);
if (rv == null) {
return;
}
String[] tvs = tv.toString().split(",");
for (String tvItem : tvs) {
if (!verifyRV(tvItem,rv.toString())) {
throw new IllegalArgumentException(rk + ":value 中value长度不合法!必须匹配 " + tk + ":" + tv + " !");
}
}
}
else {
throw new UnsupportedDataTypeException("服务器Request表verify配置错误!");
}
}
else if (tk.endsWith("<>")) { //rv包含tv内的值
logic = new Logic(tk.substring(0, tk.length() - 2));
rk = logic.getKey();
rv = real.get(rk);
if (rv == null) {
return;
}
if (rv instanceof JSONArray == false) {
throw new UnsupportedDataTypeException("服务器Request表verify配置错误!");
}
JSONArray array = AbstractSQLConfig.newJSONArray(tv);
boolean isOr = false;
for (Object o : array) {
if (((JSONArray) rv).contains(o)) {
if (logic.isNot()) {
throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !");
}
if (logic.isOr()) {
isOr = true;
break;
}
} else {
if (logic.isAnd()) {
throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !");
}
}
}
if (isOr == false && logic.isOr()) {
throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !");
}
}
else {
throw new IllegalArgumentException("服务器Request表verify配置错误!");
}
}
/**
* 校验字符串长度
*
* @param rule 规则
* @param content 内容
* @return
* @throws UnsupportedDataTypeException
*/
private static boolean verifyRV(String rule,String content) throws UnsupportedDataTypeException {
String first = null;
String second = null;
Matcher matcher = VERIFY_LENGTH_PATTERN.matcher(rule);
while (matcher.find()) {
first = StringUtil.isEmpty(first)?matcher.group("first"):first;
second = StringUtil.isEmpty(second)?matcher.group("second"):second;
}
// first和second为空表示规则不合法
if(StringUtil.isEmpty(first) || StringUtil.isEmpty(second)){
throw new UnsupportedDataTypeException("服务器Request表verify配置错误!");
}
int secondNum = Integer.parseInt(second);
switch (Objects.requireNonNull(first)){
case ">":
return content.length() > secondNum;
case ">=":
return content.length() >= secondNum;
case "<":
return content.length() < secondNum;
case "<=":
return content.length() <= secondNum;
case "<>":
return content.length() != secondNum;
default:
}
// 出现不能识别的符号也认为规则不合法
throw new UnsupportedDataTypeException("服务器Request表verify配置错误!");
}
/**通过数据库执行SQL语句来验证条件
* @param funChar
* @param real
* @param tk
* @param tv
* @param creator
* @throws Exception
*/
private static void verifyCondition(@NotNull String funChar, @NotNull JSONObject real, @NotNull String tk, @NotNull Object tv
, @NotNull SQLCreator creator) throws Exception {
//不能用Parser, 0 这种不符合 StringUtil.isName !
Logic logic = new Logic(tk.substring(0, tk.length() - funChar.length()));
String rk = logic.getKey();
Object rv = real.get(rk);
if (rv == null) {
return;
}
if (rv instanceof String && ((String) rv).contains("'")) { // || key.contains("#") || key.contains("--")) {
throw new IllegalArgumentException(rk + ":value 中value不合法!value 中不允许有单引号 ' !");
}
SQLConfig config = creator.createSQLConfig().setMethod(RequestMethod.GET).setCount(1).setPage(0);
config.setTest(true);
// config.setTable(Test.class.getSimpleName());
// config.setColumn(rv + logic.getChar() + funChar)
// 字符串可能 SQL 注入,目前的解决方式是加 TYPE 校验类型或者干脆不用 sqlVerify,而是通过远程函数来校验
config.putWhere(rv + logic.getChar() + funChar, tv, false);
config.setCount(1);
SQLExecutor executor = creator.createSQLExecutor();
JSONObject result = null;
try {
result = executor.execute(config, false);
} finally {
executor.close();
}
if (result != null && JSONResponse.isExist(result.getIntValue(JSONResponse.KEY_COUNT)) == false) {
throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 '" + tk + "': '" + tv + "' !");
}
}
/**验证是否存在
* @param table
* @param key
* @param value
* @throws Exception
*/
public static void verifyExist(String table, String key, Object value, long exceptId, @NotNull SQLCreator creator) throws Exception {
if (key == null || value == null) {
Log.e(TAG, "verifyExist key == null || value == null >> return;");
return;
}
if (value instanceof JSON) {
throw new UnsupportedDataTypeException(key + ":value 中value的类型不能为JSON!");
}
Map<String,Object> map = new HashMap<>();
map.put(key,value);
verifyExist(table,map,exceptId,creator);
}
/**验证是否存在
* @param table
* @param param
* @throws Exception
*/
public static void verifyExist(String table, Map<String,Object> param, long exceptId, @NotNull SQLCreator creator) throws Exception {
if (param.isEmpty()) {
Log.e(TAG, "verifyExist is empty >> return;");
return;
}
SQLConfig config = creator.createSQLConfig().setMethod(RequestMethod.HEAD).setCount(1).setPage(0);
config.setTable(table);
param.forEach((key,value) -> config.putWhere(key, value, false));
SQLExecutor executor = creator.createSQLExecutor();
try {
JSONObject result = executor.execute(config, false);
if (result == null) {
throw new Exception("服务器内部错误 verifyExist result == null");
}
if (result.getIntValue(JSONResponse.KEY_COUNT) <= 0) {
StringBuilder sb = new StringBuilder();
param.forEach((key,value) -> sb.append("key:").append(key).append(" value:").append(value).append(" "));
throw new ConflictException(sb + "的数据不存在!如果必要请先创建!");
}
} finally {
executor.close();
}
}
/**验证是否重复
* @param table
* @param key
* @param value
* @throws Exception
*/
public static void verifyRepeat(String table, String key, Object value, @NotNull SQLCreator creator) throws Exception {
verifyRepeat(table, key, value, 0, creator);
}
/**验证是否重复
* @param table
* @param key
* @param value
* @param exceptId 不包含id
* @throws Exception
*/
public static void verifyRepeat(String table, String key, Object value, long exceptId, @NotNull SQLCreator creator) throws Exception {
verifyRepeat(table, key, value, exceptId, null, creator);
}
/**验证是否重复
* TODO 与 AbstractVerifier.verifyRepeat 代码重复,需要简化
* @param table
* @param key
* @param value
* @param exceptId 不包含id
* @param idKey
* @param creator
* @throws Exception
*/
public static void verifyRepeat(String table, String key, Object value
, long exceptId, String idKey, @NotNull SQLCreator creator) throws Exception {
if (key == null || value == null) {
Log.e(TAG, "verifyRepeat key == null || value == null >> return;");
return;
}
if (value instanceof JSON) {
throw new UnsupportedDataTypeException(key + ":value 中value的类型不能为JSON!");
}
Map<String,Object> map = new HashMap<>();
map.put(key,value);
verifyRepeat(table,map,exceptId,idKey,creator);
}
/**验证是否重复
* TODO 与 AbstractVerifier.verifyRepeat 代码重复,需要简化
* @param table
* @param param
* @param exceptId 不包含id
* @param idKey
* @param creator
* @throws Exception
*/
public static void verifyRepeat(String table, Map<String,Object> param, long exceptId, String idKey, @NotNull SQLCreator creator) throws Exception {
if (param.isEmpty()) {
Log.e(TAG, "verifyRepeat is empty >> return;");
return;
}
String finalIdKey = StringUtil.isEmpty(idKey, false) ? apijson.JSONObject.KEY_ID : idKey;
SQLConfig config = creator.createSQLConfig().setMethod(RequestMethod.HEAD).setCount(1).setPage(0);
config.setTable(table);
if (exceptId > 0) { //允许修改自己的属性为该属性原来的值
config.putWhere(finalIdKey + "!", exceptId, false);
}
param.forEach((key,value) -> config.putWhere(key,value, false));
SQLExecutor executor = creator.createSQLExecutor();
try {
JSONObject result = executor.execute(config, false);
if (result == null) {
throw new Exception("服务器内部错误 verifyRepeat result == null");
}
if (result.getIntValue(JSONResponse.KEY_COUNT) > 0) {
StringBuilder sb = new StringBuilder();
param.forEach((key,value) -> sb.append("key:").append(key).append(" value:").append(value).append(" "));
throw new ConflictException(sb + "的数据已经存在,不能重复!");
}
} finally {
executor.close();
}
}
public static String getCacheKeyForRequest(String method, String tag) {
return method + "/" + tag;
}
}
| Tencent/APIJSON | APIJSONORM/src/main/java/apijson/orm/AbstractVerifier.java |
440 | package com.alibaba.otter.canal.common.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 多线程执行器模板代码,otter中好多地方都写多线程,比较多的都是重复的逻辑代码,抽象一下做个模板把
*
* <pre>
* 示例代码:
* ExecutorTemplate template = new ExecutorTemplate(executor);
* ...
* try {
* for ( ....) {
* template.submit(new Runnable() {})
* }
*
* List<?> result = template.waitForResult();
* // do result
* } finally {
* template.clear();
* }
*
* 注意:该模板工程,不支持多业务并发调用,会出现数据混乱
* </pre>
*/
public class ExecutorTemplate {
private volatile ThreadPoolExecutor executor = null;
private volatile List<Future> futures = null;
public ExecutorTemplate(ThreadPoolExecutor executor){
this.futures = Collections.synchronizedList(new ArrayList<>());
this.executor = executor;
}
public void submit(Runnable task) {
Future future = executor.submit(task, null);
futures.add(future);
check(future);
}
public void submit(Callable task) {
Future future = executor.submit(task);
futures.add(future);
check(future);
}
private void check(Future future) {
if (future.isDone()) {
// 立即判断一次,因为使用了CallerRun可能当场跑出结果,针对有异常时快速响应,而不是等跑完所有的才抛异常
try {
future.get();
} catch (Throwable e) {
// 取消完之后立马退出
cacelAllFutures();
throw new RuntimeException(e);
}
}
}
public synchronized List<?> waitForResult() {
List result = new ArrayList();
RuntimeException exception = null;
for (Future future : futures) {
try {
result.add(future.get());
} catch (Throwable e) {
exception = new RuntimeException(e);
// 如何一个future出现了异常,就退出
break;
}
}
if (exception != null) {
cacelAllFutures();
throw exception;
} else {
return result;
}
}
public void cacelAllFutures() {
for (Future future : futures) {
if (!future.isDone() && !future.isCancelled()) {
future.cancel(true);
}
}
}
public void clear() {
futures.clear();
}
}
| alibaba/canal | common/src/main/java/com/alibaba/otter/canal/common/utils/ExecutorTemplate.java |
442 | package org.nlpcn.es4sql.parse;
import com.alibaba.druid.sql.ast.SQLCommentHint;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLLimit;
import com.alibaba.druid.sql.ast.SQLOrderBy;
import com.alibaba.druid.sql.ast.SQLOrderingSpecification;
import com.alibaba.druid.sql.ast.expr.SQLCaseExpr;
import com.alibaba.druid.sql.ast.expr.SQLCharExpr;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.expr.SQLListExpr;
import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource;
import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause;
import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
import com.alibaba.druid.sql.ast.statement.SQLSelectOrderByItem;
import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock;
import com.alibaba.druid.sql.ast.statement.SQLTableSource;
import com.alibaba.druid.sql.ast.statement.SQLUnionQuery;
import com.alibaba.druid.sql.dialect.mysql.ast.expr.MySqlOrderingExpr;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDeleteStatement;
import org.elasticsearch.search.sort.ScriptSortBuilder;
import org.nlpcn.es4sql.domain.Condition;
import org.nlpcn.es4sql.domain.Delete;
import org.nlpcn.es4sql.domain.Field;
import org.nlpcn.es4sql.domain.From;
import org.nlpcn.es4sql.domain.JoinSelect;
import org.nlpcn.es4sql.domain.MethodField;
import org.nlpcn.es4sql.domain.Query;
import org.nlpcn.es4sql.domain.Select;
import org.nlpcn.es4sql.domain.TableOnJoinSelect;
import org.nlpcn.es4sql.domain.Where;
import org.nlpcn.es4sql.domain.hints.Hint;
import org.nlpcn.es4sql.domain.hints.HintFactory;
import org.nlpcn.es4sql.exception.SqlParseException;
import org.nlpcn.es4sql.query.multi.MultiQuerySelect;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* es sql support
*
* @author ansj
*/
public class SqlParser {
public SqlParser() {
}
public Select parseSelect(SQLQueryExpr mySqlExpr) throws SqlParseException {
SQLSelectQueryBlock query = (SQLSelectQueryBlock) mySqlExpr.getSubQuery().getQuery();
Select select = parseSelect(query);
return select;
}
/**
* zhongshu-comment 在访问AST里面的子句、token
* @param query
* @return
* @throws SqlParseException
*/
public Select parseSelect(SQLSelectQueryBlock query) throws SqlParseException {
Select select = new Select();
/*zhongshu-comment SqlParser类没有成员变量,里面全是方法,所以将this传到WhereParser对象时是无状态的,
即SqlParser对象并没有给WhereParser传递任何属性,也不存在WhereParser修改SqlParser的成员变量值这一说
WhereParser只是单纯想调用SqlParser的方法而已
*/
WhereParser whereParser = new WhereParser(this, query);
/*
zhongshu-comment 例如sql:select a,sum(b),case when c='a' then 1 else 2 end as my_c from tbl,
那findSelect()就是解析这一部分了:a,sum(b),case when c='a' then 1 else 2 end as my_c
*/
findSelect(query, select, query.getFrom().getAlias()); //zhongshu-comment 看过
select.getFrom().addAll(findFrom(query.getFrom())); //zhongshu-comment 看过
select.setWhere(whereParser.findWhere()); //zhongshu-comment 看过
//zhongshu-comment 这个应该是针对where子查询的,而不是from子查询,貌似又不是解析from子查询的,报错了
//zhongshu-comment 也许es本身就不支持子查询,所以es-sql就没实现,那这个fillSubQueries是什么啊??
//todo 看不懂,测试了好几个常见的sql,都没有进去该方法,那就先不理了,看别的
select.fillSubQueries();
//zhongshu-comment 解析sql语句中的注释:select /*! USE_SCROLL(10,120000) */ * FROM spark_es_table
//hint单词的意思是提示,即sql中的注释内容
// /* 和 */之间是sql的注释内容,这是sql本身的语法,然后sql解析器会将注释块之间的内容“! USE_SCROLL(10,120000) ”抽取出来
// ! USE_SCROLL是es-sql自己定义的一套规则,
// 在不增加mysql原有语法的情况下,利用注释来灵活地扩展es-sql的功能,这样就能使用druid的mysql语法解析器了,无需自己实现
// 注意:!叹号和USE_SCROLL之间要空且只能空一格
select.getHints().addAll(parseHints(query.getHints()));
findLimit(query.getLimit(), select);
//zhongshu-comment 和那个_score有关
findOrderBy(query, select); //zhongshu-comment 还没看
findGroupBy(query, select); //zhongshu-comment aggregations
return select;
}
public Delete parseDelete(SQLDeleteStatement deleteStatement) throws SqlParseException {
Delete delete = new Delete();
WhereParser whereParser = new WhereParser(this, deleteStatement);
delete.getFrom().addAll(findFrom(deleteStatement.getTableSource()));
delete.setWhere(whereParser.findWhere());
delete.getHints().addAll(parseHints(((MySqlDeleteStatement) deleteStatement).getHints()));
findLimit(((MySqlDeleteStatement) deleteStatement).getLimit(), delete);
return delete;
}
public MultiQuerySelect parseMultiSelect(SQLUnionQuery query) throws SqlParseException {
Select firstTableSelect = this.parseSelect((SQLSelectQueryBlock) query.getLeft());
Select secondTableSelect = this.parseSelect((SQLSelectQueryBlock) query.getRight());
return new MultiQuerySelect(query.getOperator(),firstTableSelect,secondTableSelect);
}
private void findSelect(SQLSelectQueryBlock query, Select select, String tableAlias) throws SqlParseException {
List<SQLSelectItem> selectList = query.getSelectList();
for (SQLSelectItem sqlSelectItem : selectList) {
Field field = FieldMaker.makeField(sqlSelectItem.getExpr(), sqlSelectItem.getAlias(), tableAlias);
select.addField(field);
}
}
private void findGroupBy(SQLSelectQueryBlock query, Select select) throws SqlParseException {
SQLSelectGroupByClause groupBy = query.getGroupBy();
//modified by xzb group by 增加Having语法
if (null != query.getGroupBy() && null != query.getGroupBy().getHaving()) {
select.setHaving(query.getGroupBy().getHaving().toString());
}
SQLTableSource sqlTableSource = query.getFrom();
if (groupBy == null) {
return;
}
List<SQLExpr> items = groupBy.getItems();
List<SQLExpr> standardGroupBys = new ArrayList<>();
for (SQLExpr sqlExpr : items) {
//todo: mysql expr patch
if (sqlExpr instanceof MySqlOrderingExpr) {
MySqlOrderingExpr sqlSelectGroupByExpr = (MySqlOrderingExpr) sqlExpr;
sqlExpr = sqlSelectGroupByExpr.getExpr();
}
if ((sqlExpr instanceof SQLParensIdentifierExpr || !(sqlExpr instanceof SQLIdentifierExpr || sqlExpr instanceof SQLMethodInvokeExpr)) && !standardGroupBys.isEmpty()) {
// flush the standard group bys
// zhongshu-comment 先将standardGroupBys里面的字段传到select对象的groupBys字段中,然后给standardGroupBys分配一个没有元素的新的list
select.addGroupBy(convertExprsToFields(standardGroupBys, sqlTableSource));
standardGroupBys = new ArrayList<>();
}
if (sqlExpr instanceof SQLParensIdentifierExpr) {
// single item with parens (should get its own aggregation)
select.addGroupBy(FieldMaker.makeField(((SQLParensIdentifierExpr) sqlExpr).getExpr(), null, sqlTableSource.getAlias()));
} else if (sqlExpr instanceof SQLListExpr) {
// multiple items in their own list
SQLListExpr listExpr = (SQLListExpr) sqlExpr;
select.addGroupBy(convertExprsToFields(listExpr.getItems(), sqlTableSource));
} else {
// everything else gets added to the running list of standard group bys
standardGroupBys.add(sqlExpr);
}
}
if (!standardGroupBys.isEmpty()) {
select.addGroupBy(convertExprsToFields(standardGroupBys, sqlTableSource));
}
}
private List<Field> convertExprsToFields(List<? extends SQLExpr> exprs, SQLTableSource sqlTableSource) throws SqlParseException {
List<Field> fields = new ArrayList<>(exprs.size());
for (SQLExpr expr : exprs) {
//here we suppose groupby field will not have alias,so set null in second parameter
//zhongshu-comment case when 有别名过不了语法解析,没有别名执行下面语句会报空指针
fields.add(FieldMaker.makeField(expr, null, sqlTableSource.getAlias()));
}
return fields;
}
private String sameAliasWhere(Where where, String... aliases) throws SqlParseException {
if (where == null) return null;
if (where instanceof Condition) {
Condition condition = (Condition) where;
String fieldName = condition.getName();
for (String alias : aliases) {
String prefix = alias + ".";
if (fieldName.startsWith(prefix)) {
return alias;
}
}
throw new SqlParseException(String.format("fieldName : %s on codition:%s does not contain alias", fieldName, condition.toString()));
}
List<String> sameAliases = new ArrayList<>();
if (where.getWheres() != null && where.getWheres().size() > 0) {
for (Where innerWhere : where.getWheres())
sameAliases.add(sameAliasWhere(innerWhere, aliases));
}
if (sameAliases.contains(null)) return null;
String firstAlias = sameAliases.get(0);
//return null if more than one alias
for (String alias : sameAliases) {
if (!alias.equals(firstAlias)) return null;
}
return firstAlias;
}
private void findOrderBy(SQLSelectQueryBlock query, Select select) throws SqlParseException {
SQLOrderBy orderBy = query.getOrderBy();
if (orderBy == null) {
return;
}
List<SQLSelectOrderByItem> items = orderBy.getItems();
addOrderByToSelect(select, items, null);
}
private void addOrderByToSelect(Select select, List<SQLSelectOrderByItem> items, String alias) throws SqlParseException {
for (SQLSelectOrderByItem sqlSelectOrderByItem : items) {
SQLExpr expr = sqlSelectOrderByItem.getExpr();
Field f = FieldMaker.makeField(expr, null, null);
String orderByName = f.toString();
Object missing = null;
String unmappedType = null;
String numericType = null;
String format = null;
if ("field_sort".equals(f.getName())) {
Map<String, Object> params = ((MethodField) f).getParamsAsMap();
for (Map.Entry<String, Object> entry : params.entrySet()) {
switch (entry.getKey()) {
case "field": orderByName = entry.getValue().toString(); break;
case "missing": missing = entry.getValue(); break;
case "unmapped_type": unmappedType = entry.getValue().toString(); break;
case "numeric_type": numericType = entry.getValue().toString(); break;
case "format": format = entry.getValue().toString(); break;
}
}
}
if (sqlSelectOrderByItem.getType() == null) {
sqlSelectOrderByItem.setType(SQLOrderingSpecification.ASC); //zhongshu-comment 默认是升序排序
}
String type = sqlSelectOrderByItem.getType().toString();
orderByName = orderByName.replace("`", "");
if (alias != null) orderByName = orderByName.replaceFirst(alias + "\\.", "");
ScriptSortBuilder.ScriptSortType scriptSortType = judgeIsStringSort(expr);
select.addOrderBy(f.getNestedPath(), orderByName, type, scriptSortType, missing, unmappedType, numericType, format);
}
}
private ScriptSortBuilder.ScriptSortType judgeIsStringSort(SQLExpr expr) {
if (expr instanceof SQLCaseExpr) {
List<SQLCaseExpr.Item> itemList = ((SQLCaseExpr) expr).getItems();
for (SQLCaseExpr.Item item : itemList) {
if (item.getValueExpr() instanceof SQLCharExpr) {
return ScriptSortBuilder.ScriptSortType.STRING;
}
}
}
return ScriptSortBuilder.ScriptSortType.NUMBER;
}
private void findLimit(SQLLimit limit, Query query) {
if (limit == null) {
return;
}
query.setRowCount(Integer.parseInt(limit.getRowCount().toString()));
if (limit.getOffset() != null)
query.setOffset(Integer.parseInt(limit.getOffset().toString()));
}
/**
* Parse the from clause
* zhongshu-comment 只解析了一般查询和join查询,没有解析子查询
* @param from the from clause.
* @return list of From objects represents all the sources.
*/
private List<From> findFrom(SQLTableSource from) {
//zhongshu-comment class1.isAssignableFrom(class2) class2是不是class1的子类或者子接口
//改成用instanceof 应该也行吧:from instanceof SQLExprTableSource
boolean isSqlExprTable = from.getClass().isAssignableFrom(SQLExprTableSource.class);
if (isSqlExprTable) {
SQLExprTableSource fromExpr = (SQLExprTableSource) from;
String[] split = fromExpr.getExpr().toString().split(",");
ArrayList<From> fromList = new ArrayList<>();
for (String source : split) {
fromList.add(new From(source.trim(), fromExpr.getAlias()));
}
return fromList;
}
SQLJoinTableSource joinTableSource = ((SQLJoinTableSource) from);
List<From> fromList = new ArrayList<>();
fromList.addAll(findFrom(joinTableSource.getLeft()));
fromList.addAll(findFrom(joinTableSource.getRight()));
return fromList;
}
public JoinSelect parseJoinSelect(SQLQueryExpr sqlExpr) throws SqlParseException {
SQLSelectQueryBlock query = (SQLSelectQueryBlock) sqlExpr.getSubQuery().getQuery();
List<From> joinedFrom = findJoinedFrom(query.getFrom());
if (joinedFrom.size() != 2)
throw new RuntimeException("currently supports only 2 tables join");
JoinSelect joinSelect = createBasicJoinSelectAccordingToTableSource((SQLJoinTableSource) query.getFrom());
List<Hint> hints = parseHints(query.getHints());
joinSelect.setHints(hints);
String firstTableAlias = joinedFrom.get(0).getAlias();
String secondTableAlias = joinedFrom.get(1).getAlias();
Map<String, Where> aliasToWhere = splitAndFindWhere(query.getWhere(), firstTableAlias, secondTableAlias);
Map<String, List<SQLSelectOrderByItem>> aliasToOrderBy = splitAndFindOrder(query.getOrderBy(), firstTableAlias, secondTableAlias);
List<Condition> connectedConditions = getConditionsFlatten(joinSelect.getConnectedWhere());
joinSelect.setConnectedConditions(connectedConditions);
fillTableSelectedJoin(joinSelect.getFirstTable(), query, joinedFrom.get(0), aliasToWhere.get(firstTableAlias), aliasToOrderBy.get(firstTableAlias), connectedConditions);
fillTableSelectedJoin(joinSelect.getSecondTable(), query, joinedFrom.get(1), aliasToWhere.get(secondTableAlias), aliasToOrderBy.get(secondTableAlias), connectedConditions);
updateJoinLimit(query.getLimit(), joinSelect);
//todo: throw error feature not supported: no group bys on joins ?
return joinSelect;
}
private Map<String, List<SQLSelectOrderByItem>> splitAndFindOrder(SQLOrderBy orderBy, String firstTableAlias, String secondTableAlias) throws SqlParseException {
Map<String, List<SQLSelectOrderByItem>> aliasToOrderBys = new HashMap<>();
aliasToOrderBys.put(firstTableAlias, new ArrayList<SQLSelectOrderByItem>());
aliasToOrderBys.put(secondTableAlias, new ArrayList<SQLSelectOrderByItem>());
if (orderBy == null) return aliasToOrderBys;
List<SQLSelectOrderByItem> orderByItems = orderBy.getItems();
for (SQLSelectOrderByItem orderByItem : orderByItems) {
if (orderByItem.getExpr().toString().startsWith(firstTableAlias + ".")) {
aliasToOrderBys.get(firstTableAlias).add(orderByItem);
} else if (orderByItem.getExpr().toString().startsWith(secondTableAlias + ".")) {
aliasToOrderBys.get(secondTableAlias).add(orderByItem);
} else
throw new SqlParseException("order by field on join request should have alias before, got " + orderByItem.getExpr().toString());
}
return aliasToOrderBys;
}
private void updateJoinLimit(SQLLimit limit, JoinSelect joinSelect) {
if (limit != null && limit.getRowCount() != null) {
int sizeLimit = Integer.parseInt(limit.getRowCount().toString());
joinSelect.setTotalLimit(sizeLimit);
}
}
private List<Hint> parseHints(List<SQLCommentHint> sqlHints) throws SqlParseException {
List<Hint> hints = new ArrayList<>();
for (SQLCommentHint sqlHint : sqlHints) {
Hint hint = HintFactory.getHintFromString(sqlHint.getText());
if (hint != null) hints.add(hint);
}
return hints;
}
private JoinSelect createBasicJoinSelectAccordingToTableSource(SQLJoinTableSource joinTableSource) throws SqlParseException {
JoinSelect joinSelect = new JoinSelect();
if (joinTableSource.getCondition() != null) {
Where where = Where.newInstance();
WhereParser whereParser = new WhereParser(this, joinTableSource.getCondition());
whereParser.parseWhere(joinTableSource.getCondition(), where);
joinSelect.setConnectedWhere(where);
}
SQLJoinTableSource.JoinType joinType = joinTableSource.getJoinType();
joinSelect.setJoinType(joinType);
return joinSelect;
}
private Map<String, Where> splitAndFindWhere(SQLExpr whereExpr, String firstTableAlias, String secondTableAlias) throws SqlParseException {
WhereParser whereParser = new WhereParser(this, whereExpr);
Where where = whereParser.findWhere();
return splitWheres(where, firstTableAlias, secondTableAlias);
}
private void fillTableSelectedJoin(TableOnJoinSelect tableOnJoin, SQLSelectQueryBlock query, From tableFrom, Where where, List<SQLSelectOrderByItem> orderBys, List<Condition> conditions) throws SqlParseException {
String alias = tableFrom.getAlias();
fillBasicTableSelectJoin(tableOnJoin, tableFrom, where, orderBys, query);
tableOnJoin.setConnectedFields(getConnectedFields(conditions, alias));
tableOnJoin.setSelectedFields(new ArrayList<Field>(tableOnJoin.getFields()));
tableOnJoin.setAlias(alias);
tableOnJoin.fillSubQueries();
}
private List<Field> getConnectedFields(List<Condition> conditions, String alias) throws SqlParseException {
List<Field> fields = new ArrayList<>();
String prefix = alias + ".";
for (Condition condition : conditions) {
if (condition.getName().startsWith(prefix)) {
fields.add(new Field(condition.getName().replaceFirst(prefix, ""), null));
} else {
if (!((condition.getValue() instanceof SQLPropertyExpr) || (condition.getValue() instanceof SQLIdentifierExpr) || (condition.getValue() instanceof String))) {
throw new SqlParseException("conditions on join should be one side is firstTable second Other , condition was:" + condition.toString());
}
String aliasDotValue = condition.getValue().toString();
int indexOfDot = aliasDotValue.indexOf(".");
String owner = aliasDotValue.substring(0, indexOfDot);
if (owner.equals(alias))
fields.add(new Field(aliasDotValue.substring(indexOfDot + 1), null));
}
}
return fields;
}
private void fillBasicTableSelectJoin(TableOnJoinSelect select, From from, Where where, List<SQLSelectOrderByItem> orderBys, SQLSelectQueryBlock query) throws SqlParseException {
select.getFrom().add(from);
findSelect(query, select, from.getAlias());
select.setWhere(where);
addOrderByToSelect(select, orderBys, from.getAlias());
}
private List<Condition> getJoinConditionsFlatten(SQLJoinTableSource from) throws SqlParseException {
List<Condition> conditions = new ArrayList<>();
if (from.getCondition() == null) return conditions;
Where where = Where.newInstance();
WhereParser whereParser = new WhereParser(this, from.getCondition());
whereParser.parseWhere(from.getCondition(), where);
addIfConditionRecursive(where, conditions);
return conditions;
}
private List<Condition> getConditionsFlatten(Where where) throws SqlParseException {
List<Condition> conditions = new ArrayList<>();
if (where == null) return conditions;
addIfConditionRecursive(where, conditions);
return conditions;
}
private Map<String, Where> splitWheres(Where where, String... aliases) throws SqlParseException {
Map<String, Where> aliasToWhere = new HashMap<>();
for (String alias : aliases) {
aliasToWhere.put(alias, null);
}
if (where == null) return aliasToWhere;
String allWhereFromSameAlias = sameAliasWhere(where, aliases);
if (allWhereFromSameAlias != null) {
removeAliasPrefix(where, allWhereFromSameAlias);
aliasToWhere.put(allWhereFromSameAlias, where);
return aliasToWhere;
}
for (Where innerWhere : where.getWheres()) {
String sameAlias = sameAliasWhere(innerWhere, aliases);
if (sameAlias == null)
throw new SqlParseException("Currently support only one hierarchy on different tables where");
removeAliasPrefix(innerWhere, sameAlias);
Where aliasCurrentWhere = aliasToWhere.get(sameAlias);
if (aliasCurrentWhere == null) {
aliasToWhere.put(sameAlias, innerWhere);
} else {
Where andWhereContainer = Where.newInstance();
andWhereContainer.addWhere(aliasCurrentWhere);
andWhereContainer.addWhere(innerWhere);
aliasToWhere.put(sameAlias, andWhereContainer);
}
}
return aliasToWhere;
}
private void removeAliasPrefix(Where where, String alias) {
if (where instanceof Condition) {
Condition cond = (Condition) where;
String fieldName = cond.getName();
String aliasPrefix = alias + ".";
cond.setName(cond.getName().replaceFirst(aliasPrefix, ""));
return;
}
for (Where innerWhere : where.getWheres()) {
removeAliasPrefix(innerWhere, alias);
}
}
private void addIfConditionRecursive(Where where, List<Condition> conditions) throws SqlParseException {
if (where instanceof Condition) {
Condition cond = (Condition) where;
if (!((cond.getValue() instanceof SQLIdentifierExpr) || (cond.getValue() instanceof SQLPropertyExpr) || (cond.getValue() instanceof String))) {
throw new SqlParseException("conditions on join should be one side is secondTable OPEAR firstTable, condition was:" + cond.toString());
}
conditions.add(cond);
}
for (Where innerWhere : where.getWheres()) {
addIfConditionRecursive(innerWhere, conditions);
}
}
private List<From> findJoinedFrom(SQLTableSource from) {
SQLJoinTableSource joinTableSource = ((SQLJoinTableSource) from);
List<From> fromList = new ArrayList<>();
fromList.addAll(findFrom(joinTableSource.getLeft()));
fromList.addAll(findFrom(joinTableSource.getRight()));
return fromList;
}
}
| NLPchina/elasticsearch-sql | src/main/java/org/nlpcn/es4sql/parse/SqlParser.java |
445 |
/**
* @author Anonymous
* @since 2019/11/22
*/
/*
* public class ListNode { int val; ListNode next = null;
*
* ListNode(int val) { this.val = val; } }
*/
public class Solution {
/**
* 求链表环的入口,若没有环,返回null
*
* @param pHead 链表头
* @return 环的入口点
*/
public ListNode EntryNodeOfLoop(ListNode pHead) {
if (pHead == null || pHead.next == null) {
return null;
}
ListNode fast = pHead;
ListNode slow = pHead;
boolean flag = false;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
flag = true;
break;
}
}
// 快指针与慢指针没有相遇,说明无环,返回 null
if (!flag) {
return null;
}
ListNode cur = slow.next;
// 求出环中结点个数
int cnt = 1;
while (cur != slow) {
cur = cur.next;
++cnt;
}
// 指针p1先走cnt步
ListNode p1 = pHead;
for (int i = 0; i < cnt; ++i) {
p1 = p1.next;
}
// p2指向链表头,然后p1/p2同时走,首次相遇的地方就是环的入口
ListNode p2 = pHead;
while (p1 != p2) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
} | geekxh/hello-algorithm | 算法读物/剑指offer/23_EntryNodeInListLoop/Solution.java |
446 | /**
* @author mcrwayfun
* @version v1.0
* @date Created in 2019/02/05
* @description
*/
class Solution {
public ArrayList<Integer> maxInWindows(int[] num, int size) {
ArrayList<Integer> reList = new ArrayList<>();
if (num == null || num.length < size || size < 1) {
return reList;
}
Deque<Integer> deque = new LinkedList<>();
for (int i = 0; i < num.length; i++) {
// 队尾元素比要入队的元素小,则把其移除(因为不可能成为窗口最大值)
while (!deque.isEmpty() && num[deque.getLast()] <= num[i]) {
deque.pollLast();
}
// 队首下标对应的元素不在窗口内(即窗口最大值),将其从队列中移除
while (!deque.isEmpty() && (i - deque.getFirst() + 1 > size)) {
deque.pollFirst();
}
// 把每次滑动的值加入到队列中
deque.add(i);
// 滑动窗口的首地址i大于size就写入窗口最大值
if (!deque.isEmpty() && i + 1 >= size) {
reList.add(num[deque.getFirst()]);
}
}
return reList;
}
} | geekxh/hello-algorithm | 算法读物/剑指offer/59_01_MaxInSlidingWindow/Solution.java |
447 |
/**
* @author Anonymous
* @since 2019/10/30
*/
public class Solution {
/**
* 获取旋转数组的最小元素
* @param array 旋转数组
* @return 数组中的最小值
*/
public int minNumberInRotateArray(int[] array) {
if (array == null || array.length == 0) {
return 0;
}
int p = 0;
// mid初始为p,为了兼容当数组是递增数组(即不满足 array[p] >= array[q])时,返回 array[p]
int mid = p;
int q = array.length - 1;
while (array[p] >= array[q]) {
if (q - p == 1) {
// 当p,q相邻时(距离为1),那么q指向的元素就是最小值
mid = q;
break;
}
mid = p + ((q - p) >> 1);
// 当p,q,mid指向的值相等时,此时只能通过遍历查找最小值
if (array[p] == array[q] && array[mid] == array[p]) {
mid = getMinIndex(array, p, q);
break;
}
if (array[mid] >= array[p]) {
p = mid;
} else if (array[mid] <= array[q]) {
q = mid;
}
}
return array[mid];
}
private int getMinIndex(int[] array, int p, int q) {
int minIndex = p;
for (int i = p + 1; i <= q; ++i) {
minIndex = array[i] < array[minIndex] ? i : minIndex;
}
return minIndex;
}
} | geekxh/hello-algorithm | 算法读物/剑指offer/11_MinNumberInRotatedArray/Solution.java |
449 | package me.zhyd.oauth.config;
import com.xkcoding.http.config.HttpConfig;
import lombok.*;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.utils.StringUtils;
import java.util.List;
/**
* JustAuth配置类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @since 1.8
*/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AuthConfig {
/**
* 客户端id:对应各平台的appKey
*/
private String clientId;
/**
* 客户端Secret:对应各平台的appSecret
*/
private String clientSecret;
/**
* 登录成功后的回调地址
*/
private String redirectUri;
/**
* 支付宝公钥:当选择支付宝登录时,该值可用
* 对应“RSA2(SHA256)密钥”中的“支付宝公钥”
*
* @deprecated 请使用AuthAlipayRequest的构造方法设置"alipayPublicKey"
*/
@Deprecated
private String alipayPublicKey;
/**
* 是否需要申请unionid,目前只针对qq登录
* 注:qq授权登录时,获取unionid需要单独发送邮件申请权限。如果个人开发者账号中申请了该权限,可以将该值置为true,在获取openId时就会同步获取unionId
* 参考链接:http://wiki.connect.qq.com/unionid%E4%BB%8B%E7%BB%8D
* <p>
* 1.7.1版本新增参数
*/
private boolean unionId;
/**
* Stack Overflow Key
* <p>
*
* @since 1.9.0
*/
private String stackOverflowKey;
/**
* 企业微信,授权方的网页应用ID
*
* @since 1.10.0
*/
private String agentId;
/**
* 企业微信第三方授权用户类型,member|admin
*
* @since 1.10.0
*/
private String usertype;
/**
* 域名前缀。
* <p>
* 使用 Coding 登录和 Okta 登录时,需要传该值。
* <p>
* Coding 登录:团队域名前缀,比如以“ https://justauth.coding.net ”为例,{@code domainPrefix} = justauth
* <p>
* Okta 登录:Okta 账号域名前缀,比如以“ https://justauth.okta.com ”为例,{@code domainPrefix} = justauth
*
* @since 1.16.0
*/
private String domainPrefix;
/**
* 针对国外服务可以单独设置代理
* HttpConfig config = new HttpConfig();
* config.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 10080)));
* config.setTimeout(15000);
*
* @since 1.15.5
*/
private HttpConfig httpConfig;
/**
* 忽略校验 {@code state} 参数,默认不开启。当 {@code ignoreCheckState} 为 {@code true} 时,
* {@link me.zhyd.oauth.request.AuthDefaultRequest#login(AuthCallback)} 将不会校验 {@code state} 的合法性。
* <p>
* 使用场景:当且仅当使用自实现 {@code state} 校验逻辑时开启
* <p>
* 以下场景使用方案仅作参考:
* 1. 授权、登录为同端,并且全部使用 JustAuth 实现时,该值建议设为 {@code false};
* 2. 授权和登录为不同端实现时,比如前端页面拼装 {@code authorizeUrl},并且前端自行对{@code state}进行校验,
* 后端只负责使用{@code code}获取用户信息时,该值建议设为 {@code true};
*
* <strong>如非特殊需要,不建议开启这个配置</strong>
* <p>
* 该方案主要为了解决以下类似场景的问题:
*
* @see <a href="https://github.com/justauth/JustAuth/issues/83">https://github.com/justauth/JustAuth/issues/83</a>
* @since 1.15.6
*/
private boolean ignoreCheckState;
/**
* 支持自定义授权平台的 scope 内容
*
* @since 1.15.7
*/
private List<String> scopes;
/**
* 设备ID, 设备唯一标识ID
*
* @since 1.15.8
*/
private String deviceId;
/**
* 喜马拉雅:客户端操作系统类型,1-iOS系统,2-Android系统,3-Web
*
* @since 1.15.9
*/
private Integer clientOsType;
/**
* 喜马拉雅:客户端包名,如果 {@link AuthConfig#clientOsType} 为1或2时必填。对Android客户端是包名,对IOS客户端是Bundle ID
*
* @since 1.15.9
*/
private String packId;
/**
* 是否开启 PKCE 模式,该配置仅用于支持 PKCE 模式的平台,针对无服务应用,不推荐使用隐式授权,推荐使用 PKCE 模式
*
* @since 1.15.9
*/
private boolean pkce;
/**
* Okta 授权服务器的 ID, 默认为 default。如果要使用自定义授权服务,此处传实际的授权服务器 ID(一个随机串)
* <p>
* 创建自定义授权服务器,请参考:
* <p>
* ① https://developer.okta.com/docs/concepts/auth-servers
* <p>
* ② https://developer.okta.com/docs/guides/customize-authz-server
*
* @since 1.16.0
*/
private String authServerId;
/**
* 忽略校验 {@code redirectUri} 参数,默认不开启。当 {@code ignoreCheckRedirectUri} 为 {@code true} 时,
* {@link me.zhyd.oauth.utils.AuthChecker#checkConfig(AuthConfig, AuthSource)} 将不会校验 {@code redirectUri} 的合法性。
*
* @since 1.16.1
*/
private boolean ignoreCheckRedirectUri;
/**
* 适配 builder 模式 set 值的情况
*
* @return authServerId
*/
public String getAuthServerId() {
return StringUtils.isEmpty(authServerId) ? "default" : authServerId;
}
/**
* Microsoft Entra ID(原微软 AAD)中的租户 ID
*/
private String tenantId;
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/config/AuthConfig.java |
451 | package me.zhyd.oauth.request;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.enums.AuthUserGender;
import me.zhyd.oauth.enums.scope.AuthQqScope;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.*;
import java.util.Map;
/**
* qq登录
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @author yangkai.shen (https://xkcoding.com)
* @since 1.1.0
*/
public class AuthQqRequest extends AuthDefaultRequest {
public AuthQqRequest(AuthConfig config) {
super(config, AuthDefaultSource.QQ);
}
public AuthQqRequest(AuthConfig config, AuthStateCache authStateCache) {
super(config, AuthDefaultSource.QQ, authStateCache);
}
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
String response = doGetAuthorizationCode(authCallback.getCode());
return getAuthToken(response);
}
@Override
public AuthResponse refresh(AuthToken authToken) {
String response = new HttpUtils(config.getHttpConfig()).get(refreshTokenUrl(authToken.getRefreshToken())).getBody();
return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(getAuthToken(response)).build();
}
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
String openId = this.getOpenId(authToken);
String response = doGetUserInfo(authToken);
JSONObject object = JSONObject.parseObject(response);
if (object.getIntValue("ret") != 0) {
throw new AuthException(object.getString("msg"));
}
String avatar = object.getString("figureurl_qq_2");
if (StringUtils.isEmpty(avatar)) {
avatar = object.getString("figureurl_qq_1");
}
String location = String.format("%s-%s", object.getString("province"), object.getString("city"));
return AuthUser.builder()
.rawUserInfo(object)
.username(object.getString("nickname"))
.nickname(object.getString("nickname"))
.avatar(avatar)
.location(location)
.uuid(openId)
.gender(AuthUserGender.getRealGender(object.getString("gender")))
.token(authToken)
.source(source.toString())
.build();
}
/**
* 获取QQ用户的OpenId,支持自定义是否启用查询unionid的功能,如果启用查询unionid的功能,
* 那就需要开发者先通过邮件申请unionid功能,参考链接 {@see http://wiki.connect.qq.com/unionid%E4%BB%8B%E7%BB%8D}
*
* @param authToken 通过{@link AuthQqRequest#getAccessToken(AuthCallback)}获取到的{@code authToken}
* @return openId
*/
private String getOpenId(AuthToken authToken) {
String response = new HttpUtils(config.getHttpConfig()).get(UrlBuilder.fromBaseUrl("https://graph.qq.com/oauth2.0/me")
.queryParam("access_token", authToken.getAccessToken())
.queryParam("unionid", config.isUnionId() ? 1 : 0)
.build()).getBody();
String removePrefix = response.replace("callback(", "");
String removeSuffix = removePrefix.replace(");", "");
String openId = removeSuffix.trim();
JSONObject object = JSONObject.parseObject(openId);
if (object.containsKey("error")) {
throw new AuthException(object.get("error") + ":" + object.get("error_description"));
}
authToken.setOpenId(object.getString("openid"));
if (object.containsKey("unionid")) {
authToken.setUnionId(object.getString("unionid"));
}
return StringUtils.isEmpty(authToken.getUnionId()) ? authToken.getOpenId() : authToken.getUnionId();
}
/**
* 返回获取userInfo的url
*
* @param authToken 用户授权token
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("oauth_consumer_key", config.getClientId())
.queryParam("openid", authToken.getOpenId())
.build();
}
private AuthToken getAuthToken(String response) {
Map<String, String> accessTokenObject = GlobalAuthUtils.parseStringToMap(response);
if (!accessTokenObject.containsKey("access_token") || accessTokenObject.containsKey("code")) {
throw new AuthException(accessTokenObject.get("msg"));
}
return AuthToken.builder()
.accessToken(accessTokenObject.get("access_token"))
.expireIn(Integer.parseInt(accessTokenObject.getOrDefault("expires_in", "0")))
.refreshToken(accessTokenObject.get("refresh_token"))
.build();
}
@Override
public String authorize(String state) {
return UrlBuilder.fromBaseUrl(super.authorize(state))
.queryParam("scope", this.getScopes(",", false, AuthScopeUtils.getDefaultScopes(AuthQqScope.values())))
.build();
}
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/request/AuthQqRequest.java |
542 | E
1526529797
tags: Tree, DFS, Double Recursive
count所有存在的 path sum == target sum. 可以从任意点开始. 但是只能parent -> child .
#### DFS
- 对所给的input sum 做减法, 知道 sum 达到一个目标值截止
- 因为可以从任意点开始, 所以当sum达标时候, 需要继续recursive, 从而找到所有情况 (有正负数, sum可能继续增加/减少)
- 经典的 helper dfs recursive + self recursive
- 1. helper dfs recursive 处理包括root的情况
- 2. self recursive 来引领 skip root的情况.
#### 特点
- 与 `Binary Tree Longest Consecutive Sequence II` 在recursive的做法上很相似:
- 利用dfs做包括root的recursive computation
- 利用这个function自己, 做`不包括root的recursive computation`
```
/*
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf,
but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int pathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}
return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
private int dfs(TreeNode node, int sum) {
int count = 0;
if (node == null) return count;
count += node.val == sum ? 1 : 0;
count += dfs(node.left, sum - node.val);
count += dfs(node.right, sum - node.val);
return count;
}
}
``` | awangdev/leet-code | Java/Path Sum III.java |
543 | package edu.stanford.nlp.coref.md;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import edu.stanford.nlp.coref.data.Dictionaries;
import edu.stanford.nlp.coref.data.Mention;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.Label;
import edu.stanford.nlp.ling.MultiTokenTag;
import edu.stanford.nlp.parser.common.ParserAnnotations;
import edu.stanford.nlp.parser.common.ParserConstraint;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.Annotator;
import edu.stanford.nlp.pipeline.ParserAnnotator;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations;
import edu.stanford.nlp.trees.HeadFinder;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeCoreAnnotations;
import edu.stanford.nlp.trees.TreeCoreAnnotations.TreeAnnotation;
import edu.stanford.nlp.trees.Trees;
import edu.stanford.nlp.trees.tregex.TregexMatcher;
import edu.stanford.nlp.trees.tregex.TregexPattern;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.Generics;
import edu.stanford.nlp.util.IntPair;
import edu.stanford.nlp.util.StringUtils;
import edu.stanford.nlp.util.logging.Redwood;
/**
* Interface for finding coref mentions in a document.
*
* @author Angel Chang
*/
public abstract class CorefMentionFinder {
/** A logger for this class */
private static Redwood.RedwoodChannels log = Redwood.channels(CorefMentionFinder.class);
protected Locale lang;
protected HeadFinder headFinder;
protected Annotator parserProcessor;
protected boolean allowReparsing;
protected static final TregexPattern npOrPrpMentionPattern = TregexPattern.compile("/^(?:NP|PN|PRP)/");
private static final boolean VERBOSE = false;
/** Get all the predicted mentions for a document.
*
* @param doc The syntactically annotated document
* @param dict Dictionaries for coref.
* @return For each of the List of sentences in the document, a List of Mention objects
*/
public abstract List<List<Mention>> findMentions(Annotation doc, Dictionaries dict, Properties props);
protected static void extractPremarkedEntityMentions(CoreMap s, List<Mention> mentions, Set<IntPair> mentionSpanSet, Set<IntPair> namedEntitySpanSet) {
List<CoreLabel> sent = s.get(CoreAnnotations.TokensAnnotation.class);
SemanticGraph basicDependency = s.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class);
SemanticGraph enhancedDependency = s.get(SemanticGraphCoreAnnotations.EnhancedDependenciesAnnotation.class);
if (enhancedDependency == null) {
enhancedDependency = s.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class);
}
int beginIndex = -1;
for (CoreLabel w : sent) {
MultiTokenTag t = w.get(CoreAnnotations.MentionTokenAnnotation.class);
if (t != null) {
// Part of a mention
if (t.isStart()) {
// Start of mention
beginIndex = w.get(CoreAnnotations.IndexAnnotation.class) - 1;
}
if (t.isEnd()) {
// end of mention
int endIndex = w.get(CoreAnnotations.IndexAnnotation.class);
if (beginIndex >= 0) {
IntPair mSpan = new IntPair(beginIndex, endIndex);
int dummyMentionId = -1;
Mention m = new Mention(dummyMentionId, beginIndex, endIndex, sent, basicDependency, enhancedDependency, new ArrayList<>(sent.subList(beginIndex, endIndex)));
mentions.add(m);
mentionSpanSet.add(mSpan);
beginIndex = -1;
} else {
Redwood.log("Start of marked mention not found in sentence: "
+ t + " at tokenIndex=" + (w.get(CoreAnnotations.IndexAnnotation.class)-1)+ " for "
+ s.get(CoreAnnotations.TextAnnotation.class));
}
}
}
}
}
/** Extract enumerations (A, B, and C) */
protected static final TregexPattern enumerationsMentionPattern = TregexPattern.compile("NP < (/^(?:NP|NNP|NML)/=m1 $.. (/^CC|,/ $.. /^(?:NP|NNP|NML)/=m2))");
protected static void extractEnumerations(CoreMap s, List<Mention> mentions, Set<IntPair> mentionSpanSet, Set<IntPair> namedEntitySpanSet) {
List<CoreLabel> sent = s.get(CoreAnnotations.TokensAnnotation.class);
Tree tree = s.get(TreeCoreAnnotations.TreeAnnotation.class);
SemanticGraph basicDependency = s.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class);
SemanticGraph enhancedDependency = s.get(SemanticGraphCoreAnnotations.EnhancedDependenciesAnnotation.class);
if (enhancedDependency == null) {
enhancedDependency = s.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class);
}
TregexPattern tgrepPattern = enumerationsMentionPattern;
TregexMatcher matcher = tgrepPattern.matcher(tree);
Map<IntPair, Tree> spanToMentionSubTree = Generics.newHashMap();
while (matcher.find()) {
matcher.getMatch();
Tree m1 = matcher.getNode("m1");
Tree m2 = matcher.getNode("m2");
List<Tree> mLeaves = m1.getLeaves();
int beginIdx = ((CoreLabel)mLeaves.get(0).label()).get(CoreAnnotations.IndexAnnotation.class)-1;
int endIdx = ((CoreLabel)mLeaves.get(mLeaves.size()-1).label()).get(CoreAnnotations.IndexAnnotation.class);
spanToMentionSubTree.put(new IntPair(beginIdx, endIdx), m1);
mLeaves = m2.getLeaves();
beginIdx = ((CoreLabel)mLeaves.get(0).label()).get(CoreAnnotations.IndexAnnotation.class)-1;
endIdx = ((CoreLabel)mLeaves.get(mLeaves.size()-1).label()).get(CoreAnnotations.IndexAnnotation.class);
spanToMentionSubTree.put(new IntPair(beginIdx, endIdx), m2);
}
for (Map.Entry<IntPair, Tree> spanMention : spanToMentionSubTree.entrySet()) {
IntPair span = spanMention.getKey();
if (!mentionSpanSet.contains(span) && !insideNE(span, namedEntitySpanSet)) {
int dummyMentionId = -1;
Mention m = new Mention(dummyMentionId, span.get(0), span.get(1), sent, basicDependency, enhancedDependency,
new ArrayList<>(sent.subList(span.get(0), span.get(1))), spanMention.getValue());
mentions.add(m);
mentionSpanSet.add(span);
}
}
}
/** Check whether a mention is inside of a named entity */
protected static boolean insideNE(IntPair mSpan, Set<IntPair> namedEntitySpanSet) {
for (IntPair span : namedEntitySpanSet){
if(span.get(0) <= mSpan.get(0) && mSpan.get(1) <= span.get(1)) return true;
}
return false;
}
public static boolean inStopList(Mention m) {
String mentionSpan = m.spanToString().toLowerCase(Locale.ENGLISH);
if (mentionSpan.equals("u.s.") || mentionSpan.equals("u.k.")
|| mentionSpan.equals("u.s.s.r")) return true;
if (mentionSpan.equals("there") || mentionSpan.startsWith("etc.")
|| mentionSpan.equals("ltd.")) return true;
if (mentionSpan.startsWith("'s ")) return true;
// if (mentionSpan.endsWith("etc.")) return true;
return false;
}
protected void removeSpuriousMentions(Annotation doc, List<List<Mention>> predictedMentions, Dictionaries dict, boolean removeNested, Locale lang) {
if(lang == Locale.ENGLISH) removeSpuriousMentionsEn(doc, predictedMentions, dict);
else if (lang == Locale.CHINESE) removeSpuriousMentionsZh(doc, predictedMentions, dict, removeNested);
}
protected void removeSpuriousMentionsEn(Annotation doc, List<List<Mention>> predictedMentions, Dictionaries dict) {
List<CoreMap> sentences = doc.get(CoreAnnotations.SentencesAnnotation.class);
for(int i=0 ; i < predictedMentions.size() ; i++) {
CoreMap s = sentences.get(i);
List<Mention> mentions = predictedMentions.get(i);
List<CoreLabel> sent = s.get(CoreAnnotations.TokensAnnotation.class);
Set<Mention> remove = Generics.newHashSet();
for(Mention m : mentions){
String headPOS = m.headWord.get(CoreAnnotations.PartOfSpeechAnnotation.class);
// non word such as 'hmm'
if(dict.nonWords.contains(m.headString)) remove.add(m);
// adjective form of nations
// the [American] policy -> not mention
// speak in [Japanese] -> mention
// check if the mention is noun and the next word is not noun
if (dict.isAdjectivalDemonym(m.spanToString())) {
if(!headPOS.startsWith("N")
|| (m.endIndex < sent.size() && sent.get(m.endIndex).tag().startsWith("N")) ) {
remove.add(m);
}
}
// stop list (e.g., U.S., there)
if (inStopList(m)) remove.add(m);
}
mentions.removeAll(remove);
}
}
protected void removeSpuriousMentionsZh(Annotation doc, List<List<Mention>> predictedMentions, Dictionaries dict, boolean removeNested) {
List<CoreMap> sentences = doc.get(CoreAnnotations.SentencesAnnotation.class);
// this goes through each sentence -- predictedMentions has a list for each sentence
for (int i=0, sz = predictedMentions.size(); i < sz ; i++) {
List<Mention> mentions = predictedMentions.get(i);
List<CoreLabel> sent = sentences.get(i).get(CoreAnnotations.TokensAnnotation.class);
Set<Mention> remove = Generics.newHashSet();
for (Mention m : mentions) {
if (m.headWord.ner().matches("PERCENT|MONEY|QUANTITY|CARDINAL")) {
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING number NER: " + m.spanToString());
} else if (m.originalSpan.size()==1 && m.headWord.tag().equals("CD")) {
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING number: " + m.spanToString());
} else if (dict.removeWords.contains(m.spanToString())) {
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING removeWord: " + m.spanToString());
} else if (mentionContainsRemoveChars(m, dict.removeChars)) {
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING removeChars: " + m.spanToString());
} else if (m.headWord.tag().equals("PU")) {
// punctuation-only mentions
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING Punctuation only mention: " + m.spanToString());
} else if (mentionIsDemonym(m, dict.countries)) {
// demonyms -- this seems to be a no-op on devset. Maybe not working?
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING Removed demonym: " + m.spanToString());
} else if (m.spanToString().equals("问题") && m.startIndex > 0 &&
sent.get(m.startIndex - 1).word().endsWith("没")) {
// 没 问题 - this is maybe okay but having 问题 on removeWords was dangerous
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING Removed meiyou: " + m.spanToString());
} else if (mentionIsRangren(m, sent)) {
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING Removed rangren: " + m.spanToString());
} else if (m.spanToString().equals("你") && m.startIndex < sent.size() - 1 &&
sent.get(m.startIndex + 1).word().startsWith("知道")) {
// 你 知道
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING Removed nizhidao: " + m.spanToString());
// The words that used to be in this case are now handled more generallyin removeCharsZh
// } else if (m.spanToString().contains("什么") || m.spanToString().contains("多少")) {
// remove.add(m);
// if (VERBOSE) log.info("MENTION FILTERING Removed many/few mention ending: " + m.spanToString());
} else if (m.spanToString().endsWith("的")) {
remove.add(m);
if (VERBOSE) log.info("MENTION FILTERING Removed de ending mention: " + m.spanToString());
// omit this case, it decreases performance. A few useful interrogative pronouns are now in the removeChars list
// } else if (mentionIsInterrogativePronoun(m, dict.interrogativePronouns)) {
// remove.add(m);
// if (VERBOSE) log.info("MENTION FILTERING Removed interrogative pronoun: " + m.spanToString());
}
// 的 handling
// if(m.startIndex>0 && sent.get(m.startIndex-1).word().equals("的")) {
// // remove.add(m);
// Tree t = sentences.get(i).get(TreeAnnotation.class);
// Tree mTree = m.mentionSubTree;
// if(mTree==null) continue;
// for(Tree p : t.pathNodeToNode(mTree, t)) {
// if(mTree==p) continue;
// if(p.value().equals("NP")) {
// remove.add(m);
// }
// }
// }
} // for each mention
// nested mention with shared headword (except apposition, enumeration): pick larger one
if (removeNested) {
for (Mention m1 : mentions){
for (Mention m2 : mentions){
if (m1==m2 || remove.contains(m1) || remove.contains(m2)) continue;
if (m1.sentNum==m2.sentNum && m1.headWord==m2.headWord && m2.insideIn(m1)) {
if (m2.endIndex < sent.size() && (sent.get(m2.endIndex).get(CoreAnnotations.PartOfSpeechAnnotation.class).equals(",")
|| sent.get(m2.endIndex).get(CoreAnnotations.PartOfSpeechAnnotation.class).equals("CC"))) {
continue;
}
remove.add(m2);
}
}
}
}
mentions.removeAll(remove);
} // for each sentence
}
private static boolean mentionContainsRemoveChars(Mention m, Set<String> removeChars) {
String spanString = m.spanToString();
for (String ch : removeChars) {
if (spanString.contains(ch)) {
return true;
}
}
return false;
}
private static boolean mentionIsDemonym(Mention m, Set<String> countries) {
String lastWord = m.originalSpan.get(m.originalSpan.size()-1).word();
return lastWord.length() > 0 && m.spanToString().endsWith("人") &&
countries.contains(lastWord.substring(0, lastWord.length()-1));
}
private static boolean mentionIsRangren(Mention m, List<CoreLabel> sent) {
if (m.spanToString().equals("人") && m.startIndex > 0) {
String priorWord = sent.get(m.startIndex - 1).word();
// cdm [2016]: This test matches everything because of the 3rd clause! That can't be right!
if (priorWord.endsWith("让") || priorWord.endsWith("令") || priorWord.endsWith("")) {
return true;
}
}
return false;
}
private static boolean mentionIsInterrogativePronoun(Mention m, Set<String> interrogatives) {
// handling interrogative pronouns
for (CoreLabel cl : m.originalSpan) {
// if (dict.interrogativePronouns.contains(m.spanToString())) remove.add(m);
if (interrogatives.contains(cl.word())) {
return true;
}
}
return false;
}
// extract mentions which have same string as another stand-alone mention
protected static void extractNamedEntityModifiers(List<CoreMap> sentences, List<Set<IntPair>> mentionSpanSetList, List<List<Mention>> predictedMentions, Set<String> neStrings) {
for (int i=0, sz = sentences.size(); i < sz ; i++ ) {
List<Mention> mentions = predictedMentions.get(i);
CoreMap sent = sentences.get(i);
List<CoreLabel> tokens = sent.get(TokensAnnotation.class);
Set<IntPair> mentionSpanSet = mentionSpanSetList.get(i);
for (int j=0, tSize=tokens.size(); j < tSize; j++) {
for (String ne : neStrings) {
int len = ne.split(" ").length;
if (j+len > tokens.size()) continue;
StringBuilder sb = new StringBuilder();
for(int k=0 ; k < len ; k++) {
sb.append(tokens.get(k+j).word()).append(" ");
}
String phrase = sb.toString().trim();
int beginIndex = j;
int endIndex = j+len;
// include "'s" if it belongs to this named entity
if( endIndex < tokens.size() && tokens.get(endIndex).word().equals("'s") && tokens.get(endIndex).tag().equals("POS")) {
Tree tree = sent.get(TreeAnnotation.class);
Tree sToken = tree.getLeaves().get(beginIndex);
Tree eToken = tree.getLeaves().get(endIndex);
Tree join = tree.joinNode(sToken, eToken);
Tree sJoin = join.getLeaves().get(0);
Tree eJoin = join.getLeaves().get(join.getLeaves().size()-1);
if(sToken == sJoin && eToken == eJoin) {
endIndex++;
}
}
// include DT if it belongs to this named entity
if( beginIndex > 0 && tokens.get(beginIndex-1).tag().equals("DT")) {
Tree tree = sent.get(TreeAnnotation.class);
Tree sToken = tree.getLeaves().get(beginIndex-1);
Tree eToken = tree.getLeaves().get(endIndex-1);
Tree join = tree.joinNode(sToken, eToken);
Tree sJoin = join.getLeaves().get(0);
Tree eJoin = join.getLeaves().get(join.getLeaves().size()-1);
if(sToken == sJoin && eToken == eJoin) {
beginIndex--;
}
}
IntPair span = new IntPair(beginIndex, endIndex);
if(phrase.equalsIgnoreCase(ne) && !mentionSpanSet.contains(span)) {
int dummyMentionId = -1;
Mention m = new Mention(dummyMentionId, beginIndex, endIndex, tokens,
sent.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class),
sent.get(SemanticGraphCoreAnnotations.EnhancedDependenciesAnnotation.class) != null
? sent.get(SemanticGraphCoreAnnotations.EnhancedDependenciesAnnotation.class)
: sent.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class),
new ArrayList<>(tokens.subList(beginIndex, endIndex)));
mentions.add(m);
mentionSpanSet.add(span);
}
}
}
}
}
protected static void addNamedEntityStrings(CoreMap s, Set<String> neStrings, Set<IntPair> namedEntitySpanSet) {
List<CoreLabel> tokens = s.get(TokensAnnotation.class);
for(IntPair p : namedEntitySpanSet) {
StringBuilder sb = new StringBuilder();
for(int idx=p.get(0) ; idx < p.get(1) ; idx++) {
sb.append(tokens.get(idx).word()).append(" ");
}
String str = sb.toString().trim();
if(str.endsWith(" 's")) {
str = str.substring(0, str.length()-3);
}
neStrings.add(str);
}
}
// temporary for debug
protected static void addGoldMentions(List<CoreMap> sentences,
List<Set<IntPair>> mentionSpanSetList,
List<List<Mention>> predictedMentions, List<List<Mention>> allGoldMentions) {
for (int i=0, sz = sentences.size(); i < sz; i++) {
List<Mention> mentions = predictedMentions.get(i);
CoreMap sent = sentences.get(i);
List<CoreLabel> tokens = sent.get(TokensAnnotation.class);
Set<IntPair> mentionSpanSet = mentionSpanSetList.get(i);
List<Mention> golds = allGoldMentions.get(i);
for (Mention g : golds) {
IntPair pair = new IntPair(g.startIndex, g.endIndex);
if(!mentionSpanSet.contains(pair)) {
int dummyMentionId = -1;
Mention m = new Mention(dummyMentionId, g.startIndex, g.endIndex, tokens,
sent.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class),
sent.get(SemanticGraphCoreAnnotations.EnhancedDependenciesAnnotation.class) != null
? sent.get(SemanticGraphCoreAnnotations.EnhancedDependenciesAnnotation.class)
: sent.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class),
new ArrayList<>(tokens.subList(g.startIndex, g.endIndex)));
mentions.add(m);
mentionSpanSet.add(pair);
}
}
}
}
public void findHead(CoreMap s, List<Mention> mentions) {
Tree tree = s.get(TreeCoreAnnotations.TreeAnnotation.class);
List<CoreLabel> sent = s.get(CoreAnnotations.TokensAnnotation.class);
tree.indexSpans(0);
for (Mention m : mentions){
if (lang == Locale.CHINESE) {
findHeadChinese(sent, m);
} else {
CoreLabel head = (CoreLabel) findSyntacticHead(m, tree, sent).label();
m.headIndex = head.get(CoreAnnotations.IndexAnnotation.class)-1;
m.headWord = sent.get(m.headIndex);
m.headString = m.headWord.get(CoreAnnotations.TextAnnotation.class).toLowerCase(Locale.ENGLISH);
}
int start = m.headIndex - m.startIndex;
if (start < 0 || start >= m.originalSpan.size()) {
Redwood.log("Invalid index for head " + start + "=" + m.headIndex + "-" + m.startIndex
+ ": originalSpan=[" + StringUtils.joinWords(m.originalSpan, " ") + "], head=" + m.headWord);
Redwood.log("Setting head string to entire mention");
m.headIndex = m.startIndex;
m.headWord = m.originalSpan.size() > 0 ? m.originalSpan.get(0) : sent.get(m.startIndex);
m.headString = m.originalSpan.toString();
}
}
}
protected static void findHeadChinese(List<CoreLabel> sent, Mention m) {
int headPos = m.endIndex - 1;
// Skip trailing punctuations
while (headPos > m.startIndex && sent.get(headPos).tag().equals("PU")) {
headPos--;
}
// If we got right to the end without finding non punctuation, reset to end again
if (headPos == m.startIndex && sent.get(headPos).tag().equals("PU")) {
headPos = m.endIndex - 1;
}
if (sent.get(headPos).originalText().equals("自己") && m.endIndex != m.startIndex && headPos > m.startIndex) {
if (!sent.get(headPos-1).tag().equals("PU"))
headPos--;
}
m.headIndex = headPos;
m.headWord = sent.get(headPos);
m.headString = m.headWord.get(CoreAnnotations.TextAnnotation.class);
}
public Tree findSyntacticHead(Mention m, Tree root, List<CoreLabel> tokens) {
// mention ends with 's
int endIdx = m.endIndex;
if (m.originalSpan.size() > 0) {
String lastWord = m.originalSpan.get(m.originalSpan.size()-1).get(CoreAnnotations.TextAnnotation.class);
if((lastWord.equals("'s") || lastWord.equals("'"))
&& m.originalSpan.size() != 1 ) endIdx--;
}
Tree exactMatch = findTreeWithSpan(root, m.startIndex, endIdx);
//
// found an exact match
//
if (exactMatch != null) {
return safeHead(exactMatch, endIdx);
}
// no exact match found
// in this case, we parse the actual extent of the mention, embedded in a sentence
// context, so as to make the parser work better :-)
if (allowReparsing) {
int approximateness = 0;
List<CoreLabel> extentTokens = new ArrayList<>();
extentTokens.add(initCoreLabel("It", "PRP"));
extentTokens.add(initCoreLabel("was", "VBD"));
final int ADDED_WORDS = 2;
for (int i = m.startIndex; i < endIdx; i++) {
// Add everything except separated dashes! The separated dashes mess with the parser too badly.
CoreLabel label = tokens.get(i);
if ( ! "-".equals(label.word())) {
extentTokens.add(tokens.get(i));
} else {
approximateness++;
}
}
extentTokens.add(initCoreLabel(".", "."));
// constrain the parse to the part we're interested in.
// Starting from ADDED_WORDS comes from skipping "It was".
// -1 to exclude the period.
// We now let it be any kind of nominal constituent, since there
// are VP and S ones
ParserConstraint constraint = new ParserConstraint(ADDED_WORDS, extentTokens.size() - 1, Pattern.compile(".*"));
List<ParserConstraint> constraints = Collections.singletonList(constraint);
Tree tree = parse(extentTokens, constraints);
convertToCoreLabels(tree); // now unnecessary, as parser uses CoreLabels?
tree.indexSpans(m.startIndex - ADDED_WORDS); // remember it has ADDED_WORDS extra words at the beginning
Tree subtree = findPartialSpan(tree, m.startIndex);
// There was a possible problem that with a crazy parse, extentHead could be one of the added words, not a real word!
// Now we make sure in findPartialSpan that it can't be before the real start, and in safeHead, we disallow something
// passed the right end (that is, just that final period).
Tree extentHead = safeHead(subtree, endIdx);
assert(extentHead != null);
// extentHead is a child in the local extent parse tree. we need to find the corresponding node in the main tree
// Because we deleted dashes, it's index will be >= the index in the extent parse tree
CoreLabel l = (CoreLabel) extentHead.label();
Tree realHead = funkyFindLeafWithApproximateSpan(root, l.value(), l.get(CoreAnnotations.BeginIndexAnnotation.class), approximateness);
assert(realHead != null);
return realHead;
}
// If reparsing wasn't allowed, try to find a span in the tree
// which happens to have the head
Tree wordMatch = findTreeWithSmallestSpan(root, m.startIndex, endIdx);
if (wordMatch != null) {
Tree head = safeHead(wordMatch, endIdx);
if (head != null) {
int index = ((CoreLabel) head.label()).get(CoreAnnotations.IndexAnnotation.class)-1;
if (index >= m.startIndex && index < endIdx) {
return head;
}
}
}
// If that didn't work, guess that it's the last word
int lastNounIdx = endIdx-1;
for(int i=m.startIndex ; i < m.endIndex ; i++) {
if(tokens.get(i).tag().startsWith("N")) lastNounIdx = i;
else if(tokens.get(i).tag().startsWith("W")) break;
}
List<Tree> leaves = root.getLeaves();
Tree endLeaf = leaves.get(lastNounIdx);
return endLeaf;
}
/** Find the tree that covers the portion of interest. */
private static Tree findPartialSpan(final Tree root, final int start) {
CoreLabel label = (CoreLabel) root.label();
int startIndex = label.get(CoreAnnotations.BeginIndexAnnotation.class);
if (startIndex == start) {
return root;
}
for (Tree kid : root.children()) {
CoreLabel kidLabel = (CoreLabel) kid.label();
int kidStart = kidLabel.get(CoreAnnotations.BeginIndexAnnotation.class);
int kidEnd = kidLabel.get(CoreAnnotations.EndIndexAnnotation.class);
if (kidStart <= start && kidEnd > start) {
return findPartialSpan(kid, start);
}
}
throw new RuntimeException("Shouldn't happen: " + start + " " + root);
}
private static Tree funkyFindLeafWithApproximateSpan(Tree root, String token, int index, int approximateness) {
// log.info("Searching " + root + "\n for " + token + " at position " + index + " (plus up to " + approximateness + ")");
List<Tree> leaves = root.getLeaves();
for (Tree leaf : leaves) {
CoreLabel label = CoreLabel.class.cast(leaf.label());
Integer indexInteger = label.get(CoreAnnotations.IndexAnnotation.class);
if (indexInteger == null) continue;
int ind = indexInteger - 1;
if (token.equals(leaf.value()) && ind >= index && ind <= index + approximateness) {
return leaf;
}
}
// this shouldn't happen
// throw new RuntimeException("RuleBasedCorefMentionFinder: ERROR: Failed to find head token");
Redwood.log("RuleBasedCorefMentionFinder: Failed to find head token:\n" +
"Tree is: " + root + "\n" +
"token = |" + token + "|" + index + "|, approx=" + approximateness);
for (Tree leaf : leaves) {
if (token.equals(leaf.value())) {
// log.info("Found it at position " + ind + "; returning " + leaf);
return leaf;
}
}
int fallback = Math.max(0, leaves.size() - 2);
Redwood.log("RuleBasedCorefMentionFinder: Last resort: returning as head: " + leaves.get(fallback));
return leaves.get(fallback); // last except for the added period.
}
private static CoreLabel initCoreLabel(String token, String posTag) {
CoreLabel label = new CoreLabel();
label.set(CoreAnnotations.TextAnnotation.class, token);
label.set(CoreAnnotations.ValueAnnotation.class, token);
label.set(CoreAnnotations.PartOfSpeechAnnotation.class, posTag);
return label;
}
private Tree parse(List<CoreLabel> tokens) {
return parse(tokens, null);
}
private Tree parse(List<CoreLabel> tokens,
List<ParserConstraint> constraints) {
CoreMap sent = new Annotation("");
sent.set(CoreAnnotations.TokensAnnotation.class, tokens);
sent.set(ParserAnnotations.ConstraintAnnotation.class, constraints);
Annotation doc = new Annotation("");
List<CoreMap> sents = new ArrayList<>(1);
sents.add(sent);
doc.set(CoreAnnotations.SentencesAnnotation.class, sents);
getParser().annotate(doc);
sents = doc.get(CoreAnnotations.SentencesAnnotation.class);
return sents.get(0).get(TreeCoreAnnotations.TreeAnnotation.class);
}
private Annotator getParser() {
if(parserProcessor == null){
parserProcessor = StanfordCoreNLP.getExistingAnnotator("parse");
if (parserProcessor == null) {
Properties emptyProperties = new Properties();
parserProcessor = new ParserAnnotator("coref.parse.md", emptyProperties);
}
assert(parserProcessor != null);
}
return parserProcessor;
}
// This probably isn't needed now; everything is always a core label. But no-op.
private static void convertToCoreLabels(Tree tree) {
Label l = tree.label();
if (! (l instanceof CoreLabel)) {
CoreLabel cl = new CoreLabel();
cl.setValue(l.value());
tree.setLabel(cl);
}
for (Tree kid : tree.children()) {
convertToCoreLabels(kid);
}
}
private Tree safeHead(Tree top, int endIndex) {
// The trees passed in do not have the CoordinationTransformer
// applied, but that just means the SemanticHeadFinder results are
// slightly worse.
Tree head = top.headTerminal(headFinder);
// One obscure failure case is that the added period becomes the head. Disallow this.
if (head != null) {
Integer headIndexInteger = ((CoreLabel) head.label()).get(CoreAnnotations.IndexAnnotation.class);
if (headIndexInteger != null) {
int headIndex = headIndexInteger - 1;
if (headIndex < endIndex) {
return head;
}
}
}
// if no head found return the right-most leaf
List<Tree> leaves = top.getLeaves();
int candidate = leaves.size() - 1;
while (candidate >= 0) {
head = leaves.get(candidate);
Integer headIndexInteger = ((CoreLabel) head.label()).get(CoreAnnotations.IndexAnnotation.class);
if (headIndexInteger != null) {
int headIndex = headIndexInteger - 1;
if (headIndex < endIndex) {
return head;
}
}
candidate--;
}
// fallback: return top
return top;
}
static Tree findTreeWithSmallestSpan(Tree tree, int start, int end) {
List<Tree> leaves = tree.getLeaves();
Tree startLeaf = leaves.get(start);
Tree endLeaf = leaves.get(end - 1);
return Trees.getLowestCommonAncestor(Arrays.asList(startLeaf, endLeaf), tree);
}
private static Tree findTreeWithSpan(Tree tree, int start, int end) {
CoreLabel l = (CoreLabel) tree.label();
if (l != null && l.containsKey(CoreAnnotations.BeginIndexAnnotation.class) && l.containsKey(CoreAnnotations.EndIndexAnnotation.class)) {
int myStart = l.get(CoreAnnotations.BeginIndexAnnotation.class);
int myEnd = l.get(CoreAnnotations.EndIndexAnnotation.class);
if (start == myStart && end == myEnd){
// found perfect match
return tree;
} else if (end < myStart) {
return null;
} else if (start >= myEnd) {
return null;
}
}
// otherwise, check inside children - a match is possible
for (Tree kid : tree.children()) {
if (kid == null) continue;
Tree ret = findTreeWithSpan(kid, start, end);
// found matching child
if (ret != null) return ret;
}
// no match
return null;
}
public static boolean partitiveRule(Mention m, List<CoreLabel> sent, Dictionaries dict) {
return m.startIndex >= 2
&& sent.get(m.startIndex - 1).get(CoreAnnotations.TextAnnotation.class).equalsIgnoreCase("of")
&& dict.parts.contains(sent.get(m.startIndex - 2).get(CoreAnnotations.TextAnnotation.class).toLowerCase(Locale.ENGLISH));
}
/** Check whether pleonastic 'it'. E.g., It is possible that ... */
private static final TregexPattern[] pleonasticPatterns = getPleonasticPatterns();
public static boolean isPleonastic(Mention m, Tree tree) {
if ( ! m.spanToString().equalsIgnoreCase("it")) return false;
for (TregexPattern p : pleonasticPatterns) {
if (checkPleonastic(m, tree, p)) {
// SieveCoreferenceSystem.logger.fine("RuleBasedCorefMentionFinder: matched pleonastic pattern '" + p + "' for " + tree);
return true;
}
}
return false;
}
public static boolean isPleonasticDebug(Mention m, Tree tree, StringBuilder sbLog) {
if ( ! m.spanToString().equalsIgnoreCase("it")) return false;
boolean isPleonastic = false;
int patternIdx = -1;
int matchedPattern = -1;
for (TregexPattern p : pleonasticPatterns) {
patternIdx++;
if (checkPleonastic(m, tree, p)) {
// SieveCoreferenceSystem.logger.fine("RuleBasedCorefMentionFinder: matched pleonastic pattern '" + p + "' for " + tree);
isPleonastic = true;
matchedPattern = patternIdx;
}
}
sbLog.append("PLEONASTIC IT: mention ID: "+m.mentionID +"\thastwin: "+m.hasTwin+"\tpleonastic it? "+isPleonastic+"\tcorrect? "+(m.hasTwin!=isPleonastic)+"\tmatched pattern: "+matchedPattern+"\n");
sbLog.append(m.contextParseTree.pennString()).append("\n");
sbLog.append("PLEONASTIC IT END\n");
return isPleonastic;
}
private static TregexPattern[] getPleonasticPatterns() {
final String[] patterns = {
// cdm 2013: I spent a while on these patterns. I fixed a syntax error in five patterns ($.. split with space), so it now shouldn't exception in checkPleonastic. This gave 0.02% on CoNLL11 dev
// I tried some more precise patterns but they didn't help. Indeed, they tended to hurt vs. the higher recall patterns.
//"NP < (PRP=m1) $.. (VP < ((/^V.*/ < /^(?:is|was|become|became)/) $.. (VP < (VBN $.. /S|SBAR/))))", // overmatches
// "@NP < (PRP=m1 < it|IT|It) $.. (@VP < (/^V.*/ < /^(?i:is|was|be|becomes|become|became)$/ $.. (@VP < (VBN < expected|hoped $.. @SBAR))))", // this one seems more accurate, but ...
"@NP < (PRP=m1 < it|IT|It) $.. (@VP < (/^V.*/ < /^(?i:is|was|be|becomes|become|became)$/ $.. (@VP < (VBN $.. @S|SBAR))))", // in practice, go with this one (best results)
"NP < (PRP=m1) $.. (VP < ((/^V.*/ < /^(?:is|was|become|became)/) $.. (ADJP $.. (/S|SBAR/))))",
"NP < (PRP=m1) $.. (VP < ((/^V.*/ < /^(?:is|was|become|became)/) $.. (ADJP < (/S|SBAR/))))",
// "@NP < (PRP=m1 < it|IT|It) $.. (@VP < (/^V.*/ < /^(?i:is|was|be|becomes|become|became)$/ $.. (@ADJP < (/^(?:JJ|VB)/ < /^(?i:(?:hard|tough|easi)(?:er|est)?|(?:im|un)?(?:possible|interesting|worthwhile|likely|surprising|certain)|disappointing|pointless|easy|fine|okay)$/) [ < @S|SBAR | $.. (@S|SBAR !< (IN !< for|For|FOR|that|That|THAT)) ] )))", // does worse than above 2 on CoNLL11 dev
"NP < (PRP=m1) $.. (VP < ((/^V.*/ < /^(?:is|was|become|became)/) $.. (NP < /S|SBAR/)))",
"NP < (PRP=m1) $.. (VP < ((/^V.*/ < /^(?:is|was|become|became)/) $.. (NP $.. ADVP $.. /S|SBAR/)))",
// "@NP < (PRP=m1 < it|IT|It) $.. (@VP < (/^V.*/ < /^(?i:is|was|be|becomes|become|became)$/ $.. (@NP $.. @ADVP $.. @SBAR)))", // cleft examples, generalized to not need ADVP; but gave worse CoNLL12 dev numbers....
// these next 5 had buggy space in "$ ..", which I fixed
"NP < (PRP=m1) $.. (VP < (MD $.. (VP < ((/^V.*/ < /^(?:be|become)/) $.. (VP < (VBN $.. /S|SBAR/))))))",
"NP < (PRP=m1) $.. (VP < (MD $.. (VP < ((/^V.*/ < /^(?:be|become)/) $.. (ADJP $.. (/S|SBAR/))))))", // extraposed. OK 1/2 correct; need non-adverbial case
"NP < (PRP=m1) $.. (VP < (MD $.. (VP < ((/^V.*/ < /^(?:be|become)/) $.. (ADJP < (/S|SBAR/))))))", // OK: 3/3 good matches on dev; but 3/4 wrong on WSJ
// certain can be either but relatively likely pleonastic with it ... be
// "@NP < (PRP=m1 < it|IT|It) $.. (@VP < (MD $.. (@VP < ((/^V.*/ < /^(?:be|become)/) $.. (@ADJP < (/^JJ/ < /^(?i:(?:hard|tough|easi)(?:er|est)?|(?:im|un)?(?:possible|interesting|worthwhile|likely|surprising|certain)|disappointing|pointless|easy|fine|okay))$/) [ < @S|SBAR | $.. (@S|SBAR !< (IN !< for|For|FOR|that|That|THAT)) ] )))))", // GOOD REPLACEMENT ; 2nd clause is for extraposed ones
"NP < (PRP=m1) $.. (VP < (MD $.. (VP < ((/^V.*/ < /^(?:be|become)/) $.. (NP < /S|SBAR/)))))",
"NP < (PRP=m1) $.. (VP < (MD $.. (VP < ((/^V.*/ < /^(?:be|become)/) $.. (NP $.. ADVP $.. /S|SBAR/)))))",
"NP < (PRP=m1) $.. (VP < ((/^V.*/ < /^(?:seems|appears|means|follows)/) $.. /S|SBAR/))",
"NP < (PRP=m1) $.. (VP < ((/^V.*/ < /^(?:turns|turned)/) $.. PRT $.. /S|SBAR/))"
};
TregexPattern[] tgrepPatterns = new TregexPattern[patterns.length];
for (int i = 0; i < tgrepPatterns.length; i++) {
tgrepPatterns[i] = TregexPattern.compile(patterns[i]);
}
return tgrepPatterns;
}
private static boolean checkPleonastic(Mention m, Tree tree, TregexPattern tgrepPattern) {
try {
TregexMatcher matcher = tgrepPattern.matcher(tree);
while (matcher.find()) {
Tree np1 = matcher.getNode("m1");
if (((CoreLabel)np1.label()).get(CoreAnnotations.BeginIndexAnnotation.class)+1 == m.headWord.get(CoreAnnotations.IndexAnnotation.class)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
| stanfordnlp/CoreNLP | src/edu/stanford/nlp/coref/md/CorefMentionFinder.java |
544 | /*
* 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.security;
import com.zfoo.protocol.util.StringUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5的全称是Message-Digest Algorithm 5,在90年代初由MIT的计算机科学实验室和RSA Data Security Inc发明,经MD2、MD3和MD4发展而来。
* <p>
* MD5将任意长度的“字节串”变换成一个128bit的大整数,并且它是一个不可逆的字符串变换算法。
* <p>
* 换句话说就是,即使你看到源程序和算法描述,也无法将一个MD5的值变换回原始的字符串。
* <p>
* 从数学原理上说,是因为原始的字符串有无穷多个,这有点象不存在反函数的数学函数。
* <p>
* MD5的典型应用是对一段Message(字节串)产生fingerprint(指纹),以防止被“篡改”。
* <p>
* 举个例子,你将一段话写在一个叫 readme.txt文件中,并对这个readme.txt产生一个MD5的值并记录在案,然后你可以传播这个文件给别人,
* 别人如果修改了文件中的任何内容,你对这个文件重新计算MD5时就会发现。如果再有一个第三方的认证机构,用MD5还可以防止文件作者的“抵赖”,
* 这就是所谓的数字签名应用。MD5还广泛用于加密和解密技术上,在很多操作系统中,用户的密码是以MD5值(或类似的其它算法)的方式保存的,
* 用户Login的时候,系统是把用户输入的密码计算成MD5值,然后再去和系统中保存的MD5值进行比较,而系统并不“知道”用户的密码是什么。
*
* @author godotg
*/
public abstract class MD5Utils {
private static final String MD5_ALGORITHM = "MD5";
/**
* 16进制字符
*/
private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static String strToMD5(String str) {
if (StringUtils.isBlank(str)) {
throw new NullPointerException();
}
return bytesToMD5(StringUtils.bytes(str));
}
// MD5将任意长度的“字节串”变换成一个128bit的大整数
public static String bytesToMD5(byte[] bytes) {
try {
var messageDigest = MessageDigest.getInstance(MD5_ALGORITHM);
// inputByteArray是输入字符串转换得到的字节数组
messageDigest.update(bytes);
// 转换并返回结果,也是字节数组,包含16个元素
// 字符数组转换成字符串返回,MD5将任意长度的字节数组变换成一个16个字节,128bit的大整数
return byteArrayToHex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD加密出现未知异常", e);
}
}
//下面这个函数用于将字节数组换成成16进制的字符串
private static String byteArrayToHex(byte[] bytes) {
// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
var resultCharArray = new char[bytes.length * 2];
// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
var index = 0;
for (var b : bytes) {
resultCharArray[index++] = HEX_CHARS[b >>> 4 & 0xf];
resultCharArray[index++] = HEX_CHARS[b & 0xf];
}
// 字符数组组合成字符串返回
return new String(resultCharArray);
}
}
| zfoo-project/zfoo | net/src/main/java/com/zfoo/net/util/security/MD5Utils.java |
545 | //package com.xxl.conf.core.util;
//
//import com.xxl.conf.core.exception.XxlConfException;
//import org.apache.zookeeper.*;
//import org.apache.zookeeper.data.Stat;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.util.concurrent.TimeUnit;
//import java.util.concurrent.locks.ReentrantLock;
//
//
///**
// * ZooKeeper cfg client (Watcher + some utils)
// *
// * @author xuxueli 2015年8月26日21:36:43
// *
// * Zookeeper
// * 从设计模式角度来看,是一个基于观察者模式设计的分布式服务管理框架,它负责存储和管理大家都关心的数据,然后接受观察者的注册
// * ,一旦这些数据的状态发生变化,Zookeeper 就将负责通知已经在 Zookeeper
// * 上注册的那些观察者做出相应的反应,从而实现集群中类似 Master/Slave 管理模式
// *
// * 1、统一命名服务(Name Service):将有层次的目录结构关联到一定资源上,广泛意义上的关联,也许你并不需要将名称关联到特定资源上,
// * 你可能只需要一个不会重复名称。
// *
// * 2、配置管理(Configuration Management):分布式统一配置管理:将配置信息保存在
// * Zookeeper 的某个目录节点中,然后将所有需要修改的应用机器监控配置信息的状态,一旦配置信息发生变化,每台应用机器就会收到
// * Zookeeper 的通知,然后从 Zookeeper 获取新的配置信息应用到系统中
// *
// * 3、集群管理(Group
// * Membership):Zookeeper 能够很容易的实现集群管理的功能,如有多台 Server 组成一个服务集群,那么必须
// * 要一个“总管”知道当前集群中每台机器的服务状态,一旦有机器不能提供服务,集群中其它集群必须知道,从而做出调整重新分配服务策略。
// * 同样当增加集群的服务能力时,就会增加一台或多台 Server,同样也必须让“总管”知道。
// *
// * 4、共享锁(Locks):
// * 5、队列管理:a、当一个队列的成员都聚齐时,这个队列才可用,否则一直等待所有成员到达,这种是同步队列。b、队列按照 FIFO 方式
// * 进行入队和出队操作,例如实现生产者和消费者模型。
// *
// * 集中式配置管理 动态更新
// *
// * 特性:
// * - 断线重连Watch
// * - 重入锁
// * - 实用util
// */
//public class XxlZkClient {
// private static Logger logger = LoggerFactory.getLogger(XxlZkClient.class);
//
//
// private String zkaddress;
// private String zkpath;
// private String zkdigest;
// private Watcher watcher; // watcher(One-time trigger)
//
//
// public XxlZkClient(String zkaddress, String zkpath, String zkdigest, Watcher watcher) {
//
// this.zkaddress = zkaddress;
// this.zkpath = zkpath;
// this.zkdigest = zkdigest;
// this.watcher = watcher;
//
// // reconnect when expire
// if (this.watcher == null) {
// // watcher(One-time trigger)
// this.watcher = new Watcher() {
// @Override
// public void process(WatchedEvent watchedEvent) {
// logger.info(">>>>>>>>>> xxl-conf: watcher:{}", watchedEvent);
//
// // session expire, close old and create new
// if (watchedEvent.getState() == Event.KeeperState.Expired) {
// destroy();
// getClient();
// }
// }
// };
// }
//
// //getClient(); // async coon, support init without conn
// }
//
// // ------------------------------ zookeeper client ------------------------------
// private ZooKeeper zooKeeper;
// private ReentrantLock INSTANCE_INIT_LOCK = new ReentrantLock(true);
// public ZooKeeper getClient(){
// if (zooKeeper==null) {
// try {
// if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) {
//
// // init new-client
// ZooKeeper newZk = null;
// try {
// if (zooKeeper==null) { // 二次校验,防止并发创建client
// newZk = new ZooKeeper(zkaddress, 10000, watcher);
// if (zkdigest!=null && zkdigest.trim().length()>0) {
// newZk.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password"
// }
// newZk.exists(zkpath, false); // sync wait until succcess conn
//
// // set success new-client
// zooKeeper = newZk;
// logger.info(">>>>>>>>>> xxl-conf, XxlZkClient init success.");
// }
// } catch (Exception e) {
// // close fail new-client
// if (newZk != null) {
// newZk.close();
// }
//
// logger.error(e.getMessage(), e);
// } finally {
// INSTANCE_INIT_LOCK.unlock();
// }
//
// }
// } catch (InterruptedException e) {
// logger.error(e.getMessage(), e);
// }
// }
// if (zooKeeper == null) {
// throw new XxlConfException("XxlZkClient.zooKeeper is null.");
// }
// return zooKeeper;
// }
//
// public void destroy(){
// if (zooKeeper!=null) {
// try {
// zooKeeper.close();
// zooKeeper = null;
// } catch (InterruptedException e) {
// logger.error(e.getMessage(), e);
// }
// }
// }
//
// // ------------------------------ util ------------------------------
//
// /**
// * create node path with parent path (PERSISTENT)
// * *
// * * zk limit parent must exist
// *
// * @param path
// */
// private Stat createPathWithParent(String path, boolean watch){
// // valid
// if (path==null || path.trim().length()==0) {
// return null;
// }
//
// try {
// Stat stat = getClient().exists(path, watch);
// if (stat == null) {
// // valid parent, createWithParent if not exists
// if (path.lastIndexOf("/") > 0) {
// String parentPath = path.substring(0, path.lastIndexOf("/"));
// Stat parentStat = getClient().exists(parentPath, watch);
// if (parentStat == null) {
// createPathWithParent(parentPath, false);
// }
// }
// // create desc node path
// getClient().create(path, new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// }
// return getClient().exists(path, true);
// } catch (Exception e) {
// throw new XxlConfException(e);
// }
// }
//
// /**
// * delete path (watch)
// *
// * @param path
// */
// public void deletePath(String path, boolean watch){
// try {
// Stat stat = getClient().exists(path, watch);
// if (stat != null) {
// getClient().delete(path, stat.getVersion());
// } else {
// logger.info(">>>>>>>>>> zookeeper node path not found :{}", path);
// }
// } catch (Exception e) {
// throw new XxlConfException(e);
// }
// }
//
// /**
// * set data to node (watch)
// *
// * @param path
// * @param data
// * @return
// */
// public Stat setPathData(String path, String data, boolean watch) {
// try {
// Stat stat = getClient().exists(path, watch);
// if (stat == null) {
// createPathWithParent(path, watch);
// stat = getClient().exists(path, watch);
// }
// return getClient().setData(path, data.getBytes("UTF-8"), stat.getVersion());
// } catch (Exception e) {
// throw new XxlConfException(e);
// }
// }
//
// /**
// * get data from node (watch)
// *
// * @param path
// * @return
// */
// public String getPathData(String path, boolean watch){
// try {
// String znodeValue = null;
// Stat stat = getClient().exists(path, watch);
// if (stat != null) {
// byte[] resultData = getClient().getData(path, watch, null);
// if (resultData != null) {
// znodeValue = new String(resultData, "UTF-8");
// }
// } else {
// logger.info(">>>>>>>>>> xxl-conf, path[{}] not found.", path);
// }
// return znodeValue;
// } catch (Exception e) {
// throw new XxlConfException(e);
// }
// }
//
//
//} | xuxueli/xxl-conf | xxl-conf-core/src/main/java/com/xxl/conf/core/deadcode/XxlZkClient.java |
547 | /**
* 思路:
* 例图: n=5
* *
* **
* **
* 从图中可以看出,本题中如果是正常的梯形,第一行 1 *,第二行 2 ** ,第三行 3 *** ..
* 因此使用 index 来标记行,每排列一行,n 就要减去对应的行数,
* 也就是 第一行 index = 1, 排列之后, n 还剩 n=n-index=4, 第二行 index = 2,排列之后 n=n-index=2
* 依次类推,知道 n < index 时,就无法再行程梯形了。
* 时间复杂度应该是 O(n) 吧,
* 还有一种方式就是利用 梯形公式;
*/
class Solution {
public int arrangeCoins(int n) {
if(n==1)
return 1;
int index = 1;
while(index<=n){
n = n-index;
index = index+1;
if(n<index){
break;
}
}
return index-1;
}
}
| algorithm001/algorithm | Week_01/id_81/LeetCode_441_81.java |
549 | package org.javacore.thread.daemon;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* 1. 知道3个WriteTask线程休眠后,CleanerTask才执行
* 2. 从结果中,可以看出队列维持在一定数量当中
* Created by bysocket on 16/3/4.
*/
public class DaemonTest {
public static void main(String[] args) {
Deque<Event> deque = new ArrayDeque<>();
WriterTask writerTask = new WriterTask(deque);
for (int i = 0; i < 3 ; i++) {
Thread thread = new Thread(writerTask);
thread.start();
}
CleanerTask cleanerTask = new CleanerTask(deque);
cleanerTask.start();
}
}
| JeffLi1993/java-core-learning-example | src/main/java/org/javacore/thread/daemon/DaemonTest.java |
550 | /**
* Copyright (c) 2011-2023, James Zhan 詹波 ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jfinal.render;
import java.io.File;
import javax.servlet.ServletContext;
import com.jfinal.config.Constants;
import com.jfinal.template.Engine;
/**
* RenderFactory.
*/
public class RenderFactory implements IRenderFactory {
protected Engine engine;
protected Constants constants;
protected ServletContext servletContext;
protected MainRenderFactory mainRenderFactory;
// private static final RenderFactory me = new RenderFactory();
// private RenderFactory() {}
// public static RenderFactory me() {
// return me;
// }
public void init(Engine engine, Constants constants, ServletContext servletContext) {
this.engine = engine;
this.constants = constants;
this.servletContext = servletContext;
// create mainRenderFactory
switch (constants.getViewType()) {
case JFINAL_TEMPLATE:
mainRenderFactory = new MainRenderFactory();
break ;
case FREE_MARKER:
mainRenderFactory = new FreeMarkerRenderFactory();
break ;
case JSP:
mainRenderFactory = new JspRenderFactory();
break ;
}
}
/**
* Return Render by default ViewType which config in JFinalConfig
*/
public Render getRender(String view) {
return mainRenderFactory.getRender(view);
}
public Render getTemplateRender(String view) {
return new TemplateRender(view);
}
public Render getFreeMarkerRender(String view) {
return new FreeMarkerRender(view);
}
public Render getJspRender(String view) {
return new JspRender(view);
}
public Render getJsonRender() {
return new JsonRender();
}
public Render getJsonRender(String key, Object value) {
return new JsonRender(key, value);
}
public Render getJsonRender(String[] attrs) {
return new JsonRender(attrs);
}
public Render getJsonRender(String jsonText) {
return new JsonRender(jsonText);
}
public Render getJsonRender(Object object) {
return new JsonRender(object);
}
public Render getTextRender(String text) {
return new TextRender(text);
}
public Render getTextRender(String text, String contentType) {
return new TextRender(text, contentType);
}
public Render getTextRender(String text, ContentType contentType) {
return new TextRender(text, contentType);
}
public Render getDefaultRender(String view) {
return getRender(view + constants.getViewExtension());
}
public Render getErrorRender(int errorCode, String viewOrJson) {
return new ErrorRender(errorCode, viewOrJson);
}
public Render getErrorRender(int errorCode) {
// 支持返回 json 数据之后,需要在 ErrorRender.render() 方法内判断 contentType 后才能确定返回 json 还是 html 页面
// 而在此处 ErrorRender.getErrorView(errorCode) 是无法知道 contentType 信息的,故去掉 errorView 参数
// return new ErrorRender(errorCode, ErrorRender.getErrorView(errorCode));
return new ErrorRender(errorCode);
}
public Render getFileRender(String fileName) {
return new FileRender(fileName);
}
public Render getFileRender(String fileName, String downloadFileName) {
return new FileRender(fileName, downloadFileName);
}
public Render getFileRender(File file) {
return new FileRender(file);
}
public Render getFileRender(File file, String downloadFileName) {
return new FileRender(file, downloadFileName);
}
public Render getRedirectRender(String url) {
return new RedirectRender(url);
}
public Render getRedirectRender(String url, boolean withQueryString) {
return new RedirectRender(url, withQueryString);
}
public Render getRedirect301Render(String url) {
return new Redirect301Render(url);
}
public Render getRedirect301Render(String url, boolean withQueryString) {
return new Redirect301Render(url, withQueryString);
}
public Render getNullRender() {
return new NullRender();
}
public Render getJavascriptRender(String jsText) {
return new JavascriptRender(jsText);
}
public Render getHtmlRender(String htmlText) {
return new HtmlRender(htmlText);
}
public Render getXmlRender(String view) {
return new XmlRender(view);
}
public Render getCaptchaRender() {
return new com.jfinal.captcha.CaptchaRender();
}
public Render getQrCodeRender(String content, int width, int height) {
return new QrCodeRender(content, width, height);
}
public Render getQrCodeRender(String content, int width, int height, char errorCorrectionLevel) {
return new QrCodeRender(content, width, height, errorCorrectionLevel);
}
// --------
private static class MainRenderFactory {
public Render getRender(String view) {
return new TemplateRender(view);
}
}
private static class FreeMarkerRenderFactory extends MainRenderFactory {
public Render getRender(String view) {
return new FreeMarkerRender(view);
}
}
private static class JspRenderFactory extends MainRenderFactory {
public Render getRender(String view) {
return new JspRender(view);
}
}
}
| jfinal/jfinal | src/main/java/com/jfinal/render/RenderFactory.java |
551 | import java.util.HashMap;
import java.util.Map;
public class Solution3 {
// 这个问题看文档要好好整理一下,找相同的量
// 把下标和值的关系放在一个哈希表里
// 这个 想不明白
public int findMaxLength(int[] nums) {
int len = nums.length;
Map<Integer, Integer> hashMap = new HashMap<>(len);
// 初始化 -1 的情况
hashMap.put(1, -1);
int res = 0;
int preSum = 0;
for (int i = 0; i < len; i++) {
preSum += nums[i];
// 满足关系式 i + j = 2 * preSum
int j = 2 * preSum - i;
if (hashMap.containsKey(j)) {
res = Math.max(res, i - hashMap.get(j));
} else {
// value 是下标,key 是什么不知道
hashMap.put(j, i);
}
}
// System.out.println(hashMap);
return res;
}
public static void main(String[] args) {
Solution3 solution3 = new Solution3();
int[] nums = new int[]{1, 1, 1, 0, 1, 0, 1};
int res = solution3.findMaxLength(nums);
System.out.println(res);
}
} | liweiwei1419/LeetCode-Solutions-in-Good-Style | 18-prefix-sum/0525-contiguous-array/src/Solution3.java |
553 | ^ 是不完全加法. 每次都忽略了进位。而 & 刚好可以算出需要的所有进位。
那么就,首先记录好进位的数字:carry. 然后 a^b 不完全加法一次。然后b用来放剩下的carry, 每次移动一位,继续加,知道b循环为0为止。
Bit Operation
Steps:
a & b: 每bit可能出得余数
a ^ b: 每bit在此次操作可能留下的值,XOR 操作
每次左移余数1位,然后存到b, 再去跟a做第一步。loop until b == 0
(http://www.meetqun.com/thread-6580-1-1.html)
```
/*
Write a function that add two numbers A and B. You should not use + or any arithmetic operators.
Example
Given a=1 and b=2 return 3
Note
There is no need to read data from standard input stream. Both parameters are given in function aplusb, you job is to calculate the sum and return it.
Challenge
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?
Clarification
Are a and b both 32-bit integers?
Yes.
Can I use bit operation?
Sure you can.
Tags Expand
Cracking The Coding Interview Bit Manipulation
*/
/*
Thought:
Bit operation. Just to remmeber this problem, doing A+B using bit.
*/
class Solution {
public int aplusb(int a, int b) {
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
};
``` | cherryljr/LintCode | A+B.java |
554 | package sf.week8;
/**
* Created by LynnSun on 2019/12/8.
* 力扣题目地址:https://leetcode-cn.com/problems/wildcard-matching
*/
public class WildcardMatching {
/**
*
* @param text
* @param pattern
* @return
*/
public boolean isMatch(String text, String pattern) {
// 多一维的空间,因为求 dp[len - 1][j] 的时候需要知道 dp[len][j] 的情况,
// 多一维的话,就可以把 对 dp[len - 1][j] 也写进循环了
boolean[][] dp = new boolean[text.length() + 1][pattern.length() + 1];
// dp[len][len] 代表两个空串是否匹配了,"" 和 "" ,当然是 true 了。
dp[text.length()][pattern.length()] = true;
// 从 len 开始减少
for (int i = text.length(); i >= 0; i--) {
for (int j = pattern.length(); j >= 0; j--) {
// dp[text.length()][pattern.length()] 已经进行了初始化
if (i == text.length() && j == pattern.length())
continue;
//相比之前增加了判断是否等于 *
boolean first_match = (i < text.length() && j < pattern.length() && (pattern.charAt(j) == text.charAt(i) || pattern.charAt(j) == '?' || pattern.charAt(j) == '*'));
if (j < pattern.length() && pattern.charAt(j) == '*') {
//将 * 跳过 和将字符匹配一个并且 pattern 不变两种情况
dp[i][j] = dp[i][j + 1] || first_match && dp[i + 1][j];
} else {
dp[i][j] = first_match && dp[i + 1][j + 1];
}
}
}
return dp[0][0];
}
/**
* 优化空间复杂度
* https://leetcode-cn.com/problems/wildcard-matching/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-9/
* @param text
* @param pattern
* @return
*/
public boolean isMatch1(String text, String pattern) {
// 多一维的空间,因为求 dp[len - 1][j] 的时候需要知道 dp[len][j] 的情况,
// 多一维的话,就可以把 对 dp[len - 1][j] 也写进循环了
boolean[][] dp = new boolean[2][pattern.length() + 1];
dp[text.length() % 2][pattern.length()] = true;
// 从 len 开始减少
for (int i = text.length(); i >= 0; i--) {
for (int j = pattern.length(); j >= 0; j--) {
if (i == text.length() && j == pattern.length())
continue;
boolean first_match = (i < text.length() && j < pattern.length() && (pattern.charAt(j) == text.charAt(i)
|| pattern.charAt(j) == '?' || pattern.charAt(j) == '*'));
if (j < pattern.length() && pattern.charAt(j) == '*') {
dp[i % 2][j] = dp[i % 2][j + 1] || first_match && dp[(i + 1) % 2][j];
} else {
dp[i % 2][j] = first_match && dp[(i + 1) % 2][j + 1];
}
}
}
return dp[0][0];
}
}
| algorithm004-01/algorithm004-01 | Week 08/id_306/WildcardMatching.java |
555 | /**
* 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;
/**
* Created by lfh on 2016/9/1.
* 书荒区帖子详情
*/
public class BookHelp extends Base{
/**
* _id : 579df15f8eaf3ec231d8bc2b
* type : help
* author : {"_id":"54ec360d77bace32513eabc1",
* "avatar":"/avatar/f1/ca/f1cad586d81253f48b360738b1b90780","nickname":"万剑一","type":"doyen",
* "lv":9,"gender":"male","rank":null,"created":"2015-02-24T08:27:57.000Z",
* "id":"54ec360d77bace32513eabc1"}
* title : 16-8养肥书单
* content : 有些评论不是我写的,但是我尽量挑公允一点的。
《皇帝直播间》
UP主魂穿高武位面的小国纨绔庶皇子,金手指系统+千千万万直播网友,创意满分,文笔平均偏下水准,文中皇帝设定正值壮年+性格多疑,争夺封王位比立功,五皇子散财赈灾,男主拉出一个前世制图专业的设定靠画地图强行当功劳,你了解本国国情吗?知道你爹喜文喜武吗?如果你爹怀疑你借机卖人情给武将或是私下里和武将来往怎么办?与其如此倒不如以五年内成为封圣强者为比试内容(五皇子方也可以选择拉拢一位封圣强者对皇帝效忠)更为妥当,首先这任务你办不到得死,硬条件,第二这个比试不涉及朝堂权力斗争,一个封圣强者拥有灭国级别的核弹实力,成不了男主死五皇子上位,成了自然而然就有自己的势力,夺嫡登基更有竞争力。
《重生之抠脚大汉变男神》
我想评价这本书的时候我必须要再一次抬出这句话了:“一本书的主角其实是作者本身特质的折射”,所以我猜测作者应该是一位拥有少女心的抠脚大汉,在闲暇午睡时来了一场如同成人童话一般的梦中重生之旅。然后,就有了这本书。虽然脱胎于某种逗比小白文的文字风格很有趣,但这类文总有一个后劲不强容易腻的通病,所以后续如何要看作者的功力。哦对了,为什么我说这书脱胎逗比小白文,因为有一些情节实在是太幼稚了,忽略那些毒点是可看的。
《气吞寰宇》
教主的新书,先养着
《百年家书》
作者文笔很好,实体风,也表现出民国的波澜壮阔。但是文风看的很累,加上写的是那个残酷的年代就更累了。
按我的说法,不会刻意去找这本书,但如果在书店碰到会买下来。但是平常在网上不会选择阅读这类书。原因不管是爽文还是虐文,看着不会累,毕竟看网络小说就是为了消遣娱乐。但是你会在休息时间在网上看悲惨世界,围城之类的名著吗?这种书还是适合实体
《红龙》
异世-异类,量大管饱,更新较慢,著名异类文兼气管炎老司机接口卡的老坑,讲述主角死后重生为一条与众不同的红龙睡觉或破坏的日常,从用牙齿种出管钱的女儿到体内长出核反应堆。目前已变成为眼里只剩母蜥蜴的淫龙,果断上了亲妹。
《韩警官》
很有味道的一本官场刑侦小说,主角重生怀疑自己做梦,家庭和睦,仕途顺利,主角慢慢向警察发展,很喜欢里面的风格,九十年代的气息扑面而来,那时候的精气神,基层人民的生活,都很好的展示出来了。作者安排的金手指大多是主角的个人道德修养吧,谦虚周到理智精明,剧情上的硬伤倒是没怎么发现。单看前几章作者对主角的安排——整顿夜市、参加律师考试,就能看出作者的精心经营,慢慢雕琢的主角谁不喜欢呢?现实中读者大多没有目的性,那么网文中行事有条理有强烈目的性的主角自然会得到众人的欢心了。另,提醒:这本几乎没有明显的装逼打脸情节,不要拿一般官场文度之,恩,比余罪严肃很多。
《特拉福买家俱乐部》
首先主角三观较正,并非见钱眼开,交易了就什么都不管的主,甚至遇到了那种穷凶极恶的交易者,还会体现出些许另类的「侠者之气」,看了不难受。
第二,文笔不错,行文流畅,顺带一提对于人偶妹子的描写让我这个轻度人偶控相当的受用。
第三,这本小说好像有那啥的倾向....不说太多,给你们四个字「圣母降临」,也是坛子里作者的作品,老司机们自然就明白了。
《柯南世界里的巫师》
作为柯南同人居然敢穿插奇门异术的力量体系,暗世界的设定可见作者魄力,这么一写俨然是鹤立鸡群,新意突显啊。文笔虽谈不上上上之选但也是流畅无阻,可以说是柯南同人中鲜有的佳作。不足之处在于感情描写颇是仓促缺乏点睛之笔,人物形象略显单一苍白。
《大明1630》
总体来说还是有干粮水平的,主角国姓爷身份的切入点也挺特别,里面几段主角立论也写得挺好。主要问题在于部分对话用语太现代,会冒出有些可能没有的词汇,还有一个攀科技树的小说一般都会出现不太切合实际这个问题。
《重生之出人头地》
沧海的马甲,真正的智斗流,写的比本尊那本兵锋无双好,沧海还是最适合写香港。各种细节信手拈來,现实和电影糅合在一起,那不是香港又是香港,那就是我们心目中的香港江湖。
《放开那个女巫》
很多人都说好的书,的确很好。仙草-。主角来到个类似中世纪(冰与火?)的时代,拯救了一群女巫,利用女巫的超能力快速发展工业,用钢铁枪炮与兄弟姐妹争夺王位的故事。好吧,虽然是中世纪发展工业,不过看点完全不在这!最大的看点是,在最黑暗的年代,主角王子扮演救世主的角色,拯救了一群被残酷迫害的女巫妹子的故事。这是多么伟大和圣母啊!!哈哈,不完全是开玩笑,工业什么的看看就行了,最好看的还是主角和妹子的互动。
《我的魔法时代》
穿越玄幻类小说,从5岁写起,整体氛围很好,没那么多戾气,文笔好。但是相应的主角的心态上感觉有些弱鸡。慢热 好看就是更的慢 又的养了。
《暗影圣贤》
作者这么爱吐槽为什么不干脆写一本逗逼文呢?上本这样,这本也是,不说写出史诗感至少也应该严肃点,插进去的各种明显是作者的无厘头吐槽配上救世题材……
《绝顶枪王》
本文选择的游戏是枪战类。之后主角做游戏通关任务,妙趣横生,又很能体现主角的实力。作者这样把竞技和游戏任务结合在一起写,很赞,至少节奏把握的很好。生活情节虽然满满热血漫的既视感,但作者把握住了风格,青春热血,激情奋斗的味道写出来了,这也就够了。对比作者的上一本书,感觉这次进步很大,作者比较擅长写这方面的故事,期待作者能保持水平,继续进步。
《这锅我不背》
晋江位面的特产——搞基文,不喜勿入。 脑洞巨大,创意独特,非常有意思的小说,作者的脑回路有异于常人,看这本书看看创意还是蛮爽的,搞基部分自动屏蔽就好了
《从酋长到球长》
看着就能感觉作者的写作水平又提高了,额,或者说这个作者本来的文字水平就是顶尖一系列的,写这本书的过程中逐渐熟悉了网文读者的好恶,努力的去写成一本网文。这么说或者有点乱,不过大概可以理解为用平铺直叙的方式来讲一个故事的情况下让你感觉到文字的美感。并且情节的把控上水平也有所提高。而且作者没有范文青病,最近的文字在超好的文笔与文青之间,非常好的把握住了那个度,让人看起来非常舒服。好书不容错过。
《[综]天生反派》
这根本就是个男版林黛玉,既不能做到有恩报恩,又不能做到有仇报仇,每次都是病殃殃的让别人可怜,最后英年早逝把所有关心他的人伤害个遍,真是个废物。
《远东王庭》
颇为有趣的DND作品,金手指虽然巴拉巴拉解释了一连串,但是和系统流差别其实不是很大。 作者应该是老作者,很明白怎么在爽的同时调整主角的进步速度。
《魔神乐园》
主流小白文的模板,准一流的打斗描写。为了配合小白文写法,反派的魅力被削弱很多。 支线加入同伴的描写,比前两本进步,有亮点。 总体来说:可以一看,有毒点,跳着看还不错。
这次书不多,主要这半年也没什么好书,说实话
* state : distillate
* updated : 2016-09-01T09:11:39.597Z
* created : 2016-07-31T12:38:55.286Z
* commentCount : 256
* shareLink : http://share.zhuishushenqi.com/post/579df15f8eaf3ec231d8bc2b
* id : 579df15f8eaf3ec231d8bc2b
*/
public HelpBean help;
public static class HelpBean {
public String _id;
public String type;
/**
* _id : 54ec360d77bace32513eabc1
* avatar : /avatar/f1/ca/f1cad586d81253f48b360738b1b90780
* nickname : 万剑一
* type : doyen
* lv : 9
* gender : male
* rank : null
* created : 2015-02-24T08:27:57.000Z
* id : 54ec360d77bace32513eabc1
*/
public AuthorBean author;
public String title;
public String content;
public String state;
public String updated;
public String created;
public int commentCount;
public String shareLink;
public String id;
public static class AuthorBean {
public String _id;
public String avatar;
public String nickname;
public String type;
public int lv;
public String gender;
public Object rank;
public String created;
public String id;
}
}
}
| smuyyh/BookReader | app/src/main/java/com/justwayward/reader/bean/BookHelp.java |
556 | package com.weishu.intercept_activity.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.weishu.intercept_activity.app.hook.AMSHookHelper;
/**
* @author weishu
* @date 16/1/7.
*/
public class MainActivity extends Activity {
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
try {
AMSHookHelper.hookActivityManagerNative();
AMSHookHelper.hookActivityThreadHandler();
} catch (Throwable throwable) {
throw new RuntimeException("hook failed", throwable);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("启动TargetActivity");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 启动目标Activity; 注意这个Activity是没有在AndroidManifest.xml中显式声明的
// 但是调用者并不需要知道, 就像一个普通的Activity一样
startActivity(new Intent(MainActivity.this, TargetActivity.class));
}
});
setContentView(button);
}
}
| tiann/understand-plugin-framework | intercept-activity/src/main/java/com/weishu/intercept_activity/app/MainActivity.java |
557 | /*
* Copyright (C) 2015-present, Ant Financial Services 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.alipay.hulu.shared.node.utils;
import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import com.alipay.hulu.common.application.LauncherApplication;
import com.alipay.hulu.common.service.SPService;
import com.alipay.hulu.common.tools.CmdTools;
import com.alipay.hulu.common.utils.LogUtil;
import com.alipay.hulu.common.utils.MiscUtil;
import com.alipay.hulu.common.utils.StringUtil;
import com.alipay.hulu.shared.node.OperationService;
import com.alipay.hulu.shared.node.action.OperationMethod;
import com.alipay.hulu.shared.node.action.PerformActionEnum;
import com.alipay.hulu.shared.node.locater.OperationNodeLocator;
import com.alipay.hulu.shared.node.tree.AbstractNodeTree;
import com.alipay.hulu.shared.node.tree.OperationNode;
import com.alipay.hulu.shared.node.tree.capture.CaptureTree;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 节点工具
* Created by cathor on 2017/12/13.
*/
public class OperationUtil {
private static final String TAG = "OperationUtil";
private static final Map<CharSequence, Integer> alertContentMap;
public static final int MAX_CONTENT_PRIORITY = Integer.MAX_VALUE;
static {
//Map中的Integer代表优先级,值越小优先级越高
Map<CharSequence, Integer> map = new HashMap<>();
map.put("打开", 0);
map.put("打开应用", 0);
map.put("同意并安装", 0);
map.put("下一步", 0);
map.put("允许", 1);
map.put("始终允许", 1);
map.put("总是允许", 1);
map.put("仅在使用中允许", 1);
map.put("仅在使用该应用时允许", 1);
map.put("安装", 1);
map.put("重新安装", 1);
map.put("继续安装", 1);
map.put("继续安装旧版本", 1);
map.put("我已充分了解该风险,继续安装", 1);
map.put("允许本次安装", 1);
map.put("同意", 1);
map.put("立即切换", 1);
map.put("好", 2);
map.put("好的", 2);
map.put("确认", 2);
map.put("确定", 2);
map.put("完成", 2);
map.put("验证", 2);
map.put("忽略", 3);
map.put("稍候再说", 3);
map.put("下次再说", 3);
map.put("稍后再说", 3);
map.put("以后再说", 3);
map.put("稍后提醒", 3);
map.put("知道了", 4);
map.put("我知道了", 4);
map.put("朕知道了", 4);
map.put("我知道啦", 4);
map.put("立即删除", 5);
map.put("清除", 5);
map.put("跳过", 5);
map.put("立即清理", 6);
map.put("忽略风险", 7);
alertContentMap = Collections.unmodifiableMap(map);
}
public static boolean isInAlertDict(CharSequence charSequence) {
if (StringUtil.isEmpty(charSequence)) {
return false;
}
for (CharSequence content : alertContentMap.keySet()) {
if (StringUtil.equals(content, charSequence)) {
return true;
}
}
return false;
}
public static int getContentPriority(CharSequence charSequence) {
if (StringUtil.isEmpty(charSequence)) {
return MAX_CONTENT_PRIORITY;
}
for (CharSequence content : alertContentMap.keySet()) {
if (StringUtil.equals(content, charSequence)) {
return alertContentMap.get(content);
}
}
return MAX_CONTENT_PRIORITY;
}
/**
* 滑动控件到屏幕内
* @param node
* @param service
* @return
*/
public static AbstractNodeTree scrollToScreen(OperationNode node, OperationService service) {
try {
// 先查询记录的节点
AbstractNodeTree operationNode;
int pos = 0;
DisplayMetrics dm = new DisplayMetrics();
((WindowManager) LauncherApplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealMetrics(dm);
int height = dm.heightPixels;
int width = dm.widthPixels;
int scrollCount = 0;
do {
service.invalidRoot();
AbstractNodeTree tmpRoot = service.getCurrentRoot();
operationNode = OperationNodeLocator.findAbstractNode(tmpRoot, node);
// 查询为空,未找到
if (operationNode == null) {
LogUtil.w(TAG, "查找控件【%s】失败", node);
return null;
}
// CaptureTree直接结束
if (!(operationNode instanceof CaptureTree)) {
// 判断下是否在屏幕内
Rect bound = operationNode.getNodeBound();
LogUtil.d(TAG, "控件空间属性:%s, 屏幕属性:%s", bound, dm);
if (bound.bottom <= 5) {
service.doSomeAction(new OperationMethod(PerformActionEnum.GLOBAL_SCROLL_TO_BOTTOM), null);
MiscUtil.sleep(2500);
scrollCount ++;
} else if (bound.top >= height - 5) {
service.doSomeAction(new OperationMethod(PerformActionEnum.GLOBAL_SCROLL_TO_TOP), null);
MiscUtil.sleep(2500);
scrollCount ++;
} else if (bound.centerX() <= 5) {
service.doSomeAction(new OperationMethod(PerformActionEnum.GLOBAL_SCROLL_TO_RIGHT), null);
MiscUtil.sleep(2500);
scrollCount ++;
} else if (bound.centerX() >= width - 5) {
service.doSomeAction(new OperationMethod(PerformActionEnum.GLOBAL_SCROLL_TO_LEFT), null);
MiscUtil.sleep(2500);
scrollCount ++;
} else {
pos = 1;
}
} else {
pos = 1;
}
} while (pos != 1 && scrollCount < 3);
LogUtil.d(TAG, "找到节点: " + operationNode);
return operationNode;
} catch (Exception e) {
LogUtil.e(TAG, e, "节点查找失败,节点: %s", node);
return null;
}
}
public static void sleepUntilTargetActivitiesShown(String... targetActivities) {
if (targetActivities == null || targetActivities.length == 0) {
return;
}
String curActivity = "";
long start = System.currentTimeMillis();
while (!isCurActivityInTargetArray(curActivity, targetActivities) && System.currentTimeMillis() - start < 60*1000) {
MiscUtil.sleep(5000);
curActivity = CmdTools.getTopActivity();
}
}
private static boolean isCurActivityInTargetArray(String curActivity, String... targetActivities) {
if (targetActivities == null || targetActivities.length == 0 || curActivity == null) {
return false;
}
for (String activity : targetActivities) {
if (curActivity.contains(activity)) {
return true;
}
}
return false;
}
public static AbstractNodeTree findAbstractNode(OperationNode node, OperationService service) {
return findAbstractNode(node, service, null);
}
/**
* 查找控件
* @param node
* @param service
* @return
*/
public static AbstractNodeTree findAbstractNode(OperationNode node, OperationService service, List<String> prepareActions) {
AbstractNodeTree tmpRoot = null;
try {
service.invalidRoot();
tmpRoot = service.getCurrentRoot();
} catch (Exception e) {
e.printStackTrace();
}
// 拿不到root
if (tmpRoot == null) {
return null;
}
AbstractNodeTree targetNode = null;
// 两次处理弹窗
int maxCount = 2;
while (targetNode == null && maxCount > 0) {
targetNode = scrollToScreen(node, service);
maxCount--;
// 找不到,先处理下弹窗
if (targetNode == null) {
long startTime = System.currentTimeMillis();
service.doSomeAction(new OperationMethod(PerformActionEnum.HANDLE_ALERT), null);
if (prepareActions != null) {
prepareActions.add(PerformActionEnum.HANDLE_ALERT.getDesc());
}
// 没有实际处理掉弹窗
if (System.currentTimeMillis() - startTime < 1500) {
break;
}
service.invalidRoot();
}
}
// 上滑刷新两次
maxCount = SPService.getInt(SPService.KEY_MAX_SCROLL_FIND_COUNT, 0);
while (targetNode == null && maxCount > 0) {
targetNode = scrollToScreen(node, service);
maxCount--;
// 找不到,先向上滑刷新
if (targetNode == null) {
service.doSomeAction(new OperationMethod(PerformActionEnum.GLOBAL_SCROLL_TO_BOTTOM), null);
if (prepareActions != null) {
prepareActions.add(PerformActionEnum.GLOBAL_SCROLL_TO_BOTTOM.getDesc());
}
} else {
break;
}
MiscUtil.sleep(1500);
service.invalidRoot();
}
// 下滑查找四次
maxCount = SPService.getInt(SPService.KEY_MAX_SCROLL_FIND_COUNT, 0) * 2;
while (targetNode == null && maxCount > 0) {
targetNode = scrollToScreen(node, service);
maxCount--;
if (targetNode == null) {
service.doSomeAction(new OperationMethod(PerformActionEnum.GLOBAL_SCROLL_TO_TOP), null);
if (prepareActions != null) {
prepareActions.add(PerformActionEnum.GLOBAL_SCROLL_TO_TOP.getDesc());
}
} else {
break;
}
MiscUtil.sleep(1500);
service.invalidRoot();
}
return targetNode;
}
/**
* 查找控件
* @param node
* @param service
* @return
*/
public static AbstractNodeTree findAbstractNodeWithoutScroll(OperationNode node, OperationService service, List<String> prepareActions) {
AbstractNodeTree tmpRoot = null;
try {
tmpRoot = service.getCurrentRoot();
} catch (Exception e) {
e.printStackTrace();
}
// 拿不到root
if (tmpRoot == null) {
return null;
}
AbstractNodeTree targetNode = null;
// 两次处理弹窗
int maxCount = 2;
while (targetNode == null && maxCount > 0) {
targetNode = scrollToScreen(node, service);
maxCount--;
// 找不到,先处理下弹窗
if (targetNode == null) {
long startTime = System.currentTimeMillis();
service.doSomeAction(new OperationMethod(PerformActionEnum.HANDLE_ALERT), null);
if (prepareActions != null) {
prepareActions.add(PerformActionEnum.HANDLE_ALERT.getDesc());
}
// 没有实际处理弹窗
if (System.currentTimeMillis() - startTime < 1500) {
break;
}
service.invalidRoot();
}
}
return targetNode;
}
}
| alipay/SoloPi | src/shared/src/main/java/com/alipay/hulu/shared/node/utils/OperationUtil.java |
558 | package com.roncoo.pay;
import com.roncoo.pay.app.polling.core.PollingPersist;
import com.roncoo.pay.app.polling.core.PollingTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.annotation.PostConstruct;
import java.util.concurrent.DelayQueue;
@SpringBootApplication
public class AppOrderPollingApplication {
private static final Log LOG = LogFactory.getLog(AppOrderPollingApplication.class);
public static DelayQueue<PollingTask> tasks = new DelayQueue<PollingTask>();
@Autowired
private ThreadPoolTaskExecutor threadPool;
@Autowired
public PollingPersist pollingPersist;
private static ThreadPoolTaskExecutor cacheThreadPool;
public static PollingPersist cachePollingPersist;
public static void main(String[] args) {
// SpringApplication.run(AppOrderPollingApplication.class, args);
new SpringApplicationBuilder().sources(AppOrderPollingApplication.class).web(WebApplicationType.NONE).run(args);
}
@PostConstruct
public void init() {
cacheThreadPool = threadPool;
cachePollingPersist = pollingPersist;
startThread();
}
private void startThread() {
LOG.info("==>startThread");
cacheThreadPool.execute(new Runnable() {
public void run() {
try {
while (true) {
Thread.sleep(100);
LOG.info("==>threadPool.getActiveCount():" + cacheThreadPool.getActiveCount());
LOG.info("==>threadPool.getMaxPoolSize():" + cacheThreadPool.getMaxPoolSize());
// 如果当前活动线程等于最大线程,那么不执行
if (cacheThreadPool.getActiveCount() < cacheThreadPool.getMaxPoolSize()) {
LOG.info("==>tasks.size():" + tasks.size());
final PollingTask task = tasks.take(); //使用take方法获取过期任务,如果获取不到,就一直等待,知道获取到数据
if (task != null) {
cacheThreadPool.execute(new Runnable() {
public void run() {
tasks.remove(task);
task.run(); // 执行通知处理
LOG.info("==>tasks.size():" + tasks.size());
}
});
}
}
}
} catch (Exception e) {
LOG.error("系统异常;", e);
}
}
});
}
}
| roncoo/roncoo-pay | roncoo-pay-app-order-polling/src/main/java/com/roncoo/pay/AppOrderPollingApplication.java |
559 | package com.u9porn.ui.about;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.util.QMUIPackageHelper;
import com.qmuiteam.qmui.widget.QMUILoadingView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.sdsmdg.tastytoast.TastyToast;
import com.u9porn.R;
import com.u9porn.data.model.UpdateVersion;
import com.u9porn.service.UpdateDownloadService;
import com.u9porn.ui.MvpActivity;
import com.u9porn.utils.ApkVersionUtils;
import com.u9porn.utils.AppCacheUtils;
import com.u9porn.utils.DialogUtils;
import com.u9porn.utils.GlideApp;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.common.io.FileUtils;
import ru.noties.markwon.Markwon;
/**
* @author flymegoc
*/
public class AboutActivity extends MvpActivity<AboutView, AboutPresenter> implements AboutView {
private static final String TAG = AboutActivity.class.getSimpleName();
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.version)
TextView mVersionTextView;
@BindView(R.id.about_list)
QMUIGroupListView mAboutGroupListView;
@BindView(R.id.copyright)
TextView mCopyrightTextView;
private AlertDialog alertDialog;
private AlertDialog cleanCacheDialog;
private QMUICommonListItemView cleanCacheQMUICommonListItemView;
@Inject
protected AboutPresenter aboutPresenter;
private TextView commonQuestionTextView;
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
ButterKnife.bind(this);
initToolBar(toolbar);
initAboutSection();
mVersionTextView.setText("v" + QMUIPackageHelper.getAppVersion(this));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy", Locale.CHINA);
String currentYear = dateFormat.format(new java.util.Date());
mCopyrightTextView.setText(String.format(getResources().getString(R.string.about_copyright), currentYear));
alertDialog = DialogUtils.initLoadingDialog(this, "正在检查更新,请稍后...");
presenter.countCacheFileSize(getString(R.string.about_item_clean_cache));
}
private void initAboutSection() {
mAboutGroupListView.setSeparatorStyle(QMUIGroupListView.SEPARATOR_STYLE_NORMAL);
cleanCacheQMUICommonListItemView = mAboutGroupListView.createItemView(getString(R.string.about_item_clean_cache));
cleanCacheQMUICommonListItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
QMUILoadingView loadingView = new QMUILoadingView(this);
cleanCacheQMUICommonListItemView.addAccessoryCustomView(loadingView);
QMUIGroupListView.newSection(this)
.addItemView(mAboutGroupListView.createItemView(getResources().getString(R.string.about_item_github)), new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://github.com/techGay/v9porn";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
})
.addItemView(mAboutGroupListView.createItemView(getResources().getString(R.string.about_item_homepage)), new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://github.com/techGay/v9porn/issues";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
})
.addItemView(mAboutGroupListView.createItemView("赞赏我,请我喝杯咖啡"), new View.OnClickListener() {
@Override
public void onClick(View v) {
showAppreciateDialog();
}
})
.addItemView(cleanCacheQMUICommonListItemView, new View.OnClickListener() {
@Override
public void onClick(View v) {
showChoiceCacheCleanDialog();
}
})
.addItemView(mAboutGroupListView.createItemView("常见问题"), new View.OnClickListener() {
@Override
public void onClick(View v) {
showCommonQuestionsDialog();
}
})
.addItemView(mAboutGroupListView.createItemView(getResources().getString(R.string.about_check_update)), new View.OnClickListener() {
@Override
public void onClick(View v) {
int versionCode = ApkVersionUtils.getVersionCode(AboutActivity.this);
if (versionCode == 0) {
showMessage("获取应用本版失败", TastyToast.ERROR);
return;
}
alertDialog.show();
presenter.checkUpdate(versionCode);
}
})
.addTo(mAboutGroupListView);
}
private void showCommonQuestionsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyDialogTheme);
builder.setTitle("常见问题");
View view = View.inflate(this, R.layout.layout_common_questions, null);
commonQuestionTextView = view.findViewById(R.id.tv_common_question);
Markwon.setMarkdown(commonQuestionTextView, "**加载中...**");
builder.setView(view);
builder.setCancelable(false);
builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
commonQuestionTextView=null;
dialog.dismiss();
}
});
builder.show();
presenter.commonQuestions();
}
private void showAppreciateDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyDialogTheme);
builder.setTitle("赞赏作者");
View view = View.inflate(this, R.layout.layout_appreciate_qrcode, null);
final ImageView imageViewWebChat = view.findViewById(R.id.iv_appreciate_qr_code_web_chat);
final ImageView imageViewAliPay = view.findViewById(R.id.iv_appreciate_qr_code_ali_pay);
final RadioGroup radioGroup = view.findViewById(R.id.rg_pay);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_web_chat:
imageViewWebChat.setVisibility(View.VISIBLE);
imageViewAliPay.setVisibility(View.GONE);
break;
case R.id.rb_ali_pay:
imageViewWebChat.setVisibility(View.GONE);
imageViewAliPay.setVisibility(View.VISIBLE);
break;
}
}
});
builder.setView(view);
builder.setNegativeButton("算了,囊中羞涩", null);
builder.setPositiveButton("保存至相册", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (radioGroup.getCheckedRadioButtonId() == R.id.rb_ali_pay) {
saveToSystemGallery("zhi_fu_bao", R.drawable.alipay1547141972480);
} else {
saveToSystemGallery("wei_xin", R.drawable.mm_reward_qrcode_1547141812376);
}
}
});
builder.show();
}
private void saveToSystemGallery(final String name, int id) {
GlideApp.with(this).downloadOnly().load(id).into(new SimpleTarget<File>() {
@Override
public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), name + ".jpg");
try {
FileUtils.copyFile(resource, file);
showMessage("保存图片成功了", TastyToast.SUCCESS);
notifySystemGallery(file);
} catch (IOException e) {
e.printStackTrace();
showMessage("保存图片失败了", TastyToast.ERROR);
}
}
});
}
private void notifySystemGallery(File file) {
MediaScannerConnection.scanFile(this, new String[]{file.getAbsolutePath()}, new String[]{"image/jpeg"}, null);
}
private void showChoiceCacheCleanDialog() {
final String[] items = new String[]{
"网页缓存(" + AppCacheUtils.getRxcacheFileSizeStr(this) + ")",
"视频缓存(" + AppCacheUtils.getVideoCacheFileSizeStr(this) + ")",
"图片缓存(" + AppCacheUtils.getGlidecacheFileSizeStr(this) + ")"
};
final QMUIDialog.MultiCheckableDialogBuilder builder = new QMUIDialog.MultiCheckableDialogBuilder(this)
.setCheckedItems(new int[]{1})
.addItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setTitle("请选择要清除的缓存");
builder.addAction("取消", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
});
builder.addAction("清除", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
actionCleanFile(builder);
dialog.dismiss();
}
});
builder.show();
}
private void actionCleanFile(QMUIDialog.MultiCheckableDialogBuilder builder) {
int selectIndexLength = builder.getCheckedItemIndexes().length;
List<File> fileDirList = new ArrayList<>();
for (int i = 0; i < selectIndexLength; i++) {
int indexCheck = builder.getCheckedItemIndexes()[i];
switch (indexCheck) {
case 0:
fileDirList.add(AppCacheUtils.getRxCacheDir(AboutActivity.this));
break;
case 1:
fileDirList.add(AppCacheUtils.getVideoCacheDir(AboutActivity.this));
break;
case 2:
fileDirList.add(AppCacheUtils.getGlideDiskCacheDir(AboutActivity.this));
default:
}
}
if (fileDirList.size() == 0) {
showMessage("未选择任何条目,无法清除缓存", TastyToast.INFO);
return;
}
presenter.cleanCacheFile(fileDirList);
}
private String getCleanCacheTitle() {
String zeroFileSize = "0 B";
String fileSizeStr = AppCacheUtils.getAllCacheFileSizeStr(this);
if (zeroFileSize.equals(fileSizeStr)) {
return getResources().getString(R.string.about_item_clean_cache);
}
return getResources().getString(R.string.about_item_clean_cache) + "(" + fileSizeStr + ")";
}
@NonNull
@Override
public AboutPresenter createPresenter() {
return aboutPresenter;
}
private void showUpdateDialog(final UpdateVersion updateVersion) {
new QMUIDialog.MessageDialogBuilder(this)
.setTitle("发现新版本--v" + updateVersion.getVersionName())
.setMessage(updateVersion.getUpdateMessage())
.addAction("立即更新", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
showMessage("开始下载", TastyToast.INFO);
Intent intent = new Intent(AboutActivity.this, UpdateDownloadService.class);
intent.putExtra("updateVersion", updateVersion);
startService(intent);
}
})
.addAction("稍后更新", new QMUIDialogAction.ActionListener() {
@Override
public void onClick(QMUIDialog dialog, int index) {
dialog.dismiss();
}
})
.show();
}
@Override
public void needUpdate(UpdateVersion updateVersion) {
showUpdateDialog(updateVersion);
}
@Override
public void noNeedUpdate() {
showMessage("当前已是最新版本", TastyToast.SUCCESS);
}
@Override
public void checkUpdateError(String message) {
showMessage(message, TastyToast.ERROR);
}
@Override
public void showLoading(boolean pullToRefresh) {
alertDialog.show();
}
@Override
public void showContent() {
dismissDialog();
}
@Override
public void showMessage(String msg, int type) {
super.showMessage(msg, type);
}
@Override
public void showError(String message) {
showMessage(message, TastyToast.ERROR);
}
@Override
public void showCleanDialog(String message) {
cleanCacheDialog = DialogUtils.initLoadingDialog(this, message);
cleanCacheDialog.show();
}
@Override
public void cleanCacheSuccess(String message) {
dismissDialog();
cleanCacheQMUICommonListItemView.setText(getCleanCacheTitle());
showMessage(message, TastyToast.SUCCESS);
}
@Override
public void cleanCacheFailure(String message) {
dismissDialog();
showMessage(message, TastyToast.ERROR);
}
@Override
public void finishCountCacheFileSize(String message) {
cleanCacheQMUICommonListItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_NONE);
cleanCacheQMUICommonListItemView.setText(message);
}
@Override
public void countCacheFileSizeError(String message) {
showMessage(message, TastyToast.ERROR);
}
@Override
public void loadCommonQuestionsSuccess(String mdString) {
Logger.t(TAG).d(mdString);
if (commonQuestionTextView != null) {
Markwon.setMarkdown(commonQuestionTextView, mdString);
}
}
@Override
public void loadCommonQuestionsFailure(String errorMessage, int code) {
showError(errorMessage);
}
private void dismissDialog() {
if (alertDialog != null && alertDialog.isShowing() && !isFinishing()) {
alertDialog.dismiss();
} else if (cleanCacheDialog != null && cleanCacheDialog.isShowing() && !isFinishing()) {
cleanCacheDialog.dismiss();
}
}
}
| techGay/v9porn | app/src/main/java/com/u9porn/ui/about/AboutActivity.java |
560 | package com.engineer.imitate.util;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;
/**
* 打开其他应用 Activity
* <p>
* https://www.cnblogs.com/loaderman/p/12156274.html
*/
public class TestHelper {
private static final String TAG = "TestHelper";
private static final String PACKAGE_NAME = "home.smart.fly.animations";
public static boolean openActivity(Context context) {
Log.d(TAG, "openActivity() called with: context = [" + context + "]");
Intent intent = new Intent(Intent.ACTION_MAIN);
/**知道要跳转应用的包命与目标Activity*/
ComponentName componentName =
new ComponentName(PACKAGE_NAME,
"home.smart.fly.animations.ui.activity.BitmapMeshActivity");
intent.setComponent(componentName);
context.startActivity(intent);
return true;
}
public static boolean openActivityHome(Context context) {
Log.d(TAG, "openActivityHome() called with: context = [" + context + "]");
PackageManager packageManager = context.getPackageManager();
for (PackageInfo installedPackage : packageManager.getInstalledPackages(
PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES)) {
Log.i(TAG, "package " + installedPackage.packageName);
}
Intent intent = context.getPackageManager().getLaunchIntentForPackage(PACKAGE_NAME);
if (intent != null) {
intent.putExtra("type", "110");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
return true;
}
public static boolean openActivityByUrl(Context context) {
Log.d(TAG, "openActivityByUrl() called with: context = [" + context + "]");
Intent intent = new Intent();
intent.setData(Uri.parse("custom_scheme://custom_host"));
intent.putExtra("", ""); // 这里Intent当然也可传递参数,但是一般情况下都会放到上面的URL中进行传递
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
return true;
}
}
| REBOOTERS/AndroidAnimationExercise | imitate/src/main/java/com/engineer/imitate/util/TestHelper.java |
561 | package com.meis.widget.particle;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.Point;
import java.util.Random;
/**
* Created by wenshi on 2018/7/4.
* Description 浮点粒子
*/
public class FloatParticle {
// 三阶贝塞尔曲线
private Point startPoint;
private Point endPoint;
private Point controlPoint1;
private Point controlPoint2;
private Paint mPaint;
private Path mPath;
private Random mRandom;
// 圆半径
private float mRadius = 5;
// 控件宽度
private int mWidth;
// 控件高度
private int mHeight;
private float mCurDistance = 0;
private static final int DISTANCE = 255;
private static final float MOVE_PER_FRAME = 1f;
// 火花外侧阴影大小
private static final float BLUR_SIZE = 5.0F;
// 路径测量
private PathMeasure mPathMeasure;
private float mMeasureLength;
public FloatParticle(int width, int height) {
mWidth = width;
mHeight = height;
mRandom = new Random();
startPoint = new Point((int) (mRandom.nextFloat() * mWidth), (int) (mRandom.nextFloat() * mHeight));
// 抗锯齿
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.WHITE);
// 防抖动
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.FILL);
// 设置模糊效果 边缘模糊
mPaint.setMaskFilter(new BlurMaskFilter(BLUR_SIZE, BlurMaskFilter.Blur.SOLID));
mPath = new Path();
mPathMeasure = new PathMeasure();
startPoint.x = (int) (mRandom.nextFloat() * mWidth);
startPoint.y = (int) (mRandom.nextFloat() * mHeight);
}
public void drawParticle(Canvas canvas) {
// 初始化三阶贝塞尔曲线数据
if (mCurDistance == 0) {
endPoint = getRandomPointRange(startPoint.x, startPoint.y, DISTANCE);
controlPoint1 = getRandomPointRange(startPoint.x, startPoint.y, mRandom.nextInt(Math.min(mWidth, mHeight) / 2));
controlPoint2 = getRandomPointRange(endPoint.x, endPoint.y, mRandom.nextInt(Math.min(mWidth, mHeight) / 2));
// 添加贝塞尔曲线路径
mPath.reset();
mPath.moveTo(startPoint.x, startPoint.y);
mPath.cubicTo(controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, endPoint.x, endPoint.y);
mPathMeasure.setPath(mPath, false);
mMeasureLength = mPathMeasure.getLength();
}
//计算当前坐标点
float[] loc = new float[2];
mPathMeasure.getPosTan(mCurDistance / DISTANCE * mMeasureLength, loc, null);
startPoint.x = (int) loc[0];
startPoint.y = (int) loc[1];
// 递增1
mCurDistance += MOVE_PER_FRAME;
if (mCurDistance >= DISTANCE) {
mCurDistance = 0;
}
canvas.drawCircle(startPoint.x, startPoint.y, mRadius, mPaint);
}
/**
* @param baseX 基准坐标x
* @param baseY 基准坐标y
* @param range 指定范围长度
* @return 根据基准点获取指定范围的随机点
*/
private Point getRandomPointRange(int baseX, int baseY, int range) {
int randomX = 0;
int randomY = 0;
//range指定长度为255,可以根据实际效果调整
if (range <= 0) {
range = 1;
}
//我们知道一点(baseX,baseY)求与它距离长度为range的另一点
//两点x方向的距离(随机产生)
int distanceX = mRandom.nextInt(range);
//知道x方向的距离与斜边的距离求y方向的距离
int distanceY = (int) Math.sqrt(range * range - distanceX * distanceX);
randomX = baseX + getRandomPNValue(distanceX);
randomY = baseY + getRandomPNValue(distanceY);
if (randomX > mWidth) {
randomX = mWidth - range;
} else if (randomX < 0) {
randomX = range;
} else if (randomY > mHeight) {
randomY = mHeight - range;
} else if (randomY < 0) {
randomY = range;
}
return new Point(randomX, randomY);
}
/**
* 获取随机的正负值
*
* @return
*/
private int getRandomPNValue(int value) {
return mRandom.nextBoolean() ? value : 0 - value;
}
/**
* 设置圆半径
*
* @param radius
*/
public void setRadius(float radius) {
mRadius = radius;
}
}
| HpWens/MeiWidgetView | widget/src/main/java/com/meis/widget/particle/FloatParticle.java |
562 | /*
* Copyright (c) 2011-2024, baomidou ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baomidou.mybatisplus.generator.config.querys;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Sybase库表信息查询
*
* @author lroyia
* @since 2022/1/19 17:08
**/
public class SybaseQuery extends AbstractDbQuery {
@Override
public String tablesSql() {
return "select name TABLE_NAME, '' TABLE_COMMENT from sysobjects ";
}
@Override
public String tableFieldsSql() {
return "select o.name TABLE_NAME, c.name FIELD_NAME, upper(t.name) as FIELD_TYPE, " +
"(CONVERT(varchar(10),c.id)+ '_' + CONVERT(varchar(10), c.colid)) FIELD_KEY, " +
"c.length as COL_LENGTH, c.status FIELD_STATUS, '' FIELD_COMMENT, c.colid SORT_INDEX " +
"FROM syscolumns c left join systypes t " +
"on c.usertype=t.usertype " +
"inner join sysobjects o " +
"on c.id=o.id and o.type='U' " +
"WHERE o.name = '%s' " +
"ORDER BY c.colid";
}
@Override
public String tableName() {
return "TABLE_NAME";
}
@Override
public String tableComment() {
return "TABLE_COMMENT";
}
@Override
public String fieldName() {
return "FIELD_NAME";
}
@Override
public String fieldType() {
return "FIELD_TYPE";
}
@Override
public String fieldComment() {
return "FIELD_COMMENT";
}
@Override
public String fieldKey() {
return "FIELD_KEY";
}
@Override
public boolean isKeyIdentity(ResultSet results) throws SQLException {
// TODO:目前没有找到准确的判断方式,如果有大佬知道,请补充
return results.getInt("SORT_INDEX") == 1 && results.getInt("FIELD_STATUS") == 0;
}
}
| baomidou/mybatis-plus | mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/SybaseQuery.java |
563 | package com.chinaztt.fda.html5;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
/**
* 当前类注释:
* 项目名:FastDev4Android
* 包名:com.chinaztt.fda.html5
* 作者:江清清 on 15/11/06 08:59
* 邮箱:[email protected]
* QQ: 781931404
* 公司:江苏中天科技软件技术有限公司
*/
import com.chinaztt.fda.ui.base.BaseActivity;
public class HTML5WebViewCustomAD extends BaseActivity {
private HTML5CustomWebView mWebView;
//http://www.zttmall.com/Wapshop/Topic.aspx?TopicId=18
private String ad_url = "http://www.zttmall.com/Wapshop/Topic.aspx?TopicId=18";
private String title="百度一下你就知道";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = new HTML5CustomWebView(this, HTML5WebViewCustomAD.this,title,ad_url);
mWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
//准备javascript注入
mWebView.addJavascriptInterface(
new Js2JavaInterface(),"Js2JavaInterface");
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
if (ad_url != null) {
mWebView.loadUrl(ad_url);
}
}
setContentView(mWebView.getLayout());
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mWebView != null) {
mWebView.saveState(outState);
}
}
@Override
protected void onResume() {
super.onResume();
if (mWebView != null) {
mWebView.onResume();
}
}
@Override
public void onStop() {
super.onStop();
if (mWebView != null) {
mWebView.stopLoading();
}
}
@Override
protected void onPause() {
super.onPause();
if (mWebView != null) {
mWebView.onPause();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mWebView != null) {
mWebView.doDestroy();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
if (mWebView != null) {
if(mWebView.canGoBack()){
mWebView.goBack();
}else{
mWebView.releaseCustomview();
}
}
super.onBackPressed();
}
/**
* JavaScript注入回调
*/
public class Js2JavaInterface {
private Context context;
private String TAG = "Js2JavaInterface";
@JavascriptInterface
public void showProduct(String productId){
if(productId!=null){
//进行跳转商品详情
showToastMsgShort("点击的商品的ID为:" + productId);
}else {
showToastMsgShort("商品ID为空!");
}
}
}
} | jiangqqlmj/FastDev4Android | app/src/main/java/com/chinaztt/fda/html5/HTML5WebViewCustomAD.java |
564 | package com.zx.sms.session.smgp;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zx.sms.codec.smgp.msg.SMGPActiveTestMessage;
import com.zx.sms.codec.smgp.msg.SMGPBaseMessage;
import com.zx.sms.codec.smgp.msg.SMGPDeliverRespMessage;
import com.zx.sms.codec.smgp.msg.SMGPSubmitRespMessage;
import com.zx.sms.common.storedMap.VersionObject;
import com.zx.sms.connect.manager.EndpointEntity;
import com.zx.sms.session.AbstractSessionStateManager;
public class SMGPSessionStateManager extends AbstractSessionStateManager<Integer, SMGPBaseMessage> {
private static final Logger logger = LoggerFactory.getLogger(SMGPSessionStateManager.class);
public SMGPSessionStateManager(EndpointEntity entity, ConcurrentMap<String, VersionObject<SMGPBaseMessage>> storeMap, boolean preSend) {
super(entity, storeMap, preSend);
}
@Override
protected Integer getSequenceId(SMGPBaseMessage msg) {
return msg.getSequenceNo();
}
@Override
protected boolean needSendAgainByResponse(SMGPBaseMessage req, SMGPBaseMessage res) {
int result = 0;
if(res instanceof SMGPSubmitRespMessage){
SMGPSubmitRespMessage submitresp = (SMGPSubmitRespMessage)res;
result = submitresp.getStatus();
}else if(res instanceof SMGPDeliverRespMessage) {
SMGPDeliverRespMessage deliRes = (SMGPDeliverRespMessage)res;
result = deliRes.getStatus();
}
//TODO 电信的超速错误码现在不知道
if (result != 0 ) {
logger.error("Entity {} Receive Err Response result: {} . Req: {} ,Resp:{}",getEntity().getId(),result, req, res);
}
return false;
}
protected boolean closeWhenRetryFailed(SMGPBaseMessage req) {
if(req instanceof SMGPActiveTestMessage) {
return true;
}
return getEntity().isCloseWhenRetryFailed();
};
}
| Lihuanghe/SMSGate | src/main/java/com/zx/sms/session/smgp/SMGPSessionStateManager.java |
565 | package com.kunfei.bookshelf.help;
import android.text.TextUtils;
import android.util.Log;
import com.kunfei.bookshelf.bean.ReplaceRuleBean;
import com.kunfei.bookshelf.model.ReplaceRuleManager;
import com.luhuiguo.chinese.ChineseUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChapterContentHelp {
private static ChapterContentHelp instance;
public static synchronized ChapterContentHelp getInstance() {
if (instance == null)
instance = new ChapterContentHelp();
return instance;
}
/**
* 转繁体
*/
private String toTraditional(String content) {
int convertCTS = ReadBookControl.getInstance().getTextConvert();
switch (convertCTS) {
case 0:
break;
case 1:
content = ChineseUtils.toSimplified(content);
break;
case 2:
content = ChineseUtils.toTraditional(content);
break;
}
return content;
}
/**
* 替换净化
*/
public String replaceContent(String bookName, String bookTag, String content, Boolean replaceEnable) {
if (!replaceEnable) return toTraditional(content);
if (ReplaceRuleManager.getEnabled().size() == 0) return toTraditional(content);
//替换
for (ReplaceRuleBean replaceRule : ReplaceRuleManager.getEnabled()) {
if (isUseTo(replaceRule.getUseTo(), bookTag, bookName)) {
{
try {
// 因为这里获取不到context,就不使用getString(R.string.replace_ad)了
if (replaceRule.getReplaceSummary().matches("^广告话术(-.*|$)")) {
// 跳过太短的文本
if (content.length() > 100)
content = replaceAd2(content, replaceRule.getRegex());
} else
content = content.replaceAll(replaceRule.getFixedRegex(), replaceRule.getReplacement());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return toTraditional(content);
}
// 緩存生成的廣告規則正則表達式
// private Map<String, Pattern> adMap = new HashMap<>();
private Map<String, String> adMap = new HashMap<>();
// 缓存长表达式,使用普通方式替换
private Map<String, String> adMapL = new HashMap<>();
// 使用广告话术规则对正文进行替换,此方法为正则算法,效率较高,但是有漏失,故暂时放弃使用
private String replaceAd(String content, String replaceRule) {
// replaceRule只对选择的内容进行了切片,不包含正则
if (replaceRule == null)
return content;
replaceRule = replaceRule.substring(2, replaceRule.length() - 2).trim();
// Pattern rule = adMap.get(replaceRule);
String rule = adMap.get(replaceRule);
StringBuffer buffer = new StringBuffer(replaceRule.length() * 2);
if (rule == null) {
String rules[] = replaceRule.split("\n");
for (String s : rules) {
s = s.trim();
if (s.length() < 1)
continue;
// 如果规则只包含特殊字符,且长度大于2,直接替换。如果长度不大于2,会在自动扩大范围的过程中包含字符
if (s.matches("\\p{P}*")) {
if (s.length() > 2) {
if (buffer.length() > 0)
buffer.append('|');
buffer.append(Pattern.quote(s));
}
} else {
// 如果规则不止包含特殊字符,需要移除首尾的特殊字符,把中间的空字符转换为\s+,把其他特殊字符转换为转义符
if (buffer.length() > 0)
buffer.append('|');
buffer.append(s
.replaceFirst("^\\p{P}+", "")
.replaceFirst("\\p{P}$", "")
.replaceAll("\\s+", "xxsp")
.replaceAll("(\\p{P})", "(\\\\p{P}?)")
.replaceAll("xxsp", "\\s+")
);
}
}
// 广告话术至少出现两次
// rule = Pattern.compile("((" + buffer + ")(\\p{P}{0,2})){1,10}(" + buffer + ")");
rule = ("((" + buffer.toString() + ")(\\p{P}{0,2})){1,20}(" + buffer.toString() + ")((\\p{P}{0,12})(?=\\p{P}{2}))?");
adMap.put(replaceRule, rule);
}
content = content.replaceAll(rule, "");
rule = adMapL.get(replaceRule);
if (rule == null) {
String rules[] = replaceRule.split("\n");
buffer = new StringBuffer(replaceRule.length() * 2);
for (String s : rules) {
s = s.trim();
if (s.length() < 1)
continue;
if (s.length() > 6) {
if (buffer.length() > 0)
buffer.append('|');
buffer.append(Pattern.quote(s));
}
}
rule = "(" + buffer.toString() + ")";
adMapL.put(replaceRule, rule);
}
// Pattern p=Pattern.compile(rule);
content = content.replaceAll(rule, "");
return content;
}
// 緩存生成的廣告 原文規則+正则扩展
// 原文与正则的最大区别,在于正则匹配规则对特殊符号的处理是保守的
private Map<String, Pattern> AdPatternMap = new HashMap<>();
// 不包含符号的文本形式的规则缓存。用于广告规则的第二次替换,以解决如下问题: 规则有 abc def,而实际出现了adefbc
private Map<String, String> AdStringDict = new HashMap<>();
// 使用广告话术规则对正文进行替换,此方法 使用Matcher匹配,合并相邻区域,再StringBlock.getResult()的算法取回没有被替换的部分
// 广告话术规则的相关代码可能存在以下问题: 零宽断言书写错误, \p{P}的使用(比如我最开始不知道\p{P}是不包含\\s的), getResult.remove()的算法(为了方便调试专门写了verify方法)
private String replaceAd2(String content, String replaceRule) {
if (replaceRule == null)
return content;
StringBlock block = new StringBlock(content);
Pattern rule = AdPatternMap.get(replaceRule);
String stringDict = AdStringDict.get(replaceRule);
if (rule == null) {
StringBuffer bufferRegex = new StringBuffer(replaceRule.length() * 3);
StringBuffer bufferDict = new StringBuffer();
String rules[] = replaceRule.split("\n");
for (String s : rules) {
s = s.trim();
if (s.length() < 1)
continue;
s = Pattern.quote(s);
if (bufferRegex.length() > 0)
bufferRegex.append('|');
else
bufferRegex.append("(?=(");
bufferRegex.append(s);
}
for (String s : rules) {
s = s.trim();
if (s.length() < 1)
continue;
// 如果规则不止包含特殊字符,需要移除首尾的特殊字符,把中间的空字符转换为\s+,把其他特殊字符转换为转义符
if (!s.matches("[\\p{P}\\s]*")) {
if (bufferRegex.length() > 0)
bufferRegex.append('|');
else
bufferRegex.append("(?=(");
bufferRegex.append(s
.replaceFirst("^\\p{P}+", "")
.replaceFirst("\\p{P}$", "")
.replaceAll("\\s+", "xxsp")
.replaceAll("(\\p{P})", "(\\\\p{P}?)")
.replaceAll("xxsp", "\\s+")
);
}
if (s.matches("[\\p{P}\\s]*[^\\p{P}]{4,}[\\p{P}\\s]*")) {
bufferDict.append('\n');
bufferDict.append(s);
}
}
bufferRegex.append("))((\\p{P}{0,12})(?=\\p{P}{2}))?");
rule = Pattern.compile(bufferRegex.toString());
AdPatternMap.put(replaceRule, rule);
stringDict = bufferDict.toString();
AdStringDict.put(replaceRule, bufferDict.toString());
}
Matcher matcher0 = rule.matcher(content);
if (matcher0.groupCount() < 2) {
// 构造的正则表达式分2个部分,第一部分匹配文字,第二部分匹配符号。完成匹配后实际已经不需要拆墙了
Log.w("replaceAd2", "2 > matcher0.group()==" + matcher0.groupCount());
return content;
}
while (matcher0.find()) {
if (matcher0.group(2) != null)
block.remove(matcher0.start(), matcher0.start() + matcher0.group(1).length() + matcher0.group(2).length());
else
block.remove(matcher0.start(), matcher0.start() + matcher0.group(1).length());
Log.d("replaceAd2()", "Remove=" + block.verify());
}
block.remove("(\\p{P}|\\s){1,6}([^\\p{P}]?(\\p{P}|\\s){1,6})?");
block.removeDict(stringDict);
block.increase(5);
return block.getResult();
}
class StringBlock {
// 保存字符串本体
private String string = "";
// 保存可以复制的区域,奇数为start,偶数为end。
private ArrayList<Integer> list;
// 保存删除的区域,用于校验
private ArrayList<Integer> removed;
public StringBlock(String string) {
this.string = string;
list = new ArrayList<>();
list.add(0);
list.add(string.length());
removed = new ArrayList<>();
}
// 验证删除操作是否有bug 验证OK输出正数,异常输出负数
public int verify() {
// 验证list数列是否有异常
if (list.size() % 2 != 0)
return -1;
int p = list.get(0);
if (p < 0)
return -2;
for (int i = 1; i < list.size(); i++) {
int q = list.get(i);
if (q <= p)
return -3;
p = q;
}
// 验证删除的区域是否还在list构成的区域内
for (int j = 0; j < removed.size() / 2; j++) {
int j2 = removed.get(j * 2);
int j2_1 = removed.get(j * 2 + 1);
for (int i = 0; i < list.size() / 2; i++) {
int i2_1 = list.get(i * 2 + 1);
int i2 = list.get(i * 2);
if (i2 > j2) {
break;
}
if (i2_1 < j2) {
continue;
}
if (i2_1 == j2) {
if (i * 2 + 2 < list.size()) {
if (list.get(i * 2 + 2) < j2_1)
return -4;
}
} else {
return -5;
}
}
}
return 0;
}
// 增加字符串的文本,避免被误删除
public void increase(int size) {
ArrayList<Integer> cache = new ArrayList<>();
if (list.get(0) > size)
cache.add(list.get(0));
else
cache.add(0);
for (int i = 1; i < list.size() - 1; i = i + 2) {
if (list.get(i + 1) - list.get(i) > size) {
cache.add(list.get(i));
cache.add(list.get(i + 1));
}
}
if (string.length() - list.get(list.size() - 1) > size)
cache.add(list.get(list.size() - 1));
else
cache.add(string.length());
list = cache;
}
// 去除长度小于等于墙厚的区域
public void remove(int wallThick) {
int j = list.size() / 2;
ArrayList<Integer> cache = new ArrayList<>();
for (int i = 0; i < j; i++) {
int i2_1 = list.get(i * 2 + 1);
int i2 = list.get(i * 2);
if ((i2_1 - i2) > wallThick) {
cache.add(i2);
cache.add(i2_1);
}
}
list = cache;
}
// 去除完全与正则匹配的区域
public void remove(String wall) {
int j = list.size() / 2;
ArrayList<Integer> cache = new ArrayList<>();
for (int i = 0; i < j; i++) {
int i2_1 = list.get(i * 2 + 1);
int i2 = list.get(i * 2);
if (!string.substring(i2, i2_1).matches(wall)) {
cache.add(i2);
cache.add(i2_1);
}
}
list = cache;
}
public void removeDict(String dict) {
// 如果孔穴的两端刚好匹配到同一词条,说明这是嵌套的广告话术
int j = list.size() / 2;
// 缓存需要操作的参数
ArrayList<Integer> cache = new ArrayList<>();
for (int i = 1; i < j; i++) {
String str_s0 = getSubString(2 * i - 2).replaceFirst("[\\p{P}\\s]+$", "");
String str_s1 = str_s0.replaceFirst("^.*[\\p{P}\\s][^$]", "");
if (str_s1.length() < 1)
continue;
String str_e0 = getSubString(2 * i).replaceFirst("^[\\p{P}\\s]+", "");
String str_e1 = str_e0.replaceFirst("[\\p{P}\\s].*$", "");
if (str_e1.length() < 1)
continue;
// m 第一部分开始的位置
int m = list.get(i * 2 - 2) + str_s0.length() - str_s1.length();
// 第二部分结尾
int n = list.get(i * 2 + 1) - str_e0.length() + str_e1.length();
if (dict.matches("[\\s\\S]*(" + str_s1 + ")([^\\p{P}]*)(" + str_e1 + ")[\\s\\S]*")) {
cache.add(m);
cache.add(n);
} else if (dict.matches("[\\s\\S]*(\n|^).*" + str_s1 + ".*(\n|\\s*$)[\\s\\S]*")) {
cache.add(m);
cache.add(list.get(i * 2));
} else if (dict.matches("[\\s\\S]*(\n|^).*" + str_e1 + ".*(\n|\\s*$)[\\s\\S]*")) {
// 因为java.*不匹配\n
cache.add(list.get(i * 2));
cache.add(n);
}
}
for (int i = 0; i < cache.size() / 2; i++) {
Log.d("removeDict", string.substring(cache.get(i * 2), cache.get((i * 2 + 1))));
remove(cache.get(i * 2), cache.get((i * 2 + 1)));
}
}
public boolean remove(int start, int end) {
if (start < 0 || end < 0 || start > string.length() || end > string.length() || start >= end)
return false;
removed.add(start);
removed.add(end);
int j = list.size() / 2;
for (int i = 0; i < j; i++) {
// start在有效区间中间和在区间的两个边缘,是不同的算法。
int i2_1 = list.get(i * 2 + 1);
int i2 = list.get(i * 2);
if (start < i2)
return true;
if (start == i2) {
if (i2_1 > end) {
list.set(i * 2, end);
return true;
} else {
for (int k = 0; 2 * i + k < list.size(); k++) {
if (list.get(k + 2 * i) > end) {
if (k % 2 == 1) {
list.set(2 * i + k - 1, end);
} else {
list.remove(i * 2);
}
for (int m = 0; m < k - 1; m++)
list.remove(i * 2);
return true;
}
}
}
} else if (i2 < start && i2_1 > start) {
if (i2_1 > end) {
list.add(i * 2 + 1, end);
list.add(i * 2 + 1, start);
return true;
} else {
list.set(i * 2 + 1, start);
// i*2+2开始的元素可能需要被删除
for (int k = 2; 2 * i + k < list.size(); k++) {
if (list.get(k + 2 * i) < end)
continue;
if (k % 2 == 1) {
if (list.get(k + 2 * i) > end) {
list.set(2 * i + k - 1, end);
}
} else {
list.remove(i * 2 + 2);
}
for (int m = 0; m < k - 1; m++)
list.remove(i * 2 + 2);
return true;
}
}
}
}
return false;
}
public String getResult() {
StringBuffer buffer = new StringBuffer(string.length());
int j = list.size() / 2;
if (j * 2 > list.size())
Log.e("StringBlock", "list.size=" + list.size());
for (int i = 0; i < j; i++) {
buffer.append(string, list.get(i * 2), list.get(i * 2 + 1));
}
return buffer.toString();
}
public String getSubString(int start) {
if (start >= 0 && start < list.size() - 1)
return string.substring(list.get(start), list.get(start + 1));
return null;
}
}
/**
* 段落重排算法入口。把整篇内容输入,连接错误的分段,再把每个段落调用其他方法重新切分
*
* @param content 正文
* @param chapterName 标题
* @return
*/
public static String LightNovelParagraph2(String content, String chapterName) {
if (ReadBookControl.getInstance().getLightNovelParagraph()) {
String _content;
int chapterNameLength = chapterName.trim().length();
if (chapterNameLength > 1) {
String regexp = chapterName.trim().replaceAll("\\s+", "(\\\\s*)");
// 质量较低的页面,章节内可能重复出现章节标题
if (chapterNameLength > 5)
_content = content.replaceAll(regexp, "").trim();
else
_content = content.replaceFirst("^\\s*" + regexp, "").trim();
} else {
_content = content;
}
List<String> dict = makeDict(_content);
String[] p = _content
.replaceAll(""", "“")
.replaceAll("[::]['\"‘”“]+", ":“")
.replaceAll("[\"”“]+[\\s]*[\"”“][\\s\"”“]*", "”\n“")
.split("\n(\\s*)");
// 初始化StringBuffer的长度,在原content的长度基础上做冗余
StringBuffer buffer = new StringBuffer((int) (content.length() * 1.15));
// 章节的文本格式为章节标题-空行-首段,所以处理段落时需要略过第一行文本。
buffer.append(" ");
if (!chapterName.trim().equals(p[0].trim())) {
// 去除段落内空格。unicode 3000 象形字间隔(中日韩符号和标点),不包含在\s内
buffer.append(p[0].replaceAll("[\u3000\\s]+", ""));
}
// 如果原文存在分段错误,需要把段落重新黏合
for (int i = 1; i < p.length; i++) {
if (match(MARK_SENTENCES_END, buffer.charAt(buffer.length() - 1)))
buffer.append("\n");
// 段落开头以外的地方不应该有空格
// 去除段落内空格。unicode 3000 象形字间隔(中日韩符号和标点),不包含在\s内
buffer.append(p[i].replaceAll("[\u3000\\s]", ""));
}
// 预分段预处理
// ”“处理为”\n“。
// ”。“处理为”。\n“。不考虑“?” “!”的情况。
// ”。xxx处理为 ”。\n xxx
p = buffer.toString()
.replaceAll("[\"”“]+[\\s]*[\"”“]+", "”\n“")
.replaceAll("[\"”“]+(?。!?!~)[\"”“]+", "”$1\n“")
.replaceAll("[\"”“]+(?。!?!~)([^\"”“])", "”$1\n$2")
.replaceAll("([问说喊唱叫骂道着答])[\\.。]", "$1。\n")
// .replaceAll("([\\.。\\!!??])([^\"”“]+)[::][\"”“]", "$1\n$2:“")
.split("\n");
buffer = new StringBuffer((int) (content.length() * 1.15));
for (String s : p) {
buffer.append("\n");
buffer.append(FindNewLines(s, dict)
);
}
buffer = reduceLength(buffer);
content = chapterName + "\n\n"
+ buffer.toString()
//处理章节头部空格和换行
.replaceFirst("^\\s+", "")
// 此规则会造成不规范引号被误换行,暂时无法解决,我认为利大于弊
// 例句:“你”“我”“他”都是一样的
// 误处理为 “你”\n“我”\n“他”都是一样的
// 而规范使用的标点不会被误处理: “你”、“我”、“他”,都是一样的。
.replaceAll("\\s*[\"”“]+[\\s]*[\"”“][\\s\"”“]*", "”\n“")
// 规范 A:“B...
.replaceAll("[::][”“\"\\s]+", ":“")
// 处理奇怪的多余引号 \n”A:“B... 为 \nA:“B...
.replaceAll("\n[\"“”]([^\n\"“”]+)([,:,:][\"”“])([^\n\"“”]+)", "\n$1:“$3")
.replaceAll("\n(\\s*)", "\n")
// 处理“……”
// .replaceAll("\n[\"”“][.,。,…]+\\s*[.,。,…]+[\"”“]","\n“……”")
// 处理被错误断行的省略号。存在较高的误判,但是我认为利大于弊
.replaceAll("[.,。,…]+\\s*[.,。,…]+", "……")
.replaceAll("\n([\\s::,,]+)", "\n")
;
}
return content;
}
/**
* 从字符串提取引号包围,且不止出现一次的内容为字典
*
* @param str
* @return 词条列表
*/
private static List<String> makeDict(String str) {
// 引号中间不包含任何标点,但是没有排除空格
Pattern patten = Pattern.compile("(?<=[\"'”“])([^\n\\p{P}]{1," + WORD_MAX_LENGTH + "})(?=[\"'”“])");
Matcher matcher = patten.matcher(str);
List<String> cache = new ArrayList<>();
List<String> dict = new ArrayList<>();
List<String> groups = new ArrayList<>();
while (matcher.find()) {
String word = matcher.group();
String w = word.replaceAll("\\s+", "");
if (!groups.contains(word))
groups.add(word);
if (!groups.contains(w))
groups.add(w);
}
for (String word : groups) {
String w = word.replaceAll("\\s+", "");
if (cache.contains(w)) {
if (!dict.contains(w)) {
dict.add(w);
if (!dict.contains(word))
dict.add(word);
}
} else {
cache.add(w);
cache.add(word);
}
}
/*
System.out.print("makeDict:");
for (String s : dict)
System.out.print("\t" + s);
System.out.print("\n");
*/
return dict;
}
/**
* 强制切分,减少段落内的句子
* 如果连续2对引号的段落没有提示语,进入对话模式。最后一对引号后强制切分段落
* 如果引号内的内容长于5句,可能引号状态有误,随机分段
* 如果引号外的内容长于3句,随机分段
*
* @param str
* @return
*/
private static StringBuffer reduceLength(StringBuffer str) {
String[] p = str.toString().split("\n");
int l = p.length;
boolean[] b = new boolean[l];
for (int i = 0; i < l; i++) {
if (p[i].matches(PARAGRAPH_DIAGLOG))
b[i] = true;
else
b[i] = false;
}
int dialogue = 0;
for (int i = 0; i < l; i++) {
if (b[i]) {
if (dialogue < 0)
dialogue = 1;
else if (dialogue < 2)
dialogue++;
} else {
if (dialogue > 1) {
p[i] = splitQuote(p[i]);
dialogue--;
} else if (dialogue > 0 && i < l - 2) {
if (b[i + 1])
p[i] = splitQuote(p[i]);
}
}
}
StringBuffer string = new StringBuffer();
for (int i = 0; i < l; i++) {
string.append('\n');
string.append(p[i]);
// System.out.print(" "+b[i]);
}
// System.out.println(" " + str);
return string;
}
// 强制切分进入对话模式后,未构成 “xxx” 形式的段落
private static String splitQuote(String str) {
// System.out.println("splitQuote() " + str);
int length = str.length();
if (length < 3)
return str;
if (match(MARK_QUOTATION, str.charAt(0))) {
int i = seekIndex(str, MARK_QUOTATION, 1, length - 2, true) + 1;
if (i > 1)
if (!match(MARK_QUOTATION_BEFORE, str.charAt(i - 1)))
return str.substring(0, i) + "\n" + str.substring(i);
} else if (match(MARK_QUOTATION, str.charAt(length - 1))) {
int i = length - 1 - seekIndex(str, MARK_QUOTATION, 1, length - 2, false);
if (i > 1)
if (!match(MARK_QUOTATION_BEFORE, str.charAt(i - 1)))
return str.substring(0, i) + "\n" + str.substring(i);
}
return str;
}
/**
* 计算随机插入换行符的位置。
*
* @param str 字符串
* @param offset 传回的结果需要叠加的偏移量
* @param min 最低几个句子,随机插入换行
* @param gain 倍率。每个句子插入换行的数学期望 = 1 / gain , gain越大越不容易插入换行
* @return
*/
private static ArrayList<Integer> forceSplit(String str, int offset, int min, int gain, int tigger) {
ArrayList<Integer> result = new ArrayList<>();
ArrayList<Integer> array_end = seekIndexs(str, MARK_SENTENCES_END_P, 0, str.length() - 2, true);
ArrayList<Integer> array_mid = seekIndexs(str, MARK_SENTENCES_MID, 0, str.length() - 2, true);
if (array_end.size() < tigger && array_mid.size() < tigger * 3)
return result;
int j = 0;
for (int i = min; i < array_end.size(); i++) {
int k = 0;
for (; j < array_mid.size(); j++) {
if (array_mid.get(j) < array_end.get(i))
k++;
}
if (Math.random() * gain < (0.8 + k / 2.5)) {
result.add(array_end.get(i) + offset);
i = Math.max(i + min, i);
}
}
return result;
}
// 对内容重新划分段落.输入参数str已经使用换行符预分割
private static String FindNewLines(String str, List<String> dict) {
StringBuffer string = new StringBuffer(str);
// 标记string中每个引号的位置.特别的,用引号进行列举时视为只有一对引号。 如:“锅”、“碗”视为“锅、碗”,从而避免误断句。
List<Integer> array_quote = new ArrayList<>();
// 标记忽略的引号
List<Integer> array_ignore_quote = new ArrayList<>();
// 标记插入换行符的位置,int为插入位置(str的char下标)
ArrayList<Integer> ins_n = new ArrayList<>();
// 标记不需要插入换行符的位置。功能暂未实现。
ArrayList<Integer> remove_n = new ArrayList<>();
// mod[i]标记str的每一段处于引号内还是引号外。范围: str.substring( array_quote.get(i), array_quote.get(i+1) )的状态。
// 长度:array_quote.size(),但是初始化时未预估占用的长度,用空间换时间
// 0未知,正数引号内,负数引号外。
// 如果相邻的两个标记都为+1,那么需要增加1个引号。
// 引号内不进行断句
int[] mod = new int[str.length()];
boolean wait_close = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (match(MARK_QUOTATION, c)) {
int size = array_quote.size();
// 把“xxx”、“yy”和“z”合并为“xxx_yy_z”进行处理
if (size > 0) {
int quote_pre = array_quote.get(size - 1);
if (i - quote_pre == 2) {
boolean remove = false;
if (wait_close) {
if (match(",,、/", str.charAt(i - 1))) {
// 考虑出现“和”这种特殊情况
remove = true;
}
} else if (match(",,、/和与或", str.charAt(i - 1))) {
remove = true;
}
if (remove) {
string.setCharAt(i, '“');
string.setCharAt(i - 2, '”');
array_quote.remove(size - 1);
mod[size - 1] = 1;
mod[size] = -1;
continue;
}
}
}
array_quote.add(i);
// 为xxx:“xxx”做标记
if (i > 1) {
// 当前发言的正引号的前一个字符
char char_b1 = str.charAt(i - 1);
// 上次发言的正引号的前一个字符
char char_b2 = 0;
if (match(MARK_QUOTATION_BEFORE, char_b1)) {
// 如果不是第一处引号,寻找上一处断句,进行分段
if (array_quote.size() > 1) {
int last_quote = array_quote.get(array_quote.size() - 2);
int p = 0;
if (char_b1 == ',' || char_b1 == ',') {
if (array_quote.size() > 2) {
p = array_quote.get(array_quote.size() - 3);
if (p > 0) {
char_b2 = str.charAt(p - 1);
}
}
}
// if(char_b2=='.' || char_b2=='。')
if (match(MARK_SENTENCES_END_P, char_b2))
ins_n.add(p - 1);
else if (match("的", char_b2)) {
//剔除引号标记aaa的"xxs",bbb的“yyy”
} else {
int last_end = seekLast(str, MARK_SENTENCES_END, i, last_quote);
if (last_end > 0)
ins_n.add(last_end);
else
ins_n.add(last_quote);
}
}
wait_close = true;
mod[size] = 1;
if (size > 0) {
mod[size - 1] = -1;
if (size > 1) {
mod[size - 2] = 1;
}
/*
int quote_pre = array_quote.get(array_quote.size() - 2);
boolean flag_ins_n = false;
for (int j = i; j > quote_pre; j--) {
if (match(MARK_SENTENCES_END, string.charAt(j))) {
ins_n.add(j);
flag_ins_n = true;
}
}
if (!flag_ins_n)
ins_n.add(quote_pre);
*/
}
} else if (wait_close) {
{
wait_close = false;
ins_n.add(i);
}
}
}
}
}
int size = array_quote.size();
// 标记循环状态,此位置前的引号是否已经配对
boolean opend = false;
if (size > 0) {
// 第1次遍历array_quote,令其元素的值不为0
for (int i = 0; i < size; i++) {
if (mod[i] > 0) {
opend = true;
} else if (mod[i] < 0) {
// 连续2个反引号表明存在冲突,强制把前一个设为正引号
if (!opend) {
if (i > 0)
mod[i] = 3;
}
opend = false;
} else {
opend = !opend;
if (opend)
mod[i] = 2;
else
mod[i] = -2;
}
}
// 修正,断尾必须封闭引号
if (opend) {
if (array_quote.get(size - 1) - string.length() > -3) {
// if((match(MARK_QUOTATION,string.charAt(string.length()-1)) || match(MARK_QUOTATION,string.charAt(string.length()-2)))){
if (size > 1)
mod[size - 2] = 4;
// 0<=i<size,故无需判断size>=1
mod[size - 1] = -4;
} else if (!match(MARK_SENTENCES_SAY, string.charAt(string.length() - 2)))
string.append("”");
}
// 第2次循环,mod[i]由负变正时,前1字符如果是句末,需要插入换行
int loop2_mod_1 = -1; //上一个引号跟随内容的状态
int loop2_mod_2; //当前引号跟随内容的状态
int i = 0;
int j = array_quote.get(0) - 1; //当前引号前一字符的序号
if (j < 0) {
i = 1;
loop2_mod_1 = 0;
}
for (; i < size; i++) {
j = array_quote.get(i) - 1;
loop2_mod_2 = mod[i];
if (loop2_mod_1 < 0 && loop2_mod_2 > 0) {
if (match(MARK_SENTENCES_END, string.charAt(j)))
ins_n.add(j);
}
/* else if (mod[i - 1] > 0 && mod[i] < 0) {
if (j > 0) {
if (match(MARK_SENTENCES_END, string.charAt(j)))
ins_n.add(j);
}
}
*/
loop2_mod_1 = loop2_mod_2;
}
}
// 第3次循环,匹配并插入换行。
// "xxxx" xxxx。\n xxx“xxxx”
// 未实现
// 使用字典验证ins_n , 避免插入不必要的换行。
// 由于目前没有插入、的列表,无法解决 “xx”、“xx”“xx” 被插入换行的问题
ArrayList<Integer> _ins_n = new ArrayList<>();
for (int i : ins_n) {
if (match("\"'”“", string.charAt(i))) {
int start = seekLast(str, "\"'”“", i - 1, i - WORD_MAX_LENGTH);
if (start > 0) {
String word = str.substring(start + 1, i);
if (dict.contains(word)) {
// System.out.println("使用字典验证 跳过\tins_n=" + i + " word=" + word);
// 引号内如果是字典词条,后方不插入换行符(前方不需要优化)
remove_n.add(i);
continue;
} else {
System.out.println("使用字典验证 插入\tins_n=" + i + " word=" + word);
if (match("的地得和或", str.charAt(start))) {
// xx的“xx”,后方不插入换行符(前方不需要优化)
continue;
}
}
}
} else {
// System.out.println("使用字典验证 else\tins_n=" + i + " substring=" + string.substring(i-5,i+5));
}
_ins_n.add(i);
}
ins_n = _ins_n;
// 随机在句末插入换行符
ins_n = new ArrayList<Integer>(new HashSet<Integer>(ins_n));
Collections.sort(ins_n);
{
String subs = "";
int j = 0;
int progress = 0;
int next_line = -1;
if (ins_n.size() > 0)
next_line = ins_n.get(j);
int gain = 3;
int min = 0;
int trigger = 2;
for (int i = 0; i < array_quote.size(); i++) {
int qutoe = array_quote.get(i);
if (qutoe > 0) {
gain = 4;
min = 2;
trigger = 4;
} else {
gain = 3;
min = 0;
trigger = 2;
}
// 把引号前的换行符与内容相间插入
for (; j < ins_n.size(); j++) {
// 如果下一个换行符在当前引号前,那么需要此次处理.如果紧挨当前引号,需要考虑插入引号的情况
if (next_line >= qutoe)
break;
next_line = ins_n.get(j);
if (progress < next_line) {
subs = string.substring(progress, next_line);
ins_n.addAll(forceSplit(subs, progress, min, gain, trigger));
progress = next_line + 1;
}
}
if (progress < qutoe) {
subs = string.substring(progress, qutoe + 1);
ins_n.addAll(forceSplit(subs, progress, min, gain, trigger));
progress = qutoe + 1;
}
}
for (; j < ins_n.size(); j++) {
next_line = ins_n.get(j);
if (progress < next_line) {
subs = string.substring(progress, next_line);
ins_n.addAll(forceSplit(subs, progress, min, gain, trigger));
progress = next_line + 1;
}
}
if (progress < string.length()) {
subs = string.substring(progress, string.length());
ins_n.addAll(forceSplit(subs, progress, min, gain, trigger));
}
}
// 根据段落状态修正引号方向、计算需要插入引号的位置
// ins_quote跟随array_quote ins_quote[i]!=0,则array_quote.get(i)的引号前需要前插入'”'
boolean[] ins_quote = new boolean[size];
opend = false;
for (int i = 0; i < size; i++) {
int p = array_quote.get(i);
if (mod[i] > 0) {
string.setCharAt(p, '“');
if (opend)
ins_quote[i] = true;
opend = true;
} else if (mod[i] < 0) {
string.setCharAt(p, '”');
opend = false;
} else {
opend = !opend;
if (opend)
string.setCharAt(p, '“');
else
string.setCharAt(p, '”');
}
}
ins_n = new ArrayList<Integer>(new HashSet<Integer>(ins_n));
Collections.sort(ins_n);
// 输出log进行检验
/*
System.out.println("quote[i]:position/mod\t" + string);
for (int i = 0; i < array_quote.size(); i++) {
System.out.print(" [" + i + "]" + array_quote.get(i) + "/" + mod[i]);
}
System.out.print("\n");
System.out.print("ins_q:");
for (int i = 0; i < ins_quote.length; i++) {
System.out.print(" " + ins_quote[i]);
}
System.out.print("\n");
System.out.print("ins_n:");
for (int i : ins_n) {
System.out.print(" " + i);
}
System.out.print("\n");
*/
// 完成字符串拼接(从string复制、插入引号和换行
// ins_quote 在引号前插入一个引号。 ins_quote[i]!=0,则array_quote.get(i)的引号前需要前插入'”'
// ins_n 插入换行。数组的值表示插入换行符的位置
StringBuffer buffer = new StringBuffer((int) (str.length() * 1.15));
int j = 0;
int progress = 0;
int next_line = -1;
if (ins_n.size() > 0)
next_line = ins_n.get(j);
for (int i = 0; i < array_quote.size(); i++) {
int qutoe = array_quote.get(i);
// 把引号前的换行符与内容相间插入
for (; j < ins_n.size(); j++) {
// 如果下一个换行符在当前引号前,那么需要此次处理.如果紧挨当前引号,需要考虑插入引号的情况
if (next_line >= qutoe)
break;
next_line = ins_n.get(j);
buffer.append(string, progress, next_line + 1);
buffer.append('\n');
progress = next_line + 1;
}
if (progress < qutoe) {
buffer.append(string, progress, qutoe + 1);
progress = qutoe + 1;
}
if (ins_quote[i] && buffer.length() > 2) {
if (buffer.charAt(buffer.length() - 1) == '\n')
buffer.append('“');
else
buffer.insert(buffer.length() - 1, "”\n");
}
}
for (; j < ins_n.size(); j++) {
next_line = ins_n.get(j);
if (progress <= next_line) {
buffer.append(string, progress, next_line + 1);
buffer.append('\n');
progress = next_line + 1;
}
}
if (progress < string.length()) {
buffer.append(string, progress, string.length());
}
return buffer.toString();
}
/**
* 计算匹配到字典的每个字符的位置
*
* @param str 待匹配的字符串
* @param key 字典
* @param from 从字符串的第几个字符开始匹配
* @param to 匹配到第几个字符结束
* @param inOrder 是否按照从前向后的顺序匹配
* @return 返回距离构成的ArrayList<Integer>
*/
private static ArrayList<Integer> seekIndexs(String str, String key, int from, int to, boolean inOrder) {
ArrayList<Integer> list = new ArrayList<>();
if (str.length() - from < 1)
return list;
int i = 0;
if (from > i)
i = from;
int t = str.length();
if (to > 0)
t = Math.min(t, to);
char c;
for (; i < t; i++) {
if (inOrder)
c = str.charAt(i);
else
c = str.charAt(str.length() - i - 1);
if (key.indexOf(c) != -1) {
list.add(i);
}
}
return list;
}
/**
* 计算字符串最后出现与字典中字符匹配的位置
*
* @param str 数据字符串
* @param key 字典字符串
* @param from 从哪个字符开始匹配,默认最末位
* @param to 匹配到哪个字符(不包含此字符)默认0
* @return 位置(正向计算)
*/
private static int seekLast(String str, String key, int from, int to) {
if (str.length() - from < 1)
return -1;
int i = str.length() - 1;
if (from < i && i > 0)
i = from;
int t = 0;
if (to > 0)
t = to;
char c;
for (; i > t; i--) {
c = str.charAt(i);
if (key.indexOf(c) != -1) {
return i;
}
}
return -1;
}
/**
* 计算字符串与字典中字符的最短距离
*
* @param str 数据字符串
* @param key 字典字符串
* @param from 从哪个字符开始匹配,默认0
* @param to 匹配到哪个字符(不包含此字符)默认匹配到最末位
* @param inOrder 是否从正向开始匹配
* @return 返回最短距离, 注意不是str的char的下标
*/
private static int seekIndex(String str, String key, int from, int to, boolean inOrder) {
if (str.length() - from < 1)
return -1;
int i = 0;
if (from > i)
i = from;
int t = str.length();
if (to > 0)
t = Math.min(t, to);
char c;
for (; i < t; i++) {
if (inOrder)
c = str.charAt(i);
else
c = str.charAt(str.length() - i - 1);
if (key.indexOf(c) != -1) {
return i;
}
}
return -1;
}
/**
* 计算字符串与字典的距离。
*
* @param str 数据字符串
* @param form 从第几个字符开始匹配
* @param to 匹配到第几个字符串结束
* @param inOrder 是否从前向后匹配。
* @param words 可变长参数构成的字典。每个字符串代表一个字符
* @return 匹配结果。注意这个距离是使用第一个字符进行计算的
*/
private static int seekWordsIndex(String str, int form, int to, boolean inOrder, String... words) {
if (words.length < 1)
return -2;
int i = seekIndex(str, words[0], form, to, inOrder);
if (i < 0)
return i;
for (int j = 1; j < words.length; j++) {
int k = seekIndex(str, words[j], form, to, inOrder);
if (inOrder) {
if (i + j != k)
return -3;
} else {
if (i - j != k)
return -3;
}
}
return i;
}
/* 搜寻引号并进行分段。处理了一、二、五三类常见情况
参照百科词条[引号#应用示例](https://baike.baidu.com/item/%E5%BC%95%E5%8F%B7/998963?#5)对引号内容进行矫正并分句。
一、完整引用说话内容,在反引号内侧有断句标点。例如:
1) 丫姑折断几枝扔下来,边叫我的小名儿边说:“先喂饱你!”
2)“哎呀,真是美极了!”皇帝说,“我十分满意!”
3)“怕什么!海的美就在这里!”我说道。
二、部分引用,在反引号外侧有断句标点:
4)适当地改善自己的生活,岂但“你管得着吗”,而且是顺乎天理,合乎人情的。
5)现代画家徐悲鸿笔下的马,正如有的评论家所说的那样,“形神兼备,充满生机”。
6)唐朝的张嘉贞说它“制造奇特,人不知其所为”。
三、一段接着一段地直接引用时,中间段落只在段首用起引号,该段段尾却不用引回号。但是正统文学不在考虑范围内。
四、引号里面又要用引号时,外面一层用双引号,里面一层用单引号。暂时不需要考虑
五、反语和强调,周围没有断句符号。
*/
// 段落换行符
private static String SPACE_BEFORE_PARAGRAPH = "\n ";
// 段落末位的标点
private static String MARK_SENTENCES = "?。!?!~”\"";
// 句子结尾的标点。因为引号可能存在误判,不包含引号。
private static String MARK_SENTENCES_END = "?。!?!~";
private static String MARK_SENTENCES_END_P = ".?。!?!~";
// 句中标点,由于某些网站常把“,”写为".",故英文句点按照句中标点判断
private static String MARK_SENTENCES_MID = ".,、,—…";
private static String MARK_SENTENCES_F = "啊嘛吧吗噢哦了呢呐";
private static String MARK_SENTENCES_SAY = "问说喊唱叫骂道着答";
// XXX说:“”的冒号
private static String MARK_QUOTATION_BEFORE = ",:,:";
// 引号
private static String MARK_QUOTATION = "\"“”";
private static String PARAGRAPH_DIAGLOG = "^[\"”“][^\"”“]+[\"”“]$";
// 限制字典的长度
private static int WORD_MAX_LENGTH = 16;
private static boolean isFullSentences(String s) {
if (s.length() < 2)
return false;
char c = s.charAt(s.length() - 1);
return MARK_SENTENCES.indexOf(c) != -1;
}
private static boolean match(String rule, char chr) {
return rule.indexOf(chr) != -1;
}
private boolean isUseTo(String useTo, String bookTag, String bookName) {
return TextUtils.isEmpty(useTo)
|| useTo.contains(bookTag)
|| useTo.contains(bookName);
}
}
| gedoor/MyBookshelf | app/src/main/java/com/kunfei/bookshelf/help/ChapterContentHelp.java |
566 | package designpattern.command;
/**
* 知道如何实施与执行一个与请求相关的操作,任何类都可能作为一个接收者。真正执行请求的地方!
*
* @author liu yuning
*
*/
interface Reciever {
public void action();
}
class RecieverA implements Reciever {
@Override
public void action() {
System.out.println("RecieverA执行请求!");
}
}
class RecieverB implements Reciever {
@Override
public void action() {
System.out.println("RecieverB执行请求!");
}
}
class RecieverC implements Reciever {
@Override
public void action() {
System.out.println("RecieverC执行请求!");
}
}
| echoTheLiar/JavaCodeAcc | src/designpattern/command/Reciever.java |
567 | package com.qiniu.storage;
import com.qiniu.common.QiniuException;
import com.qiniu.util.StringUtils;
/**
* 私有云下载 URL 类
*/
public class DownloadPrivateCloudUrl extends DownloadUrl {
private final Configuration cfg;
private final String bucketName;
private final String accessKey;
/**
* 构造器
* 如果知道下载的 domain 信息可以使用此接口
* 如果不知道 domain 信息,可以使用 {@link DownloadPrivateCloudUrl#DownloadPrivateCloudUrl(Configuration, String, String, String)}
*
* @param domain 下载 domain, eg: qiniu.com 【必须】
* @param useHttps 是否使用 https 【必须】
* @param bucketName bucket 名称 【必须】
* @param key 下载资源在七牛云存储的 key 【必须】
* @param accessKey 七牛账户 accessKey 【必须】
*/
public DownloadPrivateCloudUrl(String domain, boolean useHttps, String bucketName, String key, String accessKey) {
super(domain, useHttps, key);
this.cfg = null;
this.bucketName = bucketName;
this.accessKey = accessKey;
}
/**
* 构造器
* 如果不知道 domain 信息,可使用此接口;内部有查询 domain 逻辑
* 查询 domain 流程:
* 1. 根据 {@link Configuration#defaultUcHost} 查找 bucketName 所在的{@link Configuration#region}
* 2. 获取 {@link Configuration#region} 中的 ioHost({@link Configuration#ioHost(String, String)} ) 作为 domain
* 注:需要配置正确的 {@link Configuration#defaultUcHost}
*
* @param cfg 查询 domain 时的Configuration 【必须】
* @param bucketName bucket 名称【必须】
* @param key 下载资源在七牛云存储的 key【必须】
* @param accessKey 七牛账户 accessKey【必须】
*/
public DownloadPrivateCloudUrl(Configuration cfg, String bucketName, String key, String accessKey) {
super(null, cfg.useHttpsDomains, key);
this.cfg = cfg;
this.bucketName = bucketName;
this.accessKey = accessKey;
}
@Override
protected void willBuildUrl() throws QiniuException {
super.willBuildUrl();
if (StringUtils.isNullOrEmpty(getDomain())) {
setDomain(queryDomain());
}
}
@Override
protected void willSetKeyForUrl(Api.Request request) throws QiniuException {
request.addPathSegment("getfile");
request.addPathSegment(accessKey);
request.addPathSegment(bucketName);
super.willSetKeyForUrl(request);
}
private String queryDomain() throws QiniuException {
if (cfg == null) {
ApiUtils.throwInvalidRequestParamException("configuration");
}
if (accessKey == null) {
ApiUtils.throwInvalidRequestParamException("accessKey");
}
if (bucketName == null) {
ApiUtils.throwInvalidRequestParamException("bucketName");
}
ConfigHelper configHelper = new ConfigHelper(cfg);
String host = configHelper.ioHost(accessKey, bucketName);
if (StringUtils.isNullOrEmpty(host)) {
return host;
}
if (host.contains("http://")) {
return host.replaceFirst("http://", "");
}
if (host.contains("https://")) {
return host.replaceFirst("https://", "");
}
return host;
}
}
| qiniu/java-sdk | src/main/java/com/qiniu/storage/DownloadPrivateCloudUrl.java |
568 | package com.battcn.annotation;
import com.battcn.validator.DateTimeValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* @author Levin
* @since 2018/6/6 0006
*/
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = DateTimeValidator.class)
public @interface DateTime {
/**
* 错误消息 - 关键字段
*
* @return 默认错误消息
*/
String message() default "格式错误";
/**
* 格式
*
* @return 验证的日期格式
*/
String format() default "yyyy-MM-dd";
/**
* 允许我们为约束指定验证组 - 关键字段(TODO 下一章中会介绍)
*
* @return 分组
*/
Class<?>[] groups() default {};
/**
* payload - 关键字段
*
* @return 暂时不清楚, 知道的欢迎留言交流
*/
Class<? extends Payload>[] payload() default {};
}
| battcn/spring-boot2-learning | chapter19/src/main/java/com/battcn/annotation/DateTime.java |
569 | package com.fangxuele.tool.push.ui.dialog;
import com.fangxuele.tool.push.App;
import com.fangxuele.tool.push.util.ComponentUtil;
import com.fangxuele.tool.push.util.SystemUtil;
import com.formdev.flatlaf.util.SystemInfo;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import lombok.Getter;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.HyperlinkEvent;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
/**
* <pre>
* 通用提示dialog
* </pre>
*
* @author <a href="https://github.com/rememberber">Zhou Bo</a>
* @since 2019/6/8.
*/
@Getter
public class CommonTipsDialog extends JDialog {
private static final long serialVersionUID = -4608047820923359408L;
private JPanel contentPane;
private JButton buttonOK;
private JTextPane textPane1;
public CommonTipsDialog() {
super(App.mainFrame, "提示");
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
if (SystemUtil.isMacOs() && SystemInfo.isMacFullWindowContentSupported) {
this.getRootPane().putClientProperty("apple.awt.fullWindowContent", true);
this.getRootPane().putClientProperty("apple.awt.transparentTitleBar", true);
this.getRootPane().putClientProperty("apple.awt.fullscreenable", true);
this.getRootPane().putClientProperty("apple.awt.windowTitleVisible", false);
GridLayoutManager gridLayoutManager = (GridLayoutManager) contentPane.getLayout();
gridLayoutManager.setMargin(new Insets(28, 0, 0, 0));
}
ComponentUtil.setPreferSizeAndLocateToCenter(this, 0.4, 0.64);
textPane1.addHyperlinkListener(e -> {
if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) {
return;
}
//超链接标记中必须带有协议指定,e.getURL()才能得到,否则只能用e.getDescription()得到href的内容。
URL linkUrl = e.getURL();
if (linkUrl != null) {
try {
Desktop.getDesktop().browse(linkUrl.toURI());
} catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(this, "超链接错误", "无法打开超链接:" + linkUrl
+ "\n详情:" + e1, JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(this, "超链接错误", "超链接信息不完整:" + e.getDescription()
+ "\n请确保链接带有协议信息,如http://,mailto:", JOptionPane.ERROR_MESSAGE);
}
});
buttonOK.addActionListener(e -> onOK());
// call onCancel() when cross is clicked
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
private void onOK() {
dispose();
}
private void onCancel() {
dispose();
}
public void setPlaneText(String planeText) {
textPane1.setContentType("text/plain; charset=utf-8");
// DefaultEditorKit kit = new DefaultEditorKit();
// textPane1.setEditorKit(kit);
textPane1.setText(planeText);
}
public void setHtmlText(String htmlText) {
textPane1.setContentType("text/html; charset=utf-8");
HTMLEditorKit kit = new HTMLEditorKit();
textPane1.setEditorKit(kit);
StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("h2{color:#FBC87A;}");
styleSheet.addRule("body{font-family:" + buttonOK.getFont().getName() + ";font-size:" + buttonOK.getFont().getSize() + ";}");
textPane1.setText(htmlText);
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPane = new JPanel();
contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 10, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 10, 0), -1, -1));
contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonOK = new JButton();
buttonOK.setText("知道了");
panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer2 = new Spacer();
panel1.add(spacer2, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JScrollPane scrollPane1 = new JScrollPane();
panel3.add(scrollPane1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
scrollPane1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
textPane1 = new JTextPane();
textPane1.setEditable(false);
textPane1.setMargin(new Insets(80, 28, 3, 28));
textPane1.setRequestFocusEnabled(false);
scrollPane1.setViewportView(textPane1);
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
}
| rememberber/WePush | src/main/java/com/fangxuele/tool/push/ui/dialog/CommonTipsDialog.java |
570 | package com.zone.weixin4j.message.event;
import com.zone.weixin4j.type.EventType;
import javax.xml.bind.annotation.XmlElement;
/**
* 自定义菜单事件(view|click)
*
* @className MenuEventMessage
* @author jinyu([email protected])
* @date 2014年4月6日
* @since JDK 1.6
* @see <a
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140454&token=&lang=zh_CN">订阅号、服务号的菜单事件</a>
* @see <a
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E6%8E%A5%E6%94%B6%E4%BA%8B%E4%BB%B6#.E4.B8.8A.E6.8A.A5.E8.8F.9C.E5.8D.95.E4.BA.8B.E4.BB.B6">企业号的菜单事件</a>
*/
public class MenuEventMessage extends EventMessage {
private static final long serialVersionUID = -1049672447995366063L;
public MenuEventMessage() {
super(EventType.click.name());
}
public MenuEventMessage(EventType eventType) {
super(eventType.name());
}
/**
* 事件KEY值,与自定义菜单接口中KEY值对应
*/
@XmlElement(name = "EventKey")
private String eventKey;
/**
* 指菜单ID,如果是个性化菜单,则可以通过这个字段,知道是哪个规则的菜单被点击了。
*/
@XmlElement(name = "MenuID")
private String menuId;
public String getEventKey() {
return eventKey;
}
public String getMenuId() {
return menuId;
}
@Override
public String toString() {
return "MenuEventMessage [eventKey=" + eventKey + ", menuId=" + menuId
+ ", " + super.toString() + "]";
}
}
| foxinmy/weixin4j | weixin4j-serverX/src/main/java/com/zone/weixin4j/message/event/MenuEventMessage.java |
571 | /*
* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.chrono.Chronology;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.SignStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.time.temporal.ValueRange;
import java.util.Objects;
import static java.time.temporal.ChronoUnit.CENTURIES;
import static java.time.temporal.ChronoUnit.DECADES;
import static java.time.temporal.ChronoUnit.ERAS;
import static java.time.temporal.ChronoUnit.MILLENNIA;
import static java.time.temporal.ChronoUnit.YEARS;
/**
* A year in the ISO-8601 calendar system, such as {@code 2007}.
* <p>
* {@code Year} is an immutable date-time object that represents a year.
* Any field that can be derived from a year can be obtained.
* <p>
* <b>Note that years in the ISO chronology only align with years in the
* Gregorian-Julian system for modern years. Parts of Russia did not switch to the
* modern Gregorian/ISO rules until 1920.
* As such, historical years must be treated with caution.</b>
* <p>
* This class does not store or represent a month, day, time or time-zone.
* For example, the value "2007" can be stored in a {@code Year}.
* <p>
* Years represented by this class follow the ISO-8601 standard and use
* the proleptic numbering system. Year 1 is preceded by year 0, then by year -1.
* <p>
* The ISO-8601 calendar system is the modern civil calendar system used today
* in most of the world. It is equivalent to the proleptic Gregorian calendar
* system, in which today's rules for leap years are applied for all time.
* For most applications written today, the ISO-8601 rules are entirely suitable.
* However, any application that makes use of historical dates, and requires them
* to be accurate will find the ISO-8601 approach unsuitable.
*
* <p>
* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
* class; use of identity-sensitive operations (including reference equality
* ({@code ==}), identity hash code, or synchronization) on instances of
* {@code Year} may have unpredictable results and should be avoided.
* The {@code equals} method should be used for comparisons.
*
* @implSpec This class is immutable and thread-safe.
* @since 1.8
*/
// x年
public final class Year implements Temporal, TemporalAdjuster, Comparable<Year>, Serializable {
/**
* The minimum supported year, '-999,999,999'.
*/
public static final int MIN_VALUE = -999_999_999;
/**
* The maximum supported year, '+999,999,999'.
*/
public static final int MAX_VALUE = 999_999_999;
/**
* Parser.
*/
private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD).toFormatter();
/**
* The year being represented.
*/
private final int year; // "Proleptic年"部件[-999_999_999, 999_999_999]
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Constructor.
*
* @param year the year to represent
*/
private Year(int year) {
this.year = year;
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Obtains the current year from the system clock in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current year.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current year using the system clock and default time-zone, not null
*/
// 基于此刻的UTC时间,构造属于系统默认时区的Year对象
public static Year now() {
// 获取一个系统时钟,其预设的时区ID为系统默认的时区ID
Clock clock = Clock.systemDefaultZone();
return now(clock);
}
/**
* Obtains the current year from the system clock in the specified time-zone.
* <p>
* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
*
* @return the current year using the system clock, not null
*/
// 基于此刻的UTC时间,构造属于zone时区的Year对象
public static Year now(ZoneId zone) {
// 获取一个系统时钟,其预设的时区ID为zone
Clock clock = Clock.system(zone);
return now(clock);
}
/**
* Obtains the current year from the specified clock.
* <p>
* This will query the specified clock to obtain the current year.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
*
* @return the current year, not null
*/
// 基于clock提供的时间戳和时区ID构造Year对象
public static Year now(Clock clock) {
// 基于clock提供的时间戳和时区ID构造"本地日期"对象
final LocalDate now = LocalDate.now(clock);
return Year.of(now.getYear());
}
/**
* Obtains an instance of {@code Year}.
* <p>
* This method accepts a year value from the proleptic ISO calendar system.
* <p>
* The year 2AD/CE is represented by 2.<br>
* The year 1AD/CE is represented by 1.<br>
* The year 1BC/BCE is represented by 0.<br>
* The year 2BC/BCE is represented by -1.<br>
*
* @param isoYear the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE}
*
* @return the year, not null
*
* @throws DateTimeException if the field is invalid
*/
// 根据指定的Proleptic年构造Year对象
public static Year of(int isoYear) {
ChronoField.YEAR.checkValidValue(isoYear);
return new Year(isoYear);
}
/**
* Obtains an instance of {@code Year} from a temporal object.
* <p>
* This obtains a year based on the specified temporal.
* A {@code TemporalAccessor} represents an arbitrary set of date and time information,
* which this factory converts to an instance of {@code Year}.
* <p>
* The conversion extracts the {@link ChronoField#YEAR year} field.
* The extraction is only permitted if the temporal object has an ISO
* chronology, or can be converted to a {@code LocalDate}.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
* allowing it to be used as a query via method reference, {@code Year::from}.
*
* @param temporal the temporal object to convert, not null
*
* @return the year, not null
*
* @throws DateTimeException if unable to convert to a {@code Year}
*/
// 从temporal中查询/构造Year对象
public static Year from(TemporalAccessor temporal) {
Objects.requireNonNull(temporal, "temporal");
if(temporal instanceof Year) {
return (Year) temporal;
}
try {
if(!IsoChronology.INSTANCE.equals(Chronology.from(temporal))) {
temporal = LocalDate.from(temporal);
}
return of(temporal.get(ChronoField.YEAR));
} catch(DateTimeException ex) {
throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " + temporal + " of type " + temporal.getClass().getName(), ex);
}
}
/**
* Obtains an instance of {@code Year} from a text string such as {@code 2007}.
* <p>
* The string must represent a valid year.
* Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
*
* @param text the text to parse such as "2007", not null
*
* @return the parsed year, not null
*
* @throws DateTimeParseException if the text cannot be parsed
*/
// 从指定的文本中解析出Year信息,要求该文本符合ISO规范,即类似:2020
public static Year parse(CharSequence text) {
return parse(text, PARSER);
}
/**
* Obtains an instance of {@code Year} from a text string using a specific formatter.
* <p>
* The text is parsed using the formatter, returning a year.
*
* @param text the text to parse, not null
* @param formatter the formatter to use, not null
*
* @return the parsed year, not null
*
* @throws DateTimeParseException if the text cannot be parsed
*/
// 从指定的文本中解析出Year信息,要求该文本符合指定的格式规范
public static Year parse(CharSequence text, DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.parse(text, Year::from);
}
/*▲ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 转换 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Combines this year with a day-of-year to create a {@code LocalDate}.
* <p>
* This returns a {@code LocalDate} formed from this year and the specified day-of-year.
* <p>
* The day-of-year value 366 is only valid in a leap year.
*
* @param dayOfYear the day-of-year to use, from 1 to 365-366
*
* @return the local date formed from this year and the specified date of year, not null
*
* @throws DateTimeException if the day of year is zero or less, 366 or greater or equal
* to 366 and this is not a leap year
*/
// 使用当前Proleptic年和年份中的天数dayOfYear构造"本地日期"对象
public LocalDate atDay(int dayOfYear) {
return LocalDate.ofYearDay(year, dayOfYear);
}
/**
* Combines this year with a month to create a {@code YearMonth}.
* <p>
* This returns a {@code YearMonth} formed from this year and the specified month.
* All possible combinations of year and month are valid.
* <p>
* This method can be used as part of a chain to produce a date:
* <pre>
* LocalDate date = year.atMonth(month).atDay(day);
* </pre>
*
* @param month the month-of-year to use, not null
*
* @return the year-month formed from this year and the specified month, not null
*/
// 使用当前Proleptic年和月份month构造YearMonth对象
public YearMonth atMonth(Month month) {
return YearMonth.of(year, month);
}
/**
* Combines this year with a month to create a {@code YearMonth}.
* <p>
* This returns a {@code YearMonth} formed from this year and the specified month.
* All possible combinations of year and month are valid.
* <p>
* This method can be used as part of a chain to produce a date:
* <pre>
* LocalDate date = year.atMonth(month).atDay(day);
* </pre>
*
* @param month the month-of-year to use, from 1 (January) to 12 (December)
*
* @return the year-month formed from this year and the specified month, not null
*
* @throws DateTimeException if the month is invalid
*/
// 使用当前Proleptic年和月份month构造YearMonth对象
public YearMonth atMonth(int month) {
return YearMonth.of(year, month);
}
/**
* Combines this year with a month-day to create a {@code LocalDate}.
* <p>
* This returns a {@code LocalDate} formed from this year and the specified month-day.
* <p>
* A month-day of February 29th will be adjusted to February 28th in the resulting
* date if the year is not a leap year.
*
* @param monthDay the month-day to use, not null
*
* @return the local date formed from this year and the specified month-day, not null
*/
// 使用当前Proleptic年和一个日期信息monthDay构造"本地日期"对象
public LocalDate atMonthDay(MonthDay monthDay) {
return monthDay.atYear(year);
}
/*▲ 转换 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 部件 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Gets the year value.
* <p>
* The year returned by this method is proleptic as per {@code get(YEAR)}.
*
* @return the year, {@code MIN_VALUE} to {@code MAX_VALUE}
*/
// 返回 "Proleptic年"部件
public int getValue() {
return year;
}
/*▲ 部件 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 增加 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a copy of this year with the specified amount added.
* <p>
* This returns a {@code Year}, based on this one, with the specified amount added.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* <p>
* The calculation is delegated to the amount object by calling
* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
* to implement the addition in any way it wishes, however it typically
* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
* of the amount implementation to determine if it can be successfully added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToAdd the amount to add, not null
*
* @return a {@code Year} based on this year with the addition made, not null
*
* @throws DateTimeException if the addition cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 对当前时间量的值与参数中的"时间段"求和
*
* 如果求和后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"求和"后的新对象再返回。
*/
@Override
public Year plus(TemporalAmount amountToAdd) {
return (Year) amountToAdd.addTo(this);
}
/**
* Returns a copy of this year with the specified amount added.
* <p>
* This returns a {@code Year}, based on this one, with the amount
* in terms of the unit added. If it is not possible to add the amount, because the
* unit is not supported or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoUnit} then the addition is implemented here.
* The supported fields behave as follows:
* <ul>
* <li>{@code YEARS} -
* Returns a {@code Year} with the specified number of years added.
* This is equivalent to {@link #plusYears(long)}.
* <li>{@code DECADES} -
* Returns a {@code Year} with the specified number of decades added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 10.
* <li>{@code CENTURIES} -
* Returns a {@code Year} with the specified number of centuries added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 100.
* <li>{@code MILLENNIA} -
* Returns a {@code Year} with the specified number of millennia added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 1,000.
* <li>{@code ERAS} -
* Returns a {@code Year} with the specified number of eras added.
* Only two eras are supported so the amount must be one, zero or minus one.
* If the amount is non-zero then the year is changed such that the year-of-era
* is unchanged.
* </ul>
* <p>
* All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
* passing {@code this} as the argument. In this case, the unit determines
* whether and how to perform the addition.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToAdd the amount of the unit to add to the result, may be negative
* @param unit the unit of the amount to add, not null
*
* @return a {@code Year} based on this year with the specified amount added, not null
*
* @throws DateTimeException if the addition cannot be made
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 对当前时间量的值累加amountToAdd个unit单位的时间量
*
* 如果累加后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
@Override
public Year plus(long amountToAdd, TemporalUnit unit) {
if(unit instanceof ChronoUnit) {
switch((ChronoUnit) unit) {
case YEARS:
return plusYears(amountToAdd);
case DECADES:
return plusYears(Math.multiplyExact(amountToAdd, 10));
case CENTURIES:
return plusYears(Math.multiplyExact(amountToAdd, 100));
case MILLENNIA:
return plusYears(Math.multiplyExact(amountToAdd, 1000));
case ERAS:
return with(ChronoField.ERA, Math.addExact(getLong(ChronoField.ERA), amountToAdd));
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.addTo(this, amountToAdd);
}
/**
* Returns a copy of this {@code Year} with the specified number of years added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToAdd the years to add, may be negative
*
* @return a {@code Year} based on this year with the years added, not null
*
* @throws DateTimeException if the result exceeds the supported range
*/
/*
* 在当前时间量的值上累加yearsToAdd年
*
* 如果累加后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"累加"操作后的新对象再返回。
*/
public Year plusYears(long yearsToAdd) {
if(yearsToAdd == 0) {
return this;
}
return of(ChronoField.YEAR.checkValidIntValue(year + yearsToAdd)); // overflow safe
}
/*▲ 增加 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 减少 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a copy of this year with the specified amount subtracted.
* <p>
* This returns a {@code Year}, based on this one, with the specified amount subtracted.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* <p>
* The calculation is delegated to the amount object by calling
* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
* to implement the subtraction in any way it wishes, however it typically
* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
* of the amount implementation to determine if it can be successfully subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToSubtract the amount to subtract, not null
*
* @return a {@code Year} based on this year with the subtraction made, not null
*
* @throws DateTimeException if the subtraction cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 对当前时间量的值与参数中的"时间段"求差
*
* 如果求差后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"求差"后的新对象再返回。
*/
@Override
public Year minus(TemporalAmount amountToSubtract) {
return (Year) amountToSubtract.subtractFrom(this);
}
/**
* Returns a copy of this year with the specified amount subtracted.
* <p>
* This returns a {@code Year}, based on this one, with the amount
* in terms of the unit subtracted. If it is not possible to subtract the amount,
* because the unit is not supported or for some other reason, an exception is thrown.
* <p>
* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
* See that method for a full description of how addition, and thus subtraction, works.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToSubtract the amount of the unit to subtract from the result, may be negative
* @param unit the unit of the amount to subtract, not null
*
* @return a {@code Year} based on this year with the specified amount subtracted, not null
*
* @throws DateTimeException if the subtraction cannot be made
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 对当前时间量的值减去amountToSubtract个unit单位的时间量
*
* 如果减去后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"减去"操作后的新对象再返回。
*/
@Override
public Year minus(long amountToSubtract, TemporalUnit unit) {
if(amountToSubtract == Long.MIN_VALUE) {
return plus(Long.MAX_VALUE, unit).plus(1, unit);
}
return plus(-amountToSubtract, unit);
}
/**
* Returns a copy of this {@code Year} with the specified number of years subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToSubtract the years to subtract, may be negative
*
* @return a {@code Year} based on this year with the year subtracted, not null
*
* @throws DateTimeException if the result exceeds the supported range
*/
/*
* 在当前时间量的值上减去yearsToSubtract年
*
* 如果减去后的值与当前时间量的值相等,则直接返回当前时间量对象。
* 否则,需要构造"减去"操作后的新对象再返回。
*/
public Year minusYears(long yearsToSubtract) {
if(yearsToSubtract == Long.MIN_VALUE) {
return plusYears(Long.MAX_VALUE).plusYears(1);
}
return plusYears(-yearsToSubtract);
}
/*▲ 减少 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 时间量单位 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Checks if the specified unit is supported.
* <p>
* This checks if the specified unit can be added to, or subtracted from, this year.
* If false, then calling the {@link #plus(long, TemporalUnit)} and
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
* <p>
* If the unit is a {@link ChronoUnit} then the query is implemented here.
* The supported units are:
* <ul>
* <li>{@code YEARS}
* <li>{@code DECADES}
* <li>{@code CENTURIES}
* <li>{@code MILLENNIA}
* <li>{@code ERAS}
* </ul>
* All other {@code ChronoUnit} instances will return false.
* <p>
* If the unit is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
* passing {@code this} as the argument.
* Whether the unit is supported is determined by the unit.
*
* @param unit the unit to check, null returns false
*
* @return true if the unit can be added/subtracted, false if not
*/
// 判断当前时间量是否支持指定的时间量单位
@Override
public boolean isSupported(TemporalUnit unit) {
if(unit instanceof ChronoUnit) {
return unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;
}
return unit != null && unit.isSupportedBy(this);
}
/*▲ 时间量单位 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 时间量字段操作(TemporalAccessor) ███████████████████████████████████████████████████████┓ */
/**
* Checks if the specified field is supported.
* <p>
* This checks if this year can be queried for the specified field.
* If false, then calling the {@link #range(TemporalField) range},
* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
* methods will throw an exception.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The supported fields are:
* <ul>
* <li>{@code YEAR_OF_ERA}
* <li>{@code YEAR}
* <li>{@code ERA}
* </ul>
* All other {@code ChronoField} instances will return false.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
* passing {@code this} as the argument.
* Whether the field is supported is determined by the field.
*
* @param field the field to check, null returns false
*
* @return true if the field is supported on this year, false if not
*/
// 判断当前时间量是否支持指定的时间量字段
@Override
public boolean isSupported(TemporalField field) {
if(field instanceof ChronoField) {
return field == ChronoField.YEAR || field == ChronoField.YEAR_OF_ERA || field == ChronoField.ERA;
}
return field != null && field.isSupportedBy(this);
}
/**
* Gets the range of valid values for the specified field.
* <p>
* The range object expresses the minimum and maximum valid values for a field.
* This year is used to enhance the accuracy of the returned range.
* If it is not possible to return the range, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return
* appropriate range instances.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
* passing {@code this} as the argument.
* Whether the range can be obtained is determined by the field.
*
* @param field the field to query the range for, not null
*
* @return the range of valid values for the field, not null
*
* @throws DateTimeException if the range for the field cannot be obtained
* @throws UnsupportedTemporalTypeException if the field is not supported
*/
// 返回时间量字段field的取值区间,通常要求当前时间量支持该时间量字段
@Override
public ValueRange range(TemporalField field) {
if(field == ChronoField.YEAR_OF_ERA) {
if(year<=0) {
return ValueRange.of(1, MAX_VALUE + 1);
}
return ValueRange.of(1, MAX_VALUE);
}
return Temporal.super.range(field);
}
/**
* Gets the value of the specified field from this year as an {@code int}.
* <p>
* This queries this year for the value of the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this year.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param field the field to get, not null
*
* @return the value for the field
*
* @throws DateTimeException if a value for the field cannot be obtained or
* the value is outside the range of valid values for the field
* @throws UnsupportedTemporalTypeException if the field is not supported or
* the range of values exceeds an {@code int}
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 以int形式返回时间量字段field的值
*
* 目前支持的字段包括:
*
* ChronoField.YEAR - 返回"Proleptic年"部件
* ....................... ...........................................
* ChronoField.YEAR_OF_ERA - 将"Proleptic年"转换为位于纪元中的[年]后返回
* ChronoField.ERA - 计算"Proleptic年"年所在的纪元;在公历系统中,0是公元前,1是公元(后)
*/
@Override
public int get(TemporalField field) {
long longValue = getLong(field);
return range(field).checkValidIntValue(longValue, field);
}
/**
* Gets the value of the specified field from this year as a {@code long}.
* <p>
* This queries this year for the value of the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this year.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param field the field to get, not null
*
* @return the value for the field
*
* @throws DateTimeException if a value for the field cannot be obtained
* @throws UnsupportedTemporalTypeException if the field is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 以long形式返回时间量字段field的值
*
* 目前支持的字段包括:
*
* ChronoField.YEAR - 返回"Proleptic年"部件
* ....................... ...........................................
* ChronoField.YEAR_OF_ERA - 将"Proleptic年"转换为位于纪元中的[年]后返回
* ChronoField.ERA - 计算"Proleptic年"年所在的纪元;在公历系统中,0是公元前,1是公元(后)
*/
@Override
public long getLong(TemporalField field) {
if(field instanceof ChronoField) {
switch((ChronoField) field) {
case YEAR_OF_ERA:
return (year<1 ? 1 - year : year);
case YEAR:
return year;
case ERA:
return (year<1 ? 0 : 1);
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.getFrom(this);
}
/**
* Queries this year using the specified query.
* <p>
* This queries this year using the specified query strategy object.
* The {@code TemporalQuery} object defines the logic to be used to
* obtain the result. Read the documentation of the query to understand
* what the result of this method will be.
* <p>
* The result of this method is obtained by invoking the
* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
* specified query passing {@code this} as the argument.
*
* @param <R> the type of the result
* @param query the query to invoke, not null
*
* @return the query result, null may be returned (defined by the query)
*
* @throws DateTimeException if unable to query (defined by the query)
* @throws ArithmeticException if numeric overflow occurs (defined by the query)
*/
// 使用指定的时间量查询器,从当前时间量中查询目标信息
@SuppressWarnings("unchecked")
@Override
public <R> R query(TemporalQuery<R> query) {
if(query == TemporalQueries.precision()) {
return (R) YEARS;
}
if(query == TemporalQueries.chronology()) {
return (R) IsoChronology.INSTANCE;
}
return Temporal.super.query(query);
}
/*▲ 时间量字段操作(TemporalAccessor) ███████████████████████████████████████████████████████┛ */
/*▼ 整合 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns an adjusted copy of this year.
* <p>
* This returns a {@code Year}, based on this one, with the year adjusted.
* The adjustment takes place using the specified adjuster strategy object.
* Read the documentation of the adjuster to understand what adjustment will be made.
* <p>
* The result of this method is obtained by invoking the
* {@link TemporalAdjuster#adjustInto(Temporal)} method on the
* specified adjuster passing {@code this} as the argument.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param adjuster the adjuster to use, not null
*
* @return a {@code Year} based on {@code this} with the adjustment made, not null
*
* @throws DateTimeException if the adjustment cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 使用指定的时间量整合器adjuster来构造时间量对象。
*
* 如果整合后的值与当前时间量中的值相等,则直接返回当前时间量对象。
* 否则,需要构造"整合"后的新对象再返回。
*/
@Override
public Year with(TemporalAdjuster adjuster) {
return (Year) adjuster.adjustInto(this);
}
/**
* Returns a copy of this year with the specified field set to a new value.
* <p>
* This returns a {@code Year}, based on this one, with the value
* for the specified field changed.
* If it is not possible to set the value, because the field is not supported or for
* some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the adjustment is implemented here.
* The supported fields behave as follows:
* <ul>
* <li>{@code YEAR_OF_ERA} -
* Returns a {@code Year} with the specified year-of-era
* The era will be unchanged.
* <li>{@code YEAR} -
* Returns a {@code Year} with the specified year.
* This completely replaces the date and is equivalent to {@link #of(int)}.
* <li>{@code ERA} -
* Returns a {@code Year} with the specified era.
* The year-of-era will be unchanged.
* </ul>
* <p>
* In all cases, if the new value is outside the valid range of values for the field
* then a {@code DateTimeException} will be thrown.
* <p>
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
* passing {@code this} as the argument. In this case, the field determines
* whether and how to adjust the instant.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param field the field to set in the result, not null
* @param newValue the new value of the field in the result
*
* @return a {@code Year} based on {@code this} with the specified field set, not null
*
* @throws DateTimeException if the field cannot be set
* @throws UnsupportedTemporalTypeException if the field is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 通过整合指定类型的字段和当前时间量中的其他类型的字段来构造时间量对象。
*
* 如果整合后的值与当前时间量中的值相等,则直接返回当前时间量对象。
* 否则,需要构造"整合"后的新对象再返回。
*
* field : 待整合的字段(类型)
* newValue: field的原始值,需要根据filed的类型进行放缩
*
* 目前支持传入的字段值包括:
*
* ChronoField.YEAR - 与[Proleptic-年]整合,只会覆盖当前时间量的"Proleptic年"部件
* ....................................................................................
* ChronoField.YEAR_OF_ERA - 与位于纪元中的[年]整合,这会将该年份进行转换后覆盖"Proleptic年"部件
* ChronoField.ERA - 与[纪元]整合,即切换公元前与公元(后)
*/
@Override
public Year with(TemporalField field, long newValue) {
if(field instanceof ChronoField) {
ChronoField f = (ChronoField) field;
f.checkValidValue(newValue);
switch(f) {
case YEAR_OF_ERA:
return Year.of((int) (year >= 1 ? newValue : 1 - newValue));
case YEAR:
return Year.of((int) newValue);
case ERA:
return (getLong(ChronoField.ERA) == newValue ? this : Year.of(1 - year));
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.adjustInto(this, newValue);
}
/**
* Adjusts the specified temporal object to have this year.
* <p>
* This returns a temporal object of the same observable type as the input
* with the year changed to be the same as this.
* <p>
* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
* passing {@link ChronoField#YEAR} as the field.
* If the specified temporal object does not use the ISO calendar system then
* a {@code DateTimeException} is thrown.
* <p>
* In most cases, it is clearer to reverse the calling pattern by using
* {@link Temporal#with(TemporalAdjuster)}:
* <pre>
* // these two lines are equivalent, but the second approach is recommended
* temporal = thisYear.adjustInto(temporal);
* temporal = temporal.with(thisYear);
* </pre>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param temporal the target object to be adjusted, not null
*
* @return the adjusted object, not null
*
* @throws DateTimeException if unable to make the adjustment
* @throws ArithmeticException if numeric overflow occurs
*/
/*
* 拿当前时间量中的特定字段与时间量temporal中的其他字段进行整合。
*
* 如果整合后的值与temporal中原有的值相等,则可以直接使用temporal本身;否则,会返回新构造的时间量对象。
*
* 注:通常,这会用到当前时间量的所有部件信息
*
*
* 当前时间量参与整合字段包括:
* ChronoField.YEAR - 当前时间量的"Proleptic年"部件
*
* 目标时间量temporal的取值可以是:
* Year
* YearMonth
* LocalDate
* LocalDateTime
* OffsetDateTime
* ZonedDateTime
* ChronoLocalDateTimeImpl
* ChronoZonedDateTimeImpl
*/
@Override
public Temporal adjustInto(Temporal temporal) {
// 确保temporal是基于ISO历法系统的时间量
if(!Chronology.from(temporal).equals(IsoChronology.INSTANCE)) {
throw new DateTimeException("Adjustment only supported on ISO date-time");
}
return temporal.with(ChronoField.YEAR, year);
}
/*▲ 整合 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 杂项 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Calculates the amount of time until another year in terms of the specified unit.
* <p>
* This calculates the amount of time between two {@code Year}
* objects in terms of a single {@code TemporalUnit}.
* The start and end points are {@code this} and the specified year.
* The result will be negative if the end is before the start.
* The {@code Temporal} passed to this method is converted to a
* {@code Year} using {@link #from(TemporalAccessor)}.
* For example, the amount in decades between two year can be calculated
* using {@code startYear.until(endYear, DECADES)}.
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two years.
* For example, the amount in decades between 2012 and 2031
* will only be one decade as it is one year short of two decades.
* <p>
* There are two equivalent ways of using this method.
* The first is to invoke this method.
* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
* <pre>
* // these two lines are equivalent
* amount = start.until(end, YEARS);
* amount = YEARS.between(start, end);
* </pre>
* The choice should be made based on which makes the code more readable.
* <p>
* The calculation is implemented in this method for {@link ChronoUnit}.
* The units {@code YEARS}, {@code DECADES}, {@code CENTURIES},
* {@code MILLENNIA} and {@code ERAS} are supported.
* Other {@code ChronoUnit} values will throw an exception.
* <p>
* If the unit is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
* passing {@code this} as the first argument and the converted input temporal
* as the second argument.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param endExclusive the end date, exclusive, which is converted to a {@code Year}, not null
* @param unit the unit to measure the amount in, not null
*
* @return the amount of time between this year and the end year
*
* @throws DateTimeException if the amount cannot be calculated, or the end
* temporal cannot be converted to a {@code Year}
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
// 计算当前时间量到目标时间量endExclusive之间相差多少个unit单位的时间值
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
Year end = Year.from(endExclusive);
if(unit instanceof ChronoUnit) {
long yearsUntil = ((long) end.year) - year; // no overflow
switch((ChronoUnit) unit) {
case YEARS:
return yearsUntil;
case DECADES:
return yearsUntil / 10;
case CENTURIES:
return yearsUntil / 100;
case MILLENNIA:
return yearsUntil / 1000;
case ERAS:
return end.getLong(ChronoField.ERA) - getLong(ChronoField.ERA);
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.between(this, end);
}
/**
* Checks if this year is after the specified year.
*
* @param other the other year to compare to, not null
*
* @return true if this is after the specified year
*/
// 判断当前年份是否晚于参数中指定的年份
public boolean isAfter(Year other) {
return year>other.year;
}
/**
* Checks if this year is before the specified year.
*
* @param other the other year to compare to, not null
*
* @return true if this point is before the specified year
*/
// 判断当前年份是否早于参数中指定的年份
public boolean isBefore(Year other) {
return year<other.year;
}
/**
* Checks if the year is a leap year, according to the ISO proleptic
* calendar system rules.
* <p>
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without
* remainder. However, years divisible by 100, are not leap years, with
* the exception of years divisible by 400 which are.
* <p>
* For example, 1904 is a leap year it is divisible by 4.
* 1900 was not a leap year as it is divisible by 100, however 2000 was a
* leap year as it is divisible by 400.
* <p>
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*
* @param year the year to check
*
* @return true if the year is leap, false otherwise
*/
/*
* 判断当前年份是否为闰年
*
* 太阳连续两次通过春分点的时间间隔被称为一个太阳年,又被称为一个回归年。
* 根据公元1980年~公元2100年每回归年的时间长度计算得:
* 1回归年 = 365.2422天,即约等于365天5小时48分46秒。
* 这是根据121个回归年的平均值计算的结果,每个回归年的实际时间长短并不相等。
* 在初始的公历系统中,每年被规定为365天,这就导致公历年每年比回归年慢0.2422天,
* 每4年的话就是慢了4*0.2422=0.9688天,即将近慢了一天。
* 如果每隔4年在公历年上人为增加一天,即2月从28天变为29天,这就是我们说的"闰年"。
* 即(year%4==0)被认为是闰年。
* 这样一来,"差不多"就可以弥补公历年慢的天数。
* 但是这样的话,1-0.9688=0.0312,这又导致公历年每4年比回归年的4年快了0.0312天。
* 0.0312*100=3.12,即公历年每400年就比回归年的400年快了3.12天。
* 因此,为了使公历年与回归年更加匹配,每400年必须再减去3.12天。
* 每个400年中,必定有3个百年是不能被400整除的,
* 因此,我们可以取消这3个百年的"闰年"身份,使其成为平年。
* 但是对于那个能被400整除的百年,我们依然保留它的"闰年'身份。
* 这样一来,每400个公历年就只比400个回归年快3.12-3=0.12天了,
* 进一步计算,每个公历年比回归年快0.0003天,即:
* 1公历年 = 365.2422+0.0003 = 365.2425天
* 即每过3333年,公历年大概会比回归年快1天,这个误差在目前是可以接受的。
* 经过上述人为定义后,我们可以知道,
* 对于非百年的年份,只要该年份能被4整除,它就是"闰年"。
* 对于百年的年份来说,只有它被400整除,才被认为是"闰年"。
* 用程序表示"闰年"就是:(year%100!=0 && year%4==0) || (year%100==0 && year%400==0) -- (1)的计算结果为true,
* 由于year%4!=0时,(year%100==0 && year%400==0)必定为false,
* 因此,(1)式可以简化为:(year%100!=0 && year%4==0) || (year%400==0) -- (2)。
* 根据逻辑运算的分配律,(2)式等价于(year%100!=0 || year%400==0) && (year%4==0 || year%400==0) -- (3)。
* 因为year%4!=0时,year%400==0必定为false,
* 因此,(3)式可以简化为:(year%100!=0 || year%400==0) && (year%4==0) -- (4),本方法就是用了这个判别式。
*
* 综上所述,判断闰年的表达式可以为:
* (year%100!=0 && year%4==0) || (year%100==0 && year%400==0) -- (1)
* year%400==0 || (year%4==0 && year%100!=0) -- (2)
* year%4==0 && (year%100!=0 || year%400==0) -- (4)
*/
public static boolean isLeap(long year) {
// 能被4整除,且不能被100整除;或者,能被400整除
return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
}
/**
* Checks if the year is a leap year, according to the ISO proleptic
* calendar system rules.
* <p>
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without
* remainder. However, years divisible by 100, are not leap years, with
* the exception of years divisible by 400 which are.
* <p>
* For example, 1904 is a leap year it is divisible by 4.
* 1900 was not a leap year as it is divisible by 100, however 2000 was a
* leap year as it is divisible by 400.
* <p>
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*
* @return true if the year is leap, false otherwise
*/
// 判断当前年份是否为闰年
public boolean isLeap() {
return Year.isLeap(year);
}
/**
* Gets the length of this year in days.
*
* @return the length of this year in days, 365 or 366
*/
// 返回当前年份包含的天数
public int length() {
return isLeap() ? 366 : 365;
}
/**
* Checks if the month-day is valid for this year.
* <p>
* This method checks whether this year and the input month and day form
* a valid date.
*
* @param monthDay the month-day to validate, null returns false
*
* @return true if the month and day are valid for this year
*/
// 判断monthDay是否处于当前年份中
public boolean isValidMonthDay(MonthDay monthDay) {
return monthDay != null && monthDay.isValidYear(year);
}
/**
* Formats this year using the specified formatter.
* <p>
* This year will be passed to the formatter to produce a string.
*
* @param formatter the formatter to use, not null
*
* @return the formatted year string, not null
*
* @throws DateTimeException if an error occurs during printing
*/
// 将当前日期转换为一个指定格式的字符串后返回
public String format(DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.format(this);
}
/*▲ 杂项 ████████████████████████████████████████████████████████████████████████████████┛ */
/**
* Compares this year to another year.
* <p>
* The comparison is based on the value of the year.
* It is "consistent with equals", as defined by {@link Comparable}.
*
* @param other the other year to compare to, not null
*
* @return the comparator value, negative if less, positive if greater
*/
@Override
public int compareTo(Year other) {
return year - other.year;
}
/**
* Outputs this year as a {@code String}.
*
* @return a string representation of this year, not null
*/
@Override
public String toString() {
return Integer.toString(year);
}
/**
* Checks if this year is equal to another year.
* <p>
* The comparison is based on the time-line position of the years.
*
* @param obj the object to check, null returns false
*
* @return true if this is equal to the other year
*/
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj instanceof Year) {
return year == ((Year) obj).year;
}
return false;
}
/**
* A hash code for this year.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return year;
}
/*▼ 序列化 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Serialization version.
*/
private static final long serialVersionUID = -23038383694477807L;
/**
* Defend against malicious streams.
*
* @param s the stream to read
*
* @throws InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
/**
* Writes the object using a
* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
*
* @return the instance of {@code Ser}, not null
*
* @serialData <pre>
* out.writeByte(11); // identifies a Year
* out.writeInt(year);
* </pre>
*/
private Object writeReplace() {
return new Ser(Ser.YEAR_TYPE, this);
}
static Year readExternal(DataInput in) throws IOException {
return Year.of(in.readInt());
}
void writeExternal(DataOutput out) throws IOException {
out.writeInt(year);
}
/*▲ 序列化 ████████████████████████████████████████████████████████████████████████████████┛ */
}
| kangjianwei/LearningJDK | src/java/time/Year.java |
573 | package com.crossoverjie.algorithm;
import java.util.HashMap;
import java.util.Map;
/**
* Function:{1,3,5,7} target=8 返回{2,3}
*
* @author crossoverJie
* Date: 04/01/2018 09:53
* @since JDK 1.8
*/
public class TwoSum {
/**
* 时间复杂度为 O(N^2)
* @param nums
* @param target
* @return
*/
public int[] getTwo1(int[] nums,int target){
int[] result = null;
for (int i= 0 ;i<nums.length ;i++){
int a = nums[i] ;
for (int j = nums.length -1 ;j >=0 ;j--){
int b = nums[j] ;
if (i != j && (a + b) == target) {
result = new int[]{i,j} ;
}
}
}
return result ;
}
/**
* 时间复杂度 O(N)
* 利用Map Key存放目标值和当前值的差值,value 就是当前的下标
* 每次遍历是 查看当前遍历的值是否等于差值,如果是等于,说明两次相加就等于目标值。
* 然后取出 map 中 value ,和本次遍历的下标,就是两个下标值相加等于目标值了。
*
* @param nums
* @param target
* @return
*/
public int[] getTwo2(int[] nums,int target){
int[] result = new int[2] ;
Map<Integer,Integer> map = new HashMap<>(2) ;
for (int i=0 ;i<nums.length;i++){
if (map.containsKey(nums[i])){
result = new int[]{map.get(nums[i]),i} ;
}
map.put(target - nums[i],i) ;
}
return result ;
}
}
| crossoverJie/JCSprout | src/main/java/com/crossoverjie/algorithm/TwoSum.java |
574 | /**
* File: subset_sum_ii.java
* Created Time: 2023-06-21
* Author: krahets ([email protected])
*/
package chapter_backtracking;
import java.util.*;
public class subset_sum_ii {
/* 回溯算法:子集和 II */
static void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
// 子集和等于 target 时,记录解
if (target == 0) {
res.add(new ArrayList<>(state));
return;
}
// 遍历所有选择
// 剪枝二:从 start 开始遍历,避免生成重复子集
// 剪枝三:从 start 开始遍历,避免重复选择同一元素
for (int i = start; i < choices.length; i++) {
// 剪枝一:若子集和超过 target ,则直接结束循环
// 这是因为数组已排序,后边元素更大,子集和一定超过 target
if (target - choices[i] < 0) {
break;
}
// 剪枝四:如果该元素与左边元素相等,说明该搜索分支重复,直接跳过
if (i > start && choices[i] == choices[i - 1]) {
continue;
}
// 尝试:做出选择,更新 target, start
state.add(choices[i]);
// 进行下一轮选择
backtrack(state, target - choices[i], choices, i + 1, res);
// 回退:撤销选择,恢复到之前的状态
state.remove(state.size() - 1);
}
}
/* 求解子集和 II */
static List<List<Integer>> subsetSumII(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // 状态(子集)
Arrays.sort(nums); // 对 nums 进行排序
int start = 0; // 遍历起始点
List<List<Integer>> res = new ArrayList<>(); // 结果列表(子集列表)
backtrack(state, target, nums, start, res);
return res;
}
public static void main(String[] args) {
int[] nums = { 4, 4, 5 };
int target = 9;
List<List<Integer>> res = subsetSumII(nums, target);
System.out.println("输入数组 nums = " + Arrays.toString(nums) + ", target = " + target);
System.out.println("所有和等于 " + target + " 的子集 res = " + res);
}
}
| krahets/hello-algo | codes/java/chapter_backtracking/subset_sum_ii.java |
577 | package cn.hutool.core.io.file;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.LineHandler;
import cn.hutool.core.io.watch.SimpleWatcher;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
/**
* 行处理的Watcher实现
*
* @author looly
* @since 4.5.2
*/
public class LineReadWatcher extends SimpleWatcher implements Runnable {
private final RandomAccessFile randomAccessFile;
private final Charset charset;
private final LineHandler lineHandler;
/**
* 构造
*
* @param randomAccessFile {@link RandomAccessFile}
* @param charset 编码
* @param lineHandler 行处理器{@link LineHandler}实现
*/
public LineReadWatcher(RandomAccessFile randomAccessFile, Charset charset, LineHandler lineHandler) {
this.randomAccessFile = randomAccessFile;
this.charset = charset;
this.lineHandler = lineHandler;
}
@Override
public void run() {
onModify(null, null);
}
@Override
public void onModify(WatchEvent<?> event, Path currentPath) {
final RandomAccessFile randomAccessFile = this.randomAccessFile;
final Charset charset = this.charset;
final LineHandler lineHandler = this.lineHandler;
try {
final long currentLength = randomAccessFile.length();
final long position = randomAccessFile.getFilePointer();
if (position == currentLength) {
// 内容长度不变时忽略此次事件
return;
} else if (currentLength < position) {
// 如果内容变短或变0,说明文件做了删改或清空,回到内容末尾或0
randomAccessFile.seek(currentLength);
return;
}
// 读取行
FileUtil.readLines(randomAccessFile, charset, lineHandler);
// 记录当前读到的位置
randomAccessFile.seek(currentLength);
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
}
| dromara/hutool | hutool-core/src/main/java/cn/hutool/core/io/file/LineReadWatcher.java |
578 | package com.alibaba.otter.canal.client;
import java.util.concurrent.TimeUnit;
import com.alibaba.otter.canal.protocol.Message;
import com.alibaba.otter.canal.protocol.exception.CanalClientException;
/**
* canal数据操作客户端
*
* @author zebin.xuzb @ 2012-6-19
* @author jianghang
* @version 1.0.0
*/
public interface CanalConnector {
/**
* 链接对应的canal server
*
* @throws CanalClientException
*/
void connect() throws CanalClientException;
/**
* 释放链接
*
* @throws CanalClientException
*/
void disconnect() throws CanalClientException;
/**
* 检查下链接是否合法
*
* <pre>
* 几种case下链接不合法:
* 1. 链接canal server失败,一直没有一个可用的链接,返回false
* 2. 当前客户端在进行running抢占的时候,做为备份节点存在,非处于工作节点,返回false
*
* 说明:
* a. 当前客户端一旦做为备份节点存在,当前所有的对{@linkplain CanalConnector}的操作都会处于阻塞状态,直到转为工作节点
* b. 所以业务方最好定时调用checkValid()方法用,比如调用CanalConnector所在线程的interrupt,直接退出CanalConnector,并根据自己的需要退出自己的资源
* </pre>
*
* @throws CanalClientException
*/
boolean checkValid() throws CanalClientException;
/**
* 客户端订阅,重复订阅时会更新对应的filter信息
*
* <pre>
* 说明:
* a. 如果本次订阅中filter信息为空,则直接使用canal server服务端配置的filter信息
* b. 如果本次订阅中filter信息不为空,目前会直接替换canal server服务端配置的filter信息,以本次提交的为准
*
* TODO: 后续可以考虑,如果本次提交的filter不为空,在执行过滤时,是对canal server filter + 本次filter的交集处理,达到只取1份binlog数据,多个客户端消费不同的表
* </pre>
*
* @throws CanalClientException
*/
void subscribe(String filter) throws CanalClientException;
/**
* 客户端订阅,不提交客户端filter,以服务端的filter为准
*
* @throws CanalClientException
*/
void subscribe() throws CanalClientException;
/**
* 取消订阅
*
* @throws CanalClientException
*/
void unsubscribe() throws CanalClientException;
/**
* 获取数据,自动进行确认,该方法返回的条件:尝试拿batchSize条记录,有多少取多少,不会阻塞等待
*
* @param batchSize
* @return
* @throws CanalClientException
*/
Message get(int batchSize) throws CanalClientException;
/**
* 获取数据,自动进行确认
*
* <pre>
* 该方法返回的条件:
* a. 拿够batchSize条记录或者超过timeout时间
* b. 如果timeout=0,则阻塞至拿到batchSize记录才返回
* </pre>
*
* @param batchSize
* @return
* @throws CanalClientException
*/
Message get(int batchSize, Long timeout, TimeUnit unit) throws CanalClientException;
/**
* 不指定 position 获取事件,该方法返回的条件: 尝试拿batchSize条记录,有多少取多少,不会阻塞等待<br/>
* canal 会记住此 client 最新的position。 <br/>
* 如果是第一次 fetch,则会从 canal 中保存的最老一条数据开始输出。
*
* @param batchSize
* @throws CanalClientException
*/
Message getWithoutAck(int batchSize) throws CanalClientException;
/**
* 不指定 position 获取事件.
*
* <pre>
* 该方法返回的条件:
* a. 拿够batchSize条记录或者超过timeout时间
* b. 如果timeout=0,则阻塞至拿到batchSize记录才返回
* </pre>
*
* canal 会记住此 client 最新的position。 <br/>
* 如果是第一次 fetch,则会从 canal 中保存的最老一条数据开始输出。
*
* @param batchSize
* @param timeout
* @param unit
* @return
* @throws CanalClientException
*/
Message getWithoutAck(int batchSize, Long timeout, TimeUnit unit) throws CanalClientException;
/**
* 进行 batch id 的确认。确认之后,小于等于此 batchId 的 Message 都会被确认。
*
* @param batchId
* @throws CanalClientException
*/
void ack(long batchId) throws CanalClientException;
/**
* 回滚到未进行 {@link #ack} 的地方,指定回滚具体的batchId
*
* @throws CanalClientException
*/
void rollback(long batchId) throws CanalClientException;
/**
* 回滚到未进行 {@link #ack} 的地方,下次fetch的时候,可以从最后一个没有 {@link #ack} 的地方开始拿
*
* @throws CanalClientException
*/
void rollback() throws CanalClientException;
}
| alibaba/canal | client/src/main/java/com/alibaba/otter/canal/client/CanalConnector.java |
580 | M
tags: Greedy
time: O(n)
space: O(1)
给一串gas station array, 每个index里面有一定数量gas.
给一串cost array, 每个index有一个值, 是reach下一个gas station的油耗.
array的结尾地方, 再下一个点是开头, 形成一个circle route.
找一个index, 作为starting point: 让车子从这个点, 拿上油, 开出去, 还能开回到这个starting point
#### Greedy
- 不论从哪一个点开始, 都可以记录总油耗, `total = {gas[i] - cost[i]}`. 最后如果total < 0, 无论从哪开始, 必然都不能走回来
- 可以记录每一步的油耗积累, `remain += gas[i] - cost[i]`
- 一旦 remain < 0, 说明之前的starting point 不合适, 也就是说, 初始点肯定在后面的index. 重设: start = i + 1
- single for loop. Time: O(n)
#### NOT DP
- 看似有点像 House Robber II, 但是问题要求的是: 一个起始点的index
- 而不是求: 最后点可否走完/最值/计数
```
/*
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i
to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel
around the circuit once in the clockwise direction, otherwise return -1.
Note:
If there exists a solution, it is guaranteed to be unique.
Both input arrays are non-empty and have the same length.
Each element in the input arrays is a non-negative integer.
Example 1:
Input:
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
Output: 3
Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
Example 2:
Input:
gas = [2,3,4]
cost = [3,4,3]
Output: -1
Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
*/
/**
Thoughts: Loop through the gas station, and track the possible starting index.
Start from i = 0, use a second pointer move to track how far we are travelling
calculate: remain += gas[i] - cost[i].
if remain < 0, fail. This mean: with all remain gas before index i + gas[i], we won't make it to index i+1
Therefore, reset startIndex = i + 1: moving on to next possible starting point.
'total':simply indicates if we can make it a circle
*/
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null || cost == null || gas.length == 0 || cost.length == 0) {
return -1;
}
int startIndex = 0, remain = 0, total = 0;
for (int i = 0; i < gas.length; i++) {
total += gas[i] - cost[i];
remain += gas[i] - cost[i];
if (remain < 0) {
remain = 0;
startIndex = i + 1; // restart
}
}
return total < 0 ? -1 : startIndex;
}
}
``` | awangdev/leet-code | Java/134. Gas Station.java |
582 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.okgo.db;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.lzy.okgo.utils.OkLogger;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2017/5/11
* 描 述:
* 修订历史:
* ================================================
*/
public class DBUtils {
/** 是否需要升级表 */
public static boolean isNeedUpgradeTable(SQLiteDatabase db, TableEntity table) {
if (!isTableExists(db, table.tableName)) return true;
Cursor cursor = db.rawQuery("select * from " + table.tableName, null);
if (cursor == null) return false;
try {
int columnCount = table.getColumnCount();
if (columnCount == cursor.getColumnCount()) {
for (int i = 0; i < columnCount; i++) {
if (table.getColumnIndex(cursor.getColumnName(i)) == -1) {
return true;
}
}
} else {
return true;
}
return false;
} finally {
cursor.close();
}
}
/**
* SQLite数据库中一个特殊的名叫 SQLITE_MASTER 上执行一个SELECT查询以获得所有表的索引。每一个 SQLite 数据库都有一个叫 SQLITE_MASTER 的表, 它定义数据库的模式。
* SQLITE_MASTER 表看起来如下:
* CREATE TABLE sqlite_master (
* type TEXT,
* name TEXT,
* tbl_name TEXT,
* rootpage INTEGER,
* sql TEXT
* );
* 对于表来说,type 字段永远是 ‘table’,name 字段永远是表的名字。
*/
public static boolean isTableExists(SQLiteDatabase db, String tableName) {
if (tableName == null || db == null || !db.isOpen()) return false;
Cursor cursor = null;
int count = 0;
try {
cursor = db.rawQuery("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?", new String[]{"table", tableName});
if (!cursor.moveToFirst()) {
return false;
}
count = cursor.getInt(0);
} catch (Exception e) {
OkLogger.printStackTrace(e);
} finally {
if (cursor != null) cursor.close();
}
return count > 0;
}
public static boolean isFieldExists(SQLiteDatabase db, String tableName, String fieldName) {
if (tableName == null || db == null || fieldName == null || !db.isOpen()) return false;
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 0", null);
return cursor != null && cursor.getColumnIndex(fieldName) != -1;
} catch (Exception e) {
OkLogger.printStackTrace(e);
return false;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
| jeasonlzy/okhttp-OkGo | okgo/src/main/java/com/lzy/okgo/db/DBUtils.java |
587 | package io.mycat.net.mysql;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.mycat.backend.mysql.BufferUtil;
import io.mycat.config.Fields;
import io.mycat.memory.unsafe.row.UnsafeRow;
import io.mycat.net.FrontendConnection;
import io.mycat.util.ByteUtil;
import io.mycat.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ProtocolBinary::ResultsetRow:
* row of a binary resultset (COM_STMT_EXECUTE)
* Payload
* 1 packet header [00]
* string[$len] NULL-bitmap, length: (column_count + 7 + 2) / 8
* string[$len] values
*
* A Binary Protocol Resultset Row is made up of the NULL bitmap
* containing as many bits as we have columns in the resultset + 2
* and the values for columns that are not NULL in the Binary Protocol Value format.
*
* @see @http://dev.mysql.com/doc/internals/en/binary-protocol-resultset-row.html#packet-ProtocolBinary::ResultsetRow
* @see @http://dev.mysql.com/doc/internals/en/binary-protocol-value.html
* @author CrazyPig
*
*/
public class BinaryRowDataPacket extends MySQLPacket {
private static final Logger LOGGER = LoggerFactory.getLogger(BinaryRowDataPacket.class);
public int fieldCount;
public List<byte[]> fieldValues;
public byte packetHeader = (byte) 0;
public byte[] nullBitMap;
public List<FieldPacket> fieldPackets;
public BinaryRowDataPacket() {}
/**
* 从UnsafeRow转换成BinaryRowDataPacket
*
* 说明: 当开启<b>isOffHeapuseOffHeapForMerge</b>参数时,会使用UnsafeRow封装数据,
* 因此需要从这个对象里面将数据封装成BinaryRowDataPacket
*
* @param fieldPackets
* @param unsafeRow
*/
public void read(List<FieldPacket> fieldPackets, UnsafeRow unsafeRow) {
this.fieldPackets = fieldPackets;
this.fieldCount = unsafeRow.numFields();
this.fieldValues = new ArrayList<byte[]>(fieldCount);
this.packetId = unsafeRow.packetId;
this.nullBitMap = new byte[(fieldCount + 7 + 2) / 8];
for(int i = 0; i < this.fieldCount; i++) {
byte[] fv = unsafeRow.getBinary(i);
FieldPacket fieldPk = fieldPackets.get(i);
if(fv == null) {
storeNullBitMap(i);
this.fieldValues.add(fv);
} else {
convert(fv, fieldPk);
}
}
}
/**
* 从RowDataPacket转换成BinaryRowDataPacket
* @param fieldPackets 字段包集合
* @param rowDataPk 文本协议行数据包
*/
public void read(List<FieldPacket> fieldPackets, RowDataPacket rowDataPk) {
this.fieldPackets = fieldPackets;
this.fieldCount = rowDataPk.fieldCount;
this.fieldValues = new ArrayList<byte[]>(fieldCount);
this.packetId = rowDataPk.packetId;
this.nullBitMap = new byte[(fieldCount + 7 + 2) / 8];
List<byte[]> _fieldValues = rowDataPk.fieldValues;
for (int i = 0; i < fieldCount; i++) {
byte[] fv = _fieldValues.get(i);
FieldPacket fieldPk = fieldPackets.get(i);
if (fv == null) { // 字段值为null,根据协议规定存储nullBitMap
storeNullBitMap(i);
this.fieldValues.add(fv);
} else {
convert(fv, fieldPk);
}
}
}
private void storeNullBitMap(int i) {
int bitMapPos = (i + 2) / 8;
int bitPos = (i + 2) % 8;
this.nullBitMap[bitMapPos] |= (byte) (1 << bitPos);
}
/**
* 从RowDataPacket的fieldValue的数据转化成BinaryRowDataPacket的fieldValue数据
* @param fv
* @param fieldPk
*/
private void convert(byte[] fv, FieldPacket fieldPk) {
int fieldType = fieldPk.type;
switch (fieldType) {
case Fields.FIELD_TYPE_STRING:
case Fields.FIELD_TYPE_VARCHAR:
case Fields.FIELD_TYPE_VAR_STRING:
case Fields.FIELD_TYPE_ENUM:
case Fields.FIELD_TYPE_SET:
case Fields.FIELD_TYPE_LONG_BLOB:
case Fields.FIELD_TYPE_MEDIUM_BLOB:
case Fields.FIELD_TYPE_BLOB:
case Fields.FIELD_TYPE_TINY_BLOB:
case Fields.FIELD_TYPE_GEOMETRY:
case Fields.FIELD_TYPE_BIT:
case Fields.FIELD_TYPE_DECIMAL:
case Fields.FIELD_TYPE_NEW_DECIMAL:
// Fields
// value (lenenc_str) -- string
// Example
// 03 66 6f 6f -- string = "foo"
this.fieldValues.add(fv);
break;
case Fields.FIELD_TYPE_LONGLONG:
// Fields
// value (8) -- integer
// Example
// 01 00 00 00 00 00 00 00 -- int64 = 1
long longVar = ByteUtil.getLong(fv);
this.fieldValues.add(ByteUtil.getBytes(longVar));
break;
case Fields.FIELD_TYPE_LONG:
case Fields.FIELD_TYPE_INT24:
// Fields
// value (4) -- integer
// Example
// 01 00 00 00 -- int32 = 1
int intVar = ByteUtil.getInt(fv);
this.fieldValues.add(ByteUtil.getBytes(intVar));
break;
case Fields.FIELD_TYPE_SHORT:
case Fields.FIELD_TYPE_YEAR:
// Fields
// value (2) -- integer
// Example
// 01 00 -- int16 = 1
if (isUnsignedField(fieldPk)) {
this.fieldValues.add(ByteUtil.convertUnsignedShort2Binary(fv));
} else {
short shortVar = ByteUtil.getShort(fv);
this.fieldValues.add(ByteUtil.getBytes(shortVar));
}
break;
case Fields.FIELD_TYPE_TINY:
// Fields
// value (1) -- integer
// Example
// 01 -- int8 = 1
int tinyVar = ByteUtil.getInt(fv);
byte[] bytes = new byte[1];
bytes[0] = (byte)tinyVar;
this.fieldValues.add(bytes);
break;
case Fields.FIELD_TYPE_DOUBLE:
// Fields
// value (string.fix_len) -- (len=8) double
// Example
// 66 66 66 66 66 66 24 40 -- double = 10.2
double doubleVar = ByteUtil.getDouble(fv);
this.fieldValues.add(ByteUtil.getBytes(doubleVar));
break;
case Fields.FIELD_TYPE_FLOAT:
// Fields
// value (string.fix_len) -- (len=4) float
// Example
// 33 33 23 41 -- float = 10.2
float floatVar = ByteUtil.getFloat(fv);
this.fieldValues.add(ByteUtil.getBytes(floatVar));
break;
case Fields.FIELD_TYPE_DATE:
try {
Date dateVar = DateUtil.parseDate(ByteUtil.getDate(fv), DateUtil.DATE_PATTERN_ONLY_DATE);
this.fieldValues.add(ByteUtil.getBytes(dateVar, false));
} catch(org.joda.time.IllegalFieldValueException e1) {
// 当时间为 0000-00-00 00:00:00 的时候, 默认返回 1970-01-01 08:00:00.0
this.fieldValues.add(ByteUtil.getBytes(new Date(0L), false));
} catch (ParseException e) {
LOGGER.error("error",e);
}
break;
case Fields.FIELD_TYPE_DATETIME:
case Fields.FIELD_TYPE_TIMESTAMP:
String dateStr = ByteUtil.getDate(fv);
Date dateTimeVar = null;
try {
if (dateStr.indexOf(".") > 0) {
dateTimeVar = DateUtil.parseDate(dateStr, DateUtil.DATE_PATTERN_FULL);
this.fieldValues.add(ByteUtil.getBytes(dateTimeVar, false));
} else {
dateTimeVar = DateUtil.parseDate(dateStr, DateUtil.DEFAULT_DATE_PATTERN);
this.fieldValues.add(ByteUtil.getBytes(dateTimeVar, false));
}
} catch(org.joda.time.IllegalFieldValueException e1) {
// 当时间为 0000-00-00 00:00:00 的时候, 默认返回 1970-01-01 08:00:00.0
this.fieldValues.add(ByteUtil.getBytes(new Date(0L), false));
} catch (ParseException e) {
LOGGER.error("error",e);
}
break;
case Fields.FIELD_TYPE_TIME:
String timeStr = ByteUtil.getTime(fv);
Date timeVar = null;
try {
if (timeStr.indexOf(".") > 0) {
timeVar = DateUtil.parseDate(timeStr, DateUtil.TIME_PATTERN_FULL);
this.fieldValues.add(ByteUtil.getBytes(timeVar, true));
} else {
timeVar = DateUtil.parseDate(timeStr, DateUtil.DEFAULT_TIME_PATTERN);
this.fieldValues.add(ByteUtil.getBytes(timeVar, true));
}
} catch(org.joda.time.IllegalFieldValueException e1) {
// 当时间为 0000-00-00 00:00:00 的时候, 默认返回 1970-01-01 08:00:00.0
this.fieldValues.add(ByteUtil.getBytes(new Date(0L), true));
} catch (ParseException e) {
LOGGER.error("error",e);
}
break;
}
}
private boolean isUnsignedField(FieldPacket field) {
return (field.flags & FieldPacket.UNSIGNED_FLAG) > 0;
}
public void write(FrontendConnection conn) {
int size = calcPacketSize();
int packetHeaderSize = conn.getPacketHeaderSize();
int totalSize = size + packetHeaderSize;
ByteBuffer bb = null;
bb = conn.getProcessor().getBufferPool().allocate(totalSize);
BufferUtil.writeUB3(bb, calcPacketSize());
bb.put(packetId);
bb.put(packetHeader); // packet header [00]
bb.put(nullBitMap); // NULL-Bitmap
for(int i = 0; i < fieldCount; i++) { // values
byte[] fv = fieldValues.get(i);
if(fv != null) {
FieldPacket fieldPk = this.fieldPackets.get(i);
int fieldType = fieldPk.type;
switch(fieldType) {
case Fields.FIELD_TYPE_STRING:
case Fields.FIELD_TYPE_VARCHAR:
case Fields.FIELD_TYPE_VAR_STRING:
case Fields.FIELD_TYPE_ENUM:
case Fields.FIELD_TYPE_SET:
case Fields.FIELD_TYPE_LONG_BLOB:
case Fields.FIELD_TYPE_MEDIUM_BLOB:
case Fields.FIELD_TYPE_BLOB:
case Fields.FIELD_TYPE_TINY_BLOB:
case Fields.FIELD_TYPE_GEOMETRY:
case Fields.FIELD_TYPE_BIT:
case Fields.FIELD_TYPE_DECIMAL:
case Fields.FIELD_TYPE_NEW_DECIMAL:
// 长度编码的字符串需要一个字节来存储长度(0表示空字符串)
BufferUtil.writeLength(bb, fv.length);
break;
default:
break;
}
if(fv.length > 0) {
bb.put(fv);
}
}
}
conn.write(bb);
}
@Override
public ByteBuffer write(ByteBuffer bb, FrontendConnection c,
boolean writeSocketIfFull) {
int size = calcPacketSize();
int packetHeaderSize = c.getPacketHeaderSize();
int totalSize = size + packetHeaderSize;
bb = c.checkWriteBuffer(bb, totalSize, writeSocketIfFull);
BufferUtil.writeUB3(bb, size);
bb.put(packetId);
bb.put(packetHeader); // packet header [00]
bb.put(nullBitMap); // NULL-Bitmap
for(int i = 0; i < fieldCount; i++) { // values
byte[] fv = fieldValues.get(i);
if(fv != null) {
FieldPacket fieldPk = this.fieldPackets.get(i);
int fieldType = fieldPk.type;
switch(fieldType) {
case Fields.FIELD_TYPE_STRING:
case Fields.FIELD_TYPE_VARCHAR:
case Fields.FIELD_TYPE_VAR_STRING:
case Fields.FIELD_TYPE_ENUM:
case Fields.FIELD_TYPE_SET:
case Fields.FIELD_TYPE_LONG_BLOB:
case Fields.FIELD_TYPE_MEDIUM_BLOB:
case Fields.FIELD_TYPE_BLOB:
case Fields.FIELD_TYPE_TINY_BLOB:
case Fields.FIELD_TYPE_GEOMETRY:
case Fields.FIELD_TYPE_BIT:
case Fields.FIELD_TYPE_DECIMAL:
case Fields.FIELD_TYPE_NEW_DECIMAL:
// 长度编码的字符串需要一个字节来存储长度(0表示空字符串)
BufferUtil.writeLength(bb, fv.length);
break;
default:
break;
}
if(fv.length > 0) {
bb.put(fv);
}
}
}
return bb;
}
@Override
public int calcPacketSize() {
int size = 0;
size = size + 1 + nullBitMap.length;
for(int i = 0, n = fieldValues.size(); i < n; i++) {
byte[] value = fieldValues.get(i);
if(value != null) {
FieldPacket fieldPk = this.fieldPackets.get(i);
int fieldType = fieldPk.type;
switch(fieldType) {
case Fields.FIELD_TYPE_STRING:
case Fields.FIELD_TYPE_VARCHAR:
case Fields.FIELD_TYPE_VAR_STRING:
case Fields.FIELD_TYPE_ENUM:
case Fields.FIELD_TYPE_SET:
case Fields.FIELD_TYPE_LONG_BLOB:
case Fields.FIELD_TYPE_MEDIUM_BLOB:
case Fields.FIELD_TYPE_BLOB:
case Fields.FIELD_TYPE_TINY_BLOB:
case Fields.FIELD_TYPE_GEOMETRY:
case Fields.FIELD_TYPE_BIT:
case Fields.FIELD_TYPE_DECIMAL:
case Fields.FIELD_TYPE_NEW_DECIMAL:
/*
* 长度编码的字符串需要计算存储长度, 根据mysql协议文档描述
* To convert a length-encoded integer into its numeric value, check the first byte:
* If it is < 0xfb, treat it as a 1-byte integer.
* If it is 0xfc, it is followed by a 2-byte integer.
* If it is 0xfd, it is followed by a 3-byte integer.
* If it is 0xfe, it is followed by a 8-byte integer.
*
*/
if(value.length != 0) {
/*
* 长度编码的字符串需要计算存储长度,不能简单默认只有1个字节是表示长度,当数据足够长,占用的就不止1个字节
*/
// size = size + 1 + value.length;
size = size + BufferUtil.getLength(value);
} else {
size = size + 1; // 处理空字符串,只计算长度1个字节
}
break;
default:
size = size + value.length;
break;
}
}
}
return size;
}
@Override
protected String getPacketInfo() {
return "MySQL Binary RowData Packet";
}
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/net/mysql/BinaryRowDataPacket.java |
589 | class Solution {
public boolean isAlienSorted(String[] words, String order) {
int[] index = new int[26];
for (int i = 0; i < index.length; ++i) {
index[order.charAt(i) - 'a'] = i;
}
for (int i = 0; i < words.length - 1; ++i) {
String w1 = words[i];
String w2 = words[i + 1];
int l1 = w1.length(), l2 = w2.length();
for (int j = 0; j < Math.max(l1, l2); ++j) {
int i1 = j >= l1 ? -1 : index[w1.charAt(j) - 'a'];
int i2 = j >= l2 ? -1 : index[w2.charAt(j) - 'a'];
if (i1 > i2) {
// 说明不是按字典序排序,直接返回False
return false;
}
if (i1 < i2) {
// 说明当前两单词是按字典序排序,无需再往下进行循环比较
break;
}
}
}
return true;
}
} | doocs/leetcode | lcof2/剑指 Offer II 034. 外星语言是否排序/Solution.java |
591 | package org.hswebframework.web.dict;
import java.lang.annotation.*;
/**
* @author zhouhao
* @since 3.0
*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Dict {
/**
* @return 字典ID
* @see DictDefine#getId()
* @see DictDefineRepository
*/
String value() default "";
/**
* 字典别名
* @return 别名
*/
String alias() default "";
/**
* @return 字典说明, 备注
*/
String comments() default "";
}
| hs-web/hsweb-framework | hsweb-core/src/main/java/org/hswebframework/web/dict/Dict.java |
592 | package com.neo.config;
import com.neo.model.SysPermission;
import com.neo.model.SysRole;
import com.neo.model.UserInfo;
import com.neo.sevice.UserInfoService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import javax.annotation.Resource;
public class MyShiroRealm extends AuthorizingRealm {
@Resource
private UserInfoService userInfoService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
UserInfo userInfo = (UserInfo)principals.getPrimaryPrincipal();
for(SysRole role:userInfo.getRoleList()){
authorizationInfo.addRole(role.getRole());
for(SysPermission p:role.getPermissions()){
authorizationInfo.addStringPermission(p.getPermission());
}
}
return authorizationInfo;
}
/*主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确。*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
//获取用户的输入的账号.
String username = (String)token.getPrincipal();
System.out.println(token.getCredentials());
//通过username从数据库中查找 User对象,如果找到,没找到.
//实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
UserInfo userInfo = userInfoService.findByUsername(username);
System.out.println("----->>userInfo="+userInfo);
if(userInfo == null){
return null;
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
userInfo, //用户名
userInfo.getPassword(), //密码
ByteSource.Util.bytes(userInfo.getCredentialsSalt()),//salt=username+salt
getName() //realm name
);
return authenticationInfo;
}
} | ityouknow/spring-boot-examples | 2.x/spring-boot-shiro/src/main/java/com/neo/config/MyShiroRealm.java |
593 | package com.neo.config;
import com.neo.entity.SysPermission;
import com.neo.entity.SysRole;
import com.neo.entity.UserInfo;
import com.neo.sevice.UserInfoService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import javax.annotation.Resource;
public class MyShiroRealm extends AuthorizingRealm {
@Resource
private UserInfoService userInfoService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
UserInfo userInfo = (UserInfo)principals.getPrimaryPrincipal();
for(SysRole role:userInfo.getRoleList()){
authorizationInfo.addRole(role.getRole());
for(SysPermission p:role.getPermissions()){
authorizationInfo.addStringPermission(p.getPermission());
}
}
return authorizationInfo;
}
/*主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确。*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
//获取用户的输入的账号.
String username = (String)token.getPrincipal();
System.out.println(token.getCredentials());
//通过username从数据库中查找 User对象,如果找到,没找到.
//实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
UserInfo userInfo = userInfoService.findByUsername(username);
System.out.println("----->>userInfo="+userInfo);
if(userInfo == null){
return null;
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
userInfo, //用户名
userInfo.getPassword(), //密码
ByteSource.Util.bytes(userInfo.getCredentialsSalt()),//salt=username+salt
getName() //realm name
);
return authenticationInfo;
}
} | ityouknow/spring-boot-examples | 1.x/spring-boot-shiro/src/main/java/com/neo/config/MyShiroRealm.java |
595 | package com.taobao.arthas.core;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Arthas全局选项
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Option {
/*
* 选项级别,数字越小级别越高
*/
int level();
/*
* 选项名称
*/
String name();
/*
* 选项摘要说明
*/
String summary();
/*
* 命令描述
*/
String description();
} | alibaba/arthas | core/src/main/java/com/taobao/arthas/core/Option.java |
597 | package me.ag2s.umdlib.umd;
import androidx.annotation.NonNull;
import java.io.IOException;
import java.io.InputStream;
import me.ag2s.umdlib.domain.UmdBook;
import me.ag2s.umdlib.domain.UmdCover;
import me.ag2s.umdlib.domain.UmdHeader;
import me.ag2s.umdlib.tool.StreamReader;
import me.ag2s.umdlib.tool.UmdUtils;
/**
* UMD格式的电子书解析
* 格式规范参考:
* http://blog.sina.com.cn/s/blog_7c8dc2d501018o5d.html
* http://blog.sina.com.cn/s/blog_7c8dc2d501018o5l.html
*/
public class UmdReader {
UmdBook book;
InputStream inputStream;
int _AdditionalCheckNumber;
int _TotalContentLen;
boolean end = false;
public synchronized UmdBook read(InputStream inputStream) throws Exception {
book = new UmdBook();
this.inputStream = inputStream;
StreamReader reader = new StreamReader(inputStream);
UmdHeader umdHeader = new UmdHeader();
book.setHeader(umdHeader);
if (reader.readIntLe() != 0xde9a9b89) {
throw new IOException("Wrong header");
}
short num1 = -1;
byte ch = reader.readByte();
while (ch == 35) {
//int num2=reader.readByte();
short segType = reader.readShortLe();
byte segFlag = reader.readByte();
short len = (short) (reader.readUint8() - 5);
System.out.println("块标识:" + segType);
//short length1 = reader.readByte();
readSection(segType, segFlag, len, reader, umdHeader);
if ((int) segType == 241 || (int) segType == 10) {
segType = num1;
}
for (ch = reader.readByte(); ch == 36; ch = reader.readByte()) {
//int num3 = reader.readByte();
System.out.println(ch);
int additionalCheckNumber = reader.readIntLe();
int length2 = (reader.readIntLe() - 9);
readAdditionalSection(segType, additionalCheckNumber, length2, reader);
}
num1 = segType;
}
System.out.println(book.getHeader().toString());
return book;
}
private void readAdditionalSection(short segType, int additionalCheckNumber, int length, StreamReader reader) throws Exception {
switch (segType) {
case 14:
//this._TotalImageList.Add((object) Image.FromStream((Stream) new MemoryStream(reader.ReadBytes((int) length))));
break;
case 15:
//this._TotalImageList.Add((object) Image.FromStream((Stream) new MemoryStream(reader.ReadBytes((int) length))));
break;
case 129:
reader.readBytes(length);
break;
case 130:
//byte[] covers = reader.readBytes(length);
book.setCover(new UmdCover(reader.readBytes(length)));
//this._Book.Cover = BitmapImage.FromStream((Stream) new MemoryStream(reader.ReadBytes((int) length)));
break;
case 131:
System.out.println(length / 4);
book.setNum(length / 4);
for (int i = 0; i < length / 4; ++i) {
book.getChapters().addContentLength(reader.readIntLe());
}
break;
case 132:
//System.out.println(length/4);
System.out.println(_AdditionalCheckNumber);
System.out.println(additionalCheckNumber);
if (this._AdditionalCheckNumber != additionalCheckNumber) {
System.out.println(length);
book.getChapters().contents.write(UmdUtils.decompress(reader.readBytes(length)));
book.getChapters().contents.flush();
break;
} else {
for (int i = 0; i < book.getNum(); i++) {
short len = reader.readUint8();
byte[] title = reader.readBytes(len);
//System.out.println(UmdUtils.unicodeBytesToString(title));
book.getChapters().addTitle(title);
}
}
break;
default:
/*Console.WriteLine("未知内容");
Console.WriteLine("Seg Type = " + (object) segType);
Console.WriteLine("Seg Len = " + (object) length);
Console.WriteLine("content = " + (object) reader.ReadBytes((int) length));*/
break;
}
}
public void readSection(short segType, byte segFlag, short length, StreamReader reader, UmdHeader header) throws IOException {
switch (segType) {
case 1://umd文件头 DCTS_CMD_ID_VERSION
header.setUmdType(reader.readByte());
reader.readBytes(2);//Random 2
System.out.println("UMD文件类型:" + header.getUmdType());
break;
case 2://文件标题 DCTS_CMD_ID_TITLE
header.setTitle(UmdUtils.unicodeBytesToString(reader.readBytes(length)));
System.out.println("文件标题:" + header.getTitle());
break;
case 3://作者
header.setAuthor(UmdUtils.unicodeBytesToString(reader.readBytes(length)));
System.out.println("作者:" + header.getAuthor());
break;
case 4://年
header.setYear(UmdUtils.unicodeBytesToString(reader.readBytes(length)));
System.out.println("年:" + header.getYear());
break;
case 5://月
header.setMonth(UmdUtils.unicodeBytesToString(reader.readBytes(length)));
System.out.println("月:" + header.getMonth());
break;
case 6://日
header.setDay(UmdUtils.unicodeBytesToString(reader.readBytes(length)));
System.out.println("日:" + header.getDay());
break;
case 7://小说类型
header.setBookType(UmdUtils.unicodeBytesToString(reader.readBytes(length)));
System.out.println("小说类型:" + header.getBookType());
break;
case 8://出版商
header.setBookMan(UmdUtils.unicodeBytesToString(reader.readBytes(length)));
System.out.println("出版商:" + header.getBookMan());
break;
case 9:// 零售商
header.setShopKeeper(UmdUtils.unicodeBytesToString(reader.readBytes(length)));
System.out.println("零售商:" + header.getShopKeeper());
break;
case 10://CONTENT ID
System.out.println("CONTENT ID:" + reader.readHex(length));
break;
case 11:
//内容长度 DCTS_CMD_ID_FILE_LENGTH
_TotalContentLen = reader.readIntLe();
book.getChapters().setTotalContentLen(_TotalContentLen);
System.out.println("内容长度:" + _TotalContentLen);
break;
case 12://UMD文件结束
end = true;
int num2 = reader.readIntLe();
System.out.println("整个文件长度" + num2);
break;
case 13:
break;
case 14:
int num3 = reader.readByte();
break;
case 15:
reader.readBytes(length);
break;
case 129://正文
case 131://章节偏移
_AdditionalCheckNumber = reader.readIntLe();
System.out.println("章节偏移:" + _AdditionalCheckNumber);
break;
case 132://章节标题,正文
_AdditionalCheckNumber = reader.readIntLe();
System.out.println("章节标题,正文:" + _AdditionalCheckNumber);
break;
case 130://封面(jpg)
int num4 = reader.readByte();
_AdditionalCheckNumber = reader.readIntLe();
break;
case 135://页面偏移(Page Offset)
reader.readUint8();//fontSize 一字节 字体大小
reader.readUint8();//screenWidth 屏幕宽度
reader.readBytes(4);//BlockRandom 指向一个页面偏移数据块
break;
case 240://CDS KEY
break;
case 241://许可证(LICENCE KEY)
//System.out.println("整个文件长度" + length);
System.out.println("许可证(LICENCE KEY):" + reader.readHex(16));
break;
default:
if (length > 0) {
byte[] numArray = reader.readBytes(length);
}
}
}
@Override
@NonNull
public String toString() {
return "UmdReader{" +
"book=" + book +
'}';
}
}
| gedoor/legado | modules/book/src/main/java/me/ag2s/umdlib/umd/UmdReader.java |
598 | package com.example.gsyvideoplayer;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.transition.Explode;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.gsyvideoplayer.adapter.ListNormalAdapter;
import com.example.gsyvideoplayer.databinding.ActivityListVideo2Binding;
import com.example.gsyvideoplayer.databinding.ActivityListVideoBinding;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
public class ListVideoActivity extends AppCompatActivity {
ListNormalAdapter listNormalAdapter;
private boolean isPause;
private ActivityListVideoBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
// 设置一个exit transition
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setEnterTransition(new Explode());
getWindow().setExitTransition(new Explode());
}
super.onCreate(savedInstanceState);
binding = ActivityListVideoBinding.inflate(getLayoutInflater());
View rootView = binding.getRoot();
setContentView(rootView);
listNormalAdapter = new ListNormalAdapter(this);
binding.videoList.setAdapter(listNormalAdapter);
binding.videoList.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastVisibleItem = firstVisibleItem + visibleItemCount;
//大于0说明有播放
if (GSYVideoManager.instance().getPlayPosition() >= 0) {
//当前播放的位置
int position = GSYVideoManager.instance().getPlayPosition();
//对应的播放列表TAG
if (GSYVideoManager.instance().getPlayTag().equals(ListNormalAdapter.TAG)
&& (position < firstVisibleItem || position > lastVisibleItem)) {
if(GSYVideoManager.isFullState(ListVideoActivity.this)) {
return;
}
//如果滑出去了上面和下面就是否,和今日头条一样
GSYVideoManager.releaseAllVideos();
listNormalAdapter.notifyDataSetChanged();
}
}
}
});
}
@Override
public void onBackPressed() {
//为了支持重力旋转
onBackPressAdapter();
if (GSYVideoManager.backFromWindowFull(this)) {
return;
}
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
GSYVideoManager.onPause();
isPause = true;
}
@Override
protected void onResume() {
super.onResume();
GSYVideoManager.onResume();
isPause = false;
}
@Override
protected void onDestroy() {
super.onDestroy();
GSYVideoManager.releaseAllVideos();
if (listNormalAdapter != null) {
listNormalAdapter.onDestroy();
}
}
/********************************为了支持重力旋转********************************/
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (listNormalAdapter != null && listNormalAdapter.getListNeedAutoLand() && !isPause) {
listNormalAdapter.onConfigurationChanged(this, newConfig);
}
}
private void onBackPressAdapter() {
//为了支持重力旋转
if (listNormalAdapter != null && listNormalAdapter.getListNeedAutoLand()) {
listNormalAdapter.onBackPressed();
}
}
}
| CarGuo/GSYVideoPlayer | app/src/main/java/com/example/gsyvideoplayer/ListVideoActivity.java |
599 | package com.crossoverjie.algorithm;
/**
* Function:是否是环链表,采用快慢指针,一个走的快些一个走的慢些 如果最终相遇了就说明是环
* 就相当于在一个环形跑道里跑步,速度不一样的最终一定会相遇。
*
* @author crossoverJie
* Date: 04/01/2018 11:33
* @since JDK 1.8
*/
public class LinkLoop {
public static class Node{
private Object data ;
public Node next ;
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public Node(Object data) {
this.data = data ;
}
}
/**
* 判断链表是否有环
* @param node
* @return
*/
public boolean isLoop(Node node){
Node slow = node ;
Node fast = node.next ;
while (slow.next != null){
Object dataSlow = slow.data;
Object dataFast = fast.data;
//说明有环
if (dataFast == dataSlow){
return true ;
}
//一共只有两个节点,但却不是环形链表的情况,判断NPE
if (fast.next == null){
return false ;
}
//slow走慢点 fast走快点
slow = slow.next ;
fast = fast.next.next ;
//如果走的快的发现为空 说明不存在环
if (fast == null){
return false ;
}
}
return false ;
}
}
| crossoverJie/JCSprout | src/main/java/com/crossoverjie/algorithm/LinkLoop.java |
600 | package me.zhyd.oauth.config;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.request.*;
/**
* JustAuth内置的各api需要的url, 用枚举类分平台类型管理
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @since 1.0
*/
public enum AuthDefaultSource implements AuthSource {
/**
* Github
*/
GITHUB {
@Override
public String authorize() {
return "https://github.com/login/oauth/authorize";
}
@Override
public String accessToken() {
return "https://github.com/login/oauth/access_token";
}
@Override
public String userInfo() {
return "https://api.github.com/user";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthGithubRequest.class;
}
},
/**
* 新浪微博
*/
WEIBO {
@Override
public String authorize() {
return "https://api.weibo.com/oauth2/authorize";
}
@Override
public String accessToken() {
return "https://api.weibo.com/oauth2/access_token";
}
@Override
public String userInfo() {
return "https://api.weibo.com/2/users/show.json";
}
@Override
public String revoke() {
return "https://api.weibo.com/oauth2/revokeoauth2";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthWeiboRequest.class;
}
},
/**
* gitee
*/
GITEE {
@Override
public String authorize() {
return "https://gitee.com/oauth/authorize";
}
@Override
public String accessToken() {
return "https://gitee.com/oauth/token";
}
@Override
public String userInfo() {
return "https://gitee.com/api/v5/user";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthGiteeRequest.class;
}
},
/**
* 钉钉扫码登录
*/
DINGTALK {
@Override
public String authorize() {
return "https://oapi.dingtalk.com/connect/qrconnect";
}
@Override
public String accessToken() {
throw new AuthException(AuthResponseStatus.UNSUPPORTED);
}
@Override
public String userInfo() {
return "https://oapi.dingtalk.com/sns/getuserinfo_bycode";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthDingTalkRequest.class;
}
},
/**
* 钉钉账号登录
*/
DINGTALK_ACCOUNT {
@Override
public String authorize() {
return "https://oapi.dingtalk.com/connect/oauth2/sns_authorize";
}
@Override
public String accessToken() {
return DINGTALK.accessToken();
}
@Override
public String userInfo() {
return DINGTALK.userInfo();
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthDingTalkAccountRequest.class;
}
},
/**
* 百度
*/
BAIDU {
@Override
public String authorize() {
return "https://openapi.baidu.com/oauth/2.0/authorize";
}
@Override
public String accessToken() {
return "https://openapi.baidu.com/oauth/2.0/token";
}
@Override
public String userInfo() {
return "https://openapi.baidu.com/rest/2.0/passport/users/getInfo";
}
@Override
public String revoke() {
return "https://openapi.baidu.com/rest/2.0/passport/auth/revokeAuthorization";
}
@Override
public String refresh() {
return "https://openapi.baidu.com/oauth/2.0/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthBaiduRequest.class;
}
},
/**
* csdn
*/
CSDN {
@Override
public String authorize() {
return "https://api.csdn.net/oauth2/authorize";
}
@Override
public String accessToken() {
return "https://api.csdn.net/oauth2/access_token";
}
@Override
public String userInfo() {
return "https://api.csdn.net/user/getinfo";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthCsdnRequest.class;
}
},
/**
* Coding,
* <p>
* 参考 https://help.coding.net/docs/project/open/oauth.html#%E7%94%A8%E6%88%B7%E6%8E%88%E6%9D%83 中的说明,
* 新版的 coding API 地址需要传入用户团队名,这儿使用动态参数,方便在 request 中使用
*/
CODING {
@Override
public String authorize() {
return "https://%s.coding.net/oauth_authorize.html";
}
@Override
public String accessToken() {
return "https://%s.coding.net/api/oauth/access_token";
}
@Override
public String userInfo() {
return "https://%s.coding.net/api/account/current_user";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthCodingRequest.class;
}
},
/**
* oschina 开源中国
*/
OSCHINA {
@Override
public String authorize() {
return "https://www.oschina.net/action/oauth2/authorize";
}
@Override
public String accessToken() {
return "https://www.oschina.net/action/openapi/token";
}
@Override
public String userInfo() {
return "https://www.oschina.net/action/openapi/user";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthOschinaRequest.class;
}
},
/**
* 支付宝
*/
ALIPAY {
@Override
public String authorize() {
return "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm";
}
@Override
public String accessToken() {
return "https://openapi.alipay.com/gateway.do";
}
@Override
public String userInfo() {
return "https://openapi.alipay.com/gateway.do";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthAlipayRequest.class;
}
},
/**
* QQ
*/
QQ {
@Override
public String authorize() {
return "https://graph.qq.com/oauth2.0/authorize";
}
@Override
public String accessToken() {
return "https://graph.qq.com/oauth2.0/token";
}
@Override
public String userInfo() {
return "https://graph.qq.com/user/get_user_info";
}
@Override
public String refresh() {
return "https://graph.qq.com/oauth2.0/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthQqRequest.class;
}
},
/**
* 微信开放平台
*/
WECHAT_OPEN {
@Override
public String authorize() {
return "https://open.weixin.qq.com/connect/qrconnect";
}
@Override
public String accessToken() {
return "https://api.weixin.qq.com/sns/oauth2/access_token";
}
@Override
public String userInfo() {
return "https://api.weixin.qq.com/sns/userinfo";
}
@Override
public String refresh() {
return "https://api.weixin.qq.com/sns/oauth2/refresh_token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthWeChatOpenRequest.class;
}
},
/**
* 微信公众平台
*/
WECHAT_MP {
@Override
public String authorize() {
return "https://open.weixin.qq.com/connect/oauth2/authorize";
}
@Override
public String accessToken() {
return "https://api.weixin.qq.com/sns/oauth2/access_token";
}
@Override
public String userInfo() {
return "https://api.weixin.qq.com/sns/userinfo";
}
@Override
public String refresh() {
return "https://api.weixin.qq.com/sns/oauth2/refresh_token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthWeChatMpRequest.class;
}
},
/**
* 淘宝
*/
TAOBAO {
@Override
public String authorize() {
return "https://oauth.taobao.com/authorize";
}
@Override
public String accessToken() {
return "https://oauth.taobao.com/token";
}
@Override
public String userInfo() {
throw new AuthException(AuthResponseStatus.UNSUPPORTED);
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthTaobaoRequest.class;
}
},
/**
* Google
*/
GOOGLE {
@Override
public String authorize() {
return "https://accounts.google.com/o/oauth2/v2/auth";
}
@Override
public String accessToken() {
return "https://www.googleapis.com/oauth2/v4/token";
}
@Override
public String userInfo() {
return "https://www.googleapis.com/oauth2/v3/userinfo";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthGoogleRequest.class;
}
},
/**
* Facebook
*/
FACEBOOK {
@Override
public String authorize() {
return "https://www.facebook.com/v18.0/dialog/oauth";
}
@Override
public String accessToken() {
return "https://graph.facebook.com/v18.0/oauth/access_token";
}
@Override
public String userInfo() {
return "https://graph.facebook.com/v18.0/me";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthFacebookRequest.class;
}
},
/**
* 抖音
*/
DOUYIN {
@Override
public String authorize() {
return "https://open.douyin.com/platform/oauth/connect";
}
@Override
public String accessToken() {
return "https://open.douyin.com/oauth/access_token/";
}
@Override
public String userInfo() {
return "https://open.douyin.com/oauth/userinfo/";
}
@Override
public String refresh() {
return "https://open.douyin.com/oauth/refresh_token/";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthDouyinRequest.class;
}
},
/**
* 领英
*/
LINKEDIN {
@Override
public String authorize() {
return "https://www.linkedin.com/oauth/v2/authorization";
}
@Override
public String accessToken() {
return "https://www.linkedin.com/oauth/v2/accessToken";
}
@Override
public String userInfo() {
return "https://api.linkedin.com/v2/me";
}
@Override
public String refresh() {
return "https://www.linkedin.com/oauth/v2/accessToken";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthLinkedinRequest.class;
}
},
/**
* 微软
*/
MICROSOFT {
@Override
public String authorize() {
return "https://login.microsoftonline.com/%s/oauth2/v2.0/authorize";
}
@Override
public String accessToken() {
return "https://login.microsoftonline.com/%s/oauth2/v2.0/token";
}
@Override
public String userInfo() {
return "https://graph.microsoft.com/v1.0/me";
}
@Override
public String refresh() {
return "https://login.microsoftonline.com/%s/oauth2/v2.0/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthMicrosoftRequest.class;
}
},
/**
* 微软中国(世纪互联)
*/
MICROSOFT_CN {
@Override
public String authorize() {
return "https://login.partner.microsoftonline.cn/%s/oauth2/v2.0/authorize";
}
@Override
public String accessToken() {
return "https://login.partner.microsoftonline.cn/%s/oauth2/v2.0/token";
}
@Override
public String userInfo() {
return "https://microsoftgraph.chinacloudapi.cn/v1.0/me";
}
@Override
public String refresh() {
return "https://login.partner.microsoftonline.cn/%s/oauth2/v2.0/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() { return AuthMicrosoftCnRequest.class; }
},
/**
* 小米
*/
MI {
@Override
public String authorize() {
return "https://account.xiaomi.com/oauth2/authorize";
}
@Override
public String accessToken() {
return "https://account.xiaomi.com/oauth2/token";
}
@Override
public String userInfo() {
return "https://open.account.xiaomi.com/user/profile";
}
@Override
public String refresh() {
return "https://account.xiaomi.com/oauth2/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthMiRequest.class;
}
},
/**
* 今日头条
*/
TOUTIAO {
@Override
public String authorize() {
return "https://open.snssdk.com/auth/authorize";
}
@Override
public String accessToken() {
return "https://open.snssdk.com/auth/token";
}
@Override
public String userInfo() {
return "https://open.snssdk.com/data/user_profile";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthToutiaoRequest.class;
}
},
/**
* Teambition
*/
TEAMBITION {
@Override
public String authorize() {
return "https://account.teambition.com/oauth2/authorize";
}
@Override
public String accessToken() {
return "https://account.teambition.com/oauth2/access_token";
}
@Override
public String refresh() {
return "https://account.teambition.com/oauth2/refresh_token";
}
@Override
public String userInfo() {
return "https://api.teambition.com/users/me";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthTeambitionRequest.class;
}
},
/**
* 人人网
*/
RENREN {
@Override
public String authorize() {
return "https://graph.renren.com/oauth/authorize";
}
@Override
public String accessToken() {
return "https://graph.renren.com/oauth/token";
}
@Override
public String refresh() {
return "https://graph.renren.com/oauth/token";
}
@Override
public String userInfo() {
return "https://api.renren.com/v2/user/get";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthRenrenRequest.class;
}
},
/**
* Pinterest
*/
PINTEREST {
@Override
public String authorize() {
return "https://api.pinterest.com/oauth";
}
@Override
public String accessToken() {
return "https://api.pinterest.com/v1/oauth/token";
}
@Override
public String userInfo() {
return "https://api.pinterest.com/v1/me";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthPinterestRequest.class;
}
},
/**
* Stack Overflow
*/
STACK_OVERFLOW {
@Override
public String authorize() {
return "https://stackoverflow.com/oauth";
}
@Override
public String accessToken() {
return "https://stackoverflow.com/oauth/access_token/json";
}
@Override
public String userInfo() {
return "https://api.stackexchange.com/2.2/me";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthStackOverflowRequest.class;
}
},
/**
* 华为
*
* @since 1.10.0
*/
HUAWEI {
@Override
public String authorize() {
return "https://oauth-login.cloud.huawei.com/oauth2/v2/authorize";
}
@Override
public String accessToken() {
return "https://oauth-login.cloud.huawei.com/oauth2/v2/token";
}
@Override
public String userInfo() {
return "https://api.vmall.com/rest.php";
}
@Override
public String refresh() {
return "https://oauth-login.cloud.huawei.com/oauth2/v2/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthHuaweiRequest.class;
}
},
/**
* 企业微信二维码登录
*
* @since 1.10.0
*/
WECHAT_ENTERPRISE {
@Override
public String authorize() {
return "https://open.work.weixin.qq.com/wwopen/sso/qrConnect";
}
@Override
public String accessToken() {
return "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
}
@Override
public String userInfo() {
return "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthWeChatEnterpriseQrcodeRequest.class;
}
},
/**
* 企业微信二维码第三方登录
*/
WECHAT_ENTERPRISE_QRCODE_THIRD {
/**
* 授权的api
*
* @return url
*/
@Override
public String authorize() {
return "https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect";
}
/**
* 获取accessToken的api
*
* @return url
*/
@Override
public String accessToken() {
return "https://qyapi.weixin.qq.com/cgi-bin/service/get_provider_token";
}
/**
* 获取用户信息的api
*
* @return url
*/
@Override
public String userInfo() {
return "https://qyapi.weixin.qq.com/cgi-bin/service/get_login_info";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthWeChatEnterpriseThirdQrcodeRequest.class;
}
},
/**
* 企业微信网页登录
*/
WECHAT_ENTERPRISE_WEB {
@Override
public String authorize() {
return "https://open.weixin.qq.com/connect/oauth2/authorize";
}
@Override
public String accessToken() {
return "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
}
@Override
public String userInfo() {
return "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthWeChatEnterpriseWebRequest.class;
}
},
/**
* 酷家乐
*
* @since 1.11.0
*/
KUJIALE {
@Override
public String authorize() {
return "https://oauth.kujiale.com/oauth2/show";
}
@Override
public String accessToken() {
return "https://oauth.kujiale.com/oauth2/auth/token";
}
@Override
public String userInfo() {
return "https://oauth.kujiale.com/oauth2/openapi/user";
}
@Override
public String refresh() {
return "https://oauth.kujiale.com/oauth2/auth/token/refresh";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthKujialeRequest.class;
}
},
/**
* Gitlab
*
* @since 1.11.0
*/
GITLAB {
@Override
public String authorize() {
return "https://gitlab.com/oauth/authorize";
}
@Override
public String accessToken() {
return "https://gitlab.com/oauth/token";
}
@Override
public String userInfo() {
return "https://gitlab.com/api/v4/user";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthGitlabRequest.class;
}
},
/**
* 美团
*
* @since 1.12.0
*/
MEITUAN {
@Override
public String authorize() {
return "https://openapi.waimai.meituan.com/oauth/authorize";
}
@Override
public String accessToken() {
return "https://openapi.waimai.meituan.com/oauth/access_token";
}
@Override
public String userInfo() {
return "https://openapi.waimai.meituan.com/oauth/userinfo";
}
@Override
public String refresh() {
return "https://openapi.waimai.meituan.com/oauth/refresh_token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthMeituanRequest.class;
}
},
/**
* 饿了么
* <p>
* 注:集成的是正式环境,非沙箱环境
*
* @since 1.12.0
*/
ELEME {
@Override
public String authorize() {
return "https://open-api.shop.ele.me/authorize";
}
@Override
public String accessToken() {
return "https://open-api.shop.ele.me/token";
}
@Override
public String userInfo() {
return "https://open-api.shop.ele.me/api/v1/";
}
@Override
public String refresh() {
return "https://open-api.shop.ele.me/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthElemeRequest.class;
}
},
/**
* Twitter
*
* @since 1.13.0
*/
TWITTER {
@Override
public String authorize() {
return "https://api.twitter.com/oauth/authenticate";
}
@Override
public String accessToken() {
return "https://api.twitter.com/oauth/access_token";
}
@Override
public String userInfo() {
return "https://api.twitter.com/1.1/account/verify_credentials.json";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthTwitterRequest.class;
}
},
/**
* 飞书平台,企业自建应用授权登录,原逻辑由 beacon 集成于 1.14.0 版,但最新的飞书 api 已修改,并且飞书平台一直为 {@code Deprecated} 状态
* <p>
* 所以,最终修改该平台的实际发布版本为 1.15.9
*
* @since 1.15.9
*/
FEISHU {
@Override
public String authorize() {
return "https://open.feishu.cn/open-apis/authen/v1/index";
}
@Override
public String accessToken() {
return "https://open.feishu.cn/open-apis/authen/v1/access_token";
}
@Override
public String userInfo() {
return "https://open.feishu.cn/open-apis/authen/v1/user_info";
}
@Override
public String refresh() {
return "https://open.feishu.cn/open-apis/authen/v1/refresh_access_token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthFeishuRequest.class;
}
},
/**
* 京东
*
* @since 1.15.0
*/
JD {
@Override
public String authorize() {
return "https://open-oauth.jd.com/oauth2/to_login";
}
@Override
public String accessToken() {
return "https://open-oauth.jd.com/oauth2/access_token";
}
@Override
public String userInfo() {
return "https://api.jd.com/routerjson";
}
@Override
public String refresh() {
return "https://open-oauth.jd.com/oauth2/refresh_token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthJdRequest.class;
}
},
/**
* 阿里云
*/
ALIYUN {
@Override
public String authorize() {
return "https://signin.aliyun.com/oauth2/v1/auth";
}
@Override
public String accessToken() {
return "https://oauth.aliyun.com/v1/token";
}
@Override
public String userInfo() {
return "https://oauth.aliyun.com/v1/userinfo";
}
@Override
public String refresh() {
return "https://oauth.aliyun.com/v1/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthAliyunRequest.class;
}
},
/**
* 喜马拉雅
*/
XMLY {
@Override
public String authorize() {
return "https://api.ximalaya.com/oauth2/js/authorize";
}
@Override
public String accessToken() {
return "https://api.ximalaya.com/oauth2/v2/access_token";
}
@Override
public String userInfo() {
return "https://api.ximalaya.com/profile/user_info";
}
@Override
public String refresh() {
return "https://oauth.aliyun.com/v1/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthXmlyRequest.class;
}
},
/**
* Amazon
*
* @since 1.16.0
*/
AMAZON {
@Override
public String authorize() {
return "https://www.amazon.com/ap/oa";
}
@Override
public String accessToken() {
return "https://api.amazon.com/auth/o2/token";
}
@Override
public String userInfo() {
return "https://api.amazon.com/user/profile";
}
@Override
public String refresh() {
return "https://api.amazon.com/auth/o2/token";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthAmazonRequest.class;
}
},
/**
* Slack
*
* @since 1.16.0
*/
SLACK {
@Override
public String authorize() {
return "https://slack.com/oauth/v2/authorize";
}
/**
* 该 API 获取到的是 access token
*
* https://slack.com/api/oauth.token 获取到的是 workspace token
*
* @return String
*/
@Override
public String accessToken() {
return "https://slack.com/api/oauth.v2.access";
}
@Override
public String userInfo() {
return "https://slack.com/api/users.info";
}
@Override
public String revoke() {
return "https://slack.com/api/auth.revoke";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthSlackRequest.class;
}
},
/**
* line
*
* @since 1.16.0
*/
LINE {
@Override
public String authorize() {
return "https://access.line.me/oauth2/v2.1/authorize";
}
@Override
public String accessToken() {
return "https://api.line.me/oauth2/v2.1/token";
}
@Override
public String userInfo() {
return "https://api.line.me/v2/profile";
}
@Override
public String refresh() {
return "https://api.line.me/oauth2/v2.1/token";
}
@Override
public String revoke() {
return "https://api.line.me/oauth2/v2.1/revoke";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthLineRequest.class;
}
},
/**
* Okta,
* <p>
* 团队/组织的域名不同,此处通过配置动态组装
*
* @since 1.16.0
*/
OKTA {
@Override
public String authorize() {
return "https://%s.okta.com/oauth2/%s/v1/authorize";
}
@Override
public String accessToken() {
return "https://%s.okta.com/oauth2/%s/v1/token";
}
@Override
public String refresh() {
return "https://%s.okta.com/oauth2/%s/v1/token";
}
@Override
public String userInfo() {
return "https://%s.okta.com/oauth2/%s/v1/userinfo";
}
@Override
public String revoke() {
return "https://%s.okta.com/oauth2/%s/v1/revoke";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthOktaRequest.class;
}
},
/**
* 程序员客栈
*
* @since 1.16.2
*/
PROGINN {
@Override
public String authorize() {
return "https://www.proginn.com/oauth2/authorize";
}
@Override
public String accessToken() {
return "https://www.proginn.com/oauth2/access_token";
}
@Override
public String userInfo() {
return "https://www.proginn.com/openapi/user/basic_info";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthProginnRequest.class;
}
},
/**
* 爱发电 <a href="https://afdian.net/">爱发电</a>
*/
AFDIAN {
@Override
public String authorize() {
return "https://afdian.net/oauth2/authorize";
}
@Override
public String accessToken() {
return "https://afdian.net/api/oauth2/access_token";
}
@Override
public String userInfo() {
return "";
}
@Override
public Class<? extends AuthDefaultRequest> getTargetClass() {
return AuthProginnRequest.class;
}
}
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/config/AuthDefaultSource.java |
633 | package org.lab5;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.lab5.entity.Book;
import org.lab5.entity.Record;
import org.lab5.entity.queryCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.List;
public class normalUser {
SqlSession session;
normalUser() throws IOException {
//1.读取mybatis的核心配置文件(mybatis-config.xml)
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//2.通过配置信息获取一个SqlSessionFactory工厂对象
SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
//3.通过工厂获取一个SqlSession对象
session = fac.openSession();
}
private static final Logger logger = LoggerFactory.getLogger(normalUser.class);
public void borrowBook() throws IOException {
logger.info("""
please enter 1 or 2 . input 9 will exit\s
1 show books\s
2 borrow book
"""
);
String str = null;
BufferedReader databf = new BufferedReader(new InputStreamReader(System.in));
// 借书的实现:
// 如果有库存, 那 book update库存- 1, records 插入, isbn 来自输入, cid来自输入,Borrowtime是现在的时间
// due是40天, aid是输入。
//如果没有库存, 那么找到records, 找到最快的归还时间。
while ((str = databf.readLine()) != null) {
int com = Integer.parseInt(str);
// find Records cardnum -> isbn -> book. info
if (com == 1) {
logger.info("please input card id:");
Integer cid = Integer.parseInt(databf.readLine());
logger.info("showing all books...");
List<Record> recordlist = session.selectList("recordMapper.showRecords", cid);
for (Record r : recordlist) {
Book book = session.selectOne("bookMapper.showBooks", r.getISBN());
System.out.println(book);
}
} else {
// borrow book
Integer cardnum = Integer.parseInt(databf.readLine());
Integer aid = Integer.parseInt(databf.readLine());
logger.info("please input isdn:");
String isbn = databf.readLine();
logger.info("searching books...");
Book book = session.selectOne("bookMapper.showBooks", isbn);
Record record = new Record(isbn, cardnum, aid);
if (book.getInventory() > 0) {
session.update("bookMapper.borrowbook", isbn);
session.insert("recordMapper.insertOne", record);
session.commit();
logger.info("borrow book success!");
} else {
logger.error("This book doesn't have inventory!");
List<Record> recordlist = session.selectList("recordMapper.findNearestDue", isbn);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
logger.info("The nearest due is : "+sdf.format(recordlist.get(0).getDue()));
}
}
}
}
public void returnBook() throws IOException {
logger.info("""
please enter 1 or 2 . input 9 will exit\s
1 show books\s
2 return book
"""
);
String str = null;
BufferedReader databf = new BufferedReader(new InputStreamReader(System.in));
// 还书的实现:
while ((str = databf.readLine()) != null) {
int com = Integer.parseInt(str);
if (com == 1) {
logger.info("please input card id:");
Integer cid = Integer.parseInt(databf.readLine());
logger.info("showing all books...");
List<Record> recordlist = session.selectList("recordMapper.showRecords", cid);
for (Record r : recordlist) {
Book book = session.selectOne("bookMapper.showBooks", r.getISBN());
System.out.println(book);
}
} else {
// return book
Integer cardnum = Integer.parseInt(databf.readLine());
Integer aid = Integer.parseInt(databf.readLine());
Integer cid = 2;
logger.info("please input isdn:");
String isbn = databf.readLine();
logger.info("searching books...");
List<Record> recordlist = session.selectList("recordMapper.showRecords", cid);
boolean flag = false;
for (Record r : recordlist) {
if (r.getISBN().equals(isbn)) {
session.update("bookMapper.returnbook", isbn);
session.delete("recordMapper.deleteOne", r);
session.commit();
logger.info("return book success!");
flag = true;
break;
}
}
if (flag == false)
logger.error("This book isn't borrowed! ");
}
}
}
public void queryBook() throws IOException {
System.out.print("""
please enter 8 parameters . input 9 will exit\s
1 category\s
2 title\s
3 publisher\s
4 pub year1\s
5 pub year2\s
6 author\s
7 price1\s
8 price2\s
"""
);
String str = null;
BufferedReader databf = new BufferedReader(new InputStreamReader(System.in));
logger.info("please enter attribute");
String sortattr = databf.readLine();
while ((str = databf.readLine()) != null) {
String[] temp = str.split(",");
//(书号,类别,书名,出版社,年份,作者,价格,数量)
String ISBN = temp[0].trim().equals("") ? null : temp[0].trim();
String Category = temp[1].trim().equals("") ? null : temp[1].trim();
String Title = temp[2].trim().equals("") ? null : temp[2].trim();
String Publisher = temp[3].trim().equals("") ? null : temp[3].trim();
Integer Year = Integer.parseInt(temp[4].trim());
Integer Year2 = Integer.parseInt(temp[5].trim());
String Author = temp[6].trim().equals("") ? null : temp[6].trim();
Double Price = temp[7].trim().equals("") ? null : Double.parseDouble(temp[7].trim());
Double Price2 = Double.parseDouble(temp[8].trim());
queryCondition query = new queryCondition(ISBN, Category, Title, Publisher, Year, Author, Price, Price2, Year2);
List<Book> list = session.selectList("bookMapper.findBooks", query);
switch (sortattr) {
case "Category":
list.sort(Comparator.comparing(Book::getCategory));
break;
case "Title":
list.sort(Comparator.comparing(Book::getTitle));
break;
case "Year":
list.sort(Comparator.comparing(Book::getYear));
break;
case "Author":
list.sort(Comparator.comparing(Book::getAuthor));
break;
case "Publisher":
list.sort(Comparator.comparing(Book::getPublisher));
break;
case "Price":
list.sort(Comparator.comparing(Book::getPrice));
break;
case "Total":
list.sort(Comparator.comparing(Book::getTotal));
break;
case "Inventory":
list.sort(Comparator.comparing(Book::getInventory));
break;
}
for (Book B : list) {
System.out.println(B);
}
}
}
}
| QSCTech/zju-icicles | 数据库系统原理/实验/lab/mybLab5/src/main/java/org/lab5/normalUser.java |
634 | package cn.hutool.poi.excel.sax;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.DependencyException;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelDateUtil;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import cn.hutool.poi.exceptions.POIException;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.record.CellValueRecordInterface;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.util.XMLHelper;
import org.apache.poi.xssf.model.SharedStrings;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
/**
* Sax方式读取Excel相关工具类
*
* @author looly
*/
public class ExcelSaxUtil {
// 填充字符串
public static final char CELL_FILL_CHAR = '@';
// 列的最大位数
public static final int MAX_CELL_BIT = 3;
/**
* 创建 {@link ExcelSaxReader}
*
* @param isXlsx 是否为xlsx格式(07格式)
* @param rowHandler 行处理器
* @return {@link ExcelSaxReader}
* @since 5.4.4
*/
public static ExcelSaxReader<?> createSaxReader(boolean isXlsx, RowHandler rowHandler) {
return isXlsx
? new Excel07SaxReader(rowHandler)
: new Excel03SaxReader(rowHandler);
}
/**
* 根据数据类型获取数据
*
* @param cellDataType 数据类型枚举
* @param value 数据值
* @param sharedStrings {@link SharedStrings}
* @param numFmtString 数字格式名
* @return 数据值
*/
public static Object getDataValue(CellDataType cellDataType, String value, SharedStrings sharedStrings, String numFmtString) {
if (null == value) {
return null;
}
if (null == cellDataType) {
cellDataType = CellDataType.NULL;
}
Object result;
switch (cellDataType) {
case BOOL:
result = (value.charAt(0) != '0');
break;
case ERROR:
result = StrUtil.format("\\\"ERROR: {} ", value);
break;
case FORMULA:
result = StrUtil.format("\"{}\"", value);
break;
case INLINESTR:
result = new XSSFRichTextString(value).toString();
break;
case SSTINDEX:
try {
final int index = Integer.parseInt(value);
result = sharedStrings.getItemAt(index).getString();
} catch (NumberFormatException e) {
result = value;
}
break;
case NUMBER:
try {
result = getNumberValue(value, numFmtString);
} catch (NumberFormatException e) {
result = value;
}
break;
case DATE:
try {
result = getDateValue(value);
} catch (Exception e) {
result = value;
}
break;
default:
result = value;
break;
}
return result;
}
/**
* 格式化数字或日期值
*
* @param value 值
* @param numFmtIndex 数字格式索引
* @param numFmtString 数字格式名
* @return 格式化后的值
*/
public static String formatCellContent(String value, int numFmtIndex, String numFmtString) {
if (null != numFmtString) {
try {
value = new DataFormatter().formatRawCellContents(Double.parseDouble(value), numFmtIndex, numFmtString);
} catch (NumberFormatException e) {
// ignore
}
}
return value;
}
/**
* 计算两个单元格之间的单元格数目(同一行)
*
* @param preRef 前一个单元格位置,例如A1
* @param ref 当前单元格位置,例如A8
* @return 同一行中两个单元格之间的空单元格数
*/
public static int countNullCell(String preRef, String ref) {
// excel2007最大行数是1048576,最大列数是16384,最后一列列名是XFD
// 数字代表列,去掉列信息
String preXfd = StrUtil.nullToDefault(preRef, "@").replaceAll("\\d+", "");
String xfd = StrUtil.nullToDefault(ref, "@").replaceAll("\\d+", "");
// A表示65,@表示64,如果A算作1,那@代表0
// 填充最大位数3
preXfd = StrUtil.fillBefore(preXfd, CELL_FILL_CHAR, MAX_CELL_BIT);
xfd = StrUtil.fillBefore(xfd, CELL_FILL_CHAR, MAX_CELL_BIT);
char[] preLetter = preXfd.toCharArray();
char[] letter = xfd.toCharArray();
// 用字母表示则最多三位,每26个字母进一位
int res = (letter[0] - preLetter[0]) * 26 * 26 + (letter[1] - preLetter[1]) * 26 + (letter[2] - preLetter[2]);
return res - 1;
}
/**
* 从Excel的XML文档中读取内容,并使用{@link ContentHandler}处理
*
* @param xmlDocStream Excel的XML文档流
* @param handler 文档内容处理接口,实现此接口用于回调处理数据
* @throws DependencyException 依赖异常
* @throws POIException POI异常,包装了SAXException
* @throws IORuntimeException IO异常,如流关闭或异常等
* @since 5.1.4
*/
public static void readFrom(InputStream xmlDocStream, ContentHandler handler) throws DependencyException, POIException, IORuntimeException {
XMLReader xmlReader;
try {
xmlReader = XMLHelper.newXMLReader();
} catch (SAXException | ParserConfigurationException e) {
if (e.getMessage().contains("org.apache.xerces.parsers.SAXParser")) {
throw new DependencyException(e, "You need to add 'xerces:xercesImpl' to your project and version >= 2.11.0");
} else {
throw new POIException(e);
}
}
xmlReader.setContentHandler(handler);
try {
xmlReader.parse(new InputSource(xmlDocStream));
} catch (IOException e) {
throw new IORuntimeException(e);
} catch (SAXException e) {
throw new POIException(e);
}
}
/**
* 判断数字Record中是否为日期格式
*
* @param cell 单元格记录
* @param formatListener {@link FormatTrackingHSSFListener}
* @return 是否为日期格式
* @since 5.4.8
*/
public static boolean isDateFormat(CellValueRecordInterface cell, FormatTrackingHSSFListener formatListener) {
final int formatIndex = formatListener.getFormatIndex(cell);
final String formatString = formatListener.getFormatString(cell);
return isDateFormat(formatIndex, formatString);
}
/**
* 判断日期格式
*
* @param formatIndex 格式索引,一般用于内建格式
* @param formatString 格式字符串
* @return 是否为日期格式
* @see ExcelDateUtil#isDateFormat(int, String)
* @since 5.5.3
*/
public static boolean isDateFormat(int formatIndex, String formatString) {
return ExcelDateUtil.isDateFormat(formatIndex, formatString);
}
/**
* 获取日期
*
* @param value 单元格值
* @return 日期
* @since 5.3.6
*/
public static DateTime getDateValue(String value) {
return getDateValue(Double.parseDouble(value));
}
/**
* 获取日期
*
* @param value 单元格值
* @return 日期
* @since 4.1.0
*/
public static DateTime getDateValue(double value) {
return DateUtil.date(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value, false));
}
/**
* 在Excel03 sax读取中获取日期或数字类型的结果值
*
* @param cell 记录单元格
* @param value 值
* @param formatListener {@link FormatTrackingHSSFListener}
* @return 值,可能为Date或Double或Long
* @since 5.5.0
*/
public static Object getNumberOrDateValue(CellValueRecordInterface cell, double value, FormatTrackingHSSFListener formatListener) {
if (isDateFormat(cell, formatListener)) {
// 可能为日期格式
return getDateValue(value);
}
return getNumberValue(value, formatListener.getFormatString(cell));
}
/**
* 获取数字类型值
*
* @param value 值
* @param numFmtString 格式
* @return 数字,可以是Double、Long
* @since 4.1.0
*/
private static Number getNumberValue(String value, String numFmtString) {
if (StrUtil.isBlank(value)) {
return null;
}
return getNumberValue(Double.parseDouble(value), numFmtString);
}
/**
* 获取数字类型值,除非格式中明确数字保留小数,否则无小数情况下按照long返回
*
* @param numValue 值
* @param numFmtString 格式
* @return 数字,可以是Double、Long
* @since 5.5.3
*/
private static Number getNumberValue(double numValue, String numFmtString) {
// 普通数字
if (null != numFmtString && false == StrUtil.contains(numFmtString, CharUtil.DOT)) {
final long longPart = (long) numValue;
//noinspection RedundantIfStatement
if (longPart == numValue) {
// 对于无小数部分的数字类型,转为Long
return longPart;
}
}
return numValue;
}
}
| dromara/hutool | hutool-poi/src/main/java/cn/hutool/poi/excel/sax/ExcelSaxUtil.java |
638 | E
有序, 假设有这样的数字:target.
target 左边的数字,一定不比index大,target右边的数字,一定比index大。
这样可以binary search.O(logn)
```
/*
来自网上uber面经:给一个有序数组(不含重复),返回任意一个数字,这个数字的值和它的数组下标相等
可能的follow up:
1. 如果含有重复数字怎么办?
如果有序,也没问题,还是binary search
2. 另一种follow up:找这样数字的边界.
如果存在,那么和index match的一定在一块.
找到任何一个candiate, 找边界,也可以binary search,只是match的condition不同罢了。
*/
//Binary search.
import java.io.*;
import java.util.*;
class Solution {
public int indexMatch(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start)/2;
if (nums[mid] == mid) {
return mid;
} else if (nums[mid] < mid) {
start = mid;
} else {//nums[mid] > mid
end = mid;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println("START");
int[] input = {-1, 0, 1, 3, 5, 8, 9};//return 3
Solution sol = new Solution();
int rst = sol.indexMatch(input);
System.out.println(rst);
}
}
``` | awangdev/leet-code | Java/IndexMatch.java |
639 | package com.xkcoding.zookeeper.annotation;
import java.lang.annotation.*;
/**
* <p>
* 分布式锁动态key注解,配置之后key的值会动态获取参数内容
* </p>
*
* @author yangkai.shen
* @date Created in 2018-12-27 14:17
*/
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LockKeyParam {
/**
* 如果动态key在user对象中,那么就需要设置fields的值为user对象中的属性名可以为多个,基本类型则不需要设置该值
* <p>例1:public void count(@LockKeyParam({"id"}) User user)
* <p>例2:public void count(@LockKeyParam({"id","userName"}) User user)
* <p>例3:public void count(@LockKeyParam String userId)
*/
String[] fields() default {};
}
| xkcoding/spring-boot-demo | demo-zookeeper/src/main/java/com/xkcoding/zookeeper/annotation/LockKeyParam.java |
642 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.demo.okrx2;
import android.content.Intent;
import com.lzy.demo.base.MainFragment;
import com.lzy.demo.model.ItemModel;
import java.util.List;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2017/6/9
* 描 述:
* 修订历史:
* ================================================
*/
public class OkRx2Fragment extends MainFragment {
@Override
public void fillData(List<ItemModel> items) {
items.add(new ItemModel("基本请求", //
"1.支持GET,HEAD,OPTIONS,POST,PUT,DELETE, PATCH, TRACE 8种请求方式\n" +//
"2.自动解析JSONObject对象\n" +//
"3.自动解析JSONArray对象\n" +//
"4.上传string文本\n" +//
"5.上传json数据"));
items.add(new ItemModel("rx使用缓存", "okrx的缓存与okgo的缓存一模一样,详细看okrx的文档介绍"));
items.add(new ItemModel("统一管理请求", "如果你熟悉Retrofit,那么和Retrofit一样,可以使用一个Api类管理所有的请求"));
items.add(new ItemModel("请求图片", "请求服务器返回bitmap对象"));
items.add(new ItemModel("文件上传", "支持参数和文件一起上传,并回调上传进度"));
items.add(new ItemModel("文件下载", "支持下载进度回调"));
}
@Override
public void onItemClick(int position) {
if (position == 0) startActivity(new Intent(context, RxCommonActivity.class));
if (position == 1) startActivity(new Intent(context, RxCacheActivity.class));
if (position == 2) startActivity(new Intent(context, RxRetrofitActivity.class));
if (position == 3) startActivity(new Intent(context, RxBitmapActivity.class));
if (position == 4) startActivity(new Intent(context, RxFormUploadActivity.class));
if (position == 5) startActivity(new Intent(context, RxFileDownloadActivity.class));
}
}
| jeasonlzy/okhttp-OkGo | demo/src/main/java/com/lzy/demo/okrx2/OkRx2Fragment.java |
643 | package com.blankj.bus;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.AdviceAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/09
* desc :
* </pre>
*/
public class BusClassVisitor extends ClassVisitor {
private Map<String, List<BusInfo>> mBusMap;
private String className;
private BusInfo busInfo;
private String tag;
private String funParamDesc;
private String mBusUtilsClass;
private boolean isStartVisitParams;
public BusClassVisitor(ClassVisitor classVisitor, Map<String, List<BusInfo>> busMap, String busUtilsClass) {
super(Opcodes.ASM5, classVisitor);
mBusMap = busMap;
mBusUtilsClass = busUtilsClass.replace(".", "/");
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
className = name.replace("/", ".");
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public MethodVisitor visitMethod(int access, String funName, String desc, String signature, String[] exceptions) {
if (cv == null) return null;
MethodVisitor mv = cv.visitMethod(access, funName, desc, signature, exceptions);
busInfo = null;
isStartVisitParams = false;
mv = new AdviceAdapter(Opcodes.ASM5, mv, access, funName, desc) {
@Override
public AnnotationVisitor visitAnnotation(String desc1, boolean visible) {
final AnnotationVisitor av = super.visitAnnotation(desc1, visible);
if (("L" + mBusUtilsClass + "$Bus;").equals(desc1)) {
busInfo = new BusInfo(className, funName);
funParamDesc = desc.substring(1, desc.indexOf(")"));
return new AnnotationVisitor(Opcodes.ASM5, av) {
@Override
public void visit(String name, Object value) {// 可获取注解的值
super.visit(name, value);
if ("tag".equals(name)) {
tag = (String) value;
} else if ("sticky".equals(name) && (Boolean) value) {
busInfo.sticky = true;
} else if ("priority".equals(name)) {
busInfo.priority = (int) value;
}
}
@Override
public void visitEnum(String name, String desc, String value) {
super.visitEnum(name, desc, value);
if ("threadMode".equals(name)) {
busInfo.threadMode = value;
}
}
};
}
return av;
}
@Override
public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
super.visitLocalVariable(name, desc, signature, start, end, index);// 获取方法参数信息
if (busInfo != null && !funParamDesc.equals("")) {
if (!isStartVisitParams && index != 0) {
return;
}
isStartVisitParams = true;
if ("this".equals(name)) {
return;
}
funParamDesc = funParamDesc.substring(desc.length());// 每次去除参数直到为 "",那么之后的就不是参数了
busInfo.paramsInfo.add(new BusInfo.ParamsInfo(Type.getType(desc).getClassName(), name));
if (busInfo.isParamSizeNoMoreThanOne && busInfo.paramsInfo.size() > 1) {
busInfo.isParamSizeNoMoreThanOne = false;
}
}
}
@Override
public void visitEnd() {
super.visitEnd();
if (busInfo != null) {
List<BusInfo> infoList = mBusMap.get(tag);
if (infoList == null) {
infoList = new ArrayList<>();
mBusMap.put(tag, infoList);
}
infoList.add(busInfo);
}
}
};
return mv;
}
}
| Blankj/AndroidUtilCode | plugin/bus-gradle-plugin/src/main/java/com/blankj/bus/BusClassVisitor.java |
645 | package org.nutz.dao.sql;
import java.util.Map;
import org.nutz.dao.Condition;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.Record;
import org.nutz.dao.jdbc.ValueAdaptor;
/**
* 封装了自定义 SQL
*
* @author zozoh([email protected])
* @author wendal([email protected])
*/
public interface Sql extends DaoStatement {
/**
* 所谓"变量",就是当 Sql 对象转换成 Statement 对象前,预先被填充的占位符。
* <p>
* 这个集合允许你为 SQL 的变量占位符设值
*
* @return 变量集合
*/
VarSet vars();
/**
* sql.vars().set(name, value)的链式调用方式
* @param name 变量名称
* @param value 变量值
* @return 原Sql对象,用于链式调用
* @see #vars()
*/
Sql setVar(String name, Object value);
/**
* 批量设置vars
* @param vars 参数集合
* @return 原Sql对象,用于链式调用
* @see #params()
*/
Sql setVars(Map<String,Object> vars);
/**
* 所谓"参数",就是当 Sql 对象转换成 PreparedStatement 对象前,会被填充成 ? 的占位符
* <p>
* 集合是一个个的名值对,你设置了值的地方,会在执行时,被设置到 PreparedStatement中。<br>
* 这样省却了你一个一个计算 ? 位置的烦恼
*
* @return 参数集合
*/
VarSet params();
/**
* sql.params().set(name, value)的链式调用方式
* @param name 参数名称
* @param value 参数值
* @return 原Sql对象,用于链式调用
* @see #params()
*/
Sql setParam(String name, Object value);
/**
* 批量设置params
* @param params 参数集合
* @return 原Sql对象,用于链式调用
* @see #params()
*/
Sql setParams(Map<String,Object> params);
/**
* 手动为某个语句参数设置适配器。
* <p>
* 默认的,Sql 的实现类会自动根据你设置的值,自动为所有的参数设置适配器。<br>
* 但是,有些时候,你可能传入了 null 值或者其他的特殊对象,<br>
* 这里允许你主动为其设置一个适配器,这样你就有了终极手段最合理的适配你的参数对象
*
* @param name
* 对应参数的名称
* @param adaptor
* 适配器实例
*/
void setValueAdaptor(String name, ValueAdaptor adaptor);
/**
* @return 整个 SQL 的变量索引,你可以获得变量的个数和名称
*/
VarIndex varIndex();
/**
* @return 整个 SQL 的参数索引,你可以获得参数的个数和名称
*/
VarIndex paramIndex();
/**
* 将当前的参数列表存储,以便执行批处理
*/
void addBatch();
/**
* 清除所有的曾经设置过的参数
*/
void clearBatch();
/**
* 重写父接口返回值
*/
Sql setEntity(Entity<?> entity);
/**
* 当前 Statement 被执行完毕后,有可能会产生一个 ResultSet。 针对这个 ResultSet 你可以执行更多的操作。
* <p>
* 当然如果不是 SELECT 语句,那么你依然可以设置一个回调,<br>
* 当你的语句执行完毕后, 会调用它(Connection 不会被 commit),但是 ResultSet 参数会是 null
*
* @param callback
* 回调函数
* @return 自身
*/
Sql setCallback(SqlCallback callback);
/**
* 为 SQL 增加条件,SQL 必须有 '$condition' 变量
*
* @param cnd
* 条件
* @return 自身
*/
Sql setCondition(Condition cnd);
/**
* @return 一个新的和当前对象一样的对象。只是原来设置的变量和参数,需要你重新设置
*/
Sql duplicate();
/**
* 设置原始SQL,将重新解析里面的占位符
* @param sql
*/
void setSourceSql(String sql);
/**
* 获取原始SQL
*/
String getSourceSql();
/**
* 获取存储过程的出参
*/
Record getOutParams();
/**
* 修改原有的占位符(默认是$和@),并重新解析.仅作用于当前SQL对象
* @param param 参数占位符,默认是@
* @param var 变量占位符,默认是$
* @return 当前SQL对象
*/
Sql changePlaceholder(char param, char var);
Sql appendSourceSql(String ext);
}
| nutzam/nutz | src/org/nutz/dao/sql/Sql.java |
646 | package io.mycat.backend.jdbc;
import io.mycat.backend.datasource.PhysicalDBPool;
import io.mycat.backend.datasource.PhysicalDatasource;
import io.mycat.backend.heartbeat.MySQLHeartbeat;
import io.mycat.config.model.DataHostConfig;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import io.mycat.backend.heartbeat.DBHeartbeat;
import io.mycat.statistic.HeartbeatRecorder;
public class JDBCHeartbeat extends DBHeartbeat{
public static final Logger LOGGER = LoggerFactory.getLogger(JDBCHeartbeat.class);
private final ReentrantLock lock;
private final JDBCDatasource source;
private final boolean heartbeatnull;
private Long lastSendTime = System.currentTimeMillis();
private Long lastReciveTime = System.currentTimeMillis();
private final int maxRetryCount;
private Logger logger = LoggerFactory.getLogger(this.getClass());
public JDBCHeartbeat(JDBCDatasource source)
{
this.source = source;
lock = new ReentrantLock(false);
this.status = INIT_STATUS;
this.heartbeatSQL = source.getHostConfig().getHearbeatSQL().trim();
this.heartbeatnull= heartbeatSQL.length()==0;
this.maxRetryCount = source.getHostConfig().getMaxRetryCount();
}
@Override
public void start()
{
if (this.heartbeatnull){
stop();
return;
}
lock.lock();
try
{
isStop.compareAndSet(true, false);
this.status = DBHeartbeat.OK_STATUS;
} finally
{
lock.unlock();
}
}
@Override
public void stop()
{
lock.lock();
try
{
if (isStop.compareAndSet(false, true))
{
isChecking.set(false);
}
} finally
{
lock.unlock();
}
}
@Override
public String getLastActiveTime()
{
long t = lastReciveTime;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date(t));
}
@Override
public long getTimeout()
{
return 0;
}
@Override
public HeartbeatRecorder getRecorder() {
recorder.set(lastReciveTime - lastSendTime);
return recorder;
}
@Override
public void heartbeat()
{
if (isStop.get()) {
return;
}
lastSendTime = System.currentTimeMillis();
lock.lock();
try
{
isChecking.set(true);
try (Connection c = source.getConnection())
{
try (Statement s = c.createStatement())
{
s.execute(heartbeatSQL);
}
c.close();
}
setResult(OK_STATUS);
if(logger.isDebugEnabled()){
logger.debug("JDBCHeartBeat con query sql: "+heartbeatSQL);
}
} catch (Exception ex)
{
logger.error("JDBCHeartBeat error",ex);
// status = ERROR_STATUS;
setResult(ERROR_STATUS);
} finally
{
lock.unlock();
this.isChecking.set(false);
lastReciveTime = System.currentTimeMillis();
}
}
public void setResult(int result) {
switch (result) {
case OK_STATUS:
setOk();
break;
case ERROR_STATUS:
setError();
break;
case TIMEOUT_STATUS:
setTimeout();
break;
}
if (this.status != OK_STATUS) {
switchSourceIfNeed("heartbeat error");
}
}
private void setOk() {
switch (status) {
case DBHeartbeat.TIMEOUT_STATUS:
writeStatusMsg(source.getDbPool().getHostName(), source.getName() ,DBHeartbeat.INIT_STATUS);
this.status = DBHeartbeat.INIT_STATUS;
this.errorCount.set(0);
//前一个状态为超时 当前状态为正常状态 那就马上发送一个请求 来验证状态是否恢复为Ok
heartbeat();// timeout, heart beat again
break;
case DBHeartbeat.OK_STATUS:
this.errorCount.set(0);
break;
default:
writeStatusMsg(source.getDbPool().getHostName(), source.getName() ,DBHeartbeat.OK_STATUS);
this.status = OK_STATUS;
this.errorCount.set(0);;
}
}
//发生错误了,是否进行下一次心跳检测的策略 . 是否进行下一次心跳检测.
private void nextDector( int nextStatue) {
if (isStop.get()) {
writeStatusMsg(source.getDbPool().getHostName(), source.getName() ,DBHeartbeat.OK_STATUS);
this.status = nextStatue;
} else {
// should continues check error status
if(errorCount.get() < maxRetryCount) {
} else {
writeStatusMsg(source.getDbPool().getHostName(), source.getName() ,nextStatue);
this.status = nextStatue;
this.errorCount.set(0);
}
}
}
private void setError() {
errorCount.incrementAndGet() ;
nextDector( ERROR_STATUS);
}
private void setTimeout() {
errorCount.incrementAndGet() ;
nextDector( TIMEOUT_STATUS);
//status = DBHeartbeat.TIMEOUT_STATUS;
}
/**
* switch data source
*/
private void switchSourceIfNeed(String reason) {
int switchType = source.getHostConfig().getSwitchType();
String notSwitch = source.getHostConfig().getNotSwitch();
if (notSwitch.equals(DataHostConfig.FOVER_NOT_SWITCH_DS)
|| switchType == DataHostConfig.NOT_SWITCH_DS) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("not switch datasource ,for switchType is "
+ DataHostConfig.NOT_SWITCH_DS);
return;
}
return;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("to switchSourceIfNeed function 进行读节点转换 "
);
}
PhysicalDBPool pool = this.source.getDbPool();
int curDatasourceHB = pool.getSource().getHeartbeat().getStatus();
// read node can't switch ,only write node can switch
if (pool.getWriteType() == PhysicalDBPool.WRITE_ONLYONE_NODE
&& !source.isReadNode()
&& curDatasourceHB != DBHeartbeat.OK_STATUS
&& pool.getSources().length > 1) {
synchronized (pool) {
// try to see if need switch datasource
curDatasourceHB = pool.getSource().getHeartbeat().getStatus();
if (curDatasourceHB != DBHeartbeat.INIT_STATUS && curDatasourceHB != DBHeartbeat.OK_STATUS) {
int curIndex = pool.getActivedIndex();
int nextId = pool.next(curIndex);
PhysicalDatasource[] allWriteNodes = pool.getSources();
while (true) {
if (nextId == curIndex) {
break;
}
PhysicalDatasource theSource = allWriteNodes[nextId];
DBHeartbeat theSourceHB = theSource.getHeartbeat();
int theSourceHBStatus = theSourceHB.getStatus();
if (theSourceHBStatus == DBHeartbeat.OK_STATUS) {
if (switchType == DataHostConfig.SYN_STATUS_SWITCH_DS) {
if (Integer.valueOf(0).equals( theSourceHB.getSlaveBehindMaster())) {
LOGGER.info("try to switch datasource ,slave is synchronized to master " + theSource.getConfig());
pool.switchSourceOrVoted(nextId, true, reason);
break;
} else {
LOGGER.warn("ignored datasource ,slave is not synchronized to master , slave behind master :"
+ theSourceHB.getSlaveBehindMaster()
+ " " + theSource.getConfig());
}
} else {
// normal switch
LOGGER.info("try to switch datasource ,not checked slave synchronize status " + theSource.getConfig());
pool.switchSourceOrVoted(nextId, true, reason);
break;
}
}
nextId = pool.next(nextId);
}
}
}
}
}
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/backend/jdbc/JDBCHeartbeat.java |
647 | /*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 com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import apijson.JSON;
import apijson.JSONResponse;
import apijson.Log;
import apijson.NotNull;
import apijson.RequestMethod;
import apijson.SQL;
import apijson.StringUtil;
import apijson.orm.Join.On;
import apijson.orm.exception.NotExistException;
import apijson.orm.exception.UnsupportedDataTypeException;
import apijson.orm.model.Access;
import apijson.orm.model.AllColumn;
import apijson.orm.model.AllColumnComment;
import apijson.orm.model.AllTable;
import apijson.orm.model.AllTableComment;
import apijson.orm.model.Column;
import apijson.orm.model.Document;
import apijson.orm.model.ExtendedProperty;
import apijson.orm.model.Function;
import apijson.orm.model.PgAttribute;
import apijson.orm.model.PgClass;
import apijson.orm.model.Request;
import apijson.orm.model.SysColumn;
import apijson.orm.model.SysTable;
import apijson.orm.model.Table;
import apijson.orm.model.TestRecord;
import static apijson.JSONObject.KEY_CACHE;
import static apijson.JSONObject.KEY_CAST;
import static apijson.JSONObject.KEY_COLUMN;
import static apijson.JSONObject.KEY_COMBINE;
import static apijson.JSONObject.KEY_DATABASE;
import static apijson.JSONObject.KEY_DATASOURCE;
import static apijson.JSONObject.KEY_EXPLAIN;
import static apijson.JSONObject.KEY_FROM;
import static apijson.JSONObject.KEY_GROUP;
import static apijson.JSONObject.KEY_HAVING;
import static apijson.JSONObject.KEY_HAVING_AND;
import static apijson.JSONObject.KEY_ID;
import static apijson.JSONObject.KEY_JSON;
import static apijson.JSONObject.KEY_NULL;
import static apijson.JSONObject.KEY_ORDER;
import static apijson.JSONObject.KEY_KEY;
import static apijson.JSONObject.KEY_RAW;
import static apijson.JSONObject.KEY_ROLE;
import static apijson.JSONObject.KEY_SCHEMA;
import static apijson.JSONObject.KEY_USER_ID;
import static apijson.RequestMethod.DELETE;
import static apijson.RequestMethod.GET;
import static apijson.RequestMethod.POST;
import static apijson.RequestMethod.PUT;
import static apijson.JSONObject.KEY_METHOD;
import static apijson.SQL.AND;
import static apijson.SQL.NOT;
import static apijson.SQL.ON;
import static apijson.SQL.OR;
/**config sql for JSON Request
* @author Lemon
*/
public abstract class AbstractSQLConfig<T extends Object> implements SQLConfig<T> {
private static final String TAG = "AbstractSQLConfig";
/**
* 为 true 则兼容 5.0 之前 @having:"toId>0;avg(id)<100000" 默认 AND 连接,为 HAVING toId>0 AND avg(id)<100000;
* 否则按 5.0+ 新版默认 OR 连接,为 HAVING toId>0 OR avg(id)<100000,使用 @having& 或 @having:{ @combine: null } 时才用 AND 连接
*/
public static boolean IS_HAVING_DEFAULT_AND = false;
/**
* 为 true 则兼容 5.0 之前 @having:"toId>0" 这种不包含 SQL 函数的表达式;
* 否则按 5.0+ 新版不允许,可以用 @having:"(toId)>0" 替代
*/
public static boolean IS_HAVING_ALLOW_NOT_FUNCTION = false;
/**
* 开启 WITH AS 表达式(在支持这种语法的数据库及版本)来简化 SQL 和提升性能
*/
public static boolean ENABLE_WITH_AS = false;
/**
* 对指定的方法,忽略空字符串,不作为 GET 条件,PUT 值等。可取值 new RequestMethod[]{ RequestMethod.GET, RequestMethod.POST ... }
*/
public static List<RequestMethod> IGNORE_EMPTY_STRING_METHOD_LIST = null;
/**
* 对指定的方法,忽略空白字符串。即首尾 trim 去掉所有不可见字符后,仍然为空的,就忽略,不作为 GET 条件,PUT 值等。
* 可取值 new RequestMethod[]{ RequestMethod.GET, RequestMethod.POST ... }
*/
public static List<RequestMethod> IGNORE_BLANK_STRING_METHOD_LIST = null;
public static String KEY_DELETED_KEY = "deletedKey";
public static String KEY_DELETED_VALUE = "deletedValue";
public static String KEY_NOT_DELETED_VALUE = "notDeletedValue";
public static int MAX_HAVING_COUNT = 5;
public static int MAX_WHERE_COUNT = 10;
public static int MAX_COMBINE_DEPTH = 2;
public static int MAX_COMBINE_COUNT = 5;
public static int MAX_COMBINE_KEY_COUNT = 2;
public static float MAX_COMBINE_RATIO = 1.0f;
public static boolean ALLOW_MISSING_KEY_4_COMBINE = true;
public static String DEFAULT_DATABASE = DATABASE_MYSQL;
public static String DEFAULT_SCHEMA = "sys";
public static String PREFIX_DISTINCT = "DISTINCT ";
public static Pattern PATTERN_SCHEMA;
// * 和 / 不能同时出现,防止 /* */ 段注释! # 和 -- 不能出现,防止行注释! ; 不能出现,防止隔断SQL语句!空格不能出现,防止 CRUD,DROP,SHOW TABLES等语句!
public static Pattern PATTERN_RANGE;
public static Pattern PATTERN_FUNCTION;
/**
* 表名映射,隐藏真实表名,对安全要求很高的表可以这么做
*/
public static Map<String, String> TABLE_KEY_MAP;
/**
* 字段名映射,隐藏真实字段名,对安全要求很高的表可以这么做,另外可以配置 name_tag:(name,tag) 来实现多字段 IN,length_tag:length(tag) 来实现 SQL 函数复杂条件
*/
public static Map<String, String> COLUMN_KEY_MAP;
/**
* 允许批量增删改部分记录失败的表
*/
public static Map<String, String> ALLOW_PARTIAL_UPDATE_FAIL_TABLE_MAP;
public static List<String> CONFIG_TABLE_LIST;
public static List<String> DATABASE_LIST;
// 自定义原始 SQL 片段 Map<key, substring>:当 substring 为 null 时忽略;当 substring 为 "" 时整个 value 是 raw SQL;其它情况则只是 substring 这段为 raw SQL
public static Map<String, String> RAW_MAP;
// 允许调用的 SQL 函数:当 substring 为 null 时忽略;当 substring 为 "" 时整个 value 是 raw SQL;其它情况则只是 substring 这段为 raw SQL
public static Map<String, String> SQL_AGGREGATE_FUNCTION_MAP;
public static Map<String, String> SQL_FUNCTION_MAP;
static { // 凡是 SQL 边界符、分隔符、注释符 都不允许,例如 ' " ` ( ) ; # -- /**/ ,以免拼接 SQL 时被注入意外可执行指令
PATTERN_SCHEMA = Pattern.compile("^[A-Za-z0-9_-]+$");
PATTERN_RANGE = Pattern.compile("^[0-9%,!=\\<\\>/\\.\\+\\-\\*\\^]+$"); // ^[a-zA-Z0-9_*%!=<>(),"]+$ 导致 exists(select*from(Comment)) 通过!
// TODO 改成更好的正则,校验前面为单词,中间为操作符,后面为值
PATTERN_FUNCTION = Pattern.compile("^[A-Za-z0-9%,:_@&~`!=\\<\\>\\|\\[\\]\\{\\} /\\.\\+\\-\\*\\^\\?\\(\\)\\$]+$");
TABLE_KEY_MAP = new HashMap<>();
TABLE_KEY_MAP.put(Table.class.getSimpleName(), Table.TABLE_NAME);
TABLE_KEY_MAP.put(Column.class.getSimpleName(), Column.TABLE_NAME);
TABLE_KEY_MAP.put(PgClass.class.getSimpleName(), PgClass.TABLE_NAME);
TABLE_KEY_MAP.put(PgAttribute.class.getSimpleName(), PgAttribute.TABLE_NAME);
TABLE_KEY_MAP.put(SysTable.class.getSimpleName(), SysTable.TABLE_NAME);
TABLE_KEY_MAP.put(SysColumn.class.getSimpleName(), SysColumn.TABLE_NAME);
TABLE_KEY_MAP.put(ExtendedProperty.class.getSimpleName(), ExtendedProperty.TABLE_NAME);
TABLE_KEY_MAP.put(AllTable.class.getSimpleName(), AllTable.TABLE_NAME);
TABLE_KEY_MAP.put(AllColumn.class.getSimpleName(), AllColumn.TABLE_NAME);
TABLE_KEY_MAP.put(AllTableComment.class.getSimpleName(), AllTableComment.TABLE_NAME);
TABLE_KEY_MAP.put(AllColumnComment.class.getSimpleName(), AllColumnComment.TABLE_NAME);
ALLOW_PARTIAL_UPDATE_FAIL_TABLE_MAP = new HashMap<>();
CONFIG_TABLE_LIST = new ArrayList<>(); // Table, Column 等是系统表 AbstractVerifier.SYSTEM_ACCESS_MAP.keySet());
CONFIG_TABLE_LIST.add(Function.class.getSimpleName());
CONFIG_TABLE_LIST.add(Request.class.getSimpleName());
CONFIG_TABLE_LIST.add(Access.class.getSimpleName());
CONFIG_TABLE_LIST.add(Document.class.getSimpleName());
CONFIG_TABLE_LIST.add(TestRecord.class.getSimpleName());
DATABASE_LIST = new ArrayList<>();
DATABASE_LIST.add(DATABASE_MYSQL);
DATABASE_LIST.add(DATABASE_POSTGRESQL);
DATABASE_LIST.add(DATABASE_SQLSERVER);
DATABASE_LIST.add(DATABASE_ORACLE);
DATABASE_LIST.add(DATABASE_DB2);
DATABASE_LIST.add(DATABASE_MARIADB);
DATABASE_LIST.add(DATABASE_TIDB);
DATABASE_LIST.add(DATABASE_DAMENG);
DATABASE_LIST.add(DATABASE_KINGBASE);
DATABASE_LIST.add(DATABASE_ELASTICSEARCH);
DATABASE_LIST.add(DATABASE_CLICKHOUSE);
DATABASE_LIST.add(DATABASE_HIVE);
DATABASE_LIST.add(DATABASE_PRESTO);
DATABASE_LIST.add(DATABASE_TRINO);
DATABASE_LIST.add(DATABASE_MILVUS);
DATABASE_LIST.add(DATABASE_INFLUXDB);
DATABASE_LIST.add(DATABASE_TDENGINE);
DATABASE_LIST.add(DATABASE_SNOWFLAKE);
DATABASE_LIST.add(DATABASE_DATABRICKS);
DATABASE_LIST.add(DATABASE_REDIS);
DATABASE_LIST.add(DATABASE_MONGODB);
DATABASE_LIST.add(DATABASE_CASSANDRA);
DATABASE_LIST.add(DATABASE_KAFKA);
DATABASE_LIST.add(DATABASE_MQ);
RAW_MAP = new LinkedHashMap<>(); // 保证顺序,避免配置冲突等意外情况
RAW_MAP.put("+", "");
RAW_MAP.put("-", "");
RAW_MAP.put("*", "");
RAW_MAP.put("/", "");
RAW_MAP.put("=", "");
RAW_MAP.put("!=", "");
RAW_MAP.put(">", "");
RAW_MAP.put(">=", "");
RAW_MAP.put("<", "");
RAW_MAP.put("<=", "");
RAW_MAP.put("%", "");
RAW_MAP.put("(", "");
RAW_MAP.put(")", "");
RAW_MAP.put("&", ""); // 位运算
RAW_MAP.put("|", ""); // 位运算
RAW_MAP.put("^", ""); // 位运算
RAW_MAP.put("~", ""); // 位运算
RAW_MAP.put("&=", ""); // 位运算
RAW_MAP.put("|=", ""); // 位运算
RAW_MAP.put("~=", ""); // 位运算
RAW_MAP.put(">>", ""); // 位运算
RAW_MAP.put("<<", ""); // 位运算
// MySQL 关键字
RAW_MAP.put("AS", "");
RAW_MAP.put("IS NOT NULL", "");
RAW_MAP.put("IS NULL", "");
RAW_MAP.put("IS", "");
RAW_MAP.put("NULL", "");
RAW_MAP.put("AND", "");
RAW_MAP.put("OR", "");
RAW_MAP.put("NOT", "");
RAW_MAP.put("VALUE", "");
RAW_MAP.put("DISTINCT", "");
RAW_MAP.put("CASE", "");
RAW_MAP.put("WHEN", "");
RAW_MAP.put("THEN", "");
RAW_MAP.put("ELSE", "");
RAW_MAP.put("END", "");
//时间
RAW_MAP.put("now()", "");
RAW_MAP.put("DATE", "");
RAW_MAP.put("TIME", "");
RAW_MAP.put("DATETIME", "");
RAW_MAP.put("TIMESTAMP", "");
RAW_MAP.put("DateTime", "");
RAW_MAP.put("SECOND", "");
RAW_MAP.put("MINUTE", "");
RAW_MAP.put("HOUR", "");
RAW_MAP.put("DAY", "");
RAW_MAP.put("WEEK", "");
RAW_MAP.put("MONTH", "");
RAW_MAP.put("QUARTER", "");
RAW_MAP.put("YEAR", "");
// RAW_MAP.put("json", "");
// RAW_MAP.put("unit", "");
//MYSQL 数据类型 BINARY,CHAR,DATETIME,TIME,DECIMAL,SIGNED,UNSIGNED
RAW_MAP.put("BINARY", "");
RAW_MAP.put("SIGNED", "");
RAW_MAP.put("DECIMAL", "");
RAW_MAP.put("DOUBLE", "");
RAW_MAP.put("FLOAT", "");
RAW_MAP.put("BOOLEAN", "");
RAW_MAP.put("ENUM", "");
RAW_MAP.put("SET", "");
RAW_MAP.put("POINT", "");
RAW_MAP.put("BLOB", "");
RAW_MAP.put("LONGBLOB", "");
RAW_MAP.put("BINARY", "");
RAW_MAP.put("UNSIGNED", "");
RAW_MAP.put("BIT", "");
RAW_MAP.put("TINYINT", "");
RAW_MAP.put("SMALLINT", "");
RAW_MAP.put("INT", "");
RAW_MAP.put("BIGINT", "");
RAW_MAP.put("CHAR", "");
RAW_MAP.put("VARCHAR", "");
RAW_MAP.put("TEXT", "");
RAW_MAP.put("LONGTEXT", "");
RAW_MAP.put("JSON", "");
//窗口函数关键字
RAW_MAP.put("OVER", "");
RAW_MAP.put("INTERVAL", "");
RAW_MAP.put("GROUP BY", ""); // 往前
RAW_MAP.put("GROUP", ""); // 往前
RAW_MAP.put("ORDER BY", ""); // 往前
RAW_MAP.put("ORDER", "");
RAW_MAP.put("PARTITION BY", ""); // 往前
RAW_MAP.put("PARTITION", ""); // 往前
RAW_MAP.put("BY", "");
RAW_MAP.put("DESC", "");
RAW_MAP.put("ASC", "");
RAW_MAP.put("FOLLOWING", ""); // 往后
RAW_MAP.put("BETWEEN", "");
RAW_MAP.put("AND", "");
RAW_MAP.put("ROWS", "");
RAW_MAP.put("AGAINST", "");
RAW_MAP.put("IN NATURAL LANGUAGE MODE", "");
RAW_MAP.put("IN BOOLEAN MODE", "");
RAW_MAP.put("IN", "");
RAW_MAP.put("BOOLEAN", "");
RAW_MAP.put("NATURAL", "");
RAW_MAP.put("LANGUAGE", "");
RAW_MAP.put("MODE", "");
SQL_AGGREGATE_FUNCTION_MAP = new LinkedHashMap<>(); // 保证顺序,避免配置冲突等意外情况
SQL_AGGREGATE_FUNCTION_MAP.put("max", ""); // MAX(a, b, c ...) 最大值
SQL_AGGREGATE_FUNCTION_MAP.put("min", ""); // MIN(a, b, c ...) 最小值
SQL_AGGREGATE_FUNCTION_MAP.put("avg", ""); // AVG(a, b, c ...) 平均值
SQL_AGGREGATE_FUNCTION_MAP.put("count", ""); // COUNT(a, b, c ...) 总数
SQL_AGGREGATE_FUNCTION_MAP.put("sum", ""); // SUM(a, b, c ...) 总和
SQL_FUNCTION_MAP = new LinkedHashMap<>(); // 保证顺序,避免配置冲突等意外情况
// 窗口函数
SQL_FUNCTION_MAP.put("rank", ""); // RANK(a, b, c ...) 得到数据项在分组中的排名,排名相等的时候会留下空位
SQL_FUNCTION_MAP.put("dense_rank", ""); // DENSE_RANK(a, b, c ...) 得到数据项在分组中的排名,排名相等的时候不会留下空位
SQL_FUNCTION_MAP.put("row_num", ""); // ROW_NUM() 按照分组中的顺序生成序列,不存在重复的序列
SQL_FUNCTION_MAP.put("row_number", ""); // ROW_NUMBER() 按照分组中的顺序生成序列,不存在重复的序列
SQL_FUNCTION_MAP.put("ntile", ""); // NTILE(a, b, c ...) 用于将分组数据按照顺序切分成N片,返回当前切片值,不支持ROWS_BETWEE
SQL_FUNCTION_MAP.put("first_value", ""); // FIRST_VALUE() 取分组排序后,截止到当前行,分组内第一个值
SQL_FUNCTION_MAP.put("last_value", ""); // LAST_VALUE() 取分组排序后,截止到当前行,分组内的最后一个值
SQL_FUNCTION_MAP.put("lag", ""); // LAG() 统计窗口内往上第n行值。第一个参数为列名,第二个参数为往上第n行(可选,默认为1),第三个参数为默认值(当往上第n行为NULL时候,取默认值,如不指定,则为NULL)
SQL_FUNCTION_MAP.put("lead", ""); // LEAD() 统计窗口内往下第n行值。第一个参数为列名,第二个参数为往下第n行(可选,默认为1),第三个参数为默认值(当往下第n行为NULL时候,取默认值,如不指定,则为NULL)
SQL_FUNCTION_MAP.put("cume_dist", ""); // CUME_DIST() 返回(小于等于当前行值的行数)/(当前分组内的总行数)
SQL_FUNCTION_MAP.put("percent_rank", ""); // PERCENT_RANK(a, b, c ...) 返回(组内当前行的rank值-1)/(分组内做总行数-1)
// MySQL 字符串函数
SQL_FUNCTION_MAP.put("ascii", ""); // ASCII(s) 返回字符串 s 的第一个字符的 ASCII 码。
SQL_FUNCTION_MAP.put("char_length", ""); // CHAR_LENGTH(s) 返回字符串 s 的字符数
SQL_FUNCTION_MAP.put("character_length", ""); // CHARACTER_LENGTH(s) 返回字符串 s 的字符数
SQL_FUNCTION_MAP.put("concat", ""); // CONCAT(s1, s2...sn) 字符串 s1,s2 等多个字符串合并为一个字符串
SQL_FUNCTION_MAP.put("concat_ws", ""); // CONCAT_WS(x, s1, s2...sn) 同 CONCAT(s1, s2 ...) 函数,但是每个字符串之间要加上 x,x 可以是分隔符
SQL_FUNCTION_MAP.put("field", ""); // FIELD(s, s1, s2...) 返回第一个字符串 s 在字符串列表 (s1, s2...)中的位置
SQL_FUNCTION_MAP.put("find_in_set", ""); // FIND_IN_SET(s1, s2) 返回在字符串s2中与s1匹配的字符串的位置
SQL_FUNCTION_MAP.put("format", ""); // FORMAT(x, n) 函数可以将数字 x 进行格式化 "#,###.##", 将 x 保留到小数点后 n 位,最后一位四舍五入。
SQL_FUNCTION_MAP.put("insert", ""); // INSERT(s1, x, len, s2) 字符串 s2 替换 s1 的 x 位置开始长度为 len 的字符串
SQL_FUNCTION_MAP.put("locate", ""); // LOCATE(s1, s) 从字符串 s 中获取 s1 的开始位置
SQL_FUNCTION_MAP.put("lcase", ""); // LCASE(s) 将字符串 s 的所有字母变成小写字母
SQL_FUNCTION_MAP.put("left", ""); // LEFT(s, n) 返回字符串 s 的前 n 个字符
SQL_FUNCTION_MAP.put("length", ""); // LENGTH(s) 返回字符串 s 的字符数
SQL_FUNCTION_MAP.put("lower", ""); // LOWER(s) 将字符串 s 的所有字母变成小写字母
SQL_FUNCTION_MAP.put("lpad", ""); // LPAD(s1, len, s2) 在字符串 s1 的开始处填充字符串 s2,使字符串长度达到 len
SQL_FUNCTION_MAP.put("ltrim", ""); // LTRIM(s) 去掉字符串 s 开始处的空格
SQL_FUNCTION_MAP.put("mid", ""); // MID(s, n, len) 从字符串 s 的 n 位置截取长度为 len 的子字符串,同 SUBSTRING(s, n, len)
SQL_FUNCTION_MAP.put("position", ""); // POSITION(s, s1); 从字符串 s 中获取 s1 的开始位置
SQL_FUNCTION_MAP.put("repeat", ""); // REPEAT(s, n) 将字符串 s 重复 n 次
SQL_FUNCTION_MAP.put("replace", ""); // REPLACE(s, s1, s2) 将字符串 s2 替代字符串 s 中的字符串 s1
SQL_FUNCTION_MAP.put("reverse", ""); // REVERSE(s); // ) 将字符串s的顺序反过来
SQL_FUNCTION_MAP.put("right", ""); // RIGHT(s, n) 返回字符串 s 的后 n 个字符
SQL_FUNCTION_MAP.put("rpad", ""); // RPAD(s1, len, s2) 在字符串 s1 的结尾处添加字符串 s2,使字符串的长度达到 len
SQL_FUNCTION_MAP.put("rtrim", ""); // RTRIM", ""); // ) 去掉字符串 s 结尾处的空格
SQL_FUNCTION_MAP.put("space", ""); // SPACE(n) 返回 n 个空格
SQL_FUNCTION_MAP.put("strcmp", ""); // STRCMP(s1, s2) 比较字符串 s1 和 s2,如果 s1 与 s2 相等返回 0 ,如果 s1>s2 返回 1,如果 s1<s2 返回 -1
SQL_FUNCTION_MAP.put("substr", ""); // SUBSTR(s, start, length) 从字符串 s 的 start 位置截取长度为 length 的子字符串
SQL_FUNCTION_MAP.put("substring", ""); // STRING(s, start, length)) 从字符串 s 的 start 位置截取长度为 length 的子字符串
SQL_FUNCTION_MAP.put("substring_index", ""); // SUBSTRING_INDEX(s, delimiter, number) 返回从字符串 s 的第 number 个出现的分隔符 delimiter 之后的子串。
SQL_FUNCTION_MAP.put("trim", ""); // TRIM(s) 去掉字符串 s 开始和结尾处的空格
SQL_FUNCTION_MAP.put("ucase", ""); // UCASE(s) 将字符串转换为大写
SQL_FUNCTION_MAP.put("upper", ""); // UPPER(s) 将字符串转换为大写
// MySQL 数字函数
SQL_FUNCTION_MAP.put("abs", ""); // ABS(x) 返回 x 的绝对值
SQL_FUNCTION_MAP.put("acos", ""); // ACOS(x) 求 x 的反余弦值(参数是弧度)
SQL_FUNCTION_MAP.put("asin", ""); // ASIN(x) 求反正弦值(参数是弧度)
SQL_FUNCTION_MAP.put("atan", ""); // ATAN(x) 求反正切值(参数是弧度)
SQL_FUNCTION_MAP.put("atan2", ""); // ATAN2(n, m) 求反正切值(参数是弧度)
SQL_FUNCTION_MAP.put("avg", ""); // AVG(expression) 返回一个表达式的平均值,expression 是一个字段
SQL_FUNCTION_MAP.put("ceil", ""); // CEIL(x) 返回大于或等于 x 的最小整数
SQL_FUNCTION_MAP.put("ceiling", ""); // CEILING(x) 返回大于或等于 x 的最小整数
SQL_FUNCTION_MAP.put("cos", ""); // COS(x) 求余弦值(参数是弧度)
SQL_FUNCTION_MAP.put("cot", ""); // COT(x) 求余切值(参数是弧度)
SQL_FUNCTION_MAP.put("count", ""); // COUNT(expression) 返回查询的记录总数,expression 参数是一个字段或者 * 号
SQL_FUNCTION_MAP.put("degrees", ""); // DEGREES(x) 将弧度转换为角度
SQL_FUNCTION_MAP.put("div", ""); // n DIV m 整除,n 为被除数,m 为除数
SQL_FUNCTION_MAP.put("exp", ""); // EXP(x) 返回 e 的 x 次方
SQL_FUNCTION_MAP.put("floor", ""); // FLOOR(x) 返回小于或等于 x 的最大整数
SQL_FUNCTION_MAP.put("greatest", ""); // GREATEST(expr1, expr2, expr3, ...) 返回列表中的最大值
SQL_FUNCTION_MAP.put("least", ""); // LEAST(expr1, expr2, expr3, ...) 返回列表中的最小值
SQL_FUNCTION_MAP.put("ln", ""); // 2); LN 返回数字的自然对数,以 e 为底。
SQL_FUNCTION_MAP.put("log", ""); // LOG(x) 或 LOG(base, x) 返回自然对数(以 e 为底的对数),如果带有 base 参数,则 base 为指定带底数。
SQL_FUNCTION_MAP.put("log10", ""); // LOG10(x) 返回以 10 为底的对数
SQL_FUNCTION_MAP.put("log2", ""); // LOG2(x) 返回以 2 为底的对数
SQL_FUNCTION_MAP.put("max", ""); // MAX(expression) 返回字段 expression 中的最大值
SQL_FUNCTION_MAP.put("min", ""); // MIN(expression) 返回字段 expression 中的最小值
SQL_FUNCTION_MAP.put("mod", ""); // MOD(x,y) 返回 x 除以 y 以后的余数
SQL_FUNCTION_MAP.put("pi", ""); // PI() 返回圆周率(3.141593)
SQL_FUNCTION_MAP.put("pow", ""); // POW(x,y) 返回 x 的 y 次方
SQL_FUNCTION_MAP.put("power", ""); // POWER(x,y) 返回 x 的 y 次方
SQL_FUNCTION_MAP.put("radians", ""); // RADIANS(x) 将角度转换为弧度
SQL_FUNCTION_MAP.put("rand", ""); // RAND() 返回 0 到 1 的随机数
SQL_FUNCTION_MAP.put("round", ""); // ROUND(x) 返回离 x 最近的整数
SQL_FUNCTION_MAP.put("sign", ""); // SIGN(x) 返回 x 的符号,x 是负数、0、正数分别返回 -1、0 和 1
SQL_FUNCTION_MAP.put("sin", ""); // SIN(x) 求正弦值(参数是弧度)
SQL_FUNCTION_MAP.put("sqrt", ""); // SQRT(x) 返回x的平方根
SQL_FUNCTION_MAP.put("sum", ""); // SUM(expression) 返回指定字段的总和
SQL_FUNCTION_MAP.put("tan", ""); // TAN(x) 求正切值(参数是弧度)
SQL_FUNCTION_MAP.put("truncate", ""); // TRUNCATE(x,y) 返回数值 x 保留到小数点后 y 位的值(与 ROUND 最大的区别是不会进行四舍五入)
// MySQL 时间与日期函数
SQL_FUNCTION_MAP.put("adddate", ""); // ADDDATE(d,n) 计算起始日期 d 加上 n 天的日期
SQL_FUNCTION_MAP.put("addtime", ""); // ADDTIME(t,n) n 是一个时间表达式,时间 t 加上时间表达式 n
SQL_FUNCTION_MAP.put("curdate", ""); // CURDATE() 返回当前日期
SQL_FUNCTION_MAP.put("current_date", ""); // CURRENT_DATE() 返回当前日期
SQL_FUNCTION_MAP.put("current_time", ""); // CURRENT_TIME 返回当前时间
SQL_FUNCTION_MAP.put("current_timestamp", ""); // CURRENT_TIMESTAMP() 返回当前日期和时间
SQL_FUNCTION_MAP.put("curtime", ""); // CURTIME() 返回当前时间
SQL_FUNCTION_MAP.put("date", ""); // DATE() 从日期或日期时间表达式中提取日期值
SQL_FUNCTION_MAP.put("datediff", ""); // DATEDIFF(d1,d2) 计算日期 d1->d2 之间相隔的天数
SQL_FUNCTION_MAP.put("date_add", ""); // DATE_ADD(d,INTERVAL expr type) 计算起始日期 d 加上一个时间段后的日期
SQL_FUNCTION_MAP.put("date_format", ""); // DATE_FORMAT(d,f) 按表达式 f的要求显示日期 d
SQL_FUNCTION_MAP.put("date_sub", ""); // DATE_SUB(date,INTERVAL expr type) 函数从日期减去指定的时间间隔。
SQL_FUNCTION_MAP.put("day", ""); // DAY(d) 返回日期值 d 的日期部分
SQL_FUNCTION_MAP.put("dayname", ""); // DAYNAME(d) 返回日期 d 是星期几,如 Monday,Tuesday
SQL_FUNCTION_MAP.put("dayofmonth", ""); // DAYOFMONTH(d) 计算日期 d 是本月的第几天
SQL_FUNCTION_MAP.put("dayofweek", ""); // DAYOFWEEK(d) 日期 d 今天是星期几,1 星期日,2 星期一,以此类推
SQL_FUNCTION_MAP.put("dayofyear", ""); // DAYOFYEAR(d) 计算日期 d 是本年的第几天
SQL_FUNCTION_MAP.put("extract", ""); // EXTRACT(type FROM d) 从日期 d 中获取指定的值,type 指定返回的值。
SQL_FUNCTION_MAP.put("from_days", ""); // FROM_DAYS(n) 计算从 0000 年 1 月 1 日开始 n 天后的日期
SQL_FUNCTION_MAP.put("hour", ""); // 'HOUR(t) 返回 t 中的小时值
SQL_FUNCTION_MAP.put("last_day", ""); // LAST_DAY(d) 返回给给定日期的那一月份的最后一天
SQL_FUNCTION_MAP.put("localtime", ""); // LOCALTIME() 返回当前日期和时间
SQL_FUNCTION_MAP.put("localtimestamp", ""); // LOCALTIMESTAMP() 返回当前日期和时间
SQL_FUNCTION_MAP.put("makedate", ""); // MAKEDATE(year, day-of-year) 基于给定参数年份 year 和所在年中的天数序号 day-of-year 返回一个日期
SQL_FUNCTION_MAP.put("maketime", ""); // MAKETIME(hour, minute, second) 组合时间,参数分别为小时、分钟、秒
SQL_FUNCTION_MAP.put("microsecond", ""); // MICROSECOND(date) 返回日期参数所对应的微秒数
SQL_FUNCTION_MAP.put("minute", ""); // MINUTE(t) 返回 t 中的分钟值
SQL_FUNCTION_MAP.put("monthname", ""); // MONTHNAME(d) 返回日期当中的月份名称,如 November
SQL_FUNCTION_MAP.put("month", ""); // MONTH(d) 返回日期d中的月份值,1 到 12
SQL_FUNCTION_MAP.put("now", ""); // NOW() 返回当前日期和时间
SQL_FUNCTION_MAP.put("period_add", ""); // PERIOD_ADD(period, number) 为 年-月 组合日期添加一个时段
SQL_FUNCTION_MAP.put("period_diff", ""); // PERIOD_DIFF(period1, period2) 返回两个时段之间的月份差值
SQL_FUNCTION_MAP.put("quarter", ""); // QUARTER(d) 返回日期d是第几季节,返回 1 到 4
SQL_FUNCTION_MAP.put("second", ""); // SECOND(t) 返回 t 中的秒钟值
SQL_FUNCTION_MAP.put("sec_to_time", ""); // SEC_TO_TIME(sec, format); // ) 将以秒为单位的时间 s 转换为时分秒的格式
SQL_FUNCTION_MAP.put("str_to_date", ""); // STR_TO_DATE(string, format) 将字符串转变为日期
SQL_FUNCTION_MAP.put("subdate", ""); // SUBDATE(d,n) 日期 d 减去 n 天后的日期
SQL_FUNCTION_MAP.put("subtime", ""); // SUBTIME(t,n) 时间 t 减去 n 秒的时间
SQL_FUNCTION_MAP.put("sysdate", ""); // SYSDATE() 返回当前日期和时间
SQL_FUNCTION_MAP.put("time", ""); // TIME(expression) 提取传入表达式的时间部分
SQL_FUNCTION_MAP.put("time_format", ""); // TIME_FORMAT(t,f) 按表达式 f 的要求显示时间 t
SQL_FUNCTION_MAP.put("time_to_sec", ""); // TIME_TO_SEC(t) 将时间 t 转换为秒
SQL_FUNCTION_MAP.put("timediff", ""); // TIMEDIFF(time1, time2) 计算时间差值
SQL_FUNCTION_MAP.put("timestamp", ""); // TIMESTAMP(expression, interval) 单个参数时,函数返回日期或日期时间表达式;有2个参数时,将参数加和
SQL_FUNCTION_MAP.put("to_days", ""); // TO_DAYS(d) 计算日期 d 距离 0000 年 1 月 1 日的天数
SQL_FUNCTION_MAP.put("week", ""); // WEEK(d) 计算日期 d 是本年的第几个星期,范围是 0 到 53
SQL_FUNCTION_MAP.put("weekday", ""); // WEEKDAY(d) 日期 d 是星期几,0 表示星期一,1 表示星期二
SQL_FUNCTION_MAP.put("weekofyear", ""); // WEEKOFYEAR(d) 计算日期 d 是本年的第几个星期,范围是 0 到 53
SQL_FUNCTION_MAP.put("year", ""); // YEAR(d) 返回年份
SQL_FUNCTION_MAP.put("yearweek", ""); // YEARWEEK(date, mode) 返回年份及第几周(0到53),mode 中 0 表示周天,1表示周一,以此类推
SQL_FUNCTION_MAP.put("unix_timestamp", ""); // UNIX_TIMESTAMP(date) 获取UNIX时间戳函数,返回一个以 UNIX 时间戳为基础的无符号整数
SQL_FUNCTION_MAP.put("from_unixtime", ""); // FROM_UNIXTIME(date) 将 UNIX 时间戳转换为时间格式,与UNIX_TIMESTAMP互为反函数
// MYSQL JSON 函数
SQL_FUNCTION_MAP.put("json_append", ""); // JSON_APPEND(json_doc, path, val[, path, val] ...)) 插入JSON数组
SQL_FUNCTION_MAP.put("json_array", ""); // JSON_ARRAY(val1, val2...) 创建JSON数组
SQL_FUNCTION_MAP.put("json_array_append", ""); // JSON_ARRAY_APPEND(json_doc, val) 将数据附加到JSON文档
SQL_FUNCTION_MAP.put("json_array_insert", ""); // JSON_ARRAY_INSERT(json_doc, val) 插入JSON数组
SQL_FUNCTION_MAP.put("json_array_get", ""); // JSON_ARRAY_GET(json_doc, position) 从JSON数组提取指定位置的元素
SQL_FUNCTION_MAP.put("json_contains", ""); // JSON_CONTAINS(json_doc, val) JSON文档是否在路径中包含特定对象
SQL_FUNCTION_MAP.put("json_array_contains", ""); // JSON_ARRAY_CONTAINS(json_doc, path) JSON文档是否在路径中包含特定对象
SQL_FUNCTION_MAP.put("json_contains_path", ""); // JSON_CONTAINS_PATH(json_doc, path) JSON文档是否在路径中包含任何数据
SQL_FUNCTION_MAP.put("json_depth", ""); // JSON_DEPTH(json_doc) JSON文档的最大深度
SQL_FUNCTION_MAP.put("json_extract", ""); // JSON_EXTRACT(json_doc, path) 从JSON文档返回数据
SQL_FUNCTION_MAP.put("json_extract_scalar", ""); // JSON_EXTRACT_SCALAR(json_doc, path) 从JSON文档返回基础类型数据,例如 Boolean, Number, String
SQL_FUNCTION_MAP.put("json_insert", ""); // JSON_INSERT(json_doc, val) 将数据插入JSON文档
SQL_FUNCTION_MAP.put("json_keys", ""); // JSON_KEYS(json_doc[, path]) JSON文档中的键数组
SQL_FUNCTION_MAP.put("json_length", ""); // JSON_LENGTH(json_doc) JSON文档中的元素数
SQL_FUNCTION_MAP.put("json_size", ""); // JSON_SIZE(json_doc) JSON文档中的元素数
SQL_FUNCTION_MAP.put("json_array_length", ""); // JSON_ARRAY_LENGTH(json_doc) JSON文档中的元素数
SQL_FUNCTION_MAP.put("json_format", ""); // JSON_FORMAT(json_doc) 格式化 JSON
SQL_FUNCTION_MAP.put("json_parse", ""); // JSON_PARSE(val) 转换为 JSON
SQL_FUNCTION_MAP.put("json_merge", ""); // JSON_MERGE(json_doc1, json_doc2) (已弃用) 合并JSON文档,保留重复的键。JSON_MERGE_PRESERVE()的已弃用同义词
SQL_FUNCTION_MAP.put("json_merge_patch", ""); // JSON_MERGE_PATCH(json_doc1, json_doc2) 合并JSON文档,替换重复键的值
SQL_FUNCTION_MAP.put("json_merge_preserve", ""); // JSON_MERGE_PRESERVE(json_doc1, json_doc2) 合并JSON文档,保留重复的键
SQL_FUNCTION_MAP.put("json_object", ""); // JSON_OBJECT(key1, val1, key2, val2...) 创建JSON对象
SQL_FUNCTION_MAP.put("json_overlaps", ""); // JSON_OVERLAPS(json_doc1, json_doc2) (引入8.0.17) 比较两个JSON文档,如果它们具有相同的键值对或数组元素,则返回TRUE(1),否则返回FALSE(0)
SQL_FUNCTION_MAP.put("json_pretty", ""); // JSON_PRETTY(json_doc) 以易于阅读的格式打印JSON文档
SQL_FUNCTION_MAP.put("json_quote", ""); // JSON_QUOTE(json_doc1) 引用JSON文档
SQL_FUNCTION_MAP.put("json_remove", ""); // JSON_REMOVE(json_doc1, path) 从JSON文档中删除数据
SQL_FUNCTION_MAP.put("json_replace", ""); // JSON_REPLACE(json_doc1, val1, val2) 替换JSON文档中的值
SQL_FUNCTION_MAP.put("json_schema_valid", ""); // JSON_SCHEMA_VALID(json_doc) (引入8.0.17) 根据JSON模式验证JSON文档;如果文档针对架构进行验证,则返回TRUE / 1;否则,则返回FALSE / 0
SQL_FUNCTION_MAP.put("json_schema_validation_report", ""); // JSON_SCHEMA_VALIDATION_REPORT(json_doc, mode) (引入8.0.17) 根据JSON模式验证JSON文档;以JSON格式返回有关验证结果的报告,包括成功或失败以及失败原因
SQL_FUNCTION_MAP.put("json_search", ""); // JSON_SEARCH(json_doc, val) JSON文档中值的路径
SQL_FUNCTION_MAP.put("json_set", ""); // JSON_SET(json_doc, val) 将数据插入JSON文档
// SQL_FUNCTION_MAP.put("json_storage_free", ""); // JSON_STORAGE_FREE() 部分更新后,JSON列值的二进制表示形式中的可用空间
// SQL_FUNCTION_MAP.put("json_storage_size", ""); // JSON_STORAGE_SIZE() 用于存储JSON文档的二进制表示的空间
SQL_FUNCTION_MAP.put("json_table", ""); // JSON_TABLE() 从JSON表达式返回数据作为关系表
SQL_FUNCTION_MAP.put("json_type", ""); // JSON_TYPE(json_doc) JSON值类型
SQL_FUNCTION_MAP.put("json_unquote", ""); // JSON_UNQUOTE(json_doc) 取消引用JSON值
SQL_FUNCTION_MAP.put("json_valid", ""); // JSON_VALID(json_doc) JSON值是否有效
SQL_FUNCTION_MAP.put("json_arrayagg", ""); // JSON_ARRAYAGG(key) 将每个表达式转换为 JSON 值,然后返回一个包含这些 JSON 值的 JSON 数组
SQL_FUNCTION_MAP.put("json_objectagg", ""); // JSON_OBJECTAGG(key, val)) 将每个表达式转换为 JSON 值,然后返回一个包含这些 JSON 值的 JSON 对象
SQL_FUNCTION_MAP.put("is_json_scalar", ""); // IS_JSON_SCALAR(val)) 是否为JSON基本类型,例如 Boolean, Number, String
// MySQL 高级函数
// SQL_FUNCTION_MAP.put("bin", ""); // BIN(x) 返回 x 的二进制编码
// SQL_FUNCTION_MAP.put("binary", ""); // BINARY(s) 将字符串 s 转换为二进制字符串
SQL_FUNCTION_MAP.put("case", ""); // CASE 表示函数开始,END 表示函数结束。如果 condition1 成立,则返回 result1, 如果 condition2 成立,则返回 result2,当全部不成立则返回 result,而当有一个成立之后,后面的就不执行了。
SQL_FUNCTION_MAP.put("cast", ""); // CAST(x AS type) 转换数据类型
SQL_FUNCTION_MAP.put("coalesce", ""); // COALESCE(expr1, expr2, ...., expr_n) 返回参数中的第一个非空表达式(从左向右)
// SQL_FUNCTION_MAP.put("conv", ""); // CONV(x,f1,f2) 返回 f1 进制数变成 f2 进制数
// SQL_FUNCTION_MAP.put("convert", ""); // CONVERT(s, cs) 函数将字符串 s 的字符集变成 cs
SQL_FUNCTION_MAP.put("if", ""); // IF(expr,v1,v2) 如果表达式 expr 成立,返回结果 v1;否则,返回结果 v2。
SQL_FUNCTION_MAP.put("ifnull", ""); // IFNULL(v1,v2) 如果 v1 的值不为 NULL,则返回 v1,否则返回 v2。
SQL_FUNCTION_MAP.put("isnull", ""); // ISNULL(expression) 判断表达式是否为 NULL
SQL_FUNCTION_MAP.put("nullif", ""); // NULLIF(expr1, expr2) 比较两个字符串,如果字符串 expr1 与 expr2 相等 返回 NULL,否则返回 expr1
SQL_FUNCTION_MAP.put("group_concat", ""); // GROUP_CONCAT([DISTINCT], s1, s2...) 聚合拼接字符串
SQL_FUNCTION_MAP.put("match", ""); // MATCH (name,tag) AGAINST ('a b' IN NATURAL LANGUAGE MODE) 全文检索
SQL_FUNCTION_MAP.put("any_value", ""); // any_value(userId) 解决 ONLY_FULL_GROUP_BY 报错
// ClickHouse 字符串函数 注释的函数表示返回的格式暂时不支持,如:返回数组 ,同时包含因版本不同 clickhosue不支持的函数,版本
SQL_FUNCTION_MAP.put("empty", ""); // empty(s) 对于空字符串s返回1,对于非空字符串返回0
SQL_FUNCTION_MAP.put("notEmpty", ""); // notEmpty(s) 对于空字符串返回0,对于非空字符串返回1。
SQL_FUNCTION_MAP.put("lengthUTF8", ""); // 假定字符串以UTF-8编码组成的文本,返回此字符串的Unicode字符长度。如果传入的字符串不是UTF-8编码,则函数可能返回一个预期外的值
SQL_FUNCTION_MAP.put("lcase", ""); // 将字符串中的ASCII转换为小写
SQL_FUNCTION_MAP.put("ucase", ""); // 将字符串中的ASCII转换为大写。
SQL_FUNCTION_MAP.put("lowerUTF8", ""); // 将字符串转换为小写,函数假设字符串是以UTF-8编码文本的字符集。
SQL_FUNCTION_MAP.put("upperUTF8", ""); // 将字符串转换为大写,函数假设字符串是以UTF-8编码文本的字符集。
SQL_FUNCTION_MAP.put("isValidUTF8", ""); // 检查字符串是否为有效的UTF-8编码,是则返回1,否则返回0。
SQL_FUNCTION_MAP.put("toValidUTF8", ""); // 用(U+FFFD)字符替换无效的UTF-8字符。所有连续的无效字符都会被替换为一个替换字符。
SQL_FUNCTION_MAP.put("reverseUTF8", ""); // 以Unicode字符为单位反转UTF-8编码的字符串。
SQL_FUNCTION_MAP.put("concatAssumeInjective", ""); // concatAssumeInjective(s1, s2, …) 与concat相同,区别在于,你需要保证concat(s1, s2, s3) -> s4是单射的,它将用于GROUP BY的优化。
SQL_FUNCTION_MAP.put("substringUTF8", ""); // substringUTF8(s,offset,length)¶ 与’substring’相同,但其操作单位为Unicode字符,函数假设字符串是以UTF-8进行编码的文本。如果不是则可能返回一个预期外的结果(不会抛出异常)。
SQL_FUNCTION_MAP.put("appendTrailingCharIfAbsent", ""); // appendTrailingCharIfAbsent(s,c) 如果’s’字符串非空并且末尾不包含’c’字符,则将’c’字符附加到末尾
SQL_FUNCTION_MAP.put("convertCharset", ""); // convertCharset(s,from,to) 返回从’from’中的编码转换为’to’中的编码的字符串’s’。
SQL_FUNCTION_MAP.put("base64Encode", ""); // base64Encode(s) 将字符串’s’编码成base64
SQL_FUNCTION_MAP.put("base64Decode", ""); // base64Decode(s) 使用base64将字符串解码成原始字符串。如果失败则抛出异常。
SQL_FUNCTION_MAP.put("tryBase64Decode", ""); // tryBase64Decode(s) 使用base64将字符串解码成原始字符串。但如果出现错误,将返回空字符串。
SQL_FUNCTION_MAP.put("endsWith", ""); // endsWith(s,后缀) 返回是否以指定的后缀结尾。如果字符串以指定的后缀结束,则返回1,否则返回0。
SQL_FUNCTION_MAP.put("startsWith", ""); // startsWith(s,前缀) 返回是否以指定的前缀开头。如果字符串以指定的前缀开头,则返回1,否则返回0。
SQL_FUNCTION_MAP.put("trimLeft", ""); // trimLeft(s)返回一个字符串,用于删除左侧的空白字符。
SQL_FUNCTION_MAP.put("trimRight", ""); // trimRight(s) 返回一个字符串,用于删除右侧的空白字符。
SQL_FUNCTION_MAP.put("trimBoth", ""); // trimBoth(s),用于删除任一侧的空白字符
SQL_FUNCTION_MAP.put("extractAllGroups", ""); // extractAllGroups(text, regexp) 从正则表达式匹配的非重叠子字符串中提取所有组
// SQL_FUNCTION_MAP.put("leftPad", ""); // leftPad('string', 'length'[, 'pad_string']) 用空格或指定的字符串从左边填充当前字符串(如果需要,可以多次),直到得到的字符串达到给定的长度
// SQL_FUNCTION_MAP.put("leftPadUTF8", ""); // leftPadUTF8('string','length'[, 'pad_string']) 用空格或指定的字符串从左边填充当前字符串(如果需要,可以多次),直到得到的字符串达到给定的长度
// SQL_FUNCTION_MAP.put("rightPad", ""); // rightPad('string', 'length'[, 'pad_string']) 用空格或指定的字符串(如果需要,可以多次)从右边填充当前字符串,直到得到的字符串达到给定的长度
// SQL_FUNCTION_MAP.put("rightPadUTF8", "");// rightPadUTF8('string','length'[, 'pad_string']) 用空格或指定的字符串(如果需要,可以多次)从右边填充当前字符串,直到得到的字符串达到给定的长度。
SQL_FUNCTION_MAP.put("normalizeQuery", ""); // normalizeQuery(x) 用占位符替换文字、文字序列和复杂的别名。
SQL_FUNCTION_MAP.put("normalizedQueryHash", ""); // normalizedQueryHash(x) 为类似查询返回相同的64位散列值,但不包含文字值。有助于对查询日志进行分析
SQL_FUNCTION_MAP.put("positionUTF8", ""); // positionUTF8(s, needle[, start_pos]) 返回在字符串中找到的子字符串的位置(以Unicode点表示),从1开始。
SQL_FUNCTION_MAP.put("multiSearchFirstIndex", ""); // multiSearchFirstIndex(s, [needle1, needle2, …, needlen]) 返回字符串s中最左边的needlei的索引i(从1开始),否则返回0
SQL_FUNCTION_MAP.put("multiSearchAny", ""); // multiSearchAny(s, [needle1, needle2, …, needlen])如果至少有一个字符串needlei匹配字符串s,则返回1,否则返回0。
SQL_FUNCTION_MAP.put("match", ""); // match(s, pattern) 检查字符串是否与模式正则表达式匹配。re2正则表达式。re2正则表达式的语法比Perl正则表达式的语法更有局限性。
SQL_FUNCTION_MAP.put("multiMatchAny", ""); // multiMatchAny(s, [pattern1, pattern2, …, patternn]) 与match相同,但是如果没有匹配的正则表达式返回0,如果有匹配的模式返回1
SQL_FUNCTION_MAP.put("multiMatchAnyIndex", ""); // multiMatchAnyIndex(s, [pattern1, pattern2, …, patternn]) 与multiMatchAny相同,但返回与干堆匹配的任何索引
SQL_FUNCTION_MAP.put("extract", ""); // extract(s, pattern) 使用正则表达式提取字符串的片段
SQL_FUNCTION_MAP.put("extractAll", ""); // extractAll(s, pattern) 使用正则表达式提取字符串的所有片段
SQL_FUNCTION_MAP.put("like", ""); // like(s, pattern) 检查字符串是否与简单正则表达式匹配
SQL_FUNCTION_MAP.put("notLike", ""); // 和‘like’是一样的,但是是否定的
SQL_FUNCTION_MAP.put("countSubstrings", ""); // countSubstrings(s, needle[, start_pos])返回子字符串出现的次数
SQL_FUNCTION_MAP.put("countMatches", ""); // 返回干s中的正则表达式匹配数。countMatches(s, pattern)
SQL_FUNCTION_MAP.put("replaceOne", ""); // replaceOne(s, pattern, replacement)将' s '中的' pattern '子串的第一个出现替换为' replacement '子串。
SQL_FUNCTION_MAP.put("replaceAll", ""); // replaceAll(s, pattern, replacement)/用' replacement '子串替换' s '中所有出现的' pattern '子串
SQL_FUNCTION_MAP.put("replaceRegexpOne", ""); // replaceRegexpOne(s, pattern, replacement)使用' pattern '正则表达式进行替换
SQL_FUNCTION_MAP.put("replaceRegexpAll", ""); // replaceRegexpAll(s, pattern, replacement)
SQL_FUNCTION_MAP.put("regexpQuoteMeta", ""); // regexpQuoteMeta(s)该函数在字符串中某些预定义字符之前添加一个反斜杠
// clickhouse日期函数
SQL_FUNCTION_MAP.put("toYear", ""); // 将Date或DateTime转换为包含年份编号(AD)的UInt16类型的数字。
SQL_FUNCTION_MAP.put("toQuarter", ""); // 将Date或DateTime转换为包含季度编号的UInt8类型的数字。
SQL_FUNCTION_MAP.put("toMonth", ""); // Date或DateTime转换为包含月份编号(1-12)的UInt8类型的数字。
SQL_FUNCTION_MAP.put("toDayOfYear", ""); // 将Date或DateTime转换为包含一年中的某一天的编号的UInt16(1-366)类型的数字。
SQL_FUNCTION_MAP.put("toDayOfMonth", "");// 将Date或DateTime转换为包含一月中的某一天的编号的UInt8(1-31)类型的数字。
SQL_FUNCTION_MAP.put("toDayOfWeek", ""); // 将Date或DateTime转换为包含一周中的某一天的编号的UInt8(周一是1, 周日是7)类型的数字。
SQL_FUNCTION_MAP.put("toHour", ""); // 将DateTime转换为包含24小时制(0-23)小时数的UInt8数字。
SQL_FUNCTION_MAP.put("toMinute", ""); // 将DateTime转换为包含一小时中分钟数(0-59)的UInt8数字。
SQL_FUNCTION_MAP.put("toSecond", ""); // 将DateTime转换为包含一分钟中秒数(0-59)的UInt8数字。
SQL_FUNCTION_MAP.put("toUnixTimestamp", ""); // 对于DateTime参数:将值转换为UInt32类型的数字-Unix时间戳
SQL_FUNCTION_MAP.put("toStartOfYear", ""); // 将Date或DateTime向前取整到本年的第一天。
SQL_FUNCTION_MAP.put("toStartOfISOYear", ""); // 将Date或DateTime向前取整到ISO本年的第一天。
SQL_FUNCTION_MAP.put("toStartOfQuarter", "");// 将Date或DateTime向前取整到本季度的第一天。
SQL_FUNCTION_MAP.put("toStartOfMonth", ""); // 将Date或DateTime向前取整到本月的第一天。
SQL_FUNCTION_MAP.put("toMonday", ""); // 将Date或DateTime向前取整到本周的星期
SQL_FUNCTION_MAP.put("toStartOfWeek", ""); // 按mode将Date或DateTime向前取整到最近的星期日或星期一。
SQL_FUNCTION_MAP.put("toStartOfDay", ""); // 将DateTime向前取整到今天的开始。
SQL_FUNCTION_MAP.put("toStartOfHour", ""); // 将DateTime向前取整到当前小时的开始。
SQL_FUNCTION_MAP.put("toStartOfMinute", ""); // 将DateTime向前取整到当前分钟的开始。
SQL_FUNCTION_MAP.put("toStartOfSecond", ""); // 将DateTime向前取整到当前秒数的开始。
SQL_FUNCTION_MAP.put("toStartOfFiveMinute", "");// 将DateTime以五分钟为单位向前取整到最接近的时间点。
SQL_FUNCTION_MAP.put("toStartOfTenMinutes", ""); // 将DateTime以十分钟为单位向前取整到最接近的时间点。
SQL_FUNCTION_MAP.put("toStartOfFifteenMinutes", ""); // 将DateTime以十五分钟为单位向前取整到最接近的时间点。
SQL_FUNCTION_MAP.put("toStartOfInterval", ""); //
SQL_FUNCTION_MAP.put("toTime", ""); // 将DateTime中的日期转换为一个固定的日期,同时保留时间部分。
SQL_FUNCTION_MAP.put("toISOYear", ""); // 将Date或DateTime转换为包含ISO年份的UInt16类型的编号。
SQL_FUNCTION_MAP.put("toISOWeek", ""); //
SQL_FUNCTION_MAP.put("toWeek", "");// 返回Date或DateTime的周数。
SQL_FUNCTION_MAP.put("toYearWeek", ""); // 返回年和周的日期
SQL_FUNCTION_MAP.put("date_trunc", ""); // 截断日期和时间数据到日期的指定部分
SQL_FUNCTION_MAP.put("date_diff", ""); // 回两个日期或带有时间值的日期之间的差值。
SQL_FUNCTION_MAP.put("yesterday", ""); // 不接受任何参数并在请求执行时的某一刻返回昨天的日期(Date)。
SQL_FUNCTION_MAP.put("today", ""); // 不接受任何参数并在请求执行时的某一刻返回当前日期(Date)。
SQL_FUNCTION_MAP.put("timeSlot", ""); // 将时间向前取整半小时。
SQL_FUNCTION_MAP.put("toYYYYMM", ""); //
SQL_FUNCTION_MAP.put("toYYYYMMDD", "");//
SQL_FUNCTION_MAP.put("toYYYYMMDDhhmmss", ""); //
SQL_FUNCTION_MAP.put("addYears", ""); // Function adds a Date/DateTime interval to a Date/DateTime and then return the Date/DateTime
SQL_FUNCTION_MAP.put("addMonths", ""); // 同上
SQL_FUNCTION_MAP.put("addWeeks", ""); // 同上
SQL_FUNCTION_MAP.put("addDays", ""); // 同上
SQL_FUNCTION_MAP.put("addHours", ""); // 同上
SQL_FUNCTION_MAP.put("addMinutes", "");// 同上
SQL_FUNCTION_MAP.put("addSeconds", ""); // 同上
SQL_FUNCTION_MAP.put("addQuarters", ""); // 同上
SQL_FUNCTION_MAP.put("subtractYears", ""); // Function subtract a Date/DateTime interval to a Date/DateTime and then return the Date/DateTime
SQL_FUNCTION_MAP.put("subtractMonths", ""); // 同上
SQL_FUNCTION_MAP.put("subtractWeeks", ""); // 同上
SQL_FUNCTION_MAP.put("subtractDays", ""); // 同上
SQL_FUNCTION_MAP.put("subtractours", "");// 同上
SQL_FUNCTION_MAP.put("subtractMinutes", ""); // 同上
SQL_FUNCTION_MAP.put("subtractSeconds", ""); // 同上
SQL_FUNCTION_MAP.put("subtractQuarters", ""); // 同上
SQL_FUNCTION_MAP.put("formatDateTime", ""); // 函数根据给定的格式字符串来格式化时间
SQL_FUNCTION_MAP.put("timestamp_add", ""); // 使用提供的日期或日期时间值添加指定的时间值。
SQL_FUNCTION_MAP.put("timestamp_sub", ""); // 从提供的日期或带时间的日期中减去时间间隔。
// ClickHouse json函数
SQL_FUNCTION_MAP.put("visitParamHas", ""); // visitParamHas(params, name)检查是否存在«name»名称的字段
SQL_FUNCTION_MAP.put("visitParamExtractUInt", ""); // visitParamExtractUInt(params, name)将名为«name»的字段的值解析成UInt64。
SQL_FUNCTION_MAP.put("visitParamExtractInt", ""); // 与visitParamExtractUInt相同,但返回Int64。
SQL_FUNCTION_MAP.put("visitParamExtractFloat", ""); // 与visitParamExtractUInt相同,但返回Float64。
SQL_FUNCTION_MAP.put("visitParamExtractBool", "");// 解析true/false值。其结果是UInt8类型的。
SQL_FUNCTION_MAP.put("visitParamExtractRaw", ""); // 返回字段的值,包含空格符。
SQL_FUNCTION_MAP.put("visitParamExtractString", ""); // 使用双引号解析字符串。这个值没有进行转义。如果转义失败,它将返回一个空白字符串。
SQL_FUNCTION_MAP.put("JSONHas", ""); // 如果JSON中存在该值,则返回1。
SQL_FUNCTION_MAP.put("JSONLength", ""); // 返回JSON数组或JSON对象的长度。
SQL_FUNCTION_MAP.put("JSONType", ""); // 返回JSON值的类型。
SQL_FUNCTION_MAP.put("JSONExtractUInt", ""); // 解析JSON并提取值。这些函数类似于visitParam*函数。
SQL_FUNCTION_MAP.put("JSONExtractInt", ""); //
SQL_FUNCTION_MAP.put("JSONExtractFloat", ""); //
SQL_FUNCTION_MAP.put("JSONExtractBool", ""); //
SQL_FUNCTION_MAP.put("JSONExtractString", ""); // 解析JSON并提取字符串。此函数类似于visitParamExtractString函数。
SQL_FUNCTION_MAP.put("JSONExtract", ""); // 解析JSON并提取给定ClickHouse数据类型的值。
SQL_FUNCTION_MAP.put("JSONExtractKeysAndValues", ""); // 从JSON中解析键值对,其中值是给定的ClickHouse数据类型
SQL_FUNCTION_MAP.put("JSONExtractRaw", ""); // 返回JSON的部分。
SQL_FUNCTION_MAP.put("toJSONString", ""); //
// ClickHouse 类型转换函数
SQL_FUNCTION_MAP.put("toInt8", ""); // toInt8(expr) 转换一个输入值为Int类型
SQL_FUNCTION_MAP.put("toInt16", "");
SQL_FUNCTION_MAP.put("toInt32", "");
SQL_FUNCTION_MAP.put("toInt64", "");
SQL_FUNCTION_MAP.put("toInt8OrZero", ""); // toInt(8|16|32|64)OrZero 尝试把字符串转为 Int
SQL_FUNCTION_MAP.put("toInt16OrZero", "");
SQL_FUNCTION_MAP.put("toInt32OrZero", "");
SQL_FUNCTION_MAP.put("toInt64OrZero", "");
SQL_FUNCTION_MAP.put("toInt8OrNull", "");// toInt(8|16|32|64)O 尝试把字符串转为 Int
SQL_FUNCTION_MAP.put("toInt16OrNull", "");
SQL_FUNCTION_MAP.put("toInt32OrNull", "");
SQL_FUNCTION_MAP.put("toInt64OrNull", "");
SQL_FUNCTION_MAP.put("toUInt8", ""); // toInt8(expr) 转换一个输入值为Int类型
SQL_FUNCTION_MAP.put("toUInt16", "");
SQL_FUNCTION_MAP.put("toUInt32", "");
SQL_FUNCTION_MAP.put("toUInt64", "");
SQL_FUNCTION_MAP.put("toUInt8OrZero", ""); // toInt(8|16|32|64)OrZero 尝试把字符串转为 Int
SQL_FUNCTION_MAP.put("toUInt16OrZero", "");
SQL_FUNCTION_MAP.put("toUInt32OrZero", "");
SQL_FUNCTION_MAP.put("toUInt64OrZero", "");
SQL_FUNCTION_MAP.put("toUInt8OrNull", ""); // toInt(8|16|32|64)OrNull 尝试把字符串转为 Int
SQL_FUNCTION_MAP.put("toUInt16OrNull", "");
SQL_FUNCTION_MAP.put("toUInt32OrNull", "");
SQL_FUNCTION_MAP.put("toUInt64OrNull", "");
SQL_FUNCTION_MAP.put("toFloat32", "");
SQL_FUNCTION_MAP.put("toFloat64", "");
SQL_FUNCTION_MAP.put("toFloat32OrZero", "");
SQL_FUNCTION_MAP.put("toFloat64OrZero", "");
SQL_FUNCTION_MAP.put("toFloat32OrNull", "");
SQL_FUNCTION_MAP.put("toFloat64OrNull", "");
SQL_FUNCTION_MAP.put("toDate", ""); //
SQL_FUNCTION_MAP.put("toDateOrZero", ""); // toInt16(expr)
SQL_FUNCTION_MAP.put("toDateOrNull", ""); // toInt32(expr)
SQL_FUNCTION_MAP.put("toDateTimeOrZero", ""); // toInt64(expr) 尝试把字符串转为 DateTime
SQL_FUNCTION_MAP.put("toDateTimeOrNull", ""); // toInt(8|16|32|64) 尝试把字符串转为 DateTime
SQL_FUNCTION_MAP.put("toDecimal32", "");
SQL_FUNCTION_MAP.put("toFixedString", ""); // 将String类型的参数转换为FixedString(N)类型的值
SQL_FUNCTION_MAP.put("toStringCutToZero", ""); // 接受String或FixedString参数,返回String,其内容在找到的第一个零字节处被截断。
SQL_FUNCTION_MAP.put("toDecimal256", "");
SQL_FUNCTION_MAP.put("toDecimal32OrNull", "");
SQL_FUNCTION_MAP.put("toDecimal64OrNull", "");
SQL_FUNCTION_MAP.put("toDecimal128OrNull", "");
SQL_FUNCTION_MAP.put("toDecimal256OrNull", "");
SQL_FUNCTION_MAP.put("toDecimal32OrZero", "");
SQL_FUNCTION_MAP.put("toDecimal64OrZero", "");
SQL_FUNCTION_MAP.put("toDecimal128OrZero", "");
SQL_FUNCTION_MAP.put("toDecimal256OrZero", "");
SQL_FUNCTION_MAP.put("toIntervalSecond", ""); // 把一个数值类型的值转换为Interval类型的数据。
SQL_FUNCTION_MAP.put("toIntervalMinute", "");
SQL_FUNCTION_MAP.put("toIntervalHour", "");
SQL_FUNCTION_MAP.put("toIntervalDay", "");
SQL_FUNCTION_MAP.put("toIntervalWeek", "");
SQL_FUNCTION_MAP.put("toIntervalMonth", "");
SQL_FUNCTION_MAP.put("toIntervalQuarter", "");
SQL_FUNCTION_MAP.put("toIntervalYear", "");
SQL_FUNCTION_MAP.put("parseDateTimeBestEffort", ""); // 把String类型的时间日期转换为DateTime数据类型。
SQL_FUNCTION_MAP.put("parseDateTimeBestEffortOrNull", "");
SQL_FUNCTION_MAP.put("parseDateTimeBestEffortOrZero", "");
SQL_FUNCTION_MAP.put("toLowCardinality", "");
// ClickHouse hash 函数
SQL_FUNCTION_MAP.put("halfMD5", ""); // 计算字符串的MD5。然后获取结果的前8个字节并将它们作为UInt64(大端)返回
SQL_FUNCTION_MAP.put("MD5", ""); // 计算字符串的MD5并将结果放入FixedString(16)中返回
// ClickHouse ip 地址函数
SQL_FUNCTION_MAP.put("IPv4NumToString", ""); // 接受一个 UInt32(大端)表示的IPv4的地址,返回相应IPv4的字符串表现形式
SQL_FUNCTION_MAP.put("IPv4StringToNum", ""); // 与IPv4NumToString函数相反。如果IPv4地址格式无效,则返回0。
SQL_FUNCTION_MAP.put("IPv6NumToString", ""); // 接受FixedString(16)类型的二进制格式的IPv6地址。以文本格式返回此地址的字符串。
SQL_FUNCTION_MAP.put("IPv6StringToNum", ""); // 与IPv6NumToString的相反。如果IPv6地址格式无效,则返回空字节字符串。
SQL_FUNCTION_MAP.put("IPv4ToIPv6", ""); // 接受一个UInt32类型的IPv4地址,返回FixedString(16)类型的IPv6地址
SQL_FUNCTION_MAP.put("cutIPv6", ""); // 接受一个FixedString(16)类型的IPv6地址,返回 String,包含删除指定位之后的地址的文本格
SQL_FUNCTION_MAP.put("toIPv4", ""); // IPv4StringToNum()的别名,
SQL_FUNCTION_MAP.put("toIPv6", ""); // IPv6StringToNum()的别名
SQL_FUNCTION_MAP.put("isIPAddressInRange", ""); // 确定一个IP地址是否包含在以CIDR符号表示的网络中
// ClickHouse Nullable 处理函数
SQL_FUNCTION_MAP.put("isNull", ""); // 检查参数是否为NULL。
SQL_FUNCTION_MAP.put("isNotNull", ""); // 检查参数是否不为 NULL.
SQL_FUNCTION_MAP.put("ifNull", ""); // 如果第一个参数为«NULL»,则返回第二个参数的值。
SQL_FUNCTION_MAP.put("assumeNotNull", ""); // 将可为空类型的值转换为非Nullable类型的值。
SQL_FUNCTION_MAP.put("toNullable", ""); // 将参数的类型转换为Nullable。
// ClickHouse UUID 函数
SQL_FUNCTION_MAP.put("generateUUIDv4", ""); // 生成一个UUID
SQL_FUNCTION_MAP.put("toUUID", ""); // toUUID(x) 将String类型的值转换为UUID类型的值。
// ClickHouse 系统函数
SQL_FUNCTION_MAP.put("hostName", ""); // hostName()回一个字符串,其中包含执行此函数的主机的名称。
SQL_FUNCTION_MAP.put("getMacro", ""); // 从服务器配置的宏部分获取指定值。
SQL_FUNCTION_MAP.put("FQDN", ""); // 返回完全限定的域名。
SQL_FUNCTION_MAP.put("basename", ""); // 提取字符串最后一个斜杠或反斜杠之后的尾随部分
SQL_FUNCTION_MAP.put("currentUser", ""); // 返回当前用户的登录。在分布式查询的情况下,将返回用户的登录,即发起的查询
SQL_FUNCTION_MAP.put("version", ""); // 以字符串形式返回服务器版本。
SQL_FUNCTION_MAP.put("uptime", ""); // 以秒为单位返回服务器的正常运行时间。
// ClickHouse 数学函数
SQL_FUNCTION_MAP.put("least", ""); // least(a, b) 返回a和b中最小的值。
SQL_FUNCTION_MAP.put("greatest", ""); // greatest(a, b) 返回a和b的最大值。
SQL_FUNCTION_MAP.put("plus", ""); // plus(a, b), a + b operator¶计算数值的总和。
SQL_FUNCTION_MAP.put("minus", ""); // minus(a, b), a - b operator 计算数值之间的差,结果总是有符号的。
SQL_FUNCTION_MAP.put("multiply", "");// multiply(a, b), a * b operator 计算数值的乘积
SQL_FUNCTION_MAP.put("divide", ""); // divide(a, b), a / b operator 计算数值的商。结果类型始终是浮点类型
SQL_FUNCTION_MAP.put("intDiv", ""); // intDiv(a,b)计算数值的商,向下舍入取整(按绝对值)。
SQL_FUNCTION_MAP.put("intDivOrZero", ""); // intDivOrZero(a,b)与’intDiv’的不同之处在于它在除以零或将最小负数除以-1时返回零。
SQL_FUNCTION_MAP.put("modulo", ""); // modulo(a, b), a % b operator 计算除法后的余数。
SQL_FUNCTION_MAP.put("moduloOrZero", ""); // 和modulo不同之处在于,除以0时结果返回0
SQL_FUNCTION_MAP.put("negate", ""); // 通过改变数值的符号位对数值取反,结果总是有符号
SQL_FUNCTION_MAP.put("gcd", ""); // gcd(a,b) 返回数值的最大公约数。
SQL_FUNCTION_MAP.put("lcm", ""); // lcm(a,b) 返回数值的最小公倍数
SQL_FUNCTION_MAP.put("e", ""); // e() 返回一个接近数学常量e的Float64数字。
SQL_FUNCTION_MAP.put("pi", ""); // pi() 返回一个接近数学常量π的Float64数字。
SQL_FUNCTION_MAP.put("exp2", ""); // exp2(x)¶接受一个数值类型的参数并返回它的2的x次幂。
SQL_FUNCTION_MAP.put("exp10", ""); // exp10(x)¶接受一个数值类型的参数并返回它的10的x次幂。
SQL_FUNCTION_MAP.put("cbrt", ""); // cbrt(x) 接受一个数值类型的参数并返回它的立方根。
SQL_FUNCTION_MAP.put("lgamma", ""); // lgamma(x) 返回x的绝对值的自然对数的伽玛函数。
SQL_FUNCTION_MAP.put("tgamma", ""); // tgamma(x)¶返回x的伽玛函数。
SQL_FUNCTION_MAP.put("intExp2", ""); // intExp2 接受一个数值类型的参数并返回它的2的x次幂(UInt64)
SQL_FUNCTION_MAP.put("intExp10", ""); // intExp10 接受一个数值类型的参数并返回它的10的x次幂(UInt64)。
SQL_FUNCTION_MAP.put("cosh", ""); // cosh(x)
SQL_FUNCTION_MAP.put("sinh", ""); // sinh(x)
SQL_FUNCTION_MAP.put("asinh", ""); // asinh(x)
SQL_FUNCTION_MAP.put("atanh", ""); // atanh(x)
SQL_FUNCTION_MAP.put("atan2", ""); // atan2(y, x)
SQL_FUNCTION_MAP.put("hypot", ""); // hypot(x, y)
SQL_FUNCTION_MAP.put("log1p", ""); // log1p(x)
SQL_FUNCTION_MAP.put("trunc", ""); // 和 truncate 一样
SQL_FUNCTION_MAP.put("roundToExp2", ""); // roundToExp2(num) 接受一个数字。如果数字小于1,它返回0。
SQL_FUNCTION_MAP.put("roundDuration", ""); // roundDuration(num) 接受一个数字。如果数字小于1,它返回0。
SQL_FUNCTION_MAP.put("roundAge", ""); // roundAge(age) 接受一个数字。如果数字小于18,它返回0。
SQL_FUNCTION_MAP.put("roundDown", ""); // roundDown(num, arr) 接受一个数字并将其舍入到指定数组中的一个元素
SQL_FUNCTION_MAP.put("bitAnd", ""); // bitAnd(a,b)
SQL_FUNCTION_MAP.put("bitOr", ""); // bitOr(a,b)
// PostgreSQL 表结构相关 SQL 函数
SQL_FUNCTION_MAP.put("obj_description", "");
SQL_FUNCTION_MAP.put("col_description", "");
// SQLServer 相关 SQL 函数
SQL_FUNCTION_MAP.put("len", "");
SQL_FUNCTION_MAP.put("datalength", "");
}
private Parser<T> parser;
@Override
public Parser<T> getParser() {
if (parser == null && objectParser != null) {
parser = objectParser.getParser();
}
return parser;
}
@Override
public AbstractSQLConfig<T> setParser(Parser<T> parser) {
this.parser = parser;
return this;
}
public AbstractSQLConfig<T> putWarnIfNeed(String type, String warn) {
if (Log.DEBUG && parser instanceof AbstractParser) {
((AbstractParser<T>) parser).putWarnIfNeed(type, warn);
}
return this;
}
public AbstractSQLConfig<T> putWarn(String type, String warn) {
if (Log.DEBUG && parser instanceof AbstractParser) {
((AbstractParser<T>) parser).putWarn(type, warn);
}
return this;
}
private ObjectParser objectParser;
@Override
public ObjectParser getObjectParser() {
return objectParser;
}
@Override
public AbstractSQLConfig<T> setObjectParser(ObjectParser objectParser) {
this.objectParser = objectParser;
return this;
}
private int version;
@Override
public int getVersion() {
if (version <= 0 && parser != null) {
version = parser.getVersion();
}
return version;
}
@Override
public AbstractSQLConfig setVersion(int version) {
this.version = version;
return this;
}
private String tag;
@Override
public String getTag() {
if (StringUtil.isEmpty(tag) && parser != null) {
tag = parser.getTag();
}
return tag;
}
@Override
public AbstractSQLConfig setTag(String tag) {
this.tag = tag;
return this;
}
// mysql8版本以上,子查询支持with as表达式
private List<String> withAsExprSqlList = null;
protected List<Object> withAsExprPreparedValueList = new ArrayList<>();
private int[] dbVersionNums = null;
@Override
public int[] getDBVersionNums() {
if (dbVersionNums == null || dbVersionNums.length <= 0) {
dbVersionNums = SQLConfig.super.getDBVersionNums();
}
return dbVersionNums;
}
@Override
public boolean limitSQLCount() {
return AbstractVerifier.SYSTEM_ACCESS_MAP.containsKey(getTable()) == false;
}
@Override
public boolean allowPartialUpdateFailed() {
return allowPartialUpdateFailed(getTable());
}
public static boolean allowPartialUpdateFailed(String table) {
return ALLOW_PARTIAL_UPDATE_FAIL_TABLE_MAP.containsKey(table);
}
@NotNull
@Override
public String getIdKey() {
return KEY_ID;
}
@NotNull
@Override
public String getUserIdKey() {
return KEY_USER_ID;
}
private RequestMethod method; //操作方法
private boolean prepared = true; //预编译
private boolean main = true;
private Object id; // Table 的 id
private Object idIn; // User Table 的 id IN
private Object userId; // Table 的 userId
private Object userIdIn; // Table 的 userId IN
/**
* TODO 被关联的表通过就忽略关联的表?(这个不行 User:{"sex@":"/Comment/toId"})
*/
private String role; //发送请求的用户的角色
private boolean distinct = false;
private String database; //表所在的数据库类型
private String schema; //表所在的数据库名
private String datasource; //数据源
private String table; //表名
private String alias; //表别名
private String group; //分组方式的字符串数组,','分隔
private String havingCombine; //聚合函数的字符串数组,','分隔
private Map<String, Object> having; //聚合函数的字符串数组,','分隔
private String order; //排序方式的字符串数组,','分隔
private Map<String, String> keyMap; //字段名映射,支持 name_tag:(name,tag) 多字段 IN,year:left(date,4) 截取日期年份等
private List<String> raw; //需要保留原始 SQL 的字段,','分隔
private List<String> json; //需要转为 JSON 的字段,','分隔
private Subquery from; //子查询临时表
private List<String> column; //表内字段名(或函数名,仅查询操作可用)的字符串数组,','分隔
private List<List<Object>> values; //对应表内字段的值的字符串数组,','分隔
private List<String> nulls;
private Map<String, String> cast;
private Map<String, Object> content; //Request内容,key:value形式,column = content.keySet(),values = content.values()
private Map<String, Object> where; //筛选条件,key:value形式
private String combine; //条件组合, a | (b & c & !(d | !e))
private Map<String, List<String>> combineMap; //条件组合,{ "&":[key], "|":[key], "!":[key] }
//array item <<<<<<<<<<
private int count; //Table数量
private int page; //Table所在页码
private int position; //Table在[]中的位置
private int query; //JSONRequest.query
private Boolean compat; //JSONRequest.compat query total
private int type; //ObjectParser.type
private int cache;
private boolean explain;
private List<Join> joinList; //连表 配置列表
//array item >>>>>>>>>>
private boolean test; //测试
private String procedure;
public SQLConfig setProcedure(String procedure) {
this.procedure = procedure;
return this;
}
public String getProcedure() {
return procedure;
}
public AbstractSQLConfig(RequestMethod method) {
setMethod(method);
}
public AbstractSQLConfig(RequestMethod method, String table) {
this(method);
setTable(table);
}
public AbstractSQLConfig(RequestMethod method, int count, int page) {
this(method);
setCount(count);
setPage(page);
}
@NotNull
@Override
public RequestMethod getMethod() {
if (method == null) {
method = GET;
}
return method;
}
@Override
public AbstractSQLConfig setMethod(RequestMethod method) {
this.method = method;
return this;
}
@Override
public boolean isPrepared() {
return prepared;
}
@Override
public AbstractSQLConfig setPrepared(boolean prepared) {
this.prepared = prepared;
return this;
}
@Override
public boolean isMain() {
return main;
}
@Override
public AbstractSQLConfig setMain(boolean main) {
this.main = main;
return this;
}
@Override
public Object getId() {
return id;
}
@Override
public AbstractSQLConfig setId(Object id) {
this.id = id;
return this;
}
@Override
public Object getIdIn() {
return idIn;
}
@Override
public AbstractSQLConfig setIdIn(Object idIn) {
this.idIn = idIn;
return this;
}
@Override
public Object getUserId() {
return userId;
}
@Override
public AbstractSQLConfig setUserId(Object userId) {
this.userId = userId;
return this;
}
@Override
public Object getUserIdIn() {
return userIdIn;
}
@Override
public AbstractSQLConfig setUserIdIn(Object userIdIn) {
this.userIdIn = userIdIn;
return this;
}
@Override
public String getRole() {
//不能 @NotNull , AbstractParser#getSQLObject 内当getRole() == null时填充默认值
return role;
}
@Override
public AbstractSQLConfig setRole(String role) {
this.role = role;
return this;
}
@Override
public boolean isDistinct() {
return distinct;
}
@Override
public SQLConfig setDistinct(boolean distinct) {
this.distinct = distinct;
return this;
}
@Override
public String getDatabase() {
return database;
}
@Override
public SQLConfig setDatabase(String database) {
this.database = database;
return this;
}
/**
* @return db == null ? DEFAULT_DATABASE : db
*/
@NotNull
public String getSQLDatabase() {
String db = getDatabase();
return db == null ? DEFAULT_DATABASE : db; // "" 表示已设置,不需要用全局默认的 StringUtil.isEmpty(db, false)) {
}
@Override
public boolean isMySQL() {
return isMySQL(getSQLDatabase());
}
public static boolean isMySQL(String db) {
return DATABASE_MYSQL.equals(db);
}
@Override
public boolean isPostgreSQL() {
return isPostgreSQL(getSQLDatabase());
}
public static boolean isPostgreSQL(String db) {
return DATABASE_POSTGRESQL.equals(db);
}
@Override
public boolean isSQLServer() {
return isSQLServer(getSQLDatabase());
}
public static boolean isSQLServer(String db) {
return DATABASE_SQLSERVER.equals(db);
}
@Override
public boolean isOracle() {
return isOracle(getSQLDatabase());
}
public static boolean isOracle(String db) {
return DATABASE_ORACLE.equals(db);
}
@Override
public boolean isDb2() {
return isDb2(getSQLDatabase());
}
public static boolean isDb2(String db) {
return DATABASE_DB2.equals(db);
}
@Override
public boolean isMariaDB() {
return isMariaDB(getSQLDatabase());
}
public static boolean isMariaDB(String db) {
return DATABASE_MARIADB.equals(db);
}
@Override
public boolean isTiDB() {
return isTiDB(getSQLDatabase());
}
public static boolean isTiDB(String db) {
return DATABASE_TIDB.equals(db);
}
@Override
public boolean isDameng() {
return isDameng(getSQLDatabase());
}
public static boolean isDameng(String db) {
return DATABASE_DAMENG.equals(db);
}
@Override
public boolean isKingBase() {
return isKingBase(getSQLDatabase());
}
public static boolean isKingBase(String db) {
return DATABASE_KINGBASE.equals(db);
}
@Override
public boolean isElasticsearch() {
return isElasticsearch(getSQLDatabase());
}
public static boolean isElasticsearch(String db) {
return DATABASE_ELASTICSEARCH.equals(db);
}
@Override
public boolean isClickHouse() {
return isClickHouse(getSQLDatabase());
}
public static boolean isClickHouse(String db) {
return DATABASE_CLICKHOUSE.equals(db);
}
@Override
public boolean isHive() {
return isHive(getSQLDatabase());
}
public static boolean isHive(String db) {
return DATABASE_HIVE.equals(db);
}
@Override
public boolean isPresto() {
return isPresto(getSQLDatabase());
}
public static boolean isPresto(String db) {
return DATABASE_PRESTO.equals(db);
}
@Override
public boolean isTrino() {
return isTrino(getSQLDatabase());
}
public static boolean isTrino(String db) {
return DATABASE_TRINO.equals(db);
}
@Override
public boolean isSnowflake() {
return isSnowflake(getSQLDatabase());
}
public static boolean isSnowflake(String db) {
return DATABASE_SNOWFLAKE.equals(db);
}
@Override
public boolean isDatabricks() {
return isDatabricks(getSQLDatabase());
}
public static boolean isDatabricks(String db) {
return DATABASE_DATABRICKS.equals(db);
}
@Override
public boolean isCassandra() {
return isCassandra(getSQLDatabase());
}
public static boolean isCassandra(String db) {
return DATABASE_CASSANDRA.equals(db);
}
@Override
public boolean isMilvus() {
return isMilvus(getSQLDatabase());
}
public static boolean isMilvus(String db) {
return DATABASE_MILVUS.equals(db);
}
@Override
public boolean isInfluxDB() {
return isInfluxDB(getSQLDatabase());
}
public static boolean isInfluxDB(String db) {
return DATABASE_INFLUXDB.equals(db);
}
@Override
public boolean isTDengine() {
return isTDengine(getSQLDatabase());
}
public static boolean isTDengine(String db) {
return DATABASE_TDENGINE.equals(db);
}
@Override
public boolean isRedis() {
return isRedis(getSQLDatabase());
}
public static boolean isRedis(String db) {
return DATABASE_REDIS.equals(db);
}
@Override
public boolean isMongoDB() {
return isMongoDB(getSQLDatabase());
}
public static boolean isMongoDB(String db) {
return DATABASE_MONGODB.equals(db);
}
@Override
public boolean isKafka() {
return isKafka(getSQLDatabase());
}
public static boolean isKafka(String db) {
return DATABASE_KAFKA.equals(db);
}
@Override
public boolean isMQ() {
return isMQ(getSQLDatabase());
}
public static boolean isMQ(String db) {
return DATABASE_MQ.equals(db) || isKafka(db);
}
@Override
public String getQuote() {
if(isElasticsearch()) {
return "";
}
return isMySQL() || isMariaDB() || isTiDB() || isClickHouse() || isTDengine() || isMilvus() ? "`" : "\"";
}
public String quote(String s) {
String q = getQuote();
return q + s + q;
}
@Override
public String getSchema() {
return schema;
}
@NotNull
@Override
public String getSQLSchema() {
String table = getTable();
//强制,避免因为全局默认的 @schema 自动填充进来,导致这几个类的 schema 为 sys 等其它值
if (Table.TAG.equals(table) || Column.TAG.equals(table)) {
return SCHEMA_INFORMATION; //MySQL, PostgreSQL, SQL Server 都有的
}
if (PgClass.TAG.equals(table) || PgAttribute.TAG.equals(table)) {
return ""; //PostgreSQL 的 pg_class 和 pg_attribute 表好像不属于任何 Schema
}
if (SysTable.TAG.equals(table) || SysColumn.TAG.equals(table) || ExtendedProperty.TAG.equals(table)) {
return SCHEMA_SYS; //SQL Server 在 sys 中的属性比 information_schema 中的要全,能拿到注释
}
if (AllTable.TAG.equals(table) || AllColumn.TAG.equals(table)
|| AllTableComment.TAG.equals(table) || AllTableComment.TAG.equals(table)) {
return ""; //Oracle, Dameng 的 all_tables, dba_tables 和 all_tab_columns, dba_columns 表好像不属于任何 Schema
}
String sch = getSchema();
return sch == null ? DEFAULT_SCHEMA : sch;
}
@Override
public AbstractSQLConfig setSchema(String schema) {
if (schema != null) {
AbstractFunctionParser.verifySchema(schema, getTable());
}
this.schema = schema;
return this;
}
@Override
public String getDatasource() {
return datasource;
}
@Override
public SQLConfig setDatasource(String datasource) {
this.datasource = datasource;
return this;
}
/**请求传进来的Table名
* @return
* @see {@link #getSQLTable()}
*/
@Override
public String getTable() {
return table;
}
/**数据库里的真实Table名
* 通过 {@link #TABLE_KEY_MAP} 映射
* @return
*/
@JSONField(serialize = false)
@Override
public String getSQLTable() {
// 如果要强制小写,则可在子类重写这个方法再 toLowerCase
// return DATABASE_POSTGRESQL.equals(getDatabase()) ? t.toLowerCase() : t;
String ot = getTable();
String nt = TABLE_KEY_MAP.get(ot);
return StringUtil.isEmpty(nt) ? ot : nt;
}
@JSONField(serialize = false)
@Override
public String getTablePath() {
String q = getQuote();
String sch = getSQLSchema();
String sqlTable = getSQLTable();
return (StringUtil.isEmpty(sch, true) ? "" : q + sch + q + ".") + q + sqlTable + q
+ ( isKeyPrefix() ? " AS " + getAliasWithQuote() : "");
}
@Override
public AbstractSQLConfig setTable(String table) { //Table已经在Parser中校验,所以这里不用防SQL注入
this.table = table;
return this;
}
@Override
public String getAlias() {
return alias;
}
@Override
public AbstractSQLConfig setAlias(String alias) {
this.alias = alias;
return this;
}
public String getAliasWithQuote() {
String a = getAlias();
if (StringUtil.isEmpty(a, true)) {
a = getTable();
}
String q = getQuote();
// getTable 不能小写,因为Verifier用大小写敏感的名称判断权限
// 如果要强制小写,则可在子类重写这个方法再 toLowerCase
// return q + (DATABASE_POSTGRESQL.equals(getDatabase()) ? a.toLowerCase() : a) + q;
return q + a + q;
}
@Override
public String getGroup() {
return group;
}
public AbstractSQLConfig setGroup(String... keys) {
return setGroup(StringUtil.getString(keys));
}
@Override
public AbstractSQLConfig setGroup(String group) {
this.group = group;
return this;
}
@JSONField(serialize = false)
public String getGroupString(boolean hasPrefix) {
//加上子表的 group
String joinGroup = "";
if (joinList != null) {
boolean first = true;
for (Join j : joinList) {
if (j.isAppJoin()) {
continue;
}
SQLConfig ocfg = j.getOuterConfig();
SQLConfig cfg = (ocfg != null && ocfg.getGroup() != null) || j.isLeftOrRightJoin() ? ocfg : j.getJoinConfig();
if (cfg != null) {
cfg.setMain(false).setKeyPrefix(true);
if (StringUtil.isEmpty(cfg.getAlias(), true)) {
cfg.setAlias(cfg.getTable());
}
String c = ((AbstractSQLConfig) cfg).getGroupString(false);
if (StringUtil.isEmpty(c, true) == false) {
joinGroup += (first ? "" : ", ") + c;
first = false;
}
}
}
}
group = StringUtil.getTrimedString(group);
String[] keys = StringUtil.split(group);
if (keys == null || keys.length <= 0) {
return StringUtil.isEmpty(joinGroup, true) ? "" : (hasPrefix ? " GROUP BY " : "") + joinGroup;
}
for (int i = 0; i < keys.length; i++) {
if (isPrepared()) {
// 不能通过 ? 来代替,因为SQLExecutor statement.setString后 GROUP BY 'userId' 有单引号,只能返回一条数据,必须去掉单引号才行!
if (StringUtil.isName(keys[i]) == false) {
throw new IllegalArgumentException("@group:value 中 value里面用 , 分割的每一项都必须是1个单词!并且不要有空格!");
}
}
keys[i] = getKey(keys[i]);
}
return (hasPrefix ? " GROUP BY " : "") + StringUtil.concat(StringUtil.getString(keys), joinGroup, ", ");
}
@Override
public String getHavingCombine() {
return havingCombine;
}
@Override
public SQLConfig setHavingCombine(String havingCombine) {
this.havingCombine = havingCombine;
return this;
}
@Override
public Map<String, Object> getHaving() {
return having;
}
@Override
public SQLConfig setHaving(Map<String, Object> having) {
this.having = having;
return this;
}
public AbstractSQLConfig setHaving(String... conditions) {
return setHaving(StringUtil.getString(conditions));
}
/**TODO @having 改为默认 | 或连接,且支持 @having: { "key1>": 1, "key{}": "length(key2)>0", "@combine": "key1,key2" }
* @return HAVING conditoin0 AND condition1 OR condition2 ...
* @throws Exception
*/
@JSONField(serialize = false)
public String getHavingString(boolean hasPrefix) throws Exception {
//加上子表的 having
String joinHaving = "";
if (joinList != null) {
boolean first = true;
for (Join j : joinList) {
if (j.isAppJoin()) {
continue;
}
SQLConfig ocfg = j.getOuterConfig();
SQLConfig cfg = (ocfg != null && ocfg.getHaving() != null) || j.isLeftOrRightJoin() ? ocfg : j.getJoinConfig();
if (cfg != null) {
cfg.setMain(false).setKeyPrefix(true);
if (StringUtil.isEmpty(cfg.getAlias(), true)) {
cfg.setAlias(cfg.getTable());
}
String c = ((AbstractSQLConfig) cfg).getHavingString(false);
if (StringUtil.isEmpty(c, true) == false) {
joinHaving += (first ? "" : ", ") + c;
first = false;
}
}
}
}
Map<String, Object> map = getHaving();
Set<Entry<String, Object>> set = map == null ? null : map.entrySet();
if (set == null || set.isEmpty()) {
return StringUtil.isEmpty(joinHaving, true) ? "" : (hasPrefix ? " HAVING " : "") + joinHaving;
}
List<String> raw = getRaw();
// 提前把 @having& 转为 @having,或者干脆不允许 @raw:"@having&" boolean containRaw = raw != null && (raw.contains(KEY_HAVING) || raw.contains(KEY_HAVING_AND));
boolean containRaw = raw != null && raw.contains(KEY_HAVING);
// 直接把 having 类型从 Map<String, String> 定改为 Map<String, Object>,避免额外拷贝
// Map<String, Object> newMap = new LinkedHashMap<>(map.size());
// for (Entry<String, String> entry : set) {
// newMap.put(entry.getKey(), entry.getValue());
// }
//fun0(arg0,arg1,...);fun1(arg0,arg1,...)
String havingString = parseCombineExpression(getMethod(), getQuote(), getTable()
, getAliasWithQuote(), map, getHavingCombine(), true, containRaw, true);
return (hasPrefix ? " HAVING " : "") + StringUtil.concat(havingString, joinHaving, AND);
}
protected String getHavingItem(String quote, String table, String alias
, String key, String expression, boolean containRaw) throws Exception {
//fun(arg0,arg1,...)
if (containRaw) {
String rawSQL = getRawSQL(KEY_HAVING, expression);
if (rawSQL != null) {
return rawSQL;
}
}
if (expression.length() > 100) {
throw new UnsupportedOperationException("@having:value 的 value 中字符串 " + expression + " 不合法!"
+ "不允许传超过 100 个字符的函数或表达式!请用 @raw 简化传参!");
}
int start = expression.indexOf("(");
if (start < 0) {
if (isPrepared() && PATTERN_FUNCTION.matcher(expression).matches() == false) {
throw new UnsupportedOperationException("字符串 " + expression + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中 column?value 必须符合正则表达式 " + PATTERN_FUNCTION + " 且不包含连续减号 -- !不允许空格!");
}
return expression;
}
int end = expression.lastIndexOf(")");
if (start >= end) {
throw new IllegalArgumentException("字符 " + expression + " 不合法!"
+ "@having:value 中 value 里的 SQL函数必须为 function(arg0,arg1,...) 这种格式!");
}
String method = expression.substring(0, start);
if (method.isEmpty() == false) {
if (SQL_FUNCTION_MAP == null || SQL_FUNCTION_MAP.isEmpty()) {
if (StringUtil.isName(method) == false) {
throw new IllegalArgumentException("字符 " + method + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中 function 必须符合小写英文单词的 SQL 函数名格式!");
}
}
else if (SQL_FUNCTION_MAP.containsKey(method) == false) {
throw new IllegalArgumentException("字符 " + method + " 不合法!"
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中 function 必须符合小写英文单词的 SQL 函数名格式!且必须是后端允许调用的 SQL 函数!");
}
}
return method + parseSQLExpression(KEY_HAVING, expression.substring(start), containRaw, false, null);
}
@Override
public String getOrder() {
return order;
}
public AbstractSQLConfig setOrder(String... conditions) {
return setOrder(StringUtil.getString(conditions));
}
@Override
public AbstractSQLConfig setOrder(String order) {
this.order = order;
return this;
}
@JSONField(serialize = false)
public String getOrderString(boolean hasPrefix) {
//加上子表的 order
String joinOrder = "";
if (joinList != null) {
boolean first = true;
for (Join j : joinList) {
if (j.isAppJoin()) {
continue;
}
SQLConfig ocfg = j.getOuterConfig();
SQLConfig cfg = (ocfg != null && ocfg.getOrder() != null) || j.isLeftOrRightJoin() ? ocfg : j.getJoinConfig();
if (cfg != null) {
cfg.setMain(false).setKeyPrefix(true);
if (StringUtil.isEmpty(cfg.getAlias(), true)) {
cfg.setAlias(cfg.getTable());
}
String c = ((AbstractSQLConfig) cfg).getOrderString(false);
if (StringUtil.isEmpty(c, true) == false) {
joinOrder += (first ? "" : ", ") + c;
first = false;
}
}
}
}
String order = StringUtil.getTrimedString(getOrder());
// SELECT * FROM sys.Moment ORDER BY userId ASC, rand(); 前面的 userId ASC 和后面的 rand() 都有效
// if ("rand()".equals(order)) {
// return (hasPrefix ? " ORDER BY " : "") + StringUtil.concat(order, joinOrder, ", ");
// }
if (getCount() > 0 && (isSQLServer() || isDb2())) {
// Oracle, SQL Server, DB2 的 OFFSET 必须加 ORDER BY.去掉Oracle,Oracle里面没有offset关键字
// String[] ss = StringUtil.split(order);
if (StringUtil.isEmpty(order, true)) { //SQL Server 子查询内必须指定 OFFSET 才能用 ORDER BY
String idKey = getIdKey();
if (StringUtil.isEmpty(idKey, true)) {
idKey = "id";
// ORDER BY NULL 不行,SQL Server 会报错,必须要有排序,才能使用 OFFSET FETCH,如果没有 idKey,请求中指定 @order 即可
}
order = idKey; //让数据库调控默认升序还是降序 + "+";
}
//不用这么全面,毕竟没有语法问题还浪费性能,如果有其它问题,让前端传的 JSON 直接加上 @order 来解决
// boolean contains = false;
// if (ss != null) {
// for (String s : ss) {
// if (s != null && s.startsWith(idKey)) {
// s = s.substring(idKey.length());
// if ("+".equals(s) || "-".equals(s)) {// || " ASC ".equals(s) || " DESC ".equals(s)) {
// contains = true;
// break;
// }
// }
// }
// }
// if (contains == false) {
// order = (ss == null || ss.length <= 0 ? "" : order + ",") + idKey + "+";
// }
}
String[] keys = StringUtil.split(order);
if (keys == null || keys.length <= 0) {
return StringUtil.isEmpty(joinOrder, true) ? "" : (hasPrefix ? " ORDER BY " : "") + joinOrder;
}
for (int i = 0; i < keys.length; i++) {
String item = keys[i];
if ("rand()".equals(item)) {
continue;
}
int index = item.endsWith("+") ? item.length() - 1 : -1; //StringUtil.split返回数组中,子项不会有null
String sort;
if (index < 0) {
index = item.endsWith("-") ? item.length() - 1 : -1;
sort = index <= 0 ? "" : " DESC ";
}
else {
sort = " ASC ";
}
String origin = index < 0 ? item : item.substring(0, index);
if (isPrepared()) { //不能通过 ? 来代替,SELECT 'id','name' 返回的就是 id:"id", name:"name",而不是数据库里的值!
//这里既不对origin trim,也不对 ASC/DESC ignoreCase,希望前端严格传没有任何空格的字符串过来,减少传输数据量,节约服务器性能
if (StringUtil.isName(origin) == false) {
throw new IllegalArgumentException("预编译模式下 @order:value 中 " + item + " 不合法! value 里面用 , 分割的"
+ "每一项必须是 随机函数 rand() 或 column+ / column- 且其中 column 必须是 1 个单词!并且不要有多余的空格!");
}
}
keys[i] = getKey(origin) + sort;
}
return (hasPrefix ? " ORDER BY " : "") + StringUtil.concat(StringUtil.getString(keys), joinOrder, ", ");
}
@Override
public Map<String, String> getKeyMap() {
return keyMap;
}
@Override
public AbstractSQLConfig setKeyMap(Map<String, String> keyMap) {
this.keyMap = keyMap;
return this;
}
@Override
public List<String> getRaw() {
return raw;
}
@Override
public AbstractSQLConfig setRaw(List<String> raw) {
this.raw = raw;
return this;
}
/**获取原始 SQL 片段
* @param key
* @param value
* @return
* @throws Exception
*/
@Override
public String getRawSQL(String key, Object value) throws Exception {
return getRawSQL(key, value, ! ALLOW_MISSING_KEY_4_COMBINE);
}
/**获取原始 SQL 片段
* @param key
* @param value
* @param throwWhenMissing
* @return
* @throws Exception
*/
@Override
public String getRawSQL(String key, Object value, boolean throwWhenMissing) throws Exception {
if (value == null) {
return null;
}
List<String> rawList = getRaw();
boolean containRaw = rawList != null && rawList.contains(key);
if (containRaw && value instanceof String == false) {
throw new UnsupportedOperationException("@raw:value 的 value 中 " + key + " 不合法!"
+ "对应的 " + key + ":value 中 value 类型只能为 String!");
}
String rawSQL = containRaw ? RAW_MAP.get(value) : null;
if (containRaw) {
if (rawSQL == null) {
if (throwWhenMissing) {
throw new UnsupportedOperationException("@raw:value 的 value 中 " + key + " 不合法!"
+ "对应的 " + key + ":value 中 value 值 " + value + " 未在后端 RAW_MAP 中配置 !");
}
putWarnIfNeed(JSONRequest.KEY_RAW, "@raw:value 的 value 中 "
+ key + " 不合法!对应的 " + key + ":value 中 value 值 " + value + " 未在后端 RAW_MAP 中配置 !");
}
else if (rawSQL.isEmpty()) {
return (String) value;
}
}
return rawSQL;
}
@Override
public List<String> getJson() {
return json;
}
@Override
public AbstractSQLConfig setJson(List<String> json) {
this.json = json;
return this;
}
@Override
public Subquery getFrom() {
return from;
}
@Override
public AbstractSQLConfig setFrom(Subquery from) {
this.from = from;
return this;
}
@Override
public List<String> getColumn() {
return column;
}
@Override
public AbstractSQLConfig setColumn(List<String> column) {
this.column = column;
return this;
}
@JSONField(serialize = false)
public String getColumnString() throws Exception {
return getColumnString(false);
}
@JSONField(serialize = false)
public String getColumnString(boolean inSQLJoin) throws Exception {
List<String> column = getColumn();
switch (getMethod()) {
case HEAD:
case HEADS: //StringUtil.isEmpty(column, true) || column.contains(",") 时SQL.count(column)会return "*"
if (isPrepared() && column != null) {
List<String> raw = getRaw();
boolean containRaw = raw != null && raw.contains(KEY_COLUMN);
for (String c : column) {
if (containRaw) {
// 由于 HashMap 对 key 做了 hash 处理,所以 get 比 containsValue 更快
if ("".equals(RAW_MAP.get(c)) || RAW_MAP.containsValue(c)) { // newSQLConfig 提前处理好的
//排除@raw中的值,以避免使用date_format(date,'%Y-%m-%d %H:%i:%s') 时,冒号的解析出错
//column.remove(c);
continue;
}
}
int index = c.lastIndexOf(":"); //StringUtil.split返回数组中,子项不会有null
String origin = index < 0 ? c : c.substring(0, index);
String alias = index < 0 ? null : c.substring(index + 1);
if (alias != null && StringUtil.isName(alias) == false) {
throw new IllegalArgumentException("HEAD请求: 字符 " + alias
+ " 不合法!预编译模式下 @column:value 中 value里面用 , 分割的每一项"
+ " column:alias 中 column 必须是1个单词!如果有alias,则alias也必须为1个单词!并且不要有多余的空格!");
}
if (StringUtil.isName(origin) == false) {
int start = origin.indexOf("(");
if (start < 0 || origin.lastIndexOf(")") <= start) {
throw new IllegalArgumentException("HEAD请求: 字符" + origin
+ " 不合法!预编译模式下 @column:value 中 value里面用 , 分割的每一项"
+ " column:alias 中 column 必须是1个单词!"
+ "如果有alias,则 alias 也必须为1个单词!并且不要有多余的空格!");
}
if (start > 0 && StringUtil.isName(origin.substring(0, start)) == false) {
throw new IllegalArgumentException("HEAD请求: 字符 " + origin.substring(0, start)
+ " 不合法!预编译模式下 @column:value 中 value里面用 , 分割的每一项"
+ " column:alias 中 column 必须是1个单词!如果有alias,则alias也必须为1个单词!并且不要有多余的空格!");
}
}
}
}
boolean onlyOne = column != null && column.size() == 1;
String c0 = onlyOne ? column.get(0) : null;
if (onlyOne) {
int index = c0 == null ? -1 : c0.lastIndexOf(":");
if (index > 0) {
c0 = c0.substring(0, index);
}
int start = c0 == null ? -1 : c0.indexOf("(");
int end = start <= 0 ? -1 : c0.lastIndexOf(")");
if (start > 0 && end > start) {
String fun = c0.substring(0, start);
// Invalid use of group function SELECT count(max(`id`)) AS count FROM `sys`.`Comment`
if (SQL_AGGREGATE_FUNCTION_MAP.containsKey(fun)) {
String group = getGroup(); // TODO 唯一 100% 兼容的可能只有 SELECT count(*) FROM (原语句) AS table
return StringUtil.isEmpty(group, true) ? "1" : "count(DISTINCT " + group + ")";
}
String[] args = start == end - 1 ? null : StringUtil.split(c0.substring(start + 1, end));
if (args == null || args.length <= 0) {
return SQL.count(c0);
}
List<String> raw = getRaw();
boolean containRaw = raw != null && raw.contains(KEY_COLUMN);
return SQL.count(parseSQLExpression(KEY_COLUMN, c0, containRaw, false, null));
}
}
return SQL.count(onlyOne ? getKey(c0) : "*");
// return SQL.count(onlyOne && StringUtil.isName(column.get(0)) ? getKey(column.get(0)) : "*");
case POST:
if (column == null || column.isEmpty()) {
throw new IllegalArgumentException("POST 请求必须在Table内设置要保存的 key:value !");
}
String s = "";
boolean pfirst = true;
for (String c : column) {
if (isPrepared() && StringUtil.isName(c) == false) {
// 不能通过 ? 来代替,SELECT 'id','name' 返回的就是 id:"id", name:"name",而不是数据库里的值!
throw new IllegalArgumentException("POST请求: 每一个 key:value 中的key都必须是1个单词!");
}
s += ((pfirst ? "" : ",") + getKey(c));
pfirst = false;
}
return "(" + s + ")";
case GET:
case GETS:
String joinColumn = "";
if (joinList != null) {
boolean first = true;
for (Join j : joinList) {
if (j.isAppJoin()) {
continue;
}
SQLConfig ocfg = j.getOuterConfig();
boolean isEmpty = ocfg == null || ocfg.getColumn() == null;
boolean isLeftOrRightJoin = j.isLeftOrRightJoin();
if (isEmpty && isLeftOrRightJoin) {
// 改为 SELECT ViceTable.* 解决 SELECT sum(ViceTable.id)
// LEFT/RIGHT JOIN (SELECT sum(id) FROM ViceTable...) AS ViceTable
// 不仅导致 SQL 函数重复计算,还有时导致 SQL 报错或对应字段未返回
String quote = getQuote();
joinColumn += (first ? "" : ", ") + quote + (StringUtil.isEmpty(j.getAlias(), true)
? j.getTable() : j.getAlias()) + quote + ".*";
first = false;
} else {
SQLConfig cfg = isLeftOrRightJoin == false && isEmpty ? j.getJoinConfig() : ocfg;
if (cfg != null) {
cfg.setMain(false).setKeyPrefix(true);
if (StringUtil.isEmpty(cfg.getAlias(), true)) {
cfg.setAlias(cfg.getTable());
}
String c = ((AbstractSQLConfig) cfg).getColumnString(true);
if (StringUtil.isEmpty(c, true) == false) {
joinColumn += (first ? "" : ", ") + c;
first = false;
}
}
}
inSQLJoin = true;
}
}
String tableAlias = getAliasWithQuote();
// String c = StringUtil.getString(column); //id,name;json_length(contactIdList):contactCount;...
String[] keys = column == null ? null : column.toArray(new String[]{}); //StringUtil.split(c, ";");
if (keys == null || keys.length <= 0) {
boolean noColumn = column != null && inSQLJoin;
String mc = isKeyPrefix() == false ? (noColumn ? "" : "*") : (noColumn ? "" : tableAlias + ".*");
return StringUtil.concat(mc, joinColumn, ", ", true);
}
List<String> raw = getRaw();
boolean containRaw = raw != null && raw.contains(KEY_COLUMN);
//...;fun0(arg0,arg1,...):fun0;fun1(arg0,arg1,...):fun1;...
for (int i = 0; i < keys.length; i++) {
String expression = keys[i]; //fun(arg0,arg1,...)
if (containRaw) { // 由于 HashMap 对 key 做了 hash 处理,所以 get 比 containsValue 更快
if ("".equals(RAW_MAP.get(expression)) || RAW_MAP.containsValue(expression)) { // newSQLConfig 提前处理好的
continue;
}
// 简单点, 后台配置就带上 AS
int index = expression.lastIndexOf(":");
String alias = expression.substring(index+1);
boolean hasAlias = StringUtil.isName(alias);
String pre = index > 0 && hasAlias ? expression.substring(0, index) : expression;
if (RAW_MAP.containsValue(pre) || "".equals(RAW_MAP.get(pre))) { // newSQLConfig 提前处理好的
keys[i] = pre + (hasAlias ? " AS " + alias : "");
continue;
}
}
if (expression.length() > 100) {
throw new UnsupportedOperationException("@column:value 的 value 中字符串 " + expression + " 不合法!"
+ "不允许传超过 100 个字符的函数或表达式!请用 @raw 简化传参!");
}
keys[i] = parseSQLExpression(KEY_COLUMN, expression, containRaw, true
, "@column:\"column0,column1:alias1;function0(arg0,arg1,...);function1(...):alias2...\"");
}
String c = StringUtil.getString(keys);
c = c + (StringUtil.isEmpty(joinColumn, true) ? "" : ", " + joinColumn);//不能在这里改,后续还要用到:
return isMain() && isDistinct() ? PREFIX_DISTINCT + c : c;
default:
throw new UnsupportedOperationException(
"服务器内部错误:getColumnString 不支持 " + RequestMethod.getName(getMethod())
+ " 等 [GET,GETS,HEAD,HEADS,POST] 外的ReuqestMethod!"
);
}
}
/**解析@column 中以“;”分隔的表达式("@column":"expression1;expression2;expression2;....")中的expression
* @param key
* @param expression
* @param containRaw
* @param allowAlias
* @return
*/
public String parseSQLExpression(String key, String expression, boolean containRaw, boolean allowAlias) {
return parseSQLExpression(key, expression, containRaw, allowAlias, null);
}
/**解析@column 中以“;”分隔的表达式("@column":"expression1;expression2;expression2;....")中的expression
* @param key
* @param expression
* @param containRaw
* @param allowAlias
* @param example
* @return
*/
public String parseSQLExpression(String key, String expression, boolean containRaw, boolean allowAlias, String example) {
if (containRaw) {
String s = RAW_MAP.get(expression);
if ("".equals(s)) {
return expression;
}
if (s != null) {
return s;
}
}
String quote = getQuote();
int start = expression.indexOf('(');
if (start < 0) {
//没有函数 ,可能是字段,也可能是 DISTINCT xx
String[] cks = parseArgsSplitWithComma(expression, true, containRaw, allowAlias);
expression = StringUtil.getString(cks);
} else { // FIXME 用括号断开? 如果少的话,用关键词加括号断开,例如 )OVER( 和 )AGAINST(
// 窗口函数 rank() OVER (PARTITION BY id ORDER BY userId ASC)
// 全文索引 math(name,tag) AGAINST ('a b +c -d' IN NATURALE LANGUAGE MODE) // IN BOOLEAN MODE
if (StringUtil.isEmpty(example)) {
if (KEY_COLUMN.equals(key)) {
example = key + ":\"column0,column1:alias1;function0(arg0,arg1,...);function1(...):alias2...\"";
}
// 和 key{}:"" 一样 else if (KEY_HAVING.equals(key) || KEY_HAVING_AND.equals(key)) {
// exeptionExample = key + ":\"function0(arg0,arg1,...)>1;function1(...)%5<=3...\"";
// }
else {
example = key + ":\"column0!=0;column1+3*2<=10;function0(arg0,arg1,...)>1;function1(...)%5<=3...\"";
}
}
//有函数,但不是窗口函数
int overIndex = expression.indexOf(")OVER("); // 传参不传空格,拼接带空格 ") OVER (");
int againstIndex = expression.indexOf(")AGAINST("); // 传参不传空格,拼接带空格 ") AGAINST (");
boolean containOver = overIndex > 0 && overIndex < expression.length() - ")OVER(".length();
boolean containAgainst = againstIndex > 0 && againstIndex < expression.length() - ")AGAINST(".length();
if (containOver && containAgainst) {
throw new IllegalArgumentException("字符 " + expression + " 不合法!预编译模式下 " + example
+ " 中 function 必须符合小写英文单词的 SQL 函数名格式!不能同时存在窗口函数关键词 OVER 和全文索引关键词 AGAINST!");
}
if (containOver == false && containAgainst == false) {
int end = expression.lastIndexOf(')');
if (start >= end) {
throw new IllegalArgumentException("字符 " + expression + " 不合法!"
+ key + ":value 中 value 里的 SQL函数必须为 function(arg0,arg1,...) 这种格式!");
}
String fun = expression.substring(0, start);
if (fun.isEmpty() == false) {
if (SQL_FUNCTION_MAP == null || SQL_FUNCTION_MAP.isEmpty()) {
if (StringUtil.isName(fun) == false) {
throw new IllegalArgumentException("字符 " + fun + " 不合法!预编译模式下 " + example
+ " 中 function 必须符合小写英文单词的 SQL 函数名格式!");
}
} else if (SQL_FUNCTION_MAP.containsKey(fun) == false) {
throw new IllegalArgumentException("字符 " + fun + " 不合法!预编译模式下 " + example
+ " 中 function 必须符合小写英文单词的 SQL 函数名格式!且必须是后端允许调用的 SQL 函数!");
}
}
String s = expression.substring(start + 1, end);
boolean distinct = s.startsWith(PREFIX_DISTINCT);
if (distinct) {
s = s.substring(PREFIX_DISTINCT.length());
}
// 解析函数内的参数
String ckeys[] = parseArgsSplitWithComma(s, false, containRaw, allowAlias);
String suffix = expression.substring(end + 1, expression.length()); //:contactCount
String alias = null;
if (allowAlias) {
int index = suffix.lastIndexOf(":");
alias = index < 0 ? "" : suffix.substring(index + 1); //contactCount
suffix = index < 0 ? suffix : suffix.substring(0, index);
if (alias.isEmpty() == false && StringUtil.isName(alias) == false) {
throw new IllegalArgumentException("字符串 " + alias + " 不合法!预编译模式下 "
+ key + ":value 中 value里面用 ; 分割的每一项"
+ " function(arg0,arg1,...):alias 中 alias 必须是1个单词!并且不要有多余的空格!");
}
}
if (suffix.isEmpty() == false && (((String) suffix).contains("--") || ((String) suffix).contains("/*")
|| PATTERN_RANGE.matcher((String) suffix).matches() == false)) {
throw new UnsupportedOperationException("字符串 " + suffix + " 不合法!预编译模式下 " + key
+ ":\"column?value;function(arg0,arg1,...)?value...\""
+ " 中 ?value 必须符合正则表达式 " + PATTERN_RANGE + " 且不包含连续减号 -- 或注释符 /* !不允许多余的空格!");
}
String origin = fun + "(" + (distinct ? PREFIX_DISTINCT : "") + StringUtil.getString(ckeys) + ")" + suffix;
expression = origin + (StringUtil.isEmpty(alias, true) ? "" : " AS " + quote + alias + quote);
}
else {
//是窗口函数 fun(arg0,agr1) OVER (agr0 agr1 ...)
int keyIndex = containOver ? overIndex : againstIndex;
String s1 = expression.substring(0, keyIndex + 1); // OVER 前半部分
String s2 = expression.substring(keyIndex + 1); // OVER 后半部分
int index1 = s1.indexOf("("); // 函数 "(" 的起始位置
int end = s2.lastIndexOf(")"); // 后半部分 “)” 的位置
if (index1 >= end + s1.length()) {
throw new IllegalArgumentException("字符 " + expression + " 不合法!"
+ key + ":value 中 value 里的 SQL 函数必须为 function(arg0,arg1,...) 这种格式!");
}
String fun = s1.substring(0, index1); // 函数名称
if (fun.isEmpty() == false) {
if (SQL_FUNCTION_MAP == null || SQL_FUNCTION_MAP.isEmpty()) {
if (StringUtil.isName(fun) == false) {
throw new IllegalArgumentException("字符 " + fun + " 不合法!预编译模式下 " + example
+ " 中 function 必须符合小写英文单词的 SQL 函数名格式!");
}
}
else if (SQL_FUNCTION_MAP.containsKey(fun) == false) {
throw new IllegalArgumentException("字符 " + fun + " 不合法!预编译模式下 " + example
+ " 中 function 必须符合小写英文单词的 SQL 函数名格式!且必须是后端允许调用的 SQL 函数!");
}
}
// 获取前半部分函数的参数解析 fun(arg0,agr1)
String agrsString1[] = parseArgsSplitWithComma(
s1.substring(index1 + 1, s1.lastIndexOf(")")), false, containRaw, allowAlias
);
int index2 = s2.indexOf("("); // 后半部分 “(”的起始位置
String argString2 = s2.substring(index2 + 1, end); // 后半部分的参数
// 别名
int aliasIndex = allowAlias == false ? -1 : s2.lastIndexOf(":");
String alias = aliasIndex < 0 ? "" : s2.substring(aliasIndex + 1);
if (alias.isEmpty() == false && StringUtil.isName(alias) == false) {
throw new IllegalArgumentException("字符串 " + alias + " 不合法!预编译模式下 "
+ key + ":value 中 value里面用 ; 分割的每一项"
+ " function(arg0,arg1,...):alias 中 alias 必须是1个单词!并且不要有多余的空格!");
}
String suffix = s2.substring(end + 1, aliasIndex < 0 ? s2.length() : aliasIndex);
if (suffix.isEmpty() == false && (((String) suffix).contains("--") || ((String) suffix).contains("/*")
|| PATTERN_RANGE.matcher((String) suffix).matches() == false)) {
throw new UnsupportedOperationException("字符串 " + suffix + " 不合法!预编译模式下 " + key
+ ":\"column?value;function(arg0,arg1,...)?value...\""
+ " 中 ?value 必须符合正则表达式 " + PATTERN_RANGE + " 且不包含连续减号 -- 或注释符 /* !不允许多余的空格!");
}
// 获取后半部分的参数解析 (agr0 agr1 ...)
String argsString2[] = parseArgsSplitWithComma(argString2, false, containRaw, allowAlias);
expression = fun + "(" + StringUtil.getString(agrsString1) + (containOver ? ") OVER (" : ") AGAINST (")
+ StringUtil.getString(argsString2) + ")" + suffix // 传参不传空格,拼接带空格
+ (StringUtil.isEmpty(alias, true) ? "" : " AS " + quote + alias + quote);
}
}
return expression;
}
/**解析函数参数或者字段,此函数对于解析字段 和 函数内参数通用
* @param param
* @param isColumn true:不是函数参数。false:是函数参数
* @param containRaw
* @param allowAlias
* @return
*/
private String[] parseArgsSplitWithComma(String param, boolean isColumn, boolean containRaw, boolean allowAlias) {
// 以"," 分割参数
String quote = getQuote();
boolean isKeyPrefix = isKeyPrefix();
String tableAlias = getAliasWithQuote();
String ckeys[] = StringUtil.split(param); // 以","分割参数
if (ckeys != null && ckeys.length > 0) {
for (int i = 0; i < ckeys.length; i++) {
String ck = ckeys[i];
String origin;
String alias;
// 如果参数包含 "'" ,解析字符串
if (ck.startsWith("`") && ck.endsWith("`")) {
origin = ck.substring(1, ck.length() - 1);
//sql 注入判断 判断
if (origin.startsWith("_") || StringUtil.isName(origin) == false) {
throw new IllegalArgumentException("字符 " + ck + " 不合法!"
+ "预编译模式下 @column:\"`column0`,`column1`:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中所有字符串 column 都必须必须为1个单词 !");
}
origin = getKey(origin).toString();
}
else if (ck.startsWith("'") && ck.endsWith("'")) {
origin = ck.substring(1, ck.length() - 1);
if (origin.contains("'")) {
throw new IllegalArgumentException("字符串 " + ck + " 不合法!"
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中字符串参数不合法,必须以 ' 开头, ' 结尾,字符串中不能包含 ' ");
}
// 1.字符串不是字段也没有别名,所以不解析别名 2. 是字符串,进行预编译,使用getValue() ,对字符串进行截取
origin = getValue(origin).toString();
}
else {
// 参数不包含",",即不是字符串
// 解析参数:1. 字段 ,2. 是以空格分隔的参数 eg: cast(now() as date)
if ("=null".equals(ck)) {
origin = SQL.isNull();
}
else if ("!=null".equals(ck)) {
origin = SQL.isNull(false);
}
else {
origin = ck;
alias = null;
if (allowAlias) {
int index = isColumn ? ck.lastIndexOf(":") : -1; //StringUtil.split返回数组中,子项不会有null
origin = index < 0 ? ck : ck.substring(0, index); //获取 : 之前的
alias = index < 0 ? null : ck.substring(index + 1);
if (isPrepared()) {
if (isColumn) {
if (StringUtil.isName(origin) == false || (alias != null && StringUtil.isName(alias) == false)) {
throw new IllegalArgumentException("字符 " + ck + " 不合法!"
+ "预编译模式下 @column:value 中 value里面用 , 分割的每一项"
+ " column:alias 中 column 必须是1个单词!如果有alias,则alias也必须为1个单词!"
+ "关键字必须全大写,且以空格分隔的参数,空格必须只有 1 个!其它情况不允许空格!");
}
} else {
if (origin.startsWith("_") || origin.contains("--")) {
// || PATTERN_FUNCTION.matcher(origin).matches() == false) {
throw new IllegalArgumentException("字符 " + ck + " 不合法!"
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中所有 arg 都必须是1个不以 _ 开头的单词 或者符合正则表达式 "
+ PATTERN_FUNCTION + " 且不包含连续减号 -- !" +
"DISTINCT 必须全大写,且后面必须有且只有 1 个空格!其它情况不允许空格!");
}
}
}
}
// 以空格分割参数
String[] mkes = containRaw ? StringUtil.split(ck, " ", true) : new String[]{ ck };
//如果参数中含有空格(少数情况) 比如 fun(arg1, arg2,arg3,arg4) 中的 arg1 arg2 arg3,比如 DISTINCT id
if (mkes != null && mkes.length >= 2) {
origin = parseArgsSplitWithSpace(mkes);
} else {
String mk = RAW_MAP.get(origin);
if (mk != null) { // newSQLConfig 提前处理好的
if (mk.length() > 0) {
origin = mk;
}
} else if (StringUtil.isNumer(origin)) {
//do nothing
} else {
String[] keys = origin.split("[.]");
StringBuilder sb = new StringBuilder();
int len = keys == null ? 0 : keys.length;
if (len > 0) {
boolean first = true;
for (String k : keys) {
if (StringUtil.isName(k) == false) {
sb = null;
break;
}
sb.append(first ? "" : ".").append(quote).append(k).append(quote);
first = false;
}
}
String s = sb == null ? null : sb.toString();
if (StringUtil.isNotEmpty(s, true)) {
origin = (len == 1 && isKeyPrefix ? tableAlias + "." : "") + s;
} else {
origin = getValue(origin).toString();
}
}
if (isColumn && StringUtil.isEmpty(alias, true) == false) {
origin += " AS " + quote + alias + quote;
}
}
}
}
ckeys[i] = origin;
}
}
return ckeys;
}
/**
* 只解析以空格分隔的参数
*
* @param mkes
* @return
*/
private String parseArgsSplitWithSpace(String mkes[]) {
String quote = getQuote();
boolean isKeyPrefix = isKeyPrefix();
String tableAlias = getAliasWithQuote();
// 包含空格的参数 肯定不包含别名 不用处理别名
if (mkes != null && mkes.length > 0) {
for (int j = 0; j < mkes.length; j++) {
// now()/AS/ DISTINCT/VALUE 等等放在RAW_MAP中
String origin = mkes[j];
String mk = RAW_MAP.get(origin);
if (mk != null) { // newSQLConfig 提前处理好的
if (mk.length() > 0) {
mkes[j] = mk;
}
continue;
}
//这里为什么还要做一次判断 是因为解析窗口函数调用的时候会判断一次
String ck = origin;
// 如果参数包含 "`" 或 "'" ,解析字符串
if (ck.startsWith("`") && ck.endsWith("`")) {
origin = ck.substring(1, ck.length() - 1);
if (origin.startsWith("_") || StringUtil.isName(origin) == false) {
throw new IllegalArgumentException("字符 " + ck + " 不合法!"
+ "预编译模式下 @column:\"`column0`,`column1`:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中所有字符串 column 都必须必须为1个单词 !");
}
mkes[j] = getKey(origin);
continue;
}
else if (ck.startsWith("'") && ck.endsWith("'")) {
origin = ck.substring(1, ck.length() - 1);
if (origin.contains("'")) {
throw new IllegalArgumentException("字符串 " + ck + " 不合法!"
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中字符串参数不合法,必须以 ' 开头, ' 结尾,字符串中不能包含 ' ");
}
// 1.字符串不是字段也没有别名,所以不解析别名 2. 是字符串,进行预编译,使用getValue() ,对字符串进行截取
mkes[j] = getValue(origin).toString();
continue;
}
else if (ck.contains("`") || ck.contains("'") || origin.startsWith("_") || origin.contains("--")) {
// || PATTERN_FUNCTION.matcher(origin).matches() == false) {
throw new IllegalArgumentException("字符 " + origin + " 不合法!"
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中所有 arg 都必须是1个不以 _ 开头的单词 或者符合正则表达式 " + PATTERN_FUNCTION
+ " 且不包含连续减号 -- !DISTINCT 必须全大写,且后面必须有且只有 1 个空格!其它情况不允许空格!");
}
if (StringUtil.isNumer(origin)) {
//do nothing
} else {
String[] keys = origin.split("[.]");
StringBuilder sb = new StringBuilder();
int len = keys == null ? 0 : keys.length;
if (len > 0) {
boolean first = true;
for (String k : keys) {
if (StringUtil.isName(k) == false) {
sb = null;
break;
}
sb.append(first ? "" : ".").append(quote).append(k).append(quote);
first = false;
}
}
String s = sb == null ? null : sb.toString();
if (StringUtil.isNotEmpty(s, true)) {
origin = (len == 1 && isKeyPrefix ? tableAlias + "." : "") + s;
} else {
origin = getValue(origin).toString();
}
}
mkes[j] = origin;
}
}
// 返回重新以" "拼接后的参数
return StringUtil.join(mkes, " ");
}
@Override
public List<List<Object>> getValues() {
return values;
}
@JSONField(serialize = false)
public String getValuesString() {
String s = "";
if (values != null && values.size() > 0) {
Object[] items = new Object[values.size()];
List<Object> vs;
for (int i = 0; i < values.size(); i++) {
vs = values.get(i);
if (vs == null) {
continue;
}
items[i] = "(";
for (int j = 0; j < vs.size(); j++) {
items[i] += ((j <= 0 ? "" : ",") + getValue(vs.get(j)));
}
items[i] += ")";
}
s = StringUtil.getString(items);
}
return s;
}
@Override
public AbstractSQLConfig setValues(List<List<Object>> valuess) {
this.values = valuess;
return this;
}
@Override
public Map<String, Object> getContent() {
return content;
}
@Override
public AbstractSQLConfig setContent(Map<String, Object> content) {
this.content = content;
return this;
}
@Override
public int getCount() {
return count;
}
@Override
public AbstractSQLConfig setCount(int count) {
this.count = count;
return this;
}
@Override
public int getPage() {
return page;
}
@Override
public AbstractSQLConfig setPage(int page) {
this.page = page;
return this;
}
@Override
public int getPosition() {
return position;
}
@Override
public AbstractSQLConfig setPosition(int position) {
this.position = position;
return this;
}
@Override
public int getQuery() {
return query;
}
@Override
public AbstractSQLConfig setQuery(int query) {
this.query = query;
return this;
}
@Override
public Boolean getCompat() {
return compat;
}
@Override
public AbstractSQLConfig setCompat(Boolean compat) {
this.compat = compat;
return this;
}
@Override
public int getType() {
return type;
}
@Override
public AbstractSQLConfig setType(int type) {
this.type = type;
return this;
}
@Override
public int getCache() {
return cache;
}
@Override
public AbstractSQLConfig setCache(int cache) {
this.cache = cache;
return this;
}
public AbstractSQLConfig setCache(String cache) {
return setCache(getCache(cache));
}
public static int getCache(String cache) {
int cache2;
if (cache == null) {
cache2 = JSONRequest.CACHE_ALL;
}
else {
// if (isSubquery) {
// throw new IllegalArgumentException("子查询内不支持传 " + JSONRequest.KEY_CACHE + "!");
// }
switch (cache) {
case "0":
case JSONRequest.CACHE_ALL_STRING:
cache2 = JSONRequest.CACHE_ALL;
break;
case "1":
case JSONRequest.CACHE_ROM_STRING:
cache2 = JSONRequest.CACHE_ROM;
break;
case "2":
case JSONRequest.CACHE_RAM_STRING:
cache2 = JSONRequest.CACHE_RAM;
break;
default:
throw new IllegalArgumentException(JSONRequest.KEY_CACHE
+ ":value 中 value 的值不合法!必须在 [0,1,2] 或 [ALL, ROM, RAM] 内 !");
}
}
return cache2;
}
@Override
public boolean isExplain() {
return explain;
}
@Override
public AbstractSQLConfig setExplain(boolean explain) {
this.explain = explain;
return this;
}
@Override
public List<Join> getJoinList() {
return joinList;
}
@Override
public SQLConfig setJoinList(List<Join> joinList) {
this.joinList = joinList;
return this;
}
@Override
public boolean hasJoin() {
return joinList != null && joinList.isEmpty() == false;
}
@Override
public boolean isTest() {
return test;
}
@Override
public AbstractSQLConfig setTest(boolean test) {
this.test = test;
return this;
}
/**获取初始位置offset
* @return
*/
@JSONField(serialize = false)
public int getOffset() {
return getOffset(getPage(), getCount());
}
/**获取初始位置offset
* @param page
* @param count
* @return
*/
public static int getOffset(int page, int count) {
return page*count;
}
/**获取限制数量
* @return
*/
@JSONField(serialize = false)
public String getLimitString() {
int count = getCount();
if (isMilvus()) {
if (count == 0) {
Parser<T> parser = getParser();
count = parser == null ? AbstractParser.MAX_QUERY_COUNT : parser.getMaxQueryCount();
}
int offset = getOffset(getPage(), count);
return " LIMIT " + offset + ", " + count; // 目前 moql-transx 的限制
}
if (count <= 0 || RequestMethod.isHeadMethod(getMethod(), true)) { // TODO HEAD 真的不需要 LIMIT ?
return "";
}
return getLimitString(
getPage()
, getCount()
, isOracle() || isSQLServer() || isDb2()
, isOracle() || isDameng() || isKingBase()
, isPresto() || isTrino()
);
}
/**获取限制数量及偏移量
* @param page
* @param count
* @param isTSQL
* @param isOracle
* @return
*/
public static String getLimitString(int page, int count, boolean isTSQL, boolean isOracle) {
return getLimitString(page, count, isTSQL, isOracle, false);
}
/**获取限制数量及偏移量
* @param page
* @param count
* @param isTSQL
* @param isOracle
* @param isPresto
* @return
*/
public static String getLimitString(int page, int count, boolean isTSQL, boolean isOracle, boolean isPresto) {
int offset = getOffset(page, count);
if (isOracle) { // TODO 判断版本,高版本可以用 OFFSET FETCH
return " WHERE ROWNUM BETWEEN " + offset + " AND " + (offset + count);
}
if (isTSQL) { // OFFSET FECTH 中所有关键词都不可省略, 另外 Oracle 数据库使用子查询加 where 分页
return " OFFSET " + offset + " ROWS FETCH FIRST " + count + " ROWS ONLY";
}
if (isPresto) { // https://prestodb.io/docs/current/sql/select.html
return (offset <= 0 ? "" : " OFFSET " + offset) + " LIMIT " + count;
}
return " LIMIT " + count + (offset <= 0 ? "" : " OFFSET " + offset); // DELETE, UPDATE 不支持 OFFSET
}
@Override
public List<String> getNull() {
return nulls;
}
@Override
public SQLConfig setNull(List<String> nulls) {
this.nulls = nulls;
return this;
}
@Override
public Map<String, String> getCast() {
return cast;
}
@Override
public SQLConfig setCast(Map<String, String> cast) {
this.cast = cast;
return this;
}
//WHERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
protected int getMaxHavingCount() {
return MAX_HAVING_COUNT;
}
protected int getMaxWhereCount() {
return MAX_WHERE_COUNT;
}
protected int getMaxCombineDepth() {
return MAX_COMBINE_DEPTH;
}
protected int getMaxCombineCount() {
return MAX_COMBINE_COUNT;
}
protected int getMaxCombineKeyCount() {
return MAX_COMBINE_KEY_COUNT;
}
protected float getMaxCombineRatio() {
return MAX_COMBINE_RATIO;
}
@Override
public String getCombine() {
return combine;
}
@Override
public AbstractSQLConfig setCombine(String combine) {
this.combine = combine;
return this;
}
@NotNull
@Override
public Map<String, List<String>> getCombineMap() {
List<String> andList = combineMap == null ? null : combineMap.get("&");
if (andList == null) {
andList = where == null ? new ArrayList<String>() : new ArrayList<String>(where.keySet());
if (combineMap == null) {
combineMap = new HashMap<>();
}
combineMap.put("&", andList);
}
return combineMap;
}
@Override
public AbstractSQLConfig setCombineMap(Map<String, List<String>> combineMap) {
this.combineMap = combineMap;
return this;
}
@Override
public Map<String, Object> getWhere() {
return where;
}
@Override
public AbstractSQLConfig setWhere(Map<String, Object> where) {
this.where = where;
return this;
}
/**
* noFunctionChar = false
* @param key
* @return
*/
@JSONField(serialize = false)
@Override
public Object getWhere(String key) {
return getWhere(key, false);
}
//CS304 Issue link: https://github.com/Tencent/APIJSON/issues/48
/**
* @param key - the key passed in
* @param exactMatch - whether it is exact match
* @return
* <p>use entrySet+getValue() to replace keySet+get() to enhance efficiency</p>
*/
@JSONField(serialize = false)
@Override
public Object getWhere(String key, boolean exactMatch) {
if (exactMatch) {
return where == null ? null : where.get(key);
}
if (key == null || where == null){
return null;
}
int index;
for (Entry<String,Object> entry : where.entrySet()) {
String k = entry.getKey();
index = k.indexOf(key);
if (index >= 0 && StringUtil.isName(k.substring(index, index + 1)) == false) {
return entry.getValue();
}
}
return null;
}
@Override
public AbstractSQLConfig putWhere(String key, Object value, boolean prior) {
if (key != null) {
if (where == null) {
where = new LinkedHashMap<String, Object>();
}
if (value == null) {
where.remove(key);
} else {
where.put(key, value);
}
Map<String, List<String>> combineMap = getCombineMap();
List<String> andList = combineMap.get("&");
if (value == null) {
if (andList != null) {
andList.remove(key);
}
}
else if (andList == null || andList.contains(key) == false) {
int i = 0;
if (andList == null) {
andList = new ArrayList<>();
}
else if (prior && andList.isEmpty() == false) {
String idKey = getIdKey();
String idInKey = idKey + "{}";
String userIdKey = getUserIdKey();
String userIdInKey = userIdKey + "{}";
int lastIndex;
if (key.equals(idKey)) {
setId(value);
lastIndex = -1;
}
else if (key.equals(idInKey)) {
setIdIn(value);
lastIndex = andList.lastIndexOf(idKey);
}
else if (key.equals(userIdKey)) {
setUserId(value);
lastIndex = andList.lastIndexOf(idInKey);
if (lastIndex < 0) {
lastIndex = andList.lastIndexOf(idKey);
}
}
else if (key.equals(userIdInKey)) {
setUserIdIn(value);
lastIndex = andList.lastIndexOf(userIdKey);
if (lastIndex < 0) {
lastIndex = andList.lastIndexOf(idInKey);
}
if (lastIndex < 0) {
lastIndex = andList.lastIndexOf(idKey);
}
}
else {
lastIndex = andList.lastIndexOf(userIdInKey);
if (lastIndex < 0) {
lastIndex = andList.lastIndexOf(userIdKey);
}
if (lastIndex < 0) {
lastIndex = andList.lastIndexOf(idInKey);
}
if (lastIndex < 0) {
lastIndex = andList.lastIndexOf(idKey);
}
}
i = lastIndex + 1;
}
if (prior) {
andList.add(i, key); // userId 的优先级不能比 id 高 0, key);
} else {
// AbstractSQLExecutor.onPutColumn 里 getSQL,要保证缓存的 SQL 和查询的 SQL 里 where 的 key:value 顺序一致
andList.add(key);
}
}
combineMap.put("&", andList);
}
return this;
}
/**获取WHERE
* @return
* @throws Exception
*/
@JSONField(serialize = false)
@Override
public String getWhereString(boolean hasPrefix) throws Exception {
String combineExpr = getCombine();
if (StringUtil.isEmpty(combineExpr, false)) {
return getWhereString(hasPrefix, getMethod(), getWhere(), getCombineMap(), getJoinList(), ! isTest());
}
return getWhereString(hasPrefix, getMethod(), getWhere(), combineExpr, getJoinList(), ! isTest());
}
/**获取WHERE
* @param method
* @param where
* @return
* @throws Exception
*/
@JSONField(serialize = false)
public String getWhereString(boolean hasPrefix, RequestMethod method, Map<String, Object> where
, String combine, List<Join> joinList, boolean verifyName) throws Exception {
String whereString = parseCombineExpression(method, getQuote(), getTable(), getAliasWithQuote()
, where, combine, verifyName, false, false);
whereString = concatJoinWhereString(whereString);
String result = StringUtil.isEmpty(whereString, true) ? "" : (hasPrefix ? " WHERE " : "") + whereString;
if (result.isEmpty() && RequestMethod.isQueryMethod(method) == false) {
throw new UnsupportedOperationException("写操作请求必须带条件!!!");
}
return result;
}
/**解析 @combine 条件 key 组合的与或非+括号的逻辑运算表达式为具体的完整条件组合
* @param method
* @param quote
* @param table
* @param alias
* @param conditionMap where 或 having 对应条件的 Map
* @param combine
* @param verifyName
* @param containRaw
* @param isHaving
* @return
* @throws Exception
*/
protected String parseCombineExpression(RequestMethod method, String quote, String table, String alias
, Map<String, Object> conditionMap, String combine, boolean verifyName, boolean containRaw, boolean isHaving) throws Exception {
String errPrefix = table + (isHaving ? ":{ @having:{ " : ":{ ") + "@combine:'" + combine + (isHaving ? "' } }" : "' }");
String s = StringUtil.getString(combine);
if (s.startsWith(" ") || s.endsWith(" ") ) {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s
+ "' 不合法!不允许首尾有空格,也不允许连续空格!空格不能多也不能少!"
+ "逻辑连接符 & | 左右必须各一个相邻空格!左括号 ( 右边和右括号 ) 左边都不允许有相邻空格!");
}
if (conditionMap == null) {
conditionMap = new HashMap<>();
}
int size = conditionMap.size();
int maxCount = isHaving ? getMaxHavingCount() : getMaxWhereCount();
if (maxCount > 0 && size > maxCount) {
throw new IllegalArgumentException(table + (isHaving ? ":{ @having:{ " : ":{ ") + "key0:value0, key1:value1... " + combine
+ (isHaving ? " } }" : " }") + " 中条件 key:value 数量 " + size + " 已超过最大数量,必须在 0-" + maxCount + " 内!");
}
String result = "";
List<Object> preparedValues = getPreparedValueList();
if (preparedValues == null && isHaving == false) {
preparedValues = new ArrayList<>();
}
Map<String, Integer> usedKeyCountMap = new HashMap<>(size);
int n = s.length();
if (n > 0) {
if (isHaving == false) { // 只收集表达式条件值
setPreparedValueList(new ArrayList<>()); // 必须反过来,否则 JOIN ON 内部 @combine 拼接后顺序错误
}
int maxDepth = getMaxCombineDepth();
int maxCombineCount = getMaxCombineCount();
int maxCombineKeyCount = getMaxCombineKeyCount();
float maxCombineRatio = getMaxCombineRatio();
int depth = 0;
int allCount = 0;
int i = 0;
char lastLogic = 0;
char last = 0;
boolean first = true;
boolean isNot = false;
String key = "";
while (i <= n) { // "date> | (contactIdList<> & (name*~ | tag&$))"
boolean isOver = i >= n;
char c = isOver ? 0 : s.charAt(i);
boolean isBlankOrRightParenthesis = c == ' ' || c == ')';
if (isOver || isBlankOrRightParenthesis) {
boolean isEmpty = StringUtil.isEmpty(key, true);
if (isEmpty && last != ')') {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + (isOver ? s : s.substring(i))
+ "' 不合法!" + (c == ' ' ? "空格 ' ' " : "右括号 ')'") + " 左边缺少条件 key !逻辑连接符 & | 左右必须各一个相邻空格!"
+ "空格不能多也不能少!不允许首尾有空格,也不允许连续空格!左括号 ( 的右边 和 右括号 ) 的左边 都不允许有相邻空格!");
}
if (isEmpty == false) {
if (first == false && lastLogic <= 0) {
throw new IllegalArgumentException(errPrefix + " 中字符 "
+ "'" + s.substring(i - key.length() - (isOver ? 1 : 0))
+ "' 不合法!左边缺少 & | 其中一个逻辑连接符!");
}
allCount ++;
if (allCount > maxCombineCount && maxCombineCount > 0) {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s + "' 不合法!"
+ "其中 key 数量 " + allCount + " 已超过最大值,必须在条件键值对数量 0-" + maxCombineCount + " 内!");
}
String column = key;
int keyIndex = column.indexOf(":");
column = keyIndex > 0 ? column.substring(0, keyIndex) : column;
Object value = conditionMap.get(column);
String wi = "";
if (value == null && conditionMap.containsKey(column) == false) { // 兼容@null
isNot = false; // 以占位表达式为准
size++; // 兼容 key 数量判断
wi = keyIndex > 0 ? key.substring(keyIndex + 1) : "";
if (StringUtil.isEmpty(wi)) {
throw new IllegalArgumentException(errPrefix + " 中字符 '"
+ key + "' 对应的条件键值对 " + column + ":value 不存在!");
}
} else {
wi = isHaving ? getHavingItem(quote, table, alias, column, (String) value, containRaw)
: getWhereItem(column, value, method, verifyName);
}
if (1.0f*allCount/size > maxCombineRatio && maxCombineRatio > 0) {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s + "' 不合法!"
+ "其中 key 数量 " + allCount + " / 条件键值对数量 " + size + " = " + (1.0f*allCount/size)
+ " 已超过 最大倍数,必须在条件键值对数量 0-" + maxCombineRatio + " 倍内!");
}
if (StringUtil.isEmpty(wi, true)) { // 转成 1=1 ?
throw new IllegalArgumentException(errPrefix + " 中字符 '" + key
+ "' 对应的 " + column + ":value 不是有效条件键值对!");
}
Integer count = usedKeyCountMap.get(column);
count = count == null ? 1 : count + 1;
if (count > maxCombineKeyCount && maxCombineKeyCount > 0) {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s + "' 不合法!"
+ "其中 '" + column + "' 重复引用,次数 " + count
+ " 已超过最大值,必须在 0-" + maxCombineKeyCount + " 内!");
}
usedKeyCountMap.put(column, count);
result += "( " + getCondition(isNot, wi) + " )";
isNot = false;
first = false;
}
key = "";
lastLogic = 0;
if (isOver) {
break;
}
}
if (c == ' ') {
}
else if (c == '&') {
if (last == ' ') {
if (i >= n - 1 || s.charAt(i + 1) != ' ') {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + (i >= n - 1 ? s : s.substring(0, i + 1))
+ "' 不合法!逻辑连接符 & 右边缺少一个空格 !逻辑连接符 & | 左右必须各一个相邻空格!空格不能多也不能少!"
+ "不允许首尾有空格,也不允许连续空格!左括号 ( 的右边 和 右括号 ) 的左边 都不允许有相邻空格!");
}
result += SQL.AND;
lastLogic = c;
i ++;
}
else {
key += c;
}
}
else if (c == '|') {
if (last == ' ') {
if (i >= n - 1 || s.charAt(i + 1) != ' ') {
throw new IllegalArgumentException(table + ":{ @combine: '" + combine
+ "' } 中字符 '" + (i >= n - 1 ? s : s.substring(0, i + 1))
+ "' 不合法!逻辑连接符 | 右边缺少一个空格 !逻辑连接符 & | 左右必须各一个相邻空格!空格不能多也不能少!"
+ "不允许首尾有空格,也不允许连续空格!左括号 ( 右边和右括号 ) 左边都不允许有相邻空格!");
}
result += SQL.OR;
lastLogic = c;
i ++;
}
else {
key += c;
}
}
else if (c == '!') {
last = i <= 0 ? 0 : s.charAt(i - 1); // & | 后面跳过了空格
char next = i >= n - 1 ? 0 : s.charAt(i + 1);
if (last == ' ' || last == '(') {
if (next == ' ') {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s.substring(0, i + 1)
+ "' 不合法!非逻辑符 '!' 右边多了一个空格 ' ' !非逻辑符 '!' " +
"右边不允许任何相邻空格 ' ',也不允许 ')' '&' '|' 中任何一个!");
}
if (next == ')' || next == '&' || next == '!') {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s.substring(0, i + 1)
+ "' 不合法!非逻辑符 '!' 右边多了一个字符 '"
+ next + "' !非逻辑符 '!' 右边不允许任何相邻空格 ' ',也不允许 ')' '&' '|' 中任何一个!");
}
if (i > 0 && lastLogic <= 0 && last != '(') {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s.substring(i)
+ "' 不合法!左边缺少 & | 逻辑连接符!逻辑连接符 & | 左右必须各一个相邻空格!空格不能多也不能少!"
+ "不允许首尾有空格,也不允许连续空格!左括号 ( 的右边 和 右括号 ) 的左边 都不允许有相邻空格!");
}
}
if (next == '(') {
result += SQL.NOT;
lastLogic = c;
}
else if (last <= 0 || last == ' ' || last == '(') {
isNot = true;
// lastLogic = c;
}
else {
key += c;
}
}
else if (c == '(') {
if (key.isEmpty() == false || (i > 0 && lastLogic <= 0 && last != '(')) {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s.substring(i)
+ "' 不合法!左边缺少 & | 逻辑连接符!逻辑连接符 & | 左右必须各一个相邻空格!空格不能多也不能少!"
+ "不允许首尾有空格,也不允许连续空格!左括号 ( 的右边 和 右括号 ) 的左边 都不允许有相邻空格!");
}
depth ++;
if (depth > maxDepth && maxDepth > 0) {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s.substring(0, i + 1)
+ "' 不合法!括号 (()) 嵌套层级 " + depth + " 已超过最大值,必须在 0-" + maxDepth + " 内!");
}
result += c;
lastLogic = 0;
first = true;
}
else if (c == ')') {
depth --;
if (depth < 0) {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s.substring(0, i + 1)
+ "' 不合法!左括号 ( 比 右括号 ) 少!数量必须相等从而完整闭合 (...) !");
}
result += c;
lastLogic = 0;
}
else {
key += c;
}
last = c;
i ++;
}
if (depth != 0) {
throw new IllegalArgumentException(errPrefix + " 中字符 '" + s
+ "' 不合法!左括号 ( 比 右括号 ) 多!数量必须相等从而完整闭合 (...) !");
}
}
List<Object> exprPreparedValues = getPreparedValueList();
if (isHaving == false) { // 只收集 AND 条件值
setPreparedValueList(new ArrayList<>());
}
Set<Entry<String, Object>> set = conditionMap.entrySet();
String andCond = "";
boolean isItemFirst = true;
for (Entry<String, Object> entry : set) {
String key = entry == null ? null : entry.getKey();
if (key == null || usedKeyCountMap.containsKey(key)) {
continue;
}
String wi = isHaving ? getHavingItem(quote, table, alias, key, (String) entry.getValue(), containRaw)
: getWhereItem(key, entry.getValue(), method, verifyName);
if (StringUtil.isEmpty(wi, true)) {//避免SQL条件连接错误
continue;
}
andCond += (isItemFirst ? "" : AND) + "(" + wi + ")";
isItemFirst = false;
}
if (isHaving == false) { // 优先存放 AND 条件值
preparedValues.addAll(getPreparedValueList());
}
if (StringUtil.isEmpty(result, true)) {
result = andCond;
}
else if (StringUtil.isNotEmpty(andCond, true)) { // andCond 必须放后面,否则 prepared 值顺序错误
if (isHaving) {
// HAVING 前 WHERE 已经有条件 ? 占位,不能反过来,想优化 AND 连接在最前,需要多遍历一次内部的 key,也可以 newSQLConfig 时存到 andList
result = "( " + result + " )" + AND + andCond;
}
else {
result = andCond + AND + "( " + result + " )"; // 先暂存之前的 prepared 值,然后反向整合
}
}
if (isHaving == false) {
if (exprPreparedValues != null && exprPreparedValues.isEmpty() == false) {
preparedValues.addAll(exprPreparedValues); // 在 AND 条件值后存放表达式内的条件值
}
setPreparedValueList(preparedValues);
}
return result;
}
/**@combine:"a,b" 条件组合。虽然有了 @combine:"a | b" 这种新方式,但为了 Join 多个 On 能保证顺序正确,以及这个性能更好,还是保留这个方式
* @param hasPrefix
* @param method
* @param where
* @param combine
* @param joinList
* @param verifyName
* @return
* @throws Exception
*/
public String getWhereString(boolean hasPrefix, RequestMethod method, Map<String, Object> where
, Map<String, List<String>> combine, List<Join> joinList, boolean verifyName) throws Exception {
Set<Entry<String, List<String>>> combineSet = combine == null ? null : combine.entrySet();
if (combineSet == null || combineSet.isEmpty()) {
Log.w(TAG, "getWhereString combineSet == null || combineSet.isEmpty() >> return \"\";");
return "";
}
List<String> keyList;
String whereString = "";
boolean isCombineFirst = true;
int logic;
boolean isItemFirst;
String c;
String cs;
for (Entry<String, List<String>> ce : combineSet) {
keyList = ce == null ? null : ce.getValue();
if (keyList == null || keyList.isEmpty()) {
continue;
}
if ("|".equals(ce.getKey())) {
logic = Logic.TYPE_OR;
}
else if ("!".equals(ce.getKey())) {
logic = Logic.TYPE_NOT;
}
else {
logic = Logic.TYPE_AND;
}
isItemFirst = true;
cs = "";
for (String key : keyList) {
c = getWhereItem(key, where.get(key), method, verifyName);
if (StringUtil.isEmpty(c, true)) {//避免SQL条件连接错误
continue;
}
cs += (isItemFirst ? "" : (Logic.isAnd(logic) ? AND : OR)) + "(" + c + ")";
isItemFirst = false;
}
if (StringUtil.isEmpty(cs, true)) {//避免SQL条件连接错误
continue;
}
whereString += (isCombineFirst ? "" : AND) + (Logic.isNot(logic) ? NOT : "") + " ( " + cs + " ) ";
isCombineFirst = false;
}
whereString = concatJoinWhereString(whereString);
String s = StringUtil.isEmpty(whereString, true) ? "" : (hasPrefix ? " WHERE " : "") + whereString;
if (s.isEmpty() && RequestMethod.isQueryMethod(method) == false) {
throw new UnsupportedOperationException("写操作请求必须带条件!!!");
}
return s;
}
protected String concatJoinWhereString(String whereString) throws Exception {
List<Join> joinList = getJoinList();
if (joinList != null) {
String newWs = "";
String ws = whereString;
List<Object> newPvl = new ArrayList<>();
List<Object> pvl = new ArrayList<>(getPreparedValueList());
SQLConfig jc;
String js;
boolean changed = false;
// 各种 JOIN 没办法统一用 & | !连接,只能按优先级,和 @combine 一样?
for (Join j : joinList) {
String jt = j.getJoinType();
switch (jt) {
case "*": // CROSS JOIN
case "@": // APP JOIN
case "<": // LEFT JOIN
case ">": // RIGHT JOIN
break;
case "&": // INNER JOIN: A & B
case "": // FULL JOIN: A | B
case "|": // FULL JOIN: A | B
case "!": // OUTER JOIN: ! (A | B)
case "^": // SIDE JOIN: ! (A & B)
case "(": // ANTI JOIN: A & ! B
case ")": // FOREIGN JOIN: B & ! A
jc = j.getJoinConfig();
boolean isMain = jc.isMain();
jc.setMain(false).setPrepared(isPrepared()).setPreparedValueList(new ArrayList<Object>());
js = jc.getWhereString(false);
jc.setMain(isMain);
boolean isOuterJoin = "!".equals(jt);
boolean isSideJoin = "^".equals(jt);
boolean isAntiJoin = "(".equals(jt);
boolean isForeignJoin = ")".equals(jt);
boolean isWsEmpty = StringUtil.isEmpty(ws, true);
if (isWsEmpty) {
if (isOuterJoin) { // ! OUTER JOIN: ! (A | B)
throw new NotExistException("no result for ! OUTER JOIN( ! (A | B) ) when A or B is empty!");
}
if (isForeignJoin) { // ) FOREIGN JOIN: B & ! A
throw new NotExistException("no result for ) FOREIGN JOIN( B & ! A ) when A is empty!");
}
}
if (StringUtil.isEmpty(js, true)) {
if (isOuterJoin) { // ! OUTER JOIN: ! (A | B)
throw new NotExistException("no result for ! OUTER JOIN( ! (A | B) ) when A or B is empty!");
}
if (isAntiJoin) { // ( ANTI JOIN: A & ! B
throw new NotExistException("no result for ( ANTI JOIN( A & ! B ) when B is empty!");
}
if (isWsEmpty) {
if (isSideJoin) {
throw new NotExistException("no result for ^ SIDE JOIN( ! (A & B) ) when both A and B are empty!");
}
}
else {
if (isSideJoin || isForeignJoin) {
newWs += " ( " + getCondition(true, ws) + " ) ";
newPvl.addAll(pvl);
newPvl.addAll(jc.getPreparedValueList());
changed = true;
}
}
continue;
}
if (StringUtil.isEmpty(newWs, true) == false) {
newWs += AND;
}
if (isAntiJoin) { // ( ANTI JOIN: A & ! B
newWs += " ( " + ( isWsEmpty ? "" : ws + AND ) + NOT + " ( " + js + " ) " + " ) ";
}
else if (isForeignJoin) { // ) FOREIGN JOIN: (! A) & B // preparedValueList.add 不好反过来 B & ! A
newWs += " ( " + NOT + " ( " + ws + " ) ) " + AND + " ( " + js + " ) ";
}
else if (isSideJoin) { // ^ SIDE JOIN: ! (A & B)
//MySQL 因为 NULL 值处理问题,(A & ! B) | (B & ! A) 与 ! (A & B) 返回结果不一样,后者往往更多
newWs += " ( " + getCondition(
true,
( isWsEmpty ? "" : ws + AND ) + " ( " + js + " ) "
) + " ) ";
}
else { // & INNER JOIN: A & B; | FULL JOIN: A | B; OUTER JOIN: ! (A | B)
int logic = Logic.getType(jt);
newWs += " ( "
+ getCondition(
Logic.isNot(logic),
ws
+ ( isWsEmpty ? "" : (Logic.isAnd(logic) ? AND : OR) )
+ " ( " + js + " ) "
)
+ " ) ";
}
newPvl.addAll(pvl);
newPvl.addAll(jc.getPreparedValueList());
changed = true;
break;
default:
throw new UnsupportedOperationException(
"join:value 中 value 里的 " + jt + "/" + j.getPath()
+ "错误!不支持 " + jt + " 等 [ @ APP, < LEFT, > RIGHT, * CROSS"
+ ", & INNER, | FULL, ! OUTER, ^ SIDE, ( ANTI, ) FOREIGN ] 之外的 JOIN 类型 !"
);
}
}
if (changed) {
whereString = newWs;
setPreparedValueList(newPvl);
}
}
return whereString;
}
/**
* @param key
* @param value
* @param method
* @param verifyName
* @return
* @throws Exception
*/
protected String getWhereItem(String key, Object value, RequestMethod method, boolean verifyName) throws Exception {
Log.d(TAG, "getWhereItem key = " + key);
// 避免筛选到全部 value = key == null ? null : where.get(key);
if (key == null || key.endsWith("()") || key.startsWith("@")) { //关键字||方法, +或-直接报错
Log.d(TAG, "getWhereItem key == null || key.endsWith(()) || key.startsWith(@) >> continue;");
return null;
}
if (key.endsWith("@")) { // 引用
// key = key.substring(0, key.lastIndexOf("@"));
throw new IllegalArgumentException(TAG + ".getWhereItem: 字符 " + key + " 不合法!");
}
if (value == null) {
return null;
}
int keyType;
if (key.endsWith("$")) {
keyType = 1;
}
else if (key.endsWith("~")) {
keyType = key.charAt(key.length() - 2) == '*' ? -2 : 2; //FIXME StringIndexOutOfBoundsException
}
else if (key.endsWith("%")) {
keyType = 3;
}
else if (key.endsWith("{}")) {
keyType = 4;
}
else if (key.endsWith("}{")) {
keyType = 5;
}
else if (key.endsWith("<>")) {
keyType = 6;
}
else if (key.endsWith(">=")) {
keyType = 7;
}
else if (key.endsWith("<=")) {
keyType = 8;
}
else if (key.endsWith(">")) {
keyType = 9;
}
else if (key.endsWith("<")) {
keyType = 10;
} else { // else绝对不能省,避免再次踩坑! keyType = 0; 写在for循环外面都没注意!
keyType = 0;
}
String column = getRealKey(method, key, false, true, verifyName);
// 原始 SQL 片段
String rawSQL = getRawSQL(key, value);
switch (keyType) {
case 1:
return getSearchString(key, column, value, rawSQL);
case -2:
case 2:
return getRegExpString(key, column, value, keyType < 0, rawSQL);
case 3:
return getBetweenString(key, column, value, rawSQL);
case 4:
return getRangeString(key, column, value, rawSQL);
case 5:
return getExistsString(key, column, value, rawSQL);
case 6:
return getContainString(key, column, value, rawSQL);
case 7:
return getCompareString(key, column, value, ">=", rawSQL);
case 8:
return getCompareString(key, column, value, "<=", rawSQL);
case 9:
return getCompareString(key, column, value, ">", rawSQL);
case 10:
return getCompareString(key, column, value, "<", rawSQL);
default: // TODO MySQL JSON类型的字段对比 key='[]' 会无结果! key LIKE '[1, 2, 3]' //TODO MySQL , 后面有空格!
return getEqualString(key, column, value, rawSQL);
}
}
@JSONField(serialize = false)
public String getEqualString(String key, String column, Object value, String rawSQL) throws Exception {
if (value != null && JSON.isBooleanOrNumberOrString(value) == false && value instanceof Subquery == false) {
throw new IllegalArgumentException(key + ":value 中value不合法!非PUT请求只支持 [Boolean, Number, String] 内的类型 !");
}
boolean not = column.endsWith("!"); // & | 没有任何意义,写法多了不好控制
if (not) {
column = column.substring(0, column.length() - 1);
}
if (StringUtil.isName(column) == false) {
throw new IllegalArgumentException(key + ":value 中key不合法!不支持 ! 以外的逻辑符 !");
}
String logic = value == null && rawSQL == null ? (not ? SQL.IS_NOT : SQL.IS) : (not ? " != " : " = ");
return getKey(column) + logic + (value instanceof Subquery ? getSubqueryString((Subquery) value)
: (rawSQL != null ? rawSQL : getValue(key, column, value)));
}
@JSONField(serialize = false)
public String getCompareString(String key, String column, Object value, String type, String rawSQL) throws Exception {
if (value != null && JSON.isBooleanOrNumberOrString(value) == false && value instanceof Subquery == false) {
throw new IllegalArgumentException(key + ":value 中 value 不合法!比较运算 [>, <, >=, <=] 只支持 [Boolean, Number, String] 内的类型 !");
}
if (StringUtil.isName(column) == false) {
throw new IllegalArgumentException(key + ":value 中 key 不合法!比较运算 [>, <, >=, <=] 不支持 [&, !, |] 中任何逻辑运算符 !");
}
return getKey(column) + " " + type + " " + (value instanceof Subquery ? getSubqueryString((Subquery) value)
: (rawSQL != null ? rawSQL : getValue(key, column, value)));
}
public String getKey(String key) {
if (isTest()) {
if (key.contains("'")) { // || key.contains("#") || key.contains("--")) {
throw new IllegalArgumentException("参数 " + key + " 不合法!key 中不允许有单引号 ' !");
}
return getSQLValue(key).toString();
}
Map<String, String> keyMap = getKeyMap();
String expression = keyMap == null ? null : keyMap.get(key);
if (expression == null) {
expression = COLUMN_KEY_MAP == null ? null : COLUMN_KEY_MAP.get(key);
}
if (expression == null) {
return getSQLKey(key);
}
// (name,tag) left(date,4) 等
List<String> raw = getRaw();
return parseSQLExpression(KEY_KEY, expression, raw != null && raw.contains(KEY_KEY), false);
}
public String getSQLKey(String key) {
String q = getQuote();
return (isKeyPrefix() ? getAliasWithQuote() + "." : "") + q + key + q;
}
/**
* 使用prepareStatement预编译,值为 ? ,后续动态set进去
*/
protected Object getValue(@NotNull Object value) {
return getValue(null, null, value);
}
protected List<Object> preparedValueList = new ArrayList<>();
protected Object getValue(String key, String column, Object value) {
if (isPrepared()) {
if (value == null) {
return null;
}
Map<String, String> castMap = getCast();
String type = key == null || castMap == null ? null : castMap.get(key);
// if ("DATE".equalsIgnoreCase(type) && value instanceof Date == false) {
// value = value instanceof Number ? new Date(((Number) value).longValue()) : Date.valueOf((String) value);
// }
// else if ("TIME".equalsIgnoreCase(type) && value instanceof Time == false) {
// value = value instanceof Number ? new Time(((Number) value).longValue()) : Time.valueOf((String) value);
// }
// else if ("TIMESTAMP".equalsIgnoreCase(type) && value instanceof Timestamp == false) {
// value = value instanceof Number ? new Timestamp(((Number) value).longValue()) : Timestamp.valueOf((String) value);
// }
// else if ("ARRAY".equalsIgnoreCase(type) && value instanceof Array == false) {
// value = ((Collection<?>) value).toArray();
// }
// else if (StringUtil.isEmpty(type, true) == false) {
// preparedValueList.add(value);
// return "cast(?" + SQL.AS + type + ")";
// }
preparedValueList.add(value);
return StringUtil.isEmpty(type, true) ? "?" : "cast(?" + SQL.AS + type + ")";
}
return key == null ? getSQLValue(value) : getSQLValue(key, column, value);
}
public Object getSQLValue(String key, String column, @NotNull Object value) {
Map<String, String> castMap = getCast();
String type = key == null || castMap == null ? null : castMap.get(key);
Object val = getSQLValue(value);
return StringUtil.isEmpty(type, true) ? val : "cast(" + val + SQL.AS + type + ")";
}
public Object getSQLValue(@NotNull Object value) {
if (value == null) {
return SQL.NULL;
}
// return (value instanceof Number || value instanceof Boolean)
// && DATABASE_POSTGRESQL.equals(getDatabase()) ? value : "'" + value + "'";
return (value instanceof Number || value instanceof Boolean)
? value : "'" + value.toString().replaceAll("\\'", "\\\\'") + "'"; // MySQL 隐式转换用不了索引
}
@Override
public List<Object> getPreparedValueList() {
return preparedValueList;
}
@Override
public AbstractSQLConfig setPreparedValueList(List<Object> preparedValueList) {
this.preparedValueList = preparedValueList;
return this;
}
//$ search <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**search key match value
* @param key
* @param column
* @param value
* @param rawSQL
* @return {@link #getSearchString(String, String, Object[], int)}
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getSearchString(String key, String column, Object value, String rawSQL) throws IllegalArgumentException {
if (rawSQL != null) {
throw new UnsupportedOperationException("@raw:value 中 "
+ key + " 不合法!@raw 不支持 key$ 这种功能符 !只支持 key, key!, key<, key{} 等比较运算 和 @column, @having !");
}
if (value == null) {
return "";
}
Logic logic = new Logic(column);
column = logic.getKey();
Log.i(TAG, "getSearchString column = " + column);
JSONArray arr = newJSONArray(value);
if (arr.isEmpty()) {
return "";
}
return getSearchString(key, column, arr.toArray(), logic.getType());
}
/**search key match values
* @param key
* @param column
* @param values
* @param type
* @return LOGIC [ key LIKE 'values[i]' ]
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getSearchString(String key, String column, Object[] values, int type) throws IllegalArgumentException {
if (values == null || values.length <= 0) {
return "";
}
String condition = "";
for (int i = 0; i < values.length; i++) {
Object v = values[i];
if (v instanceof String == false) {
throw new IllegalArgumentException(key + ":value 中 value 的类型只能为 String 或 String[]!");
}
if (((String) v).isEmpty()) { // 允许查空格 StringUtil.isEmpty((String) v, true)
throw new IllegalArgumentException(key + ":value 中 value 值 " + v + "是空字符串,没有意义,不允许这样传!");
}
// if (((String) v).contains("%%")) { // 需要通过 %\%% 来模糊搜索 %
// throw new IllegalArgumentException(key + "$:value 中 value 值 " + v + " 中包含 %% !不允许有连续的 % !");
// }
condition += (i <= 0 ? "" : (Logic.isAnd(type) ? AND : OR)) + getLikeString(key, column, (String) v);
}
return getCondition(Logic.isNot(type), condition);
}
/**WHERE key LIKE 'value'
* @param key
* @param column
* @param value
* @return key LIKE 'value'
*/
@JSONField(serialize = false)
public String getLikeString(@NotNull String key, @NotNull String column, String value) {
String k = key.substring(0, key.length() - 1);
char r = k.charAt(k.length() - 1);
char l;
if (r == '%' || r == '_' || r == '?') {
k = k.substring(0, k.length() - 1);
l = k.charAt(k.length() - 1);
if (l == '%' || l == '_' || l == '?') {
if (l == r) {
throw new IllegalArgumentException(key + ":value 中字符 "
+ k + " 不合法!key$:value 中不允许 key 中有连续相同的占位符!");
}
k = k.substring(0, k.length() - 1);
}
else if (l > 0 && StringUtil.isName(String.valueOf(l))) {
l = r;
}
if (l == '?') {
l = 0;
}
if (r == '?') {
r = 0;
}
}
else {
l = r = 0;
}
if (l > 0 || r > 0) {
if (value == null) {
throw new IllegalArgumentException(key + ":value 中 value 为 null!" +
"key$:value 中 value 不能为 null,且类型必须是 String !");
}
value = value.replaceAll("\\\\", "\\\\\\\\");
value = value.replaceAll("\\%", "\\\\%");
value = value.replaceAll("\\_", "\\\\_");
if (l > 0) {
value = l + value;
}
if (r > 0) {
value = value + r;
}
}
return getKey(column) + " LIKE " + getValue(key, column, value);
}
//$ search >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//~ regexp <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**search key match RegExp values
* @param key
* @param column
* @param value
* @param ignoreCase
* @return {@link #getRegExpString(String, String, Object[], int, boolean)}
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getRegExpString(String key, String column, Object value, boolean ignoreCase, String rawSQL)
throws IllegalArgumentException {
if (rawSQL != null) {
throw new UnsupportedOperationException("@raw:value 中 " + key + " 不合法!@raw 不支持 key~ 这种功能符 !" +
"只支持 key, key!, key<, key{} 等比较运算 和 @column, @having !");
}
if (value == null) {
return "";
}
Logic logic = new Logic(column);
column = logic.getKey();
Log.i(TAG, "getRegExpString column = " + column);
JSONArray arr = newJSONArray(value);
if (arr.isEmpty()) {
return "";
}
return getRegExpString(key, column, arr.toArray(), logic.getType(), ignoreCase);
}
/**search key match RegExp values
* @param key
* @param values
* @param type
* @param ignoreCase
* @return LOGIC [ key REGEXP 'values[i]' ]
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getRegExpString(String key, String column, Object[] values, int type, boolean ignoreCase)
throws IllegalArgumentException {
if (values == null || values.length <= 0) {
return "";
}
String condition = "";
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof String == false) {
throw new IllegalArgumentException(key + ":value 中value的类型只能为String或String[]!");
}
condition += (i <= 0 ? "" : (Logic.isAnd(type) ? AND : OR))
+ getRegExpString(key, column, (String) values[i], ignoreCase);
}
return getCondition(Logic.isNot(type), condition);
}
/**WHERE key REGEXP 'value'
* @param key
* @param value
* @param ignoreCase
* @return key REGEXP 'value'
*/
@JSONField(serialize = false)
public String getRegExpString(String key, String column, String value, boolean ignoreCase) {
if (isPostgreSQL() || isInfluxDB()) {
return getKey(column) + " ~" + (ignoreCase ? "* " : " ") + getValue(key, column, value);
}
if (isOracle() || isDameng() || isKingBase() || (isMySQL() && getDBVersionNums()[0] >= 8)) {
return "regexp_like(" + getKey(column) + ", " + getValue(key, column, value) + (ignoreCase ? ", 'i'" : ", 'c'") + ")";
}
if (isPresto() || isTrino()) {
return "regexp_like(" + (ignoreCase ? "lower(" : "") + getKey(column) + (ignoreCase ? ")" : "")
+ ", " + (ignoreCase ? "lower(" : "") + getValue(key, column, value) + (ignoreCase ? ")" : "") + ")";
}
if (isClickHouse()) {
return "match(" + (ignoreCase ? "lower(" : "") + getKey(column) + (ignoreCase ? ")" : "")
+ ", " + (ignoreCase ? "lower(" : "") + getValue(key, column, value) + (ignoreCase ? ")" : "") + ")";
}
if (isElasticsearch()) {
return getKey(column) + " RLIKE " + getValue(key, column, value);
}
if (isHive()) {
return (ignoreCase ? "lower(" : "") + getKey(column) + (ignoreCase ? ")" : "")
+ " REGEXP " + (ignoreCase ? "lower(" : "") + getValue(key, column, value) + (ignoreCase ? ")" : "");
}
return getKey(column) + " REGEXP " + (ignoreCase ? "" : "BINARY ") + getValue(key, column, value);
}
//~ regexp >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//% between <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**WHERE key BETWEEN 'start' AND 'end'
* @param key
* @param value 'start,end'
* @return LOGIC [ key BETWEEN 'start' AND 'end' ]
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getBetweenString(String key, String column, Object value, String rawSQL) throws IllegalArgumentException {
if (rawSQL != null) {
throw new UnsupportedOperationException("@raw:value 中 " + key + " 不合法!@raw 不支持 key% 这种功能符 !" +
"只支持 key, key!, key<, key{} 等比较运算 和 @column, @having !");
}
if (value == null) {
return "";
}
Logic logic = new Logic(column);
column = logic.getKey();
Log.i(TAG, "getBetweenString column = " + column);
JSONArray arr = newJSONArray(value);
if (arr.isEmpty()) {
return "";
}
return getBetweenString(key, column, arr.toArray(), logic.getType());
}
/**WHERE key BETWEEN 'start' AND 'end'
* @param key
* @param column
* @param values ['start,end'] TODO 在 '1,2' 和 ['1,2', '3,4'] 基础上新增支持 [1, 2] 和 [[1,2], [3,4]] ?
* @param type
* @return LOGIC [ key BETWEEN 'start' AND 'end' ]
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getBetweenString(String key, String column, Object[] values, int type) throws IllegalArgumentException {
if (values == null || values.length <= 0) {
return "";
}
String condition = "";
String[] vs;
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof String == false) {
throw new IllegalArgumentException(key + ":value 中 value 的类型只能为 String 或 String[] !");
}
vs = StringUtil.split((String) values[i]);
if (vs == null || vs.length != 2) {
throw new IllegalArgumentException(key + ":value 中 value 不合法!类型为 String 时必须包括1个逗号 , " +
"且左右两侧都有值!类型为 String[] 里面每个元素要符合前面类型为 String 的规则 !");
}
condition += (i <= 0 ? "" : (Logic.isAnd(type) ? AND : OR))
+ "(" + getBetweenString(key, column, vs[0], (Object) vs[1]) + ")";
}
return getCondition(Logic.isNot(type), condition);
}
/**WHERE key BETWEEN 'start' AND 'end'
* @return key
* @param column
* @param start
* @param end
* @return LOGIC [ key BETWEEN 'start' AND 'end' ]
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getBetweenString(String key, String column, Object start, Object end) throws IllegalArgumentException {
if (JSON.isBooleanOrNumberOrString(start) == false || JSON.isBooleanOrNumberOrString(end) == false) {
throw new IllegalArgumentException(key + ":value 中 value 不合法!类型为 String 时必须包括1个逗号 , " +
"且左右两侧都有值!类型为 String[] 里面每个元素要符合前面类型为 String 的规则 !");
}
return getKey(column) + " BETWEEN " + getValue(key, column, start) + AND + getValue(key, column, end);
}
//% between >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//{} range <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**WHERE key > 'key0' AND key <= 'key1' AND ...
* @param key
* @param range "condition0,condition1..."
* @return key condition0 AND key condition1 AND ...
* @throws Exception
*/
@JSONField(serialize = false)
public String getRangeString(String key, String column, Object range, String rawSQL) throws Exception {
Log.i(TAG, "getRangeString column = " + column);
if (range == null) {//依赖的对象都没有给出有效值,这个存在无意义。如果是客户端传的,那就能在客户端确定了。
throw new NotExistException(TAG + "getRangeString(" + column + ", " + range + ") range == null");
}
Logic logic = new Logic(column);
String k = logic.getKey();
Log.i(TAG, "getRangeString k = " + k);
if (range instanceof List) {
if (rawSQL != null) {
throw new UnsupportedOperationException("@raw:value 的 value 中 " + key + " 不合法!"
+ "Raw SQL 不支持 key{}:[] 这种键值对!");
}
if (logic.isOr() || logic.isNot()) {
List<?> l = (List<?>) range;
if (logic.isNot() && l.isEmpty()) {
return ""; // key!{}: [] 这个条件无效,加到 SQL 语句中 key IN() 会报错,getInString 里不好处理
}
return getKey(k) + getInString(k, column, l.toArray(), logic.isNot());
}
throw new IllegalArgumentException(key + ":[] 中 {} 前面的逻辑运算符错误!只能用'|','!'中的一种 !");
}
else if (range instanceof String) {//非Number类型需要客户端拼接成 < 'value0', >= 'value1'这种
String condition = "";
String[] cs = rawSQL != null ? null : StringUtil.split((String) range, ";", false);
if (rawSQL != null) {
int index = rawSQL.indexOf("(");
condition = (index >= 0 && index < rawSQL.lastIndexOf(")") ? "" : getKey(k) + " ") + rawSQL;
}
if (cs != null) {
List<String> raw = getRaw();
boolean containRaw = raw == null ? false : raw.contains(key);
String lk = logic.isAnd() ? AND : OR;
for (int i = 0; i < cs.length; i++) {//对函数条件length(key)<=5这种不再在开头加key
String expr = cs[i];
if (expr.length() > 100) {
throw new UnsupportedOperationException(key + ":value 的 value 中字符串 " + expr + " 不合法!"
+ "不允许传超过 100 个字符的函数或表达式!请用 @raw 简化传参!");
}
int index = expr == null ? -1 : expr.indexOf("(");
if (index >= 0) {
expr = parseSQLExpression(key, expr, containRaw, false
, key + ":\"!=null;+3*2<=10;function0(arg0,arg1,...)>1;function1(...)%5<=3...\"");
}
else {
String fk = getKey(k) + " ";
String[] ccs = StringUtil.split(expr, false);
expr = "";
for (int j = 0; j < ccs.length; j++) {
String c = ccs[j];
if ("=null".equals(c)) {
c = SQL.isNull();
}
else if ("!=null".equals(c)) {
c = SQL.isNull(false);
}
else if (isPrepared() && (c.contains("--") || PATTERN_RANGE.matcher(c).matches() == false)) {
throw new UnsupportedOperationException(key + ":value 的 value 中 " + c + " 不合法!"
+ "预编译模式下 key{}:\"condition\" 中 condition 必须 为 =null 或 !=null " +
"或 符合正则表达式 " + PATTERN_RANGE + " !不允许连续减号 -- !不允许空格!");
}
expr += (j <= 0 ? "" : lk) + fk + c;
}
}
condition += ((i <= 0 ? "" : lk) + expr);
}
}
if (condition.isEmpty()) {
return "";
}
return getCondition(logic.isNot(), condition);
}
else if (range instanceof Subquery) {
// 如果在 Parser 解析成 SQL 字符串再引用,没法保证安全性,毕竟可以再通过远程函数等方式来拼接再替代,最后引用的字符串就能注入
return getKey(k) + (logic.isNot() ? NOT : "") + " IN " + getSubqueryString((Subquery) range);
}
throw new IllegalArgumentException(key + ":range 类型为" + range.getClass().getSimpleName()
+ "!range 只能是 用','分隔条件的字符串 或者 可取选项JSONArray!");
}
/**WHERE key IN ('key0', 'key1', ... )
* @param in
* @return IN ('key0', 'key1', ... )
* @throws NotExistException
*/
@JSONField(serialize = false)
public String getInString(String key, String column, Object[] in, boolean not) throws NotExistException {
String condition = "";
if (in != null) {//返回 "" 会导致 id:[] 空值时效果和没有筛选id一样!
for (int i = 0; i < in.length; i++) {
condition += ((i > 0 ? "," : "") + getValue(key, column, in[i]));
}
}
if (condition.isEmpty()) {//条件如果存在必须执行,不能忽略。条件为空会导致出错,又很难保证条件不为空(@:条件),所以还是这样好
throw new NotExistException(TAG + ".getInString(" + key + "," + column + ", [], " + not + ") >> condition.isEmpty() >> IN()");
}
return (not ? NOT : "") + " IN (" + condition + ")";
}
//{} range >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//}{ exists <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**WHERE EXISTS subquery
* 如果合并到 getRangeString,一方面支持不了 [1,2,2] 和 ">1" (转成 EXISTS(SELECT IN ) 需要
* static newSQLConfig,但它不能传入子类实例,除非不是 static),另一方面多了子查询临时表性能会比 IN 差
* @param key
* @param value
* @return EXISTS ALL(SELECT ...)
* @throws NotExistException
*/
@JSONField(serialize = false)
public String getExistsString(String key, String column, Object value, String rawSQL) throws Exception {
if (rawSQL != null) {
throw new UnsupportedOperationException("@raw:value 中 " + key + " 不合法!" +
"@raw 不支持 key}{ 这种功能符 !只支持 key, key!, key<, key{} 等比较运算 和 @column, @having !");
}
if (value == null) {
return "";
}
if (value instanceof Subquery == false) {
throw new IllegalArgumentException(key + ":subquery 类型为" + value.getClass().getSimpleName()
+ "!subquery 只能是 子查询JSONObejct!");
}
Logic logic = new Logic(column);
column = logic.getKey();
Log.i(TAG, "getExistsString column = " + column);
return (logic.isNot() ? NOT : "") + " EXISTS " + getSubqueryString((Subquery) value);
}
//}{ exists >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//<> contain <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**WHERE key contains value
* @param key
* @param value
* @return {@link #getContainString(String, String, Object[], int)}
* @throws NotExistException
*/
@JSONField(serialize = false)
public String getContainString(String key, String column, Object value, String rawSQL) throws IllegalArgumentException {
if (rawSQL != null) {
throw new UnsupportedOperationException("@raw:value 中 " + key + " 不合法!@raw 不支持 key<> 这种功能符 !" +
"只支持 key, key!, key<, key{} 等比较运算 和 @column, @having !");
}
Logic logic = new Logic(column);
column = logic.getKey();
Log.i(TAG, "getContainString column = " + column);
return getContainString(key, column, newJSONArray(value).toArray(), logic.getType());
}
/**WHERE key contains childs TODO 支持 key<>: { "path":"$[0].name", "value": 82001 }
* 或者 key<$[0].name>:82001 或者 key$[0].name<>:82001 ? 还是前者好,key 一旦复杂了,
* 包含 , ; : / [] 等就容易和 @combine 其它功能等冲突
* @param key
* @param childs null ? "" : (empty ? no child : contains childs)
* @param type |, &, !
* @return LOGIC [ ( key LIKE '[" + childs[i] + "]' OR key LIKE '[" + childs[i] + ", %'
* OR key LIKE '%, " + childs[i] + ", %' OR key LIKE '%, " + childs[i] + "]' ) ]
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getContainString(String key, String column, Object[] childs, int type) throws IllegalArgumentException {
boolean not = Logic.isNot(type);
String condition = "";
if (childs != null) {
for (int i = 0; i < childs.length; i++) {
Object c = childs[i];
if (c instanceof Collection) {
throw new IllegalArgumentException(key + ":value 中 value 类型不能为 [JSONArray, Collection] 中的任何一个 !");
}
Object path = "";
if (c instanceof Map) {
path = ((Map<?, ?>) c).get("path");
if (path != null && path instanceof String == false) {
throw new IllegalArgumentException(key + ":{ path:path, value:value } 中 path 类型错误," +
"只能是 $, $.key1, $[0].key2 等符合 SQL 中 JSON 路径的 String !");
}
c = ((Map<?, ?>) c).get("value");
if (c instanceof Collection || c instanceof Map) {
throw new IllegalArgumentException(key + ":{ path:path, value:value } 中 value 类型" +
"不能为 [JSONObject, JSONArray, Collection, Map] 中的任何一个 !");
}
}
condition += (i <= 0 ? "" : (Logic.isAnd(type) ? AND : OR));
if (isPostgreSQL() || isInfluxDB()) {
condition += (getKey(column) + " @> " + getValue(key, column, newJSONArray(c)));
// operator does not exist: jsonb @> character varying "[" + c + "]");
}
else if (isOracle() || isDameng() || isKingBase()) {
condition += ("json_textcontains(" + getKey(column) + ", " + (StringUtil.isEmpty(path, true)
? "'$'" : getValue(key, column, path)) + ", " + getValue(key, column, c == null ? null : c.toString()) + ")");
}
else if (isPresto() || isTrino()) {
condition += ("json_array_contains(cast(" + getKey(column) + " AS VARCHAR), "
+ getValue(key, column, c) + (StringUtil.isEmpty(path, true)
? "" : ", " + getValue(key, column, path)) + ")");
}
else {
String v = c == null ? "null" : (c instanceof Boolean || c instanceof Number ? c.toString() : "\"" + c + "\"");
if (isClickHouse()) {
condition += (condition + "has(JSONExtractArrayRaw(assumeNotNull(" + getKey(column) + "))"
+ ", " + getValue(key, column, v) + (StringUtil.isEmpty(path, true)
? "" : ", " + getValue(key, column, path)) + ")");
}
else {
condition += ("json_contains(" + getKey(column) + ", " + getValue(key, column, v)
+ (StringUtil.isEmpty(path, true) ? "" : ", " + getValue(key, column, path)) + ")");
}
}
}
if (condition.isEmpty()) {
condition = getKey(column) + SQL.isNull(true) + OR + getLikeString(key, column, "[]"); // key = '[]' 无结果!
}
else {
condition = getKey(column) + SQL.isNull(false) + AND + "(" + condition + ")";
}
}
if (condition.isEmpty()) {
return "";
}
return getCondition(not, condition);
}
//<> contain >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//key@:{} Subquery <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**
* 只要 method != RequestMethod.POST 就都支持 with-as表达式
* @param cfg
* @param subquery
* @return
* @throws Exception
*/
private String withAsExpreSubqueryString(SQLConfig cfg, Subquery subquery) throws Exception {
boolean isWithAsEnable = isWithAsEnable();
List<String> list = isWithAsEnable ? getWithAsExprSqlList() : null;
if (cfg.getMethod() != RequestMethod.POST && list == null) {
clearWithAsExprListIfNeed();
}
String quote = getQuote();
String withAsExpreSql;
if (list != null) {
String withQuoteName = quote + subquery.getKey() + quote;
list.add(" " + withQuoteName + " AS " + "(" + cfg.getSQL(isPrepared()) + ") ");
withAsExpreSql = " SELECT * FROM " + withQuoteName;
// 预编译参数 FIXME 这里重复添加了,导致子查询都报错参数超过 ? 数量 Parameter index out of range (5 > number of parameters, which is 4)
List<Object> subPvl = cfg.getPreparedValueList();
if (subPvl != null && subPvl.isEmpty() == false) {
List<Object> valueList = getWithAsExprPreparedValueList();
if (valueList == null) {
valueList = new ArrayList<>();
}
valueList.addAll(subPvl);
setWithAsExprPreparedValueList(valueList);
cfg.setPreparedValueList(new ArrayList<>());
}
} else {
withAsExpreSql = cfg.getSQL(isPrepared());
// mysql 才存在这个问题, 主表和子表是一张表
if (isWithAsEnable && isMySQL() && StringUtil.equals(getTable(), subquery.getFrom())) {
withAsExpreSql = " SELECT * FROM (" + withAsExpreSql + ") AS " + quote + subquery.getKey() + quote;
}
}
return withAsExpreSql;
}
@Override
public String getSubqueryString(Subquery subquery) throws Exception {
if (subquery == null) {
return "";
}
String range = subquery.getRange();
SQLConfig cfg = subquery.getConfig();
// 子查询 = 主语句 datasource
if(StringUtil.equals(this.getTable(), subquery.getFrom() ) == false && cfg.hasJoin() == false) {
cfg.setDatasource(this.getDatasource());
}
cfg.setPreparedValueList(new ArrayList<>());
String withAsExprSql = withAsExpreSubqueryString(cfg, subquery);
String sql = (range == null || range.isEmpty() ? "" : range) + "(" + withAsExprSql + ") ";
//// SELECT .. FROM(SELECT ..) .. WHERE .. 格式需要把子查询中的预编译值提前
//// 如果外查询 SELECT concat(`name`,?) 这种 SELECT 里也有预编译值,那就不能这样简单反向
//List<Object> subPvl = cfg.getPreparedValueList();
//if (subPvl != null && subPvl.isEmpty() == false) {
// List<Object> pvl = getPreparedValueList();
//
// if (pvl != null && pvl.isEmpty() == false) {
// subPvl.addAll(pvl);
// }
// setPreparedValueList(subPvl);
//}
List<Object> subPvl = cfg.getPreparedValueList();
if (subPvl != null && subPvl.isEmpty() == false) {
List<Object> pvl = getPreparedValueList();
if (pvl == null || pvl.isEmpty()) {
pvl = subPvl;
}
else {
pvl.addAll(subPvl);
}
setPreparedValueList(pvl);
}
return sql;
}
//key@:{} Subquery >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/**拼接条件
* @param not
* @param condition
* @return
*/
public static String getCondition(boolean not, String condition) {
return getCondition(not, condition, false);
}
/**拼接条件
* @param not
* @param condition
* @param addOuterBracket
* @return
*/
public static String getCondition(boolean not, String condition, boolean addOuterBracket) {
String s = not ? NOT + "(" + condition + ")" : condition;
return addOuterBracket ? "( " + s + " )" : s;
}
/**转为JSONArray
* @param obj
* @return
*/
@NotNull
public static JSONArray newJSONArray(Object obj) {
JSONArray array = new JSONArray();
if (obj != null) {
if (obj instanceof Collection) {
array.addAll((Collection<?>) obj);
} else {
array.add(obj);
}
}
return array;
}
//WHERE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//SET <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**获取SET
* @return
* @throws Exception
*/
@JSONField(serialize = false)
public String getSetString() throws Exception {
return getSetString(getMethod(), getContent(), ! isTest());
}
//CS304 Issue link: https://github.com/Tencent/APIJSON/issues/48
/**获取SET
* @param method -the method used
* @param content -the content map
* @return
* @throws Exception
* <p>use entrySet+getValue() to replace keySet+get() to enhance efficiency</p>
*/
@JSONField(serialize = false)
public String getSetString(RequestMethod method, Map<String, Object> content, boolean verifyName) throws Exception {
Set<String> set = content == null ? null : content.keySet();
String setString = "";
if (set != null && set.size() > 0) {
boolean isFirst = true;
int keyType;// 0 - =; 1 - +, 2 - -
Object value;
String idKey = getIdKey();
for (Entry<String,Object> entry : content.entrySet()) {
String key = entry.getKey();
//避免筛选到全部 value = key == null ? null : content.get(key);
if (key == null || idKey.equals(key)) {
continue;
}
if (key.endsWith("+")) {
keyType = 1;
} else if (key.endsWith("-")) {
keyType = 2;
} else {
keyType = 0; //注意重置类型,不然不该加减的字段会跟着加减
}
value = entry.getValue();
String column = getRealKey(method, key, false, true, verifyName);
setString += (isFirst ? "" : ", ") + (getKey(column) + " = "
+ (keyType == 1 ? getAddString(key, column, value) : (keyType == 2
? getRemoveString(key, column, value) : getValue(key, column, value)) )
);
isFirst = false;
}
}
if (setString.isEmpty()) {
throw new IllegalArgumentException("PUT 请求必须在Table内设置要修改的 key:value !");
}
return (isClickHouse()?" ":" SET ") + setString;
}
/**SET key = concat(key, 'value')
* @param key
* @param value
* @return concat(key, 'value')
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getAddString(String key, String column, Object value) throws IllegalArgumentException {
if (value instanceof Number) {
return getKey(column) + " + " + value;
}
if (value instanceof String) {
return SQL.concat(getKey(column), (String) getValue(key, column, value));
}
throw new IllegalArgumentException(key + ":value 中 value 类型错误,必须是 Number,String,Array 中的任何一种!");
}
/**SET key = replace(key, 'value', '')
* @param key
* @param value
* @return REPLACE (key, 'value', '')
* @throws IllegalArgumentException
*/
@JSONField(serialize = false)
public String getRemoveString(String key, String column, Object value) throws IllegalArgumentException {
if (value instanceof Number) {
return getKey(column) + " - " + value;
}
if (value instanceof String) {
return SQL.replace(getKey(column), (String) getValue(key, column, value), "''");
// " replace(" + column + ", '" + value + "', '') ";
}
throw new IllegalArgumentException(key + ":value 中 value 类型错误,必须是 Number,String,Array 中的任何一种!");
}
//SET >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@Override
public boolean isFakeDelete() {
return false;
}
@Override
public Map<String, Object> onFakeDelete(Map<String, Object> map) {
return map;
}
/**
* @return
* @throws Exception
*/
@JSONField(serialize = false)
@Override
public String getSQL(boolean prepared) throws Exception {
boolean isPrepared = isPrepared();
if (isPrepared == prepared) {
return getSQL(this);
}
String sql = getSQL(this.setPrepared(prepared));
setPrepared(isPrepared);
return sql;
}
/**
* @param config
* @return
* @throws Exception
*/
public static String getSQL(AbstractSQLConfig config) throws Exception {
if (config == null) {
Log.i(TAG, "getSQL config == null >> return null;");
return null;
}
// TODO procedure 改为 List<Procedure> procedureList; behind : true; function: callFunction(); String key; ...
// for (...) { Call procedure1();\n SQL \n; Call procedure2(); ... }
// 貌似不需要,因为 ObjectParser 里就已经处理的顺序等,只是这里要解决下 Schema 问题。
String procedure = config.getProcedure();
if (StringUtil.isNotEmpty(procedure, true)) {
int ind = procedure.indexOf(".");
boolean hasPrefix = ind >= 0 && ind < procedure.indexOf("(");
String sch = hasPrefix ? AbstractFunctionParser.extractSchema(
procedure.substring(0, ind), config.getTable()
) : config.getSQLSchema();
String q = config.getQuote();
return "CALL " + q + sch + q + "." + (hasPrefix ? procedure.substring(ind + 1) : procedure);
}
String tablePath = config.getTablePath();
if (StringUtil.isNotEmpty(tablePath, true) == false) {
Log.i(TAG, "getSQL StringUtil.isNotEmpty(tablePath, true) == false >> return null;");
return null;
}
// 解决重复添加导致报错:Parameter index out of range (6 > number of parameters, which is 5)
config.setPreparedValueList(new ArrayList<>());
String cSql = null;
switch (config.getMethod()) {
case POST:
return "INSERT INTO " + tablePath + config.getColumnString() + " VALUES" + config.getValuesString();
case PUT:
if(config.isClickHouse()){
return "ALTER TABLE " + tablePath + " UPDATE" + config.getSetString() + config.getWhereString(true);
}
cSql = "UPDATE " + tablePath + config.getSetString() + config.getWhereString(true)
+ (config.isMySQL() ? config.getLimitString() : "");
cSql = buildWithAsExprSql(config, cSql);
return cSql;
case DELETE:
if(config.isClickHouse()){
return "ALTER TABLE " + tablePath + " DELETE" + config.getWhereString(true);
}
cSql = "DELETE FROM " + tablePath + config.getWhereString(true)
+ (config.isMySQL() ? config.getLimitString() : ""); // PostgreSQL 不允许 LIMIT
cSql = buildWithAsExprSql(config, cSql);
return cSql;
default:
String explain = config.isExplain() ? (config.isSQLServer() ? "SET STATISTICS PROFILE ON "
: (config.isOracle() || config.isDameng() || config.isKingBase() ? "EXPLAIN PLAN FOR " : "EXPLAIN ")) : "";
if (config.isTest() && RequestMethod.isGetMethod(config.getMethod(), true)) { // FIXME 为啥是 code 而不是 count ?
String q = config.getQuote(); // 生成 SELECT ( (24 >=0 AND 24 <3) ) AS `code` LIMIT 1 OFFSET 0
return explain + "SELECT " + config.getWhereString(false)
+ " AS " + q + JSONResponse.KEY_COUNT + q + config.getLimitString();
}
config.setPreparedValueList(new ArrayList<Object>());
String column = config.getColumnString();
if (config.isOracle() || config.isDameng() || config.isKingBase()) {
//When config's database is oracle,Using subquery since Oracle12 below does not support OFFSET FETCH paging syntax.
//针对oracle分组后条数的统计
if (StringUtil.isNotEmpty(config.getGroup(),true) && RequestMethod.isHeadMethod(config.getMethod(), true)){
return explain + "SELECT count(*) FROM (SELECT " + (config.getCache() == JSONRequest.CACHE_RAM
? "SQL_NO_CACHE " : "") + column + " FROM " + getConditionString(tablePath, config) + ") " + config.getLimitString();
}
String sql = "SELECT " + (config.getCache() == JSONRequest.CACHE_RAM
? "SQL_NO_CACHE " : "") + column + " FROM " + getConditionString(tablePath, config);
return explain + config.getOraclePageSql(sql);
}
cSql = "SELECT " + (config.getCache() == JSONRequest.CACHE_RAM ? "SQL_NO_CACHE " : "")
+ column + " FROM " + getConditionString(tablePath, config) + config.getLimitString();
cSql = buildWithAsExprSql(config, cSql);
if(config.isElasticsearch()) { // elasticSearch 不支持 explain
return cSql;
}
return explain + cSql;
}
}
private static String buildWithAsExprSql(@NotNull AbstractSQLConfig config, String cSql) throws Exception {
if (config.isWithAsEnable() == false) {
return cSql;
}
List<String> list = config.getWithAsExprSqlList();
int size = list == null ? 0 : list.size();
if (size > 0) {
String withAsExpreSql = "WITH ";
for (int i = 0; i < size; i++) {
withAsExpreSql += (i <= 0 ? "" : ",") + list.get(i) + "\n";
}
cSql = withAsExpreSql + cSql;
config.clearWithAsExprListIfNeed();
}
return cSql;
}
@Override
public boolean isWithAsEnable() {
return ENABLE_WITH_AS && (isMySQL() == false || getDBVersionNums()[0] >= 8);
}
/**Oracle的分页获取
* @param sql
* @return
*/
protected String getOraclePageSql(String sql) {
int count = getCount();
if (count <= 0 || RequestMethod.isHeadMethod(getMethod(), true)) { // TODO HEAD 真的不需要 LIMIT ?
return sql;
}
int offset = getOffset(getPage(), count);
String alias = getAliasWithQuote();
String quote = getQuote();
return "SELECT * FROM (SELECT " + alias + ".*, ROWNUM "+ quote + "RN" + quote +" FROM (" + sql + ") " + alias
+ " WHERE ROWNUM <= " + (offset + count) + ") WHERE "+ quote + "RN" + quote +" > " + offset;
}
/**获取条件SQL字符串
* @param table
* @param config
* @return
* @throws Exception
*/
private static String getConditionString(String table, AbstractSQLConfig config) throws Exception {
Subquery from = config.getFrom();
if (from != null) {
table = config.getSubqueryString(from) + " AS " + config.getAliasWithQuote() + " ";
}
String join = config.getJoinString();
String where = config.getWhereString(true);
//根据方法不同,聚合语句不同。GROUP BY 和 HAVING 可以加在 HEAD 上, HAVING 可以加在 PUT, DELETE 上,GET 全加,POST 全都不加
String aggregation;
if (RequestMethod.isGetMethod(config.getMethod(), true)) {
aggregation = config.getGroupString(true) + config.getHavingString(true)
+ config.getOrderString(true);
}
else if (RequestMethod.isHeadMethod(config.getMethod(), true)) {
// TODO 加参数 isPagenation 判断是 GET 内分页 query:2 查总数,不用加这些条件
aggregation = config.getGroupString(true) + config.getHavingString(true) ;
}
else if (config.getMethod() == PUT || config.getMethod() == DELETE) {
aggregation = config.getHavingString(true) ;
}
else {
aggregation = "";
}
String condition = table + join + where + aggregation;
; //+ config.getLimitString();
//no need to optimize
// if (config.getPage() <= 0 || ID.equals(column.trim())) {
return condition; // config.isOracle() ? condition : condition + config.getLimitString();
// }
//
//
// //order: id+ -> id >= idOfStartIndex; id- -> id <= idOfStartIndex <<<<<<<<<<<<<<<<<<<
// String order = StringUtil.getNoBlankString(config.getOrder());
// List<String> orderList = order.isEmpty() ? null : Arrays.asList(StringUtil.split(order));
//
// int type = 0;
// if (BaseModel.isEmpty(orderList) || BaseModel.isContain(orderList, ID+"+")) {
// type = 1;
// }
// else if (BaseModel.isContain(orderList, ID+"-")) {
// type = 2;
// }
//
// if (type > 0) {
// return condition.replace("WHERE",
// "WHERE id " + (type == 1 ? ">=" : "<=") + " (SELECT id FROM " + table
// + where + " ORDER BY id " + (type == 1 ? "ASC" : "DESC") + " LIMIT " + config.getOffset() + ", 1) AND"
// )
// + " LIMIT " + config.getCount(); //子查询起始id不一定准确,只能作为最小可能! ;//
// }
// //order: id+ -> id >= idOfStartIndex; id- -> id <= idOfStartIndex >>>>>>>>>>>>>>>>>>
//
//
// //结果错误!SELECT * FROM User AS t0 INNER JOIN
// (SELECT id FROM User ORDER BY date ASC LIMIT 20, 10) AS t1 ON t0.id = t1.id
// //common case, inner join
// condition += config.getLimitString();
// return table + " AS t0 INNER JOIN (SELECT id FROM " + condition + ") AS t1 ON t0.id = t1.id";
}
private boolean keyPrefix;
@Override
public boolean isKeyPrefix() {
return keyPrefix;
}
@Override
public AbstractSQLConfig setKeyPrefix(boolean keyPrefix) {
this.keyPrefix = keyPrefix;
return this;
}
public String getJoinString() throws Exception {
String joinOns = "";
if (joinList != null) {
String quote = getQuote();
List<Object> pvl = getPreparedValueList(); // new ArrayList<>();
//boolean changed = false;
// 主表不用别名 String ta;
for (Join j : joinList) {
onGetJoinString(j);
if (j.isAppJoin()) { // APP JOIN,只是作为一个标记,执行完主表的查询后自动执行副表的查询 User.id IN($commentIdList)
continue;
}
String type = j.getJoinType();
//LEFT JOIN sys.apijson_user AS User ON User.id = Moment.userId, 都是用 = ,通过relateType处理缓存
// <"INNER JOIN User ON User.id = Moment.userId", UserConfig> TODO AS 放 getSQLTable 内
SQLConfig jc = j.getJoinConfig();
jc.setPrepared(isPrepared());
// 将关联表所属数据源配置为主表数据源
jc.setDatasource(this.getDatasource());
String jt = StringUtil.isEmpty(jc.getAlias(), true) ? jc.getTable() : jc.getAlias();
List<On> onList = j.getOnList();
//如果要强制小写,则可在子类重写这个方法再 toLowerCase
// if (DATABASE_POSTGRESQL.equals(getDatabase())) {
// jt = jt.toLowerCase();
// tn = tn.toLowerCase();
// }
String sql;
switch (type) {
//前面已跳过 case "@": // APP JOIN
// continue;
case "*": // CROSS JOIN
onGetCrossJoinString(j);
case "<": // LEFT JOIN
case ">": // RIGHT JOIN
jc.setMain(true).setKeyPrefix(false);
sql = ( "<".equals(type) ? " LEFT" : (">".equals(type) ? " RIGHT" : " CROSS") )
+ " JOIN ( " + jc.getSQL(isPrepared()) + " ) AS " + quote + jt + quote;
sql = concatJoinOn(sql, quote, j, jt, onList);
jc.setMain(false).setKeyPrefix(true);
pvl.addAll(jc.getPreparedValueList());
//changed = true;
break;
case "&": // INNER JOIN: A & B
case "": // FULL JOIN: A | B
case "|": // FULL JOIN: A | B
case "!": // OUTER JOIN: ! (A | B)
case "^": // SIDE JOIN: ! (A & B)
case "(": // ANTI JOIN: A & ! B
case ")": // FOREIGN JOIN: B & ! A
sql = " INNER JOIN " + jc.getTablePath();
sql = concatJoinOn(sql, quote, j, jt, onList);
break;
default:
throw new UnsupportedOperationException(
"join:value 中 value 里的 " + jt + "/" + j.getPath()
+ "错误!不支持 " + jt + " 等 [ @ APP, < LEFT, > RIGHT, * CROSS"
+ ", & INNER, | FULL, ! OUTER, ^ SIDE, ( ANTI, ) FOREIGN ] 之外的 JOIN 类型 !"
);
}
SQLConfig oc = j.getOuterConfig();
String ow = null;
if (oc != null) {
oc.setPrepared(isPrepared());
oc.setPreparedValueList(new ArrayList<>());
oc.setMain(false).setKeyPrefix(true);
ow = oc.getWhereString(false);
pvl.addAll(oc.getPreparedValueList());
//changed = true;
}
joinOns += " \n " + sql + (StringUtil.isEmpty(ow, true) ? "" : " AND ( " + ow + " ) ");
}
//if (changed) {
// List<Object> opvl = getPreparedValueList();
// if (opvl != null && opvl.isEmpty() == false) {
// pvl.addAll(opvl);
// }
setPreparedValueList(pvl);
//}
}
return StringUtil.isEmpty(joinOns, true) ? "" : joinOns + " \n";
}
protected String concatJoinOn(@NotNull String sql, @NotNull String quote, @NotNull Join j, @NotNull String jt, List<On> onList) {
if (onList != null) {
boolean first = true;
for (On on : onList) {
Logic logic = on.getLogic();
boolean isNot = logic == null ? false : logic.isNot();
if (isNot) {
onJoinNotRelation(sql, quote, j, jt, onList, on);
}
String rt = on.getRelateType();
if (StringUtil.isEmpty(rt, false)) {
sql += (first ? ON : AND) + quote + jt + quote + "." + quote + on.getKey() + quote + (isNot ? " != " : " = ")
+ quote + on.getTargetTable() + quote + "." + quote + on.getTargetKey() + quote;
}
else {
onJoinComplexRelation(sql, quote, j, jt, onList, on);
if (">=".equals(rt) || "<=".equals(rt) || ">".equals(rt) || "<".equals(rt)) {
if (isNot) {
throw new IllegalArgumentException("join:value 中 value 里的 " + jt + "/" + j.getPath()
+ " 中 JOIN ON 条件关联逻辑符 " + rt + " 不合法! >, <, >=, <= 不支持与或非逻辑符 & | ! !");
}
sql += (first ? ON : AND) + quote + jt + quote + "." + quote + on.getKey() + quote + " " + rt + " "
+ quote + on.getTargetTable() + quote + "." + quote + on.getTargetKey() + quote;
}
else if (rt.endsWith("$")) {
String t = rt.substring(0, rt.length() - 1);
char r = t.isEmpty() ? 0 : t.charAt(t.length() - 1);
char l;
if (r == '%' || r == '_' || r == '?') {
t = t.substring(0, t.length() - 1);
if (t.isEmpty()) {
if (r == '?') {
throw new IllegalArgumentException(on.getOriginKey() + ":value 中字符 " + on.getOriginKey()
+ " 不合法!key$:value 中不允许只有单独的 '?',必须和 '%', '_' 之一配合使用 !");
}
l = r;
}
else {
l = t.charAt(t.length() - 1);
if (l == '%' || l == '_' || l == '?') {
if (l == r) {
throw new IllegalArgumentException(on.getOriginKey()
+ ":value 中字符 " + t + " 不合法!key$:value 中不允许 key 中有连续相同的占位符!");
}
t = t.substring(0, t.length() - 1);
}
else if (l > 0 && StringUtil.isName(String.valueOf(l))) {
l = r;
}
}
if (l == '?') {
l = 0;
}
if (r == '?') {
r = 0;
}
}
else {
l = r = 0;
}
if (l <= 0 && r <= 0) {
sql += (first ? ON : AND) + quote + jt + quote + "." + quote + on.getKey() + quote + (isNot ? NOT : "")
+ " LIKE " + quote + on.getTargetTable() + quote + "." + quote + on.getTargetKey() + quote;
}
else {
sql += (first ? ON : AND) + quote + jt + quote + "." + quote + on.getKey() + quote + (isNot ? NOT : "")
+ (l <= 0 ? " LIKE concat(" : " LIKE concat('" + l + "', ") + quote + on.getTargetTable() + quote
+ "." + quote + on.getTargetKey() + quote + (r <= 0 ? ")" : ", '" + r + "')");
}
}
else if (rt.endsWith("~")) {
boolean ignoreCase = "*~".equals(rt);
if (isPostgreSQL() || isInfluxDB()) {
sql += (first ? ON : AND) + quote + jt + quote + "." + quote + on.getKey() + quote
+ (isNot ? NOT : "") + " ~" + (ignoreCase ? "* " : " ")
+ quote + on.getTargetTable() + quote + "." + quote + on.getTargetKey() + quote;
}
else if (isOracle() || isDameng() || isKingBase()) {
sql += (first ? ON : AND) + "regexp_like(" + quote + jt + quote + "." + quote + on.getKey() + quote
+ ", " + quote + on.getTargetTable() + quote + "." + quote + on.getTargetKey() + quote
+ (ignoreCase ? ", 'i'" : ", 'c'") + ")";
}
else if (isPresto() || isTrino()) {
sql += (first ? ON : AND) + "regexp_like(" + (ignoreCase ? "lower(" : "") + quote
+ jt + quote + "." + quote + on.getKey() + quote + (ignoreCase ? ")" : "")
+ ", " + (ignoreCase ? "lower(" : "") + quote + on.getTargetTable()
+ quote + "." + quote + on.getTargetKey() + quote + (ignoreCase ? ")" : "") + ")";
}
else if (isClickHouse()) {
sql += (first ? ON : AND) + "match(" + (ignoreCase ? "lower(" : "") + quote + jt
+ quote + "." + quote + on.getKey() + quote + (ignoreCase ? ")" : "")
+ ", " + (ignoreCase ? "lower(" : "") + quote + on.getTargetTable()
+ quote + "." + quote + on.getTargetKey() + quote + (ignoreCase ? ")" : "") + ")";
}
else if (isElasticsearch()) {
sql += (first ? ON : AND) + quote + jt + quote + "." + quote + on.getKey() + quote + (isNot ? NOT : "")
+ " RLIKE " + quote + on.getTargetTable() + quote + "." + quote + on.getTargetKey() + quote;
}
else if (isHive()) {
sql += (first ? ON : AND) + (ignoreCase ? "lower(" : "") + quote + jt + quote + "." + quote + on.getKey() + quote + (ignoreCase ? ")" : "")
+ " REGEXP " + (ignoreCase ? "lower(" : "") + quote + on.getTargetTable()
+ quote + "." + quote + on.getTargetKey() + quote + (ignoreCase ? ")" : "");
}
else {
sql += (first ? ON : AND) + quote + jt + quote + "." + quote + on.getKey() + quote + (isNot ? NOT : "")
+ " REGEXP " + (ignoreCase ? "" : "BINARY ")
+ quote + on.getTargetTable() + quote + "." + quote + on.getTargetKey() + quote;
}
}
else if ("{}".equals(rt) || "<>".equals(rt)) {
String tt = on.getTargetTable();
String ta = on.getTargetAlias();
Map<String, String> cast = null;
if (tt.equals(getTable()) && ((ta == null && getAlias() == null) || ta.equals(getAlias()))) {
cast = getCast();
}
else {
boolean find = false;
for (Join jn : joinList) {
if (tt.equals(jn.getTable()) && ((ta == null && jn.getAlias() == null) || ta.equals(jn.getAlias()))) {
cast = getCast();
find = true;
break;
}
}
if (find == false) {
throw new IllegalArgumentException("join:value 中 value 里的 " + jt + "/" + j.getPath()
+ " 中 JOIN ON 条件中找不到对应的 " + rt + " 不合法!只支持 =, {}, <> 这几种!");
}
}
boolean isBoolOrNum = SQL.isBooleanOrNumber(cast == null ? null : cast.get(on.getTargetKey()));
String arrKeyPath;
String itemKeyPath;
if ("{}".equals(rt)) {
arrKeyPath = quote + on.getTargetTable() + quote + "." + quote + on.getTargetKey() + quote;
itemKeyPath = quote + jt + quote + "." + quote + on.getKey() + quote;
}
else {
arrKeyPath = quote + jt + quote + "." + quote + on.getKey() + quote;
itemKeyPath = quote + on.getTargetTable() + quote + "." + quote + on.getTargetKey() + quote;
}
if (isPostgreSQL() || isInfluxDB()) { //operator does not exist: jsonb @> character varying "[" + c + "]");
sql += (first ? ON : AND) + (isNot ? "( " : "") + getCondition(isNot, arrKeyPath
+ " IS NOT NULL AND " + arrKeyPath + " @> " + itemKeyPath) + (isNot ? ") " : "");
}
else if (isOracle() || isDameng() || isKingBase()) {
sql += (first ? ON : AND) + (isNot ? "( " : "") + getCondition(isNot, arrKeyPath
+ " IS NOT NULL AND json_textcontains(" + arrKeyPath
+ ", '$', " + itemKeyPath + ")") + (isNot ? ") " : "");
}
else if (isPresto() || isTrino()) {
sql += (first ? ON : AND) + (isNot ? "( " : "") + getCondition(isNot, arrKeyPath
+ " IS NOT NULL AND json_array_contains(cast(" + arrKeyPath
+ " AS VARCHAR), " + itemKeyPath + ")") + (isNot ? ") " : "");
}
else if (isClickHouse()) {
sql += (first ? ON : AND) + (isNot ? "( " : "") + getCondition(isNot, arrKeyPath
+ " IS NOT NULL AND has(JSONExtractArrayRaw(assumeNotNull(" + arrKeyPath + "))"
+ ", " + itemKeyPath + ")") + (isNot ? ") " : "");
}
else {
sql += (first ? ON : AND) + (isNot ? "( " : "") + getCondition(isNot, arrKeyPath
+ " IS NOT NULL AND json_contains(" + arrKeyPath
+ (isBoolOrNum ? ", cast(" + itemKeyPath + " AS CHAR), '$')"
: ", concat('\"', " + itemKeyPath + ", '\"'), '$')"
)
) + (isNot ? ") " : "");
}
}
else {
throw new IllegalArgumentException("join:value 中 value 里的 " + jt + "/" + j.getPath()
+ " 中 JOIN ON 条件关联类型 " + rt + " 不合法!只支持 =, >, <, >=, <=, !=, $, ~, {}, <> 这几种!");
}
}
first = false;
}
}
return sql;
}
protected void onJoinNotRelation(String sql, String quote, Join join, String table, List<On> onList, On on) {
throw new UnsupportedOperationException("JOIN 已禁用 '!' 非逻辑连接符 !性能很差、需求极少,如要取消禁用可在后端重写相关方法!");
}
protected void onJoinComplexRelation(String sql, String quote, Join join, String table, List<On> onList, On on) {
throw new UnsupportedOperationException("JOIN 已禁用 $, ~, {}, <>, >, <, >=, <= 等复杂关联 !" +
"性能很差、需求极少,默认只允许 = 等价关联,如要取消禁用可在后端重写相关方法!");
}
protected void onGetJoinString(Join join) throws UnsupportedOperationException {
}
protected void onGetCrossJoinString(Join join) throws UnsupportedOperationException {
throw new UnsupportedOperationException("已禁用 * CROSS JOIN !性能很差、需求极少,如要取消禁用可在后端重写相关方法!");
}
/**新建SQL配置
* @param table
* @param request
* @param joinList
* @param isProcedure
* @param callback
* @return
* @throws Exception
*/
public static <T extends Object> SQLConfig<T> newSQLConfig(RequestMethod method, String table, String alias
, JSONObject request, List<Join> joinList, boolean isProcedure, Callback<T> callback) throws Exception {
if (request == null) { // User:{} 这种空内容在查询时也有效
throw new NullPointerException(TAG + ": newSQLConfig request == null!");
}
Boolean explain = request.getBoolean(KEY_EXPLAIN);
if (explain != null && explain && Log.DEBUG == false) { // 不在 config.setExplain 抛异常,一方面处理更早性能更好,另一方面为了内部调用可以绕过这个限制
throw new UnsupportedOperationException("非DEBUG模式, 不允许传 " + KEY_EXPLAIN + " !");
}
String database = request.getString(KEY_DATABASE);
if (StringUtil.isEmpty(database, false) == false && DATABASE_LIST.contains(database) == false) {
throw new UnsupportedDataTypeException("@database:value 中 value 错误,只能是 ["
+ StringUtil.getString(DATABASE_LIST.toArray()) + "] 中的一种!");
}
String schema = request.getString(KEY_SCHEMA);
String datasource = request.getString(KEY_DATASOURCE);
SQLConfig<T> config = callback.getSQLConfig(method, database, schema, datasource, table);
config.setAlias(alias);
config.setDatabase(database); // 不删,后面表对象还要用的,必须放在 parseJoin 前
config.setSchema(schema); // 不删,后面表对象还要用的
config.setDatasource(datasource); // 不删,后面表对象还要用的
if (isProcedure) {
return config;
}
config = parseJoin(method, config, joinList, callback); // 放后面会导致主表是空对象时 joinList 未解析
if (request.isEmpty()) { // User:{} 这种空内容在查询时也有效
return config; // request.remove(key); 前都可以直接return,之后必须保证 put 回去
}
// 对 id, id{}, userId, userId{} 处理,这些只要不为 null 就一定会作为 AND 条件 <<<<<<<<<<<<<<<<<<<<<<<<<
String idKey = callback.getIdKey(datasource, database, schema, table);
String idInKey = idKey + "{}";
String userIdKey = callback.getUserIdKey(datasource, database, schema, table);
String userIdInKey = userIdKey + "{}";
Object idIn = request.get(idInKey); // 可能是 id{}:">0"
if (idIn instanceof Collection) { // 排除掉 0, 负数, 空字符串 等无效 id 值
Collection<?> ids = (Collection<?>) idIn;
List<Object> newIdIn = new ArrayList<>();
for (Object d : ids) { // 不用 idIn.contains(id) 因为 idIn 里存到很可能是 Integer,id 又是 Long!
if ((d instanceof Number && ((Number) d).longValue() > 0) || (d instanceof String && StringUtil.isNotEmpty(d, true))) {
if (newIdIn.contains(d) == false) {
newIdIn.add(d);
}
}
}
if (newIdIn.isEmpty()) {
throw new NotExistException(TAG + ": newSQLConfig idIn instanceof List >> 去掉无效 id 后 newIdIn.isEmpty()");
}
idIn = newIdIn;
if (method == DELETE || method == PUT) {
config.setCount(newIdIn.size());
}
}
Object id = request.get(idKey);
if (id == null && method == POST) {
id = callback.newId(method, database, schema, datasource, table); // null 表示数据库自增 id
}
if (id != null) { // null 无效
if (id instanceof Number) {
if (((Number) id).longValue() <= 0) { // 一定没有值
throw new NotExistException(TAG + ": newSQLConfig " + table + ".id <= 0");
}
}
else if (id instanceof String) {
if (StringUtil.isEmpty(id, true)) { // 一定没有值
throw new NotExistException(TAG + ": newSQLConfig StringUtil.isEmpty(" + table + ".id, true)");
}
}
else if (id instanceof Subquery) {}
else {
throw new IllegalArgumentException(idKey + ":value 中 value 的类型只能是 Long , String 或 Subquery !");
}
if (idIn instanceof Collection) { // 共用idIn场景少性能差
boolean contains = false;
Collection<?> idList = ((Collection<?>) idIn);
for (Object d : idList) { // 不用 idIn.contains(id) 因为 idIn 里存到很可能是 Integer,id 又是 Long!
if (d != null && id.toString().equals(d.toString())) {
contains = true;
break;
}
}
if (contains == false) { // empty有效 BaseModel.isEmpty(idIn) == false) {
throw new NotExistException(TAG + ": newSQLConfig idIn != null && (((List<?>) idIn).contains(id) == false");
}
}
if (method == DELETE || method == PUT) {
config.setCount(1);
}
}
// 对 id, id{}, userId, userId{} 处理,这些只要不为 null 就一定会作为 AND 条件 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Object userIdIn = userIdInKey.equals(idInKey) ? null : request.get(userIdInKey); // 可能是 userId{}:">0"
if (userIdIn instanceof Collection) { // 排除掉 0, 负数, 空字符串 等无效 userId 值
Collection<?> userIds = (Collection<?>) userIdIn;
List<Object> newUserIdIn = new ArrayList<>();
for (Object d : userIds) { // 不用 userIdIn.contains(userId) 因为 userIdIn 里存到很可能是 Integer,userId 又是 Long!
if ((d instanceof Number && ((Number) d).longValue() > 0) || (d instanceof String && StringUtil.isNotEmpty(d, true))) {
if (newUserIdIn.contains(d) == false) {
newUserIdIn.add(d);
}
}
}
if (newUserIdIn.isEmpty()) {
throw new NotExistException(TAG + ": newSQLConfig userIdIn instanceof List >> 去掉无效 userId 后 newIdIn.isEmpty()");
}
userIdIn = newUserIdIn;
}
Object userId = userIdKey.equals(idKey) ? null : request.get(userIdKey);
if (userId != null) { // null 无效
if (userId instanceof Number) {
if (((Number) userId).longValue() <= 0) { // 一定没有值
throw new NotExistException(TAG + ": newSQLConfig " + table + ".userId <= 0");
}
}
else if (userId instanceof String) {
if (StringUtil.isEmpty(userId, true)) { // 一定没有值
throw new NotExistException(TAG + ": newSQLConfig StringUtil.isEmpty(" + table + ".userId, true)");
}
}
else if (userId instanceof Subquery) {}
else {
throw new IllegalArgumentException(userIdKey + ":value 中 value 的类型只能是 Long , String 或 Subquery !");
}
if (userIdIn instanceof Collection) { // 共用 userIdIn 场景少性能差
boolean contains = false;
Collection<?> userIds = (Collection<?>) userIdIn;
for (Object d : userIds) { // 不用 userIdIn.contains(userId) 因为 userIdIn 里存到很可能是 Integer,userId 又是 Long!
if (d != null && userId.toString().equals(d.toString())) {
contains = true;
break;
}
}
if (contains == false) { // empty有效 BaseModel.isEmpty(userIdIn) == false) {
throw new NotExistException(TAG + ": newSQLConfig userIdIn != null && (((List<?>) userIdIn).contains(userId) == false");
}
}
}
// 对 id, id{}, userId, userId{} 处理,这些只要不为 null 就一定会作为 AND 条件 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
String role = request.getString(KEY_ROLE);
String cache = request.getString(KEY_CACHE);
Subquery from = (Subquery) request.get(KEY_FROM);
String column = request.getString(KEY_COLUMN);
String nulls = request.getString(KEY_NULL);
String cast = request.getString(KEY_CAST);
String combine = request.getString(KEY_COMBINE);
String group = request.getString(KEY_GROUP);
Object having = request.get(KEY_HAVING);
String havingAnd = request.getString(KEY_HAVING_AND);
String order = request.getString(KEY_ORDER);
Object keyMap = request.get(KEY_KEY);
String raw = request.getString(KEY_RAW);
String json = request.getString(KEY_JSON);
String mthd = request.getString(KEY_METHOD);
try {
// 强制作为条件且放在最前面优化性能
request.remove(idKey);
request.remove(idInKey);
request.remove(userIdKey);
request.remove(userIdInKey);
// 关键词
request.remove(KEY_ROLE);
request.remove(KEY_EXPLAIN);
request.remove(KEY_CACHE);
request.remove(KEY_DATASOURCE);
request.remove(KEY_DATABASE);
request.remove(KEY_SCHEMA);
request.remove(KEY_FROM);
request.remove(KEY_COLUMN);
request.remove(KEY_NULL);
request.remove(KEY_CAST);
request.remove(KEY_COMBINE);
request.remove(KEY_GROUP);
request.remove(KEY_HAVING);
request.remove(KEY_HAVING_AND);
request.remove(KEY_ORDER);
request.remove(KEY_KEY);
request.remove(KEY_RAW);
request.remove(KEY_JSON);
request.remove(KEY_METHOD);
// @null <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
String[] nullKeys = StringUtil.split(nulls);
if (nullKeys != null && nullKeys.length > 0) {
for (String nk : nullKeys) {
if (StringUtil.isEmpty(nk, true)) {
throw new IllegalArgumentException(table + ":{ @null: value } 中的字符 '" + nk + "' 不合法!不允许为空!");
}
if (request.get(nk) != null) {
throw new IllegalArgumentException(table + ":{ @null: value } 中的字符 '"
+ nk + "' 已在当前对象有非 null 值!不允许对同一个 JSON key 设置不同值!");
}
request.put(nk, null);
}
}
// @null >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// @cast <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
String[] casts = StringUtil.split(cast);
Map<String, String> castMap = null;
if (casts != null && casts.length > 0) {
castMap = new HashMap<>(casts.length);
for (String c : casts) {
apijson.orm.Entry<String, String> p = Pair.parseEntry(c);
if (StringUtil.isEmpty(p.getKey(), true)) {
throw new IllegalArgumentException(table + ":{} 里的 @cast: 'key0:type0,key1:type1..' 中 '"
+ c + "' 对应的 key 的字符 '" + p.getKey() + "' 不合法!不允许为空!");
}
if (StringUtil.isName(p.getValue()) == false) {
throw new IllegalArgumentException(table + ":{} 里的 @cast: 'key0:type0,key1:type1..' 中 '"
+ c + "' 对应的 type 的字符 '" + p.getValue() + "' 不合法!必须符合类型名称格式!");
}
if (castMap.get(p.getKey()) != null) {
throw new IllegalArgumentException(table + ":{} 里的 @cast: 'key0:type0,key1:type1..' 中 '"
+ c + "' 对应的 key 的字符 '" + p.getKey() + "' 已存在!不允许重复设置类型!");
}
castMap.put(p.getKey(), p.getValue());
}
}
// @cast >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
String[] rawArr = StringUtil.split(raw);
config.setRaw(rawArr == null || rawArr.length <= 0 ? null : new ArrayList<>(Arrays.asList(rawArr)));
Map<String, Object> tableWhere = new LinkedHashMap<String, Object>(); // 保证顺序好优化 WHERE id > 1 AND name LIKE...
boolean ignoreBlankStr = IGNORE_BLANK_STRING_METHOD_LIST != null && IGNORE_BLANK_STRING_METHOD_LIST.contains(method);
boolean ignoreEmptyStr = ignoreBlankStr || (IGNORE_EMPTY_STRING_METHOD_LIST != null && IGNORE_EMPTY_STRING_METHOD_LIST.contains(method));
boolean ignoreEmptyOrBlankStr = ignoreEmptyStr || ignoreBlankStr;
boolean enableFakeDelete = config.isFakeDelete();
// 已经 remove了 id 和 id{},以及 @key
Set<String> set = request.keySet(); // 前面已经判断 request 是否为空
if (method == POST) { // POST操作
if (idIn != null) {
throw new IllegalArgumentException(table + ":{" + idInKey + ": value} 里的 key 不合法!POST 请求中不允许传 " + idInKey
+ " 这种非字段命名 key !必须为 英文字母 开头且只包含 英文字母、数字、下划线的 字段命名!"); }
if (userIdIn != null) {
throw new IllegalArgumentException(table + ":{" + userIdInKey + ": value} 里的 key 不合法!POST 请求中不允许传 " + userIdInKey
+ " 这种非字段命名 key !必须为 英文字母 开头且只包含 英文字母、数字、下划线的 字段命名!"); }
if (set != null && set.isEmpty() == false) { // 不能直接return,要走完下面的流程
for (String k : set) {
if (StringUtil.isName(k) == false) {
throw new IllegalArgumentException(table + ":{" + k + ": value} 里的 key 不合法!POST 请求中不允许传 " + k
+ " 这种非字段命名 key !必须为 英文字母 开头且只包含 英文字母、数字、下划线的 字段命名!");
}
}
String[] columns = set.toArray(new String[]{});
Collection<Object> valueCollection = request.values();
Object[] values = valueCollection == null ? null : valueCollection.toArray();
if (values == null || values.length != columns.length) {
throw new Exception("服务器内部错误:\n" + TAG
+ " newSQLConfig values == null || values.length != columns.length !");
}
column = (id == null ? "" : idKey + ",") + (userId == null ? "" : userIdKey + ",")
+ StringUtil.getString(columns); //set已经判断过不为空
int idCount = id == null ? (userId == null ? 0 : 1) : (userId == null ? 1 : 2);
int size = idCount + columns.length; // 以 key 数量为准
List<Object> items = new ArrayList<>(size); // VALUES(item0, item1, ...)
if (id != null) {
items.add(id); // idList.get(i)); // 第 0 个就是 id
}
if (userId != null) {
items.add(userId); // idList.get(i)); // 第 1 个就是 userId
}
for (int j = 0; j < values.length; j++) {
items.add(values[j]); // 从第 1 个开始,允许 "null"
}
List<List<Object>> valuess = new ArrayList<>(1);
valuess.add(items);
config.setValues(valuess);
}
}
else { // 非 POST 操作
final boolean isWhere = method != PUT; // 除了POST,PUT,其它全是条件!!!
// 条件<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
String[] ws = StringUtil.split(combine);
String combineExpr = ws == null || ws.length != 1 ? null : ws[0];
Map<String, List<String>> combineMap = new LinkedHashMap<>();
List<String> andList = new ArrayList<>();
List<String> orList = new ArrayList<>();
List<String> notList = new ArrayList<>();
List<String> whereList = new ArrayList<>();
// 强制作为条件且放在最前面优化性能
if (id != null) {
tableWhere.put(idKey, id);
andList.add(idKey);
whereList.add(idKey);
}
if (idIn != null) {
tableWhere.put(idInKey, idIn);
andList.add(idInKey);
whereList.add(idInKey);
}
if (userId != null) {
tableWhere.put(userIdKey, userId);
andList.add(userIdKey);
whereList.add(userIdKey);
}
if (userIdIn != null) {
tableWhere.put(userIdInKey, userIdIn);
andList.add(userIdInKey);
whereList.add(userIdInKey);
}
if (enableFakeDelete) {
// 查询 Access 假删除
Map<String, Object> accessFakeDeleteMap = method == DELETE
? null : AbstractVerifier.ACCESS_FAKE_DELETE_MAP.get(config.getTable());
Object deletedKey = accessFakeDeleteMap == null ? null : accessFakeDeleteMap.get(KEY_DELETED_KEY);
boolean hasKey = deletedKey instanceof String && StringUtil.isNotEmpty(deletedKey, true);
Object deletedValue = hasKey ? accessFakeDeleteMap.get(KEY_DELETED_VALUE) : null;
boolean containNotDeletedValue = hasKey ? accessFakeDeleteMap.containsKey(KEY_NOT_DELETED_VALUE) : false;
Object notDeletedValue = containNotDeletedValue ? accessFakeDeleteMap.get(KEY_NOT_DELETED_VALUE) : null;
if (deletedValue != null || containNotDeletedValue) {
boolean isFakeDelete = true;
if (from != null) {
// 兼容 JOIN 外层 SELECT 重复生成 deletedKey
SQLConfig<?> cfg = from.getConfig();
if (cfg != null && StringUtil.equals(table, cfg.getTable())) {
isFakeDelete = false;
}
List<Join> jl = isFakeDelete && cfg != null ? cfg.getJoinList() : null;
if (jl != null) {
for (Join join : jl) {
if (join != null && StringUtil.equals(table, join.getTable())) {
isFakeDelete = false;
break;
}
}
}
}
if (isFakeDelete) { // 支持 deleted != 1 / deleted is null 等表达式
if (deletedValue != null) { // deletedKey != deletedValue
String key = deletedKey + "!";
tableWhere.put(key, deletedValue);
andList.add(key);
whereList.add(key);
}
if (containNotDeletedValue) { // deletedKey = notDeletedValue
String key = deletedKey.toString();
tableWhere.put(key, notDeletedValue);
andList.add(key);
whereList.add(key);
}
}
}
}
if (StringUtil.isNotEmpty(combineExpr, true)) {
List<String> banKeyList = Arrays.asList(idKey, idInKey, userIdKey, userIdInKey);
for (String key : banKeyList) {
if (isKeyInCombineExpr(combineExpr, key)) {
throw new UnsupportedOperationException(table + ":{} 里的 @combine:value 中的 value 里 " + key + " 不合法!"
+ "不允许传 [" + idKey + ", " + idInKey + ", " + userIdKey + ", " + userIdInKey + "] 其中任何一个!");
}
}
}
else if (ws != null) {
for (int i = 0; i < ws.length; i++) { // 去除 &,|,! 前缀
String w = ws[i];
if (w != null) {
if (w.startsWith("&")) {
w = w.substring(1);
andList.add(w);
}
else if (w.startsWith("|")) {
if (method == PUT) {
throw new IllegalArgumentException(table + ":{} 里的 @combine:value 中的value里条件 " + ws[i] + " 不合法!"
+ "PUT请求的 @combine:\"key0,key1,...\" 不允许传 |key 或 !key !");
}
w = w.substring(1);
orList.add(w);
}
else if (w.startsWith("!")) {
if (method == PUT) {
throw new IllegalArgumentException(table + ":{} 里的 @combine:value 中的value里条件 " + ws[i] + " 不合法!"
+ "PUT请求的 @combine:\"key0,key1,...\" 不允许传 |key 或 !key !");
}
w = w.substring(1);
notList.add(w);
}
else {
orList.add(w);
}
if (w.isEmpty()) {
throw new IllegalArgumentException(table + ":{} 里的 @combine:value 中的value里条件 " + ws[i] + " 不合法!不允许为空值!");
}
else {
if (idKey.equals(w) || idInKey.equals(w) || userIdKey.equals(w) || userIdInKey.equals(w)) {
throw new UnsupportedOperationException(table + ":{} 里的 @combine:value 中的 value 里 " + ws[i] + " 不合法!"
+ "不允许传 [" + idKey + ", " + idInKey + ", " + userIdKey + ", " + userIdInKey + "] 其中任何一个!");
}
}
whereList.add(w);
}
// 可重写回调方法自定义处理 // 动态设置的场景似乎很少,而且去掉后不方便用户排错!
// 去掉判断,有时候不在没关系,如果是对增删改等非开放请求强制要求传对应的条件,可以用 Operation.NECESSARY
if (request.containsKey(w) == false) { // 和 request.get(w) == null 没区别,前面 Parser 已经过滤了 null
// throw new IllegalArgumentException(table + ":{} 里的 @combine:value 中的value里 " + ws[i] + " 对应的 " + w + " 不在它里面!");
callback.onMissingKey4Combine(table, request, combine, ws[i], w);
if (config instanceof AbstractSQLConfig) {
((AbstractSQLConfig<T>) config).putWarnIfNeed(KEY_COMBINE, table + ":{} 里的 @combine:value 中的 value 里 "
+ ws[i] + " 对应的条件 " + w + ":value 中 value 必须存在且不能为 null!");
}
}
}
}
// 条件 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Map<String, Object> tableContent = new LinkedHashMap<String, Object>();
for (String key : set) {
Object value = request.get(key);
if (ignoreEmptyOrBlankStr && value instanceof String && StringUtil.isEmpty(value, ignoreBlankStr)) {
continue;
}
if (key.endsWith("<>") == false && value instanceof Map) { // 只允许常规 Object
throw new IllegalArgumentException(table + ":{ " + key + ":value } 中 value 类型错误!除了 key<>:{} 外,不允许 "
+ key + " 等其它任何 key 对应 value 的类型为 JSONObject {} !");
}
// 兼容 PUT @combine
// 解决AccessVerifier新增userId没有作为条件,而是作为内容,导致PUT,DELETE出错
if ((isWhere || (StringUtil.isName(key.replaceFirst("[+-]$", "")) == false))
|| (isWhere == false && StringUtil.isNotEmpty(combineExpr, true) && isKeyInCombineExpr(combineExpr, key))) {
tableWhere.put(key, value);
if (whereList.contains(key) == false) {
andList.add(key);
}
} else if (whereList.contains(key)) {
tableWhere.put(key, value);
} else {
tableContent.put(key, value); // 一样 instanceof JSONArray ? JSON.toJSONString(value) : value);
}
}
if (combineMap != null) {
combineMap.put("&", andList);
combineMap.put("|", orList);
combineMap.put("!", notList);
}
config.setCombineMap(combineMap);
config.setCombine(combineExpr);
config.setContent(tableContent);
}
if (enableFakeDelete && method == DELETE) {
// 查询 Access 假删除
Map<String, Object> accessFakeDeleteMap = AbstractVerifier.ACCESS_FAKE_DELETE_MAP.get(config.getTable());
Object deletedKey = accessFakeDeleteMap.get(KEY_DELETED_KEY);
if (StringUtil.isNotEmpty(deletedKey, true)) {
// 假删除需要更新的其他字段,比如:删除时间 deletedTime 之类的
Map<String, Object> fakeDeleteMap = new HashMap<>();
fakeDeleteMap.put(deletedKey.toString(), accessFakeDeleteMap.get(KEY_DELETED_VALUE));
fakeDeleteMap = config.onFakeDelete(fakeDeleteMap);
Map<String, Object> content = config.getContent();
if (content == null || content.isEmpty()) {
content = fakeDeleteMap;
} else {
content.putAll(fakeDeleteMap);
}
config.setMethod(PUT);
config.setContent(content);
}
}
List<String> cs = new ArrayList<>();
List<String> rawList = config.getRaw();
boolean containColumnHavingAnd = rawList != null && rawList.contains(KEY_HAVING_AND);
if (containColumnHavingAnd) {
throw new IllegalArgumentException(table + ":{ @raw:value } 的 value 里字符 @having& 不合法!"
+ "@raw 不支持 @having&,请用 @having 替代!");
}
// TODO 这段是否必要?如果 @column 只支持分段后的 SQL 片段,也没问题
boolean containColumnRaw = rawList != null && rawList.contains(KEY_COLUMN);
String rawColumnSQL = null;
if (containColumnRaw) {
rawColumnSQL = config.getRawSQL(KEY_COLUMN, column);
if (rawColumnSQL != null) {
cs.add(rawColumnSQL);
}
}
boolean distinct = rawColumnSQL == null && column != null && column.startsWith(PREFIX_DISTINCT);
if (rawColumnSQL == null) {
// key0,key1;fun0(key0,...);fun1(key0,...);key3;fun2(key0,...)
String[] fks = StringUtil.split(distinct ? column.substring(PREFIX_DISTINCT.length()) : column, ";");
if (fks != null) {
for (String fk : fks) {
if (containColumnRaw) {
String rawSQL = config.getRawSQL(KEY_COLUMN, fk);
if (rawSQL != null) {
cs.add(rawSQL);
continue;
}
}
if (fk.contains("(")) { // fun0(key0,...)
cs.add(fk);
}
else { // key0,key1...
String[] ks = StringUtil.split(fk);
if (ks != null && ks.length > 0) {
cs.addAll(Arrays.asList(ks));
}
}
}
}
}
// @having, @haivng& <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Object newHaving = having;
boolean isHavingAnd = false;
Map<String, Object> havingMap = new LinkedHashMap<>();
if (havingAnd != null) {
if (having != null) {
throw new IllegalArgumentException(table + ":{ @having: value1, @having&: value2 } "
+ "中 value1 与 value2 不合法!不允许同时传 @having 和 @having& ,两者最多传一个!");
}
newHaving = havingAnd;
isHavingAnd = true;
}
String havingKey = (isHavingAnd ? KEY_HAVING_AND : KEY_HAVING);
String havingCombine = "";
if (newHaving instanceof String) {
String[] havingss = StringUtil.split((String) newHaving, ";");
if (havingss != null) {
int ind = -1;
for (int i = 0; i < havingss.length; i++) {
String havingsStr = havingss[i];
int start = havingsStr == null ? -1 : havingsStr.indexOf("(");
int end = havingsStr == null ? -1 : havingsStr.lastIndexOf(")");
if (IS_HAVING_ALLOW_NOT_FUNCTION == false && (start < 0 || start >= end)) {
throw new IllegalArgumentException(table + ":{ " + havingKey + ":value } 里的 value 中的第 " + i +
" 个字符 '" + havingsStr + "' 不合法!里面没有包含 SQL 函数!必须为 fun(col1,col2..)?val 格式!");
}
String[] havings = start >= 0 && end > start ? new String[]{havingsStr} : StringUtil.split(havingsStr);
if (havings != null) {
for (int j = 0; j < havings.length; j++) {
ind ++;
String h = havings[j];
if (StringUtil.isEmpty(h, true)) {
throw new IllegalArgumentException(table + ":{ " + havingKey + ":value } 里的"
+ " value 中的第 " + ind + " 个字符 '" + h + "' 不合法!不允许为空!");
}
havingMap.put("having" + ind, h);
if (isHavingAnd == false && IS_HAVING_DEFAULT_AND == false) {
havingCombine += (ind <= 0 ? "" : " | ") + "having" + ind;
}
}
}
}
}
}
else if (newHaving instanceof JSONObject) {
if (isHavingAnd) {
throw new IllegalArgumentException(table + ":{ " + havingKey + ":value } 里的 value 类型不合法!"
+ "@having&:value 中 value 只能是 String,@having:value 中 value 只能是 String 或 JSONObject !");
}
JSONObject havingObj = (JSONObject) newHaving;
Set<Entry<String, Object>> havingSet = havingObj.entrySet();
for (Entry<String, Object> entry : havingSet) {
String k = entry == null ? null : entry.getKey();
Object v = k == null ? null : entry.getValue();
if (v == null) {
continue;
}
if (v instanceof String == false) {
throw new IllegalArgumentException(table + ":{ " + havingKey + ":{ " + k + ":value } } 里的"
+ " value 不合法!类型只能是 String,且不允许为空!");
}
if (ignoreEmptyOrBlankStr && StringUtil.isEmpty(v, ignoreBlankStr)) {
continue;
}
if (KEY_COMBINE.equals(k)) {
havingCombine = (String) v;
}
else if (StringUtil.isName(k) == false) {
throw new IllegalArgumentException(table + ":{ " + havingKey + ":{ " + k + ":value } } 里的"
+ " key 对应字符 " + k + " 不合法!必须为 英文字母 开头,且只包含 英文字母、下划线、数字 的合法变量名!");
}
else {
havingMap.put(k, (String) v);
}
}
}
else if (newHaving != null) {
throw new IllegalArgumentException(table + ":{ " + havingKey + ":value } 里的 value 类型不合法!"
+ "@having:value 中 value 只能是 String 或 JSONObject,@having&:value 中 value 只能是 String !");
}
// @having, @haivng& >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
if (keyMap instanceof Map) {
config.setKeyMap((Map<String, String>) keyMap);
}
else if (keyMap instanceof String) {
String[] ks = StringUtil.split((String) keyMap, ";");
if (ks.length > 0) {
Map<String, String> nkm = new LinkedHashMap<>();
for (int i = 0; i < ks.length; i++) {
Entry<String, String> ety = Pair.parseEntry(ks[i]);
if (ety == null) {
continue;
}
nkm.put(ety.getKey(), ety.getValue());
}
config.setKeyMap(nkm);
}
}
else if (keyMap != null) {
throw new UnsupportedDataTypeException("@key:value 中 value 错误,只能是 String, JSONObject 中的一种!");
}
config.setExplain(explain != null && explain);
config.setCache(getCache(cache));
config.setDistinct(distinct);
config.setColumn(column == null ? null : cs); //解决总是 config.column != null,总是不能得到 *
config.setFrom(from);
config.setRole(role);
config.setId(id);
config.setIdIn(idIn);
config.setUserId(userId);
config.setUserIdIn(userIdIn);
config.setNull(nullKeys == null || nullKeys.length <= 0 ? null : new ArrayList<>(Arrays.asList(nullKeys)));
config.setCast(castMap);
config.setWhere(tableWhere);
config.setGroup(group);
config.setHaving(havingMap);
config.setHavingCombine(havingCombine);
config.setOrder(order);
String[] jsons = StringUtil.split(json);
config.setJson(jsons == null || jsons.length <= 0 ? null : new ArrayList<>(Arrays.asList(jsons)));
}
finally { // 后面还可能用到,要还原
// id, id{}, userId, userIdIn 条件
if (id != null) {
request.put(idKey, id);
}
if (idIn != null) {
request.put(idInKey, idIn);
}
if (userId != null) {
request.put(userIdKey, userId);
}
if (userIdIn != null) {
request.put(userIdInKey, userIdIn);
}
// 关键词
if (role != null) {
request.put(KEY_ROLE, role);
}
if (explain != null) {
request.put(KEY_EXPLAIN, explain);
}
if (cache != null) {
request.put(KEY_CACHE, cache);
}
if (database != null) {
request.put(KEY_DATABASE, database);
}
if (datasource != null) {
request.put(KEY_DATASOURCE, datasource);
}
if (schema != null) {
request.put(KEY_SCHEMA, schema);
}
if (from != null) {
request.put(KEY_FROM, from);
}
if (column != null) {
request.put(KEY_COLUMN, column);
}
if (nulls != null) {
request.put(KEY_NULL, nulls);
}
if (cast != null) {
request.put(KEY_CAST, cast);
}
if (combine != null) {
request.put(KEY_COMBINE, combine);
}
if (group != null) {
request.put(KEY_GROUP, group);
}
if (having != null) {
request.put(KEY_HAVING, having);
}
if (havingAnd != null) {
request.put(KEY_HAVING_AND, havingAnd);
}
if (order != null) {
request.put(KEY_ORDER, order);
}
if (keyMap != null) {
request.put(KEY_KEY, keyMap);
}
if (raw != null) {
request.put(KEY_RAW, raw);
}
if (json != null) {
request.put(KEY_JSON, json);
}
if (mthd != null) {
request.put(KEY_METHOD, mthd);
}
}
return config;
}
/**
* @param method
* @param config
* @param joinList
* @param callback
* @return
* @throws Exception
*/
public static <T extends Object> SQLConfig<T> parseJoin(RequestMethod method, SQLConfig<T> config
, List<Join> joinList, Callback<T> callback) throws Exception {
boolean isQuery = RequestMethod.isQueryMethod(method);
config.setKeyPrefix(isQuery && config.isMain() == false);
//TODO 解析出 SQLConfig 再合并 column, order, group 等
if (joinList == null || joinList.isEmpty() || RequestMethod.isQueryMethod(method) == false) {
return config;
}
String table;
String alias;
for (Join j : joinList) {
table = j.getTable();
alias = j.getAlias();
//JOIN子查询不能设置LIMIT,因为ON关系是在子查询后处理的,会导致结果会错误
SQLConfig<T> joinConfig = newSQLConfig(method, table, alias, j.getRequest(), null, false, callback);
SQLConfig<T> cacheConfig = j.canCacheViceTable() == false ? null : newSQLConfig(method, table, alias
, j.getRequest(), null, false, callback).setCount(j.getCount());
if (j.isAppJoin() == false) { //除了 @ APP JOIN,其它都是 SQL JOIN,则副表要这样配置
if (joinConfig.getDatabase() == null) {
joinConfig.setDatabase(config.getDatabase()); //解决主表 JOIN 副表,引号不一致
}
else if (joinConfig.getDatabase().equals(config.getDatabase()) == false) {
throw new IllegalArgumentException("主表 " + config.getTable() + " 的 @database:" + config.getDatabase()
+ " 和它 SQL JOIN 的副表 " + table + " 的 @database:" + joinConfig.getDatabase() + " 不一致!");
}
if (joinConfig.getSchema() == null) {
joinConfig.setSchema(config.getSchema()); //主表 JOIN 副表,默认 schema 一致
}
if (cacheConfig != null) {
cacheConfig.setDatabase(joinConfig.getDatabase()).setSchema(joinConfig.getSchema()); //解决主表 JOIN 副表,引号不一致
}
if (isQuery) {
config.setKeyPrefix(true);
}
joinConfig.setMain(false).setKeyPrefix(true);
if (j.getOuter() != null) {
SQLConfig<T> outterConfig = newSQLConfig(method, table, alias, j.getOuter(), null, false, callback);
outterConfig.setMain(false)
.setKeyPrefix(true)
.setDatabase(joinConfig.getDatabase())
.setSchema(joinConfig.getSchema()); //解决主表 JOIN 副表,引号不一致
j.setOuterConfig(outterConfig);
}
}
//解决 query: 1/2 查数量时报错
/* SELECT count(*) AS count FROM sys.Moment AS Moment
LEFT JOIN ( SELECT count(*) AS count FROM sys.Comment ) AS Comment ON Comment.momentId = Moment.id LIMIT 1 OFFSET 0 */
if (RequestMethod.isHeadMethod(method, true)) {
List<On> onList = j.getOnList();
List<String> column = onList == null ? null : new ArrayList<>(onList.size());
if (column != null) {
for (On on : onList) {
column.add(on.getKey());
}
}
joinConfig.setMethod(GET); // 子查询不能为 SELECT count(*) ,而应该是 SELECT momentId
joinConfig.setColumn(column); // 优化性能,不取非必要的字段
if (cacheConfig != null) {
cacheConfig.setMethod(GET); // 子查询不能为 SELECT count(*) ,而应该是 SELECT momentId
cacheConfig.setColumn(column); // 优化性能,不取非必要的字段
}
}
j.setJoinConfig(joinConfig);
j.setCacheConfig(cacheConfig);
}
config.setJoinList(joinList);
return config;
}
/**获取客户端实际需要的key
* verifyName = true
* @param method
* @param originKey
* @param isTableKey
* @param saveLogic 保留逻辑运算符 & | !
* @return
*/
public static String getRealKey(RequestMethod method, String originKey
, boolean isTableKey, boolean saveLogic) throws Exception {
return getRealKey(method, originKey, isTableKey, saveLogic, true);
}
/**获取客户端实际需要的key
* @param method
* @param originKey
* @param isTableKey
* @param saveLogic 保留逻辑运算符 & | !
* @param verifyName 验证key名是否符合代码变量/常量名
* @return
*/
public static String getRealKey(RequestMethod method, String originKey
, boolean isTableKey, boolean saveLogic, boolean verifyName) throws Exception {
Log.i(TAG, "getRealKey saveLogic = " + saveLogic + "; originKey = " + originKey);
if (originKey == null || apijson.JSONObject.isArrayKey(originKey)) {
Log.w(TAG, "getRealKey originKey == null || apijson.JSONObject.isArrayKey(originKey) >> return originKey;");
return originKey;
}
String key = new String(originKey);
if (key.endsWith("$")) {//搜索 LIKE,查询时处理
String k = key.substring(0, key.length() - 1);
// key%$:"a" -> key LIKE '%a%'; key?%$:"a" -> key LIKE 'a%'; key_?$:"a" -> key LIKE '_a'; key_%$:"a" -> key LIKE '_a%'
char c = k.isEmpty() ? 0 : k.charAt(k.length() - 1);
if (c == '%' || c == '_' || c == '?') {
k = k.substring(0, k.length() - 1);
char c2 = k.isEmpty() ? 0 : k.charAt(k.length() - 1);
if (c2 == '%' || c2 == '_' || c2 == '?') {
if (c2 == c) {
throw new IllegalArgumentException(originKey + ":value 中字符 "
+ k + " 不合法!key$:value 中不允许 key 中有连续相同的占位符!");
}
k = k.substring(0, k.length() - 1);
}
else if (c == '?') {
throw new IllegalArgumentException(originKey + ":value 中字符 " + originKey
+ " 不合法!key$:value 中不允许只有单独的 '?',必须和 '%', '_' 之一配合使用 !");
}
}
key = k;
}
else if (key.endsWith("~")) {//匹配正则表达式 REGEXP,查询时处理
key = key.substring(0, key.length() - 1);
if (key.endsWith("*")) {//忽略大小写
key = key.substring(0, key.length() - 1);
}
}
else if (key.endsWith("%")) {//数字、文本、日期范围 BETWEEN AND
key = key.substring(0, key.length() - 1);
}
else if (key.endsWith("{}")) {//被包含 IN,或者说key对应值处于value的范围内。查询时处理
key = key.substring(0, key.length() - 2);
}
else if (key.endsWith("}{")) {//被包含 EXISTS,或者说key对应值处于value的范围内。查询时处理
key = key.substring(0, key.length() - 2);
}
else if (key.endsWith("<>")) {//包含 json_contains,或者说value处于key对应值的范围内。查询时处理
key = key.substring(0, key.length() - 2);
}
else if (key.endsWith("()")) {//方法,查询完后处理,先用一个Map<key,function>保存
key = key.substring(0, key.length() - 2);
}
else if (key.endsWith("@")) {//引用,引用对象查询完后处理。fillTarget中暂时不用处理,因为非GET请求都是由给定的id确定,不需要引用
key = key.substring(0, key.length() - 1);
}
else if (key.endsWith(">=")) {//比较。查询时处理
key = key.substring(0, key.length() - 2);
}
else if (key.endsWith("<=")) {//比较。查询时处理
key = key.substring(0, key.length() - 2);
}
else if (key.endsWith(">")) {//比较。查询时处理
key = key.substring(0, key.length() - 1);
}
else if (key.endsWith("<")) {//比较。查询时处理
key = key.substring(0, key.length() - 1);
}
else if (key.endsWith("+")) {//延长,PUT查询时处理
if (method == PUT) {//不为PUT就抛异常
key = key.substring(0, key.length() - 1);
}
}
else if (key.endsWith("-")) {//缩减,PUT查询时处理
if (method == PUT) {//不为PUT就抛异常
key = key.substring(0, key.length() - 1);
}
}
//TODO if (key.endsWith("-")) { // 表示 key 和 value 顺序反过来: value LIKE key
//不用Logic优化代码,否则 key 可能变为 key| 导致 key=value 变成 key|=value 而出错
String last = key.isEmpty() ? "" : key.substring(key.length() - 1);
if ("&".equals(last) || "|".equals(last) || "!".equals(last)) {
key = key.substring(0, key.length() - 1);
} else {
last = null;//避免key + StringUtil.getString(last)错误延长
}
//"User:toUser":User转换"toUser":User, User为查询同名Table得到的JSONObject。交给客户端处理更好
if (isTableKey) {//不允许在column key中使用Type:key形式
key = Pair.parseEntry(key, true).getKey();//table以左边为准
} else {
key = Pair.parseEntry(key).getValue();//column以右边为准
}
if (verifyName && StringUtil.isName(key.startsWith("@") ? key.substring(1) : key) == false) {
throw new IllegalArgumentException(method + "请求,字符 " + originKey + " 不合法!"
+ " key:value 中的key只能关键词 '@key' 或 'key[逻辑符][条件符]' 或 PUT请求下的 'key+' / 'key-' !");
}
if (saveLogic && last != null) {
key = key + last;
}
Log.i(TAG, "getRealKey return key = " + key);
return key;
}
public static interface IdCallback<T extends Object> {
/**为 post 请求新建 id, 只能是 Long 或 String
* @param method
* @param database
* @param schema
* @param table
* @return
*/
T newId(RequestMethod method, String database, String schema, String datasource, String table);
/**获取主键名
* @param database
* @param schema
* @param table
* @return
*/
String getIdKey(String database, String schema, String datasource, String table);
/**获取 User 的主键名
* @param database
* @param schema
* @param table
* @return
*/
String getUserIdKey(String database, String schema, String datasource, String table);
}
public static interface Callback<T extends Object> extends IdCallback<T> {
/**获取 SQLConfig 的实例
* @param method
* @param database
* @param schema
* @param table
* @return
*/
SQLConfig<T> getSQLConfig(RequestMethod method, String database, String schema, String datasource, String table);
/**combine 里的 key 在 request 中 value 为 null 或不存在,即 request 中缺少用来作为 combine 条件的 key: value
* @param combine
* @param key
* @param request
*/
void onMissingKey4Combine(String name, JSONObject request, String combine, String item, String key) throws Exception;
}
public static Long LAST_ID;
static {
LAST_ID = System.currentTimeMillis();
}
public static abstract class SimpleCallback<T extends Object> implements Callback<T> {
@SuppressWarnings("unchecked")
@Override
public T newId(RequestMethod method, String database, String schema, String datasource, String table) {
Long id = System.currentTimeMillis();
if (id <= LAST_ID) {
id = LAST_ID + 1; // 解决高并发下 id 冲突导致新增记录失败
}
LAST_ID = id;
return (T) id;
}
@Override
public String getIdKey(String database, String schema, String datasource, String table) {
return KEY_ID;
}
@Override
public String getUserIdKey(String database, String schema, String datasource, String table) {
return KEY_USER_ID;
}
@Override
public void onMissingKey4Combine(String name, JSONObject request, String combine, String item, String key) throws Exception {
if (ALLOW_MISSING_KEY_4_COMBINE) {
return;
}
throw new IllegalArgumentException(name + ":{} 里的 @combine:value 中的value里 "
+ item + " 对应的条件 " + key + ":value 中 value 必须存在且不能为 null!");
}
}
private static boolean isKeyInCombineExpr(String combineExpr, String key) {
while (combineExpr.isEmpty() == false) {
int index = combineExpr.indexOf(key);
if (index < 0) {
return false;
}
char left = index <= 0 ? ' ' : combineExpr.charAt(index - 1);
char right = index >= combineExpr.length() - key.length() ? ' ' : combineExpr.charAt(index + key.length());
if ((left == ' ' || left == '(' || left == '&' || left == '|' || left == '!') && (right == ' ' || right == ')' || right == ':')) {
return true;
}
int newIndex = index + key.length() + 1;
if (combineExpr.length() <= newIndex) {
break;
}
combineExpr = combineExpr.substring(newIndex);
}
return false;
}
public List<String> getWithAsExprSqlList() {
return withAsExprSqlList;
}
private void clearWithAsExprListIfNeed() {
// mysql8版本以上,子查询支持with as表达式
if(this.isMySQL() && this.getDBVersionNums()[0] >= 8) {
this.withAsExprSqlList = new ArrayList<>();
}
}
@Override
public List<Object> getWithAsExprPreparedValueList() {
return this.withAsExprPreparedValueList;
}
@Override
public AbstractSQLConfig setWithAsExprPreparedValueList(List<Object> list) {
this.withAsExprPreparedValueList = list;
return this;
}
}
| Tencent/APIJSON | APIJSONORM/src/main/java/apijson/orm/AbstractSQLConfig.java |
648 | /**
* File: knapsack.java
* Created Time: 2023-07-10
* Author: krahets ([email protected])
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class knapsack {
/* 0-1 背包:暴力搜索 */
static int knapsackDFS(int[] wgt, int[] val, int i, int c) {
// 若已选完所有物品或背包无剩余容量,则返回价值 0
if (i == 0 || c == 0) {
return 0;
}
// 若超过背包容量,则只能选择不放入背包
if (wgt[i - 1] > c) {
return knapsackDFS(wgt, val, i - 1, c);
}
// 计算不放入和放入物品 i 的最大价值
int no = knapsackDFS(wgt, val, i - 1, c);
int yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
// 返回两种方案中价值更大的那一个
return Math.max(no, yes);
}
/* 0-1 背包:记忆化搜索 */
static int knapsackDFSMem(int[] wgt, int[] val, int[][] mem, int i, int c) {
// 若已选完所有物品或背包无剩余容量,则返回价值 0
if (i == 0 || c == 0) {
return 0;
}
// 若已有记录,则直接返回
if (mem[i][c] != -1) {
return mem[i][c];
}
// 若超过背包容量,则只能选择不放入背包
if (wgt[i - 1] > c) {
return knapsackDFSMem(wgt, val, mem, i - 1, c);
}
// 计算不放入和放入物品 i 的最大价值
int no = knapsackDFSMem(wgt, val, mem, i - 1, c);
int yes = knapsackDFSMem(wgt, val, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
// 记录并返回两种方案中价值更大的那一个
mem[i][c] = Math.max(no, yes);
return mem[i][c];
}
/* 0-1 背包:动态规划 */
static int knapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// 初始化 dp 表
int[][] dp = new int[n + 1][cap + 1];
// 状态转移
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// 若超过背包容量,则不选物品 i
dp[i][c] = dp[i - 1][c];
} else {
// 不选和选物品 i 这两种方案的较大值
dp[i][c] = Math.max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* 0-1 背包:空间优化后的动态规划 */
static int knapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// 初始化 dp 表
int[] dp = new int[cap + 1];
// 状态转移
for (int i = 1; i <= n; i++) {
// 倒序遍历
for (int c = cap; c >= 1; c--) {
if (wgt[i - 1] <= c) {
// 不选和选物品 i 这两种方案的较大值
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
public static void main(String[] args) {
int[] wgt = { 10, 20, 30, 40, 50 };
int[] val = { 50, 120, 150, 210, 240 };
int cap = 50;
int n = wgt.length;
// 暴力搜索
int res = knapsackDFS(wgt, val, n, cap);
System.out.println("不超过背包容量的最大物品价值为 " + res);
// 记忆化搜索
int[][] mem = new int[n + 1][cap + 1];
for (int[] row : mem) {
Arrays.fill(row, -1);
}
res = knapsackDFSMem(wgt, val, mem, n, cap);
System.out.println("不超过背包容量的最大物品价值为 " + res);
// 动态规划
res = knapsackDP(wgt, val, cap);
System.out.println("不超过背包容量的最大物品价值为 " + res);
// 空间优化后的动态规划
res = knapsackDPComp(wgt, val, cap);
System.out.println("不超过背包容量的最大物品价值为 " + res);
}
}
| krahets/hello-algo | codes/java/chapter_dynamic_programming/knapsack.java |
649 | package com.alibaba.datax.core;
import com.alibaba.datax.common.element.ColumnCast;
import com.alibaba.datax.common.exception.DataXException;
import com.alibaba.datax.common.spi.ErrorCode;
import com.alibaba.datax.common.statistics.PerfTrace;
import com.alibaba.datax.common.statistics.VMInfo;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.common.util.MessageSource;
import com.alibaba.datax.core.job.JobContainer;
import com.alibaba.datax.core.taskgroup.TaskGroupContainer;
import com.alibaba.datax.core.util.ConfigParser;
import com.alibaba.datax.core.util.ConfigurationValidate;
import com.alibaba.datax.core.util.ExceptionTracker;
import com.alibaba.datax.core.util.FrameworkErrorCode;
import com.alibaba.datax.core.util.container.CoreConstant;
import com.alibaba.datax.core.util.container.LoadUtil;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Engine是DataX入口类,该类负责初始化Job或者Task的运行容器,并运行插件的Job或者Task逻辑
*/
public class Engine {
private static final Logger LOG = LoggerFactory.getLogger(Engine.class);
private static String RUNTIME_MODE;
/* check job model (job/task) first */
public void start(Configuration allConf) {
// 绑定column转换信息
ColumnCast.bind(allConf);
/**
* 初始化PluginLoader,可以获取各种插件配置
*/
LoadUtil.bind(allConf);
boolean isJob = !("taskGroup".equalsIgnoreCase(allConf
.getString(CoreConstant.DATAX_CORE_CONTAINER_MODEL)));
//JobContainer会在schedule后再行进行设置和调整值
int channelNumber =0;
AbstractContainer container;
long instanceId;
int taskGroupId = -1;
if (isJob) {
allConf.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_MODE, RUNTIME_MODE);
container = new JobContainer(allConf);
instanceId = allConf.getLong(
CoreConstant.DATAX_CORE_CONTAINER_JOB_ID, 0);
} else {
container = new TaskGroupContainer(allConf);
instanceId = allConf.getLong(
CoreConstant.DATAX_CORE_CONTAINER_JOB_ID);
taskGroupId = allConf.getInt(
CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_ID);
channelNumber = allConf.getInt(
CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_CHANNEL);
}
//缺省打开perfTrace
boolean traceEnable = allConf.getBool(CoreConstant.DATAX_CORE_CONTAINER_TRACE_ENABLE, true);
boolean perfReportEnable = allConf.getBool(CoreConstant.DATAX_CORE_REPORT_DATAX_PERFLOG, true);
//standalone模式的 datax shell任务不进行汇报
if(instanceId == -1){
perfReportEnable = false;
}
Configuration jobInfoConfig = allConf.getConfiguration(CoreConstant.DATAX_JOB_JOBINFO);
//初始化PerfTrace
PerfTrace perfTrace = PerfTrace.getInstance(isJob, instanceId, taskGroupId, traceEnable);
perfTrace.setJobInfo(jobInfoConfig,perfReportEnable,channelNumber);
container.start();
}
// 注意屏蔽敏感信息
public static String filterJobConfiguration(final Configuration configuration) {
Configuration jobConfWithSetting = configuration.getConfiguration("job").clone();
Configuration jobContent = jobConfWithSetting.getConfiguration("content");
filterSensitiveConfiguration(jobContent);
jobConfWithSetting.set("content",jobContent);
return jobConfWithSetting.beautify();
}
public static Configuration filterSensitiveConfiguration(Configuration configuration){
Set<String> keys = configuration.getKeys();
for (final String key : keys) {
boolean isSensitive = StringUtils.endsWithIgnoreCase(key, "password")
|| StringUtils.endsWithIgnoreCase(key, "accessKey");
if (isSensitive && configuration.get(key) instanceof String) {
configuration.set(key, configuration.getString(key).replaceAll(".", "*"));
}
}
return configuration;
}
public static void entry(final String[] args) throws Throwable {
Options options = new Options();
options.addOption("job", true, "Job config.");
options.addOption("jobid", true, "Job unique id.");
options.addOption("mode", true, "Job runtime mode.");
BasicParser parser = new BasicParser();
CommandLine cl = parser.parse(options, args);
String jobPath = cl.getOptionValue("job");
// 如果用户没有明确指定jobid, 则 datax.py 会指定 jobid 默认值为-1
String jobIdString = cl.getOptionValue("jobid");
RUNTIME_MODE = cl.getOptionValue("mode");
Configuration configuration = ConfigParser.parse(jobPath);
// 绑定i18n信息
MessageSource.init(configuration);
MessageSource.reloadResourceBundle(Configuration.class);
long jobId;
if (!"-1".equalsIgnoreCase(jobIdString)) {
jobId = Long.parseLong(jobIdString);
} else {
// only for dsc & ds & datax 3 update
String dscJobUrlPatternString = "/instance/(\\d{1,})/config.xml";
String dsJobUrlPatternString = "/inner/job/(\\d{1,})/config";
String dsTaskGroupUrlPatternString = "/inner/job/(\\d{1,})/taskGroup/";
List<String> patternStringList = Arrays.asList(dscJobUrlPatternString,
dsJobUrlPatternString, dsTaskGroupUrlPatternString);
jobId = parseJobIdFromUrl(patternStringList, jobPath);
}
boolean isStandAloneMode = "standalone".equalsIgnoreCase(RUNTIME_MODE);
if (!isStandAloneMode && jobId == -1) {
// 如果不是 standalone 模式,那么 jobId 一定不能为-1
throw DataXException.asDataXException(FrameworkErrorCode.CONFIG_ERROR, "非 standalone 模式必须在 URL 中提供有效的 jobId.");
}
configuration.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_ID, jobId);
//打印vmInfo
VMInfo vmInfo = VMInfo.getVmInfo();
if (vmInfo != null) {
LOG.info(vmInfo.toString());
}
LOG.info("\n" + Engine.filterJobConfiguration(configuration) + "\n");
LOG.debug(configuration.toJSON());
ConfigurationValidate.doValidate(configuration);
Engine engine = new Engine();
engine.start(configuration);
}
/**
* -1 表示未能解析到 jobId
*
* only for dsc & ds & datax 3 update
*/
private static long parseJobIdFromUrl(List<String> patternStringList, String url) {
long result = -1;
for (String patternString : patternStringList) {
result = doParseJobIdFromUrl(patternString, url);
if (result != -1) {
return result;
}
}
return result;
}
private static long doParseJobIdFromUrl(String patternString, String url) {
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
return Long.parseLong(matcher.group(1));
}
return -1;
}
public static void main(String[] args) throws Exception {
int exitCode = 0;
try {
Engine.entry(args);
} catch (Throwable e) {
exitCode = 1;
LOG.error("\n\n经DataX智能分析,该任务最可能的错误原因是:\n" + ExceptionTracker.trace(e));
if (e instanceof DataXException) {
DataXException tempException = (DataXException) e;
ErrorCode errorCode = tempException.getErrorCode();
if (errorCode instanceof FrameworkErrorCode) {
FrameworkErrorCode tempErrorCode = (FrameworkErrorCode) errorCode;
exitCode = tempErrorCode.toExitValue();
}
}
System.exit(exitCode);
}
System.exit(exitCode);
}
}
| alibaba/DataX | core/src/main/java/com/alibaba/datax/core/Engine.java |
652 | package com.blankj.hard._1028;
import com.blankj.structure.TreeNode;
import java.util.LinkedList;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2020/06/19
* desc :
* </pre>
*/
public class Solution {
// public TreeNode recoverFromPreorder(String S) {
// char[] chars = S.toCharArray();
// int len = chars.length;
// List<TreeNode> levels = new LinkedList<>();
// for (int i = 0; i < len; ) {
// int level = 0, val = 0;
// while (chars[i] == '-') { // 获取所在层级,Character.isDigit() 会比较慢
// ++i;
// ++level;
// }
// while (i < len && chars[i] != '-') { // 获取节点的值
// val = val * 10 + chars[i++] - '0';
// }
// TreeNode curNode = new TreeNode(val);
// if (level > 0) {
// TreeNode parent = levels.get(level - 1);
// if (parent.left == null) { // 如果节点只有一个子节点,那么保证该子节点为左子节点。
// parent.left = curNode;
// } else {
// parent.right = curNode;
// }
// }
// levels.add(level, curNode); // 因为是前序遍历(根-左-右),也就是右覆盖左时,此时左树已遍历完成,故无需考虑覆盖问题
// }
// return levels.get(0);
// }
public TreeNode recoverFromPreorder(String S) {
char[] chars = S.toCharArray();
int len = chars.length;
LinkedList<TreeNode> stack = new LinkedList<>();
for (int i = 0; i < len; ) {
int level = 0, val = 0;
while (chars[i] == '-') { // 获取所在层级,Character.isDigit() 会比较慢
++i;
++level;
}
while (i < len && chars[i] != '-') { // 获取节点的值
val = val * 10 + chars[i++] - '0';
}
TreeNode curNode = new TreeNode(val);
while (stack.size() > level) { // 栈顶不是父亲,栈顶出栈
stack.removeLast();
}
if (level > 0) {
TreeNode parent = stack.getLast();
if (parent.left == null) { // 如果节点只有一个子节点,那么保证该子节点为左子节点。
parent.left = curNode;
} else {
parent.right = curNode;
}
}
stack.addLast(curNode);
}
return stack.get(0);
}
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode.print(solution.recoverFromPreorder("1-2--3--4-5--6--7"));
System.out.println("==============================================");
TreeNode.print(solution.recoverFromPreorder("1-2--3---4-5--6---7"));
}
}
| Blankj/awesome-java-leetcode | src/com/blankj/hard/_1028/Solution.java |
654 | package com.alibaba.otter.canal.parse.inbound.mysql;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import com.alibaba.otter.canal.common.utils.JsonUtils;
import com.alibaba.otter.canal.parse.CanalEventParser;
import com.alibaba.otter.canal.parse.CanalHASwitchable;
import com.alibaba.otter.canal.parse.driver.mysql.packets.server.FieldPacket;
import com.alibaba.otter.canal.parse.driver.mysql.packets.server.ResultSetPacket;
import com.alibaba.otter.canal.parse.exception.CanalParseException;
import com.alibaba.otter.canal.parse.ha.CanalHAController;
import com.alibaba.otter.canal.parse.inbound.ErosaConnection;
import com.alibaba.otter.canal.parse.inbound.HeartBeatCallback;
import com.alibaba.otter.canal.parse.inbound.SinkFunction;
import com.alibaba.otter.canal.parse.inbound.mysql.MysqlConnection.BinlogFormat;
import com.alibaba.otter.canal.parse.inbound.mysql.MysqlConnection.BinlogImage;
import com.alibaba.otter.canal.parse.inbound.mysql.dbsync.LogEventConvert;
import com.alibaba.otter.canal.parse.inbound.mysql.dbsync.TableMetaCache;
import com.alibaba.otter.canal.parse.inbound.mysql.tsdb.DatabaseTableMeta;
import com.alibaba.otter.canal.parse.support.AuthenticationInfo;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.position.EntryPosition;
import com.alibaba.otter.canal.protocol.position.LogPosition;
import com.taobao.tddl.dbsync.binlog.LogEvent;
/**
* 基于向mysql server复制binlog实现
*
* <pre>
* 1. 自身不控制mysql主备切换,由ha机制来控制. 比如接入tddl/cobar/自身心跳包成功率
* 2. 切换机制
* </pre>
*
* @author jianghang 2012-6-21 下午04:06:32
* @version 1.0.0
*/
public class MysqlEventParser extends AbstractMysqlEventParser implements CanalEventParser, CanalHASwitchable {
private CanalHAController haController = null;
private int defaultConnectionTimeoutInSeconds = 30; // sotimeout
private int receiveBufferSize = 64 * 1024;
private int sendBufferSize = 64 * 1024;
// 数据库信息
protected AuthenticationInfo masterInfo; // 主库
protected AuthenticationInfo standbyInfo; // 备库
// binlog信息
protected EntryPosition masterPosition;
protected EntryPosition standbyPosition;
private long slaveId; // 链接到mysql的slave
// 心跳检查信息
private String detectingSQL; // 心跳sql
private MysqlConnection metaConnection; // 查询meta信息的链接
private TableMetaCache tableMetaCache; // 对应meta
private int fallbackIntervalInSeconds = 60; // 切换回退时间
private BinlogFormat[] supportBinlogFormats; // 支持的binlogFormat,如果设置会执行强校验
private BinlogImage[] supportBinlogImages; // 支持的binlogImage,如果设置会执行强校验
// update by yishun.chen,特殊异常处理参数
private int dumpErrorCount = 0; // binlogDump失败异常计数
private int dumpErrorCountThreshold = 2; // binlogDump失败异常计数阀值
private boolean rdsOssMode = false;
private boolean autoResetLatestPosMode = false; // true:
// binlog被删除之后,自动按最新的数据订阅
private boolean multiStreamEnable;//support for polardbx binlog-x
protected ErosaConnection buildErosaConnection() {
return buildMysqlConnection(this.runningInfo);
}
protected void preDump(ErosaConnection connection) {
if (!(connection instanceof MysqlConnection)) {
throw new CanalParseException("Unsupported connection type : " + connection.getClass().getSimpleName());
}
if (binlogParser != null && binlogParser instanceof LogEventConvert) {
metaConnection = (MysqlConnection) connection.fork();
try {
metaConnection.connect();
} catch (IOException e) {
throw new CanalParseException(e);
}
if (supportBinlogFormats != null && supportBinlogFormats.length > 0) {
BinlogFormat format = ((MysqlConnection) metaConnection).getBinlogFormat();
boolean found = false;
for (BinlogFormat supportFormat : supportBinlogFormats) {
if (supportFormat != null && format == supportFormat) {
found = true;
break;
}
}
if (!found) {
throw new CanalParseException("Unsupported BinlogFormat " + format);
}
}
if (supportBinlogImages != null && supportBinlogImages.length > 0) {
BinlogImage image = ((MysqlConnection) metaConnection).getBinlogImage();
boolean found = false;
for (BinlogImage supportImage : supportBinlogImages) {
if (supportImage != null && image == supportImage) {
found = true;
break;
}
}
if (!found) {
throw new CanalParseException("Unsupported BinlogImage " + image);
}
}
if (tableMetaTSDB != null && tableMetaTSDB instanceof DatabaseTableMeta) {
((DatabaseTableMeta) tableMetaTSDB).setConnection(metaConnection);
((DatabaseTableMeta) tableMetaTSDB).setFilter(eventFilter);
((DatabaseTableMeta) tableMetaTSDB).setBlackFilter(eventBlackFilter);
((DatabaseTableMeta) tableMetaTSDB).setSnapshotInterval(tsdbSnapshotInterval);
((DatabaseTableMeta) tableMetaTSDB).setSnapshotExpire(tsdbSnapshotExpire);
((DatabaseTableMeta) tableMetaTSDB).init(destination);
}
tableMetaCache = new TableMetaCache(metaConnection, tableMetaTSDB);
((LogEventConvert) binlogParser).setTableMetaCache(tableMetaCache);
}
}
protected void afterDump(ErosaConnection connection) {
super.afterDump(connection);
if (connection == null) {
throw new CanalParseException("illegal connection is null");
}
if (!(connection instanceof MysqlConnection)) {
throw new CanalParseException("Unsupported connection type : " + connection.getClass().getSimpleName());
}
if (metaConnection != null) {
try {
metaConnection.disconnect();
} catch (IOException e) {
logger.error("ERROR # disconnect meta connection for address:{}", metaConnection.getConnector()
.getAddress(), e);
}
}
}
public void start() throws CanalParseException {
if (runningInfo == null) { // 第一次链接主库
runningInfo = masterInfo;
}
super.start();
}
public void stop() throws CanalParseException {
if (metaConnection != null) {
try {
metaConnection.disconnect();
} catch (IOException e) {
logger.error("ERROR # disconnect meta connection for address:{}", metaConnection.getConnector()
.getAddress(), e);
}
}
if (tableMetaCache != null) {
tableMetaCache.clearTableMeta();
}
super.stop();
}
protected TimerTask buildHeartBeatTimeTask(ErosaConnection connection) {
if (!(connection instanceof MysqlConnection)) {
throw new CanalParseException("Unsupported connection type : " + connection.getClass().getSimpleName());
}
// 开始mysql心跳sql
if (detectingEnable && StringUtils.isNotBlank(detectingSQL)) {
return new MysqlDetectingTimeTask((MysqlConnection) connection.fork());
} else {
return super.buildHeartBeatTimeTask(connection);
}
}
protected void stopHeartBeat() {
TimerTask heartBeatTimerTask = this.heartBeatTimerTask;
super.stopHeartBeat();
if (heartBeatTimerTask != null && heartBeatTimerTask instanceof MysqlDetectingTimeTask) {
MysqlConnection mysqlConnection = ((MysqlDetectingTimeTask) heartBeatTimerTask).getMysqlConnection();
try {
mysqlConnection.disconnect();
} catch (IOException e) {
logger.error("ERROR # disconnect heartbeat connection for address:{}", mysqlConnection.getConnector()
.getAddress(), e);
}
}
}
/**
* 心跳信息
*
* @author jianghang 2012-7-6 下午02:50:15
* @version 1.0.0
*/
class MysqlDetectingTimeTask extends TimerTask {
private boolean reconnect = false;
private MysqlConnection mysqlConnection;
public MysqlDetectingTimeTask(MysqlConnection mysqlConnection){
this.mysqlConnection = mysqlConnection;
}
public void run() {
try {
if (reconnect) {
reconnect = false;
mysqlConnection.reconnect();
} else if (!mysqlConnection.isConnected()) {
mysqlConnection.connect();
}
long startTime = System.currentTimeMillis();
// 可能心跳sql为select 1
if (StringUtils.startsWithIgnoreCase(detectingSQL.trim(), "select")
|| StringUtils.startsWithIgnoreCase(detectingSQL.trim(), "show")
|| StringUtils.startsWithIgnoreCase(detectingSQL.trim(), "explain")
|| StringUtils.startsWithIgnoreCase(detectingSQL.trim(), "desc")) {
mysqlConnection.query(detectingSQL);
} else {
mysqlConnection.update(detectingSQL);
}
long costTime = System.currentTimeMillis() - startTime;
if (haController != null && haController instanceof HeartBeatCallback) {
((HeartBeatCallback) haController).onSuccess(costTime);
}
} catch (Throwable e) {
if (haController != null && haController instanceof HeartBeatCallback) {
((HeartBeatCallback) haController).onFailed(e);
}
reconnect = true;
logger.warn("connect failed by ", e);
}
}
public MysqlConnection getMysqlConnection() {
return mysqlConnection;
}
}
// 处理主备切换的逻辑
public void doSwitch() {
AuthenticationInfo newRunningInfo = (runningInfo.equals(masterInfo) ? standbyInfo : masterInfo);
this.doSwitch(newRunningInfo);
}
public void doSwitch(AuthenticationInfo newRunningInfo) {
// 1. 需要停止当前正在复制的过程
// 2. 找到新的position点
// 3. 重新建立链接,开始复制数据
// 切换ip
String alarmMessage = null;
if (this.runningInfo.equals(newRunningInfo)) {
alarmMessage = "same runingInfo switch again : " + runningInfo.getAddress().toString();
logger.warn(alarmMessage);
return;
}
if (newRunningInfo == null) {
alarmMessage = "no standby config, just do nothing, will continue try:"
+ runningInfo.getAddress().toString();
logger.warn(alarmMessage);
sendAlarm(destination, alarmMessage);
return;
} else {
stop();
alarmMessage = "try to ha switch, old:" + runningInfo.getAddress().toString() + ", new:"
+ newRunningInfo.getAddress().toString();
logger.warn(alarmMessage);
sendAlarm(destination, alarmMessage);
runningInfo = newRunningInfo;
start();
}
}
// =================== helper method =================
private MysqlConnection buildMysqlConnection(AuthenticationInfo runningInfo) {
MysqlConnection connection = new MysqlConnection(runningInfo.getAddress(),
runningInfo.getUsername(),
runningInfo.getPassword(),
connectionCharsetNumber,
runningInfo.getDefaultDatabaseName());
connection.getConnector().setReceiveBufferSize(receiveBufferSize);
connection.getConnector().setSendBufferSize(sendBufferSize);
connection.getConnector().setSoTimeout(defaultConnectionTimeoutInSeconds * 1000);
connection.setCharset(connectionCharset);
connection.setReceivedBinlogBytes(receivedBinlogBytes);
// 随机生成slaveId
if (this.slaveId <= 0) {
this.slaveId = generateUniqueServerId();
}
connection.setSlaveId(this.slaveId);
return connection;
}
private final long generateUniqueServerId() {
try {
// a=`echo $masterip|cut -d\. -f1`
// b=`echo $masterip|cut -d\. -f2`
// c=`echo $masterip|cut -d\. -f3`
// d=`echo $masterip|cut -d\. -f4`
// #server_id=`expr $a \* 256 \* 256 \* 256 + $b \* 256 \* 256 + $c
// \* 256 + $d `
// #server_id=$b$c$d
// server_id=`expr $b \* 256 \* 256 + $c \* 256 + $d `
InetAddress localHost = InetAddress.getLocalHost();
byte[] addr = localHost.getAddress();
int salt = (destination != null) ? destination.hashCode() : 0;
return ((0x7f & salt) << 24) + ((0xff & (int) addr[1]) << 16) // NL
+ ((0xff & (int) addr[2]) << 8) // NL
+ (0xff & (int) addr[3]);
} catch (UnknownHostException e) {
throw new CanalParseException("Unknown host", e);
}
}
protected EntryPosition findStartPosition(ErosaConnection connection) throws IOException {
if (isGTIDMode()) {
// GTID模式下,CanalLogPositionManager里取最后的gtid,没有则取instance配置中的
LogPosition logPosition = getLogPositionManager().getLatestIndexBy(destination);
if (logPosition != null) {
// 如果以前是非GTID模式,后来调整为了GTID模式,那么为了保持兼容,需要判断gtid是否为空
if (StringUtils.isNotEmpty(logPosition.getPostion().getGtid())) {
return logPosition.getPostion();
}
} else {
if (masterPosition != null && StringUtils.isNotEmpty(masterPosition.getGtid())) {
return masterPosition;
}
}
}
EntryPosition startPosition = findStartPositionInternal(connection);
if (needTransactionPosition.get()) {
logger.warn("prepare to find last position : {}", startPosition.toString());
Long preTransactionStartPosition = findTransactionBeginPosition(connection, startPosition);
if (!preTransactionStartPosition.equals(startPosition.getPosition())) {
logger.warn("find new start Transaction Position , old : {} , new : {}",
startPosition.getPosition(),
preTransactionStartPosition);
startPosition.setPosition(preTransactionStartPosition);
}
needTransactionPosition.compareAndSet(true, false);
}
return startPosition;
}
protected EntryPosition findEndPosition(ErosaConnection connection) throws IOException {
MysqlConnection mysqlConnection = (MysqlConnection) connection;
EntryPosition endPosition = findEndPosition(mysqlConnection);
return endPosition;
}
protected EntryPosition findEndPositionWithMasterIdAndTimestamp(MysqlConnection connection) {
MysqlConnection mysqlConnection = (MysqlConnection) connection;
final EntryPosition endPosition = findEndPosition(mysqlConnection);
if (tableMetaTSDB != null || isGTIDMode()) {
long startTimestamp = System.currentTimeMillis();
return findAsPerTimestampInSpecificLogFile(mysqlConnection,
startTimestamp,
endPosition,
endPosition.getJournalName(),
true);
} else {
return endPosition;
}
}
protected EntryPosition findPositionWithMasterIdAndTimestamp(MysqlConnection connection, EntryPosition fixedPosition) {
MysqlConnection mysqlConnection = (MysqlConnection) connection;
if (tableMetaTSDB != null && (fixedPosition.getTimestamp() == null || fixedPosition.getTimestamp() <= 0)) {
// 使用一个未来极大的时间,基于位点进行定位
long startTimestamp = System.currentTimeMillis() + 102L * 365 * 24 * 3600 * 1000; // 当前时间的未来102年
EntryPosition entryPosition = findAsPerTimestampInSpecificLogFile(mysqlConnection,
startTimestamp,
fixedPosition,
fixedPosition.getJournalName(),
true);
if (entryPosition == null) {
throw new CanalParseException("[fixed timestamp] can't found begin/commit position before with fixed position "
+ fixedPosition.getJournalName() + ":" + fixedPosition.getPosition());
}
return entryPosition;
} else {
return fixedPosition;
}
}
protected EntryPosition findStartPositionInternal(ErosaConnection connection) {
MysqlConnection mysqlConnection = (MysqlConnection) connection;
LogPosition logPosition = logPositionManager.getLatestIndexBy(destination);
if (logPosition == null) {// 找不到历史成功记录
EntryPosition entryPosition = null;
if (masterInfo != null && mysqlConnection.getConnector().getAddress().equals(masterInfo.getAddress())) {
entryPosition = masterPosition;
} else if (standbyInfo != null
&& mysqlConnection.getConnector().getAddress().equals(standbyInfo.getAddress())) {
entryPosition = standbyPosition;
}
if (entryPosition == null) {
entryPosition =
findEndPositionWithMasterIdAndTimestamp(mysqlConnection); // 默认从当前最后一个位置进行消费
}
// 判断一下是否需要按时间订阅
if (StringUtils.isEmpty(entryPosition.getJournalName())) {
// 如果没有指定binlogName,尝试按照timestamp进行查找
if (entryPosition.getTimestamp() != null && entryPosition.getTimestamp() > 0L) {
logger.warn("prepare to find start position {}:{}:{}",
new Object[] { "", "", entryPosition.getTimestamp() });
return findByStartTimeStamp(mysqlConnection, entryPosition.getTimestamp());
} else {
logger.warn("prepare to find start position just show master status");
return findEndPositionWithMasterIdAndTimestamp(mysqlConnection); // 默认从当前最后一个位置进行消费
}
} else {
if (entryPosition.getPosition() != null && entryPosition.getPosition() > 0L) {
// 如果指定binlogName + offest,直接返回
entryPosition = findPositionWithMasterIdAndTimestamp(mysqlConnection, entryPosition);
logger.warn("prepare to find start position {}:{}:{}",
new Object[] { entryPosition.getJournalName(), entryPosition.getPosition(),
entryPosition.getTimestamp() });
return entryPosition;
} else {
EntryPosition specificLogFilePosition = null;
if (entryPosition.getTimestamp() != null && entryPosition.getTimestamp() > 0L) {
// 如果指定binlogName +
// timestamp,但没有指定对应的offest,尝试根据时间找一下offest
EntryPosition endPosition = findEndPosition(mysqlConnection);
if (endPosition != null) {
logger.warn("prepare to find start position {}:{}:{}",
new Object[] { entryPosition.getJournalName(), "", entryPosition.getTimestamp() });
specificLogFilePosition = findAsPerTimestampInSpecificLogFile(mysqlConnection,
entryPosition.getTimestamp(),
endPosition,
entryPosition.getJournalName(),
true);
}
}
if (specificLogFilePosition == null) {
if (isRdsOssMode()) {
// 如果binlog位点不存在,并且属于timestamp不为空,可以返回null走到oss binlog处理
return null;
}
// position不存在,从文件头开始
entryPosition.setPosition(BINLOG_START_OFFEST);
return entryPosition;
} else {
return specificLogFilePosition;
}
}
}
} else {
if (logPosition.getIdentity().getSourceAddress().equals(mysqlConnection.getConnector().getAddress())) {
if (dumpErrorCountThreshold >= 0 && dumpErrorCount > dumpErrorCountThreshold) {
// binlog定位位点失败,可能有两个原因:
// 1. binlog位点被删除
// 2.vip模式的mysql,发生了主备切换,判断一下serverId是否变化,针对这种模式可以发起一次基于时间戳查找合适的binlog位点
boolean case2 = (standbyInfo == null || standbyInfo.getAddress() == null)
&& logPosition.getPostion().getServerId() != null
&& !logPosition.getPostion().getServerId().equals(findServerId(mysqlConnection));
if (case2) {
EntryPosition findPosition = fallbackFindByStartTimestamp(logPosition, mysqlConnection);
dumpErrorCount = 0;
return findPosition;
}
// 处理 binlog 位点被删除的情况,提供自动重置到当前位点的功能
// 应用场景: 测试环境不稳定,位点经常被删。强烈不建议在正式环境中开启此控制参数,因为binlog
// 丢失调到最新位点也即意味着数据丢失
if (isAutoResetLatestPosMode()) {
dumpErrorCount = 0;
return findEndPosition(mysqlConnection);
}
Long timestamp = logPosition.getPostion().getTimestamp();
if (isRdsOssMode() && (timestamp != null && timestamp > 0)) {
// 如果binlog位点不存在,并且属于timestamp不为空,可以返回null走到oss binlog处理
return null;
}
} else if (StringUtils.isBlank(logPosition.getPostion().getJournalName())
&& logPosition.getPostion().getPosition() <= 0
&& logPosition.getPostion().getTimestamp() > 0) {
return fallbackFindByStartTimestamp(logPosition, mysqlConnection);
}
// 其余情况
logger.warn("prepare to find start position just last position\n {}",
JsonUtils.marshalToString(logPosition));
return logPosition.getPostion();
} else {
// 针对切换的情况,考虑回退时间
long newStartTimestamp = logPosition.getPostion().getTimestamp() - fallbackIntervalInSeconds * 1000;
logger.warn("prepare to find start position by switch {}:{}:{}", new Object[] { "", "",
logPosition.getPostion().getTimestamp() });
return findByStartTimeStamp(mysqlConnection, newStartTimestamp);
}
}
}
/**
* find position by timestamp with a fallback interval seconds.
*
* @param logPosition
* @param mysqlConnection
* @return
*/
protected EntryPosition fallbackFindByStartTimestamp(LogPosition logPosition, MysqlConnection mysqlConnection) {
long timestamp = logPosition.getPostion().getTimestamp();
long newStartTimestamp = timestamp - fallbackIntervalInSeconds * 1000;
logger.warn("prepare to find start position by last position {}:{}:{}", new Object[] { "", "",
logPosition.getPostion().getTimestamp() });
return findByStartTimeStamp(mysqlConnection, newStartTimestamp);
}
// 根据想要的position,可能这个position对应的记录为rowdata,需要找到事务头,避免丢数据
// 主要考虑一个事务执行时间可能会几秒种,如果仅仅按照timestamp相同,则可能会丢失事务的前半部分数据
private Long findTransactionBeginPosition(ErosaConnection mysqlConnection, final EntryPosition entryPosition)
throws IOException {
// 针对开始的第一条为非Begin记录,需要从该binlog扫描
final java.util.concurrent.atomic.AtomicLong preTransactionStartPosition = new java.util.concurrent.atomic.AtomicLong(0L);
mysqlConnection.reconnect();
mysqlConnection.seek(entryPosition.getJournalName(), 4L, entryPosition.getGtid(), new SinkFunction<LogEvent>() {
private LogPosition lastPosition;
public boolean sink(LogEvent event) {
try {
CanalEntry.Entry entry = parseAndProfilingIfNecessary(event, true);
if (entry == null) {
return true;
}
// 直接查询第一条业务数据,确认是否为事务Begin
// 记录一下transaction begin position
if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN
&& entry.getHeader().getLogfileOffset() < entryPosition.getPosition()) {
preTransactionStartPosition.set(entry.getHeader().getLogfileOffset());
}
if (entry.getHeader().getLogfileOffset() >= entryPosition.getPosition()) {
return false;// 退出
}
lastPosition = buildLastPosition(entry);
} catch (Exception e) {
processSinkError(e, lastPosition, entryPosition.getJournalName(), entryPosition.getPosition());
return false;
}
return running;
}
});
// 判断一下找到的最接近position的事务头的位置
if (preTransactionStartPosition.get() > entryPosition.getPosition()) {
logger.error("preTransactionEndPosition greater than startPosition from zk or localconf, maybe lost data");
throw new CanalParseException("preTransactionStartPosition greater than startPosition from zk or localconf, maybe lost data");
}
return preTransactionStartPosition.get();
}
// 根据时间查找binlog位置
private EntryPosition findByStartTimeStamp(MysqlConnection mysqlConnection, Long startTimestamp) {
EntryPosition endPosition = findEndPosition(mysqlConnection);
EntryPosition startPosition = findStartPosition(mysqlConnection);
String maxBinlogFileName = endPosition.getJournalName();
String minBinlogFileName = startPosition.getJournalName();
logger.info("show master status to set search end condition:{} ", endPosition);
String startSearchBinlogFile = endPosition.getJournalName();
boolean shouldBreak = false;
while (running && !shouldBreak) {
try {
EntryPosition entryPosition = findAsPerTimestampInSpecificLogFile(mysqlConnection,
startTimestamp,
endPosition,
startSearchBinlogFile,
false);
if (entryPosition == null) {
if (StringUtils.equalsIgnoreCase(minBinlogFileName, startSearchBinlogFile)) {
// 已经找到最早的一个binlog,没必要往前找了
shouldBreak = true;
logger.warn("Didn't find the corresponding binlog files from {} to {}",
minBinlogFileName,
maxBinlogFileName);
} else {
// 继续往前找
int binlogSeqNum = Integer.parseInt(startSearchBinlogFile.substring(startSearchBinlogFile.indexOf(".") + 1));
if (binlogSeqNum <= 1) {
logger.warn("Didn't find the corresponding binlog files");
shouldBreak = true;
} else {
int nextBinlogSeqNum = binlogSeqNum - 1;
String binlogFileNamePrefix = startSearchBinlogFile.substring(0,
startSearchBinlogFile.indexOf(".") + 1);
String binlogFileNameSuffix = String.format("%06d", nextBinlogSeqNum);
startSearchBinlogFile = binlogFileNamePrefix + binlogFileNameSuffix;
}
}
} else {
logger.info("found and return:{} in findByStartTimeStamp operation.", entryPosition);
return entryPosition;
}
} catch (Exception e) {
logger.warn(String.format("the binlogfile:%s doesn't exist, to continue to search the next binlogfile , caused by",
startSearchBinlogFile),
e);
int binlogSeqNum = Integer.parseInt(startSearchBinlogFile.substring(startSearchBinlogFile.indexOf(".") + 1));
if (binlogSeqNum <= 1) {
logger.warn("Didn't find the corresponding binlog files");
shouldBreak = true;
} else {
int nextBinlogSeqNum = binlogSeqNum - 1;
String binlogFileNamePrefix = startSearchBinlogFile.substring(0,
startSearchBinlogFile.indexOf(".") + 1);
String binlogFileNameSuffix = String.format("%06d", nextBinlogSeqNum);
startSearchBinlogFile = binlogFileNamePrefix + binlogFileNameSuffix;
}
}
}
// 找不到
return null;
}
/**
* 查询当前db的serverId信息
*/
private Long findServerId(MysqlConnection mysqlConnection) {
try {
ResultSetPacket packet = mysqlConnection.query("show variables like 'server_id'");
List<String> fields = packet.getFieldValues();
if (CollectionUtils.isEmpty(fields)) {
throw new CanalParseException("command : show variables like 'server_id' has an error! pls check. you need (at least one of) the SUPER,REPLICATION CLIENT privilege(s) for this operation");
}
return Long.valueOf(fields.get(1));
} catch (IOException e) {
throw new CanalParseException("command : show variables like 'server_id' has an error!", e);
}
}
/**
* 查询当前的binlog位置
*/
private EntryPosition findEndPosition(MysqlConnection mysqlConnection) {
try {
String showSql = multiStreamEnable ? "show master status with " + destination : "show master status";
ResultSetPacket packet = mysqlConnection.query(showSql);
List<String> fields = packet.getFieldValues();
if (CollectionUtils.isEmpty(fields)) {
throw new CanalParseException(
"command : 'show master status' has an error! pls check. you need (at least one of) the SUPER,REPLICATION CLIENT privilege(s) for this operation");
}
EntryPosition endPosition = new EntryPosition(fields.get(0), Long.valueOf(fields.get(1)));
if (isGTIDMode() && fields.size() > 4) {
endPosition.setGtid(fields.get(4));
}
// MariaDB 无法通过`show master status`获取 gtid
if (mysqlConnection.isMariaDB() && isGTIDMode()) {
ResultSetPacket gtidPacket = mysqlConnection.query("SELECT @@global.gtid_binlog_pos");
List<String> gtidFields = gtidPacket.getFieldValues();
if (!CollectionUtils.isEmpty(gtidFields) && gtidFields.size() > 0) {
endPosition.setGtid(gtidFields.get(0));
}
}
return endPosition;
} catch (IOException e) {
throw new CanalParseException("command : 'show master status' has an error!", e);
}
}
/**
* 查询当前的binlog位置
*/
private EntryPosition findStartPosition(MysqlConnection mysqlConnection) {
try {
String showSql = multiStreamEnable ?
"show binlog events with " + destination + " limit 1" : "show binlog events limit 1";
ResultSetPacket packet = mysqlConnection.query(showSql);
List<String> fields = packet.getFieldValues();
if (CollectionUtils.isEmpty(fields)) {
throw new CanalParseException(
"command : 'show binlog events limit 1' has an error! pls check. you need (at least one of) the SUPER,REPLICATION CLIENT privilege(s) for this operation");
}
EntryPosition endPosition = new EntryPosition(fields.get(0), Long.valueOf(fields.get(1)));
return endPosition;
} catch (IOException e) {
throw new CanalParseException("command : 'show binlog events limit 1' has an error!", e);
}
}
/**
* 查询当前的slave视图的binlog位置
*/
@SuppressWarnings("unused")
private SlaveEntryPosition findSlavePosition(MysqlConnection mysqlConnection) {
try {
ResultSetPacket packet = mysqlConnection.query("show slave status");
List<FieldPacket> names = packet.getFieldDescriptors();
List<String> fields = packet.getFieldValues();
if (CollectionUtils.isEmpty(fields)) {
return null;
}
int i = 0;
Map<String, String> maps = new HashMap<>(names.size(), 1f);
for (FieldPacket name : names) {
maps.put(name.getName(), fields.get(i));
i++;
}
String errno = maps.get("Last_Errno");
String slaveIORunning = maps.get("Slave_IO_Running"); // Slave_SQL_Running
String slaveSQLRunning = maps.get("Slave_SQL_Running"); // Slave_SQL_Running
if ((!"0".equals(errno)) || (!"Yes".equalsIgnoreCase(slaveIORunning))
|| (!"Yes".equalsIgnoreCase(slaveSQLRunning))) {
logger.warn("Ignoring failed slave: " + mysqlConnection.getConnector().getAddress() + ", Last_Errno = "
+ errno + ", Slave_IO_Running = " + slaveIORunning + ", Slave_SQL_Running = "
+ slaveSQLRunning);
return null;
}
String masterHost = maps.get("Master_Host");
String masterPort = maps.get("Master_Port");
String binlog = maps.get("Master_Log_File");
String position = maps.get("Exec_Master_Log_Pos");
return new SlaveEntryPosition(binlog, Long.valueOf(position), masterHost, masterPort);
} catch (IOException e) {
logger.error("find slave position error", e);
}
return null;
}
/**
* 根据给定的时间戳,在指定的binlog中找到最接近于该时间戳(必须是小于时间戳)的一个事务起始位置。
* 针对最后一个binlog会给定endPosition,避免无尽的查询
*/
private EntryPosition findAsPerTimestampInSpecificLogFile(MysqlConnection mysqlConnection,
final Long startTimestamp,
final EntryPosition endPosition,
final String searchBinlogFile,
final Boolean justForPositionTimestamp) {
final LogPosition logPosition = new LogPosition();
try {
mysqlConnection.reconnect();
// 开始遍历文件
mysqlConnection.seek(searchBinlogFile, 4L, endPosition.getGtid(), new SinkFunction<LogEvent>() {
private LogPosition lastPosition;
public boolean sink(LogEvent event) {
EntryPosition entryPosition = null;
try {
CanalEntry.Entry entry = parseAndProfilingIfNecessary(event, true);
if (justForPositionTimestamp && logPosition.getPostion() == null && event.getWhen() > 0) {
// 初始位点
entryPosition = new EntryPosition(searchBinlogFile,
event.getLogPos() - event.getEventLen(),
event.getWhen() * 1000,
event.getServerId());
entryPosition.setGtid(event.getHeader().getGtidSetStr());
logPosition.setPostion(entryPosition);
}
// 直接用event的位点来处理,解决一个binlog文件里没有任何事件导致死循环无法退出的问题
String logfilename = event.getHeader().getLogFileName();
// 记录的是binlog end offest,
// 因为与其对比的offest是show master status里的end offest
Long logfileoffset = event.getHeader().getLogPos();
Long logposTimestamp = event.getHeader().getWhen() * 1000;
Long serverId = event.getHeader().getServerId();
// 如果最小的一条记录都不满足条件,可直接退出
if (logposTimestamp >= startTimestamp) {
return false;
}
if (StringUtils.equals(endPosition.getJournalName(), logfilename)
&& endPosition.getPosition() <= logfileoffset) {
return false;
}
if (entry == null) {
return true;
}
// 记录一下上一个事务结束的位置,即下一个事务的position
// position = current +
// data.length,代表该事务的下一条offest,避免多余的事务重复
if (CanalEntry.EntryType.TRANSACTIONEND.equals(entry.getEntryType())) {
entryPosition = new EntryPosition(logfilename, logfileoffset, logposTimestamp, serverId);
if (logger.isDebugEnabled()) {
logger.debug("set {} to be pending start position before finding another proper one...",
entryPosition);
}
logPosition.setPostion(entryPosition);
entryPosition.setGtid(entry.getHeader().getGtid());
} else if (CanalEntry.EntryType.TRANSACTIONBEGIN.equals(entry.getEntryType())) {
// 当前事务开始位点
entryPosition = new EntryPosition(logfilename, logfileoffset, logposTimestamp, serverId);
if (logger.isDebugEnabled()) {
logger.debug("set {} to be pending start position before finding another proper one...",
entryPosition);
}
entryPosition.setGtid(entry.getHeader().getGtid());
logPosition.setPostion(entryPosition);
}
lastPosition = buildLastPosition(entry);
} catch (Throwable e) {
processSinkError(e, lastPosition, searchBinlogFile, 4L);
}
return running;
}
});
} catch (IOException e) {
logger.error("ERROR ## findAsPerTimestampInSpecificLogFile has an error", e);
}
if (logPosition.getPostion() != null) {
return logPosition.getPostion();
} else {
return null;
}
}
@Override
protected void processDumpError(Throwable e) {
if (e instanceof IOException) {
String message = e.getMessage();
if (StringUtils.contains(message, "errno = 1236")) {
// 1236 errorCode代表ER_MASTER_FATAL_ERROR_READING_BINLOG
dumpErrorCount++;
}
}
super.processDumpError(e);
}
public void setSupportBinlogFormats(String formatStrs) {
String[] formats = StringUtils.split(formatStrs, ',');
if (formats != null) {
BinlogFormat[] supportBinlogFormats = new BinlogFormat[formats.length];
int i = 0;
for (String format : formats) {
supportBinlogFormats[i++] = BinlogFormat.valuesOf(format);
}
this.supportBinlogFormats = supportBinlogFormats;
}
}
public void setSupportBinlogImages(String imageStrs) {
String[] images = StringUtils.split(imageStrs, ',');
if (images != null) {
BinlogImage[] supportBinlogImages = new BinlogImage[images.length];
int i = 0;
for (String image : images) {
supportBinlogImages[i++] = BinlogImage.valuesOf(image);
}
this.supportBinlogImages = supportBinlogImages;
}
}
// ===================== setter / getter ========================
public void setDefaultConnectionTimeoutInSeconds(int defaultConnectionTimeoutInSeconds) {
this.defaultConnectionTimeoutInSeconds = defaultConnectionTimeoutInSeconds;
}
public void setReceiveBufferSize(int receiveBufferSize) {
this.receiveBufferSize = receiveBufferSize;
}
public void setSendBufferSize(int sendBufferSize) {
this.sendBufferSize = sendBufferSize;
}
public void setMasterInfo(AuthenticationInfo masterInfo) {
this.masterInfo = masterInfo;
}
public void setStandbyInfo(AuthenticationInfo standbyInfo) {
this.standbyInfo = standbyInfo;
}
public void setMasterPosition(EntryPosition masterPosition) {
this.masterPosition = masterPosition;
}
public void setStandbyPosition(EntryPosition standbyPosition) {
this.standbyPosition = standbyPosition;
}
public void setSlaveId(long slaveId) {
this.slaveId = slaveId;
}
public void setDetectingSQL(String detectingSQL) {
this.detectingSQL = detectingSQL;
}
public void setDetectingIntervalInSeconds(Integer detectingIntervalInSeconds) {
this.detectingIntervalInSeconds = detectingIntervalInSeconds;
}
public void setDetectingEnable(boolean detectingEnable) {
this.detectingEnable = detectingEnable;
}
public void setFallbackIntervalInSeconds(int fallbackIntervalInSeconds) {
this.fallbackIntervalInSeconds = fallbackIntervalInSeconds;
}
public CanalHAController getHaController() {
return haController;
}
public void setHaController(CanalHAController haController) {
this.haController = haController;
}
public void setDumpErrorCountThreshold(int dumpErrorCountThreshold) {
this.dumpErrorCountThreshold = dumpErrorCountThreshold;
}
public boolean isRdsOssMode() {
return rdsOssMode;
}
public void setRdsOssMode(boolean rdsOssMode) {
this.rdsOssMode = rdsOssMode;
}
public void setDumpErrorCount(int dumpErrorCount) {
this.dumpErrorCount = dumpErrorCount;
}
public boolean isAutoResetLatestPosMode() {
return autoResetLatestPosMode;
}
public void setAutoResetLatestPosMode(boolean autoResetLatestPosMode) {
this.autoResetLatestPosMode = autoResetLatestPosMode;
}
public void setMultiStreamEnable(boolean multiStreamEnable) {
this.multiStreamEnable = multiStreamEnable;
}
}
| alibaba/canal | parse/src/main/java/com/alibaba/otter/canal/parse/inbound/mysql/MysqlEventParser.java |
656 | package cn.hutool.core.lang;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import java.util.Scanner;
import static java.lang.System.err;
import static java.lang.System.out;
/**
* 命令行(控制台)工具方法类<br>
* 此类主要针对{@link System#out} 和 {@link System#err} 做封装。
*
* @author Looly
*/
public class Console {
private static final String TEMPLATE_VAR = "{}";
// --------------------------------------------------------------------------------- Log
/**
* 同 System.out.println()方法,打印控制台日志
*/
public static void log() {
out.println();
}
/**
* 同 System.out.println()方法,打印控制台日志<br>
* 如果传入打印对象为{@link Throwable}对象,那么同时打印堆栈
*
* @param obj 要打印的对象
*/
public static void log(Object obj) {
if (obj instanceof Throwable) {
final Throwable e = (Throwable) obj;
log(e, e.getMessage());
} else {
log(TEMPLATE_VAR, obj);
}
}
/**
* 同 System.out.println()方法,打印控制台日志<br>
* 如果传入打印对象为{@link Throwable}对象,那么同时打印堆栈
*
* @param obj1 第一个要打印的对象
* @param otherObjs 其它要打印的对象
* @since 5.4.3
*/
public static void log(Object obj1, Object... otherObjs) {
if (ArrayUtil.isEmpty(otherObjs)) {
log(obj1);
} else {
log(buildTemplateSplitBySpace(otherObjs.length + 1), ArrayUtil.insert(otherObjs, 0, obj1));
}
}
/**
* 同 System.out.println()方法,打印控制台日志<br>
* 当传入template无"{}"时,被认为非模板,直接打印多个参数以空格分隔
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param values 值
*/
public static void log(String template, Object... values) {
if (ArrayUtil.isEmpty(values) || StrUtil.contains(template, TEMPLATE_VAR)) {
logInternal(template, values);
} else {
logInternal(buildTemplateSplitBySpace(values.length + 1), ArrayUtil.insert(values, 0, template));
}
}
/**
* 同 System.out.println()方法,打印控制台日志
*
* @param t 异常对象
* @param template 文本模板,被替换的部分用 {} 表示
* @param values 值
*/
public static void log(Throwable t, String template, Object... values) {
out.println(StrUtil.format(template, values));
if (null != t) {
//noinspection CallToPrintStackTrace
t.printStackTrace(out);
out.flush();
}
}
/**
* 同 System.out.println()方法,打印控制台日志
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param values 值
* @since 5.4.3
*/
private static void logInternal(String template, Object... values) {
log(null, template, values);
}
// --------------------------------------------------------------------------------- print
/**
* 打印表格到控制台
*
* @param consoleTable 控制台表格
* @since 5.4.5
*/
public static void table(ConsoleTable consoleTable) {
print(consoleTable.toString());
}
/**
* 同 System.out.print()方法,打印控制台日志
*
* @param obj 要打印的对象
* @since 3.3.1
*/
public static void print(Object obj) {
print(TEMPLATE_VAR, obj);
}
/**
* 同 System.out.println()方法,打印控制台日志<br>
* 如果传入打印对象为{@link Throwable}对象,那么同时打印堆栈
*
* @param obj1 第一个要打印的对象
* @param otherObjs 其它要打印的对象
* @since 5.4.3
*/
public static void print(Object obj1, Object... otherObjs) {
if (ArrayUtil.isEmpty(otherObjs)) {
print(obj1);
} else {
print(buildTemplateSplitBySpace(otherObjs.length + 1), ArrayUtil.insert(otherObjs, 0, obj1));
}
}
/**
* 同 System.out.print()方法,打印控制台日志
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param values 值
* @since 3.3.1
*/
public static void print(String template, Object... values) {
if (ArrayUtil.isEmpty(values) || StrUtil.contains(template, TEMPLATE_VAR)) {
printInternal(template, values);
} else {
printInternal(buildTemplateSplitBySpace(values.length + 1), ArrayUtil.insert(values, 0, template));
}
}
/**
* 打印进度条
*
* @param showChar 进度条提示字符,例如“#”
* @param len 打印长度
* @since 4.5.6
*/
public static void printProgress(char showChar, int len) {
print("{}{}", CharUtil.CR, StrUtil.repeat(showChar, len));
}
/**
* 打印进度条
*
* @param showChar 进度条提示字符,例如“#”
* @param totalLen 总长度
* @param rate 总长度所占比取值0~1
* @since 4.5.6
*/
public static void printProgress(char showChar, int totalLen, double rate) {
Assert.isTrue(rate >= 0 && rate <= 1, "Rate must between 0 and 1 (both include)");
printProgress(showChar, (int) (totalLen * rate));
}
/**
* 同 System.out.println()方法,打印控制台日志
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param values 值
* @since 5.4.3
*/
private static void printInternal(String template, Object... values) {
out.print(StrUtil.format(template, values));
}
// --------------------------------------------------------------------------------- Error
/**
* 同 System.err.println()方法,打印控制台日志
*/
public static void error() {
err.println();
}
/**
* 同 System.err.println()方法,打印控制台日志
*
* @param obj 要打印的对象
*/
public static void error(Object obj) {
if (obj instanceof Throwable) {
Throwable e = (Throwable) obj;
error(e, e.getMessage());
} else {
error(TEMPLATE_VAR, obj);
}
}
/**
* 同 System.out.println()方法,打印控制台日志<br>
* 如果传入打印对象为{@link Throwable}对象,那么同时打印堆栈
*
* @param obj1 第一个要打印的对象
* @param otherObjs 其它要打印的对象
* @since 5.4.3
*/
public static void error(Object obj1, Object... otherObjs) {
if (ArrayUtil.isEmpty(otherObjs)) {
error(obj1);
} else {
error(buildTemplateSplitBySpace(otherObjs.length + 1), ArrayUtil.insert(otherObjs, 0, obj1));
}
}
/**
* 同 System.err.println()方法,打印控制台日志
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param values 值
*/
public static void error(String template, Object... values) {
if (ArrayUtil.isEmpty(values) || StrUtil.contains(template, TEMPLATE_VAR)) {
errorInternal(template, values);
} else {
errorInternal(buildTemplateSplitBySpace(values.length + 1), ArrayUtil.insert(values, 0, template));
}
}
/**
* 同 System.err.println()方法,打印控制台日志
*
* @param t 异常对象
* @param template 文本模板,被替换的部分用 {} 表示
* @param values 值
*/
public static void error(Throwable t, String template, Object... values) {
err.println(StrUtil.format(template, values));
if (null != t) {
t.printStackTrace(err);
err.flush();
}
}
/**
* 同 System.err.println()方法,打印控制台日志
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param values 值
*/
private static void errorInternal(String template, Object... values) {
error(null, template, values);
}
// --------------------------------------------------------------------------------- in
/**
* 创建从控制台读取内容的{@link Scanner}
*
* @return {@link Scanner}
* @since 3.3.1
*/
public static Scanner scanner() {
return new Scanner(System.in);
}
/**
* 读取用户输入的内容(在控制台敲回车前的内容)
*
* @return 用户输入的内容
* @since 3.3.1
*/
public static String input() {
return scanner().nextLine();
}
// --------------------------------------------------------------------------------- console lineNumber
/**
* 返回当前位置+行号 (不支持Lambda、内部类、递归内使用)
*
* @return 返回当前行号
* @author dahuoyzs
* @since 5.2.5
*/
public static String where() {
final StackTraceElement stackTraceElement = new Throwable().getStackTrace()[1];
final String className = stackTraceElement.getClassName();
final String methodName = stackTraceElement.getMethodName();
final String fileName = stackTraceElement.getFileName();
final Integer lineNumber = stackTraceElement.getLineNumber();
return String.format("%s.%s(%s:%s)", className, methodName, fileName, lineNumber);
}
/**
* 返回当前行号 (不支持Lambda、内部类、递归内使用)
*
* @return 返回当前行号
* @since 5.2.5
*/
public static Integer lineNumber() {
return new Throwable().getStackTrace()[1].getLineNumber();
}
/**
* 构建空格分隔的模板,类似于"{} {} {} {}"
*
* @param count 变量数量
* @return 模板
*/
private static String buildTemplateSplitBySpace(int count) {
return StrUtil.repeatAndJoin(TEMPLATE_VAR, count, StrUtil.SPACE);
}
}
| dromara/hutool | hutool-core/src/main/java/cn/hutool/core/lang/Console.java |
657 | E
1531701138
tags: DP, Sequence DP
time: O(n)
space: O(n)
#### DP
- 最多2个fence 颜色相同
- 假设i是和 i-1不同,那么结果就是 (k-1)*dp[i - 1]
- 假设i是何 i-1相同,那么根据条件,i-1和i-2肯定不同。那么所有的结果就是(k-1)*dp[i-2]
- dp[i]: count # of ways to paint 前i个 fence
- 加法原理
- time, space: O(n)
- rolling array: space O(1)
#### Previous Notes
- 这题目很有意思. 一开始分析的太复杂, 最后按照这个哥们的想法(http://yuanhsh.iteye.com/blog/2219891) 的来做,反而简单了许多。
- 设定T(n)的做法,最后题目化简以后就跟Fibonacci number一样一样的。详细分析如下。
- 做完,还是觉得如有神。本来是个Easy题,想不到,就是搞不出。
```
/*
There is a fence with n posts, each post can be painted with one of the k colors.
You have to paint all the posts such that no more than two adjacent fence posts have the same color.
Return the total number of ways you can paint the fence.
Note:
n and k are non-negative integers.
Tags: Dynamic Programming
Similar Problems: (E) House Robber, (M) House Robber II, (M) Paint House, (H) Paint House II
*/
/*
Thoughts:
dp[i]: i ways to paint first i posts.
dp[i] depends on dp[i-1] or dp[i - 2]: no more than 2 adjacent same color means: dp[i] will differ from dp[i-1] or dp[i-2]
The remain color will be k
*/
class Solution {
public int numWays(int n, int k) {
// edge case
if (n <= 1 || k <= 0) {
return n * k;
}
// init dp[n+1]
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = k;
dp[2] = k + k * (k - 1); // [1,2] same color + [1,2] diff color
// process
for (int i = 3; i <= n; i++) {
dp[i] = (k - 1) * (dp[i - 1] + dp[i - 2]);
}
return dp[n];
}
}
// Rolling array, space O(1)
class Solution {
public int numWays(int n, int k) {
// edge case
if (n <= 1 || k <= 0) {
return n * k;
}
// init dp[n+1]
int[] dp = new int[3];
dp[0] = 0;
dp[1] = k;
dp[2] = k + k * (k - 1);
// process
for (int i = 3; i <= n; i++) {
dp[i % 3] = (k - 1) * (dp[(i - 1) % 3] + dp[(i - 2) % 3]);
}
return dp[n % 3];
}
}
/*
Thoughts:
Inspiration(http://yuanhsh.iteye.com/blog/2219891)
Consider posts from 1 ~ n. Now we look at last post, marked n:
S(n) means: last 2 fence posts have same color.
Note: S(n) will equal to whatever that's on n-1 position.
Also, just because n and n-1 are same, that means n-2 and n-1 have to be differnet.
SO:
S(n) = D(n - 1)
D(n) means: last 2 fence posts have different color.
Note: for n - 1, and n-2 positions, we have 2 different conditions:
For example: xxy, or wxy, same 2 x's or different w vs. x.
So:
D(n) = (k - 1) * (D(n - 1) + S(n - 1))
We can also create T(n) = S(n) + D(n); //T(n) is our totoal results. Will need to return T(n);
Use above equations to figure out T(n)
T(n) = S(n) + D(n) = D(n - 1) + (k - 1) * (D(n - 1) + S(n - 1))
= D(n - 1) + (k - 1)(T(n - 1))
= (k - 1) * (D(n - 2) + S(n - 2)) + (k - 1)(T(n - 1))
= (k - 1)(T(n - 1) + T(n - 2))
Since n-2 >=1, so n>=3. We need fiture out cases for n = 0,1,2,3
Note:
n == 1: just k ways
n == 0: just 0.
k == 0: just 0;
Besides these cases, we are okay. Btw, k does not really matter as long as it's >=1, it can be plugged in.
*/
``` | awangdev/leet-code | Java/Paint Fence.java |
658 | H
1524723994
tags: DP, Backpack DP
给n种不同的物品, int[] A weight, int[] V value, 每种物品可以用无限次
问最大多少value可以装进size是 m 的包?
#### DP
- 可以无限使用物品, 就失去了last i, last unique item的意义: 因为可以重复使用.
- 所以可以转换一个角度:
- 1. 用i **种** 物品, 拼出w, 并且满足题目条件(max value). 这里因为item i可以无限次使用, 所以考虑使用了多少次K.
- 2. K虽然可以无限, 但是也被 k*A[i]所限制: 最大不能超过背包大小.
- dp[i][w]: 前i种物品, fill weight w 的背包, 最大价值是多少.
- dp[i][w] = max {dp[i - 1][w - k*A[i-1]] + kV[i-1]}, k >= 0
- Time O(nmk)
- 如果k = 0 或者 1, 其实就是 Backpack II: 拿或者不拿
#### 优化
- 优化时间复杂度, 画图发现:
- 所计算的 (dp[i - 1][j - k*A[i - 1]] + k * V[i - 1])
- 其实跟同一行的 dp[i][j-A[i-1]] 那个格子, 就多出了 V[i-1]
- 所以没必要每次都 loop over k times
- 简化: dp[i][j] 其中一个可能就是: dp[i][j - A[i - 1]] + V[i - 1]
- Time O(mn)
#### 空间优化到1维数组
- 根据上一个优化的情况, 画出 2 rows 网格
- 发现 dp[i][j] 取决于: 1. dp[i - 1][j], 2. dp[i][j - A[i - 1]]
- 其中: dp[i - 1][j] 是上一轮 (i-1) 的结算结果, 一定是已经算好, ready to be used 的
- 然而, 当我们 i++,j++ 之后, 在之前 row = i - 1, col < j的格子, 全部不需要.
- 降维简化: 只需要留着 weigth 这个 dimension, 而i这个dimension 可以省略:
- (i - 1) row 不过是需要用到之前算出的旧value: 每一轮, j = [0 ~ m], 那么dp[j]本身就有记录旧值的功能.
- 变成1个一位数组
- 降维优化的重点: 看双行的左右计算方向
- Time(mn). Space(m)
```
/*
Given n kind of items with size Ai and value Vi
(each item has an infinite number available)
and a backpack with size m.
What's the maximum value can you put into the backpack?
Notice
You cannot divide item into small pieces and the total size of items
you choose should smaller or equal to m.
*/
/*
Thoughts:
dp[i][w]: first i types of items to fill weight w, find the max value.
1st loop: which type of item to pick from A
2nd loop: weight from 0 ~ m
3rd loop: # times when A[i] is used.
Goal: dp[n][m]
Condition1: didn't pick A[i - 1], dp[i][j] = dp[i - 1][j];
Condition2: pickced A[i - 1], dp[i][j] = dp[i - 1][j - k * A[i - 1]] + k * V[i - 1];
O(nmk)
*/
public class Solution {
public int backPackIII(int[] A, int[] V, int m) {
if (A == null || A.length == 0 || V == null || V.length == 0 || m <= 0) {
return 0;
}
int n = A.length;
int[][] dp = new int[n + 1][m + 1];
dp[0][0] = 0; // 0 items to fill 0 weight, value = 0
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = dp[i - 1][j];
for (int k = 1; k * A[i - 1] <= j; k++) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - k * A[i - 1]] + k * V[i - 1]);
}
}
}
return dp[n][m];
}
}
/**
Optimization1:
- 优化时间复杂度, 画图发现:
- 所计算的 (dp[i - 1][j - k*A[i - 1]] + k * V[i - 1])
- 其实跟同一行的 dp[i][j-A[i-1]] 那个格子, 就多出了 V[i-1]
- 所以没必要每次都 loop over k times
- 简化: dp[i][j] 其中一个可能就是: dp[i][j - A[i - 1]] + V[i - 1]
*/
public class Solution {
public int backPackIII(int[] A, int[] V, int m) {
if (A == null || A.length == 0 || V == null || V.length == 0 || m <= 0) {
return 0;
}
int n = A.length;
int[][] dp = new int[n + 1][m + 1];
dp[0][0] = 0; // 0 items to fill 0 weight, value = 0
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= m; j++) {
dp[i][j] = dp[i - 1][j];
if (j >= A[i - 1]) {
dp[i][j] = Math.max(dp[i][j], dp[i][j - A[i - 1]] + V[i - 1]);
}
}
}
return dp[n][m];
}
}
/**
Optimization2:
- 根据上一个优化的情况, 画出 2 rows 网格
- 发现 dp[i][j] 取决于: 1. dp[i - 1][j], 2. dp[i][j - A[i - 1]]
- 其中: dp[i - 1][j] 是上一轮 (i-1) 的结算结果, 一定是已经算好, ready to be used 的
- 然而, 当我们 i++,j++ 之后, 在之前 row = i - 1, col < j的格子, 全部不需要.
- 降维简化: 只需要留着 weigth 这个 dimension, 而i这个dimension 可以省略:
- (i - 1) row 不过是需要用到之前算出的旧value: 每一轮, j = [0 ~ m], 那么dp[j]本身就有记录旧值的功能.
*/
public class Solution {
public int backPackIII(int[] A, int[] V, int m) {
if (A == null || A.length == 0 || V == null || V.length == 0 || m <= 0) {
return 0;
}
int n = A.length;
int[] dp = new int[m + 1]; // DP on weight
dp[0] = 0; // 0 items to fill 0 weight, value = 0
for (int i = 1; i <= n; i++) {
for (int j = A[i - 1]; j <= m && j >= A[i - 1]; j++) {
dp[j] = Math.max(dp[j], dp[j - A[i - 1]] + V[i - 1]);
}
}
return dp[m];
}
}
/*
Thoughts:
Can pick any item for infinite times: there is no indicator of what's being picked last.
We don't know which item && how many times it was picked.
We should consider tracking: what type of items was picked how many times
(consider once done with 1 type of item, move on to others and never re-pick)
If A[i-1] was picked 0, 1, 2 ...., k times, then
dp[i][w] = max{dp[i - 1][j - k*A[i - 1]] + k*V[i - 1]}, where k >= 0 -> infinite
Space: O(mn)
Time: O(m * m * n) = O(nm^2)
*/
public class Solution {
public int backPackIII(int[] A, int[] V, int m) {
if (A == null || V == null || A.length != V.length) {
return 0;
}
int n = A.length;
int[][] dp = new int[n + 1][m + 1]; // max value with i items of weight w.
for (int j = 0; j <= m; j++) {
dp[0][j] = -1; // 0 items cannot form j weight, hence value = 0
}
dp[0][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= m; j++) { // for all weight j at i items
for (int k = 0; k * A[i - 1] <= m; k++) { // use A[i-1] for k times
if (j - k * A[i - 1] >= 0 && dp[i - 1][j - k * A[i - 1]] != -1) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - k * A[i - 1]] + k * V[i - 1]);
}
}
}
}
int rst = 0;
for (int j = 0; j <= m; j++) {
rst = Math.max(rst, dp[n][j]);
}
return rst;
}
}
// Optimization
// curve up
/*
dp[i][w] = max{dp[i - 1][j - k*A[i - 1]] + k*V[i - 1]}, where k >= 0 -> infinite
1. Every position, we are adding k*V[i - 1]
2. If we draw out how V[i-1] was being added alone with k = [0 ~ ...], we realize:
the next i is basically: max{...all k's possibilities} + V[i - 1]
So it reduces to:
dp[i][w] = max{dp[i - 1][w], dp[i][w - A[i-1]] + V[i-1]}
*/
public class Solution {
public int backPackIII(int[] A, int[] V, int m) {
if (A == null || V == null || A.length != V.length) {
return 0;
}
int n = A.length;
int[][] dp = new int[n + 1][m + 1]; // max value with i items of weight w.
for (int j = 0; j <= m; j++) {
dp[0][j] = -1; // 0 items cannot form j weight, hence value = 0
}
dp[0][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= m; j++) { // for all weight j at i items
dp[i][j] = dp[i - 1][j];
if (j - A[i - 1] >= 0) {
dp[i][j] = Math.max(dp[i][j], dp[i][j - A[i - 1]] + V[i - 1]);
}
}
}
int rst = 0;
for (int j = 0; j <= m; j++) {
rst = Math.max(rst, dp[n][j]);
}
return rst;
}
}
``` | awangdev/leet-code | Java/Backpack III.java |
659 | E
tags: Math, String, Two Pointers
#### Two Pointers
- 注意加法结果的位置.
- Use two pointers i, j to track the 2 strings
- Add when i and j are applicable. While (i >= 0 || j >= 0)
- `StringBuffer.insert(0, x);`
- handle carry
#### reverse
- Reverse string -> Convert to Integer List, add up -> Convert back to string
- pointer 从前向后, 所以只需要 1个pointer.
- 操作复杂, 如上, 证明可以解决. 没必要reverse.
#### Incorrect: convert to Integer
把binary换成数字作加法. 如果input很大,那么很可能int,long都hold不住。不保险。
```
/*
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
*/
public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() -1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) sum += a.charAt(i--) - '0';
if (j >= 0) sum += b.charAt(j--) - '0';
sb.insert(0, sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.insert(0, carry);
return sb.toString();
}
}
/*
Thoughts:
Can't just convert to int because of Integer.MAX_VALUE limitation.
Convert to char, and add up all chars
*/
```
| awangdev/leet-code | Java/67. Add Binary.java |
660 | E
1526012135
tags: Array, Math, Bit Manipulation
给一串unique数字, 数字取自 [0 ~ n], 无序, 找第一个skipped的数字.
#### Swap
- 跟First Missing Positive 非常像, 只有一行代码的区别.
- swap 所有的数字, 到自己的correct position
- 最后一个for loop找到错位的index, 也就是缺的数字.
#### Bit Manipulation
- XOR will only retain bits that are different 1 ^ 0 = 1, but 0^0, 1^1 == 0
- Use that feature, 把所有value都和index XOR了
- 剩下的多余的数字, 其实是那个index无法被XOR消掉, 也就是那个缺的number value.
- 注意: 题目告诉数字是 [0 ~ n], 然而缺一个数字, 那么在[0 ~ n - 1] 里面, 最大的数字(不管缺没缺), 一定是 n = nums.length.
#### HastSet
- 全存, 找missing
- O(n) space, 不合题意
#### sorting
- sort, 找1st missing
- O(n log n) 太慢, 不合题意
```
/*
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n,
find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity.
Could you implement it using only constant extra space complexity?
*/
public class Solution {
public int missingNumber(int[] nums) {
// check input
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
// 1st loop, swap to correct location
for (int i = 0; i < n; i++) {
int val = nums[i];
while (val != i && val < n && val != nums[val]) { // val != nums[val], avoid infinitely loop
swap(nums, val, i);
val = nums[i];
}
}
// 2nd loop, find 1st missing
for (int i = 0; i < n; i++) {
if (nums[i] != i) {
return i;
}
}
return n;
}
private void swap(int[] nums, int x, int y) {
int temp = nums[x];
nums[x] = nums[y];
nums[y] = temp;
}
}
public class Solution {
public int missingNumber(int[] nums) {
// check input
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
// 1st loop, swap to correct location
int i = 0;
while (i < n) {
int val = nums[i];
if (val != i && val < n && val != nums[val]) { // val != nums[val], avoid infinitely loop
swap(nums, val, i);
} else {
i++;
}
}
// 2nd loop, find 1st missing
for (i = 0; i < n; i++) {
if (nums[i] != i) {
return i;
}
}
return n;
}
private void swap(int[] nums, int x, int y) {
int temp = nums[x];
nums[x] = nums[y];
nums[y] = temp;
}
}
// Bit manipulation
class Solution {
public int missingNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int result = nums.length;
for (int i = 0; i < nums.length; i++) {
result = result ^ nums[i] ^ i;
}
return result;
}
}
``` | awangdev/leet-code | Java/Missing Number.java |
661 | E
1516341495
tags: Math
方法1:
Power of 3: 3 ^ x == n ?
意思是 n / 3 一直除, 最后是可以等于1的, 那么就有了 n/=3, check n%3, 最后看结果是不是整除到1的做法. 用while loop.
方法2:
如果n是power of 3, 那么 3 ^ x的这个 x一定是个比n小的数字. 那么可以在 0 ~ n 之间做binary serach, 但是就比较慢.
方法3:
巧妙的想法.最大的3^x integer是 3^19. 那么找到这个数, 一定可以被n整除. 一步到位.
```
/*
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Hide Company Tags Google
Hide Tags Math
Hide Similar Problems (E) Power of Two
*/
/*
Thoughts:
Use binary serach: pick an item, do 3^x and see if equals to n, < n or >n, then move the number.
*/
class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) {
return false;
}
int start = 0;
int end = n;
while (start + 1 < end) {
int mid = start + (end - start)/2;
long powerOfThree = (long) Math.pow(3, mid);
if (powerOfThree == n) {
return true;
}
if (powerOfThree < n) {
start = mid;
} else {
end = mid;
}
}
return Math.pow(3, start) == n;
}
}
//Check if n = 3 ^ x;
public class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) {
return false;
}
if (n == 1) {
return true;
}
if (n % 3 != 0) {
return false;
}
return isPowerOfThree(n / 3);
}
}
// Shorter version
class Solution {
public boolean isPowerOfThree(int n) {
while (n/3>=1){
if (n%3!=0) return false;
n/=3;
}
return n==1;
}
}
/*
Thoughts:
The largest int is 2^31, and the largest 3^x = 3^19.
If n is power of 3, it should 3^19 % n should == 0
*/
class Solution {
public boolean isPowerOfThree(int n) {
return (n > 0 && Math.pow(3, 19) % n == 0);
}
}
``` | awangdev/leet-code | Java/Power of Three.java |
662 | package com.crossoverjie.actual;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
/**
* Function:读取文件
*
* @author crossoverJie
* Date: 05/01/2018 14:11
* @since JDK 1.8
*/
public class ReadFile {
private final static Logger LOGGER = LoggerFactory.getLogger(ReadFile.class);
private static List<String> content ;
private static String path ="/Users/chenjie/Desktop/test.log" ;
/**
* 查找关键字
*/
private static final String KEYWORD = "login" ;
private static Map<String,Integer> countMap ;
/**
* 去重集合
*/
private static Set<SortString> contentSet ;
public static void main(String[] args) {
contentSet = new TreeSet<>() ;
countMap = new HashMap<>(30) ;
File file = new File(path) ;
try {
//查找
sortAndFindKeyWords(file);
LOGGER.info(contentSet.toString());
} catch (IOException e) {
LOGGER.error("IOException",e);
}
}
/**
* 查找关键字
* @param file
* @throws IOException
*/
private static void sortAndFindKeyWords(File file) throws IOException {
content = Files.readLines(file, Charset.defaultCharset());
LOGGER.info(String.valueOf(content));
for (String value : content) {
boolean flag = value.contains(KEYWORD) ;
if (!flag){
continue;
}
if (countMap.containsKey(value)){
countMap.put(value,countMap.get(value) + 1) ;
} else {
countMap.put(value,1) ;
}
}
for (String key :countMap.keySet()){
SortString sort = new SortString() ;
sort.setKey(key);
sort.setCount(countMap.get(key));
contentSet.add(sort) ;
}
}
private static class SortString implements Comparable<SortString>{
private String key ;
private Integer count ;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@Override
public int compareTo(SortString o) {
if (this.getCount() >o.getCount()){
return 1;
}else {
return -1 ;
}
}
@Override
public String toString() {
return "SortString{" +
"key='" + key + '\'' +
", count=" + count +
'}';
}
}
}
| crossoverJie/JCSprout | src/main/java/com/crossoverjie/actual/ReadFile.java |
664 | package cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
/**
* Guava demo.
*
* @author skywalker
*/
public class CacheDemo {
@Test
public void cacheLoader() throws ExecutionException {
LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(2)
.build(new CacheLoader<String, String>() {
@Override
public String load(String s) throws Exception {
return "Hello: " + s;
}
});
System.out.println(cache.get("China"));
cache.put("US", "US");
System.out.println(cache.get("US"));
//放不进去
cache.put("UK", "UK");
}
}
| seaswalker/spring-analysis | src/main/java/cache/CacheDemo.java |
665 | package com.macro.mall.demo.config;
import com.macro.mall.demo.bo.AdminUserDetails;
import com.macro.mall.mapper.UmsAdminMapper;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.UmsAdminExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.List;
/**
* SpringSecurity相关配置
* Created by macro on 2018/4/26.
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UmsAdminMapper umsAdminMapper;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//配置权限
// .antMatchers("/").access("hasRole('TEST')")//该路径需要TEST角色
// .antMatchers("/brand/list").hasAuthority("TEST")//该路径需要TEST权限
.antMatchers("/**").permitAll()
.and()//启用基于http的认证
.httpBasic()
.realmName("/")
.and()//配置登录页面
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.and()//配置退出路径
.logout()
.logoutSuccessUrl("/")
// .and()//记住密码功能
// .rememberMe()
// .tokenValiditySeconds(60*60*24)
// .key("rememberMeKey")
.and()//关闭跨域伪造
.csrf()
.disable()
.headers()//去除X-Frame-Options
.frameOptions()
.disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
public UserDetailsService userDetailsService() {
//获取登录用户信息
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UmsAdminExample example = new UmsAdminExample();
example.createCriteria().andUsernameEqualTo(username);
List<UmsAdmin> umsAdminList = umsAdminMapper.selectByExample(example);
if (umsAdminList != null && umsAdminList.size() > 0) {
return new AdminUserDetails(umsAdminList.get(0));
}
throw new UsernameNotFoundException("用户名或密码错误");
}
};
}
}
| macrozheng/mall | mall-demo/src/main/java/com/macro/mall/demo/config/SecurityConfig.java |
666 | /**
* @author mcrwayfun
* @version v1.0
* @date Created in 2019/12/29
* @description
*/
public class Solution1 {
private int index = 0;
/**
* 判断是否是数值
* @param str
* @return
*/
public boolean isNumeric(char[] str) {
if (str == null || str.length < 1) {
return false;
}
// 判断是否存在整数
boolean flag = scanInteger(str);
// 小数部分
if (index < str.length && str[index] == '.') {
index++;
// 小数部分可以有整数或者没有整数
// 所以使用 ||
flag = scanUnsignedInteger(str) || flag;
}
if (index < str.length && (str[index] == 'e' || str[index] == 'E')) {
index++;
// e或E前面必须有数字
// e或者E后面必须有整数
// 所以使用 &&
flag = scanInteger(str) && flag;
}
return flag && index == str.length;
}
private boolean scanInteger(char[] str) {
// 去除符号
if (index < str.length && (str[index] == '+' || str[index] == '-')) {
index++;
}
return scanUnsignedInteger(str);
}
private boolean scanUnsignedInteger(char[] str) {
int start = index;
while (index < str.length && str[index] >= '0' && str[index] <= '9') {
index++;
}
// 判断是否存在整数
return index > start;
}
}
| geekxh/hello-algorithm | 算法读物/剑指offer/20_NumericStrings/Solution1.java |
667 | M
1527969371
tags: DFS, Divide and Conquer
如题: Calculate the a^n % b where a, b and n are all 32bit integers.
#### Divide and Conquer
- a^n可以被拆解成(a*a*a*a....*a), 是乘机形式,而%是可以把每一项都mod一下的。所以就拆开来take mod.
- 这里用个二分的方法,recursively二分下去,直到n/2为0或者1,然后分别对待.
- 注意1: 二分后要conquer,乘积可能大于Integer.MAX_VALUE, 所以用个long.
- 注意2: 要处理n%2==1的情况,二分时候自动省掉了一份 a,要乘一下。
```
/*
Calculate the a^n % b where a, b and n are all 32bit integers.
Example
For 2^31 % 3 = 2
For 100^1000 % 1000 = 0
Challenge
O(logn)
Tags Expand
Divide and Conquer
*/
/*
Thoughts:
Learn online:
(a * b) % p = (a % p * b % p) % p
Than mean: a ^ n can be divided into a^(n/2) * a^(n/2), that can be used for recursion: divde and conqure.
Note: when n is odd number, it cannot be evenly divided into n/2 and n/2. This case needs special treatment: n = n/2 + n/2 + 1;
*/
class Solution {
public int fastPower(int a, int b, int n) {
if (n == 0) {
return 1 % b;
}
if (n == 1) {
return a % b;
}
long recurPow = fastPower(a, b, n / 2);
recurPow = (recurPow * recurPow) % b;
if (n % 2 == 1) {
recurPow = recurPow * a % b;
}
return (int)recurPow;
}
};
``` | awangdev/leet-code | Java/Fast Power.java |
668 | package dshomewrok;
import java.util.*;
//首先 , 从小到大排序,就是这个树的中序遍历
//递归法, 首先如果到叶了,就return, 否则先往左一直过去, level[i++] root*2+1), 左边递归完了,然后中间 = in[root], 然后右边递归判断
//
public class CompletBinarySearchTree {
static int count = 0,root =0;
static int[] level = new int[1010];//动态数组的标准分配
public static void main(String[] args) {
int i=0,j = 0, k = 0,n = 0;
Scanner sc = new Scanner(System.in);
k = sc.nextInt(); // k is number of the tree's node
int[] arr = new int[k];//动态数组的标准分配
for(j = 0;j < k;j++) {
arr[j] = sc.nextInt();
}
Arrays.sort(arr);//得到树的中序遍历
System.out.print(arr[0]);
// System.out.println(Arrays.toString(arr2));
Build(arr,root);
System.out.print(level[0]);
for(i = 1;i<k;i++)
System.out.print(" "+level[i]);// no extra space, you could ,first print [0], and then print "space"+[i]
sc.close();
}
public static void Build(int[] arr, int root) {
if(root >= arr.length) return; // arrive leaf
Build(arr,root*2+1);
level[root] = arr[count++];
Build(arr,root*2+2);
}
}
/*Arrays类中的sort()使用的是“经过调优的快速排序法”;
(2)比如int[],double[],char[]等基数据类型的数组,Arrays类之只是提供了默认的升序排列,没有提供相应的降序排列方法。
(3)要对基础类型的数组进行降序排序,需要将这些数组转化为对应的封装类数组,如Integer[],Double[],Character[]等,对这些类数组进行排序。(其实还不如先进行升序排序,自己在转为将序)。
*/ | QSCTech/zju-icicles | 数据结构基础/作业/dsHomework/tree/CompletBinarySearchTree.java |
669 | package cn.itcast_03;
import java.util.ArrayList;
import java.util.Collections;
/*
* 模拟斗地主洗牌和发牌
*
* 扑克牌:54
* 小王
* 大王
* 黑桃A,黑桃2,黑桃3,黑桃4,黑桃...,黑桃10,黑桃J,黑桃Q,黑桃K
* 红桃...
* 梅花...
* 方块...
*
* 分析:
* A:造一个牌盒(集合)
* B:造每一张牌,然后存储到牌盒里面去
* C:洗牌
* D:发牌
* E:看牌
*/
public class PokerDemo {
public static void main(String[] args) {
// 造一个牌盒(集合)
ArrayList<String> array = new ArrayList<String>();
// 造每一张牌,然后存储到牌盒里面去
// 定义花色数组
String[] colors = { "♠", "♥", "♣", "♦" };
// 定义点数数组
String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"J", "Q", "K" };
for (String color : colors) {
for (String number : numbers) {
array.add(color.concat(number));
}
}
array.add("小王");
array.add("大王");
// 看牌
// System.out.println(array);
// 洗牌
Collections.shuffle(array);
// 发牌
// 三个选手
ArrayList<String> linQingXia = new ArrayList<String>();
ArrayList<String> fengQingYang = new ArrayList<String>();
ArrayList<String> liuYi = new ArrayList<String>();
// 底牌
ArrayList<String> diPai = new ArrayList<String>();
for (int x = 0; x < array.size(); x++) {
if (x >= array.size() - 3) {
diPai.add(array.get(x));
} else if (x % 3 == 0) {
linQingXia.add(array.get(x));
} else if (x % 3 == 1) {
fengQingYang.add(array.get(x));
} else if (x % 3 == 2) {
liuYi.add(array.get(x));
}
}
// 看牌
lookPoker("林青霞", linQingXia);
lookPoker("风清扬", fengQingYang);
lookPoker("刘意", liuYi);
lookPoker("底牌", diPai);
}
// 写一个功能实现遍历
public static void lookPoker(String name, ArrayList<String> array) {
System.out.print(name + "的牌是:");
for (String s : array) {
System.out.print(s + " ");
}
System.out.println();
}
}
| DuGuQiuBai/Java | day18/code/day18_Collections/src/cn/itcast_03/PokerDemo.java |
670 | /*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;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Set;
/**parser for response
* @author Lemon
* @see #getObject
* @see #getList
* @use JSONResponse response = new JSONResponse(json);
* <br> User user = response.getObject(User.class);//not a must
* <br> List<Comment> commenntList = response.getList("Comment[]", Comment.class);//not a must
*/
public class JSONResponse extends apijson.JSONObject {
private static final long serialVersionUID = 1L;
// 节约性能和减少 bug,除了关键词 @key ,一般都符合变量命名规范,不符合也原样返回便于调试
/**格式化带 - 中横线的单词
*/
public static boolean IS_FORMAT_HYPHEN = false;
/**格式化带 _ 下划线的单词
*/
public static boolean IS_FORMAT_UNDERLINE = false;
/**格式化带 $ 美元符的单词
*/
public static boolean IS_FORMAT_DOLLAR = false;
private static final String TAG = "JSONResponse";
public JSONResponse() {
super();
}
public JSONResponse(String json) {
this(parseObject(json));
}
public JSONResponse(JSONObject object) {
super(format(object));
}
//状态信息,非GET请求获得的信息<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
public static final int CODE_SUCCESS = 200; //成功
public static final int CODE_UNSUPPORTED_ENCODING = 400; //编码错误
public static final int CODE_ILLEGAL_ACCESS = 401; //权限错误
public static final int CODE_UNSUPPORTED_OPERATION = 403; //禁止操作
public static final int CODE_NOT_FOUND = 404; //未找到
public static final int CODE_ILLEGAL_ARGUMENT = 406; //参数错误
public static final int CODE_NOT_LOGGED_IN = 407; //未登录
public static final int CODE_TIME_OUT = 408; //超时
public static final int CODE_CONFLICT = 409; //重复,已存在
public static final int CODE_CONDITION_ERROR = 412; //条件错误,如密码错误
public static final int CODE_UNSUPPORTED_TYPE = 415; //类型错误
public static final int CODE_OUT_OF_RANGE = 416; //超出范围
public static final int CODE_NULL_POINTER = 417; //对象为空
public static final int CODE_SERVER_ERROR = 500; //服务器内部错误
public static final String MSG_SUCCEED = "success"; //成功
public static final String MSG_SERVER_ERROR = "Internal Server Error!"; //服务器内部错误
public static String KEY_OK = "ok";
public static String KEY_CODE = "code";
public static String KEY_MSG = "msg";
public static final String KEY_COUNT = "count";
public static final String KEY_TOTAL = "total";
public static final String KEY_INFO = "info"; //详细的分页信息
public static final String KEY_FIRST = "first"; //是否为首页
public static final String KEY_LAST = "last"; //是否为尾页
public static final String KEY_MAX = "max"; //最大页码
public static final String KEY_MORE = "more"; //是否有更多
/**获取状态
* @return
*/
public int getCode() {
try {
return getIntValue(KEY_CODE);
} catch (Exception e) {
//empty
}
return 0;
}
/**获取状态
* @return
*/
public static int getCode(JSONObject reponse) {
try {
return reponse.getIntValue(KEY_CODE);
} catch (Exception e) {
//empty
}
return 0;
}
/**获取状态描述
* @return
*/
public String getMsg() {
return getString(KEY_MSG);
}
/**获取状态描述
* @param reponse
* @return
*/
public static String getMsg(JSONObject reponse) {
return reponse == null ? null : reponse.getString(KEY_MSG);
}
/**获取id
* @return
*/
public long getId() {
try {
return getLongValue(KEY_ID);
} catch (Exception e) {
//empty
}
return 0;
}
/**获取数量
* @return
*/
public int getCount() {
try {
return getIntValue(KEY_COUNT);
} catch (Exception e) {
//empty
}
return 0;
}
/**获取总数
* @return
*/
public int getTotal() {
try {
return getIntValue(KEY_TOTAL);
} catch (Exception e) {
//empty
}
return 0;
}
/**是否成功
* @return
*/
public boolean isSuccess() {
return isSuccess(getCode());
}
/**是否成功
* @param code
* @return
*/
public static boolean isSuccess(int code) {
return code == CODE_SUCCESS;
}
/**是否成功
* @param response
* @return
*/
public static boolean isSuccess(JSONResponse response) {
return response != null && response.isSuccess();
}
/**是否成功
* @param response
* @return
*/
public static boolean isSuccess(JSONObject response) {
return response != null && isSuccess(response.getIntValue(KEY_CODE));
}
/**校验服务端是否存在table
* @return
*/
public boolean isExist() {
return isExist(getCount());
}
/**校验服务端是否存在table
* @param count
* @return
*/
public static boolean isExist(int count) {
return count > 0;
}
/**校验服务端是否存在table
* @param response
* @return
*/
public static boolean isExist(JSONResponse response) {
return response != null && response.isExist();
}
/**获取内部的JSONResponse
* @param key
* @return
*/
public JSONResponse getJSONResponse(String key) {
return getObject(key, JSONResponse.class);
}
//cannot get javaBeanDeserizer
// /**获取内部的JSONResponse
// * @param response
// * @param key
// * @return
// */
// public static JSONResponse getJSONResponse(JSONObject response, String key) {
// return response == null ? null : response.getObject(key, JSONResponse.class);
// }
//状态信息,非GET请求获得的信息>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/**
* key = clazz.getSimpleName()
* @param clazz
* @return
*/
public <T> T getObject(Class<T> clazz) {
return getObject(clazz == null ? "" : clazz.getSimpleName(), clazz);
}
/**
* @param key
* @param clazz
* @return
*/
public <T> T getObject(String key, Class<T> clazz) {
return getObject(this, key, clazz);
}
/**
* @param object
* @param key
* @param clazz
* @return
*/
public static <T> T getObject(JSONObject object, String key, Class<T> clazz) {
return toObject(object == null ? null : object.getJSONObject(formatObjectKey(key)), clazz);
}
/**
* @param clazz
* @return
*/
public <T> T toObject(Class<T> clazz) {
return toObject(this, clazz);
}
/**
* @param object
* @param clazz
* @return
*/
public static <T> T toObject(JSONObject object, Class<T> clazz) {
return JSON.parseObject(JSON.toJSONString(object), clazz);
}
/**
* key = KEY_ARRAY
* @param clazz
* @return
*/
public <T> List<T> getList(Class<T> clazz) {
return getList(KEY_ARRAY, clazz);
}
/**
* arrayObject = this
* @param key
* @param clazz
* @return
*/
public <T> List<T> getList(String key, Class<T> clazz) {
return getList(this, key, clazz);
}
/**
* key = KEY_ARRAY
* @param object
* @param clazz
* @return
*/
public static <T> List<T> getList(JSONObject object, Class<T> clazz) {
return getList(object, KEY_ARRAY, clazz);
}
/**
* @param object
* @param key
* @param clazz
* @return
*/
public static <T> List<T> getList(JSONObject object, String key, Class<T> clazz) {
return object == null ? null : JSON.parseArray(object.getString(formatArrayKey(key)), clazz);
}
/**
* key = KEY_ARRAY
* @return
*/
public JSONArray getArray() {
return getArray(KEY_ARRAY);
}
/**
* @param key
* @return
*/
public JSONArray getArray(String key) {
return getArray(this, key);
}
/**
* @param object
* @return
*/
public static JSONArray getArray(JSONObject object) {
return getArray(object, KEY_ARRAY);
}
/**
* key = KEY_ARRAY
* @param object
* @param key
* @return
*/
public static JSONArray getArray(JSONObject object, String key) {
return object == null ? null : object.getJSONArray(formatArrayKey(key));
}
// /**
// * @return
// */
// public JSONObject format() {
// return format(this);
// }
/**格式化key名称
* @param object
* @return
*/
public static JSONObject format(final JSONObject object) {
//太长查看不方便,不如debug Log.i(TAG, "format object = \n" + JSON.toJSONString(object));
if (object == null || object.isEmpty()) {
Log.i(TAG, "format object == null || object.isEmpty() >> return object;");
return object;
}
JSONObject formatedObject = new JSONObject(true);
Set<String> set = object.keySet();
if (set != null) {
Object value;
for (String key : set) {
value = object.get(key);
if (value instanceof JSONArray) {//JSONArray,遍历来format内部项
formatedObject.put(formatArrayKey(key), format((JSONArray) value));
}
else if (value instanceof JSONObject) {//JSONObject,往下一级提取
formatedObject.put(formatObjectKey(key), format((JSONObject) value));
}
else {//其它Object,直接填充
formatedObject.put(formatOtherKey(key), value);
}
}
}
//太长查看不方便,不如debug Log.i(TAG, "format return formatedObject = " + JSON.toJSONString(formatedObject));
return formatedObject;
}
/**格式化key名称
* @param array
* @return
*/
public static JSONArray format(final JSONArray array) {
//太长查看不方便,不如debug Log.i(TAG, "format array = \n" + JSON.toJSONString(array));
if (array == null || array.isEmpty()) {
Log.i(TAG, "format array == null || array.isEmpty() >> return array;");
return array;
}
JSONArray formatedArray = new JSONArray();
Object value;
for (int i = 0; i < array.size(); i++) {
value = array.get(i);
if (value instanceof JSONArray) {//JSONArray,遍历来format内部项
formatedArray.add(format((JSONArray) value));
}
else if (value instanceof JSONObject) {//JSONObject,往下一级提取
formatedArray.add(format((JSONObject) value));
}
else {//其它Object,直接填充
formatedArray.add(value);
}
}
//太长查看不方便,不如debug Log.i(TAG, "format return formatedArray = " + JSON.toJSONString(formatedArray));
return formatedArray;
}
/**获取表名称
* @param fullName name 或 name:alias
* @return name => name; name:alias => alias
*/
public static String getTableName(String fullName) {
//key:alias -> alias; key:alias[] -> alias[]
int index = fullName == null ? -1 : fullName.indexOf(":");
return index < 0 ? fullName : fullName.substring(0, index);
}
/**获取变量名
* @param fullName
* @return {@link #formatKey(String, boolean, boolean, boolean, boolean, boolean, boolean)} formatColon = true, formatAt = true, formatHyphen = true, firstCase = true
*/
public static String getVariableName(String fullName) {
if (isArrayKey(fullName)) {
fullName = StringUtil.addSuffix(fullName.substring(0, fullName.length() - 2), "list");
}
return formatKey(fullName, true, true, true, true, false, true);
}
/**格式化数组的名称 key[] => keyList; key:alias[] => aliasList; Table-column[] => tableColumnList
* @param key empty ? "list" : key + "List" 且首字母小写
* @return {@link #formatKey(String, boolean, boolean, boolean, boolean, boolean, boolean)} formatColon = false, formatAt = true, formatHyphen = true, firstCase = true
*/
public static String formatArrayKey(String key) {
if (isArrayKey(key)) {
key = StringUtil.addSuffix(key.substring(0, key.length() - 2), "list");
}
int index = key == null ? -1 : key.indexOf(":");
if (index >= 0) {
return key.substring(index + 1); //不处理自定义的
}
return formatKey(key, false, true, true, IS_FORMAT_UNDERLINE, IS_FORMAT_DOLLAR, false); //节约性能,除了数组对象 Table-column:alias[] ,一般都符合变量命名规范
}
/**格式化对象的名称 name => name; name:alias => alias
* @param key name 或 name:alias
* @return {@link #formatKey(String, boolean, boolean, boolean, boolean, boolean, boolean)} formatColon = false, formatAt = true, formatHyphen = false, firstCase = true
*/
public static String formatObjectKey(String key) {
int index = key == null ? -1 : key.indexOf(":");
if (index >= 0) {
return key.substring(index + 1); // 不处理自定义的
}
return formatKey(key, false, true, IS_FORMAT_HYPHEN, IS_FORMAT_UNDERLINE, IS_FORMAT_DOLLAR, false); //节约性能,除了表对象 Table:alias ,一般都符合变量命名规范
}
/**格式化普通值的名称 name => name; name:alias => alias
* @param fullName name 或 name:alias
* @return {@link #formatKey(String, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean)} formatColon = false, formatAt = true, formatHyphen = false, firstCase = false
*/
public static String formatOtherKey(String fullName) {
return formatKey(fullName, false, true, IS_FORMAT_HYPHEN, IS_FORMAT_UNDERLINE, IS_FORMAT_DOLLAR
, IS_FORMAT_HYPHEN || IS_FORMAT_UNDERLINE || IS_FORMAT_DOLLAR ? false : null);
}
/**格式化名称
* @param fullName name 或 name:alias
* @param formatAt 去除前缀 @ , @a => a
* @param formatColon 去除分隔符 : , A:b => b
* @param formatHyphen 去除分隔符 - , A-b-cd-Efg => aBCdEfg
* @param formatUnderline 去除分隔符 _ , A_b_cd_Efg => aBCdEfg
* @param formatDollar 去除分隔符 $ , A$b$cd$Efg => aBCdEfg
* @param firstCase 第一个单词首字母小写,后面的首字母大写, Ab => ab ; A-b-Cd => aBCd
* @return name => name; name:alias => alias
*/
public static String formatKey(String fullName, boolean formatColon, boolean formatAt, boolean formatHyphen
, boolean formatUnderline, boolean formatDollar, Boolean firstCase) {
if (fullName == null) {
Log.w(TAG, "formatKey fullName == null >> return null;");
return null;
}
if (formatColon) {
fullName = formatColon(fullName);
}
if (formatAt) { //关键词只去掉前缀,不格式化单词,例如 @a-b 返回 a-b ,最后不会调用 setter
fullName = formatAt(fullName);
}
if (formatHyphen) {
fullName = formatHyphen(fullName, firstCase != null);
}
if (formatUnderline) {
fullName = formatUnderline(fullName, firstCase != null);
}
if (formatDollar) {
fullName = formatDollar(fullName, firstCase != null);
}
// 默认不格式化普通 key:value (value 不为 [], {}) 的 key
return firstCase == null ? fullName : StringUtil.firstCase(fullName, firstCase);
}
/**"@key" => "key"
* @param key
* @return
*/
public static String formatAt(@NotNull String key) {
return key.startsWith("@") ? key.substring(1) : key;
}
/**key:alias => alias
* @param key
* @return
*/
public static String formatColon(@NotNull String key) {
int index = key.indexOf(":");
return index < 0 ? key : key.substring(index + 1);
}
/**A-b-cd-Efg => ABCdEfg
* @param key
* @return
*/
public static String formatHyphen(@NotNull String key, Boolean firstCase) {
return formatDivider(key, "-", firstCase);
}
/**A_b_cd_Efg => ABCdEfg
* @param key
* @return
*/
public static String formatUnderline(@NotNull String key, Boolean firstCase) {
return formatDivider(key, "_", firstCase);
}
/**A$b$cd$Efg => ABCdEfg
* @param key
* @return
*/
public static String formatDollar(@NotNull String key, Boolean firstCase) {
return formatDivider(key, "$", firstCase);
}
/**A.b.cd.Efg => ABCdEfg
* @param key
* @return
*/
public static String formatDot(@NotNull String key, Boolean firstCase) {
return formatDivider(key, ".", firstCase);
}
/**A/b/cd/Efg => ABCdEfg
* @param key
* @return
*/
public static String formatDivider(@NotNull String key, Boolean firstCase) {
return formatDivider(key, "/", firstCase);
}
/**去除分割符,返回驼峰格式
* @param key
* @param divider
* @param firstCase
* @return
*/
public static String formatDivider(@NotNull String key, @NotNull String divider, Boolean firstCase) {
String[] parts = StringUtil.split(key, divider);
StringBuilder name = new StringBuilder();
for (String part : parts) {
part = part.toLowerCase(); // 始终小写,也方便反过来 ABCdEfg -> A_b_cd_Efg
if (firstCase != null) {
// 始终小写, A_b_cd_Efg -> ABCdEfg, firstCase ? part.toLowerCase() : part.toUpperCase();
part = StringUtil.firstCase(part, firstCase);
}
name.append(part);
}
return name.toString();
}
}
| Tencent/APIJSON | APIJSONORM/src/main/java/apijson/JSONResponse.java |
671 | package org.elasticsearch.client;
import java.io.IOException;
import org.apache.http.client.methods.HttpGet;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest;
import org.elasticsearch.common.Strings;
/**
* RequestConverters扩展
*
* @author rewerma 2019-08-01
* @version 1.0.0
*/
public class RequestConvertersExt {
/**
* 修改 getMappings 去掉request参数
*
* @param getMappingsRequest
* @return
* @throws IOException
*/
static Request getMappings(GetMappingsRequest getMappingsRequest) throws IOException {
String[] indices = getMappingsRequest.indices() == null ? Strings.EMPTY_ARRAY : getMappingsRequest.indices();
String[] types = getMappingsRequest.types() == null ? Strings.EMPTY_ARRAY : getMappingsRequest.types();
return new Request(HttpGet.METHOD_NAME, RequestConverters.endpoint(indices, "_mapping", types));
}
}
| alibaba/canal | client-adapter/es6x/src/main/java/org/elasticsearch/client/RequestConvertersExt.java |
672 | /**
* Copyright (c) 2011-2023, James Zhan 詹波 ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jfinal.aop;
/**
* Aop 支持在任意时空便捷使用 Aop
*
* Aop 主要功能:
* 1:Aop.get(Class) 根据 Class 去创建对象,然后对创建好的对象进行依赖注入
*
* 2:Aop.inject(Object) 对传入的对象进行依赖注入
*
* 3:Aop.inject(...) 与 Aop.get(...) 的区别是前者只针对传入的对象之中的属性进行注入。
* 而后者先要使用 Class 去创建对象,创建完对象以后对该对象之中的属性进行注入。
* 简单一句话:get(...) 比 inject(...) 多了一个目标对象的创建过程
*
* 4:AopManager.me().setSingleton(...) 用于配置默认是否为单例
*
* 5:在目标类上使用注解 Singleton 可以覆盖掉上面 setSingleton(...) 方法配置的默认值
*
*
* 基本用法:
* 1:先定义业务
* public class Service {
* @Inject
* OtherService otherSrv;
*
* @Before(Aaa.class)
* public void doIt() {
* ...
* }
* }
*
* public class OtherService {
* @Before(Bbb.class)
* public void doOther() {
* ...
* }
* }
*
*
* 2:只进行注入,对象自己创建
* Service srv = Aop.inject(new Service());
* srv.doIt();
* 由于 Service 对象是 new 出来的,不会被 AOP 代理,所以其 doIt() 方法上的 Aaa 拦截器并不会生效
* Aop.inject(...) 会对 OtherService otherSrv 进行注入,并且对 otherSrv 进行 AOP 代理,
* 所以 OtherService.doOther() 方法上的 Bbb 拦截器会生效
*
* 3:创建对象并注入
* Service srv = Aop.get(Service.class);
* srv.doIt();
* Aop.get(...) 用法对 OtherService otherSrv 的处理方式完全一样,在此基础之上 Service 自身也会被
* AOP 代理,所以 doIt() 上的 Aaa 拦截器会生效
*
* 4:小结:对象的创建交给 Aop 而不是自己 new 出来,所创建的对象才能被 AOP 代理,其上的拦截器才能生效
*
*
* 高级用法:
* 1:@Inject 注解默认注入属性自身类型的对象,可以通过如下代码指定被注入的类型:
* @Inject(UserServiceImpl.class) // 此处的 UserServiceImpl 为 UserService 的子类或实现类
* UserService userService;
*
* 2:被注入对象默认是 singleton 单例,可以通过 AopManager.me().setSingleton(false) 配置默认不为单例
*
* 3:可以在目标类中中直接配置注解 Singleton:
* @Singleton(false)
* public class MyService {...}
*
* 注意:以上代码中的注解会覆盖掉 2 中 setSingleton() 方法配置的默认值
*
* 4:如上 2、3 中的配置,建议的用法是:先用 setSingleton() 配置大多数情况,然后在个别
* 违反上述配置的情况下使用 Singleton 注解来覆盖默认配置,这样可以节省大量代码
*/
public class Aop {
static AopFactory aopFactory = new AopFactory();
public static <T> T get(Class<T> targetClass) {
return aopFactory.get(targetClass);
}
public static <T> T inject(T targetObject) {
return aopFactory.inject(targetObject);
}
/* 通过 AopManager.me().getAopFactory().inject(...) 可调用如下方法,不直接开放出来
public static <T> T inject(Class<T> targetClass, T targetObject) {
return aopFactory.inject(targetClass, targetObject);
}*/
}
| jfinal/jfinal | src/main/java/com/jfinal/aop/Aop.java |
673 | /*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dianping.cat.alarm.spi;
import com.dianping.cat.Cat;
import com.dianping.cat.alarm.service.AlertService;
import com.dianping.cat.alarm.spi.config.AlertPolicyManager;
import com.dianping.cat.alarm.spi.decorator.DecoratorManager;
import com.dianping.cat.alarm.spi.receiver.ContactorManager;
import com.dianping.cat.alarm.spi.sender.SendMessageEntity;
import com.dianping.cat.alarm.spi.sender.SenderManager;
import com.dianping.cat.alarm.spi.spliter.SpliterManager;
import com.dianping.cat.config.server.ServerConfigManager;
import com.dianping.cat.helper.TimeHelper;
import com.dianping.cat.message.Event;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.helper.Threads;
import org.unidal.helper.Threads.Task;
import org.unidal.lookup.annotation.Inject;
import org.unidal.lookup.annotation.Named;
import org.unidal.tuple.Pair;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
@Named
public class AlertManager implements Initializable {
private static final int MILLIS1MINUTE = 60 * 1000;
@Inject
protected SpliterManager m_splitterManager;
@Inject
protected SenderManager m_senderManager;
@Inject
protected AlertService m_alertService;
@Inject
private AlertPolicyManager m_policyManager;
@Inject
private DecoratorManager m_decoratorManager;
@Inject
private ContactorManager m_contactorManager;
@Inject
private ServerConfigManager m_configManager;
private BlockingQueue<AlertEntity> m_alerts = new LinkedBlockingDeque<AlertEntity>(10000);
private Map<String, AlertEntity> m_unrecoveredAlerts = new ConcurrentHashMap<String, AlertEntity>(1000);
private Map<String, AlertEntity> m_sendedAlerts = new ConcurrentHashMap<String, AlertEntity>(1000);
private ConcurrentHashMap<AlertEntity, Long> m_alertMap = new ConcurrentHashMap<AlertEntity, Long>();
public boolean addAlert(AlertEntity entity) {
m_alertMap.put(entity, entity.getDate().getTime());
String group = entity.getGroup();
Cat.logEvent("Alert:" + entity.getType().getName(), group, Event.SUCCESS, entity.toString());
if (m_configManager.isAlertMachine()) {
return m_alerts.offer(entity);
} else {
return true;
}
}
@Override
public void initialize() throws InitializationException {
Threads.forGroup("Cat").start(new SendExecutor());
Threads.forGroup("Cat").start(new RecoveryAnnouncer());
}
public boolean isSuspend(String alertKey, int suspendMinute) {
AlertEntity sendedAlert = m_sendedAlerts.get(alertKey);
if (sendedAlert != null) {
long duration = System.currentTimeMillis() - sendedAlert.getDate().getTime();
if (duration / MILLIS1MINUTE < suspendMinute) {
Cat.logEvent("SuspendAlert", alertKey, Event.SUCCESS, null);
return true;
}
}
return false;
}
public List<AlertEntity> queryLastestAlarmKey(int minute) {
List<AlertEntity> keys = new ArrayList<AlertEntity>();
long currentTimeMillis = System.currentTimeMillis();
for (Entry<AlertEntity, Long> entry : m_alertMap.entrySet()) {
Long value = entry.getValue();
if (currentTimeMillis - value < TimeHelper.ONE_MINUTE * minute) {
keys.add(entry.getKey());
}
}
return keys;
}
//List去重
private void removeDuplicate(List<String> list) {
LinkedHashSet<String> set = new LinkedHashSet<String>(list.size());
set.addAll(list);
list.clear();
list.addAll(set);
}
private boolean send(AlertEntity alert) {
boolean result = false;
String type = alert.getType().getName();
String group = alert.getGroup();
String level = alert.getLevel().getLevel();
String alertKey = alert.getKey();
List<AlertChannel> channels = m_policyManager.queryChannels(type, group, level);
int suspendMinute = m_policyManager.querySuspendMinute(type, group, level);
m_unrecoveredAlerts.put(alertKey, alert);
Pair<String, String> pair = m_decoratorManager.generateTitleAndContent(alert);
String title = pair.getKey();
if (suspendMinute > 0) {
if (isSuspend(alertKey, suspendMinute)) {
return true;
} else {
m_sendedAlerts.put(alertKey, alert);
}
}
SendMessageEntity message = null;
for (AlertChannel channel : channels) {
String contactGroup = alert.getContactGroup();
List<String> receivers = m_contactorManager.queryReceivers(contactGroup, channel, type);
//去重
removeDuplicate(receivers);
if (receivers.size() > 0) {
String rawContent = pair.getValue();
if (suspendMinute > 0) {
rawContent = rawContent + "<br/>[告警间隔时间]" + suspendMinute + "分钟";
}
String content = m_splitterManager.process(rawContent, channel);
message = new SendMessageEntity(group, title, type, content, receivers);
if (m_senderManager.sendAlert(channel, message)) {
result = true;
}
} else {
Cat.logEvent("NoneReceiver:" + channel, type + ":" + contactGroup, Event.SUCCESS, null);
}
}
String dbContent = Pattern.compile("<div.*(?=</div>)</div>", Pattern.DOTALL).matcher(pair.getValue()).replaceAll("");
if (message == null) {
message = new SendMessageEntity(group, title, type, "", null);
}
message.setContent(dbContent);
m_alertService.insert(alert, message);
return result;
}
private boolean sendRecoveryMessage(AlertEntity alert, String currentMinute) {
AlertType alterType = alert.getType();
String type = alterType.getName();
String group = alert.getGroup();
String level = alert.getLevel().getLevel();
List<AlertChannel> channels = m_policyManager.queryChannels(type, group, level);
for (AlertChannel channel : channels) {
String title = "[告警恢复] [告警类型 " + alterType.getTitle() + "][" + group + " " + alert.getMetric() + "]";
String content = "[告警已恢复][恢复时间]" + currentMinute;
List<String> receivers = m_contactorManager.queryReceivers(alert.getContactGroup(), channel, type);
//去重
removeDuplicate(receivers);
if (receivers.size() > 0) {
SendMessageEntity message = new SendMessageEntity(group, title, type, content, receivers);
if (m_senderManager.sendAlert(channel, message)) {
return true;
}
}
}
return false;
}
private class RecoveryAnnouncer implements Task {
private DateFormat m_sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
@Override
public String getName() {
return getClass().getSimpleName();
}
private int queryRecoverMinute(AlertEntity alert) {
String type = alert.getType().getName();
String group = alert.getGroup();
String level = alert.getLevel().getLevel();
return m_policyManager.queryRecoverMinute(type, group, level);
}
@Override
public void run() {
while (true) {
long current = System.currentTimeMillis();
String currentStr = m_sdf.format(new Date(current));
List<String> recoveredItems = new ArrayList<String>();
for (Entry<String, AlertEntity> entry : m_unrecoveredAlerts.entrySet()) {
try {
String key = entry.getKey();
AlertEntity alert = entry.getValue();
int recoverMinute = queryRecoverMinute(alert);
long alertTime = alert.getDate().getTime();
int alreadyMinutes = (int) ((current - alertTime) / MILLIS1MINUTE);
if (alreadyMinutes >= recoverMinute) {
recoveredItems.add(key);
sendRecoveryMessage(alert, currentStr);
}
} catch (Exception e) {
Cat.logError(e);
}
}
for (String key : recoveredItems) {
m_unrecoveredAlerts.remove(key);
}
long duration = System.currentTimeMillis() - current;
if (duration < MILLIS1MINUTE) {
long lackMills = MILLIS1MINUTE - duration;
try {
TimeUnit.MILLISECONDS.sleep(lackMills);
} catch (InterruptedException e) {
Cat.logError(e);
}
}
}
}
@Override
public void shutdown() {
}
}
private class SendExecutor implements Task {
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public void run() {
while (true) {
try {
AlertEntity alert = m_alerts.poll(5, TimeUnit.MILLISECONDS);
if (alert != null) {
send(alert);
}
} catch (Exception e) {
Cat.logError(e);
e.printStackTrace();
}
}
}
@Override
public void shutdown() {
}
}
}
| dianping/cat | cat-alarm/src/main/java/com/dianping/cat/alarm/spi/AlertManager.java |
675 | package com.blankj.subutil.util;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/09/19
* desc : 相机相关工具类
* </pre>
*/
public final class CameraUtils {
// private CameraUtils() {
// throw new UnsupportedOperationException("u can't instantiate me...");
// }
//
// /**
// * 获取打开照程序界面的Intent
// */
// public static Intent getOpenCameraIntent() {
// return new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// }
//
// /**
// * 获取跳转至相册选择界面的Intent
// */
// public static Intent getImagePickerIntent() {
// Intent intent = new Intent(Intent.ACTION_PICK, null);
// return intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
// }
//
// /**
// * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent
// */
// public static Intent getImagePickerIntent(int outputX, int outputY, Uri fromFileURI,
// Uri saveFileURI) {
// return getImagePickerIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI);
// }
//
// /**
// * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent
// */
// public static Intent getImagePickerIntent(int aspectX, int aspectY, int outputX, int outputY, Uri fromFileURI,
// Uri saveFileURI) {
// return getImagePickerIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI);
// }
//
// /**
// * 获取[跳转至相册选择界面,并跳转至裁剪界面,可以指定是否缩放裁剪区域]的Intent
// *
// * @param aspectX 裁剪框尺寸比例X
// * @param aspectY 裁剪框尺寸比例Y
// * @param outputX 输出尺寸宽度
// * @param outputY 输出尺寸高度
// * @param canScale 是否可缩放
// * @param fromFileURI 文件来源路径URI
// * @param saveFileURI 输出文件路径URI
// */
// public static Intent getImagePickerIntent(int aspectX, int aspectY, int outputX, int outputY, boolean canScale,
// Uri fromFileURI, Uri saveFileURI) {
// Intent intent = new Intent(Intent.ACTION_PICK);
// intent.setDataAndType(fromFileURI, "image/*");
// intent.putExtra("crop", "true");
// intent.putExtra("aspectX", aspectX <= 0 ? 1 : aspectX);
// intent.putExtra("aspectY", aspectY <= 0 ? 1 : aspectY);
// intent.putExtra("outputX", outputX);
// intent.putExtra("outputY", outputY);
// intent.putExtra("scale", canScale);
// // 图片剪裁不足黑边解决
// intent.putExtra("scaleUpIfNeeded", true);
// intent.putExtra("return-data", false);
// intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI);
// intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// // 去除人脸识别
// return intent.putExtra("noFaceDetection", true);
// }
//
// /**
// * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent
// */
// public static Intent getCameraIntent(final Uri saveFileURI) {
// Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// return mIntent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI);
// }
//
// /**
// * 获取[跳转至裁剪界面,默认可缩放]的Intent
// */
// public static Intent getCropImageIntent(int outputX, int outputY, Uri fromFileURI,
// Uri saveFileURI) {
// return getCropImageIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI);
// }
//
// /**
// * 获取[跳转至裁剪界面,默认可缩放]的Intent
// */
// public static Intent getCropImageIntent(int aspectX, int aspectY, int outputX, int outputY, Uri fromFileURI,
// Uri saveFileURI) {
// return getCropImageIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI);
// }
//
//
// /**
// * 获取[跳转至裁剪界面]的Intent
// */
// public static Intent getCropImageIntent(int aspectX, int aspectY, int outputX, int outputY, boolean canScale,
// Uri fromFileURI, Uri saveFileURI) {
// Intent intent = new Intent("com.android.camera.action.CROP");
// intent.setDataAndType(fromFileURI, "image/*");
// intent.putExtra("crop", "true");
// // X方向上的比例
// intent.putExtra("aspectX", aspectX <= 0 ? 1 : aspectX);
// // Y方向上的比例
// intent.putExtra("aspectY", aspectY <= 0 ? 1 : aspectY);
// intent.putExtra("outputX", outputX);
// intent.putExtra("outputY", outputY);
// intent.putExtra("scale", canScale);
// // 图片剪裁不足黑边解决
// intent.putExtra("scaleUpIfNeeded", true);
// intent.putExtra("return-data", false);
// // 需要将读取的文件路径和裁剪写入的路径区分,否则会造成文件0byte
// intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI);
// // true-->返回数据类型可以设置为Bitmap,但是不能传输太大,截大图用URI,小图用Bitmap或者全部使用URI
// intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// // 取消人脸识别功能
// intent.putExtra("noFaceDetection", true);
// return intent;
// }
//
// /**
// * 获得选中相册的图片
// *
// * @param context 上下文
// * @param data onActivityResult返回的Intent
// * @return bitmap
// */
// public static Bitmap getChoosedImage(final Activity context, final Intent data) {
// if (data == null) return null;
// Bitmap bm = null;
// ContentResolver cr = context.getContentResolver();
// Uri originalUri = data.getData();
// try {
// bm = MediaStore.Images.Media.getBitmap(cr, originalUri);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return bm;
// }
//
// /**
// * 获得选中相册的图片路径
// *
// * @param context 上下文
// * @param data onActivityResult返回的Intent
// * @return
// */
// public static String getChoosedImagePath(final Activity context, final Intent data) {
// if (data == null) return null;
// String path = "";
// ContentResolver resolver = context.getContentResolver();
// Uri originalUri = data.getData();
// if (null == originalUri) return null;
// String[] projection = {MediaStore.Images.Media.DATA};
// Cursor cursor = resolver.query(originalUri, projection, null, null, null);
// if (null != cursor) {
// try {
// int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// cursor.moveToFirst();
// path = cursor.getString(column_index);
// } catch (IllegalArgumentException e) {
// e.printStackTrace();
// } finally {
// try {
// if (!cursor.isClosed()) {
// cursor.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
// return StringUtils.isEmpty(path) ? originalUri.getPath() : null;
// }
//
// /**
// * 获取拍照之后的照片文件(JPG格式)
// *
// * @param data onActivityResult回调返回的数据
// * @param filePath The path of file.
// * @return 文件
// */
// public static File getTakePictureFile(final Intent data, final String filePath) {
// if (data == null) return null;
// Bundle extras = data.getExtras();
// if (extras == null) return null;
// Bitmap photo = extras.getParcelable("data");
// File file = new File(filePath);
// if (ImageUtils.save(photo, file, Bitmap.CompressFormat.JPEG)) return file;
// return null;
// }
}
| Blankj/AndroidUtilCode | lib/subutil/src/main/java/com/blankj/subutil/util/CameraUtils.java |
676 | package org.jeecg.common.util;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* @author 张代浩
* @desc 通过反射来动态调用get 和 set 方法
*/
@Slf4j
public class ReflectHelper {
private Class cls;
/**
* 传过来的对象
*/
private Object obj;
/**
* 存放get方法
*/
private Hashtable<String, Method> getMethods = null;
/**
* 存放set方法
*/
private Hashtable<String, Method> setMethods = null;
/**
* 定义构造方法 -- 一般来说是个pojo
*
* @param o 目标对象
*/
public ReflectHelper(Object o) {
obj = o;
initMethods();
}
/**
* @desc 初始化
*/
public void initMethods() {
getMethods = new Hashtable<String, Method>();
setMethods = new Hashtable<String, Method>();
cls = obj.getClass();
Method[] methods = cls.getMethods();
// 定义正则表达式,从方法中过滤出getter / setter 函数.
String gs = "get(\\w+)";
Pattern getM = Pattern.compile(gs);
String ss = "set(\\w+)";
Pattern setM = Pattern.compile(ss);
// 把方法中的"set" 或者 "get" 去掉
String rapl = "$1";
String param;
for (int i = 0; i < methods.length; ++i) {
Method m = methods[i];
String methodName = m.getName();
if (Pattern.matches(gs, methodName)) {
param = getM.matcher(methodName).replaceAll(rapl).toLowerCase();
getMethods.put(param, m);
} else if (Pattern.matches(ss, methodName)) {
param = setM.matcher(methodName).replaceAll(rapl).toLowerCase();
setMethods.put(param, m);
} else {
// logger.info(methodName + " 不是getter,setter方法!");
}
}
}
/**
* @desc 调用set方法
*/
public boolean setMethodValue(String property, Object object) {
Method m = setMethods.get(property.toLowerCase());
if (m != null) {
try {
// 调用目标类的setter函数
m.invoke(obj, object);
return true;
} catch (Exception ex) {
log.info("invoke getter on " + property + " error: " + ex.toString());
return false;
}
}
return false;
}
/**
* @desc 调用set方法
*/
public Object getMethodValue(String property) {
Object value = null;
Method m = getMethods.get(property.toLowerCase());
if (m != null) {
try {
/*
* 调用obj类的setter函数
*/
value = m.invoke(obj, new Object[]{});
} catch (Exception ex) {
log.info("invoke getter on " + property + " error: " + ex.toString());
}
}
return value;
}
/**
* 把map中的内容全部注入到obj中
*
* @param data
* @return
*/
public Object setAll(Map<String, Object> data) {
if (data == null || data.keySet().size() <= 0) {
return null;
}
for (Entry<String, Object> entry : data.entrySet()) {
this.setMethodValue(entry.getKey(), entry.getValue());
}
return obj;
}
/**
* 把map中的内容全部注入到obj中
*
* @param o
* @param data
* @return
*/
public static Object setAll(Object o, Map<String, Object> data) {
ReflectHelper reflectHelper = new ReflectHelper(o);
reflectHelper.setAll(data);
return o;
}
/**
* 把map中的内容全部注入到新实例中
*
* @param clazz
* @param data
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T setAll(Class<T> clazz, Map<String, Object> data) {
T o = null;
try {
o = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
o = null;
return o;
}
return (T) setAll(o, data);
}
/**
* 根据传入的class将mapList转换为实体类list
*
* @param mapist
* @param clazz
* @return
*/
public static <T> List<T> transList2Entrys(List<Map<String, Object>> mapist, Class<T> clazz) {
List<T> list = new ArrayList<T>();
if (mapist != null && mapist.size() > 0) {
for (Map<String, Object> data : mapist) {
list.add(ReflectHelper.setAll(clazz, data));
}
}
return list;
}
/**
* 根据属性名获取属性值
*/
public static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(o, new Object[]{});
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取属性值
*/
public static Object getFieldVal(String fieldName, Object o) {
try {
// 暴力反射获取属性
Field filed = o.getClass().getDeclaredField(fieldName);
// 设置反射时取消Java的访问检查,暴力访问
filed.setAccessible(true);
Object val = filed.get(o);
return val;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取属性名数组
*/
public static String[] getFiledName(Object o) {
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
//log.info(fields[i].getType());
fieldNames[i] = fields[i].getName();
}
return fieldNames;
}
/**
* 获取属性类型(type),属性名(name),属性值(value)的map组成的list
*/
public static List<Map> getFiledsInfo(Object o) {
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
List<Map> list = new ArrayList<Map>();
Map<String, Object> infoMap = null;
for (int i = 0; i < fields.length; i++) {
infoMap = new HashMap<>(5);
infoMap.put("type", fields[i].getType().toString());
infoMap.put("name", fields[i].getName());
infoMap.put("value", getFieldValueByName(fields[i].getName(), o));
list.add(infoMap);
}
return list;
}
/**
* 获取对象的所有属性值,返回一个对象数组
*/
public static Object[] getFiledValues(Object o) {
String[] fieldNames = getFiledName(o);
Object[] value = new Object[fieldNames.length];
for (int i = 0; i < fieldNames.length; i++) {
value[i] = getFieldValueByName(fieldNames[i], o);
}
return value;
}
/**
* 判断给定的字段是不是类中的属性
* @param field 字段名
* @param clazz 类对象
* @return
*/
public static boolean isClassField(String field, Class clazz){
Field[] fields = clazz.getDeclaredFields();
for(int i=0;i<fields.length;i++){
String fieldName = fields[i].getName();
String tableColumnName = oConvertUtils.camelToUnderline(fieldName);
if(fieldName.equalsIgnoreCase(field) || tableColumnName.equalsIgnoreCase(field)){
return true;
}
}
return false;
}
/**
* 获取class的 包括父类的
* @param clazz
* @return
*/
public static List<Field> getClassFields(Class<?> clazz) {
List<Field> list = new ArrayList<Field>();
Field[] fields;
do{
fields = clazz.getDeclaredFields();
for(int i = 0;i<fields.length;i++){
list.add(fields[i]);
}
clazz = clazz.getSuperclass();
}while(clazz!= Object.class&&clazz!=null);
return list;
}
/**
* 获取表字段名
* @param clazz
* @param name
* @return
*/
public static String getTableFieldName(Class<?> clazz, String name) {
try {
//如果字段加注解了@TableField(exist = false),不走DB查询
Field field = null;
try {
field = clazz.getDeclaredField(name);
} catch (NoSuchFieldException e) {
//e.printStackTrace();
}
//如果为空,则去父类查找字段
if (field == null) {
List<Field> allFields = getClassFields(clazz);
List<Field> searchFields = allFields.stream().filter(a -> a.getName().equals(name)).collect(Collectors.toList());
if(searchFields!=null && searchFields.size()>0){
field = searchFields.get(0);
}
}
if (field != null) {
TableField tableField = field.getAnnotation(TableField.class);
if (tableField != null){
if(tableField.exist() == false){
//如果设置了TableField false 这个字段不需要处理
return null;
}else{
String column = tableField.value();
//如果设置了TableField value 这个字段是实体字段
if(!"".equals(column)){
return column;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
} | jeecgboot/jeecg-boot | jeecg-boot-base-core/src/main/java/org/jeecg/common/util/ReflectHelper.java |
677 | package io.mycat.statistic.stat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.ast.statement.SQLInsertStatement;
import com.alibaba.druid.sql.ast.statement.SQLReplaceStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter;
import com.alibaba.druid.sql.parser.SQLParserUtils;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.alibaba.druid.sql.visitor.SQLASTVisitorAdapter;
import io.mycat.server.parser.ServerParse;
/**
* 按SQL表名进行计算
*
* @author zhuam
*
*/
public class TableStatAnalyzer implements QueryResultListener {
private static final Logger LOGGER = LoggerFactory.getLogger(TableStatAnalyzer.class);
private Map<String, TableStat> tableStatMap = new ConcurrentHashMap<>();
private ReentrantLock lock = new ReentrantLock();
//解析SQL 提取表名
private SQLParser sqlParser = new SQLParser();
private final static TableStatAnalyzer instance = new TableStatAnalyzer();
private TableStatAnalyzer() {}
public static TableStatAnalyzer getInstance() {
return instance;
}
@Override
public void onQueryResult(QueryResult queryResult) {
int sqlType = queryResult.getSqlType();
String sql = queryResult.getSql();
switch(sqlType) {
case ServerParse.SELECT:
case ServerParse.UPDATE:
case ServerParse.INSERT:
case ServerParse.DELETE:
case ServerParse.REPLACE:
//关联表提取
String masterTable = null;
List<String> relaTables = new ArrayList<String>();
List<String> tables = sqlParser.parseTableNames(sql);
for(int i = 0; i < tables.size(); i++) {
String table = tables.get(i);
if ( i == 0 ) {
masterTable = table;
} else {
relaTables.add( table );
}
}
if ( masterTable != null ) {
TableStat tableStat = getTableStat( masterTable );
tableStat.update(sqlType, sql, queryResult.getStartTime(), queryResult.getEndTime(), relaTables);
}
break;
}
}
private TableStat getTableStat(String tableName) {
TableStat userStat = tableStatMap.get(tableName);
if (userStat == null) {
if(lock.tryLock()){
try{
userStat = new TableStat(tableName);
tableStatMap.put(tableName, userStat);
} finally {
lock.unlock();
}
}else{
while(userStat == null){
userStat = tableStatMap.get(tableName);
}
}
}
return userStat;
}
public Map<String, TableStat> getTableStatMap() {
Map<String, TableStat> map = new LinkedHashMap<String, TableStat>(tableStatMap.size());
map.putAll(tableStatMap);
return map;
}
/**
* 获取 table 访问排序统计
*/
public List<TableStat> getTableStats(boolean isClear) {
SortedSet<TableStat> tableStatSortedSet = new TreeSet<>(tableStatMap.values());
List<TableStat> list = new ArrayList<>(tableStatSortedSet);
return list;
}
public void ClearTable() {
tableStatMap.clear();
}
/**
* 解析 table name
*/
private static class SQLParser {
private SQLStatement parseStmt(String sql) {
SQLStatementParser statParser = SQLParserUtils.createSQLStatementParser(sql, "mysql");
SQLStatement stmt = statParser.parseStatement();
return stmt;
}
/**
* 去掉库名、去掉``
* @param tableName
* @return
*/
private String fixName(String tableName) {
if ( tableName != null ) {
tableName = tableName.replace("`", "");
int dotIdx = tableName.indexOf(".");
if ( dotIdx > 0 ) {
tableName = tableName.substring(1 + dotIdx).trim();
}
}
return tableName;
}
/**
* 解析 SQL table name
*/
public List<String> parseTableNames(String sql) {
final List<String> tables = new ArrayList<String>();
try{
SQLStatement stmt = parseStmt(sql);
if (stmt instanceof SQLReplaceStatement) {
String table = ((SQLReplaceStatement) stmt).getTableName().getSimpleName();
tables.add( fixName( table ) );
} else if (stmt instanceof SQLInsertStatement ) {
String table = ((SQLInsertStatement)stmt).getTableName().getSimpleName();
tables.add( fixName( table ) );
} else if (stmt instanceof SQLUpdateStatement ) {
String table = ((SQLUpdateStatement)stmt).getTableName().getSimpleName();
tables.add( fixName( table ) );
} else if (stmt instanceof SQLDeleteStatement ) {
// Ken.li 2020/04/02
//String table = ((SQLDeleteStatement)stmt).getTableName().getSimpleName();
//tables.add( fixName( table ) );
((SQLDeleteStatement)stmt).getTableSource().accept(new SQLASTVisitorAdapter() {
public boolean visit(SQLExprTableSource x){
tables.add( fixName( x.toString() ) );
return super.visit(x);
}
});
if (((SQLDeleteStatement)stmt).getFrom() != null) {
((SQLDeleteStatement)stmt).getFrom().accept(new SQLASTVisitorAdapter() {
public boolean visit(SQLExprTableSource x){
if (tables.contains(x.getAlias())) {
tables.remove(x.getAlias());
tables.add( fixName( x.toString() ) );
}
return super.visit(x);
}
});
}
} else if (stmt instanceof SQLSelectStatement ) {
//TODO: modify by owenludong
DbType dbType = ((SQLSelectStatement) stmt).getDbType();
if (DbType.mysql.equals(dbType)) {
stmt.accept(new MySqlASTVisitorAdapter() {
public boolean visit(SQLExprTableSource x){
tables.add( fixName( x.toString() ) );
return super.visit(x);
}
});
} else {
stmt.accept(new SQLASTVisitorAdapter() {
public boolean visit(SQLExprTableSource x){
tables.add( fixName( x.toString() ) );
return super.visit(x);
}
});
}
}
} catch (Exception e) {
LOGGER.error("TableStatAnalyzer err:" + sql, e);
}
return tables;
}
}
/* public static void main(String[] args) {
List<String> sqls = new ArrayList<String>();
sqls.add( "SELECT id, name, age FROM v1select1 a LEFT OUTER JOIN v1select2 b ON a.id = b.id WHERE a.name = 12 ");
sqls.add( "insert into v1user_insert(id, name) values(1,3)");
sqls.add( "delete from v1user_delete where id= 2");
sqls.add( "update v1user_update set id=2 where id=3");
sqls.add( "select ename,deptno,sal from v1user_subquery1 where deptno=(select deptno from v1user_subquery2 where loc='NEW YORK')");
sqls.add( "replace into v1user_insert(id, name) values(1,3)");
sqls.add( "select * from v1xx where id=3 group by zz");
sqls.add( "select * from v1yy where xx=3 limit 0,3");
sqls.add( "SELECT * FROM (SELECT * FROM posts ORDER BY dateline DESC) GROUP BY tid ORDER BY dateline DESC LIMIT 10");
for(String sql: sqls) {
List<String> tables = TableStatAnalyzer.getInstance().sqlParser.parseTableNames(sql);
for(String t: tables) {
System.out.println( t );
}
}
}
*/
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/statistic/stat/TableStatAnalyzer.java |
678 | /*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.utils;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import me.zhengjie.exception.BadRequestException;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* File工具类,扩展 hutool 工具包
*
* @author Zheng Jie
* @date 2018-12-27
*/
public class FileUtil extends cn.hutool.core.io.FileUtil {
private static final Logger log = LoggerFactory.getLogger(FileUtil.class);
/**
* 系统临时目录
* <br>
* windows 包含路径分割符,但Linux 不包含,
* 在windows \\==\ 前提下,
* 为安全起见 同意拼装 路径分割符,
* <pre>
* java.io.tmpdir
* windows : C:\Users/xxx\AppData\Local\Temp\
* linux: /temp
* </pre>
*/
public static final String SYS_TEM_DIR = System.getProperty("java.io.tmpdir") + File.separator;
/**
* 定义GB的计算常量
*/
private static final int GB = 1024 * 1024 * 1024;
/**
* 定义MB的计算常量
*/
private static final int MB = 1024 * 1024;
/**
* 定义KB的计算常量
*/
private static final int KB = 1024;
/**
* 格式化小数
*/
private static final DecimalFormat DF = new DecimalFormat("0.00");
public static final String IMAGE = "图片";
public static final String TXT = "文档";
public static final String MUSIC = "音乐";
public static final String VIDEO = "视频";
public static final String OTHER = "其他";
/**
* MultipartFile转File
*/
public static File toFile(MultipartFile multipartFile) {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = "." + getExtensionName(fileName);
File file = null;
try {
// 用uuid作为文件名,防止生成的临时文件重复
file = new File(SYS_TEM_DIR + IdUtil.simpleUUID() + prefix);
// MultipartFile to File
multipartFile.transferTo(file);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return file;
}
/**
* 获取文件扩展名,不带 .
*/
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
/**
* Java文件操作 获取不带扩展名的文件名
*/
public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
}
/**
* 文件大小转换
*/
public static String getSize(long size) {
String resultSize;
if (size / GB >= 1) {
//如果当前Byte的值大于等于1GB
resultSize = DF.format(size / (float) GB) + "GB ";
} else if (size / MB >= 1) {
//如果当前Byte的值大于等于1MB
resultSize = DF.format(size / (float) MB) + "MB ";
} else if (size / KB >= 1) {
//如果当前Byte的值大于等于1KB
resultSize = DF.format(size / (float) KB) + "KB ";
} else {
resultSize = size + "B ";
}
return resultSize;
}
/**
* inputStream 转 File
*/
static File inputStreamToFile(InputStream ins, String name){
File file = new File(SYS_TEM_DIR + name);
if (file.exists()) {
return file;
}
OutputStream os = null;
try {
os = new FileOutputStream(file);
int bytesRead;
int len = 8192;
byte[] buffer = new byte[len];
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
CloseUtil.close(os);
CloseUtil.close(ins);
}
return file;
}
/**
* 将文件名解析成文件的上传路径
*/
public static File upload(MultipartFile file, String filePath) {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");
// 过滤非法文件名
String name = getFileNameNoEx(verifyFilename(file.getOriginalFilename()));
String suffix = getExtensionName(file.getOriginalFilename());
String nowStr = "-" + format.format(date);
try {
String fileName = name + nowStr + "." + suffix;
String path = filePath + fileName;
// getCanonicalFile 可解析正确各种路径
File dest = new File(path).getCanonicalFile();
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
if (!dest.getParentFile().mkdirs()) {
System.out.println("was not successful.");
}
}
// 文件写入
file.transferTo(dest);
return dest;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* 导出excel
*/
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";
File file = new File(tempPath);
BigExcelWriter writer = ExcelUtil.getBigWriter(file);
// 一次性写出内容,使用默认样式,强制输出标题
writer.write(list, true);
SXSSFSheet sheet = (SXSSFSheet)writer.getSheet();
//上面需要强转SXSSFSheet 不然没有trackAllColumnsForAutoSizing方法
sheet.trackAllColumnsForAutoSizing();
//列宽自适应
writer.autoSizeColumnAll();
//response为HttpServletResponse对象
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");
ServletOutputStream out = response.getOutputStream();
// 终止后删除临时文件
file.deleteOnExit();
writer.flush(out, true);
//此处记得关闭输出Servlet流
IoUtil.close(out);
}
public static String getFileType(String type) {
String documents = "txt doc pdf ppt pps xlsx xls docx";
String music = "mp3 wav wma mpa ram ra aac aif m4a";
String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg";
String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg";
if (image.contains(type)) {
return IMAGE;
} else if (documents.contains(type)) {
return TXT;
} else if (music.contains(type)) {
return MUSIC;
} else if (video.contains(type)) {
return VIDEO;
} else {
return OTHER;
}
}
public static void checkSize(long maxSize, long size) {
// 1M
int len = 1024 * 1024;
if (size > (maxSize * len)) {
throw new BadRequestException("文件超出规定大小:" + maxSize + "MB");
}
}
/**
* 判断两个文件是否相同
*/
public static boolean check(File file1, File file2) {
String img1Md5 = getMd5(file1);
String img2Md5 = getMd5(file2);
if(img1Md5 != null){
return img1Md5.equals(img2Md5);
}
return false;
}
/**
* 判断两个文件是否相同
*/
public static boolean check(String file1Md5, String file2Md5) {
return file1Md5.equals(file2Md5);
}
private static byte[] getByte(File file) {
// 得到文件长度
byte[] b = new byte[(int) file.length()];
InputStream in = null;
try {
in = new FileInputStream(file);
try {
System.out.println(in.read(b));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
} finally {
CloseUtil.close(in);
}
return b;
}
private static String getMd5(byte[] bytes) {
// 16进制字符
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(bytes);
byte[] md = mdTemp.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
// 移位 输出字符串
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* 下载文件
*
* @param request /
* @param response /
* @param file /
*/
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) {
response.setCharacterEncoding(request.getCharacterEncoding());
response.setContentType("application/octet-stream");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
IOUtils.copy(fis, response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (fis != null) {
try {
fis.close();
if (deleteOnExit) {
file.deleteOnExit();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
/**
* 验证并过滤非法的文件名
* @param fileName 文件名
* @return 文件名
*/
public static String verifyFilename(String fileName) {
// 过滤掉特殊字符
fileName = fileName.replaceAll("[\\\\/:*?\"<>|~\\s]", "");
// 去掉文件名开头和结尾的空格和点
fileName = fileName.trim().replaceAll("^[. ]+|[. ]+$", "");
// 不允许文件名超过255(在Mac和Linux中)或260(在Windows中)个字符
int maxFileNameLength = 255;
if (System.getProperty("os.name").startsWith("Windows")) {
maxFileNameLength = 260;
}
if (fileName.length() > maxFileNameLength) {
fileName = fileName.substring(0, maxFileNameLength);
}
// 过滤掉控制字符
fileName = fileName.replaceAll("[\\p{Cntrl}]", "");
// 过滤掉 ".." 路径
fileName = fileName.replaceAll("\\.{2,}", "");
// 去掉文件名开头的 ".."
fileName = fileName.replaceAll("^\\.+/", "");
// 保留文件名中最后一个 "." 字符,过滤掉其他 "."
fileName = fileName.replaceAll("^(.*)(\\.[^.]*)$", "$1").replaceAll("\\.", "") +
fileName.replaceAll("^(.*)(\\.[^.]*)$", "$2");
return fileName;
}
public static String getMd5(File file) {
return getMd5(getByte(file));
}
}
| elunez/eladmin | eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java |
679 | package org.ansj.app.crf.model;
import org.ansj.app.crf.Config;
import org.ansj.app.crf.Model;
import org.nlpcn.commons.lang.tire.domain.SmartForest;
import org.nlpcn.commons.lang.util.IOUtil;
import org.nlpcn.commons.lang.util.ObjConver;
import org.nlpcn.commons.lang.util.StringUtil;
import org.nlpcn.commons.lang.util.tuples.Pair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* 加载wapiti生成的crf模型,测试使用的wapiti版本为:Wapiti v1.5.0
*
* wapiti 下载地址:https://wapiti.limsi.fr/#download 在这里感谢作者所做的工作.
*
* @author Ansj
*
*/
public class WapitiCRFModel extends Model {
@Override
public WapitiCRFModel loadModel(String modelPath) throws Exception {
try (InputStream is = IOUtil.getInputStream(modelPath)) {
return loadModel(is);
}
}
@Override
public WapitiCRFModel loadModel(InputStream is) throws Exception {
BufferedReader br = IOUtil.getReader(is, IOUtil.UTF8);
long start = System.currentTimeMillis();
logger.info("load wapiti model begin!");
String temp = br.readLine();
logger.info(temp); // #mdl#2#123
Map<String, Integer> featureIndex = loadConfig(br);
StringBuilder sb = new StringBuilder();
for (int[] t1 : config.getTemplate()) {
sb.append(Arrays.toString(t1) + " ");
}
logger.info("featureIndex is " + featureIndex);
logger.info("load template ok template : " + sb);
int[] statusCoven = loadTagCoven(br);
List<Pair<String, String>> loadFeatureName = loadFeatureName(featureIndex, br);
logger.info("load feature ok feature size : " + loadFeatureName.size());
featureTree = new SmartForest<float[]>();
loadFeatureWeight(br, statusCoven, loadFeatureName);
logger.info("load wapiti model ok ! use time :" + (System.currentTimeMillis() - start));
return this;
}
/**
* 加载特征权重
*
* @param br
* @param featureNames
* @param statusCoven
* @throws Exception
*/
private void loadFeatureWeight(BufferedReader br, int[] statusCoven, List<Pair<String, String>> featureNames) throws Exception {
int key = 0;
int offe = 0;
int tag = 0; // 赏析按标签为用来转换
int len = 0; // 权重数组的大小
int min, max = 0; // 设置边界
String name = null; // 特征名称
float[] tempW = null; // 每一个特征的权重
String temp = br.readLine();
for (Pair<String, String> pair : featureNames) {
if (temp == null) {
logger.warn(pair.getValue0() + "\t" + pair.getValue1() + " not have any weight ,so skip it !");
continue;
}
char fc = Character.toUpperCase(pair.getValue0().charAt(0));
len = fc == 'B' ? Config.TAG_NUM * Config.TAG_NUM : fc == 'U' ? Config.TAG_NUM : fc == '*' ? (Config.TAG_NUM + Config.TAG_NUM * Config.TAG_NUM) : 0;
if (len == 0) {
throw new Exception("unknow feature type " + pair.getValue0());
}
min = max;
max += len;
if (fc == 'B') { // 特殊处理转换特征数组
for (int i = 0; i < len; i++) {
String[] split = temp.split("=");
int from = statusCoven[i / Config.TAG_NUM];
int to = statusCoven[i % Config.TAG_NUM];
status[from][to] = ObjConver.getFloatValue(split[1]);
temp = br.readLine();
}
} else {
name = pair.getValue1();
tempW = new float[len];
do {
String[] split = temp.split("=");
key = ObjConver.getIntValue(split[0]);
if (key >= max) { // 如果超过边界那么跳出
break;
}
offe = key - min;
tag = statusCoven[offe];
tempW[tag] = ObjConver.getFloatValue(split[1]);
} while ((temp = br.readLine()) != null);
this.featureTree.add(name, tempW); // 将特征增加到特征🌲中
// printFeatureTree(name, tempW);
}
}
}
/**
* 加载特征值 //11:*6:_x-1/的,
*
* @param featureIndex
*
* @param br
* @return
* @throws Exception
*/
private List<Pair<String, String>> loadFeatureName(Map<String, Integer> featureIndex, BufferedReader br) throws Exception {
String temp = br.readLine();// #qrk#num
int featureNum = ObjConver.getIntValue(StringUtil.matcherFirst("\\d+", temp)); // 找到特征个数
List<Pair<String, String>> featureNames = new ArrayList<Pair<String, String>>();
for (int i = 0; i < featureNum; i++) {
temp = br.readLine();
String[] split = temp.split(":");
if (split.length == 2) {
featureNames.add(Pair.with(split[1], ""));
continue;
} else {
String name = split[2];
if (split.length > 3) {
for (int j = 3; j < split.length; j++) {
name += ":" + split[j];
}
}
// 去掉最后的空格
name = name.substring(0, name.length() - 1);
int lastFeatureId = featureIndex.get(split[1]);
if ("/".equals(name)) {
name = "//";
}
if (name.contains("//")) {
name = name.replaceAll("//", "/XIEGANG/");
}
String featureName = toFeatureName(name.trim().split("/"), lastFeatureId);
featureNames.add(Pair.with(split[1], featureName));
}
}
return featureNames;
}
private String toFeatureName(String[] split, int lastFeatureId) throws Exception {
StringBuilder result = new StringBuilder();
for (String str : split) {
if ("".equals(str)) {
continue;
} else if (str.length() == 1) {
result.append(str.charAt(0));
} else if (str.equals("XIEGANG")) {
result.append('/');
} else if (str.startsWith("num")) {
result.append((char) (Config.NUM_BEGIN + ObjConver.getIntValue(str.replace("num", ""))));
} else if (str.startsWith("en")) {
result.append((char) (Config.EN_BEGIN + ObjConver.getIntValue(str.replace("en", ""))));
} else if (str.startsWith("_x-")) {
result.append(Config.BEGIN);
} else if (str.startsWith("_x+")) {
result.append(Config.END);
} else {
throw new Exception("can find feature named " + str + " in " + Arrays.toString(split));
}
}
result.append((char) (lastFeatureId + Config.FEATURE_BEGIN));
return result.toString();
}
/**
* 加载特征标签转换
*
* @param br
* @return
* @throws Exception
*/
private int[] loadTagCoven(BufferedReader br) throws Exception {
int[] conver = new int[Config.TAG_NUM + Config.TAG_NUM * Config.TAG_NUM];
String temp = br.readLine();// #qrk#4
// TODO: 这个是个写死的过程,如果标签发生改变需要重新来写这里
for (int i = 0; i < Config.TAG_NUM; i++) {
char c = br.readLine().split(":")[1].charAt(0);
switch (c) {
case 'S':
conver[i] = Config.S;
break;
case 'B':
conver[i] = Config.B;
break;
case 'M':
conver[i] = Config.M;
break;
case 'E':
conver[i] = Config.E;
break;
default:
throw new Exception("err tag named " + c + " in model " + temp);
}
}
for (int i = Config.TAG_NUM; i < conver.length; i++) {
conver[i] = conver[(i - 4) / Config.TAG_NUM] * Config.TAG_NUM + conver[i % Config.TAG_NUM] + Config.TAG_NUM;
}
return conver;
}
/**
* 加载特征模板
*
* @param br
* @return
* @throws IOException
*/
private Map<String, Integer> loadConfig(BufferedReader br) throws IOException {
Map<String, Integer> featureIndex = new HashMap<String, Integer>();
String temp = br.readLine();// #rdr#8/0/0
int featureNum = ObjConver.getIntValue(StringUtil.matcherFirst("\\d+", temp)); // 找到特征个数
List<int[]> list = new ArrayList<int[]>();
for (int i = 0; i < featureNum; i++) {
temp = br.readLine();
List<String> matcherAll = StringUtil.matcherAll("\\[.*?\\]", temp);
if (matcherAll.size() == 0) {
continue;
}
int[] is = new int[matcherAll.size()];
for (int j = 0; j < is.length; j++) {
is[j] = ObjConver.getIntValue(StringUtil.matcherFirst("[-\\d]+", matcherAll.get(j)));
}
featureIndex.put(temp.split(":")[1], list.size());
list.add(is);
}
int[][] template = new int[list.size()][0]; // 构建特征模板
for (int i = 0; i < template.length; i++) {
template[i] = list.get(i);
}
config = new Config(template);
return featureIndex;
}
@Override
public boolean checkModel(String modelPath) {
try (InputStream is = IOUtil.getInputStream(modelPath)) {
byte[] bytes = new byte[100];
is.read(bytes);
String string = new String(bytes);
if (string.startsWith("#mdl#")) { // 加载crf++ 的txt类型的modle
return true;
}
} catch (IOException e) {
logger.warn("IO异常", e);
}
return false;
}
}
| NLPchina/ansj_seg | src/main/java/org/ansj/app/crf/model/WapitiCRFModel.java |
685 | package com.xkcoding.task.quartz.job.base;
import org.quartz.*;
/**
* <p>
* Job 基类,主要是在 {@link org.quartz.Job} 上再封装一层,只让我们自己项目里的Job去实现
* </p>
*
* @author yangkai.shen
* @date Created in 2018-11-26 13:27
*/
public interface BaseJob extends Job {
/**
* <p>
* Called by the <code>{@link Scheduler}</code> when a <code>{@link Trigger}</code>
* fires that is associated with the <code>Job</code>.
* </p>
*
* <p>
* The implementation may wish to set a
* {@link JobExecutionContext#setResult(Object) result} object on the
* {@link JobExecutionContext} before this method exits. The result itself
* is meaningless to Quartz, but may be informative to
* <code>{@link JobListener}s</code> or
* <code>{@link TriggerListener}s</code> that are watching the job's
* execution.
* </p>
*
* @param context 上下文
* @throws JobExecutionException if there is an exception while executing the job.
*/
@Override
void execute(JobExecutionContext context) throws JobExecutionException;
}
| xkcoding/spring-boot-demo | demo-task-quartz/src/main/java/com/xkcoding/task/quartz/job/base/BaseJob.java |
686 | package com.scwang.refreshlayout.util;
import androidx.annotation.NonNull;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* 动态时间格式化
* Created by scwang on 2017/6/17.
*/
public class DynamicTimeFormat extends SimpleDateFormat {
private static Locale locale = Locale.CHINA;
private static String weeks[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
private static String moments[] = {"中午", "凌晨", "早上", "下午", "晚上"};
private String mFormat = "%s";
public DynamicTimeFormat() {
this("%s", "yyyy年", "M月d日", "HH:mm");
}
public DynamicTimeFormat(String format) {
this();
this.mFormat = format;
}
public DynamicTimeFormat(String yearFormat, String dateFormat, String timeFormat) {
super(String.format(locale, "%s %s %s", yearFormat, dateFormat, timeFormat), locale);
}
public DynamicTimeFormat(String format, String yearFormat, String dateFormat, String timeFormat) {
this(yearFormat, dateFormat, timeFormat);
this.mFormat = format;
}
@Override
public StringBuffer format(@NonNull Date date, @NonNull StringBuffer toAppendTo, @NonNull FieldPosition pos) {
toAppendTo = super.format(date, toAppendTo, pos);
Calendar otherCalendar = calendar;
Calendar todayCalendar = Calendar.getInstance();
int hour = otherCalendar.get(Calendar.HOUR_OF_DAY);
String[] times = toAppendTo.toString().split(" ");
String moment = hour == 12 ? moments[0] : moments[hour / 6 + 1];
String timeFormat = moment + " " + times[2];
String dateFormat = times[1] + " " + timeFormat;
String yearFormat = times[0] + dateFormat;
toAppendTo.delete(0, toAppendTo.length());
boolean yearTemp = todayCalendar.get(Calendar.YEAR) == otherCalendar.get(Calendar.YEAR);
if (yearTemp) {
int todayMonth = todayCalendar.get(Calendar.MONTH);
int otherMonth = otherCalendar.get(Calendar.MONTH);
if (todayMonth == otherMonth) {//表示是同一个月
int temp = todayCalendar.get(Calendar.DATE) - otherCalendar.get(Calendar.DATE);
switch (temp) {
case 0:
toAppendTo.append(timeFormat);
break;
case 1:
toAppendTo.append("昨天 ");
toAppendTo.append(timeFormat);
break;
case 2:
toAppendTo.append("前天 ");
toAppendTo.append(timeFormat);
break;
case 3:
case 4:
case 5:
case 6:
int dayOfMonth = otherCalendar.get(Calendar.WEEK_OF_MONTH);
int todayOfMonth = todayCalendar.get(Calendar.WEEK_OF_MONTH);
if (dayOfMonth == todayOfMonth) {//表示是同一周
int dayOfWeek = otherCalendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != 1) {//判断当前是不是星期日 如想显示为:周日 12:09 可去掉此判断
toAppendTo.append(weeks[otherCalendar.get(Calendar.DAY_OF_WEEK) - 1]);
toAppendTo.append(' ');
toAppendTo.append(timeFormat);
} else {
toAppendTo.append(dateFormat);
}
} else {
toAppendTo.append(dateFormat);
}
break;
default:
toAppendTo.append(dateFormat);
break;
}
} else {
toAppendTo.append(dateFormat);
}
} else {
toAppendTo.append(yearFormat);
}
int length = toAppendTo.length();
toAppendTo.append(String.format(locale, mFormat, toAppendTo.toString()));
toAppendTo.delete(0, length);
return toAppendTo;
}
}
| scwang90/SmartRefreshLayout | app/src/main/java/com/scwang/refreshlayout/util/DynamicTimeFormat.java |
687 | package me.zhyd.oauth.utils;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* Base64编码
*
* @author looly
* @since 3.2.0
*/
public class Base64Utils {
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
/**
* 标准编码表
*/
private static final byte[] STANDARD_ENCODE_TABLE = { //
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', //
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', //
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', //
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', //
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', //
'w', 'x', 'y', 'z', '0', '1', '2', '3', //
'4', '5', '6', '7', '8', '9', '+', '/' //
};
/**
* URL安全的编码表,将 + 和 / 替换为 - 和 _
*/
private static final byte[] URL_SAFE_ENCODE_TABLE = { //
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', //
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', //
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', //
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', //
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', //
'w', 'x', 'y', 'z', '0', '1', '2', '3', //
'4', '5', '6', '7', '8', '9', '-', '_' //
};
// -------------------------------------------------------------------- encode
/**
* 编码为Base64,非URL安全的
*
* @param arr 被编码的数组
* @param lineSep 在76个char之后是CRLF还是EOF
* @return 编码后的bytes
*/
public static byte[] encode(byte[] arr, boolean lineSep) {
return encode(arr, lineSep, false);
}
/**
* 编码为Base64,URL安全的
*
* @param arr 被编码的数组
* @param lineSep 在76个char之后是CRLF还是EOF
* @return 编码后的bytes
* @since 3.0.6
*/
public static byte[] encodeUrlSafe(byte[] arr, boolean lineSep) {
return encode(arr, lineSep, true);
}
/**
* base64编码
*
* @param source 被编码的base64字符串
* @return 被加密后的字符串
*/
public static String encode(CharSequence source) {
return encode(source, DEFAULT_CHARSET);
}
/**
* base64编码,URL安全
*
* @param source 被编码的base64字符串
* @return 被加密后的字符串
* @since 3.0.6
*/
public static String encodeUrlSafe(CharSequence source) {
return encodeUrlSafe(source, DEFAULT_CHARSET);
}
/**
* base64编码
*
* @param source 被编码的base64字符串
* @param charset 字符集
* @return 被加密后的字符串
*/
public static String encode(CharSequence source, Charset charset) {
return encode(StringUtils.bytes(source, charset));
}
/**
* base64编码,URL安全的
*
* @param source 被编码的base64字符串
* @param charset 字符集
* @return 被加密后的字符串
* @since 3.0.6
*/
public static String encodeUrlSafe(CharSequence source, Charset charset) {
return encodeUrlSafe(StringUtils.bytes(source, charset));
}
/**
* base64编码
*
* @param source 被编码的base64字符串
* @return 被加密后的字符串
*/
public static String encode(byte[] source) {
return StringUtils.str(encode(source, false), DEFAULT_CHARSET);
}
/**
* base64编码,URL安全的
*
* @param source 被编码的base64字符串
* @return 被加密后的字符串
* @since 3.0.6
*/
public static String encodeUrlSafe(byte[] source) {
return StringUtils.str(encodeUrlSafe(source, false), DEFAULT_CHARSET);
}
/**
* 编码为Base64<br>
* 如果isMultiLine为<code>true</code>,则每76个字符一个换行符,否则在一行显示
*
* @param arr 被编码的数组
* @param isMultiLine 在76个char之后是CRLF还是EOF
* @param isUrlSafe 是否使用URL安全字符,一般为<code>false</code>
* @return 编码后的bytes
*/
public static byte[] encode(byte[] arr, boolean isMultiLine, boolean isUrlSafe) {
if (null == arr) {
return null;
}
int len = arr.length;
if (len == 0) {
return new byte[0];
}
int evenlen = (len / 3) * 3;
int cnt = ((len - 1) / 3 + 1) << 2;
int destlen = cnt + (isMultiLine ? (cnt - 1) / 76 << 1 : 0);
byte[] dest = new byte[destlen];
byte[] encodeTable = isUrlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE;
for (int s = 0, d = 0, cc = 0; s < evenlen; ) {
int i = (arr[s++] & 0xff) << 16 | (arr[s++] & 0xff) << 8 | (arr[s++] & 0xff);
dest[d++] = encodeTable[(i >>> 18) & 0x3f];
dest[d++] = encodeTable[(i >>> 12) & 0x3f];
dest[d++] = encodeTable[(i >>> 6) & 0x3f];
dest[d++] = encodeTable[i & 0x3f];
if (isMultiLine && ++cc == 19 && d < destlen - 2) {
dest[d++] = '\r';
dest[d++] = '\n';
cc = 0;
}
}
int left = len - evenlen;// 剩余位数
if (left > 0) {
int i = ((arr[evenlen] & 0xff) << 10) | (left == 2 ? ((arr[len - 1] & 0xff) << 2) : 0);
dest[destlen - 4] = encodeTable[i >> 12];
dest[destlen - 3] = encodeTable[(i >>> 6) & 0x3f];
if (isUrlSafe) {
// 在URL Safe模式下,=为URL中的关键字符,不需要补充。空余的byte位要去掉。
int urlSafeLen = destlen - 2;
if (2 == left) {
dest[destlen - 2] = encodeTable[i & 0x3f];
urlSafeLen += 1;
}
byte[] urlSafeDest = new byte[urlSafeLen];
System.arraycopy(dest, 0, urlSafeDest, 0, urlSafeLen);
return urlSafeDest;
} else {
dest[destlen - 2] = (left == 2) ? encodeTable[i & 0x3f] : (byte) '=';
dest[destlen - 1] = '=';
}
}
return dest;
}
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/utils/Base64Utils.java |
689 | package com.alibaba.druid.filter.mysql8datetime;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
/**
* 针对mysql jdbc 8.0.23及以上版本,通过该方法控制将对象类型转换成原来的类型
* @author lizongbo
* @see <a href="https://dev.mysql.com/doc/relnotes/connector-j/8.0/en/news-8-0-24.html">...</a>
*/
public class MySQL8DateTimeResultSetMetaData implements ResultSetMetaData {
private ResultSetMetaData resultSetMetaData;
public MySQL8DateTimeResultSetMetaData(ResultSetMetaData resultSetMetaData) {
super();
this.resultSetMetaData = resultSetMetaData;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return resultSetMetaData.unwrap(iface);
}
@Override
public int getColumnCount() throws SQLException {
return resultSetMetaData.getColumnCount();
}
@Override
public boolean isAutoIncrement(int column) throws SQLException {
return resultSetMetaData.isAutoIncrement(column);
}
@Override
public boolean isCaseSensitive(int column) throws SQLException {
return resultSetMetaData.isCaseSensitive(column);
}
@Override
public boolean isSearchable(int column) throws SQLException {
return resultSetMetaData.isSearchable(column);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return resultSetMetaData.isWrapperFor(iface);
}
@Override
public boolean isCurrency(int column) throws SQLException {
return resultSetMetaData.isCurrency(column);
}
@Override
public int isNullable(int column) throws SQLException {
return resultSetMetaData.isNullable(column);
}
@Override
public boolean isSigned(int column) throws SQLException {
return resultSetMetaData.isSigned(column);
}
@Override
public int getColumnDisplaySize(int column) throws SQLException {
return resultSetMetaData.getColumnDisplaySize(column);
}
@Override
public String getColumnLabel(int column) throws SQLException {
return resultSetMetaData.getColumnLabel(column);
}
@Override
public String getColumnName(int column) throws SQLException {
return resultSetMetaData.getColumnName(column);
}
@Override
public String getSchemaName(int column) throws SQLException {
return resultSetMetaData.getSchemaName(column);
}
@Override
public int getPrecision(int column) throws SQLException {
return resultSetMetaData.getPrecision(column);
}
@Override
public int getScale(int column) throws SQLException {
return resultSetMetaData.getScale(column);
}
@Override
public String getTableName(int column) throws SQLException {
return resultSetMetaData.getTableName(column);
}
@Override
public String getCatalogName(int column) throws SQLException {
return resultSetMetaData.getCatalogName(column);
}
@Override
public int getColumnType(int column) throws SQLException {
return resultSetMetaData.getColumnType(column);
}
@Override
public String getColumnTypeName(int column) throws SQLException {
return resultSetMetaData.getColumnTypeName(column);
}
@Override
public boolean isReadOnly(int column) throws SQLException {
return resultSetMetaData.isReadOnly(column);
}
@Override
public boolean isWritable(int column) throws SQLException {
return resultSetMetaData.isWritable(column);
}
@Override
public boolean isDefinitelyWritable(int column) throws SQLException {
return resultSetMetaData.isDefinitelyWritable(column);
}
/**
* 针对8.0.24版本开始,如果把mysql DATETIME映射回Timestamp,就需要把javaClass的类型也改回去
* 相关类在com.mysql.cj.MysqlType 中
* 旧版本jdbc为
* DATETIME("DATETIME", Types.TIMESTAMP, Timestamp.class, 0, MysqlType.IS_NOT_DECIMAL, 26L, "[(fsp)]"),
* 8.0.24及以上版本jdbc实现改为
* DATETIME("DATETIME", Types.TIMESTAMP, LocalDateTime.class, 0, MysqlType.IS_NOT_DECIMAL, 26L, "[(fsp)]"),
* @param column 列的索引位
* @return 列名称
* @see java.sql.ResultSetMetaData#getColumnClassName(int)
* @throws SQLException 如果发生数据库访问错误
*/
@Override
public String getColumnClassName(int column) throws SQLException {
String className = resultSetMetaData.getColumnClassName(column);
if (LocalDateTime.class.getName().equals(className)) {
return Timestamp.class.getName();
}
return className;
}
}
| alibaba/druid | core/src/main/java/com/alibaba/druid/filter/mysql8datetime/MySQL8DateTimeResultSetMetaData.java |
691 | package com.blankj.medium._0067;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2020/07/07
* desc :
* </pre>
*/
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length, n = obstacleGrid[0].length;
int[][] dp = new int[m][n];
// 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法,
// 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0;
for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) {
dp[i][0] = 1;
}
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {
dp[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 0) {
// 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
return dp[m - 1][n - 1];
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}};
System.out.println(solution.uniquePathsWithObstacles(obstacleGrid));
}
}
| Blankj/awesome-java-leetcode | src/com/blankj/medium/_0067/Solution.java |
693 | package com.macro.mall.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
/**
* 确认收货请求参数
* Created by macro on 2018/10/18.
*/
@Getter
@Setter
public class OmsUpdateStatusParam {
@ApiModelProperty("服务单号")
private Long id;
@ApiModelProperty("收货地址关联id")
private Long companyAddressId;
@ApiModelProperty("确认退款金额")
private BigDecimal returnAmount;
@ApiModelProperty("处理备注")
private String handleNote;
@ApiModelProperty("处理人")
private String handleMan;
@ApiModelProperty("收货备注")
private String receiveNote;
@ApiModelProperty("收货人")
private String receiveMan;
@ApiModelProperty("申请状态:1->退货中;2->已完成;3->已拒绝")
private Integer status;
}
| macrozheng/mall | mall-admin/src/main/java/com/macro/mall/dto/OmsUpdateStatusParam.java |