diff --git a/README.md b/README.md index 434400abfe..37f1eff303 100755 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@

- + @@ -52,35 +52,35 @@ Bus (应用/服务总线) 是一个基础框架、服务套件,它基于Java17 ## 组件信息 -| 完成 | 模块 | 描述信息 | -|-----|---------------|---------------------------------------------------| -| [√] | bus-all | 包含微服务所需的完整模块以及通用组件 | +| 完成 | 模块 | 描述信息 | +|-----|---------------|-------------------------------------------------| +| [√] | bus-all | 包含微服务所需的完整模块以及通用组件 | | [√] | bus-base | 基础功能及base相关,实体(Entity),服务(Service),接口(Controller) | -| [√] | bus-bom | 包含所有组建信息,当然可以通过配置按需加载等 | -| [√] | bus-cache | 缓存服务及工具,支持redis,memcached,,hessian等 | -| [√] | bus-core | 核心功能及工具类,包括常量、线程、类加载器、反射、集合、日期等常用工具 | -| [√] | bus-cron | 定时器及定时任务等功能 | -| [√] | bus-crypto | 加密解密,支持支持AES/DES/REA/MD5等常用加密算法 | -| [√] | bus-extra | 扩展功能及文件操作,FTP/文件/二维码/短信相关支持 | -| [√] | bus-health | 应用服务器健康信息,软件硬件信息采集等 | -| [√] | bus-http | HTTP功能封装,根据业务场景可使用 Httpd/Httpx/Httpz 等方式 | -| [√] | bus-image | 图像/影像应用服务,解析预览等 | -| [×] | bus-limiter | 请求限流,根据不同业务设置不同限流策略 | -| [√] | bus-logger | 日志信息及功能,动态检测日志实现的方式,使日志使用个更加便利灵活简单 | -| [√] | bus-mapper | 数据操作,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率 | -| [√] | bus-oauth | 第三方登录,已集成十多家第三方平台(国内外常用的基本都已包含) | -| [√] | bus-pager | 数据分页,mybatis | -| [√] | bus-office | office等相关转换及处理,POI封装实现,使Java操作Excel等文件变得简单 | -| [√] | bus-opencv | 图像识别及分析,提供丰富的图形图像处理算法,跨平台支持等 | -| [√] | bus-proxy | 公共代理,使动态代理变得简单 | -| [√] | bus-sensitive | 敏感数据脱敏,对应用和使用者透明,业务逻辑无感知,通过配置集成 | -| [√] | bus-setting | 设置工具类, 用于支持设置/配置 | -| [√] | bus-shade | Entity,Service,Mapper等相关代码生成工具 | -| [√] | bus-socket | 基础NIO/AIO通讯,Socket封装,支持TCP/UDP服务端 | -| [√] | bus-starter | SpringBoot starter,spring相关配置,启动及相关配置文件信息 | -| [√] | bus-storage | 文件存储组件,,支持阿里云、七牛,提供了工厂模式和注入两种集成方式 | -| [×] | bus-tracer | 轻量级分布式链路跟踪监控,日志及访问流程追踪以及内部调用链追踪 | -| [√] | bus-validate | 参数校验,会默认拦截所有的标记有`@Valid`的方法或类 | +| [√] | bus-bom | 包含所有组建信息,当然可以通过配置按需加载等 | +| [√] | bus-cache | 缓存服务及工具,支持redis,memcached,,hessian等 | +| [√] | bus-core | 核心功能及工具类,包括常量、线程、类加载器、反射、集合、日期等常用工具 | +| [√] | bus-cron | 定时器及定时任务等功能 | +| [√] | bus-crypto | 加密解密,支持支持AES/DES/REA/MD5等常用加密算法 | +| [√] | bus-extra | 扩展功能及文件操作,FTP/文件/二维码/短信相关支持 | +| [√] | bus-health | 应用服务器健康信息,软件硬件信息采集等 | +| [√] | bus-http | HTTP功能封装,根据业务场景可使用 Httpd/Httpx/Httpz 等方式 | +| [√] | bus-image | 图像/影像应用服务,解析预览等 | +| [√] | bus-limiter | 服务限流/降级/提升热点,根据不同业务设置不同策略 | +| [√] | bus-logger | 日志信息及功能,动态检测日志实现的方式,使日志使用个更加便利灵活简单 | +| [√] | bus-mapper | 数据操作,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率 | +| [√] | bus-oauth | 第三方登录,已集成十多家第三方平台(国内外常用的基本都已包含) | +| [√] | bus-pager | 数据分页,mybatis | +| [√] | bus-office | office等相关转换及处理,POI封装实现,使Java操作Excel等文件变得简单 | +| [√] | bus-opencv | 图像识别及分析,提供丰富的图形图像处理算法,跨平台支持等 | +| [√] | bus-proxy | 公共代理,使动态代理变得简单 | +| [√] | bus-sensitive | 敏感数据脱敏,对应用和使用者透明,业务逻辑无感知,通过配置集成 | +| [√] | bus-setting | 设置工具类, 用于支持设置/配置 | +| [√] | bus-shade | Entity,Service,Mapper等相关代码生成工具 | +| [√] | bus-socket | 基础NIO/AIO通讯,Socket封装,支持TCP/UDP服务端 | +| [√] | bus-starter | SpringBoot starter,spring相关配置,启动及相关配置文件信息 | +| [√] | bus-storage | 文件存储组件,,支持阿里云、七牛,提供了工厂模式和注入两种集成方式 | +| [×] | bus-tracer | 轻量级分布式链路跟踪监控,日志及访问流程追踪以及内部调用链追踪 | +| [√] | bus-validate | 参数校验,会默认拦截所有的标记有`@Valid`的方法或类 | ## 功能概述 diff --git a/VERSION b/VERSION index fa5fce04b3..5210382a7a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -8.0.0 \ No newline at end of file +8.0.1 \ No newline at end of file diff --git a/bus-all/pom.xml b/bus-all/pom.xml index fa8bdb4198..6963956173 100755 --- a/bus-all/pom.xml +++ b/bus-all/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-all - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-base/pom.xml b/bus-base/pom.xml index 07f92cb073..e65ee7d230 100755 --- a/bus-base/pom.xml +++ b/bus-base/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-base - 8.0.0 + 8.0.1 jar ${project.artifactId} @@ -44,7 +44,7 @@ 21 21 1.18.32 - 3.0.5 + 3.3.0 3.2.0-M2 diff --git a/bus-base/src/main/java/org/miaixz/bus/base/entity/BaseEntity.java b/bus-base/src/main/java/org/miaixz/bus/base/entity/BaseEntity.java index d0f589fded..792d4499c1 100755 --- a/bus-base/src/main/java/org/miaixz/bus/base/entity/BaseEntity.java +++ b/bus-base/src/main/java/org/miaixz/bus/base/entity/BaseEntity.java @@ -26,8 +26,9 @@ package org.miaixz.bus.base.entity; import jakarta.persistence.Transient; -import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; import org.miaixz.bus.base.normal.Consts; import org.miaixz.bus.core.data.ObjectId; import org.miaixz.bus.core.lang.Normal; @@ -42,7 +43,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @EqualsAndHashCode(callSuper = true) public class BaseEntity extends Tracer { diff --git a/bus-base/src/main/java/org/miaixz/bus/base/entity/Entity.java b/bus-base/src/main/java/org/miaixz/bus/base/entity/Entity.java index 96734982a1..372618fe6b 100755 --- a/bus-base/src/main/java/org/miaixz/bus/base/entity/Entity.java +++ b/bus-base/src/main/java/org/miaixz/bus/base/entity/Entity.java @@ -26,7 +26,8 @@ package org.miaixz.bus.base.entity; import jakarta.persistence.Id; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import java.io.Serializable; @@ -36,7 +37,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter public abstract class Entity implements Serializable { private static final long serialVersionUID = 1L; diff --git a/bus-base/src/main/java/org/miaixz/bus/base/entity/Message.java b/bus-base/src/main/java/org/miaixz/bus/base/entity/Message.java index 2713b8d3e0..7a334bfc81 100755 --- a/bus-base/src/main/java/org/miaixz/bus/base/entity/Message.java +++ b/bus-base/src/main/java/org/miaixz/bus/base/entity/Message.java @@ -25,10 +25,7 @@ ********************************************************************************/ package org.miaixz.bus.base.entity; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; +import lombok.*; /** * 返回值公用类 @@ -36,7 +33,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @Builder @NoArgsConstructor @AllArgsConstructor diff --git a/bus-base/src/main/java/org/miaixz/bus/base/entity/OAuth2.java b/bus-base/src/main/java/org/miaixz/bus/base/entity/OAuth2.java index 8b04adda34..415d8cb0a6 100755 --- a/bus-base/src/main/java/org/miaixz/bus/base/entity/OAuth2.java +++ b/bus-base/src/main/java/org/miaixz/bus/base/entity/OAuth2.java @@ -26,8 +26,9 @@ package org.miaixz.bus.base.entity; import jakarta.persistence.Transient; -import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; /** * 授权公用类 @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @EqualsAndHashCode(callSuper = true) public class OAuth2 extends Entity { diff --git a/bus-base/src/main/java/org/miaixz/bus/base/entity/Result.java b/bus-base/src/main/java/org/miaixz/bus/base/entity/Result.java index 7fe50091a9..2cacf31954 100755 --- a/bus-base/src/main/java/org/miaixz/bus/base/entity/Result.java +++ b/bus-base/src/main/java/org/miaixz/bus/base/entity/Result.java @@ -25,8 +25,9 @@ ********************************************************************************/ package org.miaixz.bus.base.entity; -import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; import java.util.Collections; import java.util.List; @@ -37,7 +38,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @EqualsAndHashCode(callSuper = true) public class Result extends BaseEntity { diff --git a/bus-base/src/main/java/org/miaixz/bus/base/entity/Tracer.java b/bus-base/src/main/java/org/miaixz/bus/base/entity/Tracer.java index 71c03e9530..31d3d3a8e1 100755 --- a/bus-base/src/main/java/org/miaixz/bus/base/entity/Tracer.java +++ b/bus-base/src/main/java/org/miaixz/bus/base/entity/Tracer.java @@ -26,8 +26,9 @@ package org.miaixz.bus.base.entity; import jakarta.persistence.Transient; -import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; /** * 访问链路跟踪 @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @EqualsAndHashCode(callSuper = true) public class Tracer extends OAuth2 { diff --git a/bus-base/src/main/java/org/miaixz/bus/base/service/ErrorService.java b/bus-base/src/main/java/org/miaixz/bus/base/service/ErrorService.java index bb9ecc8aef..d9b67d04f3 100644 --- a/bus-base/src/main/java/org/miaixz/bus/base/service/ErrorService.java +++ b/bus-base/src/main/java/org/miaixz/bus/base/service/ErrorService.java @@ -34,7 +34,7 @@ * 此类未找到实现的情况下,采用默认实现 * 可以根据不同业务需求,继承此类实现对应业务逻辑即可 * 项目中可通过SPI自定义接入 - * 例:META-INF/services/service.base.org.miaixz.bus.ErrorService + * 例:META-INF/services/org.miaixz.bus.base.service.ErrorService * * org.miaixz.bus.xxx.ErrorService * diff --git a/bus-base/src/main/java/org/miaixz/bus/base/service/impl/BaseServiceImpl.java b/bus-base/src/main/java/org/miaixz/bus/base/service/impl/BaseServiceImpl.java index 63513240d0..79f80fc238 100755 --- a/bus-base/src/main/java/org/miaixz/bus/base/service/impl/BaseServiceImpl.java +++ b/bus-base/src/main/java/org/miaixz/bus/base/service/impl/BaseServiceImpl.java @@ -25,7 +25,6 @@ ********************************************************************************/ package org.miaixz.bus.base.service.impl; -import jakarta.annotation.Resource; import org.miaixz.bus.base.entity.BaseEntity; import org.miaixz.bus.base.entity.Result; import org.miaixz.bus.base.mapper.BaseMapper; @@ -37,6 +36,7 @@ import org.miaixz.bus.mapper.entity.Condition; import org.miaixz.bus.pager.Page; import org.miaixz.bus.pager.PageContext; +import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; @@ -52,7 +52,7 @@ public class BaseServiceImpl, T extends BaseEntity> implements BaseService { - @Resource + @Autowired protected Mapper mapper; @Override diff --git a/bus-bom/pom.xml b/bus-bom/pom.xml index 5dd77555a2..b37f5ad448 100755 --- a/bus-bom/pom.xml +++ b/bus-bom/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-bom - 8.0.0 + 8.0.1 pom ${project.artifactId} diff --git a/bus-cache/pom.xml b/bus-cache/pom.xml index 6d8f322d50..44e6911c2f 100755 --- a/bus-cache/pom.xml +++ b/bus-cache/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-cache - 8.0.0 + 8.0.1 jar ${project.artifactId} @@ -44,12 +44,12 @@ 21 21 1.18.32 - 3.0.5 + 3.3.0 7.0.0 - 5.1.2 + 5.1.3 2.4.8 5.6.0 - 33.1.0-jre + 33.2.1-jre 4.0.66 8.3.0 @@ -82,12 +82,6 @@ ${guava.version} true - - redis.clients - jedis - ${jedis.version} - true - com.caucho hessian @@ -100,6 +94,26 @@ ${mysql.version} true + + redis.clients + jedis + ${jedis.version} + true + + + org.slf4j + slf4j-api + + + org.json + json + + + com.google.code.gson + gson + + + com.google.inject guice @@ -110,6 +124,10 @@ aopalliance aopalliance + + org.slf4j + slf4j-api + @@ -142,6 +160,14 @@ org.slf4j slf4j-api + + io.netty + netty-handler + + + io.netty + netty-transport-native-epoll + @@ -149,6 +175,12 @@ spring-boot-starter-jdbc ${spring.boot.version} true + + + org.slf4j + slf4j-api + + org.springframework.boot diff --git a/bus-cache/src/main/java/org/miaixz/bus/cache/magic/MethodHolder.java b/bus-cache/src/main/java/org/miaixz/bus/cache/magic/MethodHolder.java index 7dee903e78..177f2ceb9a 100755 --- a/bus-cache/src/main/java/org/miaixz/bus/cache/magic/MethodHolder.java +++ b/bus-cache/src/main/java/org/miaixz/bus/cache/magic/MethodHolder.java @@ -25,13 +25,15 @@ ********************************************************************************/ package org.miaixz.bus.cache.magic; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; /** * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter public class MethodHolder { private Class innerReturnType; diff --git a/bus-core/pom.xml b/bus-core/pom.xml index 014770a49f..b6f4780ac8 100755 --- a/bus-core/pom.xml +++ b/bus-core/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-core - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/Builder.java b/bus-core/src/main/java/org/miaixz/bus/core/Builder.java index 2ffab80e12..6d85efd213 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/Builder.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/Builder.java @@ -41,6 +41,6 @@ public interface Builder extends Serializable { * * @return 被构建的对象 */ - T build(); + T build(); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/Version.java b/bus-core/src/main/java/org/miaixz/bus/core/Version.java index e219e24698..7c71fc3252 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/Version.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/Version.java @@ -46,7 +46,7 @@ public class Version implements Comparable, Serializable { /** * 版本信息 */ - public static final String _VERSION = "8.0.0"; + public static final String _VERSION = "8.0.1"; private static final long serialVersionUID = -1L; private final String version; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/cache/provider/AbstractCache.java b/bus-core/src/main/java/org/miaixz/bus/core/cache/provider/AbstractCache.java index c1e64da71d..9e20f01e49 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/cache/provider/AbstractCache.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/cache/provider/AbstractCache.java @@ -60,6 +60,9 @@ public abstract class AbstractCache implements Cache { * 写的时候每个key一把锁,降低锁的粒度 */ protected final Map keyLockMap = new SafeConcurrentHashMap<>(); + /** + * Map缓存 + */ protected Map, CacheObject> cacheMap; /** * 返回缓存容量,{@code 0}表示无大小限制 diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Almanac.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Almanac.java index e644878f0f..7902490f5e 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Almanac.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Almanac.java @@ -25,339 +25,19 @@ ********************************************************************************/ package org.miaixz.bus.core.center.date; -import org.miaixz.bus.core.lang.Fields; - -import java.time.*; -import java.time.chrono.ChronoLocalDate; -import java.time.chrono.ChronoLocalDateTime; -import java.time.temporal.*; - /** - * 日期计算类 + * 年鉴 * * @author Kimi Liu * @since Java 17+ */ -public class Almanac extends Resolver { - - /** - * 当前日期是否在日期指定范围内 - * 起始日期和结束日期可以互换 - * - * @param date 被检查的日期 - * @param beginDate 起始日期(包含) - * @param endDate 结束日期(包含) - * @return 是否在范围内 - */ - public static boolean isIn(final TemporalAccessor date, final TemporalAccessor beginDate, final TemporalAccessor endDate) { - return isIn(date, beginDate, endDate, true, true); - } - - /** - * 当前日期是否在日期指定范围内 - * 起始日期和结束日期可以互换 - * 通过includeBegin, includeEnd参数控制日期范围区间是否为开区间,例如:传入参数:includeBegin=true, includeEnd=false, - * 则本方法会判断 date ∈ (beginDate, endDate] 是否成立 - * - * @param date 被检查的日期 - * @param beginDate 起始日期 - * @param endDate 结束日期 - * @param includeBegin 时间范围是否包含起始日期 - * @param includeEnd 时间范围是否包含结束日期 - * @return 是否在范围内 - */ - public static boolean isIn(final TemporalAccessor date, final TemporalAccessor beginDate, final TemporalAccessor endDate, - final boolean includeBegin, final boolean includeEnd) { - if (date == null || beginDate == null || endDate == null) { - throw new IllegalArgumentException("参数不可为null"); - } - - final long thisMills = toEpochMilli(date); - final long beginMills = toEpochMilli(beginDate); - final long endMills = toEpochMilli(endDate); - final long rangeMin = Math.min(beginMills, endMills); - final long rangeMax = Math.max(beginMills, endMills); - - // 先判断是否满足 date ∈ (beginDate, endDate) - boolean isIn = rangeMin < thisMills && thisMills < rangeMax; - - // 若不满足,则再判断是否在时间范围的边界上 - if (!isIn && includeBegin) { - isIn = thisMills == rangeMin; - } - - if (!isIn && includeEnd) { - isIn = thisMills == rangeMax; - } - - return isIn; - } - - - /** - * 日期偏移,根据field不同加不同值(偏移会修改传入的对象) - * - * @param time {@link LocalDateTime} - * @param number 偏移量,正数为向后偏移,负数为向前偏移 - * @param field 偏移单位,见{@link ChronoUnit},不能为null - * @return 偏移后的日期时间 - */ - public static LocalDateTime offset(final LocalDateTime time, final long number, final TemporalUnit field) { - return offset(time, number, field); - } - - /** - * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负 - * 返回结果为{@link Duration}对象,通过调用toXXX方法返回相差单位 - * - * @param startTimeInclude 开始时间(包含) - * @param endTimeExclude 结束时间(不包含) - * @return 时间差 {@link Duration}对象 - * @see Almanac#between(Temporal, Temporal) - */ - public static Duration between(final LocalDateTime startTimeInclude, final LocalDateTime endTimeExclude) { - return between(startTimeInclude, endTimeExclude); - } - - /** - * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负 - * 返回结果为时间差的long值 - * - * @param startTimeInclude 开始时间(包括) - * @param endTimeExclude 结束时间(不包括) - * @param unit 时间差单位 - * @return 时间差 - */ - public static long between(final LocalDateTime startTimeInclude, final LocalDateTime endTimeExclude, final ChronoUnit unit) { - return between(startTimeInclude, endTimeExclude, unit); - } - - /** - * 获取两个日期的表象时间差,如果结束时间早于开始时间,获取结果为负。 - * 比如2011年2月1日,和2021年8月11日,日相差了10天,月相差6月 - * - * @param startTimeInclude 开始时间(包括) - * @param endTimeExclude 结束时间(不包括) - * @return 时间差 - */ - public static Period betweenPeriod(final LocalDate startTimeInclude, final LocalDate endTimeExclude) { - return Period.between(startTimeInclude, endTimeExclude); - } - - /** - * 修改为一天的开始时间,例如:2020-02-02 00:00:00,000 - * - * @param time 日期时间 - * @return 一天的开始时间 - */ - public static LocalDateTime beginOfDay(final LocalDateTime time) { - return time.with(LocalTime.MIN); - } - - /** - * 修改为一天的结束时间,例如: - *

- * - * @param time 日期时间 - * @param truncateMillisecond 是否毫秒归零 - * @return 一天的结束时间 - */ - public static LocalDateTime endOfDay(final LocalDateTime time, final boolean truncateMillisecond) { - return time.with(max(truncateMillisecond)); - } - - /** - * 修改为月初的开始时间,例如:2020-02-01 00:00:00,000 - * - * @param time 日期时间 - * @return 月初的开始时间 - */ - public static LocalDateTime beginOfMonth(final LocalDateTime time) { - return beginOfDay(time).with(TemporalAdjusters.firstDayOfMonth()); - } - - /** - * 修改为月底的结束时间 - * - * @param time 日期时间 - * @param truncateMillisecond 是否毫秒归零 - * @return 月底的结束时间 - */ - public static LocalDateTime endOfMonth(final LocalDateTime time, final boolean truncateMillisecond) { - return endOfDay(time, truncateMillisecond).with(TemporalAdjusters.lastDayOfMonth()); - } - - /** - * 修改为一年的开始时间,例如:2020-01-01 00:00:00,000 - * - * @param time 日期时间 - * @return 一年的开始时间 - */ - public static LocalDateTime beginOfYear(final LocalDateTime time) { - return beginOfDay(time).with(TemporalAdjusters.firstDayOfYear()); - } - - /** - * 修改为一年的结束时间 - * - * @param time 日期时间 - * @param truncateMillisecond 是否毫秒归零 - * @return 一年的结束时间 - */ - public static LocalDateTime endOfYear(final LocalDateTime time, final boolean truncateMillisecond) { - return endOfDay(time, truncateMillisecond).with(TemporalAdjusters.lastDayOfYear()); - } - - /** - * 是否为周末(周六或周日) - * - * @param localDateTime 判定的日期{@link LocalDateTime} - * @return 是否为周末(周六或周日) - */ - public static boolean isWeekend(final LocalDateTime localDateTime) { - return isWeekend(localDateTime.toLocalDate()); - } - - /** - * 是否为周末(周六或周日) - * - * @param localDate 判定的日期{@link LocalDate} - * @return 是否为周末(周六或周日) - */ - public static boolean isWeekend(final LocalDate localDate) { - final DayOfWeek dayOfWeek = localDate.getDayOfWeek(); - return DayOfWeek.SATURDAY == dayOfWeek || DayOfWeek.SUNDAY == dayOfWeek; - } - - /** - * 获取{@link LocalDate}对应的星期值 - * - * @param localDate 日期{@link LocalDate} - * @return {@link Fields.Week} - */ - public static Fields.Week dayOfWeek(final LocalDate localDate) { - return Fields.Week.of(localDate.getDayOfWeek()); - } - - /** - * 检查两个时间段是否有时间重叠 - * 重叠指两个时间段是否有交集,注意此方法时间段重合时如: - * - * See 准确的区间关系参考:艾伦区间代数 - * - * @param realStartTime 第一个时间段的开始时间 - * @param realEndTime 第一个时间段的结束时间 - * @param startTime 第二个时间段的开始时间 - * @param endTime 第二个时间段的结束时间 - * @return true 表示时间有重合 - */ - public static boolean isOverlap(final ChronoLocalDateTime realStartTime, final ChronoLocalDateTime realEndTime, - final ChronoLocalDateTime startTime, final ChronoLocalDateTime endTime) { - // x>b||a>y 无交集 - // 则有交集的逻辑为 !(x>b||a>y) - // 根据德摩根公式,可化简为 x<=b && a<=y 即 realStartTime<=endTime && startTime<=realEndTime - return realStartTime.compareTo(endTime) <= 0 && startTime.compareTo(realEndTime) <= 0; - } - - /** - * 获得指定日期是所在年份的第几周,如: - * - * - * @param date 日期({@link LocalDate} 或者 {@link LocalDateTime}等) - * @return 所在年的第几周 - */ - public static int weekOfYear(final TemporalAccessor date) { - return get(date, WeekFields.ISO.weekOfYear()); - } - - /** - * 比较两个日期是否为同一天 - * - * @param date1 日期1 - * @param date2 日期2 - * @return 是否为同一天 - */ - public static boolean isSameDay(final ChronoLocalDateTime date1, final ChronoLocalDateTime date2) { - return date1 != null && date2 != null && date1.toLocalDate().isEqual(date2.toLocalDate()); - } - - /** - * 比较两个日期是否为同一天 - * - * @param date1 日期1 - * @param date2 日期2 - * @return 是否为同一天 - */ - public static boolean isSameDay(final ChronoLocalDate date1, final ChronoLocalDate date2) { - return date1 != null && date2 != null && date1.isEqual(date2); - } - - /** - * 日期偏移,根据field不同加不同值(偏移会修改传入的对象) - * - * @param 日期类型,如LocalDate或LocalDateTime - * @param time {@link Temporal} - * @param number 偏移量,正数为向后偏移,负数为向前偏移 - * @param field 偏移单位,见{@link ChronoUnit},不能为null - * @return 偏移后的日期时间 - */ - public static T offset(final T time, final long number, final TemporalUnit field) { - if (null == time) { - return null; - } - - return (T) time.plus(number, field); - } - - /** - * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负。 - *

- * 返回结果为{@link Duration}对象,通过调用toXXX方法返回相差单位 - * - * @param startTimeInclude 开始时间(包含) - * @param endTimeExclude 结束时间(不包含) - * @return 时间差 {@link Duration}对象 - */ - public static Duration between(final Temporal startTimeInclude, final Temporal endTimeExclude) { - return Duration.between(startTimeInclude, endTimeExclude); - } - - /** - * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负。 - * 返回结果为时间差的long值 - * - * @param startTimeInclude 开始时间(包括) - * @param endTimeExclude 结束时间(不包括) - * @param unit 时间差单位 - * @return 时间差 - */ - public static long between(final Temporal startTimeInclude, final Temporal endTimeExclude, final ChronoUnit unit) { - return unit.between(startTimeInclude, endTimeExclude); - } +public interface Almanac { /** - * 偏移到指定的周几 + * 名称 * - * @param temporal 日期或者日期时间 - * @param dayOfWeek 周几 - * @param 日期类型,如LocalDate或LocalDateTime - * @param isPrevious 是否向前偏移,{@code true}向前偏移,{@code false}向后偏移。 - * @return 偏移后的日期 + * @return 名称 */ - public T offset(final T temporal, final DayOfWeek dayOfWeek, final boolean isPrevious) { - return (T) temporal.with(isPrevious ? TemporalAdjusters.previous(dayOfWeek) : TemporalAdjusters.next(dayOfWeek)); - } + String getName(); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Between.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Between.java index 467f255826..82df6cca01 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Between.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Between.java @@ -25,13 +25,18 @@ ********************************************************************************/ package org.miaixz.bus.core.center.date; +import org.miaixz.bus.core.center.date.culture.en.Units; import org.miaixz.bus.core.center.date.format.FormatPeriod; import org.miaixz.bus.core.lang.Assert; -import org.miaixz.bus.core.lang.Fields; import org.miaixz.bus.core.xyz.DateKit; import java.io.Serializable; -import java.util.Calendar; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Period; +import java.time.temporal.ChronoUnit; +import java.time.temporal.Temporal; import java.util.Date; /** @@ -111,14 +116,77 @@ public static Between of(final Date begin, final Date end, final boolean isAbs) return new Between(begin, end, isAbs); } + /** + * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负。 + * 返回结果为{@link Duration}对象,通过调用toXXX方法返回相差单位 + * + * @param startTimeInclude 开始时间(包含) + * @param endTimeExclude 结束时间(不包含) + * @return 时间差 {@link Duration}对象 + */ + public static Duration between(final Temporal startTimeInclude, final Temporal endTimeExclude) { + return Duration.between(startTimeInclude, endTimeExclude); + } + + /** + * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负 + * 返回结果为{@link Duration}对象,通过调用toXXX方法返回相差单位 + * + * @param startTimeInclude 开始时间(包含) + * @param endTimeExclude 结束时间(不包含) + * @return 时间差 {@link Duration}对象 + * @see Between#between(Temporal, Temporal) + */ + public static Duration between(final LocalDateTime startTimeInclude, final LocalDateTime endTimeExclude) { + return between(startTimeInclude, endTimeExclude); + } + + /** + * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负。 + * 返回结果为时间差的long值 + * + * @param startTimeInclude 开始时间(包括) + * @param endTimeExclude 结束时间(不包括) + * @param unit 时间差单位 + * @return 时间差 + */ + public static long between(final Temporal startTimeInclude, final Temporal endTimeExclude, final ChronoUnit unit) { + return unit.between(startTimeInclude, endTimeExclude); + } + + /** + * 获取两个日期的差,如果结束时间早于开始时间,获取结果为负 + * 返回结果为时间差的long值 + * + * @param startTimeInclude 开始时间(包括) + * @param endTimeExclude 结束时间(不包括) + * @param unit 时间差单位 + * @return 时间差 + */ + public static long between(final LocalDateTime startTimeInclude, final LocalDateTime endTimeExclude, final ChronoUnit unit) { + return between(startTimeInclude, endTimeExclude, unit); + } + + /** + * 获取两个日期的表象时间差,如果结束时间早于开始时间,获取结果为负。 + * 比如2011年2月1日,和2021年8月11日,日相差了10天,月相差6月 + * + * @param startTimeInclude 开始时间(包括) + * @param endTimeExclude 结束时间(不包括) + * @return 时间差 + */ + public static Period between(final LocalDate startTimeInclude, final LocalDate endTimeExclude) { + return Period.between(startTimeInclude, endTimeExclude); + } + /** * 判断两个日期相差的时长 * 返回 给定单位的时长差 * - * @param unit 相差的单位:相差 天{@link Fields.Units#DAY}、小时{@link Fields.Units#HOUR} 等 + * @param unit 相差的单位:相差 天{@link Units#DAY}、小时{@link Units#HOUR} 等 * @return 时长差 */ - public long between(final Fields.Units unit) { + public long between(final Units unit) { final long diff = end.getTime() - begin.getTime(); return diff / unit.getMillis(); } @@ -131,16 +199,16 @@ public long between(final Fields.Units unit) { * @return 相差月数 */ public long betweenMonth(final boolean isReset) { - final Calendar beginCal = DateKit.calendar(begin); - final Calendar endCal = DateKit.calendar(end); + final java.util.Calendar beginCal = DateKit.calendar(begin); + final java.util.Calendar endCal = DateKit.calendar(end); - final int betweenYear = endCal.get(Calendar.YEAR) - beginCal.get(Calendar.YEAR); - final int betweenMonthOfYear = endCal.get(Calendar.MONTH) - beginCal.get(Calendar.MONTH); + final int betweenYear = endCal.get(java.util.Calendar.YEAR) - beginCal.get(java.util.Calendar.YEAR); + final int betweenMonthOfYear = endCal.get(java.util.Calendar.MONTH) - beginCal.get(java.util.Calendar.MONTH); final int result = betweenYear * 12 + betweenMonthOfYear; if (!isReset) { - endCal.set(Calendar.YEAR, beginCal.get(Calendar.YEAR)); - endCal.set(Calendar.MONTH, beginCal.get(Calendar.MONTH)); + endCal.set(java.util.Calendar.YEAR, beginCal.get(java.util.Calendar.YEAR)); + endCal.set(java.util.Calendar.MONTH, beginCal.get(java.util.Calendar.MONTH)); final long between = endCal.getTimeInMillis() - beginCal.getTimeInMillis(); if (between < 0) { return result - 1; @@ -157,27 +225,27 @@ public long betweenMonth(final boolean isReset) { * @return 相差年数 */ public long betweenYear(final boolean isReset) { - final Calendar beginCal = DateKit.calendar(begin); - final Calendar endCal = DateKit.calendar(end); + final java.util.Calendar beginCal = DateKit.calendar(begin); + final java.util.Calendar endCal = DateKit.calendar(end); - final int result = endCal.get(Calendar.YEAR) - beginCal.get(Calendar.YEAR); + final int result = endCal.get(java.util.Calendar.YEAR) - beginCal.get(java.util.Calendar.YEAR); if (false == isReset) { - final int beginMonthBase0 = beginCal.get(Calendar.MONTH); - final int endMonthBase0 = endCal.get(Calendar.MONTH); + final int beginMonthBase0 = beginCal.get(java.util.Calendar.MONTH); + final int endMonthBase0 = endCal.get(java.util.Calendar.MONTH); if (beginMonthBase0 < endMonthBase0) { return result; } else if (beginMonthBase0 > endMonthBase0) { return result - 1; - } else if (Calendar.FEBRUARY == beginMonthBase0 - && Calendars.isLastDayOfMonth(beginCal) - && Calendars.isLastDayOfMonth(endCal)) { + } else if (java.util.Calendar.FEBRUARY == beginMonthBase0 + && Calendar.isLastDayOfMonth(beginCal) + && Calendar.isLastDayOfMonth(endCal)) { // 考虑闰年的2月情况 // 两个日期都位于2月的最后一天,此时月数按照相等对待,此时都设置为1号 - beginCal.set(Calendar.DAY_OF_MONTH, 1); - endCal.set(Calendar.DAY_OF_MONTH, 1); + beginCal.set(java.util.Calendar.DAY_OF_MONTH, 1); + endCal.set(java.util.Calendar.DAY_OF_MONTH, 1); } - endCal.set(Calendar.YEAR, beginCal.get(Calendar.YEAR)); + endCal.set(java.util.Calendar.YEAR, beginCal.get(java.util.Calendar.YEAR)); final long between = endCal.getTimeInMillis() - beginCal.getTimeInMillis(); if (between < 0) { return result - 1; @@ -211,7 +279,7 @@ public Date getEnd() { * @param level 级别 * @return 字符串 */ - public String toString(final Fields.Units unit, final FormatPeriod.Level level) { + public String toString(final Units unit, final FormatPeriod.Level level) { return DateKit.formatBetween(between(unit), level); } @@ -222,7 +290,7 @@ public String toString(final Fields.Units unit, final FormatPeriod.Level level) * @return 字符串 */ public String toString(final FormatPeriod.Level level) { - return toString(Fields.Units.MS, level); + return toString(Units.MS, level); } @Override diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Boundary.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Boundary.java index 7cae17d9c9..d992695a04 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Boundary.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Boundary.java @@ -25,7 +25,7 @@ ********************************************************************************/ package org.miaixz.bus.core.center.date; -import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.center.date.culture.en.Various; import org.miaixz.bus.core.lang.range.Range; import org.miaixz.bus.core.xyz.DateKit; @@ -48,7 +48,7 @@ public class Boundary extends Range { * @param end 结束日期时间(包括) * @param unit 步进单位 */ - public Boundary(final Date start, final Date end, final Fields.Type unit) { + public Boundary(final Date start, final Date end, final Various unit) { this(start, end, unit, 1); } @@ -60,7 +60,7 @@ public Boundary(final Date start, final Date end, final Fields.Type unit) { * @param unit 步进单位 * @param step 步进数 */ - public Boundary(final Date start, final Date end, final Fields.Type unit, final int step) { + public Boundary(final Date start, final Date end, final Various unit, final int step) { this(start, end, unit, step, true, true); } @@ -74,7 +74,7 @@ public Boundary(final Date start, final Date end, final Fields.Type unit, final * @param isIncludeStart 是否包含开始的时间 * @param isIncludeEnd 是否包含结束的时间 */ - public Boundary(final Date start, final Date end, final Fields.Type unit, final int step, final boolean isIncludeStart, final boolean isIncludeEnd) { + public Boundary(final Date start, final Date end, final Various unit, final int step, final boolean isIncludeStart, final boolean isIncludeEnd) { super(DateKit.date(start), DateKit.date(end), (current, end1, index) -> { final DateTime dt = DateKit.date(start).offsetNew(unit, (index + 1) * step); if (dt.isAfter(end1)) { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Calculate.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Calculate.java new file mode 100644 index 0000000000..d90b02b285 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Calculate.java @@ -0,0 +1,386 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date; + +import org.miaixz.bus.core.center.date.culture.en.Week; + +import java.time.*; +import java.time.chrono.ChronoLocalDate; +import java.time.chrono.ChronoLocalDateTime; +import java.time.temporal.*; + +/** + * 日期计算类 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Calculate extends Resolver { + + /** + * 当前日期是否在日期指定范围内 + * 起始日期和结束日期可以互换 + * + * @param date 被检查的日期 + * @param beginDate 起始日期(包含) + * @param endDate 结束日期(包含) + * @return 是否在范围内 + */ + public static boolean isIn(final TemporalAccessor date, final TemporalAccessor beginDate, final TemporalAccessor endDate) { + return isIn(date, beginDate, endDate, true, true); + } + + /** + * 当前日期是否在日期指定范围内 + * 起始日期和结束日期可以互换 + * 通过includeBegin, includeEnd参数控制日期范围区间是否为开区间,例如:传入参数:includeBegin=true, includeEnd=false, + * 则本方法会判断 date ∈ (beginDate, endDate] 是否成立 + * + * @param date 被检查的日期 + * @param beginDate 起始日期 + * @param endDate 结束日期 + * @param includeBegin 时间范围是否包含起始日期 + * @param includeEnd 时间范围是否包含结束日期 + * @return 是否在范围内 + */ + public static boolean isIn(final TemporalAccessor date, final TemporalAccessor beginDate, final TemporalAccessor endDate, + final boolean includeBegin, final boolean includeEnd) { + if (date == null || beginDate == null || endDate == null) { + throw new IllegalArgumentException("参数不可为null"); + } + + final long thisMills = toEpochMilli(date); + final long beginMills = toEpochMilli(beginDate); + final long endMills = toEpochMilli(endDate); + final long rangeMin = Math.min(beginMills, endMills); + final long rangeMax = Math.max(beginMills, endMills); + + // 先判断是否满足 date ∈ (beginDate, endDate) + boolean isIn = rangeMin < thisMills && thisMills < rangeMax; + + // 若不满足,则再判断是否在时间范围的边界上 + if (!isIn && includeBegin) { + isIn = thisMills == rangeMin; + } + + if (!isIn && includeEnd) { + isIn = thisMills == rangeMax; + } + + return isIn; + } + + /** + * 检查两个时间段是否有时间重叠 + * 重叠指两个时间段是否有交集,注意此方法时间段重合时如: + *

+ * See 准确的区间关系参考:艾伦区间代数 + * + * @param realStartTime 第一个时间段的开始时间 + * @param realEndTime 第一个时间段的结束时间 + * @param startTime 第二个时间段的开始时间 + * @param endTime 第二个时间段的结束时间 + * @return true 表示时间有重合 + */ + public static boolean isOverlap(final ChronoLocalDateTime realStartTime, final ChronoLocalDateTime realEndTime, + final ChronoLocalDateTime startTime, final ChronoLocalDateTime endTime) { + // x>b||a>y 无交集 + // 则有交集的逻辑为 !(x>b||a>y) + // 根据德摩根公式,可化简为 x<=b && a<=y 即 realStartTime<=endTime && startTime<=realEndTime + return realStartTime.compareTo(endTime) <= 0 && startTime.compareTo(realEndTime) <= 0; + } + + /** + * 比较两个日期是否为同一天 + * + * @param date1 日期1 + * @param date2 日期2 + * @return 是否为同一天 + */ + public static boolean isSameDay(final ChronoLocalDateTime date1, final ChronoLocalDateTime date2) { + return date1 != null && date2 != null && date1.toLocalDate().isEqual(date2.toLocalDate()); + } + + /** + * 比较两个日期是否为同一天 + * + * @param date1 日期1 + * @param date2 日期2 + * @return 是否为同一天 + */ + public static boolean isSameDay(final ChronoLocalDate date1, final ChronoLocalDate date2) { + return date1 != null && date2 != null && date1.isEqual(date2); + } + + /** + * 是否为周末(周六或周日) + * + * @param localDateTime 判定的日期{@link LocalDateTime} + * @return 是否为周末(周六或周日) + */ + public static boolean isWeekend(final LocalDateTime localDateTime) { + return isWeekend(localDateTime.toLocalDate()); + } + + /** + * 是否为周末(周六或周日) + * + * @param localDate 判定的日期{@link LocalDate} + * @return 是否为周末(周六或周日) + */ + public static boolean isWeekend(final LocalDate localDate) { + final DayOfWeek dayOfWeek = localDate.getDayOfWeek(); + return DayOfWeek.SATURDAY == dayOfWeek || DayOfWeek.SUNDAY == dayOfWeek; + } + + /** + * 是否闰年 + * + * @return 是否闰年 + */ + public static boolean isLeapYear(final int year) { + return Year.isLeap(year); + } + + /** + * 日期偏移,根据field不同加不同值(偏移会修改传入的对象) + * + * @param time {@link LocalDateTime} + * @param number 偏移量,正数为向后偏移,负数为向前偏移 + * @param field 偏移单位,见{@link ChronoUnit},不能为null + * @return 偏移后的日期时间 + */ + public static LocalDateTime offset(final LocalDateTime time, final long number, final TemporalUnit field) { + return offset(time, number, field); + } + + /** + * 日期偏移,根据field不同加不同值(偏移会修改传入的对象) + * + * @param 日期类型,如LocalDate或LocalDateTime + * @param time {@link Temporal} + * @param number 偏移量,正数为向后偏移,负数为向前偏移 + * @param field 偏移单位,见{@link ChronoUnit},不能为null + * @return 偏移后的日期时间 + */ + public static T offset(final T time, final long number, final TemporalUnit field) { + if (null == time) { + return null; + } + + return (T) time.plus(number, field); + } + + /** + * 修改为一天的开始时间,例如:2020-02-02 00:00:00,000 + * + * @param time 日期时间 + * @return 一天的开始时间 + */ + public static LocalDateTime beginOfDay(final LocalDateTime time) { + return time.with(LocalTime.MIN); + } + + /** + * 修改为一天的开始时间,例如:2020-02-02 00:00:00,000 + * + * @param date 日期 + * @return 一天的开始时间 + */ + public static LocalDateTime beginOfDay(final LocalDate date) { + return date.atStartOfDay(); + } + + /** + * 修改为一天的结束时间 + *
    + *
  • 毫秒不归零:2020-02-02 23:59:59,999
  • + *
  • 毫秒归零:2020-02-02 23:59:59,000
  • + *
+ * + * @param time 日期时间 + * @param truncateMillisecond 是否毫秒归零 + * @return 一天的结束时间 + */ + public static LocalDateTime endOfDay(final LocalDateTime time, final boolean truncateMillisecond) { + return time.with(max(truncateMillisecond)); + } + + /** + * 修改为一天的结束时间 + *
    + *
  • 毫秒不归零:2024-05-01 23:59:59,999
  • + *
  • 毫秒归零:2024-05-01 23:59:59,000
  • + *
+ * + * @param date 日期 + * @param truncateMillisecond 是否毫秒归零 + * @return 一天的结束时间 + */ + public static LocalDateTime endOfDay(final LocalDate date, final boolean truncateMillisecond) { + return LocalDateTime.of(date, max(truncateMillisecond)); + } + + /** + * 修改为月初的开始时间,例如:2024-05-01 00:00:00,000 + * + * @param time 日期时间 + * @return 月初的开始时间 + */ + public static LocalDateTime beginOfMonth(final LocalDateTime time) { + return beginOfDay(beginOfMonth(time.toLocalDate())); + } + + /** + * 修改为月初的开始时间,例如:2024-05-01 00:00:00,000 + * + * @param date 日期 + * @return 月初的开始时间 + */ + public static LocalDate beginOfMonth(final LocalDate date) { + return date.with(TemporalAdjusters.firstDayOfMonth()); + } + + /** + * 修改为月底的结束时间 + * + * @param time 日期时间 + * @param truncateMillisecond 是否毫秒归零 + * @return 月底的结束时间 + */ + public static LocalDateTime endOfMonth(final LocalDateTime time, final boolean truncateMillisecond) { + return endOfDay(endOfMonth(time.toLocalDate()), truncateMillisecond); + } + + /** + * 修改为月底的结束时间 + * + * @param date 日期 + * @return 月底的结束时间 + */ + public static LocalDate endOfMonth(final LocalDate date) { + return date.with(TemporalAdjusters.lastDayOfMonth()); + } + + /** + * 修改为一年的开始时间,例如:2024-05-01 00:00:00,000 + * + * @param time 日期时间 + * @return 一年的开始时间 + */ + public static LocalDateTime beginOfYear(final LocalDateTime time) { + return beginOfDay(beginOfYear(time.toLocalDate())); + } + + /** + * 修改为一年的开始时间,例如:2024-05-01 00:00:00,000 + * + * @param date 日期 + * @return 一年的开始时间 + */ + public static LocalDate beginOfYear(final LocalDate date) { + return date.with(TemporalAdjusters.firstDayOfYear()); + } + + /** + * 修改为一年的结束时间 + * + * @param time 日期时间 + * @param truncateMillisecond 是否毫秒归零 + * @return 一年的结束时间 + */ + public static LocalDateTime endOfYear(final LocalDateTime time, final boolean truncateMillisecond) { + return endOfDay(endOfYear(time.toLocalDate()), truncateMillisecond); + } + + /** + * 修改为一年的结束时间 + * + * @param date 日期 + * @return 一年的结束时间 + */ + public static LocalDate endOfYear(final LocalDate date) { + return date.with(TemporalAdjusters.lastDayOfYear()); + } + + /** + * 获取{@link LocalDate}对应的星期值 + * + * @param localDate 日期{@link LocalDate} + * @return {@link Week} + */ + public static Week dayOfWeek(final LocalDate localDate) { + return Week.of(localDate.getDayOfWeek()); + } + + /** + * 获得指定日期是所在年份的第几周,如: + *
    + *
  • 如果一年的第一天是星期一,则第一周从第一天开始,没有零周
  • + *
  • 如果一年的第二天是星期一,则第一周从第二天开始,而第一天在零周
  • + *
  • 如果一年的第4天是星期一,则第一周从第4天开始,第1至第3天在零周
  • + *
  • 如果一年的第5天是星期一,则第二周从第5天开始,第1至第4天在第一周
  • + *
+ * + * @param date 日期({@link LocalDate} 或者 {@link LocalDateTime}等) + * @return 所在年的第几周 + */ + public static int weekOfYear(final TemporalAccessor date) { + return get(date, WeekFields.ISO.weekOfYear()); + } + + /** + * 获取最大时间,提供参数是否将毫秒归零 + *
    + *
  • 如果{@code truncateMillisecond}为{@code false},返回时间最大值,为:23:59:59,999
  • + *
  • 如果{@code truncateMillisecond}为{@code true},返回时间最大值,为:23:59:59,000
  • + *
+ * + * @param truncateMillisecond 是否毫秒归零 + * @return {@link LocalTime}时间最大值 + */ + public static LocalTime max(final boolean truncateMillisecond) { + return truncateMillisecond ? MAX_HMS : LocalTime.MAX; + } + + /** + * 偏移到指定的周几 + * + * @param temporal 日期或者日期时间 + * @param dayOfWeek 周几 + * @param 日期类型,如LocalDate或LocalDateTime + * @param isPrevious 是否向前偏移,{@code true}向前偏移,{@code false}向后偏移。 + * @return 偏移后的日期 + */ + public T offset(final T temporal, final DayOfWeek dayOfWeek, final boolean isPrevious) { + return (T) temporal.with(isPrevious ? TemporalAdjusters.previous(dayOfWeek) : TemporalAdjusters.next(dayOfWeek)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Calendars.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Calendar.java similarity index 57% rename from bus-core/src/main/java/org/miaixz/bus/core/center/date/Calendars.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/Calendar.java index edbd710dbd..5b514999f4 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Calendars.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Calendar.java @@ -25,43 +25,195 @@ ********************************************************************************/ package org.miaixz.bus.core.center.date; +import org.miaixz.bus.core.center.date.culture.en.Modify; +import org.miaixz.bus.core.center.date.culture.en.Month; +import org.miaixz.bus.core.center.date.culture.en.Various; import org.miaixz.bus.core.center.date.format.CustomFormat; import org.miaixz.bus.core.center.date.format.parser.DateParser; import org.miaixz.bus.core.center.date.format.parser.FastDateParser; import org.miaixz.bus.core.center.date.format.parser.PositionDateParser; import org.miaixz.bus.core.lang.Assert; -import org.miaixz.bus.core.lang.Fields; import org.miaixz.bus.core.lang.exception.DateException; import org.miaixz.bus.core.math.ChineseNumberFormatter; import org.miaixz.bus.core.xyz.CompareKit; -import org.miaixz.bus.core.xyz.DateKit; import org.miaixz.bus.core.xyz.ObjectKit; import org.miaixz.bus.core.xyz.StringKit; import javax.xml.datatype.XMLGregorianCalendar; import java.text.ParsePosition; -import java.time.Instant; -import java.time.LocalDateTime; -import java.util.Calendar; +import java.time.*; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** - * 针对{@link Calendar} 对象封装工具类 + * 针对{@link java.util.Calendar} 对象封装工具类 * * @author Kimi Liu * @since Java 17+ */ -public class Calendars extends Almanac { +public class Calendar extends Calculate { + + /** + * 是否为上午 + * + * @param calendar {@link java.util.Calendar} + * @return 是否为上午 + */ + public static boolean isAM(final java.util.Calendar calendar) { + return java.util.Calendar.AM == calendar.get(java.util.Calendar.AM_PM); + } + + /** + * 是否为下午 + * + * @param calendar {@link java.util.Calendar} + * @return 是否为下午 + */ + public static boolean isPM(final java.util.Calendar calendar) { + return java.util.Calendar.PM == calendar.get(java.util.Calendar.AM_PM); + } + + /** + * 比较两个日期是否为同一天 + * + * @param cal1 日期1 + * @param cal2 日期2 + * @return 是否为同一天 + */ + public static boolean isSameDay(final java.util.Calendar cal1, java.util.Calendar cal2) { + if (ObjectKit.notEquals(cal1.getTimeZone(), cal2.getTimeZone())) { + // 统一时区 + cal2 = calendar(cal2, cal1.getTimeZone()); + } + return isSameYear(cal1, cal2) && cal1.get(java.util.Calendar.DAY_OF_YEAR) == cal2.get(java.util.Calendar.DAY_OF_YEAR); + } + + /** + * 比较两个日期是否为同一周 + * 同一个周的意思是:ERA(公元)、year(年)、month(月)、week(周)都一致。 + * + * @param cal1 日期1 + * @param cal2 日期2 + * @param isMon 一周的第一天是否为周一。国内第一天为星期一,国外第一天为星期日 + * @return 是否为同一周 + */ + public static boolean isSameWeek(java.util.Calendar cal1, java.util.Calendar cal2, final boolean isMon) { + if (cal1 == null || cal2 == null) { + throw new IllegalArgumentException("The date must not be null"); + } + + // 防止比较前修改原始Calendar对象 + cal1 = (java.util.Calendar) cal1.clone(); + + if (ObjectKit.notEquals(cal1.getTimeZone(), cal2.getTimeZone())) { + // 统一时区 + cal2 = calendar(cal2, cal1.getTimeZone()); + } else { + cal2 = (java.util.Calendar) cal2.clone(); + } + + // 把所传日期设置为其当前周的第一天 + // 比较设置后的两个日期是否是同一天:true 代表同一周 + if (isMon) { + cal1.setFirstDayOfWeek(java.util.Calendar.MONDAY); + cal1.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.MONDAY); + cal2.setFirstDayOfWeek(java.util.Calendar.MONDAY); + cal2.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.MONDAY); + } else { + cal1.setFirstDayOfWeek(java.util.Calendar.SUNDAY); + cal1.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.SUNDAY); + cal2.setFirstDayOfWeek(java.util.Calendar.SUNDAY); + cal2.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.SUNDAY); + } + return isSameDay(cal1, cal2); + } + + /** + * 比较两个日期是否为同一月 + * 同一个月的意思是:ERA(公元)、year(年)、month(月)都一致。 + * + * @param cal1 日期1 + * @param cal2 日期2 + * @return 是否为同一月 + */ + public static boolean isSameMonth(final java.util.Calendar cal1, java.util.Calendar cal2) { + if (ObjectKit.notEquals(cal1.getTimeZone(), cal2.getTimeZone())) { + // 统一时区 + cal2 = calendar(cal2, cal1.getTimeZone()); + } + + return isSameYear(cal1, cal2) && cal1.get(java.util.Calendar.MONTH) == cal2.get(java.util.Calendar.MONTH); + } + + /** + * 比较两个日期是否为同一年 + * 同一个年的意思是:ERA(公元)、year(年)都一致。 + * + * @param cal1 日期1 + * @param cal2 日期2 + * @return 是否为同一年 + */ + public static boolean isSameYear(final java.util.Calendar cal1, java.util.Calendar cal2) { + if (cal1 == null || cal2 == null) { + throw new IllegalArgumentException("The date must not be null"); + } + + if (ObjectKit.notEquals(cal1.getTimeZone(), cal2.getTimeZone())) { + // 统一时区 + cal2 = calendar(cal2, cal1.getTimeZone()); + } + + return cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR) && + cal1.get(java.util.Calendar.ERA) == cal2.get(java.util.Calendar.ERA); + } + + /** + * 检查两个Calendar时间戳是否相同 + * 此方法检查两个Calendar的毫秒数时间戳是否相同 + * + * @param date1 时间1 + * @param date2 时间2 + * @return 两个Calendar时间戳是否相同。如果两个时间都为{@code null}返回true,否则有{@code null}返回false + */ + public static boolean isSameInstant(final java.util.Calendar date1, final java.util.Calendar date2) { + if (null == date1) { + return null == date2; + } + if (null == date2) { + return false; + } + + return date1.getTimeInMillis() == date2.getTimeInMillis(); + } + + /** + * 是否为本月第一天 + * + * @param calendar {@link java.util.Calendar} + * @return 是否为本月最后一天 + */ + public static boolean isFirstDayOfMonth(final java.util.Calendar calendar) { + return 1 == calendar.get(java.util.Calendar.DAY_OF_MONTH); + } + + /** + * 是否为本月最后一天 + * + * @param calendar {@link java.util.Calendar} + * @return 是否为本月最后一天 + */ + public static boolean isLastDayOfMonth(final java.util.Calendar calendar) { + return calendar.get(java.util.Calendar.DAY_OF_MONTH) == calendar.getActualMaximum(java.util.Calendar.DAY_OF_MONTH); + } /** * 创建Calendar对象,时间为默认时区的当前时间 * * @return Calendar对象 */ - public static Calendar calendar() { - return Calendar.getInstance(); + public static java.util.Calendar calendar() { + return java.util.Calendar.getInstance(); } /** @@ -70,7 +222,7 @@ public static Calendar calendar() { * @param date 日期对象 * @return Calendar对象 */ - public static Calendar calendar(final Date date) { + public static java.util.Calendar calendar(final Date date) { if (date instanceof DateTime) { return ((DateTime) date).toCalendar(); } else { @@ -84,7 +236,7 @@ public static Calendar calendar(final Date date) { * @param calendar 日期对象 * @return Calendar对象 */ - public static Calendar calendar(final XMLGregorianCalendar calendar) { + public static java.util.Calendar calendar(final XMLGregorianCalendar calendar) { return calendar.toGregorianCalendar(); } @@ -94,7 +246,7 @@ public static Calendar calendar(final XMLGregorianCalendar calendar) { * @param millis 时间戳 * @return Calendar对象 */ - public static Calendar calendar(final long millis) { + public static java.util.Calendar calendar(final long millis) { return calendar(millis, TimeZone.getDefault()); } @@ -105,8 +257,8 @@ public static Calendar calendar(final long millis) { * @param timeZone 时区 * @return Calendar对象 */ - public static Calendar calendar(final long millis, final TimeZone timeZone) { - final Calendar cal = Calendar.getInstance(timeZone); + public static java.util.Calendar calendar(final long millis, final TimeZone timeZone) { + final java.util.Calendar cal = java.util.Calendar.getInstance(timeZone); cal.setTimeInMillis(millis); return cal; } @@ -118,64 +270,44 @@ public static Calendar calendar(final long millis, final TimeZone timeZone) { * @param timeZone 新时区 * @return 指定时区的新的calendar对象 */ - public static Calendar calendar(Calendar calendar, final TimeZone timeZone) { + public static java.util.Calendar calendar(java.util.Calendar calendar, final TimeZone timeZone) { // 转换到统一时区,例如UTC - calendar = (Calendar) calendar.clone(); + calendar = (java.util.Calendar) calendar.clone(); calendar.setTimeZone(timeZone); return calendar; } - /** - * 是否为上午 - * - * @param calendar {@link Calendar} - * @return 是否为上午 - */ - public static boolean isAM(final Calendar calendar) { - return Calendar.AM == calendar.get(Calendar.AM_PM); - } - - /** - * 是否为下午 - * - * @param calendar {@link Calendar} - * @return 是否为下午 - */ - public static boolean isPM(final Calendar calendar) { - return Calendar.PM == calendar.get(Calendar.AM_PM); - } - /** * 修改日期为某个时间字段起始时间 * - * @param calendar {@link Calendar} - * @param type 保留到的时间字段,如定义为 {@link Fields.Type#SECOND},表示这个字段不变,这个字段以下字段全部归0 + * @param calendar {@link java.util.Calendar} + * @param various 保留到的时间字段,如定义为 {@link Various#SECOND},表示这个字段不变,这个字段以下字段全部归0 * @return 原{@link Calendar} */ - public static Calendar truncate(final Calendar calendar, final Fields.Type type) { - return Modifier.modify(calendar, type.getValue(), Fields.Modify.TRUNCATE); + public static java.util.Calendar truncate(final java.util.Calendar calendar, final Various various) { + return Modifier.modify(calendar, various.getValue(), Modify.TRUNCATE); } /** * 修改日期为某个时间字段四舍五入时间 * - * @param calendar {@link Calendar} - * @param type 时间字段,即保留到哪个日期字段 + * @param calendar {@link java.util.Calendar} + * @param various 时间字段,即保留到哪个日期字段 * @return 原{@link Calendar} */ - public static Calendar round(final Calendar calendar, final Fields.Type type) { - return Modifier.modify(calendar, type.getValue(), Fields.Modify.ROUND); + public static java.util.Calendar round(final java.util.Calendar calendar, final Various various) { + return Modifier.modify(calendar, various.getValue(), Modify.ROUND); } /** * 修改日期为某个时间字段结束时间 * - * @param calendar {@link Calendar} - * @param type 保留到的时间字段,如定义为 {@link Fields.Type#SECOND},表示这个字段不变,这个字段以下字段全部取最大值 + * @param calendar {@link java.util.Calendar} + * @param various 保留到的时间字段,如定义为 {@link Various#SECOND},表示这个字段不变,这个字段以下字段全部取最大值 * @return 原{@link Calendar} */ - public static Calendar ceiling(final Calendar calendar, final Fields.Type type) { - return Modifier.modify(calendar, type.getValue(), Fields.Modify.CEILING); + public static java.util.Calendar ceiling(final java.util.Calendar calendar, final Various various) { + return Modifier.modify(calendar, various.getValue(), Modify.CEILING); } /** @@ -186,185 +318,185 @@ public static Calendar ceiling(final Calendar calendar, final Fields.Type type) * 有时候由于毫秒部分必须为0(如MySQL数据库中),因此在此加上选项。 *

* - * @param calendar {@link Calendar} - * @param type 时间字段 + * @param calendar {@link java.util.Calendar} + * @param various 时间字段 * @param truncateMillisecond 是否毫秒归零 * @return 原{@link Calendar} */ - public static Calendar ceiling(final Calendar calendar, final Fields.Type type, final boolean truncateMillisecond) { - return Modifier.modify(calendar, type.getValue(), Fields.Modify.CEILING, truncateMillisecond); + public static java.util.Calendar ceiling(final java.util.Calendar calendar, final Various various, final boolean truncateMillisecond) { + return Modifier.modify(calendar, various.getValue(), Modify.CEILING, truncateMillisecond); } /** * 修改秒级别的开始时间,即忽略毫秒部分 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar beginOfSecond(final Calendar calendar) { - return truncate(calendar, Fields.Type.SECOND); + public static java.util.Calendar beginOfSecond(final java.util.Calendar calendar) { + return truncate(calendar, Various.SECOND); } /** * 修改秒级别的结束时间,即毫秒设置为999 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar endOfSecond(final Calendar calendar) { - return ceiling(calendar, Fields.Type.SECOND); + public static java.util.Calendar endOfSecond(final java.util.Calendar calendar) { + return ceiling(calendar, Various.SECOND); } /** * 修改某小时的开始时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar beginOfHour(final Calendar calendar) { - return truncate(calendar, Fields.Type.HOUR_OF_DAY); + public static java.util.Calendar beginOfHour(final java.util.Calendar calendar) { + return truncate(calendar, Various.HOUR_OF_DAY); } /** * 修改某小时的结束时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar endOfHour(final Calendar calendar) { - return ceiling(calendar, Fields.Type.HOUR_OF_DAY); + public static java.util.Calendar endOfHour(final java.util.Calendar calendar) { + return ceiling(calendar, Various.HOUR_OF_DAY); } /** * 修改某分钟的开始时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar beginOfMinute(final Calendar calendar) { - return truncate(calendar, Fields.Type.MINUTE); + public static java.util.Calendar beginOfMinute(final java.util.Calendar calendar) { + return truncate(calendar, Various.MINUTE); } /** * 修改某分钟的结束时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar endOfMinute(final Calendar calendar) { - return ceiling(calendar, Fields.Type.MINUTE); + public static java.util.Calendar endOfMinute(final java.util.Calendar calendar) { + return ceiling(calendar, Various.MINUTE); } /** * 修改某天的开始时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar beginOfDay(final Calendar calendar) { - return truncate(calendar, Fields.Type.DAY_OF_MONTH); + public static java.util.Calendar beginOfDay(final java.util.Calendar calendar) { + return truncate(calendar, Various.DAY_OF_MONTH); } /** * 修改某天的结束时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar endOfDay(final Calendar calendar) { - return ceiling(calendar, Fields.Type.DAY_OF_MONTH); + public static java.util.Calendar endOfDay(final java.util.Calendar calendar) { + return ceiling(calendar, Various.DAY_OF_MONTH); } /** * 修改给定日期当前周的开始时间,周一定为一周的开始时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar beginOfWeek(final Calendar calendar) { + public static java.util.Calendar beginOfWeek(final java.util.Calendar calendar) { return beginOfWeek(calendar, true); } /** * 修改给定日期当前周的开始时间 * - * @param calendar 日期 {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} * @param isMondayAsFirstDay 是否周一做为一周的第一天(false表示周日做为第一天) - * @return {@link Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar beginOfWeek(final Calendar calendar, final boolean isMondayAsFirstDay) { - calendar.setFirstDayOfWeek(isMondayAsFirstDay ? Calendar.MONDAY : Calendar.SUNDAY); + public static java.util.Calendar beginOfWeek(final java.util.Calendar calendar, final boolean isMondayAsFirstDay) { + calendar.setFirstDayOfWeek(isMondayAsFirstDay ? java.util.Calendar.MONDAY : java.util.Calendar.SUNDAY); // WEEK_OF_MONTH为上限的字段(不包括),实际调整的为DAY_OF_MONTH - return truncate(calendar, Fields.Type.WEEK_OF_MONTH); + return truncate(calendar, Various.WEEK_OF_MONTH); } /** * 修改某周的结束时间,周日定为一周的结束 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar endOfWeek(final Calendar calendar) { + public static java.util.Calendar endOfWeek(final java.util.Calendar calendar) { return endOfWeek(calendar, true); } /** * 修改某周的结束时间 * - * @param calendar 日期 {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} * @param isSundayAsLastDay 是否周日做为一周的最后一天(false表示周六做为最后一天) - * @return {@link Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar endOfWeek(final Calendar calendar, final boolean isSundayAsLastDay) { - calendar.setFirstDayOfWeek(isSundayAsLastDay ? Calendar.MONDAY : Calendar.SUNDAY); + public static java.util.Calendar endOfWeek(final java.util.Calendar calendar, final boolean isSundayAsLastDay) { + calendar.setFirstDayOfWeek(isSundayAsLastDay ? java.util.Calendar.MONDAY : java.util.Calendar.SUNDAY); // WEEK_OF_MONTH为上限的字段(不包括),实际调整的为DAY_OF_MONTH - return ceiling(calendar, Fields.Type.WEEK_OF_MONTH); + return ceiling(calendar, Various.WEEK_OF_MONTH); } /** * 修改某月的开始时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar beginOfMonth(final Calendar calendar) { - return truncate(calendar, Fields.Type.MONTH); + public static java.util.Calendar beginOfMonth(final java.util.Calendar calendar) { + return truncate(calendar, Various.MONTH); } /** * 修改某月的结束时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar endOfMonth(final Calendar calendar) { - return ceiling(calendar, Fields.Type.MONTH); + public static java.util.Calendar endOfMonth(final java.util.Calendar calendar) { + return ceiling(calendar, Various.MONTH); } /** * 修改某季度的开始时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar beginOfQuarter(final Calendar calendar) { - calendar.set(Calendar.MONTH, calendar.get(Fields.Type.MONTH.getValue()) / 3 * 3); - calendar.set(Calendar.DAY_OF_MONTH, 1); + public static java.util.Calendar beginOfQuarter(final java.util.Calendar calendar) { + calendar.set(java.util.Calendar.MONTH, calendar.get(Various.MONTH.getValue()) / 3 * 3); + calendar.set(java.util.Calendar.DAY_OF_MONTH, 1); return beginOfDay(calendar); } /** * 获取某季度的结束时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar endOfQuarter(final Calendar calendar) { - final int year = calendar.get(Calendar.YEAR); - final int month = calendar.get(Fields.Type.MONTH.getValue()) / 3 * 3 + 2; + public static java.util.Calendar endOfQuarter(final java.util.Calendar calendar) { + final int year = calendar.get(java.util.Calendar.YEAR); + final int month = calendar.get(Various.MONTH.getValue()) / 3 * 3 + 2; - final Calendar resultCal = Calendar.getInstance(calendar.getTimeZone()); - resultCal.set(year, month, Fields.Month.of(month).getLastDay(DateKit.isLeapYear(year))); + final java.util.Calendar resultCal = java.util.Calendar.getInstance(calendar.getTimeZone()); + resultCal.set(year, month, Month.of(month).getLastDay(Calculate.isLeapYear(year))); return endOfDay(resultCal); } @@ -372,135 +504,21 @@ public static Calendar endOfQuarter(final Calendar calendar) { /** * 修改某年的开始时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar beginOfYear(final Calendar calendar) { - return truncate(calendar, Fields.Type.YEAR); + public static java.util.Calendar beginOfYear(final java.util.Calendar calendar) { + return truncate(calendar, Various.YEAR); } /** * 修改某年的结束时间 * - * @param calendar 日期 {@link Calendar} - * @return {@link Calendar} + * @param calendar 日期 {@link java.util.Calendar} + * @return {@link java.util.Calendar} */ - public static Calendar endOfYear(final Calendar calendar) { - return ceiling(calendar, Fields.Type.YEAR); - } - - /** - * 比较两个日期是否为同一天 - * - * @param cal1 日期1 - * @param cal2 日期2 - * @return 是否为同一天 - */ - public static boolean isSameDay(final Calendar cal1, Calendar cal2) { - if (ObjectKit.notEquals(cal1.getTimeZone(), cal2.getTimeZone())) { - // 统一时区 - cal2 = calendar(cal2, cal1.getTimeZone()); - } - return isSameYear(cal1, cal2) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR); - } - - /** - * 比较两个日期是否为同一周 - * 同一个周的意思是:ERA(公元)、year(年)、month(月)、week(周)都一致。 - * - * @param cal1 日期1 - * @param cal2 日期2 - * @param isMon 一周的第一天是否为周一。国内第一天为星期一,国外第一天为星期日 - * @return 是否为同一周 - */ - public static boolean isSameWeek(Calendar cal1, Calendar cal2, final boolean isMon) { - if (cal1 == null || cal2 == null) { - throw new IllegalArgumentException("The date must not be null"); - } - - // 防止比较前修改原始Calendar对象 - cal1 = (Calendar) cal1.clone(); - - if (ObjectKit.notEquals(cal1.getTimeZone(), cal2.getTimeZone())) { - // 统一时区 - cal2 = calendar(cal2, cal1.getTimeZone()); - } else { - cal2 = (Calendar) cal2.clone(); - } - - // 把所传日期设置为其当前周的第一天 - // 比较设置后的两个日期是否是同一天:true 代表同一周 - if (isMon) { - cal1.setFirstDayOfWeek(Calendar.MONDAY); - cal1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - cal2.setFirstDayOfWeek(Calendar.MONDAY); - cal2.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - } else { - cal1.setFirstDayOfWeek(Calendar.SUNDAY); - cal1.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); - cal2.setFirstDayOfWeek(Calendar.SUNDAY); - cal2.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); - } - return isSameDay(cal1, cal2); - } - - /** - * 比较两个日期是否为同一月 - * 同一个月的意思是:ERA(公元)、year(年)、month(月)都一致。 - * - * @param cal1 日期1 - * @param cal2 日期2 - * @return 是否为同一月 - */ - public static boolean isSameMonth(final Calendar cal1, Calendar cal2) { - if (ObjectKit.notEquals(cal1.getTimeZone(), cal2.getTimeZone())) { - // 统一时区 - cal2 = calendar(cal2, cal1.getTimeZone()); - } - - return isSameYear(cal1, cal2) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH); - } - - /** - * 比较两个日期是否为同一年 - * 同一个年的意思是:ERA(公元)、year(年)都一致。 - * - * @param cal1 日期1 - * @param cal2 日期2 - * @return 是否为同一年 - */ - public static boolean isSameYear(final Calendar cal1, Calendar cal2) { - if (cal1 == null || cal2 == null) { - throw new IllegalArgumentException("The date must not be null"); - } - - if (ObjectKit.notEquals(cal1.getTimeZone(), cal2.getTimeZone())) { - // 统一时区 - cal2 = calendar(cal2, cal1.getTimeZone()); - } - - return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && - cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA); - } - - /** - * 检查两个Calendar时间戳是否相同 - *

- * 此方法检查两个Calendar的毫秒数时间戳是否相同 - * - * @param date1 时间1 - * @param date2 时间2 - * @return 两个Calendar时间戳是否相同。如果两个时间都为{@code null}返回true,否则有{@code null}返回false - */ - public static boolean isSameInstant(final Calendar date1, final Calendar date2) { - if (null == date1) { - return null == date2; - } - if (null == date2) { - return false; - } - - return date1.getTimeInMillis() == date2.getTimeInMillis(); + public static java.util.Calendar endOfYear(final java.util.Calendar calendar) { + return ceiling(calendar, Various.YEAR); } /** @@ -510,32 +528,32 @@ public static boolean isSameInstant(final Calendar date1, final Calendar date2) * @param cal 日期 * @return 年和季度,格式类似于20131 */ - public static String yearAndQuarter(final Calendar cal) { - return StringKit.builder().append(cal.get(Calendar.YEAR)).append(cal.get(Calendar.MONTH) / 3 + 1).toString(); + public static String yearAndQuarter(final java.util.Calendar cal) { + return StringKit.builder().append(cal.get(java.util.Calendar.YEAR)).append(cal.get(java.util.Calendar.MONTH) / 3 + 1).toString(); } /** * 获取指定日期字段的最小值,例如分钟的最小值是0 * - * @param calendar {@link Calendar} - * @param type {@link Fields.Type} + * @param calendar {@link java.util.Calendar} + * @param various {@link Various} * @return 字段最小值 - * @see Calendar#getActualMinimum(int) + * @see java.util.Calendar#getActualMinimum(int) */ - public static int getBeginValue(final Calendar calendar, final Fields.Type type) { - return getBeginValue(calendar, type.getValue()); + public static int getBeginValue(final java.util.Calendar calendar, final Various various) { + return getBeginValue(calendar, various.getValue()); } /** * 获取指定日期字段的最小值,例如分钟的最小值是0 * - * @param calendar {@link Calendar} - * @param dateField {@link Fields.Type} + * @param calendar {@link java.util.Calendar} + * @param dateField {@link Various} * @return 字段最小值 - * @see Calendar#getActualMinimum(int) + * @see java.util.Calendar#getActualMinimum(int) */ - public static int getBeginValue(final Calendar calendar, final int dateField) { - if (Calendar.DAY_OF_WEEK == dateField) { + public static int getBeginValue(final java.util.Calendar calendar, final int dateField) { + if (java.util.Calendar.DAY_OF_WEEK == dateField) { return calendar.getFirstDayOfWeek(); } return calendar.getActualMinimum(dateField); @@ -544,25 +562,25 @@ public static int getBeginValue(final Calendar calendar, final int dateField) { /** * 获取指定日期字段的最大值,例如分钟的最大值是59 * - * @param calendar {@link Calendar} - * @param type {@link Fields.Type} + * @param calendar {@link java.util.Calendar} + * @param various {@link Various} * @return 字段最大值 - * @see Calendar#getActualMaximum(int) + * @see java.util.Calendar#getActualMaximum(int) */ - public static int getEndValue(final Calendar calendar, final Fields.Type type) { - return getEndValue(calendar, type.getValue()); + public static int getEndValue(final java.util.Calendar calendar, final Various various) { + return getEndValue(calendar, various.getValue()); } /** * 获取指定日期字段的最大值,例如分钟的最大值是59 * - * @param calendar {@link Calendar} - * @param dateField {@link Fields.Type} + * @param calendar {@link java.util.Calendar} + * @param dateField {@link Various} * @return 字段最大值 - * @see Calendar#getActualMaximum(int) + * @see java.util.Calendar#getActualMaximum(int) */ - public static int getEndValue(final Calendar calendar, final int dateField) { - if (Calendar.DAY_OF_WEEK == dateField) { + public static int getEndValue(final java.util.Calendar calendar, final int dateField) { + if (java.util.Calendar.DAY_OF_WEEK == dateField) { return (calendar.getFirstDayOfWeek() + 6) % 7; } return calendar.getActualMaximum(dateField); @@ -572,11 +590,11 @@ public static int getEndValue(final Calendar calendar, final int dateField) { * 获得日期的某个部分 * 例如获得年的部分,则使用 getField(DatePart.YEAR) * - * @param calendar {@link Calendar} - * @param field 表示日期的哪个部分的枚举 {@link Fields.Type} + * @param calendar {@link java.util.Calendar} + * @param field 表示日期的哪个部分的枚举 {@link Various} * @return 某个部分的值 */ - public static int getField(final Calendar calendar, final Fields.Type field) { + public static int getField(final java.util.Calendar calendar, final Various field) { return Assert.notNull(calendar).get(Assert.notNull(field).getValue()); } @@ -586,17 +604,17 @@ public static int getField(final Calendar calendar, final Fields.Type field) { * @param calendar Date对象 * @return {@link Instant}对象 */ - public static Instant toInstant(final Calendar calendar) { + public static Instant toInstant(final java.util.Calendar calendar) { return null == calendar ? null : calendar.toInstant(); } /** - * {@link Calendar} 转换为 {@link LocalDateTime},使用系统默认时区 + * {@link java.util.Calendar} 转换为 {@link LocalDateTime},使用系统默认时区 * - * @param calendar {@link Calendar} + * @param calendar {@link java.util.Calendar} * @return {@link LocalDateTime} */ - public static LocalDateTime toLocalDateTime(final Calendar calendar) { + public static LocalDateTime toLocalDateTime(final java.util.Calendar calendar) { if (null == calendar) { return null; } @@ -604,32 +622,16 @@ public static LocalDateTime toLocalDateTime(final Calendar calendar) { } /** - * {@code null}安全的{@link Calendar}比较,{@code null}小于任何日期 + * {@code null}安全的{@link java.util.Calendar}比较,{@code null}小于任何日期 * * @param calendar1 日期1 * @param calendar2 日期2 * @return 比较结果,如果calendar1 < calendar2,返回数小于0,calendar1==calendar2返回0,calendar1 > calendar2 大于0 */ - public static int compare(final Calendar calendar1, final Calendar calendar2) { + public static int compare(final java.util.Calendar calendar1, final java.util.Calendar calendar2) { return CompareKit.compare(calendar1, calendar2); } - /** - * 计算相对于dateToCompare的年龄,常用于计算指定生日在某年的年龄 - * 按照《最高人民法院关于审理未成年人刑事案件具体应用法律若干问题的解释》第二条规定刑法第十七条规定的“周岁”,按照公历的年、月、日计算,从周岁生日的第二天起算。 - *

    - *
  • 2022-03-01出生,则相对2023-03-01,周岁为0,相对于2023-03-02才是1岁。
  • - *
  • 1999-02-28出生,则相对2000-02-29,周岁为1
  • - *
- * - * @param birthday 生日 - * @param dateToCompare 需要对比的日期 - * @return 年龄 - */ - public static int age(final Calendar birthday, final Calendar dateToCompare) { - return age(birthday.getTimeInMillis(), dateToCompare.getTimeInMillis()); - } - /** * 将指定Calendar时间格式化为纯中文形式,比如: * @@ -638,15 +640,15 @@ public static int age(final Calendar birthday, final Calendar dateToCompare) { * 2018-02-24 12:13:14 转换为 二〇一八年二月二十四日十二时十三分十四秒(withTime为true) * * - * @param calendar {@link Calendar} + * @param calendar {@link java.util.Calendar} * @param withTime 是否包含时间部分 * @return 格式化后的字符串 */ - public static String formatChineseDate(final Calendar calendar, final boolean withTime) { + public static String formatChineseDate(final java.util.Calendar calendar, final boolean withTime) { final StringBuilder result = StringKit.builder(); // 年 - final String year = String.valueOf(calendar.get(Calendar.YEAR)); + final String year = String.valueOf(calendar.get(java.util.Calendar.YEAR)); final int length = year.length(); for (int i = 0; i < length; i++) { result.append(ChineseNumberFormatter.formatChar(year.charAt(i), false)); @@ -654,12 +656,12 @@ public static String formatChineseDate(final Calendar calendar, final boolean wi result.append('年'); // 月 - final int month = calendar.get(Calendar.MONTH) + 1; + final int month = calendar.get(java.util.Calendar.MONTH) + 1; result.append(ChineseNumberFormatter.of().setColloquialMode(true).format(month)); result.append('月'); // 日 - final int day = calendar.get(Calendar.DAY_OF_MONTH); + final int day = calendar.get(java.util.Calendar.DAY_OF_MONTH); result.append(ChineseNumberFormatter.of().setColloquialMode(true).format(day)); result.append('日'); @@ -671,15 +673,15 @@ public static String formatChineseDate(final Calendar calendar, final boolean wi if (withTime) { // 时 - final int hour = calendar.get(Calendar.HOUR_OF_DAY); + final int hour = calendar.get(java.util.Calendar.HOUR_OF_DAY); result.append(ChineseNumberFormatter.of().setColloquialMode(true).format(hour)); result.append('时'); // 分 - final int minute = calendar.get(Calendar.MINUTE); + final int minute = calendar.get(java.util.Calendar.MINUTE); result.append(ChineseNumberFormatter.of().setColloquialMode(true).format(minute)); result.append('分'); // 秒 - final int second = calendar.get(Calendar.SECOND); + final int second = calendar.get(java.util.Calendar.SECOND); result.append(ChineseNumberFormatter.of().setColloquialMode(true).format(second)); result.append('秒'); } @@ -689,7 +691,7 @@ public static String formatChineseDate(final Calendar calendar, final boolean wi /** * 通过给定的日期格式解析日期时间字符串。 - * 传入的日期格式会逐个尝试,直到解析成功,返回{@link Calendar}对象,否则抛出{@link DateException}异常。 + * 传入的日期格式会逐个尝试,直到解析成功,返回{@link java.util.Calendar}对象,否则抛出{@link DateException}异常。 * 方法来自:Apache Commons-Lang3 * * @param text 日期时间字符串,非空 @@ -698,13 +700,13 @@ public static String formatChineseDate(final Calendar calendar, final boolean wi * @throws IllegalArgumentException if the date string or pattern array is null * @throws DateException if none of the date patterns were suitable */ - public static Calendar parseByPatterns(final String text, final String... parsePatterns) throws DateException { + public static java.util.Calendar parseByPatterns(final String text, final String... parsePatterns) throws DateException { return parseByPatterns(text, null, parsePatterns); } /** * 通过给定的日期格式解析日期时间字符串。 - * 传入的日期格式会逐个尝试,直到解析成功,返回{@link Calendar}对象,否则抛出{@link DateException}异常。 + * 传入的日期格式会逐个尝试,直到解析成功,返回{@link java.util.Calendar}对象,否则抛出{@link DateException}异常。 * 方法来自:Apache Commons-Lang3 * * @param text 日期时间字符串,非空 @@ -714,13 +716,13 @@ public static Calendar parseByPatterns(final String text, final String... parseP * @throws IllegalArgumentException if the date string or pattern array is null * @throws DateException if none of the date patterns were suitable */ - public static Calendar parseByPatterns(final String text, final Locale locale, final String... parsePatterns) throws DateException { + public static java.util.Calendar parseByPatterns(final String text, final Locale locale, final String... parsePatterns) throws DateException { return parseByPatterns(text, locale, true, parsePatterns); } /** * 通过给定的日期格式解析日期时间字符串。 - * 传入的日期格式会逐个尝试,直到解析成功,返回{@link Calendar}对象,否则抛出{@link DateException}异常。 + * 传入的日期格式会逐个尝试,直到解析成功,返回{@link java.util.Calendar}对象,否则抛出{@link DateException}异常。 * 方法来自:Apache Commons-Lang3 * * @param text 日期时间字符串,非空 @@ -732,7 +734,7 @@ public static Calendar parseByPatterns(final String text, final Locale locale, f * @throws DateException if none of the date patterns were suitable * @see java.util.Calendar#isLenient() */ - public static Calendar parseByPatterns(final String text, final Locale locale, final boolean lenient, final String... parsePatterns) throws DateException { + public static java.util.Calendar parseByPatterns(final String text, final Locale locale, final boolean lenient, final String... parsePatterns) throws DateException { if (text == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } @@ -740,7 +742,7 @@ public static Calendar parseByPatterns(final String text, final Locale locale, f final TimeZone tz = TimeZone.getDefault(); final Locale lcl = ObjectKit.defaultIfNull(locale, Locale.getDefault()); final ParsePosition pos = new ParsePosition(0); - final Calendar calendar = Calendar.getInstance(tz, lcl); + final java.util.Calendar calendar = java.util.Calendar.getInstance(tz, lcl); calendar.setLenient(lenient); for (final String parsePattern : parsePatterns) { @@ -769,21 +771,62 @@ public static Calendar parseByPatterns(final String text, final Locale locale, f } /** - * 使用指定{@link DateParser}解析字符串为{@link Calendar} + * 使用指定{@link DateParser}解析字符串为{@link java.util.Calendar} * * @param text 日期字符串 * @param lenient 是否宽容模式 * @param parser {@link DateParser} - * @return 解析后的 {@link Calendar},解析失败返回{@code null} + * @return 解析后的 {@link java.util.Calendar},解析失败返回{@code null} */ - public static Calendar parse(final CharSequence text, final boolean lenient, final PositionDateParser parser) { - final Calendar calendar = Calendar.getInstance(parser.getTimeZone(), parser.getLocale()); + public static java.util.Calendar parse(final CharSequence text, final boolean lenient, final PositionDateParser parser) { + final java.util.Calendar calendar = java.util.Calendar.getInstance(parser.getTimeZone(), parser.getLocale()); calendar.clear(); calendar.setLenient(lenient); return parser.parse(StringKit.toString(text), new ParsePosition(0), calendar) ? calendar : null; } + /** + * 计算年龄 + * + * @param birthDay 生日 + * @return int 年龄 + */ + public static int age(LocalDate birthDay) { + Period period = Period.between(birthDay, LocalDate.now()); + if (period.getYears() < 0) { + throw new DateTimeException("birthDay is after now!"); + } else { + return period.getYears(); + } + } + + /** + * 计算年龄 + * + * @param birthDay 生日 + * @return int 年龄 + */ + public static int age(LocalDateTime birthDay) { + return age(birthDay.toLocalDate()); + } + + /** + * 计算相对于dateToCompare的年龄,常用于计算指定生日在某年的年龄 + * 按照《最高人民法院关于审理未成年人刑事案件具体应用法律若干问题的解释》第二条规定刑法第十七条规定的“周岁”,按照公历的年、月、日计算,从周岁生日的第二天起算。 + *
    + *
  • 2022-03-01出生,则相对2023-03-01,周岁为0,相对于2023-03-02才是1岁。
  • + *
  • 1999-02-28出生,则相对2000-02-29,周岁为1
  • + *
+ * + * @param birthday 生日 + * @param dateToCompare 需要对比的日期 + * @return 年龄 + */ + public static int age(final java.util.Calendar birthday, final java.util.Calendar dateToCompare) { + return age(birthday.getTimeInMillis(), dateToCompare.getTimeInMillis()); + } + /** * 计算相对于dateToCompare的年龄(周岁),常用于计算指定生日在某年的年龄 * 按照《最高人民法院关于审理未成年人刑事案件具体应用法律若干问题的解释》第二条规定刑法第十七条规定的“周岁”,按照公历的年、月、日计算,从周岁生日的第二天起算。 @@ -801,24 +844,24 @@ protected static int age(final long birthday, final long dateToCompare) { throw new IllegalArgumentException("Birthday is after dateToCompare!"); } - final Calendar cal = Calendar.getInstance(); + final java.util.Calendar cal = java.util.Calendar.getInstance(); cal.setTimeInMillis(dateToCompare); - final int year = cal.get(Calendar.YEAR); - final int month = cal.get(Calendar.MONTH); - final int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); + final int year = cal.get(java.util.Calendar.YEAR); + final int month = cal.get(java.util.Calendar.MONTH); + final int dayOfMonth = cal.get(java.util.Calendar.DAY_OF_MONTH); // 复用cal cal.setTimeInMillis(birthday); - int age = year - cal.get(Calendar.YEAR); + int age = year - cal.get(java.util.Calendar.YEAR); //当前日期,则为0岁 if (age == 0) { return 0; } - final int monthBirth = cal.get(Calendar.MONTH); + final int monthBirth = cal.get(java.util.Calendar.MONTH); if (month == monthBirth) { - final int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); + final int dayOfMonthBirth = cal.get(java.util.Calendar.DAY_OF_MONTH); // 法定生日当天不算年龄,从第二天开始计算 if (dayOfMonth <= dayOfMonthBirth) { // 如果生日在当月,但是未达到生日当天的日期,年龄减一 @@ -832,24 +875,4 @@ protected static int age(final long birthday, final long dateToCompare) { return age; } - /** - * 是否为本月第一天 - * - * @param calendar {@link Calendar} - * @return 是否为本月最后一天 - */ - public static boolean isFirstDayOfMonth(final Calendar calendar) { - return 1 == calendar.get(Calendar.DAY_OF_MONTH); - } - - /** - * 是否为本月最后一天 - * - * @param calendar {@link Calendar} - * @return 是否为本月最后一天 - */ - public static boolean isLastDayOfMonth(final Calendar calendar) { - return calendar.get(Calendar.DAY_OF_MONTH) == calendar.getActualMaximum(Calendar.DAY_OF_MONTH); - } - } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Converter.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Converter.java index 6607b0cc48..18c429c1d4 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Converter.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Converter.java @@ -36,7 +36,7 @@ import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; -import java.util.Date; +import java.util.Calendar; import java.util.TimeZone; import java.util.concurrent.TimeUnit; @@ -48,6 +48,34 @@ */ public class Converter extends Formatter { + /** + * {@link Calendar}类型时间转为{@link DateTime} + * 始终根据已有{@link Calendar} 产生新的{@link DateTime}对象 + * + * @param calendar {@link Calendar},如果传入{@code null},返回{@code null} + * @return 时间对象 + */ + public static DateTime date(final Calendar calendar) { + if (calendar == null) { + return null; + } + return new DateTime(calendar); + } + + /** + * {@link TemporalAccessor}类型时间转为{@link DateTime} + * 始终根据已有{@link TemporalAccessor} 产生新的{@link DateTime}对象 + * + * @param temporalAccessor {@link TemporalAccessor},常用子类: {@link LocalDateTime}、 LocalDate,如果传入{@code null},返回{@code null} + * @return 时间对象 + */ + public static DateTime date(final TemporalAccessor temporalAccessor) { + if (temporalAccessor == null) { + return null; + } + return new DateTime(temporalAccessor); + } + /** * 安全获取时间的某个属性,属性不存在返回最小值,一般为0 * 注意请谨慎使用此方法,某些{@link TemporalAccessor#isSupported(TemporalField)}为{@code false}的方法返回最小值 @@ -265,23 +293,6 @@ public static LocalDateTime of(final long epochMilli, final TimeZone timeZone) { return of(Instant.ofEpochMilli(epochMilli), timeZone); } - /** - * {@link Date}转{@link LocalDateTime},使用默认时区 - * - * @param date Date对象 - * @return {@link LocalDateTime} - */ - public static LocalDateTime of(final Date date) { - if (null == date) { - return null; - } - - if (date instanceof DateTime) { - return of(date.toInstant(), ((DateTime) date).getZoneId()); - } - return of(date.toInstant()); - } - /** * {@link TemporalAccessor}转{@link LocalDateTime},使用默认时区 * @@ -352,7 +363,6 @@ public static LocalDate ofDate(final TemporalAccessor temporalAccessor) { ); } - /** * 通过日期时间字符串构建{@link DateTimeFormatter} * @@ -369,19 +379,4 @@ public static DateTimeFormatter ofPattern(final String pattern) { .toFormatter(); } - - /** - * 获取最大时间,提供参数是否将毫秒归零 - *
    - *
  • 如果{@code truncateMillisecond}为{@code false},返回时间最大值,为:23:59:59,999
  • - *
  • 如果{@code truncateMillisecond}为{@code true},返回时间最大值,为:23:59:59,000
  • - *
- * - * @param truncateMillisecond 是否毫秒归零 - * @return {@link LocalTime}时间最大值 - */ - public static LocalTime max(final boolean truncateMillisecond) { - return truncateMillisecond ? MAX_HMS : LocalTime.MAX; - } - } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/DateTime.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/DateTime.java index 3304d8b513..5d6ef149cd 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/DateTime.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/DateTime.java @@ -25,6 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.core.center.date; +import org.miaixz.bus.core.center.date.culture.en.Month; +import org.miaixz.bus.core.center.date.culture.en.*; import org.miaixz.bus.core.center.date.format.CustomFormat; import org.miaixz.bus.core.center.date.format.FormatBuilder; import org.miaixz.bus.core.center.date.format.FormatPeriod; @@ -42,13 +44,9 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; +import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; -import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; @@ -73,7 +71,7 @@ public class DateTime extends Date { /** * 一周的第一天,默认是周一, 在设置或获得 WEEK_OF_MONTH 或 WEEK_OF_YEAR 字段时,Calendar 必须确定一个月或一年的第一个星期,以此作为参考点。 */ - private Fields.Week firstDayOfWeek = Fields.Week.MONDAY; + private Week firstDayOfWeek = Week.MONDAY; /** * 时区 */ @@ -124,11 +122,11 @@ public DateTime(final Date date, final TimeZone timeZone) { /** * 给定日期的构造 * - * @param calendar {@link Calendar},不能为{@code null} + * @param calendar {@link java.util.Calendar},不能为{@code null} */ - public DateTime(final Calendar calendar) { + public DateTime(final java.util.Calendar calendar) { this(calendar.getTime(), calendar.getTimeZone()); - this.setFirstDayOfWeek(Fields.Week.of(calendar.getFirstDayOfWeek())); + this.setFirstDayOfWeek(Week.of(calendar.getFirstDayOfWeek())); } /** @@ -312,12 +310,12 @@ public static DateTime of(final Date date) { } /** - * 转换 {@link Calendar} 为 DateTime + * 转换 {@link java.util.Calendar} 为 DateTime * - * @param calendar {@link Calendar} + * @param calendar {@link java.util.Calendar} * @return DateTime */ - public static DateTime of(final Calendar calendar) { + public static DateTime of(final java.util.Calendar calendar) { return new DateTime(calendar); } @@ -370,18 +368,18 @@ private static Date parse(final CharSequence dateStr, final DateFormat dateForma * @param dateStr 日期字符串 * @param parser {@link FormatBuilder} * @param lenient 是否宽容模式 - * @return {@link Calendar} + * @return {@link java.util.Calendar} */ - private static Calendar parse(final CharSequence dateStr, final PositionDateParser parser, final boolean lenient) { + private static java.util.Calendar parse(final CharSequence dateStr, final PositionDateParser parser, final boolean lenient) { Assert.notNull(parser, "Parser or DateFromat must be not null !"); Assert.notBlank(dateStr, "Date String must be not blank !"); - final Calendar calendar = Calendars.parse(dateStr, lenient, parser); + final java.util.Calendar calendar = Calendar.parse(dateStr, lenient, parser); if (null == calendar) { throw new DateException("Parse [{}] with format [{}] error!", dateStr, parser.getPattern()); } - calendar.setFirstDayOfWeek(Fields.Week.MONDAY.getValue()); + calendar.setFirstDayOfWeek(Week.MONDAY.getCode()); return calendar; } @@ -389,16 +387,16 @@ private static Calendar parse(final CharSequence dateStr, final PositionDatePars * 调整日期和时间 * 如果此对象为可变对象,返回自身,否则返回新对象,设置是否可变对象见{@link #setMutable(boolean)} * - * @param datePart 调整的部分 {@link Fields.Type} + * @param datePart 调整的部分 {@link Various} * @param offset 偏移量,正数为向后偏移,负数为向前偏移 * @return 如果此对象为可变对象,返回自身,否则返回新对象 */ - public DateTime offset(final Fields.Type datePart, final int offset) { - if (Fields.Type.ERA == datePart) { + public DateTime offset(final Various datePart, final int offset) { + if (Various.ERA == datePart) { throw new IllegalArgumentException("ERA is not support offset!"); } - final Calendar cal = toCalendar(); + final java.util.Calendar cal = toCalendar(); cal.add(datePart.getValue(), offset); final DateTime dt = mutable ? this : ObjectKit.clone(this); @@ -409,12 +407,12 @@ public DateTime offset(final Fields.Type datePart, final int offset) { * 调整日期和时间 * 返回调整后的新DateTime,不影响原对象 * - * @param datePart 调整的部分 {@link Fields.Type} + * @param datePart 调整的部分 {@link Various} * @param offset 偏移量,正数为向后偏移,负数为向前偏移 * @return 如果此对象为可变对象,返回自身,否则返回新对象 */ - public DateTime offsetNew(final Fields.Type datePart, final int offset) { - final Calendar cal = toCalendar(); + public DateTime offsetNew(final Various datePart, final int offset) { + final java.util.Calendar cal = toCalendar(); cal.add(datePart.getValue(), offset); return ObjectKit.clone(this).setTimeInternal(cal.getTimeInMillis()); } @@ -423,10 +421,10 @@ public DateTime offsetNew(final Fields.Type datePart, final int offset) { * 获得日期的某个部分 * 例如获得年的部分,则使用 getField(DatePart.YEAR) * - * @param field 表示日期的哪个部分的枚举 {@link Fields.Type} + * @param field 表示日期的哪个部分的枚举 {@link Various} * @return 某个部分的值 */ - public int getField(final Fields.Type field) { + public int getField(final Various field) { return getField(field.getValue()); } @@ -434,7 +432,7 @@ public int getField(final Fields.Type field) { * 获得日期的某个部分 * 例如获得年的部分,则使用 getField(Calendar.YEAR) * - * @param field 表示日期的哪个部分的int值 {@link Calendar} + * @param field 表示日期的哪个部分的int值 {@link java.util.Calendar} * @return 某个部分的值 */ public int getField(final int field) { @@ -445,11 +443,11 @@ public int getField(final int field) { * 设置日期的某个部分 * 如果此对象为可变对象,返回自身,否则返回新对象,设置是否可变对象见{@link #setMutable(boolean)} * - * @param field 表示日期的哪个部分的枚举 {@link Fields.Type} + * @param field 表示日期的哪个部分的枚举 {@link Various} * @param value 值 * @return this */ - public DateTime setField(final Fields.Type field, final int value) { + public DateTime setField(final Various field, final int value) { return setField(field.getValue(), value); } @@ -457,12 +455,12 @@ public DateTime setField(final Fields.Type field, final int value) { * 设置日期的某个部分 * 如果此对象为可变对象,返回自身,否则返回新对象,设置是否可变对象见{@link #setMutable(boolean)} * - * @param field 表示日期的哪个部分的int值 {@link Calendar} + * @param field 表示日期的哪个部分的int值 {@link java.util.Calendar} * @param value 值 * @return this */ public DateTime setField(final int field, final int value) { - final Calendar calendar = toCalendar(); + final java.util.Calendar calendar = toCalendar(); calendar.set(field, value); DateTime dt = this; @@ -487,13 +485,13 @@ public void setTime(final long time) { * @return 年的部分 */ public int year() { - return getField(Fields.Type.YEAR); + return getField(Various.YEAR); } /** * 获得当前日期所属季度,从1开始计数 * - * @return 第几个季度 {@link Fields.Quarter} + * @return 第几个季度 {@link Quarter} */ public int quarter() { return month() / 3 + 1; @@ -502,10 +500,10 @@ public int quarter() { /** * 获得当前日期所属季度 * - * @return 第几个季度 {@link Fields.Quarter} + * @return 第几个季度 {@link Quarter} */ - public Fields.Quarter quarterEnum() { - return Fields.Quarter.of(quarter()); + public Quarter quarterEnum() { + return Quarter.of(quarter()); } /** @@ -514,7 +512,7 @@ public Fields.Quarter quarterEnum() { * @return 月份 */ public int month() { - return getField(Fields.Type.MONTH); + return getField(Various.MONTH); } /** @@ -528,7 +526,7 @@ public int monthBaseOne() { /** * 获得月份,从1开始计数 - * 由于{@link Calendar} 中的月份按照0开始计数,导致某些需求容易误解,因此如果想用1表示一月,2表示二月则调用此方法 + * 由于{@link java.util.Calendar} 中的月份按照0开始计数,导致某些需求容易误解,因此如果想用1表示一月,2表示二月则调用此方法 * * @return 月份 */ @@ -539,10 +537,10 @@ public int monthStartFromOne() { /** * 获得月份 * - * @return {@link Fields.Month} + * @return {@link Month} */ - public Fields.Month monthEnum() { - return Fields.Month.of(month()); + public Month monthEnum() { + return Month.of(month()); } /** @@ -553,10 +551,10 @@ public Fields.Month monthEnum() { * 跨年的那个星期得到的结果总是1 * * @return 周 - * @see #setFirstDayOfWeek(Fields.Week) + * @see #setFirstDayOfWeek(Week) */ public int weekOfYear() { - return getField(Fields.Type.WEEK_OF_YEAR); + return getField(Various.WEEK_OF_YEAR); } /** @@ -566,10 +564,10 @@ public int weekOfYear() { * 如果一周的第一天为周一,那这天是第一周(返回1) * * @return 周 - * @see #setFirstDayOfWeek(Fields.Week) + * @see #setFirstDayOfWeek(Week) */ public int weekOfMonth() { - return getField(Fields.Type.WEEK_OF_MONTH); + return getField(Various.WEEK_OF_MONTH); } /** @@ -578,7 +576,7 @@ public int weekOfMonth() { * @return 天,1表示第一天 */ public int dayOfMonth() { - return getField(Fields.Type.DAY_OF_MONTH); + return getField(Various.DAY_OF_MONTH); } /** @@ -587,7 +585,7 @@ public int dayOfMonth() { * @return 天,1表示第一天 */ public int dayOfYear() { - return getField(Fields.Type.DAY_OF_YEAR); + return getField(Various.DAY_OF_YEAR); } /** @@ -596,7 +594,7 @@ public int dayOfYear() { * @return 星期几 */ public int dayOfWeek() { - return getField(Fields.Type.DAY_OF_WEEK); + return getField(Various.DAY_OF_WEEK); } /** @@ -605,16 +603,16 @@ public int dayOfWeek() { * @return 天 */ public int dayOfWeekInMonth() { - return getField(Fields.Type.DAY_OF_WEEK_IN_MONTH); + return getField(Various.DAY_OF_WEEK_IN_MONTH); } /** * 获得指定日期是星期几 * - * @return {@link Fields.Week} + * @return {@link Week} */ - public Fields.Week dayOfWeekEnum() { - return Fields.Week.of(dayOfWeek()); + public Week dayOfWeekEnum() { + return Week.of(dayOfWeek()); } /** @@ -624,7 +622,7 @@ public Fields.Week dayOfWeekEnum() { * @return 小时数 */ public int hour(final boolean is24HourClock) { - return getField(is24HourClock ? Fields.Type.HOUR_OF_DAY : Fields.Type.HOUR); + return getField(is24HourClock ? Various.HOUR_OF_DAY : Various.HOUR); } /** @@ -634,7 +632,7 @@ public int hour(final boolean is24HourClock) { * @return 分钟数 */ public int minute() { - return getField(Fields.Type.MINUTE); + return getField(Various.MINUTE); } /** @@ -643,7 +641,7 @@ public int minute() { * @return 秒数 */ public int second() { - return getField(Fields.Type.SECOND); + return getField(Various.SECOND); } /** @@ -652,7 +650,7 @@ public int second() { * @return 毫秒数 */ public int millisecond() { - return getField(Fields.Type.MILLISECOND); + return getField(Various.MILLISECOND); } /** @@ -661,7 +659,7 @@ public int millisecond() { * @return 是否为上午 */ public boolean isAM() { - return Calendar.AM == getField(Fields.Type.AM_PM); + return java.util.Calendar.AM == getField(Various.AM_PM); } /** @@ -670,7 +668,7 @@ public boolean isAM() { * @return 是否为下午 */ public boolean isPM() { - return Calendar.PM == getField(Fields.Type.AM_PM); + return java.util.Calendar.PM == getField(Various.AM_PM); } /** @@ -680,25 +678,24 @@ public boolean isPM() { */ public boolean isWeekend() { final int dayOfWeek = dayOfWeek(); - return Calendar.SATURDAY == dayOfWeek || Calendar.SUNDAY == dayOfWeek; + return java.util.Calendar.SATURDAY == dayOfWeek || java.util.Calendar.SUNDAY == dayOfWeek; } /** * 是否闰年 * * @return 是否闰年 - * @see DateKit#isLeapYear(int) */ public boolean isLeapYear() { - return DateKit.isLeapYear(year()); + return Year.isLeap(year()); } /** * 转换为Calendar, 默认 {@link Locale} * - * @return {@link Calendar} + * @return {@link java.util.Calendar} */ - public Calendar toCalendar() { + public java.util.Calendar toCalendar() { return toCalendar(Locale.getDefault(Locale.Category.FORMAT)); } @@ -706,9 +703,9 @@ public Calendar toCalendar() { * 转换为Calendar * * @param locale 地域 {@link Locale} - * @return {@link Calendar} + * @return {@link java.util.Calendar} */ - public Calendar toCalendar(final Locale locale) { + public java.util.Calendar toCalendar(final Locale locale) { return toCalendar(this.timeZone, locale); } @@ -716,9 +713,9 @@ public Calendar toCalendar(final Locale locale) { * 转换为Calendar * * @param zone 时区 {@link TimeZone} - * @return {@link Calendar} + * @return {@link java.util.Calendar} */ - public Calendar toCalendar(final TimeZone zone) { + public java.util.Calendar toCalendar(final TimeZone zone) { return toCalendar(zone, Locale.getDefault(Locale.Category.FORMAT)); } @@ -727,14 +724,14 @@ public Calendar toCalendar(final TimeZone zone) { * * @param zone 时区 {@link TimeZone} * @param locale 地域 {@link Locale} - * @return {@link Calendar} + * @return {@link java.util.Calendar} */ - public Calendar toCalendar(final TimeZone zone, Locale locale) { + public java.util.Calendar toCalendar(final TimeZone zone, Locale locale) { if (null == locale) { locale = Locale.getDefault(Locale.Category.FORMAT); } - final Calendar cal = (null != zone) ? Calendar.getInstance(zone, locale) : Calendar.getInstance(locale); - cal.setFirstDayOfWeek(firstDayOfWeek.getValue()); + final java.util.Calendar cal = (null != zone) ? java.util.Calendar.getInstance(zone, locale) : java.util.Calendar.getInstance(locale); + cal.setFirstDayOfWeek(firstDayOfWeek.getCode()); if (minimalDaysInFirstWeek > 0) { cal.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek); } @@ -758,7 +755,7 @@ public Date toJdkDate() { * @return {@link LocalDateTime} */ public LocalDateTime toLocalDateTime() { - return Converter.of(this); + return Converter.of(this.toInstant()); } /** @@ -775,10 +772,10 @@ public Between between(final Date date) { * 计算相差时长 * * @param date 对比的日期 - * @param unit 单位 {@link Fields.Units} + * @param unit 单位 {@link Units} * @return 相差时长 */ - public long between(final Date date, final Fields.Units unit) { + public long between(final Date date, final Units unit) { return new Between(this, date).between(unit); } @@ -786,11 +783,11 @@ public long between(final Date date, final Fields.Units unit) { * 计算相差时长 * * @param date 对比的日期 - * @param unit 单位 {@link Fields.Units} + * @param unit 单位 {@link Units} * @param formatLevel 格式化级别 * @return 相差时长 */ - public String between(final Date date, final Fields.Units unit, final FormatPeriod.Level formatLevel) { + public String between(final Date date, final Units unit, final FormatPeriod.Level formatLevel) { return new Between(this, date).toString(unit, formatLevel); } @@ -915,8 +912,8 @@ public boolean isAfterOrEquals(final Date date) { * 对象是否可变 * 如果为不可变对象,以下方法将返回新方法: *
    - *
  • {@link DateTime#offset(Fields.Type, int)}
  • - *
  • {@link DateTime#setField(Fields.Type, int)}
  • + *
  • {@link DateTime#offset(Various, int)}
  • + *
  • {@link DateTime#setField(Various, int)}
  • *
  • {@link DateTime#setField(int, int)}
  • *
* 如果为不可变对象,{@link DateTime#setTime(long)}将抛出异常 @@ -930,8 +927,8 @@ public boolean isMutable() { /** * 设置对象是否可变 如果为不可变对象,以下方法将返回新方法: *
    - *
  • {@link DateTime#offset(Fields.Type, int)}
  • - *
  • {@link DateTime#setField(Fields.Type, int)}
  • + *
  • {@link DateTime#offset(Various, int)}
  • + *
  • {@link DateTime#setField(Various, int)}
  • *
  • {@link DateTime#setField(int, int)}
  • *
* 如果为不可变对象,{@link DateTime#setTime(long)}将抛出异常 @@ -949,7 +946,7 @@ public DateTime setMutable(final boolean mutable) { * * @return 一周的第一天 */ - public Fields.Week getFirstDayOfWeek() { + public Week getFirstDayOfWeek() { return firstDayOfWeek; } @@ -963,7 +960,7 @@ public Fields.Week getFirstDayOfWeek() { * @see #weekOfMonth() * @see #weekOfYear() */ - public DateTime setFirstDayOfWeek(final Fields.Week firstDayOfWeek) { + public DateTime setFirstDayOfWeek(final Week firstDayOfWeek) { this.firstDayOfWeek = firstDayOfWeek; return this; } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Formatter.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Formatter.java index 5d99accc47..4d34d6fac6 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Formatter.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Formatter.java @@ -28,10 +28,14 @@ import org.miaixz.bus.core.center.date.format.CustomFormat; import org.miaixz.bus.core.center.date.format.FormatBuilder; import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.exception.InternalException; import org.miaixz.bus.core.xyz.LambdaKit; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.core.xyz.ZoneKit; +import java.text.ParseException; +import java.text.SimpleDateFormat; import java.time.*; import java.time.chrono.ChronoLocalDate; import java.time.chrono.ChronoLocalDateTime; @@ -41,6 +45,7 @@ import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; import java.time.temporal.UnsupportedTemporalTypeException; +import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.function.Function; @@ -84,6 +89,14 @@ public class Formatter { * 标准日期格式 {@link DateTimeFormatter}:yyyy-MM-dd */ public static final DateTimeFormatter NORM_DATE_FORMATTER = FormatBuilder.getDateTimeInstance(Fields.NORM_DATE); + /** + * 标准时间格式 {@link FormatBuilder}:HH:mm + */ + public static final FormatBuilder NORM_HOUR_MINUTE_FORMAT = FormatBuilder.getInstance(Fields.NORM_HOUR_MINUTE); + /** + * 标准日期格式 {@link DateTimeFormatter}:HH:mm + */ + public static final DateTimeFormatter NORM_HOUR_MINUTE_FORMATTER = FormatBuilder.getDateTimeInstance(Fields.NORM_HOUR_MINUTE); /** * 标准时间格式 {@link FormatBuilder}:HH:mm:ss */ @@ -124,6 +137,14 @@ public class Formatter { * 标准日期格式 {@link DateTimeFormatter}:yyyy-MM-dd HH:mm:ss,SSS */ public static final DateTimeFormatter NORM_DATETIME_COMMA_MS_FORMATTER = FormatBuilder.getDateTimeInstance(Fields.NORM_DATETIME_COMMA_MS); + /** + * 标准日期格式 {@link FormatBuilder}:MM月dd日 + */ + public static final FormatBuilder CN_MONTH_FORMAT = FormatBuilder.getInstance(Fields.CN_MONTH); + /** + * 标准日期格式 {@link DateTimeFormatter}:MM月dd日 + */ + public static final DateTimeFormatter CN_MONTH_FORMATTER = FormatBuilder.getDateTimeInstance(Fields.CN_MONTH); /** * 标准日期格式 {@link FormatBuilder}:yyyy年MM月dd日 */ @@ -148,6 +169,14 @@ public class Formatter { * 标准日期格式 {@link DateTimeFormatter}:yyyyMMdd */ public static final DateTimeFormatter PURE_DATE_FORMATTER = FormatBuilder.getDateTimeInstance(Fields.PURE_DATE); + /** + * 标准日期格式 {@link FormatBuilder}:HHmm + */ + public static final FormatBuilder PPURE_HOUR_MINUTE_FORMAT = FormatBuilder.getInstance(Fields.PURE_HOUR_MINUTE); + /** + * 标准日期格式 {@link DateTimeFormatter}:HHmm + */ + public static final DateTimeFormatter PURE_HOUR_MINUTE_FORMATTER = FormatBuilder.getDateTimeInstance(Fields.PURE_HOUR_MINUTE); /** * 标准日期格式 {@link FormatBuilder}:HHmmss */ @@ -227,6 +256,76 @@ public class Formatter { */ public static final LocalTime MAX_HMS = LocalTime.of(23, 59, 59); + + /** + * 将指定的日期转换成Unix时间戳 + * + * @param text 需要转换的日期 yyyy-MM-dd HH:mm:ss + * @return long 时间戳 + */ + public static long format(String text) { + return NORM_DATETIME_FORMAT.parse(text).getTime(); + + } + + /** + * 将Unix时间戳转换成日期 + * + * @param timestamp 时间戳 + * @return String 日期字符串 + */ + public static String format(long timestamp) { + return NORM_DATETIME_FORMAT.format(new Date(timestamp)); + } + + /** + * 将Unix时间戳转换成日期 + * + * @param timestamp 时间戳 + * @param format 格式 + * @return String 日期字符串 + */ + public static String format(long timestamp, String format) { + return new SimpleDateFormat(format).format(new Date(timestamp)); + } + + /** + * 将指定的日期转换成Unix时间戳 + * + * @param text 需要转换的日期 + * @param format 格式 + * @return long 时间戳 + */ + public static long format(String text, String format) { + try { + return new SimpleDateFormat(format).parse(text).getTime(); + } catch (ParseException e) { + throw new InternalException(e); + } + } + + /** + * 格式化日期时间 + * 格式 yyyy-MM-dd HH:mm:ss + * + * @param localDateTime 被格式化的日期 + * @return 格式化后的字符串 + */ + public static String format(LocalDateTime localDateTime) { + return format(localDateTime, Fields.NORM_DATETIME); + } + + /** + * 根据特定格式格式化日期 + * + * @param localDateTime 被格式化的日期 + * @param format 日期格式,常用格式见: {@link Fields} + * @return 格式化后的字符串 + */ + public static String format(final LocalDateTime localDateTime, final String format) { + return Formatter.format(localDateTime, format); + } + /** * 格式化日期时间为指定格式 * 如果为{@link Month},调用{@link Month#toString()} @@ -292,13 +391,31 @@ public static String format(final TemporalAccessor time, final String format) { return format(time, formatter); } + /** + * 按照给定的通配模式,格式化成相应的时间字符串 + * + * @param text 原始时间字符串 + * @param srcPattern 原始时间通配符 + * @param destPattern 格式化成的时间通配符 + * @return 格式化成功返回成功后的字符串, 失败返回"" + */ + public static String format(String text, String srcPattern, String destPattern) { + try { + SimpleDateFormat srcSdf = new SimpleDateFormat(srcPattern); + SimpleDateFormat dstSdf = new SimpleDateFormat(destPattern); + return dstSdf.format(srcSdf.parse(text)); + } catch (ParseException e) { + return Normal.EMPTY; + } + } + /** * 格式化日期时间为yyyy-MM-dd HH:mm:ss格式 * * @param time {@link LocalDateTime} * @return 格式化后的字符串 */ - public static String formatNormal(final ChronoLocalDateTime time) { + public static String format(final ChronoLocalDateTime time) { return format(time, NORM_DATETIME_FORMATTER); } @@ -308,19 +425,50 @@ public static String formatNormal(final ChronoLocalDateTime time) { * @param date {@link LocalDate} * @return 格式化后的字符串 */ - public static String formatNormal(final ChronoLocalDate date) { + public static String format(final ChronoLocalDate date) { return format(date, NORM_DATE_FORMATTER); } - /** * 格式化时间函数 * * @param dateTimeFormatter {@link DateTimeFormatter} * @return 格式化时间的函数 */ - public static Function formatFunc(final DateTimeFormatter dateTimeFormatter) { - return LambdaKit.toFunction(Almanac::format, dateTimeFormatter); + public static Function format(final DateTimeFormatter dateTimeFormatter) { + return LambdaKit.toFunction(Formatter::format, dateTimeFormatter); + } + + /** + * 创建{@link SimpleDateFormat},注意此对象非线程安全! + * 此对象默认为严格格式模式,即parse时如果格式不正确会报错。 + * + * @param pattern 表达式 + * @return {@link SimpleDateFormat} + */ + public static SimpleDateFormat newSimpleFormat(final String pattern) { + return newSimpleFormat(pattern, null, null); + } + + /** + * 创建{@link SimpleDateFormat},注意此对象非线程安全! + * 此对象默认为严格格式模式,即parse时如果格式不正确会报错。 + * + * @param pattern 表达式 + * @param locale {@link Locale},{@code null}表示默认 + * @param timeZone {@link TimeZone},{@code null}表示默认 + * @return {@link SimpleDateFormat} + */ + public static SimpleDateFormat newSimpleFormat(final String pattern, Locale locale, final TimeZone timeZone) { + if (null == locale) { + locale = Locale.getDefault(Locale.Category.FORMAT); + } + final SimpleDateFormat format = new SimpleDateFormat(pattern, locale); + if (null != timeZone) { + format.setTimeZone(timeZone); + } + format.setLenient(false); + return format; } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Modifier.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Modifier.java index 6b63a29b4a..1a8e0079fc 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Modifier.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Modifier.java @@ -25,12 +25,10 @@ ********************************************************************************/ package org.miaixz.bus.core.center.date; -import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.center.date.culture.en.Modify; import org.miaixz.bus.core.xyz.ArrayKit; import org.miaixz.bus.core.xyz.DateKit; -import java.util.Calendar; - /** * 日期修改器 * 用于实现自定义某个日期字段的调整,包括: @@ -50,23 +48,23 @@ public class Modifier { * 忽略的计算的字段 */ private static final int[] IGNORE_FIELDS = new int[]{ - Calendar.HOUR_OF_DAY, // 与HOUR同名 - Calendar.AM_PM, // 此字段单独处理,不参与计算起始和结束 - Calendar.DAY_OF_WEEK_IN_MONTH, // 不参与计算 - Calendar.DAY_OF_YEAR, // DAY_OF_MONTH体现 - Calendar.WEEK_OF_MONTH, // 特殊处理 - Calendar.WEEK_OF_YEAR // WEEK_OF_MONTH体现 + java.util.Calendar.HOUR_OF_DAY, // 与HOUR同名 + java.util.Calendar.AM_PM, // 此字段单独处理,不参与计算起始和结束 + java.util.Calendar.DAY_OF_WEEK_IN_MONTH, // 不参与计算 + java.util.Calendar.DAY_OF_YEAR, // DAY_OF_MONTH体现 + java.util.Calendar.WEEK_OF_MONTH, // 特殊处理 + java.util.Calendar.WEEK_OF_YEAR // WEEK_OF_MONTH体现 }; /** * 修改日期 * - * @param calendar {@link Calendar} + * @param calendar {@link java.util.Calendar} * @param dateField 日期字段,即保留到哪个日期字段 * @param modify 修改类型,包括舍去、四舍五入、进一等 * @return 修改后的{@link Calendar} */ - public static Calendar modify(final Calendar calendar, final int dateField, final Fields.Modify modify) { + public static java.util.Calendar modify(final java.util.Calendar calendar, final int dateField, final Modify modify) { return modify(calendar, dateField, modify, false); } @@ -75,41 +73,41 @@ public static Calendar modify(final Calendar calendar, final int dateField, fina * 可选是否归零毫秒 * *

- * 在{@link Fields.Modify#TRUNCATE}模式下,毫秒始终要归零, - * 但是在{@link Fields.Modify#CEILING}和{@link Fields.Modify#ROUND}模式下, + * 在{@link Modify#TRUNCATE}模式下,毫秒始终要归零, + * 但是在{@link Modify#CEILING}和{@link Modify#ROUND}模式下, * 有时候由于毫秒部分必须为0(如MySQL数据库中),因此在此加上选项。 *

* - * @param calendar {@link Calendar} + * @param calendar {@link java.util.Calendar} * @param dateField 日期字段,即保留到哪个日期字段 * @param modify 修改类型,包括舍去、四舍五入、进一等 * @param truncateMillisecond 是否归零毫秒 * @return 修改后的{@link Calendar} */ - public static Calendar modify(final Calendar calendar, final int dateField, final Fields.Modify modify, final boolean truncateMillisecond) { + public static java.util.Calendar modify(final java.util.Calendar calendar, final int dateField, final Modify modify, final boolean truncateMillisecond) { // AM_PM上下午特殊处理 - if (Calendar.AM_PM == dateField) { + if (java.util.Calendar.AM_PM == dateField) { final boolean isAM = DateKit.isAM(calendar); switch (modify) { case TRUNCATE: - calendar.set(Calendar.HOUR_OF_DAY, isAM ? 0 : 12); + calendar.set(java.util.Calendar.HOUR_OF_DAY, isAM ? 0 : 12); break; case CEILING: - calendar.set(Calendar.HOUR_OF_DAY, isAM ? 11 : 23); + calendar.set(java.util.Calendar.HOUR_OF_DAY, isAM ? 11 : 23); break; case ROUND: final int min = isAM ? 0 : 12; final int max = isAM ? 11 : 23; final int href = (max - min) / 2 + 1; - final int value = calendar.get(Calendar.HOUR_OF_DAY); - calendar.set(Calendar.HOUR_OF_DAY, (value < href) ? min : max); + final int value = calendar.get(java.util.Calendar.HOUR_OF_DAY); + calendar.set(java.util.Calendar.HOUR_OF_DAY, (value < href) ? min : max); break; } // 处理下一级别字段 return modify(calendar, dateField + 1, modify); } - final int endField = truncateMillisecond ? Calendar.SECOND : Calendar.MILLISECOND; + final int endField = truncateMillisecond ? java.util.Calendar.SECOND : java.util.Calendar.MILLISECOND; // 循环处理各级字段,精确到毫秒字段 for (int i = dateField + 1; i <= endField; i++) { if (ArrayKit.contains(IGNORE_FIELDS, i)) { @@ -118,13 +116,13 @@ public static Calendar modify(final Calendar calendar, final int dateField, fina } // 在计算本周的起始和结束日时,月相关的字段忽略。 - if (Calendar.WEEK_OF_MONTH == dateField || Calendar.WEEK_OF_YEAR == dateField) { - if (Calendar.DAY_OF_MONTH == i) { + if (java.util.Calendar.WEEK_OF_MONTH == dateField || java.util.Calendar.WEEK_OF_YEAR == dateField) { + if (java.util.Calendar.DAY_OF_MONTH == i) { continue; } } else { // 其它情况忽略周相关字段计算 - if (Calendar.DAY_OF_WEEK == i) { + if (java.util.Calendar.DAY_OF_WEEK == i) { continue; } } @@ -133,7 +131,7 @@ public static Calendar modify(final Calendar calendar, final int dateField, fina } if (truncateMillisecond) { - calendar.set(Calendar.MILLISECOND, 0); + calendar.set(java.util.Calendar.MILLISECOND, 0); } return calendar; @@ -142,28 +140,28 @@ public static Calendar modify(final Calendar calendar, final int dateField, fina /** * 修改日期字段值 * - * @param calendar {@link Calendar} - * @param field 字段,见{@link Calendar} - * @param modify {@link Fields.Modify} + * @param calendar {@link java.util.Calendar} + * @param field 字段,见{@link java.util.Calendar} + * @param modify {@link Modify} */ - private static void modifyField(final Calendar calendar, int field, final Fields.Modify modify) { - if (Calendar.HOUR == field) { + private static void modifyField(final java.util.Calendar calendar, int field, final Modify modify) { + if (java.util.Calendar.HOUR == field) { // 修正小时。HOUR为12小时制,上午的结束时间为12:00,此处改为HOUR_OF_DAY: 23:59 - field = Calendar.HOUR_OF_DAY; + field = java.util.Calendar.HOUR_OF_DAY; } switch (modify) { case TRUNCATE: - calendar.set(field, Calendars.getBeginValue(calendar, field)); + calendar.set(field, Calendar.getBeginValue(calendar, field)); break; case CEILING: - calendar.set(field, Calendars.getEndValue(calendar, field)); + calendar.set(field, Calendar.getEndValue(calendar, field)); break; case ROUND: - final int min = Calendars.getBeginValue(calendar, field); - final int max = Calendars.getEndValue(calendar, field); + final int min = Calendar.getBeginValue(calendar, field); + final int max = Calendar.getEndValue(calendar, field); final int href; - if (Calendar.DAY_OF_WEEK == field) { + if (java.util.Calendar.DAY_OF_WEEK == field) { // 星期特殊处理,假设周一是第一天,中间的为周四 href = (min + 3) % 7; } else { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Resolver.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Resolver.java index ebd16f7578..3f73148c1e 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Resolver.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Resolver.java @@ -26,12 +26,21 @@ package org.miaixz.bus.core.center.date; import org.miaixz.bus.core.center.date.format.CustomFormat; +import org.miaixz.bus.core.center.date.format.FormatBuilder; +import org.miaixz.bus.core.center.date.format.parser.PositionDateParser; import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.lang.Symbol; +import org.miaixz.bus.core.lang.exception.DateException; +import org.miaixz.bus.core.text.CharsBacker; import org.miaixz.bus.core.xyz.StringKit; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Locale; /** * 日期解析 @@ -41,6 +50,93 @@ */ public class Resolver extends Converter { + + /** + * 构建DateTime对象 + * + * @param dateStr Date字符串 + * @param dateFormat 格式化器 {@link SimpleDateFormat} + * @return DateTime对象 + */ + public static DateTime parse(final CharSequence dateStr, final DateFormat dateFormat) { + return new DateTime(dateStr, dateFormat); + } + + /** + * 构建DateTime对象 + * + * @param dateStr Date字符串 + * @param parser 格式化器,{@link FormatBuilder} + * @return DateTime对象 + */ + public static DateTime parse(final CharSequence dateStr, final PositionDateParser parser) { + return new DateTime(dateStr, parser); + } + + /** + * 构建DateTime对象 + * + * @param dateStr Date字符串 + * @param parser 格式化器,{@link FormatBuilder} + * @param lenient 是否宽容模式 + * @return DateTime对象 + */ + public static DateTime parse(final CharSequence dateStr, final PositionDateParser parser, final boolean lenient) { + return new DateTime(dateStr, parser, lenient); + } + + /** + * 构建DateTime对象 + * + * @param dateStr Date字符串 + * @param formatter 格式化器,{@link DateTimeFormatter} + * @return DateTime对象 + */ + public static DateTime parse(final CharSequence dateStr, final DateTimeFormatter formatter) { + return new DateTime(dateStr, formatter); + } + + /** + * 将特定格式的日期转换为Date对象 + * + * @param dateStr 特定格式的日期 + * @param format 格式,例如yyyy-MM-dd + * @return 日期对象 + */ + public static DateTime parse(final CharSequence dateStr, final String format) { + return new DateTime(dateStr, format); + } + + /** + * 将特定格式的日期转换为Date对象 + * + * @param dateStr 特定格式的日期 + * @param format 格式,例如yyyy-MM-dd + * @param locale 区域信息 + * @return 日期对象 + */ + public static DateTime parse(final CharSequence dateStr, final String format, final Locale locale) { + if (CustomFormat.isCustomFormat(format)) { + // 自定义格式化器忽略Locale + return new DateTime(CustomFormat.parse(dateStr, format)); + } + return new DateTime(dateStr, newSimpleFormat(format, locale, null)); + } + + /** + * 通过给定的日期格式解析日期时间字符串 + * 传入的日期格式会逐个尝试,直到解析成功,返回{@link DateTime}对象,否则抛出{@link DateException}异常 + * + * @param text 日期时间字符串,非空 + * @param parsePatterns 需要尝试的日期时间格式数组,非空, 见SimpleDateFormat + * @return 解析后的Date + * @throws IllegalArgumentException if the date string or pattern array is null + * @throws DateException if none of the date patterns were suitable + */ + public static DateTime parse(final String text, final String... parsePatterns) throws DateException { + return date(Calendar.parseByPatterns(text, parsePatterns)); + } + /** * 解析日期时间字符串为{@link LocalDateTime} * @@ -54,7 +150,7 @@ public static LocalDateTime parseTime(CharSequence text, final String format) { } if (CustomFormat.isCustomFormat(format)) { - return of(CustomFormat.parse(text, format)); + return of(CustomFormat.parse(text, format).toInstant()); } DateTimeFormatter formatter = null; @@ -155,4 +251,67 @@ public static LocalDateTime parseTimeByISO(final CharSequence text) { } } + /** + * 标准化日期,默认处理以空格区分的日期时间格式,空格前为日期,空格后为时间: + * 将以下字符替换为"-" + * + *
+     * "."
+     * "/"
+     * "年"
+     * "月"
+     * 
+ *

+ * 将以下字符去除 + * + *

+     * "日"
+     * 
+ *

+ * 将以下字符替换为":" + * + *

+     * "时"
+     * "分"
+     * "秒"
+     * 
+ *

+ * 当末位是":"时去除之(不存在毫秒时) + * + * @param dateStr 日期时间字符串 + * @return 格式化后的日期字符串 + */ + public static String normalize(final CharSequence dateStr) { + if (StringKit.isBlank(dateStr)) { + return StringKit.toString(dateStr); + } + + // 日期时间分开处理 + final List dateAndTime = CharsBacker.splitTrim(dateStr, Symbol.SPACE); + final int size = dateAndTime.size(); + if (size < 1 || size > 2) { + // 非可被标准处理的格式 + return StringKit.toString(dateStr); + } + + final StringBuilder builder = StringKit.builder(); + + // 日期部分("\"、"/"、"."、"年"、"月"都替换为"-") + String datePart = dateAndTime.get(0).replaceAll("[/.年月]", Symbol.MINUS); + datePart = StringKit.removeSuffix(datePart, "日"); + builder.append(datePart); + + // 时间部分 + if (size == 2) { + builder.append(Symbol.C_SPACE); + String timePart = dateAndTime.get(1).replaceAll("[时分秒]", Symbol.COLON); + timePart = StringKit.removeSuffix(timePart, Symbol.COLON); + //将ISO8601中的逗号替换为. + timePart = timePart.replace(Symbol.C_COMMA, '.'); + builder.append(timePart); + } + + return builder.toString(); + } + } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Zodiac.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/Zodiac.java deleted file mode 100644 index 8835537965..0000000000 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/Zodiac.java +++ /dev/null @@ -1,139 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.core.center.date; - -import org.miaixz.bus.core.lang.Assert; -import org.miaixz.bus.core.lang.Fields; -import org.miaixz.bus.core.xyz.DateKit; - -import java.util.Calendar; -import java.util.Date; - -/** - * 星座 来自:https://blog.csdn.net/u010758605/article/details/48317881 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class Zodiac { - - /** - * 星座分隔时间日 - */ - private static final int[] DAY_ARR = new int[]{20, 19, 21, 20, 21, 22, 23, 23, 23, 24, 23, 22}; - /** - * 星座 - */ - private static final String[] ZODIACS = new String[]{"摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"}; - private static final String[] CHINESE_ZODIACS = new String[]{"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"}; - - /** - * 通过生日计算星座 - * - * @param date 出生日期 - * @return 星座名 - */ - public static String getZodiac(final Date date) { - return getZodiac(DateKit.calendar(date)); - } - - /** - * 通过生日计算星座 - * - * @param calendar 出生日期 - * @return 星座名 - */ - public static String getZodiac(final Calendar calendar) { - if (null == calendar) { - return null; - } - return getZodiac(calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); - } - - /** - * 通过生日计算星座 - * - * @param month 月,从0开始计数 - * @param day 天 - * @return 星座名 - */ - public static String getZodiac(final Fields.Month month, final int day) { - return getZodiac(month.getValue(), day); - } - - /** - * 通过生日计算星座 - * - * @param month 月,从0开始计数,见{@link Fields.Month#getValue()} - * @param day 天 - * @return 星座名 - */ - public static String getZodiac(final int month, final int day) { - Assert.checkBetween(month, - Fields.Month.JANUARY.getValue(), - Fields.Month.DECEMBER.getValue(), - "Unsupported month value, must be [0,12]"); - // 在分隔日前为前一个星座,否则为后一个星座 - return day < DAY_ARR[month] ? ZODIACS[month] : ZODIACS[month + 1]; - } - - /** - * 通过生日计算生肖,只计算1900年后出生的人 - * - * @param date 出生日期(年需农历) - * @return 星座名 - */ - public static String getChineseZodiac(final Date date) { - return getChineseZodiac(DateKit.calendar(date)); - } - - /** - * 通过生日计算生肖,只计算1900年后出生的人 - * - * @param calendar 出生日期(年需农历) - * @return 星座名 - */ - public static String getChineseZodiac(final Calendar calendar) { - if (null == calendar) { - return null; - } - return getChineseZodiac(calendar.get(Calendar.YEAR)); - } - - /** - * 计算生肖,只计算1900年后出生的人 - * - * @param year 农历年 - * @return 生肖名 - */ - public static String getChineseZodiac(final int year) { - if (year < 1900) { - return null; - } - return CHINESE_ZODIACS[(year - 1900) % CHINESE_ZODIACS.length]; - } - -} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ChineseDate.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ChineseDate.java deleted file mode 100644 index 9d2b4f579d..0000000000 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ChineseDate.java +++ /dev/null @@ -1,531 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.core.center.date.chinese; - -import org.miaixz.bus.core.center.date.Calendars; -import org.miaixz.bus.core.center.date.Resolver; -import org.miaixz.bus.core.lang.Assert; -import org.miaixz.bus.core.math.ChineseNumberFormatter; -import org.miaixz.bus.core.xyz.DateKit; -import org.miaixz.bus.core.xyz.StringKit; - -import java.time.LocalDate; -import java.util.Calendar; -import java.util.Date; -import java.util.Objects; - -/** - * 农历日期工具,最大支持到2099年,支持: - * - *

    - *
  • 通过公历日期构造获取对应农历
  • - *
  • 通过农历日期直接构造
  • - *
- *

- * 规范参考:GB/T 33661-2017 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class ChineseDate { - - //农历年 - private final int year; - //农历月,润N月这个值就是N+1,其他月按照显示月份赋值 - private final int month; - // 当前月份是否闰月 - private final boolean isLeapMonth; - //农历日 - private final int day; - - //公历年 - private final int gyear; - //公历月,从1开始计数 - private final int gmonthBase1; - //公历日 - private final int gday; - - /** - * 通过公历日期构造 - * - * @param date 公历日期 - */ - public ChineseDate(final Date date) { - this(Resolver.ofDate(Assert.notNull(date.toInstant()))); - } - - /** - * 通过公历日期构造 - * - * @param localDate 公历日期 - */ - public ChineseDate(final LocalDate localDate) { - // 公历 - gyear = localDate.getYear(); - gmonthBase1 = localDate.getMonthValue(); - gday = localDate.getDayOfMonth(); - - // 求出和1900年1月31日相差的天数 - int offset = (int) (localDate.toEpochDay() - LunarInfo.BASE_DAY); - - // 计算农历年份 - // 用offset减去每农历年的天数,计算当天是农历第几天,offset是当年的第几天 - int daysOfYear; - int iYear; - for (iYear = LunarInfo.BASE_YEAR; iYear <= LunarInfo.MAX_YEAR; iYear++) { - daysOfYear = LunarInfo.yearDays(iYear); - if (offset < daysOfYear) { - break; - } - offset -= daysOfYear; - } - - year = iYear; - // 计算农历月份 - final int leapMonth = LunarInfo.leapMonth(iYear); // 闰哪个月,1-12 - // 用当年的天数offset,逐个减去每月(农历)的天数,求出当天是本月的第几天 - int month; - int daysOfMonth; - boolean hasLeapMonth = false; - for (month = 1; month < 13; month++) { - // 闰月,如润的是五月,则5表示五月,6表示润五月 - if (leapMonth > 0 && month == (leapMonth + 1)) { - daysOfMonth = LunarInfo.leapDays(year); - hasLeapMonth = true; - } else { - // 普通月,当前面的月份存在闰月时,普通月份要-1,递补闰月的数字 - // 如2月是闰月,此时3月实际是第四个月 - daysOfMonth = LunarInfo.monthDays(year, hasLeapMonth ? month - 1 : month); - } - - if (offset < daysOfMonth) { - // offset不足月,结束 - break; - } - offset -= daysOfMonth; - } - - this.isLeapMonth = leapMonth > 0 && (month == (leapMonth + 1)); - if (hasLeapMonth && !this.isLeapMonth) { - // 当前月份前有闰月,则月份显示要-1,除非当前月份就是润月 - month--; - } - this.month = month; - this.day = offset + 1; - } - - /** - * 构造方法传入日期 - * 此方法自动判断闰月,如果chineseMonth为本年的闰月,则按照闰月计算 - * - * @param chineseYear 农历年 - * @param chineseMonth 农历月,1表示一月(正月) - * @param chineseDay 农历日,1表示初一 - */ - public ChineseDate(final int chineseYear, final int chineseMonth, final int chineseDay) { - this(chineseYear, chineseMonth, chineseDay, chineseMonth == LunarInfo.leapMonth(chineseYear)); - } - - /** - * 构造方法传入日期 - * 通过isLeapMonth参数区分是否闰月,如五月是闰月,当isLeapMonth为{@code true}时,表示润五月,{@code false}表示五月 - * - * @param chineseYear 农历年 - * @param chineseMonth 农历月,1表示一月(正月),如果isLeapMonth为{@code true},1表示润一月 - * @param chineseDay 农历日,1表示初一 - * @param isLeapMonth 当前月份是否闰月 - */ - public ChineseDate(final int chineseYear, final int chineseMonth, final int chineseDay, boolean isLeapMonth) { - if (chineseMonth != LunarInfo.leapMonth(chineseYear)) { - // 用户传入的月份可能非闰月,此时此参数无效。 - isLeapMonth = false; - } - - this.day = chineseDay; - // 当月是闰月的后边的月定义为闰月,如润的是五月,则5表示五月,6表示润五月 - this.isLeapMonth = isLeapMonth; - // 闰月时,农历月份+1,如6表示润五月 - this.month = isLeapMonth ? chineseMonth + 1 : chineseMonth; - this.year = chineseYear; - - final org.miaixz.bus.core.center.date.DateTime dateTime = lunar2solar(chineseYear, chineseMonth, chineseDay, isLeapMonth); - if (null != dateTime) { - //初始化公历年 - this.gday = dateTime.dayOfMonth(); - //初始化公历月 - this.gmonthBase1 = dateTime.month() + 1; - //初始化公历日 - this.gyear = dateTime.year(); - } else { - //初始化公历年 - this.gday = -1; - //初始化公历月 - this.gmonthBase1 = -1; - //初始化公历日 - this.gyear = -1; - } - } - - /** - * 获得农历年份 - * - * @return 返回农历年份 - */ - public int getChineseYear() { - return this.year; - } - - /** - * 获取公历的年 - * - * @return 公历年 - */ - public int getGregorianYear() { - return this.gyear; - } - - /** - * 获取农历的月,从1开始计数 - * 此方法返回实际的月序号,如一月是闰月,则一月返回1,润一月返回2 - * - * @return 农历的月 - */ - public int getMonth() { - return this.month; - } - - /** - * 获取公历的月,从1开始计数 - * - * @return 公历月 - */ - public int getGregorianMonthBase1() { - return this.gmonthBase1; - } - - /** - * 获取公历的月,从0开始计数 - * - * @return 公历月 - */ - public int getGregorianMonth() { - return this.gmonthBase1 - 1; - } - - /** - * 当前农历月份是否为闰月 - * - * @return 是否为闰月 - */ - public boolean isLeapMonth() { - return this.isLeapMonth; - } - - - /** - * 获得农历月份(中文,例如二月,十二月,或者润一月) - * - * @return 返回农历月份 - */ - public String getChineseMonth() { - return getChineseMonth(false); - } - - /** - * 获得农历月称呼(中文,例如二月,腊月,或者润正月) - * - * @return 返回农历月份称呼 - */ - public String getChineseMonthName() { - return getChineseMonth(true); - } - - /** - * 获得农历月份(中文,例如二月,十二月,或者润一月) - * - * @param isTraditional 是否传统表示,例如一月传统表示为正月 - * @return 返回农历月份 - */ - public String getChineseMonth(final boolean isTraditional) { - return ChineseMonth.getChineseMonthName(isLeapMonth(), - isLeapMonth() ? this.month - 1 : this.month, isTraditional); - } - - /** - * 获取农历的日,从1开始计数 - * - * @return 农历的日,从1开始计数 - */ - public int getDay() { - return this.day; - } - - /** - * 获取公历的日 - * - * @return 公历日 - */ - public int getGregorianDay() { - return this.gday; - } - - /** - * 获得农历日 - * - * @return 获得农历日 - */ - public String getChineseDay() { - final String[] chineseTen = {"初", "十", "廿", "卅"}; - final int n = (day % 10 == 0) ? 9 : (day % 10 - 1); - if (day > 30) { - return ""; - } - switch (day) { - case 10: - return "初十"; - case 20: - return "二十"; - case 30: - return "三十"; - default: - return chineseTen[day / 10] + ChineseNumberFormatter.of().format(n + 1); - } - } - - /** - * 获取公历的Date - * - * @return 公历Date - */ - public Date getGregorianDate() { - return DateKit.date(getGregorianCalendar()); - } - - /** - * 获取公历的Calendar - * - * @return 公历Calendar - */ - public Calendar getGregorianCalendar() { - final Calendar calendar = Calendars.calendar(); - //noinspection MagicConstant - calendar.set(this.gyear, getGregorianMonth(), this.gday, 0, 0, 0); - return calendar; - } - - /** - * 获得节日,闰月不计入节日中 - * - * @return 获得农历节日 - */ - public String getFestivals() { - return StringKit.join(",", LunarFestival.getFestivals(this.year, this.month, day)); - } - - /** - * 获得年份生肖 - * - * @return 获得年份生肖 - */ - public String getChineseZodiac() { - return org.miaixz.bus.core.center.date.Zodiac.getChineseZodiac(this.year); - } - - - /** - * 获得年的天干地支 - * - * @return 获得天干地支 - */ - public String getCyclical() { - return GanZhi.getGanzhiOfYear(this.year); - } - - /** - * 获得节气 - * - * @return 获得节气 - */ - public String getTerm() { - return SolarTerms.getTerm(gyear, gmonthBase1, gday); - } - - /** - * 转换为标准的日期格式来表示农历日期 - * 例如2020-01-13 如果存在闰月,显示闰月月份,如润二月显示2 - * - * @return 标准的日期格式 - */ - public String toStringNormal() { - return String.format("%04d-%02d-%02d", this.year, - isLeapMonth() ? this.month - 1 : this.month, this.day); - } - - @Override - public String toString() { - return toString(ChineseDateFormat.GXSS); - } - - /** - * 获取标准化农历日期 - * 支持格式 - *

    - *
  1. {@link ChineseDateFormat#GSS} 干支纪年 数序纪月 数序纪日
  2. - *
  3. {@link ChineseDateFormat#XSS} 生肖纪年 数序纪月 数序纪日
  4. - *
  5. {@link ChineseDateFormat#GXSS} 干支生肖纪年 数序纪月(传统表示) 数序纪日日
  6. - *
  7. {@link ChineseDateFormat#GSG} 干支纪年 数序纪月 干支纪日
  8. - *
  9. {@link ChineseDateFormat#GGG} 干支纪年 干支纪月 干支纪日
  10. - *
  11. {@link ChineseDateFormat#MIX} 农历年年首所在的公历年份 干支纪年 数序纪月 数序纪日
  12. - *
- * - * @param format 选择输出的标准格式 - * @return 获取的标准化农历日期 - */ - public String toString(ChineseDateFormat format) { - if (null == format) { - format = ChineseDateFormat.MIX; - } - - final int year = this.year; - CharSequence dateTemplate = "农历{}年{}{}"; - String normalizedYear = GanZhi.getGanzhiOfYear(year); - String normalizedMonth = getChineseMonth(); - String normalizedDay = getChineseDay(); - switch (format) { - case GXSS: - dateTemplate = "农历{}" + getChineseZodiac() + "年{}{}"; - normalizedMonth = getChineseMonthName(); - break; - case XSS: - normalizedYear = getChineseZodiac(); - break; - case GSG: - dateTemplate = "农历{}年{}{}日"; - normalizedDay = GanZhi.getGanzhiOfDay(this.gyear, this.gmonthBase1, this.gday); - break; - case GGG: - dateTemplate = "农历{}年{}月{}日"; - normalizedMonth = GanZhi.getGanzhiOfMonth(this.gyear, this.gmonthBase1, this.gday); - normalizedDay = GanZhi.getGanzhiOfDay(this.gyear, this.gmonthBase1, this.gday); - break; - case MIX: - //根据选择的格式返回不同标准化日期输出,默认为Mix - dateTemplate = "公元" + this.year + "年农历{}年{}{}"; - case GSS: - break; - default: - throw new IllegalArgumentException("Unsupported format: " + format); - } - - return StringKit.format(dateTemplate, - normalizedYear, - normalizedMonth, - normalizedDay); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final ChineseDate that = (ChineseDate) o; - return year == that.year && month == that.month && day == that.day && isLeapMonth == that.isLeapMonth; - } - - @Override - public int hashCode() { - return Objects.hash(year, month, day, isLeapMonth); - } - - /** - * 这里同步处理年月日的天干地支信息 - * - * @param year 公历年 - * @param month 公历月,从1开始 - * @param day 公历日 - * @return 天干地支信息 - */ - private String cyclicalm(final int year, final int month, final int day) { - return StringKit.format("{}年{}月{}日", - GanZhi.getGanzhiOfYear(this.year), - GanZhi.getGanzhiOfMonth(year, month, day), - GanZhi.getGanzhiOfDay(year, month, day)); - } - - /** - * 通过农历年月日信息 返回公历信息 提供给构造函数 - * - * @param chineseYear 农历年 - * @param chineseMonth 农历月 - * @param chineseDay 农历日 - * @param isLeapMonth 传入的月是不是闰月 - * @return 公历信息 - */ - private org.miaixz.bus.core.center.date.DateTime lunar2solar(final int chineseYear, final int chineseMonth, final int chineseDay, final boolean isLeapMonth) { - //超出了最大极限值 - if ((chineseYear == 2100 && chineseMonth == 12 && chineseDay > 1) || - (chineseYear == LunarInfo.BASE_YEAR && chineseMonth == 1 && chineseDay < 31)) { - return null; - } - final int day = LunarInfo.monthDays(chineseYear, chineseMonth); - int _day = day; - if (isLeapMonth) { - _day = LunarInfo.leapDays(chineseYear); - } - //参数合法性效验 - if (chineseYear < LunarInfo.BASE_YEAR || chineseYear > 2100 || chineseDay > _day) { - return null; - } - //计算农历的时间差 - int offset = 0; - for (int i = LunarInfo.BASE_YEAR; i < chineseYear; i++) { - offset += LunarInfo.yearDays(i); - } - int leap; - boolean isAdd = false; - for (int i = 1; i < chineseMonth; i++) { - leap = LunarInfo.leapMonth(chineseYear); - if (!isAdd) {//处理闰月 - if (leap <= i && leap > 0) { - offset += LunarInfo.leapDays(chineseYear); - isAdd = true; - } - } - offset += LunarInfo.monthDays(chineseYear, i); - } - //转换闰月农历 需补充该年闰月的前一个月的时差 - if (isLeapMonth) { - offset += day; - } - //1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点) -2203804800000 - return DateKit.date(((offset + chineseDay - 31) * 86400000L) - 2203804800000L); - } - - -} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ChineseMonth.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ChineseMonth.java deleted file mode 100644 index 2b1d6e8fd0..0000000000 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ChineseMonth.java +++ /dev/null @@ -1,65 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.core.center.date.chinese; - -/** - * 农历月份表示 - * 规范参考:GB/T 33661-2017 的6.2 农历月的命名法。 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class ChineseMonth { - - private static final String[] MONTH_NAME = {"正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"}; - private static final String[] MONTH_NAME_TRADITIONAL = {"正", "二", "三", "四", "五", "六", "七", "八", "九", "寒", "冬", "腊"}; - - /** - * 当前农历月份是否为闰月 - * - * @param year 农历年 - * @param month 农历月 - * @return 是否为闰月 - */ - public static boolean isLeapMonth(final int year, final int month) { - return month == LunarInfo.leapMonth(year); - } - - /** - * 获得农历月称呼 - * 当为传统表示时,表示为二月,腊月,或者润正月等 - * 当为非传统表示时,二月,十二月,或者润一月等 - * - * @param isLeapMonth 是否闰月 - * @param month 月份,从1开始,如果是闰月,应传入需要显示的月份 - * @param isTraditional 是否传统表示,例如一月传统表示为正月 - * @return 返回农历月份称呼 - */ - public static String getChineseMonthName(final boolean isLeapMonth, final int month, final boolean isTraditional) { - return (isLeapMonth ? "闰" : "") + (isTraditional ? MONTH_NAME_TRADITIONAL : MONTH_NAME)[month - 1] + "月"; - } - -} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/GanZhi.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/GanZhi.java deleted file mode 100644 index 00fd033f43..0000000000 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/GanZhi.java +++ /dev/null @@ -1,104 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.core.center.date.chinese; - -import java.time.LocalDate; - -/** - * 天干地支类 - * 天干地支,简称为干支 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class GanZhi { - - /** - * 十天干:甲(jiǎ)、乙(yǐ)、丙(bǐng)、丁(dīng)、戊(wù)、己(jǐ)、庚(gēng)、辛(xīn)、壬(rén)、癸(guǐ) - * 十二地支:子(zǐ)、丑(chǒu)、寅(yín)、卯(mǎo)、辰(chén)、巳(sì)、午(wǔ)、未(wèi)、申(shēn)、酉(yǒu)、戌(xū)、亥(hài) - * 十二地支对应十二生肖:子-鼠,丑-牛,寅-虎,卯-兔,辰-龙,巳-蛇, 午-马,未-羊,申-猴,酉-鸡,戌-狗,亥-猪 - * - * @see 天干地支:简称,干支 - */ - private static final String[] GAN = new String[]{"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}; - private static final String[] ZHI = new String[]{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}; - - /** - * 传入 月日的offset 传回干支, 0=甲子 - * - * @param num 月日的offset - * @return 干支 - */ - public static String cyclicalm(final int num) { - return (GAN[num % 10] + ZHI[num % 12]); - } - - /** - * 传入年传回干支 - * - * @param year 农历年 - * @return 干支 - */ - public static String getGanzhiOfYear(final int year) { - // 1864年(1900 - 36)是甲子年,用于计算基准的干支年 - return cyclicalm(year - org.miaixz.bus.core.center.date.chinese.LunarInfo.BASE_YEAR + 36); - } - - /** - * 获取干支月 - * - * @param year 公历年 - * @param month 公历月,从1开始 - * @param day 公历日 - * @return 干支月 - */ - public static String getGanzhiOfMonth(final int year, final int month, final int day) { - // 返回当月「节」为几日开始 - final int firstNode = org.miaixz.bus.core.center.date.chinese.SolarTerms.getTerm(year, (month * 2 - 1)); - // 依据12节气修正干支月 - int monthOffset = (year - org.miaixz.bus.core.center.date.chinese.LunarInfo.BASE_YEAR) * 12 + month + 11; - if (day >= firstNode) { - monthOffset++; - } - return cyclicalm(monthOffset); - } - - /** - * 获取干支日 - * - * @param year 公历年 - * @param monthBase1 公历月,从1开始 - * @param day 公历日 - * @return 干支 - */ - public static String getGanzhiOfDay(final int year, final int monthBase1, final int day) { - // 与1970-01-01相差天数,不包括当天 - final long days = LocalDate.of(year, monthBase1, day).toEpochDay() - 1; - // 1899-12-21是农历1899年腊月甲子日 41:相差1900-01-31有41天 - return cyclicalm((int) (days - org.miaixz.bus.core.center.date.chinese.LunarInfo.BASE_DAY + 41)); - } - -} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/LunarFestival.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/LunarFestival.java deleted file mode 100644 index 6fd8926a2a..0000000000 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/LunarFestival.java +++ /dev/null @@ -1,143 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.core.center.date.chinese; - -import org.miaixz.bus.core.center.map.TableMap; -import org.miaixz.bus.core.xyz.MapKit; - -import java.util.List; -import java.util.Map; - -/** - * 节假日(农历)封装 - * 由于 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class LunarFestival { - - // 农历节日 - // 来自:https://baike.baidu.com/item/%E4%B8%AD%E5%9B%BD%E4%BC%A0%E7%BB%9F%E8%8A%82%E6%97%A5/396100 - private static final TableMap, String> L_FTV = new TableMap<>(16); - - static { - // 节日 - L_FTV.put(MapKit.entry(1, 1), "春节"); - L_FTV.put(MapKit.entry(1, 2), "犬日"); - L_FTV.put(MapKit.entry(1, 3), "猪日"); - L_FTV.put(MapKit.entry(1, 4), "羊日"); - L_FTV.put(MapKit.entry(1, 5), "牛日 破五日"); - L_FTV.put(MapKit.entry(1, 6), "马日 送穷日"); - L_FTV.put(MapKit.entry(1, 7), "人日 人胜节"); - L_FTV.put(MapKit.entry(1, 8), "谷日 八仙日"); - L_FTV.put(MapKit.entry(1, 9), "天日 九皇会"); - L_FTV.put(MapKit.entry(1, 10), "地日 石头生日"); - L_FTV.put(MapKit.entry(1, 12), "火日 老鼠娶媳妇日"); - L_FTV.put(MapKit.entry(1, 13), "上(试)灯日 关公升天日"); - L_FTV.put(MapKit.entry(1, 15), "元宵节 上元节"); - L_FTV.put(MapKit.entry(1, 18), "落灯日"); - - // 二月 - L_FTV.put(MapKit.entry(2, 1), "中和节 太阳生日"); - L_FTV.put(MapKit.entry(2, 2), "龙头节 龙抬头"); - L_FTV.put(MapKit.entry(2, 12), "花朝节"); - L_FTV.put(MapKit.entry(2, 19), "观世音圣诞"); - - // 三月 - L_FTV.put(MapKit.entry(3, 3), "上巳节"); - - // 四月 - L_FTV.put(MapKit.entry(4, 1), "祭雹神"); - L_FTV.put(MapKit.entry(4, 4), "文殊菩萨诞辰"); - L_FTV.put(MapKit.entry(4, 8), "佛诞节"); - - // 五月 - L_FTV.put(MapKit.entry(5, 5), "端午节 端阳节"); - - // 六月 - L_FTV.put(MapKit.entry(6, 6), "晒衣节 姑姑节"); - L_FTV.put(MapKit.entry(6, 6), "天贶节"); - L_FTV.put(MapKit.entry(6, 24), "彝族火把节"); - - // 七月 - L_FTV.put(MapKit.entry(7, 7), "七夕节"); - L_FTV.put(MapKit.entry(7, 14), "鬼节(南方)"); - L_FTV.put(MapKit.entry(7, 15), "中元节"); - L_FTV.put(MapKit.entry(7, 15), "盂兰盆节 中元节"); - L_FTV.put(MapKit.entry(7, 30), "地藏节"); - - // 八月 - L_FTV.put(MapKit.entry(8, 15), "中秋节"); - - // 九月 - L_FTV.put(MapKit.entry(9, 9), "重阳节"); - - // 十月 - L_FTV.put(MapKit.entry(10, 1), "祭祖节"); - L_FTV.put(MapKit.entry(10, 15), "下元节"); - - // 十一月 - L_FTV.put(MapKit.entry(11, 17), "阿弥陀佛圣诞"); - - // 腊月 - L_FTV.put(MapKit.entry(12, 8), "腊八节"); - L_FTV.put(MapKit.entry(12, 16), "尾牙"); - L_FTV.put(MapKit.entry(12, 23), "小年"); - L_FTV.put(MapKit.entry(12, 30), "除夕"); - } - - /** - * 获得节日列表 - * - * @param year 年 - * @param month 月 - * @param day 日 - * @return 获得农历节日 - */ - public static List getFestivals(final int year, final int month, int day) { - // 春节判断,如果12月是小月,则29为除夕,否则30为除夕 - if (12 == month && 29 == day) { - if (29 == LunarInfo.monthDays(year, month)) { - day++; - } - } - - return getFestivals(month, day); - } - - /** - * 获得节日列表,此方法无法判断月是否为大月或小月 - * - * @param month 月 - * @param day 日 - * @return 获得农历节日 - */ - public static List getFestivals(final int month, final int day) { - return L_FTV.getValues(MapKit.entry(month, day)); - } - -} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/LunarInfo.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/LunarInfo.java deleted file mode 100644 index 75875fa12d..0000000000 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/LunarInfo.java +++ /dev/null @@ -1,146 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.core.center.date.chinese; - -import java.time.LocalDate; - -/** - * 阴历(农历)信息 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class LunarInfo { - - /** - * 1900年 - */ - public static final int BASE_YEAR = 1900; - /** - * 1900-01-31,农历正月初一 - */ - public static final long BASE_DAY = LocalDate.of(BASE_YEAR, 1, 31).toEpochDay(); - - /** - * 此表来自:https://github.com/jjonline/calendar.js/blob/master/calendar.js - * 农历表示: - * 1. 表示当年有无闰年,有的话,为闰月的月份,没有的话,为0。 - * 2-4.为除了闰月外的正常月份是大月还是小月,1为30天,0为29天。 - * 5. 表示闰月是大月还是小月,仅当存在闰月的情况下有意义。 - * - *

需要注意的是,2057年的节气时间有误差,这个存在争议,见:https://github.com/jjonline/calendar.js/issues/11#issuecomment-607126524

- */ - private static final long[] LUNAR_CODE = new long[]{ - 0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,//1900-1909 - 0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,//1910-1919 - 0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,//1920-1929 - 0x06566, 0x0d4a0, 0x0ea50, 0x16a95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,//1930-1939 - 0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,//1940-1949 - 0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0,//1950-1959 - 0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,//1960-1969 - 0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6,//1970-1979 - 0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,//1980-1989 - 0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x05ac0, 0x0ab60, 0x096d5, 0x092e0,//1990-1999 - 0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,//2000-2009 - 0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,//2010-2019 - 0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,//2020-2029 - 0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,//2030-2039 - 0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0,//2040-2049 - 0x14b63, 0x09370, 0x049f8, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x06b20, 0x1a6c4, 0x0aae0,//2050-2059 - 0x092e0, 0x0d2e3, 0x0c960, 0x0d557, 0x0d4a0, 0x0da50, 0x05d55, 0x056a0, 0x0a6d0, 0x055d4,//2060-2069 - 0x052d0, 0x0a9b8, 0x0a950, 0x0b4a0, 0x0b6a6, 0x0ad50, 0x055a0, 0x0aba4, 0x0a5b0, 0x052b0,//2070-2079 - 0x0b273, 0x06930, 0x07337, 0x06aa0, 0x0ad50, 0x14b55, 0x04b60, 0x0a570, 0x054e4, 0x0d160,//2080-2089 - 0x0e968, 0x0d520, 0x0daa0, 0x16aa6, 0x056d0, 0x04ae0, 0x0a9d4, 0x0a2d0, 0x0d150, 0x0f252,//2090-2099 - }; - - /** - * 支持的最大年限 - */ - public static final int MAX_YEAR = BASE_YEAR + LUNAR_CODE.length - 1; - - /** - * 传回农历 y年的总天数 - * - * @param y 年 - * @return 总天数 - */ - public static int yearDays(final int y) { - int i, sum = 348; - for (i = 0x8000; i > 0x8; i >>= 1) { - if ((getCode(y) & i) != 0) { - sum += 1; - } - } - return (sum + leapDays(y)); - } - - /** - * 传回农历 y年闰月的天数,如果本年无闰月,返回0,区分大小月 - * - * @param y 农历年 - * @return 闰月的天数 - */ - public static int leapDays(final int y) { - if (leapMonth(y) != 0) { - return (getCode(y) & 0x10000) != 0 ? 30 : 29; - } - - return 0; - } - - /** - * 传回农历 y年m月的总天数,区分大小月 - * - * @param y 年 - * @param m 月 - * @return 总天数 - */ - public static int monthDays(final int y, final int m) { - return (getCode(y) & (0x10000 >> m)) == 0 ? 29 : 30; - } - - /** - * 传回农历 y年闰哪个月 1-12 , 没闰传回 0 - * 此方法会返回润N月中的N,如二月、闰二月都返回2 - * - * @param y 年 - * @return 润的月, 没闰传回 0 - */ - public static int leapMonth(final int y) { - return (int) (getCode(y) & 0xf); - } - - /** - * 获取对应年的农历信息 - * - * @param year 年 - * @return 农历信息 - */ - private static long getCode(final int year) { - return LUNAR_CODE[year - BASE_YEAR]; - } - -} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ShiChen.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ShiChen.java deleted file mode 100644 index 48508aa9f8..0000000000 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ShiChen.java +++ /dev/null @@ -1,157 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.core.center.date.chinese; - -import org.miaixz.bus.core.center.date.Between; -import org.miaixz.bus.core.xyz.StringKit; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * 时辰转换器,支持宋以后的二十四时辰制度。 - *

本转换器提供以下功能: - *

    - *
  • 处理包含“时”、“初”或“正”后缀的时辰描述,并自动返回相应的现代时间段。 - * “初”和“正”分别对应每个时辰的前半段和后半段,而不带后缀的“时”描述则涵盖该时辰的完整时间段。
  • - *
  • 根据小时数转换为相应的时辰描述,通过{@code isAbs}参数控制是否包含“初”或“正”。
  • - *
- *

- * 异常情况: - *

    - *
  • 如果输入的时辰描述无效或不被识别,{@code toModernTime} 方法将抛出 {@code IllegalArgumentException}。
  • - *
  • 同样,如果{@code toShiChen}方法接收到无效的小时数,将返回“未知”。
  • - *
- * 示例: - *
    - *
  • {@code toModernTime("子时")} 返回的时间段从23点开始到1点结束。
  • - *
  • {@code toModernTime("子初")} 返回的时间段从23点开始到0点结束。
  • - *
  • {@code toModernTime("子正")} 返回的时间段从0点开始到1点结束。
  • - *
  • {@code toShiChen(0, false)} 返回“子正”。
  • - *
  • {@code toShiChen(0, true)} 返回“子时”。
  • - *
- * - * @author Kimi Liu - * @since Java 17+ - */ -public class ShiChen { - - private static final Map timeMap = new HashMap<>(); - private static final Map fullTimeMap = new HashMap<>(); - private static final Map hourToShiChenMap = new HashMap<>(); - private static final Map hourToShiChenAbsMap = new HashMap<>(); - - static { - // 初始化时辰对应的小时范围 - final String[] times = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}; - int hour = 23; - for (final String time : times) { - timeMap.put(time + "初", hour % 24); - timeMap.put(time + "正", (hour + 1) % 24); - fullTimeMap.put(time, new Integer[]{hour % 24, (hour + 2) % 24}); - hour += 2; - } - - // 初始化小时到时辰的映射 - hour = 23; - for (final String time : times) { - hourToShiChenMap.put(hour % 24, time + "初"); - hourToShiChenMap.put((hour + 1) % 24, time + "正"); - hourToShiChenAbsMap.put(hour % 24, time + "时"); - hourToShiChenAbsMap.put((hour + 1) % 24, time + "时"); - hour += 2; - } - } - - /** - * 将时辰描述转换为现代时间段。示例: - *
    - *
  • {@code toModernTime("子时")} 返回的时间段从23点开始到1点结束。
  • - *
  • {@code toModernTime("子初")} 返回的时间段从23点开始到0点结束。
  • - *
  • {@code toModernTime("子正")} 返回的时间段从0点开始到1点结束。
  • - *
- * - * @param shiChen 时辰描述,可以是“时”、“初”或“正”结尾。 - * @return {@link Between} 对象,表示起始和结束时间。 - * @throws IllegalArgumentException 如果输入的时辰描述无效。 - */ - public static Between toModernTime(final String shiChen) { - if (StringKit.isEmpty(shiChen)) { - throw new IllegalArgumentException("Invalid shiChen"); - } - final Integer startHour; - final Integer endHour; - final LocalDateTime start; - final LocalDateTime end; - - if (shiChen.endsWith("初") || shiChen.endsWith("正")) { - startHour = timeMap.get(shiChen); - if (startHour == null) { - throw new IllegalArgumentException("Invalid ShiChen time"); - } - endHour = (startHour + 1) % 24; - } else { - final String baseTime = shiChen.replace("时", ""); - final Integer[] hours = fullTimeMap.get(baseTime); - if (hours == null) { - throw new IllegalArgumentException("Invalid ShiChen time"); - } - startHour = hours[0]; - endHour = hours[1]; - } - - start = LocalDateTime.now().withHour(startHour).withMinute(0).withSecond(0).withNano(0); - end = (startHour > endHour) ? start.plusDays(1).withHour(endHour) : start.withHour(endHour); - - final Date startDate = Date.from(start.atZone(ZoneId.systemDefault()).toInstant()); - final Date endDate = Date.from(end.atZone(ZoneId.systemDefault()).toInstant()); - - return Between.of(startDate, endDate); - } - - /** - * 根据给定的小时数转换为对应的时辰描述。示例: - *
    - *
  • {@code toShiChen(0, false)} 返回“子正”。
  • - *
  • {@code toShiChen(0, true)} 返回“子时”。
  • - *
- * - * @param hour 小时数,应在0到23之间。 - * @param isAbs 是否返回绝对时辰描述(即包含“时”后缀),而不是“初”或“正”。 - * @return 时辰描述,如果小时数无效,则返回“未知”。 - */ - public static String toShiChen(final int hour, final boolean isAbs) { - String result = hourToShiChenAbsMap.getOrDefault(hour, "未知"); - if (!isAbs && !result.equals("未知")) { - result = hourToShiChenMap.get(hour); - } - return result; - } - -} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/SolarTerms.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/SolarTerms.java deleted file mode 100644 index e7c5bd7007..0000000000 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/SolarTerms.java +++ /dev/null @@ -1,239 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.core.center.date.chinese; - -import org.miaixz.bus.core.center.date.DateTime; -import org.miaixz.bus.core.lang.Normal; -import org.miaixz.bus.core.xyz.DateKit; -import org.miaixz.bus.core.xyz.MathKit; - -import java.time.LocalDate; -import java.util.Date; - -/** - * 24节气相关信息 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class SolarTerms { - - /** - * 1900-2100各年的24节气日期速查表 - * 此表来自:https://github.com/jjonline/calendar.js/blob/master/calendar.js - */ - private static final String[] S_TERM_INFO = new String[]{ - "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c3598082c95f8c965cc920f", - "97bd0b06bdb0722c965ce1cfcc920f", "b027097bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", - "97bcf97c359801ec95f8c965cc920f", "97bd0b06bdb0722c965ce1cfcc920f", "b027097bd097c36b0b6fc9274c91aa", - "97b6b97bd19801ec9210c965cc920e", "97bcf97c359801ec95f8c965cc920f", "97bd0b06bdb0722c965ce1cfcc920f", - "b027097bd097c36b0b6fc9274c91aa", "9778397bd19801ec9210c965cc920e", "97b6b97bd19801ec95f8c965cc920f", - "97bd09801d98082c95f8e1cfcc920f", "97bd097bd097c36b0b6fc9210c8dc2", "9778397bd197c36c9210c9274c91aa", - "97b6b97bd19801ec95f8c965cc920e", "97bd09801d98082c95f8e1cfcc920f", "97bd097bd097c36b0b6fc9210c8dc2", - "9778397bd097c36c9210c9274c91aa", "97b6b97bd19801ec95f8c965cc920e", "97bcf97c3598082c95f8e1cfcc920f", - "97bd097bd097c36b0b6fc9210c8dc2", "9778397bd097c36c9210c9274c91aa", "97b6b97bd19801ec9210c965cc920e", - "97bcf97c3598082c95f8c965cc920f", "97bd097bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", - "97b6b97bd19801ec9210c965cc920e", "97bcf97c3598082c95f8c965cc920f", "97bd097bd097c35b0b6fc920fb0722", - "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf97c359801ec95f8c965cc920f", - "97bd097bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", - "97bcf97c359801ec95f8c965cc920f", "97bd097bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", - "97b6b97bd19801ec9210c965cc920e", "97bcf97c359801ec95f8c965cc920f", "97bd097bd07f595b0b6fc920fb0722", - "9778397bd097c36b0b6fc9210c8dc2", "9778397bd19801ec9210c9274c920e", "97b6b97bd19801ec95f8c965cc920f", - "97bd07f5307f595b0b0bc920fb0722", "7f0e397bd097c36b0b6fc9210c8dc2", "9778397bd097c36c9210c9274c920e", - "97b6b97bd19801ec95f8c965cc920f", "97bd07f5307f595b0b0bc920fb0722", "7f0e397bd097c36b0b6fc9210c8dc2", - "9778397bd097c36c9210c9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bd07f1487f595b0b0bc920fb0722", - "7f0e397bd097c36b0b6fc9210c8dc2", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", - "97bcf7f1487f595b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", - "97b6b97bd19801ec9210c965cc920e", "97bcf7f1487f595b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", - "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", "97bcf7f1487f531b0b0bb0b6fb0722", - "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b97bd19801ec9210c965cc920e", - "97bcf7f1487f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", - "97b6b97bd19801ec9210c9274c920e", "97bcf7f0e47f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", - "9778397bd097c36b0b6fc9210c91aa", "97b6b97bd197c36c9210c9274c920e", "97bcf7f0e47f531b0b0bb0b6fb0722", - "7f0e397bd07f595b0b0bc920fb0722", "9778397bd097c36b0b6fc9210c8dc2", "9778397bd097c36c9210c9274c920e", - "97b6b7f0e47f531b0723b0b6fb0722", "7f0e37f5307f595b0b0bc920fb0722", "7f0e397bd097c36b0b6fc9210c8dc2", - "9778397bd097c36b0b70c9274c91aa", "97b6b7f0e47f531b0723b0b6fb0721", "7f0e37f1487f595b0b0bb0b6fb0722", - "7f0e397bd097c35b0b6fc9210c8dc2", "9778397bd097c36b0b6fc9274c91aa", "97b6b7f0e47f531b0723b0b6fb0721", - "7f0e27f1487f595b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", - "97b6b7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", - "9778397bd097c36b0b6fc9274c91aa", "97b6b7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", - "7f0e397bd097c35b0b6fc920fb0722", "9778397bd097c36b0b6fc9274c91aa", "97b6b7f0e47f531b0723b0b6fb0721", - "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "9778397bd097c36b0b6fc9274c91aa", - "97b6b7f0e47f531b0723b0787b0721", "7f0e27f0e47f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", - "9778397bd097c36b0b6fc9210c91aa", "97b6b7f0e47f149b0723b0787b0721", "7f0e27f0e47f531b0723b0b6fb0722", - "7f0e397bd07f595b0b0bc920fb0722", "9778397bd097c36b0b6fc9210c8dc2", "977837f0e37f149b0723b0787b0721", - "7f07e7f0e47f531b0723b0b6fb0722", "7f0e37f5307f595b0b0bc920fb0722", "7f0e397bd097c35b0b6fc9210c8dc2", - "977837f0e37f14998082b0787b0721", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e37f1487f595b0b0bb0b6fb0722", - "7f0e397bd097c35b0b6fc9210c8dc2", "977837f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", - "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", "977837f0e37f14998082b0787b06bd", - "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd097c35b0b6fc920fb0722", - "977837f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", - "7f0e397bd07f595b0b0bc920fb0722", "977837f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", - "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", "977837f0e37f14998082b0787b06bd", - "7f07e7f0e47f149b0723b0787b0721", "7f0e27f0e47f531b0b0bb0b6fb0722", "7f0e397bd07f595b0b0bc920fb0722", - "977837f0e37f14998082b0723b06bd", "7f07e7f0e37f149b0723b0787b0721", "7f0e27f0e47f531b0723b0b6fb0722", - "7f0e397bd07f595b0b0bc920fb0722", "977837f0e37f14898082b0723b02d5", "7ec967f0e37f14998082b0787b0721", - "7f07e7f0e47f531b0723b0b6fb0722", "7f0e37f1487f595b0b0bb0b6fb0722", "7f0e37f0e37f14898082b0723b02d5", - "7ec967f0e37f14998082b0787b0721", "7f07e7f0e47f531b0723b0b6fb0722", "7f0e37f1487f531b0b0bb0b6fb0722", - "7f0e37f0e37f14898082b0723b02d5", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", - "7f0e37f1487f531b0b0bb0b6fb0722", "7f0e37f0e37f14898082b072297c35", "7ec967f0e37f14998082b0787b06bd", - "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e37f0e37f14898082b072297c35", - "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722", - "7f0e37f0e366aa89801eb072297c35", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f149b0723b0787b0721", - "7f0e27f1487f531b0b0bb0b6fb0722", "7f0e37f0e366aa89801eb072297c35", "7ec967f0e37f14998082b0723b06bd", - "7f07e7f0e47f149b0723b0787b0721", "7f0e27f0e47f531b0723b0b6fb0722", "7f0e37f0e366aa89801eb072297c35", - "7ec967f0e37f14998082b0723b06bd", "7f07e7f0e37f14998083b0787b0721", "7f0e27f0e47f531b0723b0b6fb0722", - "7f0e37f0e366aa89801eb072297c35", "7ec967f0e37f14898082b0723b02d5", "7f07e7f0e37f14998082b0787b0721", - "7f07e7f0e47f531b0723b0b6fb0722", "7f0e36665b66aa89801e9808297c35", "665f67f0e37f14898082b0723b02d5", - "7ec967f0e37f14998082b0787b0721", "7f07e7f0e47f531b0723b0b6fb0722", "7f0e36665b66a449801e9808297c35", - "665f67f0e37f14898082b0723b02d5", "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", - "7f0e36665b66a449801e9808297c35", "665f67f0e37f14898082b072297c35", "7ec967f0e37f14998082b0787b06bd", - "7f07e7f0e47f531b0723b0b6fb0721", "7f0e26665b66a449801e9808297c35", "665f67f0e37f1489801eb072297c35", - "7ec967f0e37f14998082b0787b06bd", "7f07e7f0e47f531b0723b0b6fb0721", "7f0e27f1487f531b0b0bb0b6fb0722"}; - - /** - * 24节气 - */ - private static final String[] TERMS = { - "小寒", "大寒", "立春", "雨水", "惊蛰", "春分", - "清明", "谷雨", "立夏", "小满", "芒种", "夏至", - "小暑", "大暑", "立秋", "处暑", "白露", "秋分", - "寒露", "霜降", "立冬", "小雪", "大雪", "冬至" - }; - - /** - * 传入公历y年获得该年第n个节气的公历日期 - * - * @param y 公历年(1900-2100) - * @param n 二十四节气中的第几个节气(1~24);从n=1(小寒)算起 - * @return getTerm(1987, 3) -》4;意即1987年2月4日立春 - */ - public static int getTerm(final int y, final int n) { - if (y < 1900 || y > 2100) { - return -1; - } - if (n < 1 || n > 24) { - return -1; - } - - final String _table = S_TERM_INFO[y - 1900]; - final Integer[] _info = new Integer[6]; - for (int i = 0; i < 6; i++) { - _info[i] = Integer.parseInt(_table.substring(i * 5, 5 * (i + 1)), 16); - } - final String[] _calday = new String[24]; - for (int i = 0; i < 6; i++) { - _calday[4 * i] = _info[i].toString().substring(0, 1); - _calday[4 * i + 1] = _info[i].toString().substring(1, 3); - _calday[4 * i + 2] = _info[i].toString().substring(3, 4); - _calday[4 * i + 3] = _info[i].toString().substring(4, 6); - } - return MathKit.parseInt(_calday[n - 1]); - } - - /** - * 根据日期获取节气 - * - * @param date 日期 - * @return 返回指定日期所处的节气,若不是一个节气则返回空字符串 - */ - public static String getTerm(final Date date) { - final DateTime dt = DateKit.date(date); - return getTermInternal(dt.year(), dt.month() + 1, dt.dayOfMonth()); - } - - - /** - * 根据农历日期获取节气 - * - * @param chineseDate 农历日期 - * @return 返回指定农历日期所处的节气,若不是一个节气则返回空字符串 - */ - public static String getTerm(final ChineseDate chineseDate) { - return chineseDate.getTerm(); - } - - /** - * 根据日期获取节气 - * - * @param date 日期 - * @return 返回指定日期所处的节气,若不是一个节气则返回空字符串 - */ - public static String getTerm(final LocalDate date) { - return getTermInternal(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); - } - - /** - * 根据年月日获取节气 - * - * @param year 公历年 - * @param mouth 公历月,从1开始 - * @param day 公历日,从1开始 - * @return 返回指定年月日所处的节气,若不是一个节气则返回空字符串 - */ - public static String getTerm(final int year, final int mouth, final int day) { - return getTerm(LocalDate.of(year, mouth, day)); - } - - /** - * 根据年月日获取节气, 内部方法,不对月和日做有效校验 - * - * @param year 公历年 - * @param month 公历月,从1开始 - * @param day 公历日,从1开始 - * @return 返回指定年月日所处的节气,若不是一个节气则返回空字符串 - */ - private static String getTermInternal(final int year, final int month, final int day) { - if (year < 1900 || year > 2100) { - throw new IllegalArgumentException("只支持1900-2100之间的日期获取节气"); - } - - final String termTable = S_TERM_INFO[year - 1900]; - - // 节气速查表中每5个字符含有4个节气,通过月份直接计算偏移 - final int segment = (month + 1) / 2 - 1; - final int termInfo = Integer.parseInt(termTable.substring(segment * 5, (segment + 1) * 5), 16); - final String termInfoStr = String.valueOf(termInfo); - - final String[] segmentTable = new String[4]; - segmentTable[0] = termInfoStr.substring(0, 1); - segmentTable[1] = termInfoStr.substring(1, 3); - segmentTable[2] = termInfoStr.substring(3, 4); - segmentTable[3] = termInfoStr.substring(4, 6); - - // 奇数月份的节气在前2个,偶数月份的节气在后两个 - final int segmentOffset = (month & 1) == 1 ? 0 : 2; - - if (day == Integer.parseInt(segmentTable[segmentOffset])) { - return TERMS[segment * 4 + segmentOffset]; - } - if (day == Integer.parseInt(segmentTable[segmentOffset + 1])) { - return TERMS[segment * 4 + segmentOffset + 1]; - } - return Normal.EMPTY; - } - -} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/package-info.java deleted file mode 100644 index 1bb63d7fa8..0000000000 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** - * 农历相关类汇总,包括农历月、天干地支、农历节日、24节气等 - * 规范参考:GB/T 33661-2017 - * - * @author Kimi Liu - * @since Java 17+ - */ -package org.miaixz.bus.core.center.date.chinese; diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/NullProvider.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Culture.java similarity index 87% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/NullProvider.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Culture.java index 9e51656128..10146d36b1 100755 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/NullProvider.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Culture.java @@ -23,19 +23,26 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.provider; +package org.miaixz.bus.core.center.date.culture; + +import org.miaixz.bus.core.center.date.Almanac; /** - * 总是返回null + * 区域文化 * * @author Kimi Liu * @since Java 17+ */ -public class NullProvider extends AlwaysProvider { +public interface Culture extends Almanac { - public NullProvider() { - super(null); + /** + * 推移 + * + * @param n 推移步数 + * @return this + */ + default Culture next(int n) { + return this; } } - diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Galaxy.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Galaxy.java new file mode 100644 index 0000000000..666edaeb65 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Galaxy.java @@ -0,0 +1,665 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture; + +/** + * 寿星天文历工具 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Galaxy { + + /** + * 2π + */ + public static final double PI_2 = 2 * Math.PI; + public static final double ONE_THIRD = 1d / 3; + /** + * 1天对应的秒数 + */ + public static final int SECOND_PER_DAY = 86400; + /** + * 1弧度对应的角秒 + */ + public static final double SECOND_PER_RAD = 180 * 3600 / Math.PI; + private static final double[] NUT_B = { + 2.1824, -33.75705, 36e-6, -1720, 920, + 3.5069, 1256.66393, 11e-6, -132, 57, + 1.3375, 16799.4182, -51e-6, -23, 10, + 4.3649, -67.5141, 72e-6, 21, -9, + 0.04, -628.302, 0, -14, 0, + 2.36, 8328.691, 0, 7, 0, + 3.46, 1884.966, 0, -5, 2, + 5.44, 16833.175, 0, -4, 2, + 3.69, 25128.110, 0, -3, 0, + 3.55, 628.362, 0, 2, 0 + }; + private static final double[] DT_AT = { + -4000, 108371.7, -13036.80, 392.000, 0.0000, + -500, 17201.0, -627.82, 16.170, -0.3413, + -150, 12200.6, -346.41, 5.403, -0.1593, + 150, 9113.8, -328.13, -1.647, 0.0377, + 500, 5707.5, -391.41, 0.915, 0.3145, + 900, 2203.4, -283.45, 13.034, -0.1778, + 1300, 490.1, -57.35, 2.085, -0.0072, + 1600, 120.0, -9.81, -1.532, 0.1403, + 1700, 10.2, -0.91, 0.510, -0.0370, + 1800, 13.4, -0.72, 0.202, -0.0193, + 1830, 7.8, -1.81, 0.416, -0.0247, + 1860, 8.3, -0.13, -0.406, 0.0292, + 1880, -5.4, 0.32, -0.183, 0.0173, + 1900, -2.3, 2.06, 0.169, -0.0135, + 1920, 21.2, 1.69, -0.304, 0.0167, + 1940, 24.2, 1.22, -0.064, 0.0031, + 1960, 33.2, 0.51, 0.231, -0.0109, + 1980, 51.0, 1.29, -0.026, 0.0032, + 2000, 63.87, 0.1, 0, 0, + 2005, 64.7, 0.21, 0, 0, + 2012, 66.8, 0.22, 0, 0, + 2018, 69.0, 0.36, 0, 0, + 2028, 72.6 + }; + private static final double[] XL0 = { + 10000000000D, + 20, 578, 920, 1100, 1124, 1136, 1148, 1217, 1226, 1229, 1229, 1229, 1229, 1937, 2363, 2618, 2633, 2660, 2666, + 17534704567D, 0.00000000000, 0.00000000000, 334165646, 4.669256804, 6283.075849991, 3489428, 4.6261024, + 12566.1517000, 349706, 2.744118, 5753.384885, 341757, 2.828866, 3.523118, 313590, 3.627670, 77713.771468, + 267622, 4.418084, 7860.419392, 234269, 6.135162, 3930.209696, 132429, 0.742464, 11506.769770, 127317, 2.037097, + 529.690965, 119917, 1.109629, 1577.343542, 99025, 5.23268, 5884.92685, 90186, 2.04505, 26.29832, 85722, 3.50849, + 398.14900, 77979, 1.17883, 5223.69392, 75314, 2.53339, 5507.55324, 50526, 4.58293, 18849.22755, 49238, 4.20507, + 775.52261, 35666, 2.91954, 0.06731, 31709, 5.84902, 11790.62909, 28413, 1.89869, 796.29801, 27104, 0.31489, + 10977.07880, 24281, 0.34481, 5486.77784, 20616, 4.80647, 2544.31442, 20539, 1.86948, 5573.14280, 20226, 2.45768, + 6069.77675, 15552, 0.83306, 213.29910, 13221, 3.41118, 2942.46342, 12618, 1.08303, 20.77540, 11513, 0.64545, + 0.98032, 10285, 0.63600, 4694.00295, 10190, 0.97569, 15720.83878, 10172, 4.26680, 7.11355, 9921, 6.2099, + 2146.1654, 9761, 0.6810, 155.4204, 8580, 5.9832, 161000.6857, 8513, 1.2987, 6275.9623, 8471, 3.6708, 71430.6956, + 7964, 1.8079, 17260.1547, 7876, 3.0370, 12036.4607, 7465, 1.7551, 5088.6288, 7387, 3.5032, 3154.6871, 7355, + 4.6793, 801.8209, 6963, 0.8330, 9437.7629, 6245, 3.9776, 8827.3903, 6115, 1.8184, 7084.8968, 5696, 2.7843, + 6286.5990, 5612, 4.3869, 14143.4952, 5558, 3.4701, 6279.5527, 5199, 0.1891, 12139.5535, 5161, 1.3328, 1748.0164, + 5115, 0.2831, 5856.4777, 4900, 0.4874, 1194.4470, 4104, 5.3682, 8429.2413, 4094, 2.3985, 19651.0485, 3920, + 6.1683, 10447.3878, 3677, 6.0413, 10213.2855, 3660, 2.5696, 1059.3819, 3595, 1.7088, 2352.8662, 3557, 1.7760, + 6812.7668, 3329, 0.5931, 17789.8456, 3041, 0.4429, 83996.8473, 3005, 2.7398, 1349.8674, 2535, 3.1647, 4690.4798, + 2474, 0.2148, 3.5904, 2366, 0.4847, 8031.0923, 2357, 2.0653, 3340.6124, 2282, 5.2220, 4705.7323, 2189, 5.5559, + 553.5694, 2142, 1.4256, 16730.4637, 2109, 4.1483, 951.7184, 2030, 0.3713, 283.8593, 1992, 5.2221, 12168.0027, + 1986, 5.7747, 6309.3742, 1912, 3.8222, 23581.2582, 1889, 5.3863, 149854.4001, 1790, 2.2149, 13367.9726, 1748, + 4.5605, 135.0651, 1622, 5.9884, 11769.8537, 1508, 4.1957, 6256.7775, 1442, 4.1932, 242.7286, 1435, 3.7236, + 38.0277, 1397, 4.4014, 6681.2249, 1362, 1.8893, 7632.9433, 1250, 1.1305, 5.5229, 1205, 2.6223, 955.5997, 1200, + 1.0035, 632.7837, 1129, 0.1774, 4164.3120, 1083, 0.3273, 103.0928, 1052, 0.9387, 11926.2544, 1050, 5.3591, + 1592.5960, 1033, 6.1998, 6438.4962, 1001, 6.0291, 5746.2713, 980, 0.999, 11371.705, 980, 5.244, 27511.468, 938, + 2.624, 5760.498, 923, 0.483, 522.577, 922, 4.571, 4292.331, 905, 5.337, 6386.169, 862, 4.165, 7058.598, 841, + 3.299, 7234.794, 836, 4.539, 25132.303, 813, 6.112, 4732.031, 812, 6.271, 426.598, 801, 5.821, 28.449, 787, + 0.996, 5643.179, 776, 2.957, 23013.540, 769, 3.121, 7238.676, 758, 3.974, 11499.656, 735, 4.386, 316.392, 731, + 0.607, 11513.883, 719, 3.998, 74.782, 706, 0.323, 263.084, 676, 5.911, 90955.552, 663, 3.665, 17298.182, 653, + 5.791, 18073.705, 630, 4.717, 6836.645, 615, 1.458, 233141.314, 612, 1.075, 19804.827, 596, 3.321, 6283.009, + 596, 2.876, 6283.143, 555, 2.452, 12352.853, 541, 5.392, 419.485, 531, 0.382, 31441.678, 519, 4.065, 6208.294, + 513, 2.361, 10973.556, 494, 5.737, 9917.697, 450, 3.272, 11015.106, 449, 3.653, 206.186, 447, 2.064, 7079.374, + 435, 4.423, 5216.580, 421, 1.906, 245.832, 413, 0.921, 3738.761, 402, 0.840, 20.355, 387, 1.826, 11856.219, 379, + 2.344, 3.881, 374, 2.954, 3128.389, 370, 5.031, 536.805, 365, 1.018, 16200.773, 365, 1.083, 88860.057, 352, + 5.978, 3894.182, 352, 2.056, 244287.600, 351, 3.713, 6290.189, 340, 1.106, 14712.317, 339, 0.978, 8635.942, 339, + 3.202, 5120.601, 333, 0.837, 6496.375, 325, 3.479, 6133.513, 316, 5.089, 21228.392, 316, 1.328, 10873.986, 309, + 3.646, 10.637, 303, 1.802, 35371.887, 296, 3.397, 9225.539, 288, 6.026, 154717.610, 281, 2.585, 14314.168, 262, + 3.856, 266.607, 262, 2.579, 22483.849, 257, 1.561, 23543.231, 255, 3.949, 1990.745, 251, 3.744, 10575.407, 240, + 1.161, 10984.192, 238, 0.106, 7.046, 236, 4.272, 6040.347, 234, 3.577, 10969.965, 211, 3.714, 65147.620, 210, + 0.754, 13521.751, 207, 4.228, 5650.292, 202, 0.814, 170.673, 201, 4.629, 6037.244, 200, 0.381, 6172.870, 199, + 3.933, 6206.810, 199, 5.197, 6262.300, 197, 1.046, 18209.330, 195, 1.070, 5230.807, 195, 4.869, 36.028, 194, + 4.313, 6244.943, 192, 1.229, 709.933, 192, 5.595, 6282.096, 192, 0.602, 6284.056, 189, 3.744, 23.878, 188, + 1.904, 15.252, 188, 0.867, 22003.915, 182, 3.681, 15110.466, 181, 0.491, 1.484, 179, 3.222, 39302.097, 179, + 1.259, 12559.038, + 62833196674749D, 0.000000000000, 0.000000000000, 20605886, 2.67823456, 6283.07584999, 430343, 2.635127, + 12566.151700, 42526, 1.59047, 3.52312, 11926, 5.79557, 26.29832, 10898, 2.96618, 1577.34354, 9348, 2.5921, + 18849.2275, 7212, 1.1385, 529.6910, 6777, 1.8747, 398.1490, 6733, 4.4092, 5507.5532, 5903, 2.8880, 5223.6939, + 5598, 2.1747, 155.4204, 4541, 0.3980, 796.2980, 3637, 0.4662, 775.5226, 2896, 2.6471, 7.1135, 2084, 5.3414, + 0.9803, 1910, 1.8463, 5486.7778, 1851, 4.9686, 213.2991, 1729, 2.9912, 6275.9623, 1623, 0.0322, 2544.3144, 1583, + 1.4305, 2146.1654, 1462, 1.2053, 10977.0788, 1246, 2.8343, 1748.0164, 1188, 3.2580, 5088.6288, 1181, 5.2738, + 1194.4470, 1151, 2.0750, 4694.0030, 1064, 0.7661, 553.5694, 997, 1.303, 6286.599, 972, 4.239, 1349.867, 945, + 2.700, 242.729, 858, 5.645, 951.718, 758, 5.301, 2352.866, 639, 2.650, 9437.763, 610, 4.666, 4690.480, 583, + 1.766, 1059.382, 531, 0.909, 3154.687, 522, 5.661, 71430.696, 520, 1.854, 801.821, 504, 1.425, 6438.496, 433, + 0.241, 6812.767, 426, 0.774, 10447.388, 413, 5.240, 7084.897, 374, 2.001, 8031.092, 356, 2.429, 14143.495, 350, + 4.800, 6279.553, 337, 0.888, 12036.461, 337, 3.862, 1592.596, 325, 3.400, 7632.943, 322, 0.616, 8429.241, 318, + 3.188, 4705.732, 297, 6.070, 4292.331, 295, 1.431, 5746.271, 290, 2.325, 20.355, 275, 0.935, 5760.498, 270, + 4.804, 7234.794, 253, 6.223, 6836.645, 228, 5.003, 17789.846, 225, 5.672, 11499.656, 215, 5.202, 11513.883, 208, + 3.955, 10213.286, 208, 2.268, 522.577, 206, 2.224, 5856.478, 206, 2.550, 25132.303, 203, 0.910, 6256.778, 189, + 0.532, 3340.612, 188, 4.735, 83996.847, 179, 1.474, 4164.312, 178, 3.025, 5.523, 177, 3.026, 5753.385, 159, + 4.637, 3.286, 157, 6.124, 5216.580, 155, 3.077, 6681.225, 154, 4.200, 13367.973, 143, 1.191, 3894.182, 138, + 3.093, 135.065, 136, 4.245, 426.598, 134, 5.765, 6040.347, 128, 3.085, 5643.179, 127, 2.092, 6290.189, 125, + 3.077, 11926.254, 125, 3.445, 536.805, 114, 3.244, 12168.003, 112, 2.318, 16730.464, 111, 3.901, 11506.770, 111, + 5.320, 23.878, 105, 3.750, 7860.419, 103, 2.447, 1990.745, 96, 0.82, 3.88, 96, 4.08, 6127.66, 91, 5.42, 206.19, + 91, 0.42, 7079.37, 88, 5.17, 11790.63, 81, 0.34, 9917.70, 80, 3.89, 10973.56, 78, 2.40, 1589.07, 78, 2.58, + 11371.70, 77, 3.98, 955.60, 77, 3.36, 36.03, 76, 1.30, 103.09, 75, 5.18, 10969.97, 75, 4.96, 6496.37, 73, 5.21, + 38.03, 72, 2.65, 6309.37, 70, 5.61, 3738.76, 69, 2.60, 3496.03, 69, 0.39, 15.25, 69, 2.78, 20.78, 65, 1.13, + 7058.60, 64, 4.28, 28.45, 61, 5.63, 10984.19, 60, 0.73, 419.48, 60, 5.28, 10575.41, 58, 5.55, 17298.18, 58, + 3.19, 4732.03, + 5291887, 0.0000000, 0.0000000, 871984, 1.072097, 6283.075850, 30913, 0.86729, 12566.15170, 2734, 0.0530, 3.5231, + 1633, 5.1883, 26.2983, 1575, 3.6846, 155.4204, 954, 0.757, 18849.228, 894, 2.057, 77713.771, 695, 0.827, + 775.523, 506, 4.663, 1577.344, 406, 1.031, 7.114, 381, 3.441, 5573.143, 346, 5.141, 796.298, 317, 6.053, + 5507.553, 302, 1.192, 242.729, 289, 6.117, 529.691, 271, 0.306, 398.149, 254, 2.280, 553.569, 237, 4.381, + 5223.694, 208, 3.754, 0.980, 168, 0.902, 951.718, 153, 5.759, 1349.867, 145, 4.364, 1748.016, 134, 3.721, + 1194.447, 125, 2.948, 6438.496, 122, 2.973, 2146.165, 110, 1.271, 161000.686, 104, 0.604, 3154.687, 100, 5.986, + 6286.599, 92, 4.80, 5088.63, 89, 5.23, 7084.90, 83, 3.31, 213.30, 76, 3.42, 5486.78, 71, 6.19, 4690.48, 68, + 3.43, 4694.00, 65, 1.60, 2544.31, 64, 1.98, 801.82, 61, 2.48, 10977.08, 50, 1.44, 6836.65, 49, 2.34, 1592.60, + 46, 1.31, 4292.33, 46, 3.81, 149854.40, 43, 0.04, 7234.79, 40, 4.94, 7632.94, 39, 1.57, 71430.70, 38, 3.17, + 6309.37, 35, 0.99, 6040.35, 35, 0.67, 1059.38, 31, 3.18, 2352.87, 31, 3.55, 8031.09, 30, 1.92, 10447.39, 30, + 2.52, 6127.66, 28, 4.42, 9437.76, 28, 2.71, 3894.18, 27, 0.67, 25132.30, 26, 5.27, 6812.77, 25, 0.55, 6279.55, + 23, 1.38, 4705.73, 22, 0.64, 6256.78, 20, 6.07, 640.88, + 28923, 5.84384, 6283.07585, 3496, 0.0000, 0.0000, 1682, 5.4877, 12566.1517, 296, 5.196, 155.420, 129, 4.722, + 3.523, 71, 5.30, 18849.23, 64, 5.97, 242.73, 40, 3.79, 553.57, + 11408, 3.14159, 0.00000, 772, 4.134, 6283.076, 77, 3.84, 12566.15, 42, 0.42, 155.42, + 88, 3.14, 0.00, 17, 2.77, 6283.08, 5, 2.01, 155.42, 3, 2.21, 12566.15, + 27962, 3.19870, 84334.66158, 10164, 5.42249, 5507.55324, 8045, 3.8801, 5223.6939, 4381, 3.7044, 2352.8662, 3193, + 4.0003, 1577.3435, 2272, 3.9847, 1047.7473, 1814, 4.9837, 6283.0758, 1639, 3.5646, 5856.4777, 1444, 3.7028, + 9437.7629, 1430, 3.4112, 10213.2855, 1125, 4.8282, 14143.4952, 1090, 2.0857, 6812.7668, 1037, 4.0566, + 71092.8814, 971, 3.473, 4694.003, 915, 1.142, 6620.890, 878, 4.440, 5753.385, 837, 4.993, 7084.897, 770, 5.554, + 167621.576, 719, 3.602, 529.691, 692, 4.326, 6275.962, 558, 4.410, 7860.419, 529, 2.484, 4705.732, 521, 6.250, + 18073.705, + 903, 3.897, 5507.553, 618, 1.730, 5223.694, 380, 5.244, 2352.866, + 166, 1.627, 84334.662, + 10001398880D, 0.00000000000, 0.00000000000, 167069963, 3.098463508, 6283.075849991, 1395602, 3.0552461, + 12566.1517000, 308372, 5.198467, 77713.771468, 162846, 1.173877, 5753.384885, 157557, 2.846852, 7860.419392, + 92480, 5.45292, 11506.76977, 54244, 4.56409, 3930.20970, 47211, 3.66100, 5884.92685, 34598, 0.96369, 5507.55324, + 32878, 5.89984, 5223.69392, 30678, 0.29867, 5573.14280, 24319, 4.27350, 11790.62909, 21183, 5.84715, 1577.34354, + 18575, 5.02194, 10977.07880, 17484, 3.01194, 18849.22755, 10984, 5.05511, 5486.77784, 9832, 0.8868, 6069.7768, + 8650, 5.6896, 15720.8388, 8583, 1.2708, 161000.6857, 6490, 0.2725, 17260.1547, 6292, 0.9218, 529.6910, 5706, + 2.0137, 83996.8473, 5574, 5.2416, 71430.6956, 4938, 3.2450, 2544.3144, 4696, 2.5781, 775.5226, 4466, 5.5372, + 9437.7629, 4252, 6.0111, 6275.9623, 3897, 5.3607, 4694.0030, 3825, 2.3926, 8827.3903, 3749, 0.8295, 19651.0485, + 3696, 4.9011, 12139.5535, 3566, 1.6747, 12036.4607, 3454, 1.8427, 2942.4634, 3319, 0.2437, 7084.8968, 3192, + 0.1837, 5088.6288, 3185, 1.7778, 398.1490, 2846, 1.2134, 6286.5990, 2779, 1.8993, 6279.5527, 2628, 4.5890, + 10447.3878, 2460, 3.7866, 8429.2413, 2393, 4.9960, 5856.4777, 2359, 0.2687, 796.2980, 2329, 2.8078, 14143.4952, + 2210, 1.9500, 3154.6871, 2035, 4.6527, 2146.1654, 1951, 5.3823, 2352.8662, 1883, 0.6731, 149854.4001, 1833, + 2.2535, 23581.2582, 1796, 0.1987, 6812.7668, 1731, 6.1520, 16730.4637, 1717, 4.4332, 10213.2855, 1619, 5.2316, + 17789.8456, 1381, 5.1896, 8031.0923, 1364, 3.6852, 4705.7323, 1314, 0.6529, 13367.9726, 1041, 4.3329, + 11769.8537, 1017, 1.5939, 4690.4798, 998, 4.201, 6309.374, 966, 3.676, 27511.468, 874, 6.064, 1748.016, 779, + 3.674, 12168.003, 771, 0.312, 7632.943, 756, 2.626, 6256.778, 746, 5.648, 11926.254, 693, 2.924, 6681.225, 680, + 1.423, 23013.540, 674, 0.563, 3340.612, 663, 5.661, 11371.705, 659, 3.136, 801.821, 648, 2.650, 19804.827, 615, + 3.029, 233141.314, 612, 5.134, 1194.447, 563, 4.341, 90955.552, 552, 2.091, 17298.182, 534, 5.100, 31441.678, + 531, 2.407, 11499.656, 523, 4.624, 6438.496, 513, 5.324, 11513.883, 477, 0.256, 11856.219, 461, 1.722, 7234.794, + 458, 3.766, 6386.169, 458, 4.466, 5746.271, 423, 1.055, 5760.498, 422, 1.557, 7238.676, 415, 2.599, 7058.598, + 401, 3.030, 1059.382, 397, 1.201, 1349.867, 379, 4.907, 4164.312, 360, 5.707, 5643.179, 352, 3.626, 244287.600, + 348, 0.761, 10973.556, 342, 3.001, 4292.331, 336, 4.546, 4732.031, 334, 3.138, 6836.645, 324, 4.164, 9917.697, + 316, 1.691, 11015.106, 307, 0.238, 35371.887, 298, 1.306, 6283.143, 298, 1.750, 6283.009, 293, 5.738, 16200.773, + 286, 5.928, 14712.317, 281, 3.515, 21228.392, 280, 5.663, 8635.942, 277, 0.513, 26.298, 268, 4.207, 18073.705, + 266, 0.900, 12352.853, 260, 2.962, 25132.303, 255, 2.477, 6208.294, 242, 2.800, 709.933, 231, 1.054, 22483.849, + 229, 1.070, 14314.168, 216, 1.314, 154717.610, 215, 6.038, 10873.986, 200, 0.561, 7079.374, 198, 2.614, 951.718, + 197, 4.369, 167283.762, 186, 2.861, 5216.580, 183, 1.660, 39302.097, 183, 5.912, 3738.761, 175, 2.145, 6290.189, + 173, 2.168, 10575.407, 171, 3.702, 1592.596, 171, 1.343, 3128.389, 164, 5.550, 6496.375, 164, 5.856, 10984.192, + 161, 1.998, 10969.965, 161, 1.909, 6133.513, 157, 4.955, 25158.602, 154, 6.216, 23543.231, 153, 5.357, + 13521.751, 150, 5.770, 18209.330, 150, 5.439, 155.420, 139, 1.778, 9225.539, 139, 1.626, 5120.601, 128, 2.460, + 13916.019, 123, 0.717, 143571.324, 122, 2.654, 88860.057, 121, 4.414, 3894.182, 121, 1.192, 3.523, 120, 4.030, + 553.569, 119, 1.513, 17654.781, 117, 3.117, 14945.316, 113, 2.698, 6040.347, 110, 3.085, 43232.307, 109, 0.998, + 955.600, 108, 2.939, 17256.632, 107, 5.285, 65147.620, 103, 0.139, 11712.955, 103, 5.850, 213.299, 102, 3.046, + 6037.244, 101, 2.842, 8662.240, 100, 3.626, 6262.300, 98, 2.36, 6206.81, 98, 5.11, 6172.87, 98, 2.00, 15110.47, + 97, 2.67, 5650.29, 97, 2.75, 6244.94, 96, 4.02, 6282.10, 96, 5.31, 6284.06, 92, 0.10, 29088.81, 85, 3.26, + 20426.57, 84, 2.60, 28766.92, 81, 3.58, 10177.26, 80, 5.81, 5230.81, 78, 2.53, 16496.36, 77, 4.06, 6127.66, 73, + 0.04, 5481.25, 72, 5.96, 12559.04, 72, 5.92, 4136.91, 71, 5.49, 22003.91, 70, 3.41, 7.11, 69, 0.62, 11403.68, + 69, 3.90, 1589.07, 69, 1.96, 12416.59, 69, 4.51, 426.60, 67, 1.61, 11087.29, 66, 4.50, 47162.52, 66, 5.08, + 283.86, 66, 4.32, 16858.48, 65, 1.04, 6062.66, 64, 1.59, 18319.54, 63, 5.70, 45892.73, 63, 4.60, 66567.49, 63, + 3.82, 13517.87, 62, 2.62, 11190.38, 61, 1.54, 33019.02, 60, 5.58, 10344.30, 60, 5.38, 316428.23, 60, 5.78, + 632.78, 59, 6.12, 9623.69, 57, 0.16, 17267.27, 57, 3.86, 6076.89, 57, 1.98, 7668.64, 56, 4.78, 20199.09, 55, + 4.56, 18875.53, 55, 3.51, 17253.04, 54, 3.07, 226858.24, 54, 4.83, 18422.63, 53, 5.02, 12132.44, 52, 3.63, + 5333.90, 52, 0.97, 155427.54, 51, 3.36, 20597.24, 50, 0.99, 11609.86, 50, 2.21, 1990.75, 48, 1.62, 12146.67, 48, + 1.17, 12569.67, 47, 4.62, 5436.99, 47, 1.81, 12562.63, 47, 0.59, 21954.16, 47, 0.76, 7342.46, 46, 0.27, 4590.91, + 46, 3.77, 156137.48, 45, 5.66, 10454.50, 44, 5.84, 3496.03, 43, 0.24, 17996.03, 41, 5.93, 51092.73, 41, 4.21, + 12592.45, 40, 5.14, 1551.05, 40, 5.28, 15671.08, 39, 3.69, 18052.93, 39, 4.94, 24356.78, 38, 2.72, 11933.37, 38, + 5.23, 7477.52, 38, 4.99, 9779.11, 37, 3.70, 9388.01, 37, 4.44, 4535.06, 36, 2.16, 28237.23, 36, 2.54, 242.73, + 36, 0.22, 5429.88, 35, 6.15, 19800.95, 35, 2.92, 36949.23, 34, 5.63, 2379.16, 34, 5.73, 16460.33, 34, 5.11, + 5849.36, 33, 6.19, 6268.85, + 10301861, 1.10748970, 6283.07584999, 172124, 1.064423, 12566.151700, 70222, 3.14159, 0.00000, 3235, 1.0217, + 18849.2275, 3080, 2.8435, 5507.5532, 2497, 1.3191, 5223.6939, 1849, 1.4243, 1577.3435, 1008, 5.9138, 10977.0788, + 865, 1.420, 6275.962, 863, 0.271, 5486.778, 507, 1.686, 5088.629, 499, 6.014, 6286.599, 467, 5.987, 529.691, + 440, 0.518, 4694.003, 410, 1.084, 9437.763, 387, 4.750, 2544.314, 375, 5.071, 796.298, 352, 0.023, 83996.847, + 344, 0.949, 71430.696, 341, 5.412, 775.523, 322, 6.156, 2146.165, 286, 5.484, 10447.388, 284, 3.420, 2352.866, + 255, 6.132, 6438.496, 252, 0.243, 398.149, 243, 3.092, 4690.480, 225, 3.689, 7084.897, 220, 4.952, 6812.767, + 219, 0.420, 8031.092, 209, 1.282, 1748.016, 193, 5.314, 8429.241, 185, 1.820, 7632.943, 175, 3.229, 6279.553, + 173, 1.537, 4705.732, 158, 4.097, 11499.656, 158, 5.539, 3154.687, 150, 3.633, 11513.883, 148, 3.222, 7234.794, + 147, 3.653, 1194.447, 144, 0.817, 14143.495, 135, 6.151, 5746.271, 134, 4.644, 6836.645, 128, 2.693, 1349.867, + 123, 5.650, 5760.498, 118, 2.577, 13367.973, 113, 3.357, 17789.846, 110, 4.497, 4292.331, 108, 5.828, 12036.461, + 102, 5.621, 6256.778, 99, 1.14, 1059.38, 98, 0.66, 5856.48, 93, 2.32, 10213.29, 92, 0.77, 16730.46, 88, 1.50, + 11926.25, 86, 1.42, 5753.38, 85, 0.66, 155.42, 81, 1.64, 6681.22, 80, 4.11, 951.72, 66, 4.55, 5216.58, 65, 0.98, + 25132.30, 64, 4.19, 6040.35, 64, 0.52, 6290.19, 63, 1.51, 5643.18, 59, 6.18, 4164.31, 57, 2.30, 10973.56, 55, + 2.32, 11506.77, 55, 2.20, 1592.60, 55, 5.27, 3340.61, 54, 5.54, 553.57, 53, 5.04, 9917.70, 53, 0.92, 11371.70, + 52, 3.98, 17298.18, 52, 3.60, 10969.97, 49, 5.91, 3894.18, 49, 2.51, 6127.66, 48, 1.67, 12168.00, 46, 0.31, + 801.82, 42, 3.70, 10575.41, 42, 4.05, 10984.19, 40, 2.17, 7860.42, 40, 4.17, 26.30, 38, 5.82, 7058.60, 37, 3.39, + 6496.37, 36, 1.08, 6309.37, 36, 5.34, 7079.37, 34, 3.62, 11790.63, 32, 0.32, 16200.77, 31, 4.24, 3738.76, 29, + 4.55, 11856.22, 29, 1.26, 8635.94, 27, 3.45, 5884.93, 26, 5.08, 10177.26, 26, 5.38, 21228.39, 24, 2.26, + 11712.96, 24, 1.05, 242.73, 24, 5.59, 6069.78, 23, 3.63, 6284.06, 23, 1.64, 4732.03, 22, 3.46, 213.30, 21, 1.05, + 3496.03, 21, 3.92, 13916.02, 21, 4.01, 5230.81, 20, 5.16, 12352.85, 20, 0.69, 1990.75, 19, 2.73, 6062.66, 19, + 5.01, 11015.11, 18, 6.04, 6283.01, 18, 2.85, 7238.68, 18, 5.60, 6283.14, 18, 5.16, 17253.04, 18, 2.54, 14314.17, + 17, 1.58, 7.11, 17, 0.98, 3930.21, 17, 4.75, 17267.27, 16, 2.19, 6076.89, 16, 2.19, 18073.70, 16, 6.12, 3.52, + 16, 4.61, 9623.69, 16, 3.40, 16496.36, 15, 0.19, 9779.11, 15, 5.30, 13517.87, 15, 4.26, 3128.39, 15, 0.81, + 709.93, 14, 0.50, 25158.60, 14, 4.38, 4136.91, 13, 0.98, 65147.62, 13, 3.31, 154717.61, 13, 2.11, 1589.07, 13, + 1.92, 22483.85, 12, 6.03, 9225.54, 12, 1.53, 12559.04, 12, 5.82, 6282.10, 12, 5.61, 5642.20, 12, 2.38, + 167283.76, 12, 0.39, 12132.44, 12, 3.98, 4686.89, 12, 5.81, 12569.67, 12, 0.56, 5849.36, 11, 0.45, 6172.87, 11, + 5.80, 16858.48, 11, 6.22, 12146.67, 11, 2.27, 5429.88, + 435939, 5.784551, 6283.075850, 12363, 5.57935, 12566.15170, 1234, 3.1416, 0.0000, 879, 3.628, 77713.771, 569, + 1.870, 5573.143, 330, 5.470, 18849.228, 147, 4.480, 5507.553, 110, 2.842, 161000.686, 101, 2.815, 5223.694, 85, + 3.11, 1577.34, 65, 5.47, 775.52, 61, 1.38, 6438.50, 50, 4.42, 6286.60, 47, 3.66, 7084.90, 46, 5.39, 149854.40, + 42, 0.90, 10977.08, 40, 3.20, 5088.63, 35, 1.81, 5486.78, 32, 5.35, 3154.69, 30, 3.52, 796.30, 29, 4.62, + 4690.48, 28, 1.84, 4694.00, 27, 3.14, 71430.70, 27, 6.17, 6836.65, 26, 1.42, 2146.17, 25, 2.81, 1748.02, 24, + 2.18, 155.42, 23, 4.76, 7234.79, 21, 3.38, 7632.94, 21, 0.22, 4705.73, 20, 4.22, 1349.87, 20, 2.01, 1194.45, 20, + 4.58, 529.69, 19, 1.59, 6309.37, 18, 5.70, 6040.35, 18, 6.03, 4292.33, 17, 2.90, 9437.76, 17, 2.00, 8031.09, 17, + 5.78, 83996.85, 16, 0.05, 2544.31, 15, 0.95, 6127.66, 14, 0.36, 10447.39, 14, 1.48, 2352.87, 13, 0.77, 553.57, + 13, 5.48, 951.72, 13, 5.27, 6279.55, 13, 3.76, 6812.77, 11, 5.41, 6256.78, 10, 0.68, 1592.60, 10, 4.95, 398.15, + 10, 1.15, 3894.18, 10, 5.20, 244287.60, 10, 1.94, 11856.22, 9, 5.39, 25132.30, 8, 6.18, 1059.38, 8, 0.69, + 8429.24, 8, 5.85, 242.73, 7, 5.26, 14143.50, 7, 0.52, 801.82, 6, 2.24, 8635.94, 6, 4.00, 13367.97, 6, 2.77, + 90955.55, 6, 5.17, 7058.60, 5, 1.46, 233141.31, 5, 4.13, 7860.42, 5, 3.91, 26.30, 5, 3.89, 12036.46, 5, 5.58, + 6290.19, 5, 5.54, 1990.75, 5, 0.83, 11506.77, 5, 6.22, 6681.22, 4, 5.26, 10575.41, 4, 1.91, 7477.52, 4, 0.43, + 10213.29, 4, 1.09, 709.93, 4, 5.09, 11015.11, 4, 4.22, 88860.06, 4, 3.57, 7079.37, 4, 1.98, 6284.06, 4, 3.93, + 10973.56, 4, 6.18, 9917.70, 4, 0.36, 10177.26, 4, 2.75, 3738.76, 4, 3.33, 5643.18, 4, 5.36, 25158.60, + 14459, 4.27319, 6283.07585, 673, 3.917, 12566.152, 77, 0.00, 0.00, 25, 3.73, 18849.23, 4, 2.80, 6286.60, + 386, 2.564, 6283.076, 31, 2.27, 12566.15, 5, 3.44, 5573.14, 2, 2.05, 18849.23, 1, 2.06, 77713.77, 1, 4.41, + 161000.69, 1, 3.82, 149854.40, 1, 4.08, 6127.66, 1, 5.26, 6438.50, + 9, 1.22, 6283.08, 1, 0.66, 12566.15 + }; + private static final double[][] XL1 = new double[][]{ + {22639.586, 0.78475822, 8328.691424623, 1.5229241, 25.0719, -0.123598, 4586.438, 0.1873974, 7214.06286536, -2.184756, -18.860, 0.08280, 2369.914, 2.5429520, 15542.75428998, -0.661832, 6.212, -0.04080, 769.026, 3.140313, 16657.38284925, 3.04585, 50.144, -0.2472, 666.418, 1.527671, 628.30195521, -0.02664, 0.062, -0.0054, 411.596, 4.826607, 16866.9323150, -1.28012, -1.07, -0.0059, 211.656, 4.115028, -1114.6285593, -3.70768, -43.93, 0.2064, 205.436, 0.230523, 6585.7609101, -2.15812, -18.92, 0.0882, 191.956, 4.898507, 23871.4457146, 0.86109, 31.28, -0.164, 164.729, 2.586078, 14914.4523348, -0.6352, 6.15, -0.035, 147.321, 5.45530, -7700.3894694, -1.5496, -25.01, 0.118, 124.988, 0.48608, 7771.3771450, -0.3309, 3.11, -0.020, 109.380, 3.88323, 8956.9933798, 1.4963, 25.13, -0.129, 55.177, 5.57033, -1324.1780250, 0.6183, 7.3, -0.035, 45.100, 0.89898, 25195.623740, 0.2428, 24.0, -0.129, 39.533, 3.81213, -8538.240890, 2.8030, 26.1, -0.118, 38.430, 4.30115, 22756.817155, -2.8466, -12.6, 0.042, 36.124, 5.49587, 24986.074274, 4.5688, 75.2, -0.371, 30.773, 1.94559, 14428.125731, -4.3695, -37.7, 0.166, 28.397, 3.28586, 7842.364821, -2.2114, -18.8, 0.077, 24.358, 5.64142, 16171.056245, -0.6885, 6.3, -0.046, 18.585, 4.41371, -557.314280, -1.8538, -22.0, 0.10, 17.954, 3.58454, 8399.679100, -0.3576, 3.2, -0.03, 14.530, 4.9416, 23243.143759, 0.888, 31.2, -0.16, 14.380, 0.9709, 32200.137139, 2.384, 56.4, -0.29, 14.251, 5.7641, -2.301200, 1.523, 25.1, -0.12, 13.899, 0.3735, 31085.508580, -1.324, 12.4, -0.08, 13.194, 1.7595, -9443.319984, -5.231, -69.0, 0.33, 9.679, 3.0997, -16029.080894, -3.072, -50.1, 0.24, 9.366, 0.3016, 24080.995180, -3.465, -19.9, 0.08, 8.606, 4.1582, -1742.930514, -3.681, -44.0, 0.21, 8.453, 2.8416, 16100.068570, 1.192, 28.2, -0.14, 8.050, 2.6292, 14286.150380, -0.609, 6.1, -0.03, 7.630, 6.2388, 17285.684804, 3.019, 50.2, -0.25, 7.447, 1.4845, 1256.603910, -0.053, 0.1, -0.01, 7.371, 0.2736, 5957.458955, -2.131, -19.0, 0.09, 7.063, 5.6715, 33.757047, -0.308, -3.6, 0.02, 6.383, 4.7843, 7004.513400, 2.141, 32.4, -0.16, 5.742, 2.6572, 32409.686605, -1.942, 5, -0.05, 4.374, 4.3443, 22128.51520, -2.820, -13, 0.05, 3.998, 3.2545, 33524.31516, 1.766, 49, -0.25, 3.210, 2.2443, 14985.44001, -2.516, -16, 0.06, 2.915, 1.7138, 24499.74767, 0.834, 31, -0.17, 2.732, 1.9887, 13799.82378, -4.343, -38, 0.17, 2.568, 5.4122, -7072.08751, -1.576, -25, 0.11, 2.521, 3.2427, 8470.66678, -2.238, -19, 0.07, 2.489, 4.0719, -486.32660, -3.734, -44, 0.20, 2.146, 5.6135, -1952.47998, 0.645, 7, -0.03, 1.978, 2.7291, 39414.20000, 0.199, 37, -0.21, 1.934, 1.5682, 33314.76570, 6.092, 100, -0.5, 1.871, 0.4166, 30457.20662, -1.297, 12, -0.1, 1.753, 2.0582, -8886.00570, -3.38, -47, 0.2, 1.437, 2.386, -695.87607, 0.59, 7, 0, 1.373, 3.026, -209.54947, 4.33, 51, -0.2, 1.262, 5.940, 16728.37052, 1.17, 28, -0.1, 1.224, 6.172, 6656.74859, -4.04, -41, 0.2, 1.187, 5.873, 6099.43431, -5.89, -63, 0.3, 1.177, 1.014, 31571.83518, 2.41, 56, -0.3, 1.162, 3.840, 9585.29534, 1.47, 25, -0.1, 1.143, 5.639, 8364.73984, -2.18, -19, 0.1, 1.078, 1.229, 70.98768, -1.88, -22, 0.1, 1.059, 3.326, 40528.82856, 3.91, 81, -0.4, 0.990, 5.013, 40738.37803, -0.42, 30, -0.2, 0.948, 5.687, -17772.01141, -6.75, -94, 0.5, 0.876, 0.298, -0.35232, 0, 0, 0, 0.822, 2.994, 393.02097, 0, 0, 0, 0.788, 1.836, 8326.39022, 3.05, 50, -0.2, 0.752, 4.985, 22614.84180, 0.91, 31, -0.2, 0.740, 2.875, 8330.99262, 0, 0, 0, 0.669, 0.744, -24357.77232, -4.60, -75, 0.4, 0.644, 1.314, 8393.12577, -2.18, -19, 0.1, 0.639, 5.888, 575.33849, 0, 0, 0, 0.635, 1.116, 23385.11911, -2.87, -13, 0, 0.584, 5.197, 24428.75999, 2.71, 53, -0.3, 0.583, 3.513, -9095.55517, 0.95, 4, 0, 0.572, 6.059, 29970.88002, -5.03, -32, 0.1, 0.565, 2.960, 0.32863, 1.52, 25, -0.1, 0.561, 4.001, -17981.56087, -2.43, -43, 0.2, 0.557, 0.529, 7143.07519, -0.30, 3, 0, 0.546, 2.311, 25614.37623, 4.54, 75, -0.4, 0.536, 4.229, 15752.30376, -4.99, -45, 0.2, 0.493, 3.316, -8294.9344, -1.83, -29, 0.1, 0.491, 1.744, 8362.4485, 1.21, 21, -0.1, 0.478, 1.803, -10071.6219, -5.20, -69, 0.3, 0.454, 0.857, 15333.2048, 3.66, 57, -0.3, 0.445, 2.071, 8311.7707, -2.18, -19, 0.1, 0.426, 0.345, 23452.6932, -3.44, -20, 0.1, 0.420, 4.941, 33733.8646, -2.56, -2, 0, 0.413, 1.642, 17495.2343, -1.31, -1, 0, 0.404, 1.458, 23314.1314, -0.99, 9, -0.1, 0.395, 2.132, 38299.5714, -3.51, -6, 0, 0.382, 2.700, 31781.3846, -1.92, 5, 0, 0.375, 4.827, 6376.2114, 2.17, 32, -0.2, 0.361, 3.867, 16833.1753, -0.97, 3, 0, 0.358, 5.044, 15056.4277, -4.40, -38, 0.2, 0.350, 5.157, -8257.7037, -3.40, -47, 0.2, 0.344, 4.233, 157.7344, 0, 0, 0, 0.340, 2.672, 13657.8484, -0.58, 6, 0, 0.329, 5.610, 41853.0066, 3.29, 74, -0.4, 0.325, 5.895, -39.8149, 0, 0, 0, 0.309, 4.387, 21500.2132, -2.79, -13, 0.1, 0.302, 1.278, 786.0419, 0, 0, 0, 0.302, 5.341, -24567.3218, -0.27, -24, 0.1, 0.301, 1.045, 5889.8848, -1.57, -12, 0, 0.294, 4.201, -2371.2325, -3.65, -44, 0.2, 0.293, 3.704, 21642.1886, -6.55, -57, 0.2, 0.290, 4.069, 32828.4391, 2.36, 56, -0.3, 0.289, 3.472, 31713.8105, -1.35, 12, -0.1, 0.285, 5.407, -33.7814, 0.31, 4, 0, 0.283, 5.998, -16.9207, -3.71, -44, 0.2, 0.283, 2.772, 38785.8980, 0.23, 37, -0.2, 0.274, 5.343, 15613.7420, -2.54, -16, 0.1, 0.263, 3.997, 25823.9257, 0.22, 24, -0.1, 0.254, 0.600, 24638.3095, -1.61, 2, 0, 0.253, 1.344, 6447.1991, 0.29, 10, -0.1, 0.250, 0.887, 141.9754, -3.76, -44, 0.2, 0.247, 0.317, 5329.1570, -2.10, -19, 0.1, 0.245, 0.141, 36.0484, -3.71, -44, 0.2, 0.231, 2.287, 14357.1381, -2.49, -16, 0.1, 0.227, 5.158, 2.6298, 0, 0, 0, 0.219, 5.085, 47742.8914, 1.72, 63, -0.3, 0.211, 2.145, 6638.7244, -2.18, -19, 0.1, 0.201, 4.415, 39623.7495, -4.13, -14, 0, 0.194, 2.091, 588.4927, 0, 0, 0, 0.193, 3.057, -15400.7789, -3.10, -50, 0, 0.186, 5.598, 16799.3582, -0.72, 6, 0, 0.185, 3.886, 1150.6770, 0, 0, 0, 0.183, 1.619, 7178.0144, 1.52, 25, 0, 0.181, 2.635, 8328.3391, 1.52, 25, 0, 0.181, 2.077, 8329.0437, 1.52, 25, 0, 0.179, 3.215, -9652.8694, -0.90, -18, 0, 0.176, 1.716, -8815.0180, -5.26, -69, 0, 0.175, 5.673, 550.7553, 0, 0, 0, 0.170, 2.060, 31295.0580, -5.6, -39, 0, 0.167, 1.239, 7211.7617, -0.7, 6, 0, 0.165, 4.499, 14967.4158, -0.7, 6, 0, 0.164, 3.595, 15540.4531, 0.9, 31, 0, 0.164, 4.237, 522.3694, 0, 0, 0, 0.163, 4.633, 15545.0555, -2.2, -19, 0, 0.161, 0.478, 6428.0209, -2.2, -19, 0, 0.158, 2.03, 13171.5218, -4.3, -38, 0, 0.157, 2.28, 7216.3641, -3.7, -44, 0, 0.154, 5.65, 7935.6705, 1.5, 25, 0, 0.152, 0.46, 29828.9047, -1.3, 12, 0, 0.151, 1.19, -0.7113, 0, 0, 0, 0.150, 1.42, 23942.4334, -1.0, 9, 0, 0.144, 2.75, 7753.3529, 1.5, 25, 0, 0.137, 2.08, 7213.7105, -2.2, -19, 0, 0.137, 1.44, 7214.4152, -2.2, -19, 0, 0.136, 4.46, -1185.6162, -1.8, -22, 0, 0.136, 3.03, 8000.1048, -2.2, -19, 0, 0.134, 2.83, 14756.7124, -0.7, 6, 0, 0.131, 5.05, 6821.0419, -2.2, -19, 0, 0.128, 5.99, -17214.6971, -4.9, -72, 0, 0.127, 5.35, 8721.7124, 1.5, 25, 0, 0.126, 4.49, 46628.2629, -2.0, 19, 0, 0.125, 5.94, 7149.6285, 1.5, 25, 0, 0.124, 1.09, 49067.0695, 1.1, 55, 0, 0.121, 2.88, 15471.7666, 1.2, 28, 0, 0.111, 3.92, 41643.4571, 7.6, 125, -1, 0.110, 1.96, 8904.0299, 1.5, 25, 0, 0.106, 3.30, -18.0489, -2.2, -19, 0, 0.105, 2.30, -4.9310, 1.5, 25, 0, 0.104, 2.22, -6.5590, -1.9, -22, 0, 0.101, 1.44, 1884.9059, -0.1, 0, 0, 0.100, 5.92, 5471.1324, -5.9, -63, 0, 0.099, 1.12, 15149.7333, -0.7, 6, 0, 0.096, 4.73, 15508.9972, -0.4, 10, 0, 0.095, 5.18, 7230.9835, 1.5, 25, 0, 0.093, 3.37, 39900.5266, 3.9, 81, 0, 0.092, 2.01, 25057.0619, 2.7, 53, 0, 0.092, 1.21, -79.6298, 0, 0, 0, 0.092, 1.65, -26310.2523, -4.0, -68, 0, 0.091, 1.01, 42062.5561, -1.0, 23, 0, 0.090, 6.10, 29342.5781, -5.0, -32, 0, 0.090, 4.43, 15542.4020, -0.7, 6, 0, 0.090, 3.80, 15543.1066, -0.7, 6, 0, 0.089, 4.15, 6063.3859, -2.2, -19, 0, 0.086, 4.03, 52.9691, 0, 0, 0, 0.085, 0.49, 47952.4409, -2.6, 11, 0, 0.085, 1.60, 7632.8154, 2.1, 32, 0, 0.084, 0.22, 14392.0773, -0.7, 6, 0, 0.083, 6.22, 6028.4466, -4.0, -41, 0, 0.083, 0.63, -7909.9389, 2.8, 26, 0, 0.083, 5.20, -77.5523, 0, 0, 0, 0.082, 2.74, 8786.1467, -2.2, -19, 0, 0.080, 2.43, 9166.5428, -2.8, -26, 0, 0.080, 3.70, -25405.1732, 4.1, 27, 0, 0.078, 5.68, 48857.5200, 5.4, 106, -1, 0.077, 1.85, 8315.5735, -2.2, -19, 0, 0.075, 5.46, -18191.1103, 1.9, 8, 0, 0.075, 1.41, -16238.6304, 1.3, 1, 0, 0.074, 5.06, 40110.0761, -0.4, 30, 0, 0.072, 2.10, 64.4343, -3.7, -44, 0, 0.071, 2.17, 37671.2695, -3.5, -6, 0, 0.069, 1.71, 16693.4313, -0.7, 6, 0, 0.069, 3.33, -26100.7028, -8.3, -119, 1, 0.068, 1.09, 8329.4028, 1.5, 25, 0, 0.068, 3.62, 8327.9801, 1.5, 25, 0, 0.068, 2.41, 16833.1509, -1.0, 3, 0, 0.067, 3.40, 24709.2971, -3.5, -20, 0, 0.067, 1.65, 8346.7156, -0.3, 3, 0, 0.066, 2.61, 22547.2677, 1.5, 39, 0, 0.066, 3.50, 15576.5113, -1.0, 3, 0, 0.065, 5.76, 33037.9886, -2.0, 5, 0, 0.065, 4.58, 8322.1325, -0.3, 3, 0, 0.065, 6.20, 17913.9868, 3.0, 50, 0, 0.065, 1.50, 22685.8295, -1.0, 9, 0, 0.065, 2.37, 7180.3058, -1.9, -15, 0, 0.064, 1.06, 30943.5332, 2.4, 56, 0, 0.064, 1.89, 8288.8765, 1.5, 25, 0, 0.064, 4.70, 6.0335, 0.3, 4, 0, 0.063, 2.83, 8368.5063, 1.5, 25, 0, 0.063, 5.66, -2580.7819, 0.7, 7, 0, 0.062, 3.78, 7056.3285, -2.2, -19, 0, 0.061, 1.49, 8294.9100, 1.8, 29, 0, 0.061, 0.12, -10281.1714, -0.9, -18, 0, 0.061, 3.06, -8362.4729, -1.2, -21, 0, 0.061, 4.43, 8170.9571, 1.5, 25, 0, 0.059, 5.78, -13.1179, -3.7, -44, 0, 0.059, 5.97, 6625.5702, -2.2, -19, 0, 0.058, 5.01, -0.5080, -0.3, 0, 0, 0.058, 2.73, 7161.0938, -2.2, -19, 0, 0.057, 0.19, 7214.0629, -2.2, -19, 0, 0.057, 4.00, 22199.5029, -4.7, -35, 0, 0.057, 5.38, 8119.1420, 5.8, 76, 0, 0.056, 1.07, 7542.6495, 1.5, 25, 0, 0.056, 0.28, 8486.4258, 1.5, 25, 0, 0.054, 4.19, 16655.0816, 4.6, 75, 0, 0.053, 0.72, 7267.0320, -2.2, -19, 0, 0.053, 3.12, 12.6192, 0.6, 7, 0, 0.052, 2.99, -32896.013, -1.8, -49, 0, 0.052, 3.46, 1097.708, 0, 0, 0, 0.051, 5.37, -6443.786, -1.6, -25, 0, 0.051, 1.35, 7789.401, -2.2, -19, 0, 0.051, 5.83, 40042.502, 0.2, 38, 0, 0.051, 3.63, 9114.733, 1.5, 25, 0, 0.050, 1.51, 8504.484, -2.5, -22, 0, 0.050, 5.23, 16659.684, 1.5, 25, 0, 0.050, 1.15, 7247.820, -2.5, -23, 0, 0.047, 0.25, -1290.421, 0.3, 0, 0, 0.047, 4.67, -32686.464, -6.1, -100, 0, 0.047, 3.49, 548.678, 0, 0, 0, 0.047, 2.37, 6663.308, -2.2, -19, 0, 0.046, 0.98, 1572.084, 0, 0, 0, 0.046, 2.04, 14954.262, -0.7, 6, 0, 0.046, 3.72, 6691.693, -2.2, -19, 0, 0.045, 6.19, -235.287, 0, 0, 0, 0.044, 2.96, 32967.001, -0.1, 27, 0, 0.044, 3.82, -1671.943, -5.6, -66, 0, 0.043, 5.82, 1179.063, 0, 0, 0, 0.043, 0.07, 34152.617, 1.7, 49, 0, 0.043, 3.71, 6514.773, -0.3, 0, 0, 0.043, 5.62, 15.732, -2.5, -23, 0, 0.043, 5.80, 8351.233, -2.2, -19, 0, 0.042, 0.27, 7740.199, 1.5, 25, 0, 0.042, 6.14, 15385.020, -0.7, 6, 0, 0.042, 6.13, 7285.051, -4.1, -41, 0, 0.041, 1.27, 32757.451, 4.2, 78, 0, 0.041, 4.46, 8275.722, 1.5, 25, 0, 0.040, 0.23, 8381.661, 1.5, 25, 0, 0.040, 5.87, -766.864, 2.5, 29, 0, 0.040, 1.66, 254.431, 0, 0, 0, 0.040, 0.40, 9027.981, -0.4, 0, 0, 0.040, 2.96, 7777.936, 1.5, 25, 0, 0.039, 4.67, 33943.068, 6.1, 100, 0, 0.039, 3.52, 8326.062, 1.5, 25, 0, 0.039, 3.75, 21013.887, -6.5, -57, 0, 0.039, 5.60, 606.978, 0, 0, 0, 0.039, 1.19, 8331.321, 1.5, 25, 0, 0.039, 2.84, 7211.433, -2.2, -19, 0, 0.038, 0.67, 7216.693, -2.2, -19, 0, 0.038, 6.22, 25161.867, 0.6, 28, 0, 0.038, 4.40, 7806.322, 1.5, 25, 0, 0.038, 4.16, 9179.168, -2.2, -19, 0, 0.037, 4.73, 14991.999, -0.7, 6, 0, 0.036, 0.35, 67.514, -0.6, -7, 0, 0.036, 3.70, 25266.611, -1.6, 0, 0, 0.036, 5.39, 16328.796, -0.7, 6, 0, 0.035, 1.44, 7174.248, -2.2, -19, 0, 0.035, 5.00, 15684.730, -4.4, -38, 0, 0.035, 0.39, -15.419, -2.2, -19, 0, 0.035, 6.07, 15020.385, -0.7, 6, 0, 0.034, 6.01, 7371.797, -2.2, -19, 0, 0.034, 0.96, -16623.626, -3.4, -54, 0, 0.033, 6.24, 9479.368, 1.5, 25, 0, 0.033, 3.21, 23661.896, 5.2, 82, 0, 0.033, 4.06, 8311.418, -2.2, -19, 0, 0.033, 2.40, 1965.105, 0, 0, 0, 0.033, 5.17, 15489.785, -0.7, 6, 0, 0.033, 5.03, 21986.540, 0.9, 31, 0, 0.033, 4.10, 16691.140, 2.7, 46, 0, 0.033, 5.13, 47114.589, 1.7, 63, 0, 0.033, 4.45, 8917.184, 1.5, 25, 0, 0.033, 4.23, 2.078, 0, 0, 0, 0.032, 2.33, 75.251, 1.5, 25, 0, 0.032, 2.10, 7253.878, -2.2, -19, 0, 0.032, 3.11, -0.224, 1.5, 25, 0, 0.032, 4.43, 16640.462, -0.7, 6, 0, 0.032, 5.68, 8328.363, 0, 0, 0, 0.031, 5.32, 8329.020, 3.0, 50, 0, 0.031, 3.70, 16118.093, -0.7, 6, 0, 0.030, 3.67, 16721.817, -0.7, 6, 0, 0.030, 5.27, -1881.492, -1.2, -15, 0, 0.030, 5.72, 8157.839, -2.2, -19, 0, 0.029, 5.73, -18400.313, -6.7, -94, 0, 0.029, 2.76, 16.000, -2.2, -19, 0, 0.029, 1.75, 8879.447, 1.5, 25, 0, 0.029, 0.32, 8851.061, 1.5, 25, 0, 0.029, 0.90, 14704.903, 3.7, 57, 0, 0.028, 2.90, 15595.723, -0.7, 6, 0, 0.028, 5.88, 16864.631, 0.2, 24, 0, 0.028, 0.63, 16869.234, -2.8, -26, 0, 0.028, 4.04, -18609.863, -2.4, -43, 0, 0.027, 5.83, 6727.736, -5.9, -63, 0, 0.027, 6.12, 418.752, 4.3, 51, 0, 0.027, 0.14, 41157.131, 3.9, 81, 0, 0.026, 3.80, 15.542, 0, 0, 0, 0.026, 1.68, 50181.698, 4.8, 99, -1, 0.026, 0.32, 315.469, 0, 0, 0, 0.025, 5.67, 19.188, 0.3, 0, 0, 0.025, 3.16, 62.133, -2.2, -19, 0, 0.025, 3.76, 15502.939, -0.7, 6, 0, 0.025, 4.53, 45999.961, -2.0, 19, 0, 0.024, 3.21, 837.851, -4.4, -51, 0, 0.024, 2.82, 38157.596, 0.3, 37, 0, 0.024, 5.21, 15540.124, -0.7, 6, 0, 0.024, 0.26, 14218.576, 0, 13, 0, 0.024, 3.01, 15545.384, -0.7, 6, 0, 0.024, 1.16, -17424.247, -0.6, -21, 0, 0.023, 2.34, -67.574, 0.6, 7, 0, 0.023, 2.44, 18.024, -1.9, -22, 0, 0.023, 3.70, 469.400, 0, 0, 0, 0.023, 0.72, 7136.511, -2.2, -19, 0, 0.023, 4.50, 15582.569, -0.7, 6, 0, 0.023, 2.80, -16586.395, -4.9, -72, 0, 0.023, 1.51, 80.182, 0, 0, 0, 0.023, 1.09, 5261.583, -1.5, -12, 0, 0.023, 0.56, 54956.954, -0.5, 44, 0, 0.023, 4.01, 8550.860, -2.2, -19, 0, 0.023, 4.46, 38995.448, -4.1, -14, 0, 0.023, 3.82, 2358.126, 0, 0, 0, 0.022, 3.77, 32271.125, 0.5, 34, 0, 0.022, 0.82, 15935.775, -0.7, 6, 0, 0.022, 1.07, 24013.421, -2.9, -13, 0, 0.022, 0.40, 8940.078, -2.2, -19, 0, 0.022, 2.06, 15700.489, -0.7, 6, 0, 0.022, 4.27, 15124.002, -5.0, -45, 0, 0.021, 1.16, 56071.583, 3.2, 88, 0, 0.021, 5.58, 9572.189, -2.2, -19, 0, 0.020, 1.70, -17.273, -3.7, -44, 0, 0.020, 3.05, 214.617, 0, 0, 0, 0.020, 4.41, 8391.048, -2.2, -19, 0, 0.020, 5.95, 23869.145, 2.4, 56, 0, 0.020, 0.42, 40947.927, -4.7, -21, 0, 0.019, 1.39, 5818.897, 0.3, 10, 0, 0.019, 0.71, 23873.747, -0.7, 6, 0, 0.019, 2.81, 7291.615, -2.2, -19, 0, 0.019, 5.09, 8428.018, -2.2, -19, 0, 0.019, 4.14, 6518.187, -1.6, -12, 0, 0.019, 3.85, 21.330, 0, 0, 0, 0.018, 0.66, 14445.046, -0.7, 6, 0, 0.018, 1.65, 0.966, -4.0, -48, 0, 0.018, 5.64, -17143.709, -6.8, -94, 0, 0.018, 6.01, 7736.432, -2.2, -19, 0, 0.018, 2.74, 31153.083, -1.9, 5, 0, 0.018, 4.58, 6116.355, -2.2, -19, 0, 0.018, 2.28, 46.401, 0.3, 0, 0, 0.018, 3.80, 10213.597, 1.4, 25, 0, 0.018, 2.84, 56281.132, -1.1, 36, 0, 0.018, 3.53, 8249.062, 1.5, 25, 0, 0.017, 4.43, 20871.911, -3, -13, 0, 0.017, 4.44, 627.596, 0, 0, 0, 0.017, 1.85, 628.308, 0, 0, 0, 0.017, 1.19, 8408.321, 2, 25, 0, 0.017, 1.95, 7214.056, -2, -19, 0, 0.017, 1.57, 7214.070, -2, -19, 0, 0.017, 1.65, 13870.811, -6, -60, 0, 0.017, 0.30, 22.542, -4, -44, 0, 0.017, 2.62, -119.445, 0, 0, 0, 0.016, 4.87, 5747.909, 2, 32, 0, 0.016, 4.45, 14339.108, -1, 6, 0, 0.016, 1.83, 41366.680, 0, 30, 0, 0.016, 4.53, 16309.618, -3, -23, 0, 0.016, 2.54, 15542.754, -1, 6, 0, 0.016, 6.05, 1203.646, 0, 0, 0, 0.015, 5.2, 2751.147, 0, 0, 0, 0.015, 1.8, -10699.924, -5, -69, 0, 0.015, 0.4, 22824.391, -3, -20, 0, 0.015, 2.1, 30666.756, -6, -39, 0, 0.015, 2.1, 6010.417, -2, -19, 0, 0.015, 0.7, -23729.470, -5, -75, 0, 0.015, 1.4, 14363.691, -1, 6, 0, 0.015, 5.8, 16900.689, -2, 0, 0, 0.015, 5.2, 23800.458, 3, 53, 0, 0.015, 5.3, 6035.000, -2, -19, 0, 0.015, 1.2, 8251.139, 2, 25, 0, 0.015, 3.6, -8.860, 0, 0, 0, 0.015, 0.8, 882.739, 0, 0, 0, 0.015, 3.0, 1021.329, 0, 0, 0, 0.015, 0.6, 23296.107, 1, 31, 0, 0.014, 5.4, 7227.181, 2, 25, 0, 0.014, 0.1, 7213.352, -2, -19, 0, 0.014, 4.0, 15506.706, 3, 50, 0, 0.014, 3.4, 7214.774, -2, -19, 0, 0.014, 4.6, 6665.385, -2, -19, 0, 0.014, 0.1, -8.636, -2, -22, 0, 0.014, 3.1, 15465.202, -1, 6, 0, 0.014, 4.9, 508.863, 0, 0, 0, 0.014, 3.5, 8406.244, 2, 25, 0, 0.014, 1.3, 13313.497, -8, -82, 0, 0.014, 2.8, 49276.619, -3, 0, 0, 0.014, 0.1, 30528.194, -3, -10, 0, 0.013, 1.7, 25128.050, 1, 31, 0, 0.013, 2.9, 14128.405, -1, 6, 0, 0.013, 3.4, 57395.761, 3, 80, 0, 0.013, 2.7, 13029.546, -1, 6, 0, 0.013, 3.9, 7802.556, -2, -19, 0, 0.013, 1.6, 8258.802, -2, -19, 0, 0.013, 2.2, 8417.709, -2, -19, 0, 0.013, 0.7, 9965.210, -2, -19, 0, 0.013, 3.4, 50391.247, 0, 48, 0, 0.013, 3.0, 7134.433, -2, -19, 0, 0.013, 2.9, 30599.182, -5, -31, 0, 0.013, 3.6, -9723.857, 1, 0, 0, 0.013, 4.8, 7607.084, -2, -19, 0, 0.012, 0.8, 23837.689, 1, 35, 0, 0.012, 3.6, 4.409, -4, -44, 0, 0.012, 5.0, 16657.031, 3, 50, 0, 0.012, 4.4, 16657.735, 3, 50, 0, 0.012, 1.1, 15578.803, -4, -38, 0, 0.012, 6.0, -11.490, 0, 0, 0, 0.012, 1.9, 8164.398, 0, 0, 0, 0.012, 2.4, 31852.372, -4, -17, 0, 0.012, 2.4, 6607.085, -2, -19, 0, 0.012, 4.2, 8359.870, 0, 0, 0, 0.012, 0.5, 5799.713, -2, -19, 0, 0.012, 2.7, 7220.622, 0, 0, 0, 0.012, 4.3, -139.720, 0, 0, 0, 0.012, 2.3, 13728.836, -2, -16, 0, 0.011, 3.6, 14912.146, 1, 31, 0, 0.011, 4.7, 14916.748, -2, -19, 0}, + {1.67680, 4.66926, 628.301955, -0.0266, 0.1, -0.005, 0.51642, 3.3721, 6585.760910, -2.158, -18.9, 0.09, 0.41383, 5.7277, 14914.452335, -0.635, 6.2, -0.04, 0.37115, 3.9695, 7700.389469, 1.550, 25.0, -0.12, 0.27560, 0.7416, 8956.993380, 1.496, 25.1, -0.13, 0.24599, 4.2253, -2.301200, 1.523, 25.1, -0.12, 0.07118, 0.1443, 7842.36482, -2.211, -19, 0.08, 0.06128, 2.4998, 16171.05625, -0.688, 6, 0, 0.04516, 0.443, 8399.67910, -0.36, 3, 0, 0.04048, 5.771, 14286.15038, -0.61, 6, 0, 0.03747, 4.626, 1256.60391, -0.05, 0, 0, 0.03707, 3.415, 5957.45895, -2.13, -19, 0.1, 0.03649, 1.800, 23243.14376, 0.89, 31, -0.2, 0.02438, 0.042, 16029.08089, 3.07, 50, -0.2, 0.02165, 1.017, -1742.93051, -3.68, -44, 0.2, 0.01923, 3.097, 17285.68480, 3.02, 50, -0.3, 0.01692, 1.280, 0.3286, 1.52, 25, -0.1, 0.01361, 0.298, 8326.3902, 3.05, 50, -0.2, 0.01293, 4.013, 7072.0875, 1.58, 25, -0.1, 0.01276, 4.413, 8330.9926, 0, 0, 0, 0.01270, 0.101, 8470.6668, -2.24, -19, 0.1, 0.01097, 1.203, 22128.5152, -2.82, -13, 0, 0.01088, 2.545, 15542.7543, -0.66, 6, 0, 0.00835, 0.190, 7214.0629, -2.18, -19, 0.1, 0.00734, 4.855, 24499.7477, 0.83, 31, -0.2, 0.00686, 5.130, 13799.8238, -4.34, -38, 0.2, 0.00631, 0.930, -486.3266, -3.73, -44, 0, 0.00585, 0.699, 9585.2953, 1.5, 25, 0, 0.00566, 4.073, 8328.3391, 1.5, 25, 0, 0.00566, 0.638, 8329.0437, 1.5, 25, 0, 0.00539, 2.472, -1952.4800, 0.6, 7, 0, 0.00509, 2.88, -0.7113, 0, 0, 0, 0.00469, 3.56, 30457.2066, -1.3, 12, 0, 0.00387, 0.78, -0.3523, 0, 0, 0, 0.00378, 1.84, 22614.8418, 0.9, 31, 0, 0.00362, 5.53, -695.8761, 0.6, 7, 0, 0.00317, 2.80, 16728.3705, 1.2, 28, 0, 0.00303, 6.07, 157.7344, 0, 0, 0, 0.00300, 2.53, 33.7570, -0.3, -4, 0, 0.00295, 4.16, 31571.8352, 2.4, 56, 0, 0.00289, 5.98, 7211.7617, -0.7, 6, 0, 0.00285, 2.06, 15540.4531, 0.9, 31, 0, 0.00283, 2.65, 2.6298, 0, 0, 0, 0.00282, 6.17, 15545.0555, -2.2, -19, 0, 0.00278, 1.23, -39.8149, 0, 0, 0, 0.00272, 3.82, 7216.3641, -3.7, -44, 0, 0.00270, 4.37, 70.9877, -1.9, -22, 0, 0.00256, 5.81, 13657.8484, -0.6, 6, 0, 0.00244, 5.64, -0.2237, 1.5, 25, 0, 0.00240, 2.96, 8311.7707, -2.2, -19, 0, 0.00239, 0.87, -33.7814, 0.3, 4, 0, 0.00216, 2.31, 15.9995, -2.2, -19, 0, 0.00186, 3.46, 5329.1570, -2.1, -19, 0, 0.00169, 2.40, 24357.772, 4.6, 75, 0, 0.00161, 5.80, 8329.403, 1.5, 25, 0, 0.00161, 5.20, 8327.980, 1.5, 25, 0, 0.00160, 4.26, 23385.119, -2.9, -13, 0, 0.00156, 1.26, 550.755, 0, 0, 0, 0.00155, 1.25, 21500.213, -2.8, -13, 0, 0.00152, 0.60, -16.921, -3.7, -44, 0, 0.00150, 2.71, -79.630, 0, 0, 0, 0.00150, 5.29, 15.542, 0, 0, 0, 0.00148, 1.06, -2371.232, -3.7, -44, 0, 0.00141, 0.77, 8328.691, 1.5, 25, 0, 0.00141, 3.67, 7143.075, -0.3, 0, 0, 0.00138, 5.45, 25614.376, 4.5, 75, 0, 0.00129, 4.90, 23871.446, 0.9, 31, 0, 0.00126, 4.03, 141.975, -3.8, -44, 0, 0.00124, 6.01, 522.369, 0, 0, 0, 0.00120, 4.94, -10071.622, -5.2, -69, 0, 0.00118, 5.07, -15.419, -2.2, -19, 0, 0.00107, 3.49, 23452.693, -3.4, -20, 0, 0.00104, 4.78, 17495.234, -1.3, 0, 0, 0.00103, 1.44, -18.049, -2.2, -19, 0, 0.00102, 5.63, 15542.402, -0.7, 6, 0, 0.00102, 2.59, 15543.107, -0.7, 6, 0, 0.00100, 4.11, -6.559, -1.9, -22, 0, 0.00097, 0.08, 15400.779, 3.1, 50, 0, 0.00096, 5.84, 31781.385, -1.9, 5, 0, 0.00094, 1.08, 8328.363, 0, 0, 0, 0.00094, 2.46, 16799.358, -0.7, 6, 0, 0.00094, 1.69, 6376.211, 2.2, 32, 0, 0.00093, 3.64, 8329.020, 3.0, 50, 0, 0.00093, 2.65, 16655.082, 4.6, 75, 0, 0.00090, 1.90, 15056.428, -4.4, -38, 0, 0.00089, 1.59, 52.969, 0, 0, 0, 0.00088, 2.02, -8257.704, -3.4, -47, 0, 0.00088, 3.02, 7213.711, -2.2, -19, 0, 0.00087, 0.50, 7214.415, -2.2, -19, 0, 0.00087, 0.49, 16659.684, 1.5, 25, 0, 0.00082, 5.64, -4.931, 1.5, 25, 0, 0.00079, 5.17, 13171.522, -4.3, -38, 0, 0.00076, 3.60, 29828.905, -1.3, 12, 0, 0.00076, 4.08, 24567.322, 0.3, 24, 0, 0.00076, 4.58, 1884.906, -0.1, 0, 0, 0.00073, 0.33, 31713.811, -1.4, 12, 0, 0.00073, 0.93, 32828.439, 2.4, 56, 0, 0.00071, 5.91, 38785.898, 0.2, 37, 0, 0.00069, 2.20, 15613.742, -2.5, -16, 0, 0.00066, 3.87, 15.732, -2.5, -23, 0, 0.00066, 0.86, 25823.926, 0.2, 24, 0, 0.00065, 2.52, 8170.957, 1.5, 25, 0, 0.00063, 0.18, 8322.132, -0.3, 0, 0, 0.00060, 5.84, 8326.062, 1.5, 25, 0, 0.00060, 5.15, 8331.321, 1.5, 25, 0, 0.00060, 2.18, 8486.426, 1.5, 25, 0, 0.00058, 2.30, -1.731, -4, -44, 0, 0.00058, 5.43, 14357.138, -2, -16, 0, 0.00057, 3.09, 8294.910, 2, 29, 0, 0.00057, 4.67, -8362.473, -1, -21, 0, 0.00056, 4.15, 16833.151, -1, 0, 0, 0.00054, 1.93, 7056.329, -2, -19, 0, 0.00054, 5.27, 8315.574, -2, -19, 0, 0.00052, 5.6, 8311.418, -2, -19, 0, 0.00052, 2.7, -77.552, 0, 0, 0, 0.00051, 4.3, 7230.984, 2, 25, 0, 0.00050, 0.4, -0.508, 0, 0, 0, 0.00049, 5.4, 7211.433, -2, -19, 0, 0.00049, 4.4, 7216.693, -2, -19, 0, 0.00049, 4.3, 16864.631, 0, 24, 0, 0.00049, 2.2, 16869.234, -3, -26, 0, 0.00047, 6.1, 627.596, 0, 0, 0, 0.00047, 5.0, 12.619, 1, 7, 0, 0.00045, 4.9, -8815.018, -5, -69, 0, 0.00044, 1.6, 62.133, -2, -19, 0, 0.00042, 2.9, -13.118, -4, -44, 0, 0.00042, 4.1, -119.445, 0, 0, 0, 0.00041, 4.3, 22756.817, -3, -13, 0, 0.00041, 3.6, 8288.877, 2, 25, 0, 0.00040, 0.5, 6663.308, -2, -19, 0, 0.00040, 1.1, 8368.506, 2, 25, 0, 0.00039, 4.1, 6443.786, 2, 25, 0, 0.00039, 3.1, 16657.383, 3, 50, 0, 0.00038, 0.1, 16657.031, 3, 50, 0, 0.00038, 3.0, 16657.735, 3, 50, 0, 0.00038, 4.6, 23942.433, -1, 9, 0, 0.00037, 4.3, 15385.020, -1, 6, 0, 0.00037, 5.0, 548.678, 0, 0, 0, 0.00036, 1.8, 7213.352, -2, -19, 0, 0.00036, 1.7, 7214.774, -2, -19, 0, 0.00035, 1.1, 7777.936, 2, 25, 0, 0.00035, 1.6, -8.860, 0, 0, 0, 0.00035, 4.4, 23869.145, 2, 56, 0, 0.00035, 2.0, 6691.693, -2, -19, 0, 0.00034, 1.3, -1185.616, -2, -22, 0, 0.00034, 2.2, 23873.747, -1, 6, 0, 0.00033, 2.0, -235.287, 0, 0, 0, 0.00033, 3.1, 17913.987, 3, 50, 0, 0.00033, 1.0, 8351.233, -2, -19, 0}, + {0.004870, 4.6693, 628.30196, -0.027, 0, -0.01, 0.002280, 2.6746, -2.30120, 1.523, 25, -0.12, 0.001500, 3.372, 6585.76091, -2.16, -19, 0.1, 0.001200, 5.728, 14914.45233, -0.64, 6, 0, 0.001080, 3.969, 7700.38947, 1.55, 25, -0.1, 0.000800, 0.742, 8956.99338, 1.50, 25, -0.1, 0.000254, 6.002, 0.3286, 1.52, 25, -0.1, 0.000210, 0.144, 7842.3648, -2.21, -19, 0, 0.000180, 2.500, 16171.0562, -0.7, 6, 0, 0.000130, 0.44, 8399.6791, -0.4, 3, 0, 0.000126, 5.03, 8326.3902, 3.0, 50, 0, 0.000120, 5.77, 14286.1504, -0.6, 6, 0, 0.000118, 5.96, 8330.9926, 0, 0, 0, 0.000110, 1.80, 23243.1438, 0.9, 31, 0, 0.000110, 3.42, 5957.4590, -2.1, -19, 0, 0.000110, 4.63, 1256.6039, -0.1, 0, 0, 0.000099, 4.70, -0.7113, 0, 0, 0, 0.000070, 0.04, 16029.0809, 3.1, 50, 0, 0.000070, 5.14, 8328.3391, 1.5, 25, 0, 0.000070, 5.85, 8329.0437, 1.5, 25, 0, 0.000060, 1.02, -1742.9305, -3.7, -44, 0, 0.000060, 3.10, 17285.6848, 3.0, 50, 0, 0.000054, 5.69, -0.352, 0, 0, 0, 0.000043, 0.52, 15.542, 0, 0, 0, 0.000041, 2.03, 2.630, 0, 0, 0, 0.000040, 0.10, 8470.667, -2.2, -19, 0, 0.000040, 4.01, 7072.088, 1.6, 25, 0, 0.000036, 2.93, -8.860, -0.3, 0, 0, 0.000030, 1.20, 22128.515, -2.8, -13, 0, 0.000030, 2.54, 15542.754, -0.7, 6, 0, 0.000027, 4.43, 7211.762, -0.7, 6, 0, 0.000026, 0.51, 15540.453, 0.9, 31, 0, 0.000026, 1.44, 15545.055, -2.2, -19, 0, 0.000025, 5.37, 7216.364, -3.7, -44, 0}, + {0.00001200, 1.041, -2.3012, 1.52, 25, -0.1, 0.00000170, 0.31, -0.711, 0, 0, 0} + }; + private static final double[] QI_KB = { + 1640650.479938, 15.21842500, + 1642476.703182, 15.21874996, + 1683430.515601, 15.218750011, + 1752157.640664, 15.218749978, + 1807675.003759, 15.218620279, + 1883627.765182, 15.218612292, + 1907369.128100, 15.218449176, + 1936603.140413, 15.218425000, + 1939145.524180, 15.218466998, + 1947180.798300, 15.218524844, + 1964362.041824, 15.218533526, + 1987372.340971, 15.218513908, + 1999653.819126, 15.218530782, + 2007445.469786, 15.218535181, + 2021324.917146, 15.218526248, + 2047257.232342, 15.218519654, + 2070282.898213, 15.218425000, + 2073204.872850, 15.218515221, + 2080144.500926, 15.218530782, + 2086703.688963, 15.218523776, + 2110033.182763, 15.218425000, + 2111190.300888, 15.218425000, + 2113731.271005, 15.218515671, + 2120670.840263, 15.218425000, + 2123973.309063, 15.218425000, + 2125068.997336, 15.218477932, + 2136026.312633, 15.218472436, + 2156099.495538, 15.218425000, + 2159021.324663, 15.218425000, + 2162308.575254, 15.218461742, + 2178485.706538, 15.218425000, + 2178759.662849, 15.218445786, + 2185334.020800, 15.218425000, + 2187525.481425, 15.218425000, + 2188621.191481, 15.218437494, + 2322147.76 + }; + private static final double[] SHUO_KB = {1457698.231017, 29.53067166, 1546082.512234, 29.53085106, 1640640.735300, 29.53060000, 1642472.151543, 29.53085439, 1683430.509300, 29.53086148, 1752148.041079, 29.53085097, 1807665.420323, 29.53059851, 1883618.114100, 29.53060000, 1907360.704700, 29.53060000, 1936596.224900, 29.53060000, 1939135.675300, 29.53060000, 1947168.00}; + private static final String QB = decode("FrcFs22AFsckF2tsDtFqEtF1posFdFgiFseFtmelpsEfhkF2anmelpFlF1ikrotcnEqEq2FfqmcDsrFor22FgFrcgDscFs22FgEeFtE2sfFs22sCoEsaF2tsD1FpeE2eFsssEciFsFnmelpFcFhkF2tcnEqEpFgkrotcnEqrEtFermcDsrE222FgBmcmr22DaEfnaF222sD1FpeForeF2tssEfiFpEoeFssD1iFstEqFppDgFstcnEqEpFg11FscnEqrAoAF2ClAEsDmDtCtBaDlAFbAEpAAAAAD2FgBiBqoBbnBaBoAAAAAAAEgDqAdBqAFrBaBoACdAAf1AACgAAAeBbCamDgEifAE2AABa1C1BgFdiAAACoCeE1ADiEifDaAEqAAFe1AcFbcAAAAAF1iFaAAACpACmFmAAAAAAAACrDaAAADG0"); + private static final String SB = decode("EqoFscDcrFpmEsF2DfFideFelFpFfFfFiaipqti1ksttikptikqckstekqttgkqttgkqteksttikptikq2fjstgjqttjkqttgkqtekstfkptikq2tijstgjiFkirFsAeACoFsiDaDiADc1AFbBfgdfikijFifegF1FhaikgFag1E2btaieeibggiffdeigFfqDfaiBkF1kEaikhkigeidhhdiegcFfakF1ggkidbiaedksaFffckekidhhdhdikcikiakicjF1deedFhFccgicdekgiFbiaikcfi1kbFibefgEgFdcFkFeFkdcfkF1kfkcickEiFkDacFiEfbiaejcFfffkhkdgkaiei1ehigikhdFikfckF1dhhdikcfgjikhfjicjicgiehdikcikggcifgiejF1jkieFhegikggcikFegiegkfjebhigikggcikdgkaFkijcfkcikfkcifikiggkaeeigefkcdfcfkhkdgkegieidhijcFfakhfgeidieidiegikhfkfckfcjbdehdikggikgkfkicjicjF1dbidikFiggcifgiejkiegkigcdiegfggcikdbgfgefjF1kfegikggcikdgFkeeijcfkcikfkekcikdgkabhkFikaffcfkhkdgkegbiaekfkiakicjhfgqdq2fkiakgkfkhfkfcjiekgFebicggbedF1jikejbbbiakgbgkacgiejkijjgigfiakggfggcibFifjefjF1kfekdgjcibFeFkijcfkfhkfkeaieigekgbhkfikidfcjeaibgekgdkiffiffkiakF1jhbakgdki1dj1ikfkicjicjieeFkgdkicggkighdF1jfgkgfgbdkicggfggkidFkiekgijkeigfiskiggfaidheigF1jekijcikickiggkidhhdbgcfkFikikhkigeidieFikggikhkffaffijhidhhakgdkhkijF1kiakF1kfheakgdkifiggkigicjiejkieedikgdfcggkigieeiejfgkgkigbgikicggkiaideeijkefjeijikhkiggkiaidheigcikaikffikijgkiahi1hhdikgjfifaakekighie1hiaikggikhkffakicjhiahaikggikhkijF1kfejfeFhidikggiffiggkigicjiekgieeigikggiffiggkidheigkgfjkeigiegikifiggkidhedeijcfkFikikhkiggkidhh1ehigcikaffkhkiggkidhh1hhigikekfiFkFikcidhh1hitcikggikhkfkicjicghiediaikggikhkijbjfejfeFhaikggifikiggkigiejkikgkgieeigikggiffiggkigieeigekijcijikggifikiggkideedeijkefkfckikhkiggkidhh1ehijcikaffkhkiggkidhh1hhigikhkikFikfckcidhh1hiaikgjikhfjicjicgiehdikcikggifikigiejfejkieFhegikggifikiggfghigkfjeijkhigikggifikiggkigieeijcijcikfksikifikiggkidehdeijcfdckikhkiggkhghh1ehijikifffffkhsFngErD1pAfBoDd1BlEtFqA2AqoEpDqElAEsEeB2BmADlDkqBtC1FnEpDqnEmFsFsAFnllBbFmDsDiCtDmAB2BmtCgpEplCpAEiBiEoFqFtEqsDcCnFtADnFlEgdkEgmEtEsCtDmADqFtAFrAtEcCqAE1BoFqC1F1DrFtBmFtAC2ACnFaoCgADcADcCcFfoFtDlAFgmFqBq2bpEoAEmkqnEeCtAE1bAEqgDfFfCrgEcBrACfAAABqAAB1AAClEnFeCtCgAADqDoBmtAAACbFiAAADsEtBqAB2FsDqpFqEmFsCeDtFlCeDtoEpClEqAAFrAFoCgFmFsFqEnAEcCqFeCtFtEnAEeFtAAEkFnErAABbFkADnAAeCtFeAfBoAEpFtAABtFqAApDcCGJ"); + + private static String decode(String s) { + String o = "0000000000"; + String o2 = o + o; + s = s.replace("J", "00"); + s = s.replace("I", "000"); + s = s.replace("H", "0000"); + s = s.replace("G", "00000"); + s = s.replace("t", "02"); + s = s.replace("s", "002"); + s = s.replace("r", "0002"); + s = s.replace("q", "00002"); + s = s.replace("p", "000002"); + s = s.replace("o", "0000002"); + s = s.replace("n", "00000002"); + s = s.replace("m", "000000002"); + s = s.replace("l", "0000000002"); + s = s.replace("k", "01"); + s = s.replace("j", "0101"); + s = s.replace("i", "001"); + s = s.replace("h", "001001"); + s = s.replace("g", "0001"); + s = s.replace("f", "00001"); + s = s.replace("e", "000001"); + s = s.replace("d", "0000001"); + s = s.replace("c", "00000001"); + s = s.replace("b", "000000001"); + s = s.replace("a", "0000000001"); + s = s.replace("A", o2 + o2 + o2); + s = s.replace("B", o2 + o2 + o); + s = s.replace("C", o2 + o2); + s = s.replace("D", o2 + o); + s = s.replace("E", o2); + s = s.replace("F", o); + return s; + } + + public static double nutationLon2(double t) { + double a = -1.742 * t, t2 = t * t, dl = 0; + for (int i = 0, j = NUT_B.length; i < j; i += 5) { + dl += (NUT_B[i + 3] + a) * Math.sin(NUT_B[i] + NUT_B[i + 1] * t + NUT_B[i + 2] * t2); + a = 0; + } + return dl / 100 / SECOND_PER_RAD; + } + + public static double eLon(double t, int n) { + t /= 10; + double v = 0, tn = 1; + int n1, n2; + int m; + double c; + int pn = 1; + double n0, m0 = XL0[pn + 1] - XL0[pn]; + for (int i = 0; i < 6; i++, tn *= t) { + n1 = (int) XL0[pn + i]; + n2 = (int) XL0[pn + 1 + i]; + n0 = n2 - n1; + if (n0 == 0) { + continue; + } + if (n < 0) { + m = n2; + } else { + m = (int) (3 * n * n0 / m0 + 0.5) + n1; + if (i != 0) { + m += 3; + } + if (m > n2) { + m = n2; + } + } + c = 0; + for (int j = n1; j < m; j += 3) { + c += XL0[j] * Math.cos(XL0[j + 1] + t * XL0[j + 2]); + } + v += c * tn; + } + v /= XL0[0]; + double t2 = t * t; + v += (-0.0728 - 2.7702 * t - 1.1019 * t2 - 0.0996 * t2 * t) / SECOND_PER_RAD; + return v; + } + + public static double mLon(double t, int n) { + int obl = XL1[0].length; + double tn = 1; + double v = 0; + int j; + double c; + double t2 = t * t, + t3 = t2 * t, + t4 = t3 * t, + t5 = t4 * t, + tx = t - 10; + v += (3.81034409 + 8399.684730072 * t - 3.319e-05 * t2 + 3.11e-08 * t3 - 2.033e-10 * t4) * SECOND_PER_RAD; + v += 5028.792262 * t + 1.1124406 * t2 + 0.00007699 * t3 - 0.000023479 * t4 - 0.0000000178 * t5; + if (tx > 0) { + v += -0.866 + 1.43 * tx + 0.054 * tx * tx; + } + t2 /= 1e4; + t3 /= 1e8; + t4 /= 1e8; + + n *= 6; + if (n < 0) { + n = obl; + } + for (int i = 0, x = XL1.length; i < x; i++, tn *= t) { + double[] f = XL1[i]; + int l = f.length; + int m = (int) (n * l / obl + 0.5); + if (i > 0) { + m += 6; + } + if (m >= l) { + m = l; + } + for (j = 0, c = 0; j < m; j += 6) { + c += f[j] * Math.cos(f[j + 1] + t * f[j + 2] + t2 * f[j + 3] + t3 * f[j + 4] + t4 * f[j + 5]); + } + v += c * tn; + } + v /= SECOND_PER_RAD; + return v; + } + + public static double gxcSunLon(double t) { + double t2 = t * t; + double v = -0.043126 + 628.301955 * t - 0.000002732 * t2; + double e = 0.016708634 - 0.000042037 * t - 0.0000001267 * t2; + return -20.49552 * (1 + e * Math.cos(v)) / SECOND_PER_RAD; + } + + public static double ev(double t) { + double f = 628.307585 * t; + return 628.332 + 21 * Math.sin(1.527 + f) + 0.44 * Math.sin(1.48 + f * 2) + 0.129 * Math.sin(5.82 + f) * t + 0.00055 * Math.sin(4.21 + f) * t * t; + } + + public static double saLon(double t, int n) { + return eLon(t, n) + nutationLon2(t) + gxcSunLon(t) + Math.PI; + } + + public static double dtExt(double y, double jsd) { + double dy = (y - 1820) / 100; + return -20 + jsd * dy * dy; + } + + public static double dtCalc(double y) { + int size = DT_AT.length; + double y0 = DT_AT[size - 2]; + double t0 = DT_AT[size - 1]; + if (y >= y0) { + double jsd = 31; + if (y > y0 + 100) { + return dtExt(y, jsd); + } + return dtExt(y, jsd) - (dtExt(y0, jsd) - t0) * (y0 + 100 - y) / 100; + } + int i; + for (i = 0; i < size; i += 5) { + if (y < DT_AT[i + 5]) { + break; + } + } + double t1 = (y - DT_AT[i]) / (DT_AT[i + 5] - DT_AT[i]) * 10, t2 = t1 * t1, t3 = t2 * t1; + return DT_AT[i + 1] + DT_AT[i + 2] * t1 + DT_AT[i + 3] * t2 + DT_AT[i + 4] * t3; + } + + public static double dtT(double t) { + return dtCalc(t / 365.2425 + 2000) / SECOND_PER_DAY; + } + + public static double mv(double t) { + double v = 8399.71 - 914 * Math.sin(0.7848 + 8328.691425 * t + 0.0001523 * t * t); + v -= 179 * Math.sin(2.543 + 15542.7543 * t) + 160 * Math.sin(0.1874 + 7214.0629 * t) + 62 * Math.sin(3.14 + 16657.3828 * t) + 34 * Math.sin(4.827 + 16866.9323 * t) + 22 * Math.sin(4.9 + 23871.4457 * t) + 12 * Math.sin(2.59 + 14914.4523 * t) + 7 * Math.sin(0.23 + 6585.7609 * t) + 5 * Math.sin(0.9 + 25195.624 * t) + 5 * Math.sin(2.32 - 7700.3895 * t) + 5 * Math.sin(3.88 + 8956.9934 * t) + 5 * Math.sin(0.49 + 7771.3771 * t); + return v; + } + + public static double saLonT(double w) { + double v = 628.3319653318; + double t = (w - 1.75347 - Math.PI) / v; + v = ev(t); + t += (w - saLon(t, 10)) / v; + v = ev(t); + t += (w - saLon(t, -1)) / v; + return t; + } + + public static double msaLon(double t, int mn, int sn) { + return mLon(t, mn) + (-3.4E-6) - (eLon(t, sn) + gxcSunLon(t) + Math.PI); + } + + public static double msaLonT(double w) { + double v = 7771.37714500204; + double t = (w + 1.08472) / v; + t += (w - msaLon(t, 3, 3)) / v; + v = mv(t) - ev(t); + t += (w - msaLon(t, 20, 10)) / v; + t += (w - msaLon(t, -1, 60)) / v; + return t; + } + + public static double saLonT2(double w) { + double v = 628.3319653318; + double t = (w - 1.75347 - Math.PI) / v; + t -= (0.000005297 * t * t + 0.0334166 * Math.cos(4.669257 + 628.307585 * t) + 0.0002061 * Math.cos(2.67823 + 628.307585 * t) * t) / v; + t += (w - eLon(t, 8) - Math.PI + (20.5 + 17.2 * Math.sin(2.1824 - 33.75705 * t)) / SECOND_PER_RAD) / v; + return t; + } + + public static double msaLonT2(double w) { + double v = 7771.37714500204; + double t = (w + 1.08472) / v; + double t2 = t * t; + t -= (-0.00003309 * t2 + 0.10976 * Math.cos(0.784758 + 8328.6914246 * t + 0.000152292 * t2) + 0.02224 * Math.cos(0.18740 + 7214.0628654 * t - 0.00021848 * t2) - 0.03342 * Math.cos(4.669257 + 628.307585 * t)) / v; + t2 = t * t; + double l = mLon(t, 20) - (4.8950632 + 628.3319653318 * t + 0.000005297 * t2 + 0.0334166 * Math.cos(4.669257 + 628.307585 * t) + 0.0002061 * Math.cos(2.67823 + 628.307585 * t) * t + 0.000349 * Math.cos(4.6261 + 1256.61517 * t) - 20.5 / SECOND_PER_RAD); + v = 7771.38 - 914 * Math.sin(0.7848 + 8328.691425 * t + 0.0001523 * t2) - 179 * Math.sin(2.543 + 15542.7543 * t) - 160 * Math.sin(0.1874 + 7214.0629 * t); + t += (w - l) / v; + return t; + } + + public static double qiHigh(double w) { + double t = saLonT2(w) * 36525; + t = t - dtT(t) + ONE_THIRD; + double v = ((t + 0.5) % 1) * SECOND_PER_DAY; + if (v < 1200 || v > SECOND_PER_DAY - 1200) { + t = saLonT(w) * 36525 - dtT(t) + ONE_THIRD; + } + return t; + } + + public static double shuoHigh(double w) { + double t = msaLonT2(w) * 36525; + t = t - dtT(t) + ONE_THIRD; + double v = ((t + 0.5) % 1) * SECOND_PER_DAY; + if (v < 1800 || v > SECOND_PER_DAY - 1800) { + t = msaLonT(w) * 36525 - dtT(t) + ONE_THIRD; + } + return t; + } + + public static double qiLow(double w) { + double v = 628.3319653318; + double t = (w - 4.895062166) / v; + t -= (53 * t * t + 334116 * Math.cos(4.67 + 628.307585 * t) + 2061 * Math.cos(2.678 + 628.3076 * t) * t) / v / 10000000; + double n = 48950621.66 + 6283319653.318 * t + 53 * t * t + 334166 * Math.cos(4.669257 + 628.307585 * t) + 3489 * Math.cos(4.6261 + 1256.61517 * t) + 2060.6 * Math.cos(2.67823 + 628.307585 * t) * t - 994 - 834 * Math.sin(2.1824 - 33.75705 * t); + t -= (n / 10000000 - w) / 628.332 + (32 * (t + 1.8) * (t + 1.8) - 20) / SECOND_PER_DAY / 36525; + return t * 36525 + ONE_THIRD; + } + + public static double shuoLow(double w) { + double v = 7771.37714500204; + double t = (w + 1.08472) / v; + t -= (-0.0000331 * t * t + 0.10976 * Math.cos(0.785 + 8328.6914 * t) + 0.02224 * Math.cos(0.187 + 7214.0629 * t) - 0.03342 * Math.cos(4.669 + 628.3076 * t)) / v + (32 * (t + 1.8) * (t + 1.8) - 20) / SECOND_PER_DAY / 36525; + return t * 36525 + ONE_THIRD; + } + + public static double calcShuo(double jd) { + int size = SHUO_KB.length; + double d = 0; + int pc = 14, i; + jd += 2451545; + double f1 = SHUO_KB[0] - pc, f2 = SHUO_KB[size - 1] - pc, f3 = 2436935; + if (jd < f1 || jd >= f3) { + d = Math.floor(shuoHigh(Math.floor((jd + pc - 2451551) / 29.5306) * PI_2) + 0.5); + } else if (jd >= f1 && jd < f2) { + for (i = 0; i < size; i += 2) { + if (jd + pc < SHUO_KB[i + 2]) { + break; + } + } + d = SHUO_KB[i] + SHUO_KB[i + 1] * Math.floor((jd + pc - SHUO_KB[i]) / SHUO_KB[i + 1]); + d = Math.floor(d + 0.5); + if (d == 1683460) { + d++; + } + d -= 2451545; + } else if (jd >= f2) { + d = Math.floor(shuoLow(Math.floor((jd + pc - 2451551) / 29.5306) * PI_2) + 0.5); + int from = (int) ((jd - f2) / 29.5306); + String n = SB.substring(from, from + 1); + if ("1".equals(n)) { + d += 1; + } else if ("2".equals(n)) { + d -= 1; + } + } + return d; + } + + public static double calcQi(double jd) { + int size = QI_KB.length; + double d = 0; + int pc = 7, i; + jd += 2451545; + double f1 = QI_KB[0] - pc, f2 = QI_KB[size - 1] - pc, f3 = 2436935; + if (jd < f1 || jd >= f3) { + d = Math.floor(qiHigh(Math.floor((jd + pc - 2451259) / 365.2422 * 24) * Math.PI / 12) + 0.5); + } else if (jd >= f1 && jd < f2) { + for (i = 0; i < size; i += 2) { + if (jd + pc < QI_KB[i + 2]) { + break; + } + } + d = QI_KB[i] + QI_KB[i + 1] * Math.floor((jd + pc - QI_KB[i]) / QI_KB[i + 1]); + d = Math.floor(d + 0.5); + if (d == 1683460) { + d++; + } + d -= 2451545; + } else if (jd >= f2) { + d = Math.floor(qiLow(Math.floor((jd + pc - 2451259) / 365.2422 * 24) * Math.PI / 12) + 0.5); + int from = (int) ((jd - f2) / 365.2422 * 24); + String n = QB.substring(from, from + 1); + if ("1".equals(n)) { + d += 1; + } else if ("2".equals(n)) { + d -= 1; + } + } + return d; + } + + public static double qiAccurate(double w) { + double t = saLonT(w) * 36525; + return t - dtT(t) + ONE_THIRD; + } + + public static double qiAccurate2(double jd) { + double d = Math.PI / 12; + double w = Math.floor((jd + 293) / 365.2422 * 24) * d; + double a = qiAccurate(w); + if (a - jd > 5) { + return qiAccurate(w - d); + } + if (a - jd < -5) { + return qiAccurate(w + d); + } + return a; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Holiday.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Holiday.java new file mode 100755 index 0000000000..8f364218de --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Holiday.java @@ -0,0 +1,360 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture; + +import org.miaixz.bus.core.center.date.culture.solar.SolarDay; +import org.miaixz.bus.core.center.date.culture.solar.SolarMonth; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 法定假日(自2001-12-29起) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Holiday extends Loops { + + /** + * 法定假日名称 + */ + public static final String[] NAMES = { + "元旦节", "春节", "清明节", "劳动节", "端午节", "中秋节", "国庆节", "国庆中秋", "抗战胜利日" + }; + + /** + * 默认节假日数据 + * 完整格式:日期+下标+调休+节日 + * 日期:YYYYMMDD + * 节日:{@link Holiday#NAMES} 下标位置,例如,元旦-0,抗战胜利日-8 + * 调休:0工作日,1调休 + * 节日:YYYYMMDD + */ + private static final String DATA = "200112290020020101" + "200112300020020101" + + "200201010120020101" + "200201020120020101" + "200201030120020101" + "200202091020020212" + + "200202101020020212" + "200202121120020212" + "200202131120020212" + "200202141120020212" + + "200202151120020212" + "200202161120020212" + "200202171120020212" + "200202181120020212" + + "200204273020020501" + "200204283020020501" + "200205013120020501" + "200205023120020501" + + "200205033120020501" + "200205043120020501" + "200205053120020501" + "200205063120020501" + + "200205073120021001" + "200209286020021001" + "200209296020021001" + "200210016120021001" + + "200210026120021001" + "200210036120021001" + "200210046120021001" + "200210056120021001" + + "200210066120021001" + "200210076120021001" + "200301010120030101" + "200302011120030201" + + "200302021120030201" + "200302031120030201" + "200302041120030201" + "200302051120030201" + + "200302061120030201" + "200302071120030201" + "200302081020030201" + "200302091020030201" + + "200304263020030501" + "200304273020030501" + "200305013120030501" + "200305023120030501" + + "200305033120030501" + "200305043120030501" + "200305053120030501" + "200305063120030501" + + "200305073120031001" + "200309276020031001" + "200309286020031001" + "200310016120031001" + + "200310026120031001" + "200310036120031001" + "200310046120031001" + "200310056120031001" + + "200310066120031001" + "200310076120031001" + "200401010120040101" + "200401171020040122" + + "200401181020040122" + "200401221120040122" + "200401231120040122" + "200401241120040122" + + "200401251120040122" + "200401261120040122" + "200401271120040122" + "200401281120040122" + + "200405013120040501" + "200405023120040501" + "200405033120040501" + "200405043120040501" + + "200405053120040501" + "200405063120040501" + "200405073120041001" + "200405083020040501" + + "200405093020040501" + "200410016120041001" + "200410026120041001" + "200410036120041001" + + "200410046120041001" + "200410056120041001" + "200410066120041001" + "200410076120041001" + + "200410096020041001" + "200410106020041001" + "200501010120050101" + "200501020120050101" + + "200501030120050101" + "200502051020050209" + "200502061020050209" + "200502091120050209" + + "200502101120050209" + "200502111120050209" + "200502121120050209" + "200502131120050209" + + "200502141120050209" + "200502151120050209" + "200504303020050501" + "200505013120050501" + + "200505023120050501" + "200505033120050501" + "200505043120050501" + "200505053120050501" + + "200505063120050501" + "200505073120051001" + "200505083020050501" + "200510016120051001" + + "200510026120051001" + "200510036120051001" + "200510046120051001" + "200510056120051001" + + "200510066120051001" + "200510076120051001" + "200510086020051001" + "200510096020051001" + + "200512310020060101" + "200601010120060101" + "200601020120060101" + "200601030120060101" + + "200601281020060129" + "200601291120060129" + "200601301120060129" + "200601311120060129" + + "200602011120060129" + "200602021120060129" + "200602031120060129" + "200602041120060129" + + "200602051020060129" + "200604293020060501" + "200604303020060501" + "200605013120060501" + + "200605023120060501" + "200605033120060501" + "200605043120060501" + "200605053120060501" + + "200605063120060501" + "200605073120061001" + "200609306020061001" + "200610016120061001" + + "200610026120061001" + "200610036120061001" + "200610046120061001" + "200610056120061001" + + "200610066120061001" + "200610076120061001" + "200610086020061001" + "200612300020070101" + + "200612310020070101" + "200701010120070101" + "200701020120070101" + "200701030120070101" + + "200702171020070218" + "200702181120070218" + "200702191120070218" + "200702201120070218" + + "200702211120070218" + "200702221120070218" + "200702231120070218" + "200702241120070218" + + "200702251020070218" + "200704283020070501" + "200704293020070501" + "200705013120070501" + + "200705023120070501" + "200705033120070501" + "200705043120070501" + "200705053120070501" + + "200705063120070501" + "200705073120070501" + "200709296020071001" + "200709306020071001" + + "200710016120071001" + "200710026120071001" + "200710036120071001" + "200710046120071001" + + "200710056120071001" + "200710066120071001" + "200710076120071001" + "200712290020080101" + + "200712300120080101" + "200712310120080101" + "200801010120080101" + "200802021020080206" + + "200802031020080206" + "200802061120080206" + "200802071120080206" + "200802081120080206" + + "200802091120080206" + "200802101120080206" + "200802111120080206" + "200802121120080206" + + "200804042120080404" + "200804052120080404" + "200804062120080404" + "200805013120080501" + + "200805023120080501" + "200805033120080501" + "200805043020080501" + "200806074120080608" + + "200806084120080608" + "200806094120080608" + "200809135120080914" + "200809145120080914" + + "200809155120080914" + "200809276020081001" + "200809286020081001" + "200809296120081001" + + "200809306120081001" + "200810016120081001" + "200810026120081001" + "200810036120081001" + + "200810046120081001" + "200810056120081001" + "200901010120090101" + "200901020120090101" + + "200901030120090101" + "200901040020090101" + "200901241020090125" + "200901251120090125" + + "200901261120090125" + "200901271120090125" + "200901281120090125" + "200901291120090125" + + "200901301120090125" + "200901311120090125" + "200902011020090125" + "200904042120090404" + + "200904052120090404" + "200904062120090404" + "200905013120090501" + "200905023120090501" + + "200905033120090501" + "200905284120090528" + "200905294120090528" + "200905304120090528" + + "200905314020090528" + "200909276020091001" + "200910016120091001" + "200910026120091001" + + "200910036120091001" + "200910046120091001" + "200910055120091003" + "200910065120091003" + + "200910075120091003" + "200910085120091003" + "200910105020091003" + "201001010120100101" + + "201001020120100101" + "201001030120100101" + "201002131120100213" + "201002141120100213" + + "201002151120100213" + "201002161120100213" + "201002171120100213" + "201002181120100213" + + "201002191120100213" + "201002201020100213" + "201002211020100213" + "201004032120100405" + + "201004042120100405" + "201004052120100405" + "201005013120100501" + "201005023120100501" + + "201005033120100501" + "201006124020100616" + "201006134020100616" + "201006144120100616" + + "201006154120100616" + "201006164120100616" + "201009195020100922" + "201009225120100922" + + "201009235120100922" + "201009245120100922" + "201009255020100922" + "201009266020101001" + + "201010016120101001" + "201010026120101001" + "201010036120101001" + "201010046120101001" + + "201010056120101001" + "201010066120101001" + "201010076120101001" + "201010096020101001" + + "201101010120110101" + "201101020120110101" + "201101030120110101" + "201101301020110203" + + "201102021120110203" + "201102031120110203" + "201102041120110203" + "201102051120110203" + + "201102061120110203" + "201102071120110203" + "201102081120110203" + "201102121020110203" + + "201104022020110405" + "201104032120110405" + "201104042120110405" + "201104052120110405" + + "201104303120110501" + "201105013120110501" + "201105023120110501" + "201106044120110606" + + "201106054120110606" + "201106064120110606" + "201109105120110912" + "201109115120110912" + + "201109125120110912" + "201110016120111001" + "201110026120111001" + "201110036120111001" + + "201110046120111001" + "201110056120111001" + "201110066120111001" + "201110076120111001" + + "201110086020111001" + "201110096020111001" + "201112310020120101" + "201201010120120101" + + "201201020120120101" + "201201030120120101" + "201201211020120123" + "201201221120120123" + + "201201231120120123" + "201201241120120123" + "201201251120120123" + "201201261120120123" + + "201201271120120123" + "201201281120120123" + "201201291020120123" + "201203312020120404" + + "201204012020120404" + "201204022120120404" + "201204032120120404" + "201204042120120404" + + "201204283020120501" + "201204293120120501" + "201204303120120501" + "201205013120120501" + + "201205023020120501" + "201206224120120623" + "201206234120120623" + "201206244120120623" + + "201209295020120930" + "201209305120120930" + "201210016120121001" + "201210026120121001" + + "201210036120121001" + "201210046120121001" + "201210056120121001" + "201210066120121001" + + "201210076120121001" + "201210086020121001" + "201301010120130101" + "201301020120130101" + + "201301030120130101" + "201301050020130101" + "201301060020130101" + "201302091120130210" + + "201302101120130210" + "201302111120130210" + "201302121120130210" + "201302131120130210" + + "201302141120130210" + "201302151120130210" + "201302161020130210" + "201302171020130210" + + "201304042120130404" + "201304052120130404" + "201304062120130404" + "201304273020130501" + + "201304283020130501" + "201304293120130501" + "201304303120130501" + "201305013120130501" + + "201306084020130612" + "201306094020130612" + "201306104120130612" + "201306114120130612" + + "201306124120130612" + "201309195120130919" + "201309205120130919" + "201309215120130919" + + "201309225020130919" + "201309296020131001" + "201310016120131001" + "201310026120131001" + + "201310036120131001" + "201310046120131001" + "201310056120131001" + "201310066120131001" + + "201310076120131001" + "201401010120140101" + "201401261020140131" + "201401311120140131" + + "201402011120140131" + "201402021120140131" + "201402031120140131" + "201402041120140131" + + "201402051120140131" + "201402061120140131" + "201402081020140131" + "201404052120140405" + + "201404062120140405" + "201404072120140405" + "201405013120140501" + "201405023120140501" + + "201405033120140501" + "201405043020140501" + "201405314120140602" + "201406014120140602" + + "201406024120140602" + "201409065120140908" + "201409075120140908" + "201409085120140908" + + "201409286020141001" + "201410016120141001" + "201410026120141001" + "201410036120141001" + + "201410046120141004" + "201410056120141001" + "201410066120141001" + "201410076120141001" + + "201410116020141001" + "201501010120150101" + "201501020120150101" + "201501030120150101" + + "201501040020150101" + "201502151020150219" + "201502181120150219" + "201502191120150219" + + "201502201120150219" + "201502211120150219" + "201502221120150219" + "201502231120150219" + + "201502241120150219" + "201502281020150219" + "201504042120150405" + "201504052120150405" + + "201504062120150405" + "201505013120150501" + "201505023120150501" + "201505033120150501" + + "201506204120150620" + "201506214120150620" + "201506224120150620" + "201509038120150903" + + "201509048120150903" + "201509058120150903" + "201509068020150903" + "201509265120150927" + + "201509275120150927" + "201510016120151001" + "201510026120151001" + "201510036120151001" + + "201510046120151004" + "201510056120151001" + "201510066120151001" + "201510076120151001" + + "201510106020151001" + "201601010120160101" + "201601020120160101" + "201601030120160101" + + "201602061020160208" + "201602071120160208" + "201602081120160208" + "201602091120160208" + + "201602101120160208" + "201602111120160208" + "201602121120160208" + "201602131120160208" + + "201602141020160208" + "201604022120160404" + "201604032120160404" + "201604042120160404" + + "201604303120160501" + "201605013120160501" + "201605023120160501" + "201606094120160609" + + "201606104120160609" + "201606114120160609" + "201606124020160609" + "201609155120160915" + + "201609165120160915" + "201609175120160915" + "201609185020160915" + "201610016120161001" + + "201610026120161001" + "201610036120161001" + "201610046120161001" + "201610056120161001" + + "201610066120161001" + "201610076120161001" + "201610086020161001" + "201610096020161001" + + "201612310120170101" + "201701010120170101" + "201701020120170101" + "201701221020170128" + + "201701271120170128" + "201701281120170128" + "201701291120170128" + "201701301120170128" + + "201701311120170128" + "201702011120170128" + "201702021120170128" + "201702041020170128" + + "201704012020170404" + "201704022120170404" + "201704032120170404" + "201704042120170404" + + "201704293120170501" + "201704303120170501" + "201705013120170501" + "201705274020170530" + + "201705284120170530" + "201705294120170530" + "201705304120170530" + "201709306020171001" + + "201710016120171001" + "201710026120171001" + "201710036120171001" + "201710045120171004" + + "201710056120171001" + "201710066120171001" + "201710076120171001" + "201710086120171001" + + "201712300120180101" + "201712310120180101" + "201801010120180101" + "201802111020180216" + + "201802151120180216" + "201802161120180216" + "201802171120180216" + "201802181120180216" + + "201802191120180216" + "201802201120180216" + "201802211120180216" + "201802241020180216" + + "201804052120180405" + "201804062120180405" + "201804072120180405" + "201804082020180405" + + "201804283020180501" + "201804293120180501" + "201804303120180501" + "201805013120180501" + + "201806164120180618" + "201806174120180618" + "201806184120180618" + "201809225120180924" + + "201809235120180924" + "201809245120180924" + "201809296020181001" + "201809306020181001" + + "201810016120181001" + "201810026120181001" + "201810036120181001" + "201810046120181001" + + "201810056120181001" + "201810066120181001" + "201810076120181001" + "201812290020190101" + + "201812300120190101" + "201812310120190101" + "201901010120190101" + "201902021020190205" + + "201902031020190205" + "201902041120190205" + "201902051120190205" + "201902061120190205" + + "201902071120190205" + "201902081120190205" + "201902091120190205" + "201902101120190205" + + "201904052120190405" + "201904062120190405" + "201904072120190405" + "201904283020190501" + + "201905013120190501" + "201905023120190501" + "201905033120190501" + "201905043120190501" + + "201905053020190501" + "201906074120190607" + "201906084120190607" + "201906094120190607" + + "201909135120190913" + "201909145120190913" + "201909155120190913" + "201909296020191001" + + "201910016120191001" + "201910026120191001" + "201910036120191001" + "201910046120191001" + + "201910056120191001" + "201910066120191001" + "201910076120191001" + "201910126020191001" + + "202001010120200101" + "202001191020200125" + "202001241120200125" + "202001251120200125" + + "202001261120200125" + "202001271120200125" + "202001281120200125" + "202001291120200125" + + "202001301120200125" + "202001311120200125" + "202002011120200125" + "202002021120200125" + + "202004042120200404" + "202004052120200404" + "202004062120200404" + "202004263020200501" + + "202005013120200501" + "202005023120200501" + "202005033120200501" + "202005043120200501" + + "202005053120200501" + "202005093020200501" + "202006254120200625" + "202006264120200625" + + "202006274120200625" + "202006284020200625" + "202009277020201001" + "202010017120201001" + + "202010026120201001" + "202010036120201001" + "202010046120201001" + "202010056120201001" + + "202010066120201001" + "202010076120201001" + "202010086120201001" + "202010106020201001" + + "202101010120210101" + "202101020120210101" + "202101030120210101" + "202102071020210212" + + "202102111120210212" + "202102121120210212" + "202102131120210212" + "202102141120210212" + + "202102151120210212" + "202102161120210212" + "202102171120210212" + "202102201020210212" + + "202104032120210404" + "202104042120210404" + "202104052120210404" + "202104253020210501" + + "202105013120210501" + "202105023120210501" + "202105033120210501" + "202105043120210501" + + "202105053120210501" + "202105083020210501" + "202106124120210614" + "202106134120210614" + + "202106144120210614" + "202109185020210921" + "202109195120210921" + "202109205120210921" + + "202109215120210921" + "202109266020211001" + "202110016120211001" + "202110026120211001" + + "202110036120211001" + "202110046120211001" + "202110056120211001" + "202110066120211001" + + "202110076120211001" + "202110096020211001" + "202201010120220101" + "202201020120220101" + + "202201030120220101" + "202201291020220201" + "202201301020220201" + "202201311120220201" + + "202202011120220201" + "202202021120220201" + "202202031120220201" + "202202041120220201" + + "202202051120220201" + "202202061120220201" + "202204022020220405" + "202204032120220405" + + "202204042120220405" + "202204052120220405" + "202204243020220501" + "202204303120220501" + + "202205013120220501" + "202205023120220501" + "202205033120220501" + "202205043120220501" + + "202205073020220501" + "202206034120220603" + "202206044120220603" + "202206054120220603" + + "202209105120220910" + "202209115120220910" + "202209125120220910" + "202210016120221001" + + "202210026120221001" + "202210036120221001" + "202210046120221001" + "202210056120221001" + + "202210066120221001" + "202210076120221001" + "202210086020221001" + "202210096020221001" + + "202210096020221001" + "202212310120230101" + "202301010120230101" + "202301020120230101" + + "202301211120230122" + "202301221120230122" + "202301231120230122" + "202301241120230122" + + "202301251120230122" + "202301261120230122" + "202301271120230122" + "202301281020230122" + + "202301291020230122" + "202304052120230405" + "202304233020230501" + "202304293120230501" + + "202304303120230501" + "202305013120230501" + "202305023120230501" + "202305033120230501" + + "202305063020230501" + "202306224120230622" + "202306234120230622" + "202306244120230622" + + "202306254020230622" + "202309295120230929" + "202309306120231001" + "202310016120231001" + + "202310026120231001" + "202310036120231001" + "202310046120231001" + "202310056120231001" + + "202310066120231001" + "202310076020231001" + "202310086020231001" + "202312300120240101" + + "202312310120240101" + "202401010120240101" + "202402041020240210" + "202402101120240210" + + "202402111120240210" + "202402121120240210" + "202402131120240210" + "202402141120240210" + + "202402151120240210" + "202402161120240210" + "202402171120240210" + "202402181020240210" + + "202404042120240404" + "202404052120240404" + "202404062120240404" + "202404072020240404" + + "202404283020240501" + "202405013120240501" + "202405023120240501" + "202405033120240501" + + "202405043120240501" + "202405053120240501" + "202405113020240501" + "202406084120240610" + + "202406094120240610" + "202406104120240610" + "202409145020240917" + "202409155120240917" + + "202409165120240917" + "202409175120240917" + "202409296020241001" + "202410016120241001" + + "202410026120241001" + "202410036120241001" + "202410046120241001" + "202410056120241001" + + "202410066120241001" + "202410076120241001" + "202410126020241001"; + /** + * 公历日 + */ + protected SolarDay day; + + /** + * 名称 + */ + protected String name; + + /** + * 是否上班 + */ + protected boolean work; + + public Holiday(int year, int month, int day, String data) { + this.day = SolarDay.fromYmd(year, month, day); + work = '0' == data.charAt(8); + name = NAMES[data.charAt(9) - '0']; + } + + + public static Holiday fromYmd(int year, int month, int day) { + Matcher matcher = Pattern.compile(String.format("%04d%02d%02d[0-1][0-8][\\+|-]\\d{2}", year, month, day)).matcher(DATA); + if (!matcher.find()) { + return null; + } + return new Holiday(year, month, day, matcher.group()); + } + + public Holiday next(int n) { + SolarMonth m = day.getMonth(); + int year = m.getYear().getYear(); + int month = m.getMonth(); + if (n == 0) { + return fromYmd(year, month, day.getDay()); + } + List data = new ArrayList<>(); + String reg = "%04d\\d{4}[0-1][0-8][\\+|-]\\d{2}"; + String today = String.format("%04d%02d%02d", year, month, day.getDay()); + Matcher matcher = Pattern.compile(String.format(reg, year)).matcher(DATA); + while (matcher.find()) { + data.add(matcher.group()); + } + int index = -1; + int size = data.size(); + for (int i = 0; i < size; i++) { + if (data.get(i).startsWith(today)) { + index = i; + break; + } + } + if (index == -1) { + return null; + } + index += n; + int y = year; + boolean forward = n > 0; + int add = forward ? 1 : -1; + while (forward ? (index >= size) : (index < 0)) { + if (forward) { + index -= size; + } + y += add; + data.clear(); + matcher = Pattern.compile(String.format(reg, y)).matcher(DATA); + while (matcher.find()) { + data.add(matcher.group()); + } + size = data.size(); + if (size < 1) { + return null; + } + if (!forward) { + index += size; + } + } + String d = data.get(index); + return new Holiday(Integer.parseInt(d.substring(0, 4)), Integer.parseInt(d.substring(4, 6)), Integer.parseInt(d.substring(6, 8)), d); + } + + @Override + public String toString() { + return String.format("%s %s(%s)", day, name, work ? "班" : "休"); + } + + public SolarDay getDay() { + return day; + } + + public String getName() { + return name; + } + + /** + * 是否上班 + * + * @return true/false + */ + public boolean isWork() { + return work; + } + +} diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/Interceptor.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Loops.java similarity index 93% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/Interceptor.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Loops.java index 4bdb651286..cc5985f413 100755 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/Interceptor.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Loops.java @@ -23,16 +23,14 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy; +package org.miaixz.bus.core.center.date.culture; /** - * "拦截"方法调用 + * 抽象的轮回 * * @author Kimi Liu * @since Java 17+ */ -public interface Interceptor { - - Object intercept(Invocation invocation) throws Throwable; +public abstract class Loops extends Tradition implements Culture { } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/RateLimiter.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Replenish.java similarity index 73% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/RateLimiter.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Replenish.java index dfba6cacf1..930ddebef2 100755 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/RateLimiter.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Replenish.java @@ -23,47 +23,53 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.annotation; +package org.miaixz.bus.core.center.date.culture; -import org.miaixz.bus.core.lang.Normal; - -import java.lang.annotation.*; +import org.miaixz.bus.core.center.date.Almanac; /** - * 限流 + * 附加索引的传统文化 * * @author Kimi Liu * @since Java 17+ */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Inherited -@Documented -public @interface RateLimiter { - - String limiter() default Normal.EMPTY; - - String key() default Normal.EMPTY; +public abstract class Replenish extends Tradition { - String fallback() default "defaultFallbackResolver"; - - String errorHandler() default "defaultErrorHandler"; - - String[] argumentInjectors() default {}; + /** + * 传统文化 + */ + protected Tradition tradition; /** - * 限制的频率 默认 1次/秒 - * - * @return the double + * 天索引 */ - double rate() default 10.0d; + protected int dayIndex; + + public Replenish(Tradition tradition, int dayIndex) { + this.tradition = tradition; + this.dayIndex = dayIndex; + } /** - * 最大可累计的令牌容量 - * 默认为 1 且最小为1 + * 天索引 * - * @return the long + * @return 索引 */ - long capacity() default 10; + public int getDayIndex() { + return dayIndex; + } + + protected Almanac getTradition() { + return tradition; + } + + @Override + public String toString() { + return String.format("%s第%d天", tradition, dayIndex + 1); + } + + public String getName() { + return tradition.getName(); + } } diff --git a/bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/GcEntity.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Samsara.java old mode 100644 new mode 100755 similarity index 55% rename from bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/GcEntity.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Samsara.java index 4e1bc5017f..5be9e1d9e8 --- a/bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/GcEntity.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Samsara.java @@ -23,101 +23,109 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.tracer.monitor; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +package org.miaixz.bus.core.center.date.culture; /** + * 轮回的信息 + * 季度/月/星期/日/小时/分钟等 + * * @author Kimi Liu * @since Java 17+ */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class GcEntity { +public abstract class Samsara extends Loops { /** - * 当前应用进程ID - */ - private Integer id; - /** - * 当前应用名称 - */ - private String name; - /** - * 时间 格式 MM/dd HH:mm" + * 名称列表 */ - private String date; + protected String[] names; /** - * Survivor0空间的大小。单位KB。 - */ - private String s0c; - /** - * Survivor1空间的大小。单位KB。 - */ - private String s1c; - /** - * Survivor0已用空间的大小。单位KB - */ - private String s0u; - /** - * Survivor1已用空间的大小。单位KB。 - */ - private String s1u; - /** - * Eden空间的大小。单位KB。 - */ - private String ec; - /** - * Eden已用空间的大小。单位KB。 + * 索引,从0开始 */ - private String eu; - /** - * 老年代空间的大小。单位KB。 - */ - private String oc; - /** - * 老年代已用空间的大小。单位KB。 - */ - private String OU; - /** - * 元空间的大小(Metaspace) - */ - private String mc; + protected int index; + /** - * 元空间已使用大小(KB) + * 通过索引初始化 + * + * @param names 名称列表 + * @param index 索引,支持负数,自动轮转 */ - private String mu; + protected Samsara(String[] names, int index) { + this.names = names; + this.index = indexOf(index); + } + /** - * 压缩类空间大小(compressed class space) + * 通过名称初始化 + * + * @param names 名称列表 + * @param name 名称 */ - private String ccsc; + protected Samsara(String[] names, String name) { + this.names = names; + this.index = indexOf(name); + } + /** - * 压缩类空间已使用大小(KB) + * 名称 + * + * @return 名称 */ - private String ccsu; + public String getName() { + return names[index]; + } + /** - * 新生代gc次数 + * 索引 + * + * @return 索引,从0开始 */ - private String ygc; + public int getIndex() { + return index; + } + /** - * 新生代gc耗时(秒) + * 数量 + * + * @return 数量 */ - private String ygct; + public int getSize() { + return names.length; + } + /** - * Full gc次数 - */ - private String fgc; + * 名称对应的索引 + * + * @param name 名称 + * @return 索引,从0开始 + */ + protected int indexOf(String name) { + for (int i = 0, j = getSize(); i < j; i++) { + if (names[i].equals(name)) { + return i; + } + } + throw new IllegalArgumentException(String.format("illegal name: %s", name)); + } + /** - * Full gc耗时(秒) + * 转换为不超范围的索引 + * + * @param index 索引 + * @return 索引,从0开始 */ - private String fgct; + protected int indexOf(int index) { + return indexOf(index, getSize()); + } + /** - * gc总耗时(秒) + * 推移后的索引 + * + * @param n 推移步数 + * @return 索引,从0开始 */ - private String gct; + protected int nextIndex(int n) { + return indexOf(index + n); + } } diff --git a/bus-tracer/src/main/java/org/miaixz/bus/tracer/thread/ThreadLocalMap.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Tradition.java similarity index 77% rename from bus-tracer/src/main/java/org/miaixz/bus/tracer/thread/ThreadLocalMap.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Tradition.java index 98405bccfb..1879bb395d 100755 --- a/bus-tracer/src/main/java/org/miaixz/bus/tracer/thread/ThreadLocalMap.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/Tradition.java @@ -23,29 +23,41 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.tracer.thread; +package org.miaixz.bus.core.center.date.culture; -import java.util.HashMap; -import java.util.Map; +import org.miaixz.bus.core.center.date.Almanac; /** + * 中国传统文化 + * * @author Kimi Liu * @since Java 17+ */ -class ThreadLocalMap extends InheritableThreadLocal> { +public abstract class Tradition implements Culture { @Override - protected final Map initialValue() { - return new HashMap<>(); + public String toString() { + return getName(); } @Override - protected final Map childValue(Map parentValue) { - if (null == parentValue) { - return null; - } else { - return new HashMap<>(parentValue); + public boolean equals(Object o) { + return o instanceof Almanac && toString().equals(o.toString()); + } + + /** + * 转换为不超范围的索引 + * + * @param index 索引 + * @param size 数量 + * @return 索引,从0开始 + */ + protected int indexOf(int index, int size) { + int i = index % size; + if (i < 0) { + i += size; } + return i; } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Animal.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Animal.java new file mode 100644 index 0000000000..dcdb3ee03c --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Animal.java @@ -0,0 +1,74 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.star.twentyeight.TwentyEightStar; + +/** + * 动物 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Animal extends Samsara { + + public static final String[] NAMES = { + "蛟", "龙", "貉", "兔", "狐", "虎", "豹", "獬", "牛", "蝠", + "鼠", "燕", "猪", "獝", "狼", "狗", "彘", "鸡", "乌", "猴", + "猿", "犴", "羊", "獐", "马", "鹿", "蛇", "蚓" + }; + + public Animal(int index) { + super(NAMES, index); + } + + public Animal(String name) { + super(NAMES, name); + } + + public static Animal fromIndex(int index) { + return new Animal(index); + } + + public static Animal fromName(String name) { + return new Animal(name); + } + + public Animal next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 二十八宿 + * + * @return 二十八宿 + */ + public TwentyEightStar getTwentyEightStar() { + return TwentyEightStar.fromIndex(index); + } + +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/Peak.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Beast.java similarity index 72% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/Peak.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Beast.java index ba70b877df..2d65e8f67b 100755 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/Peak.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Beast.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,37 +23,47 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.annotation; +package org.miaixz.bus.core.center.date.culture.cn; -import org.miaixz.bus.core.lang.Normal; - -import java.lang.annotation.*; +import org.miaixz.bus.core.center.date.culture.Samsara; /** + * 神兽 + * * @author Kimi Liu * @since Java 17+ */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Inherited -@Documented -public @interface Peak { +public class Beast extends Samsara { + + public static final String[] NAMES = {"青龙", "玄武", "白虎", "朱雀"}; - String limiter() default Normal.EMPTY; + public Beast(int index) { + super(NAMES, index); + } - String key() default Normal.EMPTY; + public Beast(String name) { + super(NAMES, name); + } - String fallback() default "defaultFallbackResolver"; + public static Beast fromIndex(int index) { + return new Beast(index); + } - String errorHandler() default "defaultErrorHandler"; + public static Beast fromName(String name) { + return new Beast(name); + } - String[] argumentInjectors() default {}; + public Beast next(int n) { + return fromIndex(nextIndex(n)); + } /** - * 最大并发数 + * 宫 * - * @return the int + * @return 宫 */ - int max() default 10; + public Zone getZone() { + return Zone.fromIndex(index); + } } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Limiter.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Direction.java similarity index 67% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/Limiter.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Direction.java index 6f135f47f8..f24e06794b 100755 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Limiter.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Direction.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,43 +23,52 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter; +package org.miaixz.bus.core.center.date.culture.cn; -import java.lang.annotation.Annotation; -import java.util.Map; +import org.miaixz.bus.core.center.date.culture.Samsara; /** - * 限制器件的定义 + * 方位 * * @author Kimi Liu * @since Java 17+ */ -public interface Limiter { +public class Direction extends Samsara { /** - * 该限制器的名字 方便定位哪一个限制器被应用 - * - * @return the string + * 依据后天八卦排序(0坎北, 1坤西南, 2震东, 3巽东南, 4中, 5乾西北, 6兑西, 7艮东北, 8离南) */ - String getLimiterName(); + public static final String[] NAMES = { + "北", "西南", "东", "东南", "中", "西北", "西", "东北", "南" + }; - /** - * 对一个键值进行限制操作,并使用 args 参数 - * 例如实现一个速率限制器,则 args 通常为速率参数 - * - * @param key 键 - * @param args 参数 - * @return true/false - */ - boolean limit(Object key, Map args); + public Direction(int index) { + super(NAMES, index); + } + + public Direction(String name) { + super(NAMES, name); + } + + public static Direction fromIndex(int index) { + return new Direction(index); + } + + public static Direction fromName(String name) { + return new Direction(name); + } + + public Direction next(int n) { + return fromIndex(nextIndex(n)); + } /** - * 对于一个键值释放限制,例如locker 对应于locker 的unlock 操作 - * 某些种类的没有对应的释放操作 例如速率限制器 这是该方法应该是空实现 + * 九野 * - * @param key 键 - * @param args 参数 + * @return 九野 */ - void release(Object key, Map args); + public Land getLand() { + return Land.fromIndex(index); + } } diff --git a/bus-tracer/src/main/java/org/miaixz/bus/tracer/config/PropertyChain.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Duty.java similarity index 73% rename from bus-tracer/src/main/java/org/miaixz/bus/tracer/config/PropertyChain.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Duty.java index 1bcfa573d7..da2a06a23b 100755 --- a/bus-tracer/src/main/java/org/miaixz/bus/tracer/config/PropertyChain.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Duty.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,35 +23,40 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.tracer.config; +package org.miaixz.bus.core.center.date.culture.cn; -import java.util.Arrays; -import java.util.Properties; +import org.miaixz.bus.core.center.date.culture.Samsara; /** + * 建除十二值神 + * * @author Kimi Liu * @since Java 17+ */ -public class PropertyChain { +public class Duty extends Samsara { - private final Iterable propertiesChain; + public static final String[] NAMES = { + "建", "除", "满", "平", "定", "执", "破", "危", "成", "收", "开", "闭" + }; - public PropertyChain(Iterable propertiesChain) { - this.propertiesChain = propertiesChain; + public Duty(int index) { + super(NAMES, index); } - public static PropertyChain build(Properties... properties) { - return new PropertyChain(Arrays.asList(properties)); + public Duty(String name) { + super(NAMES, name); } + public static Duty fromIndex(int index) { + return new Duty(index); + } + + public static Duty fromName(String name) { + return new Duty(name); + } - public String getProperty(String key) { - for (Properties properties : propertiesChain) { - final String p = properties.getProperty(key); - if (null != p) - return p; - } - return null; + public Duty next(int n) { + return fromIndex(nextIndex(n)); } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Element.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Element.java new file mode 100755 index 0000000000..51402e4e01 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Element.java @@ -0,0 +1,96 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 五行 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Element extends Samsara { + + public static final String[] NAMES = {"木", "火", "土", "金", "水"}; + + public Element(int index) { + super(NAMES, index); + } + + public Element(String name) { + super(NAMES, name); + } + + public static Element fromIndex(int index) { + return new Element(index); + } + + public static Element fromName(String name) { + return new Element(name); + } + + public Element next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 我生者(生) + * + * @return 五行 + */ + public Element getReinforce() { + return next(1); + } + + /** + * 我克者(克) + * + * @return 五行 + */ + public Element getRestrain() { + return next(2); + } + + /** + * 生我者(泄) + * + * @return 五行 + */ + public Element getReinforced() { + return next(-1); + } + + /** + * 克我者(耗) + * + * @return 五行 + */ + public Element getRestrained() { + return next(-2); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/JulianDay.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/JulianDay.java new file mode 100755 index 0000000000..62609e208c --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/JulianDay.java @@ -0,0 +1,198 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.solar.SolarDay; +import org.miaixz.bus.core.center.date.culture.solar.SolarTime; + +/** + * 儒略日 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class JulianDay extends Loops { + + /** + * 2000年儒略日数(2000-1-1 12:00:00 UTC) + */ + public static final double J2000 = 2451545; + + /** + * 儒略日 + */ + protected double day; + + public JulianDay(double day) { + this.day = day; + } + + public static JulianDay fromJulianDay(double day) { + return new JulianDay(day); + } + + public static JulianDay fromYmdHms(int year, int month, int day, int hour, int minute, int second) { + double d = day + ((second * 1D / 60 + minute) / 60 + hour) / 24; + int n = 0; + boolean g = year * 372 + month * 31 + (int) d >= 588829; + if (month <= 2) { + month += 12; + year--; + } + if (g) { + n = (int) (year * 1D / 100); + n = 2 - n + (int) (n * 1D / 4); + } + return fromJulianDay((int) (365.25 * (year + 4716)) + (int) (30.6001 * (month + 1)) + d + n - 1524.5); + } + + /** + * 儒略日 + * + * @return 儒略日 + */ + public double getDay() { + return day; + } + + public String getName() { + return day + ""; + } + + public JulianDay next(int n) { + return fromJulianDay(day + n); + } + + /** + * 公历日 + * + * @return 公历日 + */ + public SolarDay getSolarDay() { + int d = (int) (this.day + 0.5); + double f = this.day + 0.5 - d; + + if (d >= 2299161) { + int c = (int) ((d - 1867216.25) / 36524.25); + d += 1 + c - (int) (c * 1D / 4); + } + d += 1524; + int year = (int) ((d - 122.1) / 365.25); + d -= (int) (365.25 * year); + int month = (int) (d * 1D / 30.601); + d -= (int) (30.601 * month); + int day = d; + if (month > 13) { + month -= 13; + year -= 4715; + } else { + month -= 1; + year -= 4716; + } + f *= 24; + int hour = (int) f; + + f -= hour; + f *= 60; + int minute = (int) f; + + f -= minute; + f *= 60; + int second = (int) Math.round(f); + if (second > 59) { + minute++; + } + if (minute > 59) { + hour++; + } + if (hour > 23) { + day += 1; + } + return SolarDay.fromYmd(year, month, day); + } + + /** + * 公历时刻 + * + * @return 公历时刻 + */ + public SolarTime getSolarTime() { + int d = (int) (this.day + 0.5); + double f = this.day + 0.5 - d; + + if (d >= 2299161) { + int c = (int) ((d - 1867216.25) / 36524.25); + d += 1 + c - (int) (c * 1D / 4); + } + d += 1524; + int year = (int) ((d - 122.1) / 365.25); + d -= (int) (365.25 * year); + int month = (int) (d * 1D / 30.601); + d -= (int) (30.601 * month); + int day = d; + if (month > 13) { + month -= 13; + year -= 4715; + } else { + month -= 1; + year -= 4716; + } + f *= 24; + int hour = (int) f; + + f -= hour; + f *= 60; + int minute = (int) f; + + f -= minute; + f *= 60; + int second = (int) Math.round(f); + if (second > 59) { + second -= 60; + minute++; + } + if (minute > 59) { + minute -= 60; + hour++; + } + if (hour > 23) { + hour -= 24; + day += 1; + } + return SolarTime.fromYmdHms(year, month, day, hour, minute, second); + } + + /** + * 星期 + * + * @return 星期 + */ + public Week getWeek() { + return Week.fromIndex((int) (day + 0.5) + 7000001); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Land.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Land.java new file mode 100755 index 0000000000..45b7f882f0 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Land.java @@ -0,0 +1,71 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 九野 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Land extends Samsara { + + public static final String[] NAMES = { + "玄天", "朱天", "苍天", "阳天", "钧天", "幽天", "颢天", "变天", "炎天" + }; + + public Land(int index) { + super(NAMES, index); + } + + public Land(String name) { + super(NAMES, name); + } + + public static Land fromIndex(int index) { + return new Land(index); + } + + public static Land fromName(String name) { + return new Land(name); + } + + public Land next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 方位 + * + * @return 方位 + */ + public Direction getDirection() { + return Direction.fromIndex(index); + } + +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/execute/LimitContextsValueWrapper.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Luck.java similarity index 75% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/execute/LimitContextsValueWrapper.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Luck.java index 7fb13ca63e..730776ee78 100755 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/execute/LimitContextsValueWrapper.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Luck.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,29 +23,38 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.execute; +package org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; /** + * 吉凶 + * * @author Kimi Liu * @since Java 17+ */ -public class LimitContextsValueWrapper { +public class Luck extends Samsara { + + public static final String[] NAMES = {"吉", "凶"}; - private boolean value; + public Luck(int index) { + super(NAMES, index); + } - private Object limiterFailResolveResult; + public Luck(String name) { + super(NAMES, name); + } - public LimitContextsValueWrapper(boolean value, Object limiterFailResolveResult) { - this.value = value; - this.limiterFailResolveResult = limiterFailResolveResult; + public static Luck fromIndex(int index) { + return new Luck(index); } - public boolean value() { - return value; + public static Luck fromName(String name) { + return new Luck(name); } - public Object getLimiterFailResolveResult() { - return limiterFailResolveResult; + public Luck next(int n) { + return fromIndex(nextIndex(n)); } } diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/factory/MethodSignature.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Opposite.java old mode 100755 new mode 100644 similarity index 66% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/factory/MethodSignature.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Opposite.java index 148e038aeb..da3c6e06f0 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/factory/MethodSignature.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Opposite.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,47 +23,69 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.factory; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; +package org.miaixz.bus.core.center.date.culture.cn; /** - * 用于捕获方法签名的类 + * 阴阳 * * @author Kimi Liu * @since Java 17+ */ -public class MethodSignature { +public enum Opposite { + + YIN(0, "阴"), + YANG(1, "阳"); + + /** + * 代码 + */ + private final int code; + /** + * 名称 + */ private final String name; - private final List parameterTypes; - public MethodSignature(Method method) { - this.name = method.getName(); - this.parameterTypes = Arrays.asList(method.getParameterTypes()); + Opposite(int code, String name) { + this.code = code; + this.name = name; } - public boolean equals(Object o) { - if (this == o) { - return true; + public static Opposite fromCode(Integer code) { + if (null == code) { + return null; } - if (null == o || getClass() != o.getClass()) { - return false; + for (Opposite item : values()) { + if (item.getCode() == code) { + return item; + } + } + return null; + } + + public static Opposite fromName(String name) { + if (null == name) { + return null; } - final MethodSignature that = (MethodSignature) o; - if (!name.equals(that.name)) { - return false; + for (Opposite item : values()) { + if (item.getName().equals(name)) { + return item; + } } - return parameterTypes.equals(that.parameterTypes); + return null; } - public int hashCode() { - int result = name.hashCode(); - result = 29 * result + parameterTypes.hashCode(); - return result; + public int getCode() { + return code; } -} + public String getName() { + return name; + } + @Override + public String toString() { + return getName(); + } + +} diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/BurlapProvider.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Phase.java similarity index 65% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/BurlapProvider.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Phase.java index eeb026a965..2357431e50 100755 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/BurlapProvider.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Phase.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,49 +23,44 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.provider; +package org.miaixz.bus.core.center.date.culture.cn; -import com.caucho.burlap.client.BurlapProxyFactory; -import org.miaixz.bus.core.lang.exception.InternalException; -import org.miaixz.bus.proxy.Provider; - -import java.net.MalformedURLException; +import org.miaixz.bus.core.center.date.culture.Samsara; /** - * burlap 服务提供 + * 月相 * * @author Kimi Liu * @since Java 17+ */ -public class BurlapProvider implements Provider { - - private Class serviceInterface; - private String url; +public class Phase extends Samsara { - public BurlapProvider() { + public static final String[] NAMES = { + "朔月", "既朔月", "蛾眉新月", "蛾眉新月", "蛾眉月", "夕月", + "上弦月", "上弦月", "九夜月", "宵月", "宵月", "宵月", + "渐盈凸月", "小望月", "望月", "既望月", "立待月", "居待月", + "寝待月", "更待月", "渐亏凸月", "下弦月", "下弦月", "有明月", + "有明月", "蛾眉残月", "蛾眉残月", "残月", "晓月", "晦月" + }; + public Phase(int index) { + super(NAMES, index); } - public BurlapProvider(Class serviceInterface, String url) { - this.serviceInterface = serviceInterface; - this.url = url; + public Phase(String name) { + super(NAMES, name); } - public Object getObject() { - try { - return new BurlapProxyFactory().create(serviceInterface, url); - } catch (MalformedURLException e) { - throw new InternalException("Invalid url given.", e); - } + public static Phase fromIndex(int index) { + return new Phase(index); } - public void setServiceInterface(Class serviceInterface) { - this.serviceInterface = serviceInterface; + public static Phase fromName(String name) { + return new Phase(name); } - public void setUrl(String url) { - this.url = url; + public Phase next(int n) { + return fromIndex(nextIndex(n)); } } - diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Sixty.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Sixty.java new file mode 100755 index 0000000000..9137fd4b76 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Sixty.java @@ -0,0 +1,60 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 元(60年=1元) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Sixty extends Samsara { + + public static final String[] NAMES = {"上元", "中元", "下元"}; + + public Sixty(int index) { + super(NAMES, index); + } + + public Sixty(String name) { + super(NAMES, name); + } + + public static Sixty fromIndex(int index) { + return new Sixty(index); + } + + public static Sixty fromName(String name) { + return new Sixty(name); + } + + public Sixty next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/HessianProvider.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Sound.java similarity index 65% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/HessianProvider.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Sound.java index 52ed652f98..1444abbe81 100755 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/HessianProvider.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Sound.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,49 +23,44 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.provider; +package org.miaixz.bus.core.center.date.culture.cn; -import com.caucho.hessian.client.HessianProxyFactory; -import org.miaixz.bus.core.lang.exception.InternalException; -import org.miaixz.bus.proxy.Provider; - -import java.net.MalformedURLException; +import org.miaixz.bus.core.center.date.culture.Samsara; /** - * Hessian 服务提供 + * 纳音 * * @author Kimi Liu * @since Java 17+ */ -public class HessianProvider implements Provider { - - private Class serviceInterface; - private String url; +public class Sound extends Samsara { - public HessianProvider() { + public static final String[] NAMES = { + "海中金", "炉中火", "大林木", "路旁土", "剑锋金", "山头火", + "涧下水", "城头土", "白蜡金", "杨柳木", "泉中水", "屋上土", + "霹雳火", "松柏木", "长流水", "沙中金", "山下火", "平地木", + "壁上土", "金箔金", "覆灯火", "天河水", "大驿土", "钗钏金", + "桑柘木", "大溪水", "沙中土", "天上火", "石榴木", "大海水" + }; + public Sound(int index) { + super(NAMES, index); } - public HessianProvider(Class serviceInterface, String url) { - this.serviceInterface = serviceInterface; - this.url = url; + public Sound(String name) { + super(NAMES, name); } - public Object getObject() { - try { - return new HessianProxyFactory().create(serviceInterface, url); - } catch (MalformedURLException e) { - throw new InternalException("Invalid url given.", e); - } + public static Sound fromIndex(int index) { + return new Sound(index); } - public void setServiceInterface(Class serviceInterface) { - this.serviceInterface = serviceInterface; + public static Sound fromName(String name) { + return new Sound(name); } - public void setUrl(String url) { - this.url = url; + public Sound next(int n) { + return fromIndex(nextIndex(n)); } } - diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Ten.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Ten.java new file mode 100755 index 0000000000..7600c2523d --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Ten.java @@ -0,0 +1,62 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 旬 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Ten extends Samsara { + + public static final String[] NAMES = { + "甲子", "甲戌", "甲申", "甲午", "甲辰", "甲寅" + }; + + public Ten(int index) { + super(NAMES, index); + } + + public Ten(String name) { + super(NAMES, name); + } + + public static Ten fromIndex(int index) { + return new Ten(index); + } + + public static Ten fromName(String name) { + return new Ten(name); + } + + public Ten next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Terrain.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Terrain.java new file mode 100755 index 0000000000..d1f8a83627 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Terrain.java @@ -0,0 +1,62 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 地势(长生十二神) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Terrain extends Samsara { + + public static final String[] NAMES = { + "长生", "沐浴", "冠带", "临官", "帝旺", "衰", "病", "死", "墓", "绝", "胎", "养" + }; + + public Terrain(int index) { + super(NAMES, index); + } + + public Terrain(String name) { + super(NAMES, name); + } + + public static Terrain fromIndex(int index) { + return new Terrain(index); + } + + public static Terrain fromName(String name) { + return new Terrain(name); + } + + public Terrain next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Twenty.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Twenty.java new file mode 100755 index 0000000000..aabd12dea9 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Twenty.java @@ -0,0 +1,71 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 运(20年=1运,3运=1元) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Twenty extends Samsara { + + public static final String[] NAMES = { + "一运", "二运", "三运", "四运", "五运", "六运", "七运", "八运", "九运" + }; + + public Twenty(int index) { + super(NAMES, index); + } + + public Twenty(String name) { + super(NAMES, name); + } + + public static Twenty fromIndex(int index) { + return new Twenty(index); + } + + public static Twenty fromName(String name) { + return new Twenty(name); + } + + public Twenty next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 元 + * + * @return 元 + */ + public Sixty getSixty() { + return Sixty.fromIndex(index / 3); + } + +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/BeanFactoryLimitedResourceSourceAdvisor.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Week.java similarity index 66% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/BeanFactoryLimitedResourceSourceAdvisor.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Week.java index 6c08f5af21..8545edbfab 100755 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/BeanFactoryLimitedResourceSourceAdvisor.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Week.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,39 +23,52 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.intercept; +package org.miaixz.bus.core.center.date.culture.cn; -import org.miaixz.bus.limiter.resource.LimitedResourceSource; -import org.springframework.aop.Pointcut; -import org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor; +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.star.seven.SevenStar; /** - * 实际的切面 + * 星期 * * @author Kimi Liu * @since Java 17+ */ -public class BeanFactoryLimitedResourceSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor { +public class Week extends Samsara { - private LimitedResourceSource limitedResourceSource; + public static final String[] NAMES = org.miaixz.bus.core.center.date.culture.en.Week.get("name"); - /** - * 切点 - */ - private final LimitedResourceSourcePointcut pointcut = new LimitedResourceSourcePointcut() { - @Override - protected LimitedResourceSource getLimitedResourceSource() { - return BeanFactoryLimitedResourceSourceAdvisor.this.limitedResourceSource; - } + public static final String[] WHICH = { + "第一周", "第二周", "第三周", "第四周", "第五周", "第六周" }; - public BeanFactoryLimitedResourceSourceAdvisor(LimitedResourceSource limitedResourceSource) { - this.limitedResourceSource = limitedResourceSource; + public Week(int index) { + super(NAMES, index); + } + + public Week(String name) { + super(NAMES, name); + } + + public static Week fromIndex(int index) { + return new Week(index); } - @Override - public Pointcut getPointcut() { - return this.pointcut; + public static Week fromName(String name) { + return new Week(name); + } + + public Week next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 七曜 + * + * @return 七曜 + */ + public SevenStar getSevenStar() { + return SevenStar.fromIndex(index); } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Zodiac.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Zodiac.java new file mode 100644 index 0000000000..df85f9ca73 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Zodiac.java @@ -0,0 +1,110 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.sixty.EarthBranch; +import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.xyz.DateKit; + +import java.util.Calendar; +import java.util.Date; + +/** + * 生肖 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Zodiac extends Samsara { + + public static final String[] NAMES = { + "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" + }; + + public Zodiac(int index) { + super(NAMES, index); + } + + public Zodiac(String name) { + super(NAMES, name); + } + + public static Zodiac fromIndex(int index) { + return new Zodiac(index); + } + + public static Zodiac fromName(String name) { + return new Zodiac(name); + } + + /** + * 通过生日计算生肖,只计算1900年后出生的人 + * + * @param date 出生日期(年需农历) + * @return 星座名 + */ + public static String getName(final Date date) { + return getName(DateKit.calendar(date)); + } + + /** + * 通过生日计算生肖,只计算1900年后出生的人 + * + * @param calendar 出生日期(年需农历) + * @return 星座名 + */ + public static String getName(final Calendar calendar) { + if (null == calendar) { + return null; + } + return getName(calendar.get(Calendar.YEAR)); + } + + /** + * 计算生肖 + * + * @param year 农历年 + * @return 生肖名 + */ + public static String getName(final int year) { + return NAMES[year % Normal._12]; + } + + public Zodiac next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 地支 + * + * @return 地支 + */ + public EarthBranch getEarthBranch() { + return EarthBranch.fromIndex(index); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Zone.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Zone.java new file mode 100755 index 0000000000..8540e6bd96 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/Zone.java @@ -0,0 +1,78 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 宫 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Zone extends Samsara { + + public static final String[] NAMES = {"东", "北", "西", "南"}; + + public Zone(int index) { + super(NAMES, index); + } + + public Zone(String name) { + super(NAMES, name); + } + + public static Zone fromIndex(int index) { + return new Zone(index); + } + + public static Zone fromName(String name) { + return new Zone(name); + } + + public Zone next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 方位 + * + * @return 方位 + */ + public Direction getDirection() { + return Direction.fromName(getName()); + } + + /** + * 神兽 + * + * @return 神兽 + */ + public Beast getBeast() { + return Beast.fromIndex(index); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/ChildLimit.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/ChildLimit.java new file mode 100755 index 0000000000..3e75e80403 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/ChildLimit.java @@ -0,0 +1,204 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.birth; + +import org.miaixz.bus.core.center.date.culture.cn.Opposite; +import org.miaixz.bus.core.center.date.culture.cn.birth.provider.ChildLimitProvider; +import org.miaixz.bus.core.center.date.culture.cn.birth.provider.impl.DefaultChildLimitProvider; +import org.miaixz.bus.core.center.date.culture.solar.SolarTerm; +import org.miaixz.bus.core.center.date.culture.solar.SolarTime; +import org.miaixz.bus.core.lang.Gender; + +/** + * 童限(从出生到起运的时间段) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class ChildLimit { + + /** + * 童限计算接口 + */ + public static ChildLimitProvider provider = new DefaultChildLimitProvider(); + + /** + * 八字 + */ + protected EightChar eightChar; + + /** + * 性别 + */ + protected Gender gender; + + /** + * 顺逆 + */ + protected boolean forward; + + /** + * 童限信息 + */ + protected ChildLimitInfo info; + + public ChildLimit(SolarTime birthTime, Gender gender) { + this.gender = gender; + eightChar = birthTime.getLunarHour().getEightChar(); + // 阳男阴女顺推,阴男阳女逆推 + boolean yang = Opposite.YANG == eightChar.getYear().getHeavenStem().getOpposite(); + boolean man = Gender.MALE == gender; + forward = (yang && man) || (!yang && !man); + SolarTerm term = birthTime.getTerm(); + if (!term.isJie()) { + term = term.next(-1); + } + if (forward) { + term = term.next(2); + } + info = provider.getInfo(birthTime, term); + } + + /** + * 通过出生公历时刻初始化 + * + * @param birthTime 出生公历时刻 + * @param gender 性别 + * @return 童限 + */ + public static ChildLimit fromSolarTime(SolarTime birthTime, Gender gender) { + return new ChildLimit(birthTime, gender); + } + + /** + * 八字 + * + * @return 八字 + */ + public EightChar getEightChar() { + return eightChar; + } + + /** + * 性别 + * + * @return 性别 + */ + public Gender getGender() { + return gender; + } + + /** + * 是否顺推 + * + * @return true/false + */ + public boolean isForward() { + return forward; + } + + /** + * 年数 + * + * @return 年数 + */ + public int getYearCount() { + return info.getYearCount(); + } + + /** + * 月数 + * + * @return 月数 + */ + public int getMonthCount() { + return info.getMonthCount(); + } + + /** + * 日数 + * + * @return 日数 + */ + public int getDayCount() { + return info.getDayCount(); + } + + /** + * 小时数 + * + * @return 小时数 + */ + public int getHourCount() { + return info.getHourCount(); + } + + /** + * 分钟数 + * + * @return 分钟数 + */ + public int getMinuteCount() { + return info.getMinuteCount(); + } + + /** + * 开始(即出生)的公历时刻 + * + * @return 公历时刻 + */ + public SolarTime getStartTime() { + return info.getStartTime(); + } + + /** + * 结束(即开始起运)的公历时刻 + * + * @return 公历时刻 + */ + public SolarTime getEndTime() { + return info.getEndTime(); + } + + /** + * 大运 + * + * @return 大运 + */ + public DecadeFortune getStartDecadeFortune() { + return DecadeFortune.fromChildLimit(this, 0); + } + + /** + * 小运 + * + * @return 小运 + */ + public Fortune getStartFortune() { + return Fortune.fromChildLimit(this, 0); + } + +} diff --git a/bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/ThreadEntity.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/ChildLimitInfo.java similarity index 58% rename from bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/ThreadEntity.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/ChildLimitInfo.java index 55598f4afb..f9b7117557 100644 --- a/bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/ThreadEntity.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/ChildLimitInfo.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,49 +23,89 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.tracer.monitor; +package org.miaixz.bus.core.center.date.culture.cn.birth; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +import org.miaixz.bus.core.center.date.culture.solar.SolarTime; /** + * 童限信息 + * * @author Kimi Liu * @since Java 17+ */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class ThreadEntity { +public class ChildLimitInfo { /** - * 当前应用进程ID + * 开始(即出生)的公历时刻 */ - private Integer id; + protected SolarTime startTime; + /** - * 当前应用名称 + * 结束(即开始起运)的公历时刻 */ - private String name; + protected SolarTime endTime; + /** - * 时间 格式 MM/dd HH:mm" + * 年数 */ - private String date; + protected int yearCount; + /** - * 总线程数 + * 月数 */ - private int total; + protected int monthCount; + /** - * 运行中的线程 + * 日数 */ - private int runnable; + protected int dayCount; + /** - * 这个状态就是有限的(时间限制)的WAITING, 一般出现在调用wait(long), join(long)等情况下, 另外一个线程sleep后 - * 休眠的线程数 + * 小时数 */ - private int timed_waiting; + protected int hourCount; + /** - * 这个状态下是指线程拥有了某个锁之后, 调用了他的wait方法, 等待的线程数 + * 分钟数 */ - private int waiting; + protected int minuteCount; + + public ChildLimitInfo(SolarTime startTime, SolarTime endTime, int yearCount, int monthCount, int dayCount, int hourCount, int minuteCount) { + this.startTime = startTime; + this.endTime = endTime; + this.yearCount = yearCount; + this.monthCount = monthCount; + this.dayCount = dayCount; + this.hourCount = hourCount; + this.minuteCount = minuteCount; + } + + public SolarTime getStartTime() { + return startTime; + } + + public SolarTime getEndTime() { + return endTime; + } + + public int getYearCount() { + return yearCount; + } + + public int getMonthCount() { + return monthCount; + } + + public int getDayCount() { + return dayCount; + } + + public int getHourCount() { + return hourCount; + } + + public int getMinuteCount() { + return minuteCount; + } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/DecadeFortune.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/DecadeFortune.java new file mode 100755 index 0000000000..27fb9e8344 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/DecadeFortune.java @@ -0,0 +1,129 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.birth; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.sixty.SixtyCycle; +import org.miaixz.bus.core.center.date.culture.lunar.LunarYear; + +/** + * 大运(10年1大运) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class DecadeFortune extends Loops { + + /** + * 童限 + */ + protected ChildLimit childLimit; + + /** + * 序号 + */ + protected int index; + + public DecadeFortune(ChildLimit childLimit, int index) { + this.childLimit = childLimit; + this.index = index; + } + + /** + * 通过童限初始化 + * + * @param childLimit 童限 + * @param index 序号 + * @return 大运 + */ + public static DecadeFortune fromChildLimit(ChildLimit childLimit, int index) { + return new DecadeFortune(childLimit, index); + } + + /** + * 开始年龄 + * + * @return 开始年龄 + */ + public int getStartAge() { + return childLimit.getYearCount() + 1 + index * 10; + } + + /** + * 结束年龄 + * + * @return 结束年龄 + */ + public int getEndAge() { + return getStartAge() + 9; + } + + /** + * 开始农历年 + * + * @return 农历年 + */ + public LunarYear getStartLunarYear() { + return childLimit.getEndTime().getLunarHour().getDay().getMonth().getYear().next(index * 10); + } + + /** + * 结束农历年 + * + * @return 农历年 + */ + public LunarYear getEndLunarYear() { + return getStartLunarYear().next(9); + } + + /** + * 干支 + * + * @return 干支 + */ + public SixtyCycle getSixtyCycle() { + int n = index + 1; + return childLimit.getEightChar().getMonth().next(childLimit.isForward() ? n : -n); + } + + public String getName() { + return getSixtyCycle().getName(); + } + + public DecadeFortune next(int n) { + return fromChildLimit(childLimit, index + n); + } + + /** + * 开始小运 + * + * @return 小运 + */ + public Fortune getStartFortune() { + return Fortune.fromChildLimit(childLimit, index * 10); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/EightChar.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/EightChar.java new file mode 100644 index 0000000000..a3de9fba83 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/EightChar.java @@ -0,0 +1,245 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.birth; + +import org.miaixz.bus.core.center.date.culture.Tradition; +import org.miaixz.bus.core.center.date.culture.cn.Duty; +import org.miaixz.bus.core.center.date.culture.cn.sixty.EarthBranch; +import org.miaixz.bus.core.center.date.culture.cn.sixty.HeavenStem; +import org.miaixz.bus.core.center.date.culture.cn.sixty.SixtyCycle; +import org.miaixz.bus.core.center.date.culture.solar.SolarDay; +import org.miaixz.bus.core.center.date.culture.solar.SolarMonth; +import org.miaixz.bus.core.center.date.culture.solar.SolarTerm; +import org.miaixz.bus.core.center.date.culture.solar.SolarTime; + +import java.util.ArrayList; +import java.util.List; + +/** + * 八字 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class EightChar extends Tradition { + + /** + * 年柱 + */ + protected SixtyCycle year; + + /** + * 月柱 + */ + protected SixtyCycle month; + + /** + * 日柱 + */ + protected SixtyCycle day; + + /** + * 时柱 + */ + protected SixtyCycle hour; + + /** + * 初始化 + * + * @param year 年柱 + * @param month 月柱 + * @param day 日柱 + * @param hour 时柱 + */ + public EightChar(SixtyCycle year, SixtyCycle month, SixtyCycle day, SixtyCycle hour) { + this.year = year; + this.month = month; + this.day = day; + this.hour = hour; + } + + /** + * 初始化 + * + * @param year 年柱 + * @param month 月柱 + * @param day 日柱 + * @param hour 时柱 + */ + public EightChar(String year, String month, String day, String hour) { + this(SixtyCycle.fromName(year), SixtyCycle.fromName(month), SixtyCycle.fromName(day), SixtyCycle.fromName(hour)); + } + + /** + * 年柱 + * + * @return 年柱 + */ + public SixtyCycle getYear() { + return year; + } + + /** + * 月柱 + * + * @return 月柱 + */ + public SixtyCycle getMonth() { + return month; + } + + /** + * 日柱 + * + * @return 日柱 + */ + public SixtyCycle getDay() { + return day; + } + + /** + * 时柱 + * + * @return 时柱 + */ + public SixtyCycle getHour() { + return hour; + } + + /** + * 胎元 + * + * @return 胎元 + */ + public SixtyCycle getFetalOrigin() { + return SixtyCycle.fromName(month.getHeavenStem().next(1).getName() + month.getEarthBranch().next(3).getName()); + } + + /** + * 胎息 + * + * @return 胎息 + */ + public SixtyCycle getFetalBreath() { + return SixtyCycle.fromName(day.getHeavenStem().next(5).getName() + EarthBranch.fromIndex(13 - day.getEarthBranch().getIndex()).getName()); + } + + /** + * 命宫 + * + * @return 命宫 + */ + public SixtyCycle getOwnSign() { + int offset = month.getEarthBranch().next(-1).getIndex() + hour.getEarthBranch().next(-1).getIndex(); + offset = (offset >= 14 ? 26 : 14) - offset; + offset -= 1; + return SixtyCycle.fromName(HeavenStem.fromIndex((year.getHeavenStem().getIndex() + 1) * 2 + offset).getName() + EarthBranch.fromIndex(2 + offset).getName()); + } + + /** + * 身宫 + * + * @return 身宫 + */ + public SixtyCycle getBodySign() { + int offset = month.getEarthBranch().getIndex() + hour.getEarthBranch().getIndex(); + offset %= 12; + offset -= 1; + return SixtyCycle.fromName(HeavenStem.fromIndex((year.getHeavenStem().getIndex() + 1) * 2 + offset).getName() + EarthBranch.fromIndex(2 + offset).getName()); + } + + /** + * 建除十二值神 + * + * @return 建除十二值神 + */ + public Duty getDuty() { + return Duty.fromIndex(day.getEarthBranch().getIndex() - month.getEarthBranch().getIndex()); + } + + /** + * 公历时刻列表 + * + * @param startYear 开始年(含),支持1-9999年 + * @param endYear 结束年(含),支持1-9999年 + * @return 公历时刻列表 + */ + public List getSolarTimes(int startYear, int endYear) { + List l = new ArrayList<>(); + // 月地支距寅月的偏移值 + int m = month.getEarthBranch().next(-2).getIndex(); + // 月天干要一致 + if (!HeavenStem.fromIndex((year.getHeavenStem().getIndex() + 1) * 2 + m).equals(month.getHeavenStem())) { + return l; + } + // 1年的立春是辛酉,序号57 + int y = year.next(-57).getIndex() + 1; + // 节令偏移值 + m *= 2; + // 时辰地支转时刻,子时按零点算 + int h = hour.getEarthBranch().getIndex() * 2; + int baseYear = startYear - 1; + while (y <= endYear) { + if (y >= baseYear) { + // 立春为寅月的开始 + SolarTerm term = SolarTerm.fromIndex(y, 3); + // 节令推移,年干支和月干支就都匹配上了 + if (m > 0) { + term = term.next(m); + } + SolarTime solarTime = term.getJulianDay().getSolarTime(); + if (solarTime.getDay().getMonth().getYear().getYear() >= startYear) { + int mi = 0; + int s = 0; + // 日干支和节令干支的偏移值 + SolarDay solarDay = solarTime.getDay(); + int d = day.next(-solarDay.getLunarDay().getSixtyCycle().getIndex()).getIndex(); + if (d > 0) { + // 从节令推移天数 + solarDay = solarDay.next(d); + } else if (h == solarTime.getHour()) { + // 如果正好是节令当天,且小时和节令的小时数相等的极端情况,把分钟和秒钟带上 + mi = solarTime.getMinute(); + s = solarTime.getSecond(); + } + SolarMonth solarMonth = solarDay.getMonth(); + SolarTime time = SolarTime.fromYmdHms(solarMonth.getYear().getYear(), solarMonth.getMonth(), solarDay.getDay(), h, mi, s); + // 验证一下 + if (time.getLunarHour().getEightChar().equals(this)) { + l.add(time); + } + } + } + y += 60; + } + return l; + } + + public String getName() { + return String.format("%s %s %s %s", year, month, day, hour); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/Fortune.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/Fortune.java new file mode 100755 index 0000000000..a6c6528326 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/Fortune.java @@ -0,0 +1,102 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.birth; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.sixty.SixtyCycle; +import org.miaixz.bus.core.center.date.culture.lunar.LunarYear; + +/** + * 小运 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Fortune extends Loops { + + /** + * 童限 + */ + protected ChildLimit childLimit; + + /** + * 序号 + */ + protected int index; + + public Fortune(ChildLimit childLimit, int index) { + this.childLimit = childLimit; + this.index = index; + } + + /** + * 通过童限初始化 + * + * @param childLimit 童限 + * @param index 序号 + * @return 大运 + */ + public static Fortune fromChildLimit(ChildLimit childLimit, int index) { + return new Fortune(childLimit, index); + } + + /** + * 年龄 + * + * @return 年龄 + */ + public int getAge() { + return childLimit.getYearCount() + 1 + index; + } + + /** + * 农历年 + * + * @return 农历年 + */ + public LunarYear getLunarYear() { + return childLimit.getEndTime().getLunarHour().getDay().getMonth().getYear().next(index); + } + + /** + * 干支 + * + * @return 干支 + */ + public SixtyCycle getSixtyCycle() { + int n = getAge(); + return childLimit.getEightChar().getHour().next(childLimit.isForward() ? n : -n); + } + + public String getName() { + return getSixtyCycle().getName(); + } + + public Fortune next(int n) { + return fromChildLimit(childLimit, index + n); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/package-info.java new file mode 100644 index 0000000000..514f3ba906 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/package-info.java @@ -0,0 +1,7 @@ +/** + * 生成八字 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.birth; diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/Invoker.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/ChildLimitProvider.java old mode 100755 new mode 100644 similarity index 77% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/Invoker.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/ChildLimitProvider.java index e3b726e1a4..0463455565 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/Invoker.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/ChildLimitProvider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,28 +23,26 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy; +package org.miaixz.bus.core.center.date.culture.cn.birth.provider; -import java.lang.reflect.Method; +import org.miaixz.bus.core.center.date.culture.cn.birth.ChildLimitInfo; +import org.miaixz.bus.core.center.date.culture.solar.SolarTerm; +import org.miaixz.bus.core.center.date.culture.solar.SolarTime; /** - * 调用程序负责处理方法调用 + * 童限计算接口 * * @author Kimi Liu * @since Java 17+ */ -public interface Invoker { +public interface ChildLimitProvider { /** - * 调用方法 - * 如果在尝试调用方法时出现问题,实现应该抛出异常 + * 童限信息 * - * @param proxy 代理对象 - * @param method 被调用的方法 - * @param arguments 参数 - * @return 返回值 - * @throws Throwable 抛出异常 + * @param birthTime 出生公历时刻 + * @param term 节令 + * @return 童限信息 */ - Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable; - + ChildLimitInfo getInfo(SolarTime birthTime, SolarTerm term); } diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/MethodAdapter.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/impl/China95ChildLimitProvider.java old mode 100755 new mode 100644 similarity index 56% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/MethodAdapter.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/impl/China95ChildLimitProvider.java index 64d111ca61..4017c71fa0 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/MethodAdapter.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/impl/China95ChildLimitProvider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,64 +23,45 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.intercept; +package org.miaixz.bus.core.center.date.culture.cn.birth.provider.impl; -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.miaixz.bus.proxy.Interceptor; -import org.miaixz.bus.proxy.Invocation; - -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Method; +import org.miaixz.bus.core.center.date.culture.cn.birth.ChildLimitInfo; +import org.miaixz.bus.core.center.date.culture.cn.birth.provider.ChildLimitProvider; +import org.miaixz.bus.core.center.date.culture.solar.SolarDay; +import org.miaixz.bus.core.center.date.culture.solar.SolarMonth; +import org.miaixz.bus.core.center.date.culture.solar.SolarTerm; +import org.miaixz.bus.core.center.date.culture.solar.SolarTime; /** - * 一个适配器类,使AOP联盟的{@link MethodInterceptor} - * 接口适应于Proxy的{@link Interceptor}接口 + * 元亨利贞的童限计算 * * @author Kimi Liu * @since Java 17+ */ -public class MethodAdapter implements Interceptor { - - private final MethodInterceptor methodInterceptor; - - public MethodAdapter(MethodInterceptor methodInterceptor) { - this.methodInterceptor = methodInterceptor; - } +public class China95ChildLimitProvider implements ChildLimitProvider { @Override - public Object intercept(Invocation invocation) throws Throwable { - return methodInterceptor.invoke(new MethodInvocationAdapter(invocation)); - } - - private static class MethodInvocationAdapter implements MethodInvocation { - - private final Invocation invocation; - - public MethodInvocationAdapter(Invocation invocation) { - this.invocation = invocation; - } - - public Method getMethod() { - return invocation.getMethod(); - } - - public Object[] getArguments() { - return invocation.getArguments(); - } - - public Object proceed() throws Throwable { - return invocation.proceed(); - } - - public Object getThis() { - return invocation.getProxy(); - } - - public AccessibleObject getStaticPart() { - return invocation.getMethod(); + public ChildLimitInfo getInfo(SolarTime birthTime, SolarTerm term) { + // 出生时刻和节令时刻相差的分钟数 + int minutes = Math.abs(term.getJulianDay().getSolarTime().subtract(birthTime)) / 60; + int year = minutes / 4320; + minutes %= 4320; + int month = minutes / 360; + minutes %= 360; + int day = minutes / 12; + + SolarDay birthday = birthTime.getDay(); + SolarMonth birthMonth = birthday.getMonth(); + SolarMonth sm = SolarMonth.fromYm(birthMonth.getYear().getYear() + year, birthMonth.getMonth()).next(month); + + int d = birthday.getDay() + day; + int dc = sm.getDayCount(); + if (d > dc) { + d -= dc; + sm = sm.next(1); } + return new ChildLimitInfo(birthTime, SolarTime.fromYmdHms(sm.getYear().getYear(), sm.getMonth(), d, birthTime.getHour(), birthTime.getMinute(), birthTime.getSecond()), year, month, day, 0, 0); } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/impl/DefaultChildLimitProvider.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/impl/DefaultChildLimitProvider.java new file mode 100644 index 0000000000..9d44e82a63 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/impl/DefaultChildLimitProvider.java @@ -0,0 +1,84 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.birth.provider.impl; + +import org.miaixz.bus.core.center.date.culture.cn.birth.ChildLimitInfo; +import org.miaixz.bus.core.center.date.culture.cn.birth.provider.ChildLimitProvider; +import org.miaixz.bus.core.center.date.culture.solar.SolarDay; +import org.miaixz.bus.core.center.date.culture.solar.SolarMonth; +import org.miaixz.bus.core.center.date.culture.solar.SolarTerm; +import org.miaixz.bus.core.center.date.culture.solar.SolarTime; + +/** + * 默认的童限计算 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class DefaultChildLimitProvider implements ChildLimitProvider { + + @Override + public ChildLimitInfo getInfo(SolarTime birthTime, SolarTerm term) { + // 出生时刻和节令时刻相差的秒数 + int seconds = Math.abs(term.getJulianDay().getSolarTime().subtract(birthTime)); + // 3天 = 1年,3天=60*60*24*3秒=259200秒 = 1年 + int year = seconds / 259200; + seconds %= 259200; + // 1天 = 4月,1天=60*60*24秒=86400秒 = 4月,85400秒/4=21600秒 = 1月 + int month = seconds / 21600; + seconds %= 21600; + // 1时 = 5天,1时=60*60秒=3600秒 = 5天,3600秒/5=720秒 = 1天 + int day = seconds / 720; + seconds %= 720; + // 1分 = 2时,60秒 = 2时,60秒/2=30秒 = 1时 + int hour = seconds / 30; + seconds %= 30; + // 1秒 = 2分,1秒/2=0.5秒 = 1分 + int minute = seconds * 2; + + SolarDay birthday = birthTime.getDay(); + SolarMonth birthMonth = birthday.getMonth(); + + int d = birthday.getDay() + day; + int h = birthTime.getHour() + hour; + int mi = birthTime.getMinute() + minute; + h += mi / 60; + mi %= 60; + d += h / 24; + h %= 24; + + SolarMonth sm = SolarMonth.fromYm(birthMonth.getYear().getYear() + year, birthMonth.getMonth()).next(month); + + int dc = sm.getDayCount(); + if (d > dc) { + d -= dc; + sm = sm.next(1); + } + + return new ChildLimitInfo(birthTime, SolarTime.fromYmdHms(sm.getYear().getYear(), sm.getMonth(), d, h, mi, birthTime.getSecond()), year, month, day, hour, minute); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/impl/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/impl/package-info.java new file mode 100644 index 0000000000..e6996211d0 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/impl/package-info.java @@ -0,0 +1,7 @@ +/** + * 童限计算方式 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.birth.provider.impl; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/package-info.java new file mode 100644 index 0000000000..ea8773bd16 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/birth/provider/package-info.java @@ -0,0 +1,7 @@ +/** + * 童限计算 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.birth.provider; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/Climate.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/Climate.java new file mode 100755 index 0000000000..289b729fca --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/Climate.java @@ -0,0 +1,92 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.climate; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 候 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Climate extends Samsara { + + public static final String[] NAMES = { + "蚯蚓结", "麋角解", "水泉动", "雁北乡", "鹊始巢", "雉始雊", "鸡始乳", "征鸟厉疾", + "水泽腹坚", "东风解冻", "蛰虫始振", "鱼陟负冰", "獭祭鱼", "候雁北", "草木萌动", + "桃始华", "仓庚鸣", "鹰化为鸠", "玄鸟至", "雷乃发声", "始电", "桐始华", "田鼠化为鴽", + "虹始见", "萍始生", "鸣鸠拂奇羽", "戴胜降于桑", "蝼蝈鸣", "蚯蚓出", "王瓜生", + "苦菜秀", "靡草死", "麦秋至", "螳螂生", "鵙始鸣", "反舌无声", "鹿角解", "蜩始鸣", + "半夏生", "温风至", "蟋蟀居壁", "鹰始挚", "腐草为萤", "土润溽暑", "大雨行时", + "凉风至", "白露降", "寒蝉鸣", "鹰乃祭鸟", "天地始肃", "禾乃登", "鸿雁来", + "玄鸟归", "群鸟养羞", "雷始收声", "蛰虫坯户", "水始涸", "鸿雁来宾", "雀入大水为蛤", + "菊有黄花", "豺乃祭兽", "草木黄落", "蛰虫咸俯", "水始冰", "地始冻", "雉入大水为蜃", + "虹藏不见", "天气上升地气下降", "闭塞而成冬", "鹖鴠不鸣", "虎始交", "荔挺出" + }; + + public Climate(String name) { + super(NAMES, name); + } + + public Climate(int index) { + super(NAMES, index); + } + + /** + * 从名称初始化 + * + * @param name 名称 + * @return 候 + */ + public static Climate fromName(String name) { + return new Climate(name); + } + + /** + * 从索引初始化 + * + * @param index 索引 + * @return 候 + */ + public static Climate fromIndex(int index) { + return new Climate(index); + } + + /** + * 三候 + * + * @return 三候 + */ + public ThreeClimate getThree() { + return ThreeClimate.fromIndex(index % 3); + } + + public Climate next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/ClimateDay.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/ClimateDay.java new file mode 100755 index 0000000000..ad2003b0a3 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/ClimateDay.java @@ -0,0 +1,51 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.climate; + +import org.miaixz.bus.core.center.date.culture.Replenish; + +/** + * 七十二候 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class ClimateDay extends Replenish { + + public ClimateDay(Climate climate, int dayIndex) { + super(climate, dayIndex); + } + + /** + * 候 + * + * @return 候 + */ + public Climate getClimate() { + return (Climate) tradition; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/ThreeClimate.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/ThreeClimate.java new file mode 100755 index 0000000000..9d16f08c53 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/ThreeClimate.java @@ -0,0 +1,72 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.climate; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 三候 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class ThreeClimate extends Samsara { + + public static final String[] NAMES = {"初候", "二候", "三候"}; + + public ThreeClimate(String name) { + super(NAMES, name); + } + + public ThreeClimate(int index) { + super(NAMES, index); + } + + /** + * 从名称初始化 + * + * @param name 名称 + * @return 三候 + */ + public static ThreeClimate fromName(String name) { + return new ThreeClimate(name); + } + + /** + * 从索引初始化 + * + * @param index 索引 + * @return 三候 + */ + public static ThreeClimate fromIndex(int index) { + return new ThreeClimate(index); + } + + public ThreeClimate next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/package-info.java new file mode 100644 index 0000000000..3f602dc08e --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/climate/package-info.java @@ -0,0 +1,7 @@ +/** + * 物候 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.climate; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/dog/Dog.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/dog/Dog.java new file mode 100755 index 0000000000..d5026b4493 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/dog/Dog.java @@ -0,0 +1,72 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.dog; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 三伏 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Dog extends Samsara { + + public static final String[] NAMES = {"初伏", "中伏", "末伏"}; + + public Dog(String name) { + super(NAMES, name); + } + + public Dog(int index) { + super(NAMES, index); + } + + /** + * 从名称初始化 + * + * @param name 名称 + * @return 伏 + */ + public static Dog fromName(String name) { + return new Dog(name); + } + + /** + * 从索引初始化 + * + * @param index 索引 + * @return 伏 + */ + public static Dog fromIndex(int index) { + return new Dog(index); + } + + public Dog next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-tracer/src/main/java/org/miaixz/bus/tracer/backend/ThreadLocalHashSet.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/dog/DogDay.java similarity index 82% rename from bus-tracer/src/main/java/org/miaixz/bus/tracer/backend/ThreadLocalHashSet.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/dog/DogDay.java index 8f6a890d91..47b3ef45c2 100755 --- a/bus-tracer/src/main/java/org/miaixz/bus/tracer/backend/ThreadLocalHashSet.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/dog/DogDay.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,25 +23,29 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.tracer.backend; +package org.miaixz.bus.core.center.date.culture.cn.dog; -import java.util.HashSet; -import java.util.Set; +import org.miaixz.bus.core.center.date.culture.Replenish; /** + * 三伏天 + * * @author Kimi Liu * @since Java 17+ */ -public final class ThreadLocalHashSet extends InheritableThreadLocal> { +public class DogDay extends Replenish { - @Override - protected Set childValue(Set parentValue) { - return new HashSet<>(parentValue); + public DogDay(Dog dog, int dayIndex) { + super(dog, dayIndex); } - @Override - protected Set initialValue() { - return new HashSet<>(); + /** + * 三伏 + * + * @return 三伏 + */ + public Dog getDog() { + return (Dog) tradition; } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/dog/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/dog/package-info.java new file mode 100644 index 0000000000..eb372fd464 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/dog/package-info.java @@ -0,0 +1,7 @@ +/** + * 夏季三伏 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.dog; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusDay.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusDay.java new file mode 100755 index 0000000000..8decc0b95f --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusDay.java @@ -0,0 +1,143 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.fetus; + +import org.miaixz.bus.core.center.date.culture.Tradition; +import org.miaixz.bus.core.center.date.culture.cn.Direction; +import org.miaixz.bus.core.center.date.culture.cn.sixty.SixtyCycle; +import org.miaixz.bus.core.center.date.culture.lunar.LunarDay; + +/** + * 逐日胎神 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class FetusDay extends Tradition { + + /** + * 天干六甲胎神 + */ + protected FetusHeavenStem fetusHeavenStem; + + /** + * 地支六甲胎神 + */ + protected FetusEarthBranch fetusEarthBranch; + + /** + * 内外 + */ + protected int side; + + /** + * 方位 + */ + protected Direction direction; + + public FetusDay(LunarDay lunarDay) { + SixtyCycle sixtyCycle = lunarDay.getSixtyCycle(); + fetusHeavenStem = new FetusHeavenStem(sixtyCycle.getHeavenStem().getIndex() % 5); + fetusEarthBranch = new FetusEarthBranch(sixtyCycle.getEarthBranch().getIndex() % 6); + int index = new int[]{3, 3, 8, 8, 8, 8, 8, 1, 1, 1, 1, 1, 1, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, -9, -9, -9, -9, -9, -5, -5, -1, -1, -1, -3, -7, -7, -7, -7, -5, 7, 7, 7, 7, 7, 7, 2, 2, 2, 2, 2, 3, 3, 3, 3}[sixtyCycle.getIndex()]; + side = index < 0 ? 0 : 1; + direction = Direction.fromIndex(index); + } + + /** + * 从农历日初始化 + * + * @param lunarDay 农历日 + * @return 逐日胎神 + */ + public static FetusDay fromLunarDay(LunarDay lunarDay) { + return new FetusDay(lunarDay); + } + + public String getName() { + String s = fetusHeavenStem.getName() + fetusEarthBranch.getName(); + if ("门门".equals(s)) { + s = "占大门"; + } else if ("碓磨碓".equals(s)) { + s = "占碓磨"; + } else if ("房床床".equals(s)) { + s = "占房床"; + } else if (s.startsWith("门")) { + s = "占" + s; + } + + s += " "; + + String directionName = direction.getName(); + if (0 == side) { + s += "房"; + } + s += "内"; + + if (1 == side && "北南西东".contains(directionName)) { + s += "正"; + } + s += directionName; + return s; + } + + /** + * 内外 + * + * @return 侧 + */ + public int getSide() { + return side; + } + + /** + * 方位 + * + * @return 方位 + */ + public Direction getDirection() { + return direction; + } + + /** + * 天干六甲胎神 + * + * @return 天干六甲胎神 + */ + public FetusHeavenStem getFetusHeavenStem() { + return fetusHeavenStem; + } + + /** + * 地支六甲胎神 + * + * @return 地支六甲胎神 + */ + public FetusEarthBranch getFetusEarthBranch() { + return fetusEarthBranch; + } + +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/Lock.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusEarthBranch.java similarity index 74% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/Lock.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusEarthBranch.java index 6b73410229..d316ee498d 100755 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/Lock.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusEarthBranch.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,31 +23,26 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.support.lock; +package org.miaixz.bus.core.center.date.culture.cn.fetus; -import org.miaixz.bus.limiter.Limiter; - -import java.util.Map; +import org.miaixz.bus.core.center.date.culture.Samsara; /** - * Lock + * 地支六甲胎神(《地支六甲胎神歌》子午二日碓须忌,丑未厕道莫修移。寅申火炉休要动,卯酉大门修当避。辰戌鸡栖巳亥床,犯着六甲身堕胎。) * * @author Kimi Liu * @since Java 17+ */ -public abstract class Lock implements Limiter { - - public abstract boolean lock(Object key); +public class FetusEarthBranch extends Samsara { - public abstract void unlock(Object key); + public static final String[] NAMES = {"碓", "厕", "炉", "门", "栖", "床"}; - @Override - public boolean limit(Object key, Map args) { - return lock(key); + public FetusEarthBranch(int index) { + super(NAMES, index); } - @Override - public void release(Object key, Map args) { - unlock(key); + public FetusEarthBranch next(int n) { + return new FetusEarthBranch(nextIndex(n)); } + } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusHeavenStem.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusHeavenStem.java new file mode 100755 index 0000000000..8a431cd32d --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusHeavenStem.java @@ -0,0 +1,48 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.fetus; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 天干六甲胎神(《天干六甲胎神歌》甲己之日占在门,乙庚碓磨休移动。丙辛厨灶莫相干,丁壬仓库忌修弄。戊癸房床若移整,犯之孕妇堕孩童。) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class FetusHeavenStem extends Samsara { + + public static final String[] NAMES = {"门", "碓磨", "厨灶", "仓库", "房床"}; + + public FetusHeavenStem(int index) { + super(NAMES, index); + } + + public FetusHeavenStem next(int n) { + return new FetusHeavenStem(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusMonth.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusMonth.java new file mode 100755 index 0000000000..1efaacc5e2 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/FetusMonth.java @@ -0,0 +1,62 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.fetus; + +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.lunar.LunarMonth; + +/** + * 逐月胎神(正十二月在床房,二三九十门户中,四六十一灶勿犯,五甲七子八厕凶。) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class FetusMonth extends Samsara { + + public static final String[] NAMES = { + "占房床", "占户窗", "占门堂", "占厨灶", "占房床", "占床仓", + "占碓磨", "占厕户", "占门房", "占房床", "占灶炉", "占房床" + }; + + public FetusMonth(int index) { + super(NAMES, index); + } + + /** + * 从农历月初始化 + * + * @param lunarMonth 农历月 + * @return 逐月胎神 + */ + public static FetusMonth fromLunarMonth(LunarMonth lunarMonth) { + return lunarMonth.isLeap() ? null : new FetusMonth(lunarMonth.getMonth() - 1); + } + + public FetusMonth next(int n) { + return new FetusMonth(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/package-info.java new file mode 100644 index 0000000000..776524a3a4 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/fetus/package-info.java @@ -0,0 +1,7 @@ +/** + * 胎神 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.fetus; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ChineseDateFormat.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/PengZu.java old mode 100644 new mode 100755 similarity index 62% rename from bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ChineseDateFormat.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/PengZu.java index 8fa46c3e17..19827191cf --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/chinese/ChineseDateFormat.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/PengZu.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,62 +23,64 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.core.center.date.chinese; +package org.miaixz.bus.core.center.date.culture.cn.minor; + +import org.miaixz.bus.core.center.date.culture.Tradition; +import org.miaixz.bus.core.center.date.culture.cn.sixty.SixtyCycle; /** - * 农历标准化输出格式枚举 + * 彭祖百忌 * * @author Kimi Liu * @since Java 17+ */ -public enum ChineseDateFormat { +public class PengZu extends Tradition { /** - * 干支纪年 数序纪月 数序纪日 - */ - GSS("干支纪年 数序纪月 数序纪日"), - /** - * 生肖纪年 数序纪月 数序纪日 - */ - XSS("生肖纪年 数序纪月 数序纪日"), - /** - * 干支生肖纪年 数序纪月(传统表示) 数序纪日 - */ - GXSS("干支生肖纪年 数序纪月(传统表示) 数序纪日"), - /** - * 干支纪年 数序纪月 干支纪日 - */ - GSG("干支纪年 数序纪月 干支纪日"), - /** - * 干支纪年 干支纪月 干支纪日 + * 天干彭祖百忌 */ - GGG("干支纪年 干支纪月 干支纪日"), + protected PengZuHeavenStem pengZuHeavenStem; + /** - * 农历年年首所在的公历年份 干支纪年 数序纪月 数序纪日 + * 地支彭祖百忌 */ - MIX("农历年年首所在的公历年份 干支纪年 数序纪月 数序纪日"); + protected PengZuEarthBranch pengZuEarthBranch; + + public PengZu(SixtyCycle sixtyCycle) { + pengZuHeavenStem = PengZuHeavenStem.fromIndex(sixtyCycle.getHeavenStem().getIndex()); + pengZuEarthBranch = PengZuEarthBranch.fromIndex(sixtyCycle.getEarthBranch().getIndex()); + } /** - * 农历标准化输出格式信息 + * 从干支初始化 + * + * @param sixtyCycle 干支 + * @return 彭祖百忌 */ - private final String info; + public static PengZu fromSixtyCycle(SixtyCycle sixtyCycle) { + return new PengZu(sixtyCycle); + } + + public String getName() { + return String.format("%s %s", pengZuHeavenStem, pengZuEarthBranch); + } /** - * 构造 + * 天干彭祖百忌 * - * @param info 输出格式信息 + * @return 天干彭祖百忌 */ - ChineseDateFormat(final String info) { - this.info = info; + public PengZuHeavenStem getPengZuHeavenStem() { + return pengZuHeavenStem; } /** - * 获取农历日期输出格式相关描述 + * 地支彭祖百忌 * - * @return 输出格式信息 + * @return 地支彭祖百忌 */ - public String getName() { - return this.info; + public PengZuEarthBranch getPengZuEarthBranch() { + return pengZuEarthBranch; } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/PengZuEarthBranch.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/PengZuEarthBranch.java new file mode 100755 index 0000000000..02e6a1f776 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/PengZuEarthBranch.java @@ -0,0 +1,77 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.minor; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 地支彭祖百忌 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class PengZuEarthBranch extends Samsara { + + public static final String[] NAMES = { + "子不问卜自惹祸殃", "丑不冠带主不还乡", "寅不祭祀神鬼不尝", "卯不穿井水泉不香", + "辰不哭泣必主重丧", "巳不远行财物伏藏", "午不苫盖屋主更张", "未不服药毒气入肠", + "申不安床鬼祟入房", "酉不会客醉坐颠狂", "戌不吃犬作怪上床", "亥不嫁娶不利新郎" + }; + + public PengZuEarthBranch(String name) { + super(NAMES, name); + } + + public PengZuEarthBranch(int index) { + super(NAMES, index); + } + + /** + * 从名称初始化 + * + * @param name 名称 + * @return 地支彭祖百忌 + */ + public static PengZuEarthBranch fromName(String name) { + return new PengZuEarthBranch(name); + } + + /** + * 从索引初始化 + * + * @param index 索引 + * @return 地支彭祖百忌 + */ + public static PengZuEarthBranch fromIndex(int index) { + return new PengZuEarthBranch(index); + } + + + public PengZuEarthBranch next(int n) { + return new PengZuEarthBranch(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/PengZuHeavenStem.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/PengZuHeavenStem.java new file mode 100755 index 0000000000..08ff46ae4d --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/PengZuHeavenStem.java @@ -0,0 +1,76 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.minor; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 天干彭祖百忌 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class PengZuHeavenStem extends Samsara { + + public static final String[] NAMES = { + "甲不开仓财物耗散", "乙不栽植千株不长", "丙不修灶必见灾殃", "丁不剃头头必生疮", + "戊不受田田主不祥", "己不破券二比并亡", "庚不经络织机虚张", "辛不合酱主人不尝", + "壬不泱水更难提防", "癸不词讼理弱敌强" + }; + + public PengZuHeavenStem(String name) { + super(NAMES, name); + } + + public PengZuHeavenStem(int index) { + super(NAMES, index); + } + + /** + * 从名称初始化 + * + * @param name 名称 + * @return 天干彭祖百忌 + */ + public static PengZuHeavenStem fromName(String name) { + return new PengZuHeavenStem(name); + } + + /** + * 从索引初始化 + * + * @param index 索引 + * @return 天干彭祖百忌 + */ + public static PengZuHeavenStem fromIndex(int index) { + return new PengZuHeavenStem(index); + } + + public PengZuHeavenStem next(int n) { + return new PengZuHeavenStem(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/package-info.java new file mode 100644 index 0000000000..bb78a00ee9 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/minor/package-info.java @@ -0,0 +1,7 @@ +/** + * 彭祖 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.minor; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/nine/Nine.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/nine/Nine.java new file mode 100755 index 0000000000..135bea05b9 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/nine/Nine.java @@ -0,0 +1,74 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.nine; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 数九 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Nine extends Samsara { + + public static final String[] NAMES = { + "一九", "二九", "三九", "四九", "五九", "六九", "七九", "八九", "九九" + }; + + public Nine(String name) { + super(NAMES, name); + } + + public Nine(int index) { + super(NAMES, index); + } + + /** + * 从名称初始化 + * + * @param name 名称 + * @return 数九 + */ + public static Nine fromName(String name) { + return new Nine(name); + } + + /** + * 从索引初始化 + * + * @param index 索引 + * @return 数九 + */ + public static Nine fromIndex(int index) { + return new Nine(index); + } + + public Nine next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/nine/NineDay.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/nine/NineDay.java new file mode 100755 index 0000000000..97d97d2873 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/nine/NineDay.java @@ -0,0 +1,51 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.nine; + +import org.miaixz.bus.core.center.date.culture.Replenish; + +/** + * 数九天 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class NineDay extends Replenish { + + public NineDay(Nine nine, int dayIndex) { + super(nine, dayIndex); + } + + /** + * 数九 + * + * @return 数九 + */ + public Nine getNine() { + return (Nine) tradition; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/nine/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/nine/package-info.java new file mode 100644 index 0000000000..834e61ad82 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/nine/package-info.java @@ -0,0 +1,7 @@ +/** + * 数九 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.nine; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/package-info.java new file mode 100644 index 0000000000..ef6a75d0c0 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/package-info.java @@ -0,0 +1,7 @@ +/** + * 中国传统文化/日历相关 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/EarthBranch.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/EarthBranch.java new file mode 100755 index 0000000000..581dfdccb8 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/EarthBranch.java @@ -0,0 +1,235 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.sixty; + +import org.miaixz.bus.core.center.date.Between; +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.Direction; +import org.miaixz.bus.core.center.date.culture.cn.Element; +import org.miaixz.bus.core.center.date.culture.cn.Zodiac; +import org.miaixz.bus.core.center.date.culture.cn.minor.PengZuEarthBranch; +import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.xyz.StringKit; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * 地支 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class EarthBranch extends Samsara { + + /** + * 古今十二时辰与时间对照 + * 子时(23时至01时):夜半时分,也是一天的开始。 + * 丑时(01时至03时):鸡鸣时分,意味着新的一天开始。 + * 寅时(03时至05时):平旦,夜与日的交替之际,太阳即将初升。 + * 卯时(05时至07时):日出时分,太阳刚刚露脸,冉冉初升。 + * 辰时(07时至09时):食时,古人吃早饭的时间。 + * 巳时(09时至11时):隅中,临近中午的时候。 + * 午时(11时至13时):日中,太阳最猛烈的时候。 + * 未时(13时至15时):日昳,太阳偏西为日跌。 + * 申时(15时至17时):哺时,也被称为日铺、夕食等。 + * 酉时(17时至19时):日入时分,太阳落山,天地昏黄,万物朦胧。 + * 戌时(19时至21时):黄昏时分,太阳已经落山,天色逐渐暗淡。 + * 亥时(21时至23时):人定时分,夜色已深,人们已经停止活动,安歇睡眠了。 + */ + public static final String[] NAMES = { + "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" + }; + + /** + * 时辰对应的小时范围 + */ + private static final Map TIME_MAP = new HashMap<>(); + /** + * 小时到时辰的映射 + */ + private static final Map HOUR_MAP = new HashMap<>(); + + static { + int hour = 23; + for (final String c : NAMES) { + // 初始化时辰对应的小时范围 + TIME_MAP.put(c, new Integer[]{hour % 24, (hour + 2) % 24}); + + // 初始化小时到时辰的映射 + HOUR_MAP.put(hour % 24, c + "时"); + HOUR_MAP.put((hour + 1) % 24, c + "时"); + + hour += 2; + } + } + + public EarthBranch(int index) { + super(NAMES, index); + } + + public EarthBranch(String name) { + super(NAMES, name); + } + + public static EarthBranch fromIndex(int index) { + return new EarthBranch(index); + } + + public static EarthBranch fromName(String name) { + return new EarthBranch(name); + } + + /** + * 将时辰描述转换为现代时间段。 + * + * @param chrono 时辰描述,可以是“子时”。 + * @return {@link Between} 对象,表示起始和结束时间。 + * @throws IllegalArgumentException 如果输入的时辰描述无效。 + */ + public static Between of(final String chrono) { + if (StringKit.isEmpty(chrono)) { + throw new IllegalArgumentException("Invalid args for : " + chrono); + } + final String baseTime = chrono.replace("时", Normal.EMPTY); + final Integer[] hours = TIME_MAP.get(baseTime); + if (hours == null) { + throw new IllegalArgumentException("Invalid time"); + } + final Integer startHour = hours[0]; + final Integer endHour = hours[1]; + + + final LocalDateTime start = LocalDateTime.now().withHour(startHour).withMinute(0).withSecond(0).withNano(0); + final LocalDateTime end = (startHour > endHour) ? start.plusDays(1).withHour(endHour) : start.withHour(endHour); + + final Date startDate = Date.from(start.atZone(ZoneId.systemDefault()).toInstant()); + final Date endDate = Date.from(end.atZone(ZoneId.systemDefault()).toInstant()); + + return Between.of(startDate, endDate); + } + + /** + * 根据给定的小时数转换为对应的时辰描述。 + * + * @param hour 小时数,应在0到23之间。 + * @return 时辰描述,如果小时数无效,则返回“未知”。 + */ + public static String get(final int hour) { + return HOUR_MAP.getOrDefault(hour, "未知"); + } + + public EarthBranch next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 五行 + * + * @return 五行 + */ + public Element getElement() { + return Element.fromIndex(new int[]{4, 2, 0, 0, 2, 1, 1, 2, 3, 3, 2, 4}[index]); + } + + /** + * 藏干之本气 + * + * @return 天干 + */ + public HeavenStem getHideHeavenStemMain() { + return HeavenStem.fromIndex(new int[]{9, 5, 0, 1, 4, 2, 3, 5, 6, 7, 4, 8}[index]); + } + + /** + * 藏干之中气,无中气返回null + * + * @return 天干 + */ + public HeavenStem getHideHeavenStemMiddle() { + int n = new int[]{-1, 9, 2, -1, 1, 6, 5, 3, 8, -1, 7, 0}[index]; + return n == -1 ? null : HeavenStem.fromIndex(n); + } + + /** + * 藏干之余气,无余气返回null + * + * @return 天干 + */ + public HeavenStem getHideHeavenStemResidual() { + int n = new int[]{-1, 7, 4, -1, 9, 4, -1, 1, 4, -1, 3, -1}[index]; + return n == -1 ? null : HeavenStem.fromIndex(n); + } + + /** + * 生肖 + * + * @return 生肖 + */ + public Zodiac getZodiac() { + return Zodiac.fromIndex(index); + } + + /** + * 方位 + * + * @return 方位 + */ + public Direction getDirection() { + return Direction.fromIndex(new int[]{0, 4, 2, 2, 4, 8, 8, 4, 6, 6, 4, 0}[index]); + } + + /** + * 相冲的地支(子午冲,丑未冲,寅申冲,辰戌冲,卯酉冲,巳亥冲) + * + * @return 地支 + */ + public EarthBranch next() { + return next(6); + } + + /** + * 煞(逢巳日、酉日、丑日必煞东;亥日、卯日、未日必煞西;申日、子日、辰日必煞南;寅日、午日、戌日必煞北。) + * + * @return 方位 + */ + public Direction getOminous() { + return Direction.fromIndex(new int[]{8, 2, 0, 6}[index % 4]); + } + + /** + * 地支彭祖百忌 + * + * @return 地支彭祖百忌 + */ + public PengZuEarthBranch getPengZuEarthBranch() { + return PengZuEarthBranch.fromIndex(index); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/HeavenStem.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/HeavenStem.java new file mode 100755 index 0000000000..60fe4204a7 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/HeavenStem.java @@ -0,0 +1,186 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.sixty; + +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.Direction; +import org.miaixz.bus.core.center.date.culture.cn.Element; +import org.miaixz.bus.core.center.date.culture.cn.Opposite; +import org.miaixz.bus.core.center.date.culture.cn.Terrain; +import org.miaixz.bus.core.center.date.culture.cn.minor.PengZuHeavenStem; +import org.miaixz.bus.core.center.date.culture.cn.star.ten.TenStar; + +/** + * 天干 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class HeavenStem extends Samsara { + + public static final String[] NAMES = { + "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" + }; + + public HeavenStem(int index) { + super(NAMES, index); + } + + public HeavenStem(String name) { + super(NAMES, name); + } + + public static HeavenStem fromIndex(int index) { + return new HeavenStem(index); + } + + public static HeavenStem fromName(String name) { + return new HeavenStem(name); + } + + public HeavenStem next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 五行 + * + * @return 五行 + */ + public Element getElement() { + return Element.fromIndex(index / 2); + } + + /** + * 阴阳 + * + * @return 阴阳 + */ + public Opposite getOpposite() { + return index % 2 == 0 ? Opposite.YANG : Opposite.YIN; + } + + /** + * 十神(生我者,正印偏印。我生者,伤官食神。克我者,正官七杀。我克者,正财偏财。同我者,劫财比肩。) + * + * @param target 天干 + * @return 十神 + */ + public TenStar getTenStar(HeavenStem target) { + if (null == target) { + return null; + } + Element hostElement = getElement(); + Element guestElement = target.getElement(); + int index = 0; + boolean sameYinYang = getOpposite().equals(target.getOpposite()); + if (hostElement.getReinforce().equals(guestElement)) { + index = 1; + } else if (hostElement.getRestrain().equals(guestElement)) { + index = 2; + } else if (guestElement.getRestrain().equals(hostElement)) { + index = 3; + } else if (guestElement.getReinforce().equals(hostElement)) { + index = 4; + } + return TenStar.fromIndex(index * 2 + (sameYinYang ? 0 : 1)); + } + + /** + * 方位 + * + * @return 方位 + */ + public Direction getDirection() { + return Direction.fromIndex(new int[]{2, 8, 4, 6, 0}[index / 2]); + } + + /** + * 喜神方位(《喜神方位歌》甲己在艮乙庚乾,丙辛坤位喜神安。丁壬只在离宫坐,戊癸原在在巽间。) + * + * @return 方位 + */ + public Direction getJoyDirection() { + return Direction.fromIndex(new int[]{7, 5, 1, 8, 3}[index % 5]); + } + + /** + * 阳贵神方位(《阳贵神歌》甲戊坤艮位,乙己是坤坎,庚辛居离艮,丙丁兑与乾,震巽属何日,壬癸贵神安。) + * + * @return 方位 + */ + public Direction getYangDirection() { + return Direction.fromIndex(new int[]{1, 1, 6, 5, 7, 0, 8, 7, 2, 3}[index]); + } + + /** + * 阴贵神方位(《阴贵神歌》甲戊见牛羊,乙己鼠猴乡,丙丁猪鸡位,壬癸蛇兔藏,庚辛逢虎马,此是贵神方。) + * + * @return 方位 + */ + public Direction getYinDirection() { + return Direction.fromIndex(new int[]{7, 0, 5, 6, 1, 1, 7, 8, 3, 2}[index]); + } + + /** + * 财神方位(《财神方位歌》甲乙东北是财神,丙丁向在西南寻,戊己正北坐方位,庚辛正东去安身,壬癸原来正南坐,便是财神方位真。) + * + * @return 方位 + */ + public Direction getWealthDirection() { + return Direction.fromIndex(new int[]{7, 1, 0, 2, 8}[index / 2]); + } + + /** + * 福神方位(《福神方位歌》甲乙东南是福神,丙丁正东是堪宜,戊北己南庚辛坤,壬在乾方癸在西。) + * + * @return 方位 + */ + public Direction getMascotDirection() { + return Direction.fromIndex(new int[]{3, 3, 2, 2, 0, 8, 1, 1, 5, 6}[index]); + } + + /** + * 天干彭祖百忌 + * + * @return 天干彭祖百忌 + */ + public PengZuHeavenStem getPengZuHeavenStem() { + return PengZuHeavenStem.fromIndex(index); + } + + /** + * 地势(长生十二神) + * + * @param earthBranch 地支 + * @return 地势(长生十二神) + */ + public Terrain getTerrain(EarthBranch earthBranch) { + int earthBranchIndex = earthBranch.getIndex(); + return Terrain.fromIndex(new int[]{1, 6, 10, 9, 10, 9, 7, 0, 4, 3}[index] + (Opposite.YANG == getOpposite() ? earthBranchIndex : -earthBranchIndex)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/SixtyCycle.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/SixtyCycle.java new file mode 100755 index 0000000000..8a8ed4c05c --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/SixtyCycle.java @@ -0,0 +1,128 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.sixty; + +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.Sound; +import org.miaixz.bus.core.center.date.culture.cn.Ten; +import org.miaixz.bus.core.center.date.culture.cn.minor.PengZu; + +/** + * 六十甲子(六十干支周) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SixtyCycle extends Samsara { + + public static final String[] NAMES = { + "甲子", "乙丑", "丙寅", "丁卯", "戊辰", "己巳", "庚午", "辛未", "壬申", + "癸酉", "甲戌", "乙亥", "丙子", "丁丑", "戊寅", "己卯", "庚辰", "辛巳", + "壬午", "癸未", "甲申", "乙酉", "丙戌", "丁亥", "戊子", "己丑", "庚寅", + "辛卯", "壬辰", "癸巳", "甲午", "乙未", "丙申", "丁酉", "戊戌", "己亥", + "庚子", "辛丑", "壬寅", "癸卯", "甲辰", "乙巳", "丙午", "丁未", "戊申", + "己酉", "庚戌", "辛亥", "壬子", "癸丑", "甲寅", "乙卯", "丙辰", "丁巳", + "戊午", "己未", "庚申", "辛酉", "壬戌", "癸亥" + }; + + public SixtyCycle(int index) { + super(NAMES, index); + } + + public SixtyCycle(String name) { + super(NAMES, name); + } + + public static SixtyCycle fromIndex(int index) { + return new SixtyCycle(index); + } + + public static SixtyCycle fromName(String name) { + return new SixtyCycle(name); + } + + /** + * 天干 + * + * @return 天干 + */ + public HeavenStem getHeavenStem() { + return HeavenStem.fromIndex(index % HeavenStem.NAMES.length); + } + + /** + * 地支 + * + * @return 地支 + */ + public EarthBranch getEarthBranch() { + return EarthBranch.fromIndex(index % EarthBranch.NAMES.length); + } + + /** + * 纳音 + * + * @return 纳音 + */ + public Sound getSound() { + return Sound.fromIndex(index / 2); + } + + /** + * 彭祖百忌 + * + * @return 彭祖百忌 + */ + public PengZu getPengZu() { + return PengZu.fromSixtyCycle(this); + } + + /** + * 旬 + * + * @return 旬 + */ + public Ten getTen() { + return Ten.fromIndex((getHeavenStem().getIndex() - getEarthBranch().getIndex()) / 2); + } + + /** + * 旬空(空亡),因地支比天干多2个,旬空则为每一轮干支一一配对后多出来的2个地支 + * + * @return 旬空(空亡) + */ + public EarthBranch[] getExtraEarthBranches() { + EarthBranch[] l = new EarthBranch[2]; + l[0] = EarthBranch.fromIndex(10 + getEarthBranch().getIndex() - getHeavenStem().getIndex()); + l[1] = l[0].next(1); + return l; + } + + public SixtyCycle next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/package-info.java new file mode 100644 index 0000000000..335f1935f6 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/sixty/package-info.java @@ -0,0 +1,7 @@ +/** + * 六十周期 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.sixty; diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/filter/PatternFilter.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/nine/Dipper.java similarity index 72% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/filter/PatternFilter.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/nine/Dipper.java index 3a6ad30a86..b2d499584a 100755 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/filter/PatternFilter.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/nine/Dipper.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,34 +23,40 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.intercept.filter; +package org.miaixz.bus.core.center.date.culture.cn.star.nine; -import org.miaixz.bus.proxy.intercept.MethodFilter; - -import java.lang.reflect.Method; +import org.miaixz.bus.core.center.date.culture.Samsara; /** - * 如果方法的名称与提供的正则表达式(JDK regex)模式字符串匹配,则方法筛选器实现返回true + * 北斗九星 * * @author Kimi Liu * @since Java 17+ */ -public class PatternFilter implements MethodFilter { +public class Dipper extends Samsara { - public static String GETTER_SETTER_PATTERN = "get\\w+|set\\w+"; - private final String pattern; + public static final String[] NAMES = { + "天枢", "天璇", "天玑", "天权", "玉衡", "开阳", "摇光", "洞明", "隐元" + }; - public PatternFilter(String pattern) { - this.pattern = pattern; + public Dipper(int index) { + super(NAMES, index); } - public static MethodFilter getterSetterFilter() { - return new PatternFilter(GETTER_SETTER_PATTERN); + public Dipper(String name) { + super(NAMES, name); } - public boolean accepts(Method method) { - return method.getName().matches(pattern); + public static Dipper fromIndex(int index) { + return new Dipper(index); } -} + public static Dipper fromName(String name) { + return new Dipper(name); + } + public Dipper next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/nine/NineStar.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/nine/NineStar.java new file mode 100755 index 0000000000..7744376ba6 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/nine/NineStar.java @@ -0,0 +1,106 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.star.nine; + +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.Direction; +import org.miaixz.bus.core.center.date.culture.cn.Element; +import org.miaixz.bus.core.lang.Normal; + +/** + * 九星 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class NineStar extends Samsara { + + public static final String[] NAMES = { + "一", "二", "三", "四", "五", "六", "七", "八", "九" + }; + + public NineStar(int index) { + super(NAMES, index); + } + + public NineStar(String name) { + super(NAMES, name); + } + + public static NineStar fromIndex(int index) { + return new NineStar(index); + } + + public static NineStar fromName(String name) { + return new NineStar(name); + } + + public NineStar next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 颜色 + * + * @return 颜色 + */ + public String getColor() { + return Normal.COLOR[index]; + } + + /** + * 五行 + * + * @return 五行 + */ + public Element getElement() { + return Element.fromIndex(new int[]{4, 2, 0, 0, 2, 3, 3, 2, 1}[index]); + } + + /** + * 北斗九星 + * + * @return 北斗九星 + */ + public Dipper getDipper() { + return Dipper.fromIndex(index); + } + + /** + * 方位 + * + * @return 方位 + */ + public Direction getDirection() { + return Direction.fromIndex(index); + } + + @Override + public String toString() { + return getName() + getColor() + getElement(); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/nine/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/nine/package-info.java new file mode 100644 index 0000000000..2965658410 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/nine/package-info.java @@ -0,0 +1,7 @@ +/** + * 九星 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.star.nine; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/seven/SevenStar.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/seven/SevenStar.java new file mode 100755 index 0000000000..84bf0b73d1 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/seven/SevenStar.java @@ -0,0 +1,70 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.star.seven; + +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.Week; + +/** + * 七曜(七政、七纬、七耀) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SevenStar extends Samsara { + + public static final String[] NAMES = {"日", "月", "火", "水", "木", "金", "土"}; + + public SevenStar(int index) { + super(NAMES, index); + } + + public SevenStar(String name) { + super(NAMES, name); + } + + public static SevenStar fromIndex(int index) { + return new SevenStar(index); + } + + public static SevenStar fromName(String name) { + return new SevenStar(name); + } + + public SevenStar next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 星期 + * + * @return 星期 + */ + public Week getWeek() { + return Week.fromIndex(index); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/seven/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/seven/package-info.java new file mode 100644 index 0000000000..70106f4ccc --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/seven/package-info.java @@ -0,0 +1,7 @@ +/** + * 七曜 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.star.seven; diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/filter/SimpleFilter.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/ten/TenStar.java similarity index 72% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/filter/SimpleFilter.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/ten/TenStar.java index 632a8b39c3..382444b5ea 100755 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/filter/SimpleFilter.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/ten/TenStar.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,36 +23,40 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.intercept.filter; +package org.miaixz.bus.core.center.date.culture.cn.star.ten; -import org.miaixz.bus.proxy.intercept.MethodFilter; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; +import org.miaixz.bus.core.center.date.culture.Samsara; /** - * 一个简单的方法筛选器实现,如果方法的名称在一组可接受的名称中,则该实现仅返回true + * 十神 * * @author Kimi Liu * @since Java 17+ */ -public class SimpleFilter implements MethodFilter { +public class TenStar extends Samsara { - private final Set methodNames; + public static final String[] NAMES = { + "比肩", "劫财", "食神", "伤官", "偏财", "正财", "七杀", "正官", "偏印", "正印" + }; - public SimpleFilter() { - this.methodNames = new HashSet(); + public TenStar(int index) { + super(NAMES, index); } - public SimpleFilter(String[] methodNames) { - this.methodNames = new HashSet(Arrays.asList(methodNames)); + public TenStar(String name) { + super(NAMES, name); } - public boolean accepts(Method method) { - return methodNames.contains(method.getName()); + public static TenStar fromIndex(int index) { + return new TenStar(index); } -} + public static TenStar fromName(String name) { + return new TenStar(name); + } + public TenStar next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/ten/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/ten/package-info.java new file mode 100644 index 0000000000..bcfafd864f --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/ten/package-info.java @@ -0,0 +1,7 @@ +/** + * 十神 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.star.ten; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twelve/Ecliptic.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twelve/Ecliptic.java new file mode 100755 index 0000000000..308b9ee17e --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twelve/Ecliptic.java @@ -0,0 +1,70 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.star.twelve; + +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.Luck; + +/** + * 黄道黑道 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Ecliptic extends Samsara { + + public static final String[] NAMES = {"黄道", "黑道"}; + + public Ecliptic(int index) { + super(NAMES, index); + } + + public Ecliptic(String name) { + super(NAMES, name); + } + + public static Ecliptic fromIndex(int index) { + return new Ecliptic(index); + } + + public static Ecliptic fromName(String name) { + return new Ecliptic(name); + } + + public Ecliptic next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 吉凶 + * + * @return 吉凶 + */ + public Luck getLuck() { + return Luck.fromIndex(index); + } + +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/expression/LimiterExpressionRootObject.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twelve/TwelveStar.java similarity index 66% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/expression/LimiterExpressionRootObject.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twelve/TwelveStar.java index 893f3136c0..e995ba4090 100755 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/expression/LimiterExpressionRootObject.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twelve/TwelveStar.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,57 +23,50 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.expression; +package org.miaixz.bus.core.center.date.culture.cn.star.twelve; -import org.miaixz.bus.limiter.Limiter; - -import java.lang.reflect.Method; +import org.miaixz.bus.core.center.date.culture.Samsara; /** + * 黄道黑道十二神 + * * @author Kimi Liu * @since Java 17+ */ -public class LimiterExpressionRootObject { - - private final Limiter limiter; - - private final Method targetMethod; - - private final Object[] args; +public class TwelveStar extends Samsara { - private final Object target; + public static final String[] NAMES = { + "青龙", "明堂", "天刑", "朱雀", "金匮", "天德", + "白虎", "玉堂", "天牢", "玄武", "司命", "勾陈" + }; - private final Class targetClass; - - public LimiterExpressionRootObject( - Limiter limiter, Method targetMethod, Object[] args, Object target, Class targetClass) { - - this.targetMethod = targetMethod; - this.target = target; - this.targetClass = targetClass; - this.args = args; - this.limiter = limiter; + public TwelveStar(int index) { + super(NAMES, index); } - - public Limiter getLimiter() { - return limiter; + public TwelveStar(String name) { + super(NAMES, name); } - public Method getTargetMethod() { - return targetMethod; + public static TwelveStar fromIndex(int index) { + return new TwelveStar(index); } - public Object[] getArgs() { - return args; + public static TwelveStar fromName(String name) { + return new TwelveStar(name); } - public Object getTarget() { - return target; + public TwelveStar next(int n) { + return fromIndex(nextIndex(n)); } - public Class getTargetClass() { - return targetClass; + /** + * 黄道黑道 + * + * @return 黄道黑道 + */ + public Ecliptic getEcliptic() { + return Ecliptic.fromIndex(new int[]{0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1}[index]); } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twelve/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twelve/package-info.java new file mode 100644 index 0000000000..f389fde7e6 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twelve/package-info.java @@ -0,0 +1,7 @@ +/** + * 十二神 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.star.twelve; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twentyeight/TwentyEightStar.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twentyeight/TwentyEightStar.java new file mode 100755 index 0000000000..47f9a23224 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twentyeight/TwentyEightStar.java @@ -0,0 +1,114 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.cn.star.twentyeight; + +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.Animal; +import org.miaixz.bus.core.center.date.culture.cn.Land; +import org.miaixz.bus.core.center.date.culture.cn.Luck; +import org.miaixz.bus.core.center.date.culture.cn.Zone; +import org.miaixz.bus.core.center.date.culture.cn.star.seven.SevenStar; + +/** + * 二十八宿 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class TwentyEightStar extends Samsara { + + public static final String[] NAMES = { + "角", "亢", "氐", "房", "心", "尾", "箕", "斗", "牛", "女", + "虚", "危", "室", "壁", "奎", "娄", "胃", "昴", "毕", "觜", + "参", "井", "鬼", "柳", "星", "张", "翼", "轸" + }; + + public TwentyEightStar(int index) { + super(NAMES, index); + } + + public TwentyEightStar(String name) { + super(NAMES, name); + } + + public static TwentyEightStar fromIndex(int index) { + return new TwentyEightStar(index); + } + + public static TwentyEightStar fromName(String name) { + return new TwentyEightStar(name); + } + + public TwentyEightStar next(int n) { + return fromIndex(nextIndex(n)); + } + + /** + * 七曜 + * + * @return 七曜 + */ + public SevenStar getSevenStar() { + return SevenStar.fromIndex(index % 7 + 4); + } + + /** + * 九野 + * + * @return 九野 + */ + public Land getLand() { + return Land.fromIndex(new int[]{4, 4, 4, 2, 2, 2, 7, 7, 7, 0, 0, 0, 0, 5, 5, 5, 6, 6, 6, 1, 1, 1, 8, 8, 8, 3, 3, 3}[index]); + } + + /** + * 宫 + * + * @return 宫 + */ + public Zone getZone() { + return Zone.fromIndex(index / 7); + } + + /** + * 动物 + * + * @return 动物 + */ + public Animal getAnimal() { + return Animal.fromIndex(index); + } + + /** + * 吉凶 + * + * @return 吉凶 + */ + public Luck getLuck() { + return Luck.fromIndex(new int[]{0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0}[index]); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twentyeight/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twentyeight/package-info.java new file mode 100644 index 0000000000..dd77a300d9 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/cn/star/twentyeight/package-info.java @@ -0,0 +1,7 @@ +/** + * 二十八宿 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.cn.star.twentyeight; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Constellation.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Constellation.java new file mode 100644 index 0000000000..2dfa66c9cf --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Constellation.java @@ -0,0 +1,244 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.en; + +import org.miaixz.bus.core.xyz.DateKit; +import org.miaixz.bus.core.xyz.EnumKit; + +import java.time.LocalDate; +import java.time.MonthDay; +import java.util.Calendar; +import java.util.Date; + +/** + * 星座 + * + * @author Kimi Liu + * @since Java 17+ + */ +public enum Constellation { + + /** + * 白羊座 + */ + ARIES(0, "白羊", MonthDay.of(3, 21), MonthDay.of(4, 19)), + /** + * 金牛座 + */ + TAURUS(1, "金牛", MonthDay.of(4, 20), MonthDay.of(5, 20)), + /** + * 双子座 + */ + GEMINI(2, "双子", MonthDay.of(5, 21), MonthDay.of(6, 21)), + /** + * 巨蟹座 + */ + CANCER(3, "巨蟹", MonthDay.of(6, 22), MonthDay.of(7, 22)), + /** + * 狮子座 + */ + LEO(4, "狮子", MonthDay.of(7, 23), MonthDay.of(8, 22)), + /** + * 处女座 + */ + VIRGO(5, "处女", MonthDay.of(8, 23), MonthDay.of(9, 22)), + /** + * 天秤座 + */ + LIBRA(6, "天秤", MonthDay.of(9, 23), MonthDay.of(10, 23)), + /** + * 天蝎座 + */ + SCORPIO(7, "天蝎", MonthDay.of(10, 24), MonthDay.of(11, 22)), + /** + * 射手座 + */ + SAGITTARIUS(8, "射手", MonthDay.of(11, 23), MonthDay.of(12, 21)), + /** + * 摩羯座 + */ + CAPRICORN(9, "摩羯", MonthDay.of(12, 22), MonthDay.of(1, 19)), + /** + * 水瓶座 + */ + AQUARIUS(10, "水瓶", MonthDay.of(1, 20), MonthDay.of(2, 18)), + /** + * 双鱼座 + */ + PISCES(11, "双鱼", MonthDay.of(2, 19), MonthDay.of(3, 20)); + + private static final Constellation[] ENUMS = Constellation.values(); + + /** + * 编码 + */ + private final long code; + /** + * 名称 + */ + private final String name; + + /** + * 开始月日(包含) + */ + private final MonthDay begin; + + /** + * 结束月日(包含) + */ + private final MonthDay end; + + Constellation(long code, String name, MonthDay begin, MonthDay end) { + this.code = code; + this.name = name; + this.begin = begin; + this.end = end; + } + + /** + * 按宫位获取星座 + * + * @param code 编码 + * @return this + */ + public static Constellation get(int code) { + if (code < 1 || code > 12) { + throw new IllegalArgumentException(); + } + return ENUMS[(code + 2) % 12]; + } + + /** + * 按日期获取星座 + * + * @param date 日期 + * @return this + */ + public static Constellation get(LocalDate date) { + return get(date.getMonthValue(), date.getDayOfMonth()); + } + + /** + * 按月日获取星座 + * + * @param month 月份 + * @param day 日期 + * @return this + */ + public static Constellation get(int month, int day) { + return get(MonthDay.of(month, day)); + } + + /** + * 按月日获取星座 + * + * @param monthDay 月份 + * @return this + */ + public static Constellation get(MonthDay monthDay) { + int month = monthDay.getMonthValue(); + int day = monthDay.getDayOfMonth(); + Constellation zodiac = ENUMS[month - 1]; + return day <= zodiac.end.getDayOfMonth() ? zodiac : ENUMS[month % 12]; + } + + /** + * 通过生日计算星座 + * + * @param date 出生日期 + * @return 星座名 + */ + public static String getName(final Date date) { + return getName(DateKit.calendar(date)); + } + + /** + * 通过生日计算星座 + * + * @param calendar 出生日期 + * @return 星座名 + */ + public static String getName(final Calendar calendar) { + if (null == calendar) { + return null; + } + return getName(calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); + } + + /** + * 通过生日计算星座 + * + * @param month 月,从0开始计数 + * @param day 天 + * @return 星座名 + */ + public static String getName(final Month month, final int day) { + return getName(month.getValue(), day); + } + + /** + * 通过生日计算星座 + * + * @param month 月,从0开始计数,见{@link Month#getValue()} + * @param day 天 + * @return 星座名 + */ + public static String getName(final int month, final int day) { + return get(month, day).name; + } + + /** + * 获取枚举属性信息 + * + * @param fieldName 属性名称 + * @return the string[] + */ + public static String[] get(String fieldName) { + return EnumKit.getFieldValues(Constellation.class, fieldName).toArray(String[]::new); + } + + /** + * @return 对应的名称 + */ + public String getName(final int code) { + return this.name; + } + + /** + * @return 单位对应的编码 + */ + public long getCode() { + return this.code; + } + + /** + * @return 对应的名称 + */ + public String getName() { + return this.name; + } + +} diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/factory/ProxyClass.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Modify.java old mode 100755 new mode 100644 similarity index 87% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/factory/ProxyClass.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Modify.java index 14d6769480..983fd1039d --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/factory/ProxyClass.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Modify.java @@ -23,17 +23,27 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.factory; +package org.miaixz.bus.core.center.date.culture.en; /** - * 代理类生成器生成特定类型的代理(拦截器、调用程序等) + * 修改类型 * * @author Kimi Liu * @since Java 17+ */ -public interface ProxyClass { +public enum Modify { + /** + * 取指定日期短的起始值. + */ + TRUNCATE, - Class createProxy(ClassLoader classLoader, Class[] proxyClasses); + /** + * 指定日期属性按照四舍五入处理 + */ + ROUND, + /** + * 指定日期属性按照进一法处理 + */ + CEILING } - diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Month.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Month.java new file mode 100644 index 0000000000..bcffeec62d --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Month.java @@ -0,0 +1,299 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.en; + +import org.miaixz.bus.core.lang.Assert; + +import java.time.format.TextStyle; +import java.util.Calendar; +import java.util.Locale; + +/** + * 月份枚举 + * 与Calendar中的月份int值对应 + * + * @author Kimi Liu + * @see Calendar#JANUARY + * @see Calendar#FEBRUARY + * @see Calendar#MARCH + * @see Calendar#APRIL + * @see Calendar#MAY + * @see Calendar#JUNE + * @see Calendar#JULY + * @see Calendar#AUGUST + * @see Calendar#SEPTEMBER + * @see Calendar#OCTOBER + * @see Calendar#NOVEMBER + * @see Calendar#DECEMBER + * @see Calendar#UNDECIMBER + * @since Java 17+ + */ +public enum Month { + /** + * 一月 + */ + JANUARY(Calendar.JANUARY), + /** + * 二月 + */ + FEBRUARY(Calendar.FEBRUARY), + /** + * 三月 + */ + MARCH(Calendar.MARCH), + /** + * 四月 + */ + APRIL(Calendar.APRIL), + /** + * 五月 + */ + MAY(Calendar.MAY), + /** + * 六月 + */ + JUNE(Calendar.JUNE), + /** + * 七月 + */ + JULY(Calendar.JULY), + /** + * 八月 + */ + AUGUST(Calendar.AUGUST), + /** + * 九月 + */ + SEPTEMBER(Calendar.SEPTEMBER), + /** + * 十月 + */ + OCTOBER(Calendar.OCTOBER), + /** + * 十一月 + */ + NOVEMBER(Calendar.NOVEMBER), + /** + * 十二月 + */ + DECEMBER(Calendar.DECEMBER), + /** + * 十三月,仅用于农历 + */ + UNDECIMBER(Calendar.UNDECIMBER); + + private static final Month[] ENUMS = Month.values(); + + /** + * 对应值,见{@link Calendar} + */ + private final int value; + + /** + * 构造 + * + * @param value 对应值,见{@link Calendar} + */ + Month(final int value) { + this.value = value; + } + + /** + * 将 {@link Calendar}月份相关值转换为Month枚举对象 + * 未找到返回{@code null} + * + * @param calendarMonthIntValue Calendar中关于Month的int值,从0开始 + * @return Month + * @see Calendar#JANUARY + * @see Calendar#FEBRUARY + * @see Calendar#MARCH + * @see Calendar#APRIL + * @see Calendar#MAY + * @see Calendar#JUNE + * @see Calendar#JULY + * @see Calendar#AUGUST + * @see Calendar#SEPTEMBER + * @see Calendar#OCTOBER + * @see Calendar#NOVEMBER + * @see Calendar#DECEMBER + * @see Calendar#UNDECIMBER + */ + public static Month of(final int calendarMonthIntValue) { + if (calendarMonthIntValue >= ENUMS.length || calendarMonthIntValue < 0) { + return null; + } + return ENUMS[calendarMonthIntValue]; + } + + /** + * 解析别名为Month对象,别名如:jan或者JANUARY,不区分大小写 + * + * @param name 别名值 + * @return 月份枚举Month,非空 + * @throws IllegalArgumentException 如果别名无对应的枚举,抛出此异常 + */ + public static Month of(final String name) throws IllegalArgumentException { + if (null != name && name.length() > 2) { + switch (Character.toLowerCase(name.charAt(0))) { + case 'a': + switch (Character.toLowerCase(name.charAt(1))) { + case 'p': + return APRIL; // april + case 'u': + return AUGUST; // august + } + break; + case 'j': + if (Character.toLowerCase(name.charAt(1)) == 'a') { + return JANUARY; // january + } + switch (Character.toLowerCase(name.charAt(2))) { + case 'n': + return JUNE; // june + case 'l': + return JULY; // july + } + break; + case 'f': + return FEBRUARY; // february + case 'm': + switch (Character.toLowerCase(name.charAt(2))) { + case 'r': + return MARCH; // march + case 'y': + return MAY; // may + } + break; + case 's': + return SEPTEMBER; // september + case 'o': + return OCTOBER; // october + case 'n': + return NOVEMBER; // november + case 'd': + return DECEMBER; // december + } + } + + throw new IllegalArgumentException("Invalid Month name: " + name); + } + + /** + * {@link java.time.Month}转换为Month对象 + * + * @param month {@link java.time.Month} + * @return Month + */ + public static Month of(final java.time.Month month) { + return of(month.ordinal()); + } + + /** + * 获得指定月的最后一天 + * + * @param month 月份,从0开始 + * @param isLeapYear 是否为闰年,闰年只对二月有影响 + * @return 最后一天,可能为28,29,30,31 + */ + public static int getLastDay(final int month, final boolean isLeapYear) { + final Month of = of(month); + Assert.notNull(of, "Invalid Month base 0: " + month); + return of.getLastDay(isLeapYear); + } + + /** + * 获取{@link Calendar}中的对应值 + * 此值从0开始,即0表示一月 + * + * @return {@link Calendar}中的对应月份值,从0开始计数 + */ + public int getValue() { + return this.value; + } + + /** + * 获取月份值,此值与{@link java.time.Month}对应 + * 此值从1开始,即1表示一月 + * + * @return 月份值,对应{@link java.time.Month},从1开始计数 + */ + public int getIsoValue() { + Assert.isFalse(this == UNDECIMBER, "Unsupported undecimber field"); + return getValue() + 1; + } + + /** + * 获取此月份最后一天的值 + * 不支持 {@link #UNDECIMBER} + * + * @param isLeapYear 是否闰年 + * @return 此月份最后一天的值 + */ + public int getLastDay(final boolean isLeapYear) { + switch (this) { + case FEBRUARY: + return isLeapYear ? 29 : 28; + case APRIL: + case JUNE: + case SEPTEMBER: + case NOVEMBER: + return 30; + default: + return 31; + } + } + + /** + * 转换为{@link java.time.Month} + * + * @return {@link java.time.Month} + */ + public java.time.Month toJdkMonth() { + return java.time.Month.of(getIsoValue()); + } + + /** + * 获取显示名称 + * + * @param style 名称风格 + * @return 显示名称 + */ + public String getDisplayName(final TextStyle style) { + return getDisplayName(style, Locale.getDefault()); + } + + /** + * 获取显示名称 + * + * @param style 名称风格 + * @param locale {@link Locale} + * @return 显示名称 + */ + public String getDisplayName(final TextStyle style, final Locale locale) { + return toJdkMonth().getDisplayName(style, locale); + } + +} diff --git a/bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/ClazzEntity.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Quarter.java similarity index 61% rename from bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/ClazzEntity.java rename to bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Quarter.java index 8e1cffaae0..3f026c1d8c 100644 --- a/bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/ClazzEntity.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Quarter.java @@ -23,68 +23,103 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.tracer.monitor; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +package org.miaixz.bus.core.center.date.culture.en; /** + * 季度枚举 + * * @author Kimi Liu + * @see #Q1 + * @see #Q2 + * @see #Q3 + * @see #Q4 * @since Java 17+ */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class ClazzEntity { +public enum Quarter { /** - * 当前应用进程ID - */ - private Integer id; - /** - * 当前应用名称 + * 一季度 */ - private String name; + Q1(1, "一季度"), /** - * 时间 格式 MM/dd HH:mm" + * 二季度 */ - private String date; + Q2(2, "二季度"), /** - * 表示载入了类的数量 + * 三季度 */ - private String loaded; + Q3(3, "三季度"), /** - * 表示载入了类的合计 + * 四季度 */ - private String bytes1; - /** - * 表示卸载类合计大小 - */ - private String bytes2; + Q4(4, "四季度"); + + private static final Quarter[] ENUMS = Quarter.values(); + /** - * 表示卸载类的数量 + * 编码 */ - private String unloaded; + private final int code; /** - * 表示加载和卸载类总共的耗时 + * 名称 */ - private String time1; + private final String name; + + Quarter(final int code, final String name) { + this.code = code; + this.name = name; + } + /** - * 表示编译任务执行的次数 + * 将 季度int转换为Season枚举对象 + * + * @param intValue 季度int表示 + * @return {@code Quarter} + * @see #Q1 + * @see #Q2 + * @see #Q3 + * @see #Q4 */ - private String compiled; + public static Quarter of(final int intValue) { + switch (intValue) { + case 1: + return Q1; + case 2: + return Q2; + case 3: + return Q3; + case 4: + return Q4; + default: + return null; + } + } + /** - * 表示编译失败的次数 + * 获取季度值 + * + * @return 季度值 */ - private String failed; + public static String getName(int code) { + return ENUMS[code].name; + } + /** - * 表示编译不可用的次数 + * 获取季度值 + * + * @return 季度值 */ - private String invalid; + public int getCode() { + return this.code; + } + /** - * 表示编译的总耗时 + * 获取季度值 + * + * @return 季度值 */ - private String time2; + public String getName() { + return this.name; + } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Units.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Units.java new file mode 100644 index 0000000000..99f91ac24e --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Units.java @@ -0,0 +1,132 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.en; + +import java.time.temporal.ChronoUnit; + +/** + * 日期时间单位,每个单位都是以毫秒为基数 + * + * @author Kimi Liu + * @since Java 17+ + */ +public enum Units { + /** + * 一毫秒 + */ + MS(1), + /** + * 一秒的毫秒数 + */ + SECOND(1000), + /** + * 一分钟的毫秒数 + */ + MINUTE(SECOND.getMillis() * 60), + /** + * 一小时的毫秒数 + */ + HOUR(MINUTE.getMillis() * 60), + /** + * 一天的毫秒数 + */ + DAY(HOUR.getMillis() * 24), + /** + * 一周的毫秒数 + */ + WEEK(DAY.getMillis() * 7); + + private final long millis; + + Units(final long millis) { + this.millis = millis; + } + + /** + * 单位兼容转换,将{@link ChronoUnit}转换为对应的DateUnit + * + * @param unit {@link ChronoUnit} + * @return Units,null表示不支持此单位 + */ + public static Units of(final ChronoUnit unit) { + switch (unit) { + case MICROS: + return Units.MS; + case SECONDS: + return Units.SECOND; + case MINUTES: + return Units.MINUTE; + case HOURS: + return Units.HOUR; + case DAYS: + return Units.DAY; + case WEEKS: + return Units.WEEK; + } + return null; + } + + /** + * 单位兼容转换,将DateUnit转换为对应的{@link ChronoUnit} + * + * @param unit Units + * @return {@link ChronoUnit} + */ + public static ChronoUnit toChronoUnit(final Units unit) { + switch (unit) { + case MS: + return ChronoUnit.MICROS; + case SECOND: + return ChronoUnit.SECONDS; + case MINUTE: + return ChronoUnit.MINUTES; + case HOUR: + return ChronoUnit.HOURS; + case DAY: + return ChronoUnit.DAYS; + case WEEK: + return ChronoUnit.WEEKS; + } + return null; + } + + /** + * @return 单位对应的毫秒数 + */ + public long getMillis() { + return this.millis; + } + + /** + * 单位兼容转换,将DateUnit转换为对应的{@link ChronoUnit} + * + * @return {@link ChronoUnit} + */ + public ChronoUnit toChronoUnit() { + return Units.toChronoUnit(this); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Various.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Various.java new file mode 100644 index 0000000000..97210433ea --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Various.java @@ -0,0 +1,188 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.en; + +import java.util.Calendar; + +/** + * 日期各个部分的枚举 + * 与Calendar相应值对应 + * + * @author Kimi Liu + * @since Java 17+ + */ +public enum Various { + + /** + * 世纪 + * + * @see Calendar#ERA + */ + ERA(Calendar.ERA), + /** + * 年 + * + * @see Calendar#YEAR + */ + YEAR(Calendar.YEAR), + /** + * 月 + * + * @see Calendar#MONTH + */ + MONTH(Calendar.MONTH), + /** + * 一年中第几周 + * + * @see Calendar#WEEK_OF_YEAR + */ + WEEK_OF_YEAR(Calendar.WEEK_OF_YEAR), + /** + * 一月中第几周 + * + * @see Calendar#WEEK_OF_MONTH + */ + WEEK_OF_MONTH(Calendar.WEEK_OF_MONTH), + /** + * 一月中的第几天 + * + * @see Calendar#DAY_OF_MONTH + */ + DAY_OF_MONTH(Calendar.DAY_OF_MONTH), + /** + * 一年中的第几天 + * + * @see Calendar#DAY_OF_YEAR + */ + DAY_OF_YEAR(Calendar.DAY_OF_YEAR), + /** + * 周几,1表示周日,2表示周一 + * + * @see Calendar#DAY_OF_WEEK + */ + DAY_OF_WEEK(Calendar.DAY_OF_WEEK), + /** + * 天所在的周是这个月的第几周 + * + * @see Calendar#DAY_OF_WEEK_IN_MONTH + */ + DAY_OF_WEEK_IN_MONTH(Calendar.DAY_OF_WEEK_IN_MONTH), + /** + * 上午或者下午 + * + * @see Calendar#AM_PM + */ + AM_PM(Calendar.AM_PM), + /** + * 小时,用于12小时制 + * + * @see Calendar#HOUR + */ + HOUR(Calendar.HOUR), + /** + * 小时,用于24小时制 + * + * @see Calendar#HOUR + */ + HOUR_OF_DAY(Calendar.HOUR_OF_DAY), + /** + * 分钟 + * + * @see Calendar#MINUTE + */ + MINUTE(Calendar.MINUTE), + /** + * 秒 + * + * @see Calendar#SECOND + */ + SECOND(Calendar.SECOND), + /** + * 毫秒 + * + * @see Calendar#MILLISECOND + */ + MILLISECOND(Calendar.MILLISECOND); + + private final int value; + + Various(final int value) { + this.value = value; + } + + /** + * 将 {@link Calendar}相关值转换为DatePart枚举对象 + * + * @param calendarPartIntValue Calendar中关于Week的int值 + * @return Type + */ + public static Various of(final int calendarPartIntValue) { + switch (calendarPartIntValue) { + case Calendar.ERA: + return ERA; + case Calendar.YEAR: + return YEAR; + case Calendar.MONTH: + return MONTH; + case Calendar.WEEK_OF_YEAR: + return WEEK_OF_YEAR; + case Calendar.WEEK_OF_MONTH: + return WEEK_OF_MONTH; + case Calendar.DAY_OF_MONTH: + return DAY_OF_MONTH; + case Calendar.DAY_OF_YEAR: + return DAY_OF_YEAR; + case Calendar.DAY_OF_WEEK: + return DAY_OF_WEEK; + case Calendar.DAY_OF_WEEK_IN_MONTH: + return DAY_OF_WEEK_IN_MONTH; + case Calendar.AM_PM: + return AM_PM; + case Calendar.HOUR: + return HOUR; + case Calendar.HOUR_OF_DAY: + return HOUR_OF_DAY; + case Calendar.MINUTE: + return MINUTE; + case Calendar.SECOND: + return SECOND; + case Calendar.MILLISECOND: + return MILLISECOND; + default: + return null; + } + } + + /** + * 获取{@link Calendar}中对应的值 + * + * @return {@link Calendar}中对应的值 + */ + public int getValue() { + return this.value; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Week.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Week.java new file mode 100644 index 0000000000..2d6594ff99 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/Week.java @@ -0,0 +1,269 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.en; + +import org.miaixz.bus.core.lang.Assert; +import org.miaixz.bus.core.xyz.EnumKit; + +import java.time.DayOfWeek; +import java.util.Calendar; + +/** + * 星期枚举 + * 与Calendar中的星期int值对应 + * + * @author Kimi Liu + * @see #SUNDAY + * @see #MONDAY + * @see #TUESDAY + * @see #WEDNESDAY + * @see #THURSDAY + * @see #FRIDAY + * @see #SATURDAY + * @since Java 17+ + */ +public enum Week { + + /** + * 周日 + */ + SUNDAY(Calendar.SUNDAY, "日"), + /** + * 周一 + */ + MONDAY(Calendar.MONDAY, "一"), + /** + * 周二 + */ + TUESDAY(Calendar.TUESDAY, "二"), + /** + * 周三 + */ + WEDNESDAY(Calendar.WEDNESDAY, "三"), + /** + * 周四 + */ + THURSDAY(Calendar.THURSDAY, "四"), + /** + * 周五 + */ + FRIDAY(Calendar.FRIDAY, "五"), + /** + * 周六 + */ + SATURDAY(Calendar.SATURDAY, "六"); + + private static final Week[] ENUMS = Week.values(); + + /** + * 星期对应{@link Calendar} 中的Week值 + */ + private final int code; + /** + * 星期对应名称 + */ + private final String name; + + /** + * 构造 + * + * @param code 星期对应{@link Calendar} 中的Week值 + */ + Week(final int code, final String name) { + this.code = code; + this.name = name; + } + + /** + * 将 {@link Calendar}星期相关值转换为Week枚举对象 + * + * @param code Calendar中关于Week的int值,1表示Sunday + * @return Week + * @see #SUNDAY + * @see #MONDAY + * @see #TUESDAY + * @see #WEDNESDAY + * @see #THURSDAY + * @see #FRIDAY + * @see #SATURDAY + */ + public static Week of(final int code) { + if (code > ENUMS.length || code < 1) { + return null; + } + return ENUMS[code - 1]; + } + + /** + * 解析别名为Week对象,别名如:sun或者SUNDAY,不区分大小写 + * + * @param name 别名值 + * @return 周枚举Week,非空 + * @throws IllegalArgumentException 如果别名无对应的枚举,抛出此异常 + */ + public static Week of(final String name) throws IllegalArgumentException { + if (null != name && name.length() > 1) { + switch (Character.toLowerCase(name.charAt(0))) { + case 'm': + return MONDAY; // monday + case 'w': + return WEDNESDAY; // wednesday + case 'f': + return FRIDAY; // friday + case 't': + switch (Character.toLowerCase(name.charAt(1))) { + case 'u': + return TUESDAY; // tuesday + case 'h': + return THURSDAY; // thursday + } + break; + case 's': + switch (Character.toLowerCase(name.charAt(1))) { + case 'a': + return SATURDAY; // saturday + case 'u': + return SUNDAY; // sunday + } + break; + } + } + + throw new IllegalArgumentException("Invalid Week name: " + name); + } + + /** + * 将 {@link DayOfWeek}星期相关值转换为Week枚举对象 + * + * @param dayOfWeek DayOfWeek星期值 + * @return Week + * @see #SUNDAY + * @see #MONDAY + * @see #TUESDAY + * @see #WEDNESDAY + * @see #THURSDAY + * @see #FRIDAY + * @see #SATURDAY + */ + public static Week of(final DayOfWeek dayOfWeek) { + Assert.notNull(dayOfWeek); + int week = dayOfWeek.getValue() + 1; + if (8 == week) { + // 周日 + week = 1; + } + return of(week); + } + + /** + * 转换为中文名 + * + * @param code Calendar中关于Week的int值,1表示Sunday + * @param prefix 表示星期的前缀,例如前缀为“星期”,则返回结果为“星期一”;前缀为”周“,结果为“周一” + * @return 星期的中文名 + */ + public static String getName(final int code, String prefix) { + return prefix + ENUMS[code].name; + } + + /** + * 获取枚举属性信息 + * + * @param fieldName 属性名称 + * @return the string[] + */ + public static String[] get(String fieldName) { + return EnumKit.getFieldValues(Week.class, fieldName).toArray(String[]::new); + } + + /** + * 获得星期对应{@link Calendar} 中的Week值 + * + * @return 星期对应 {@link Calendar} 中的Week值 + */ + public int getCode() { + return this.code; + } + + /** + * 获取ISO8601规范的int值,from 1 (Monday) to 7 (Sunday). + * + * @return ISO8601规范的int值 + */ + public int getIsoValue() { + int iso8601IntValue = getCode() - 1; + if (0 == iso8601IntValue) { + iso8601IntValue = 7; + } + return iso8601IntValue; + } + + /** + * 转换为中文名 + * + * @return 星期的中文名 + */ + public String getName() { + return this.name; + } + + /** + * 转换为中文名 + * + * @param prefix 表示星期的前缀,例如前缀为“星期”,则返回结果为“星期一”;前缀为”周“,结果为“周一” + * @return 星期的中文名 + */ + public String getName(final String prefix) { + switch (this) { + case SUNDAY: + return prefix + "日"; + case MONDAY: + return prefix + "一"; + case TUESDAY: + return prefix + "二"; + case WEDNESDAY: + return prefix + "三"; + case THURSDAY: + return prefix + "四"; + case FRIDAY: + return prefix + "五"; + case SATURDAY: + return prefix + "六"; + default: + return null; + } + } + + /** + * 转换为{@link DayOfWeek} + * + * @return {@link DayOfWeek} + */ + public DayOfWeek toJdkDayOfWeek() { + return DayOfWeek.of(getIsoValue()); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/package-info.java new file mode 100644 index 0000000000..49b0bbfee6 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/en/package-info.java @@ -0,0 +1,7 @@ +/** + * 西方文化相关 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.en; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarDay.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarDay.java new file mode 100755 index 0000000000..faa7a36613 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarDay.java @@ -0,0 +1,368 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.lunar; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.Direction; +import org.miaixz.bus.core.center.date.culture.cn.Duty; +import org.miaixz.bus.core.center.date.culture.cn.Phase; +import org.miaixz.bus.core.center.date.culture.cn.Week; +import org.miaixz.bus.core.center.date.culture.cn.fetus.FetusDay; +import org.miaixz.bus.core.center.date.culture.cn.sixty.EarthBranch; +import org.miaixz.bus.core.center.date.culture.cn.sixty.HeavenStem; +import org.miaixz.bus.core.center.date.culture.cn.sixty.SixtyCycle; +import org.miaixz.bus.core.center.date.culture.cn.star.nine.NineStar; +import org.miaixz.bus.core.center.date.culture.cn.star.twelve.TwelveStar; +import org.miaixz.bus.core.center.date.culture.cn.star.twentyeight.TwentyEightStar; +import org.miaixz.bus.core.center.date.culture.solar.SolarDay; +import org.miaixz.bus.core.center.date.culture.solar.SolarTerm; + +/** + * 农历日 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class LunarDay extends Loops { + + public static final String[] NAMES = { + "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十", + "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", + "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十" + }; + + /** + * 农历月 + */ + protected LunarMonth month; + + /** + * 日 + */ + protected int day; + + /** + * 初始化 + * + * @param year 农历年 + * @param month 农历月,闰月为负 + * @param day 农历日 + */ + public LunarDay(int year, int month, int day) { + LunarMonth m = LunarMonth.fromYm(year, month); + if (day < 1 || day > m.getDayCount()) { + throw new IllegalArgumentException(String.format("illegal day %d in %s", day, m)); + } + this.month = m; + this.day = day; + } + + /** + * 从农历年月日初始化 + * + * @param year 农历年 + * @param month 农历月,闰月为负 + * @param day 农历日 + */ + public static LunarDay fromYmd(int year, int month, int day) { + return new LunarDay(year, month, day); + } + + /** + * 农历月 + * + * @return 农历月 + */ + public LunarMonth getMonth() { + return month; + } + + /** + * 日 + * + * @return 日 + */ + public int getDay() { + return day; + } + + public String getName() { + return NAMES[day - 1]; + } + + @Override + public String toString() { + return month + getName(); + } + + public LunarDay next(int n) { + if (n == 0) { + return fromYmd(month.getYear().getYear(), month.getMonthWithLeap(), day); + } + int d = day + n; + LunarMonth lm = month; + int daysInMonth = lm.getDayCount(); + boolean forward = n > 0; + int add = forward ? 1 : -1; + while (forward ? (d > daysInMonth) : (d <= 0)) { + if (forward) { + d -= daysInMonth; + } + lm = lm.next(add); + daysInMonth = lm.getDayCount(); + if (!forward) { + d += daysInMonth; + } + } + return fromYmd(lm.getYear().getYear(), lm.getMonthWithLeap(), d); + } + + /** + * 是否在指定农历日之前 + * + * @param target 农历日 + * @return true/false + */ + public boolean isBefore(LunarDay target) { + int aYear = month.getYear().getYear(); + LunarMonth targetMonth = target.getMonth(); + int bYear = targetMonth.getYear().getYear(); + if (aYear == bYear) { + int aMonth = month.getMonth(); + int bMonth = targetMonth.getMonth(); + if (aMonth == bMonth) { + if (month.isLeap() && !targetMonth.isLeap()) { + return false; + } + return day < target.getDay(); + } + return aMonth < bMonth; + } + return aYear < bYear; + } + + /** + * 是否在指定农历日之后 + * + * @param target 农历日 + * @return true/false + */ + public boolean isAfter(LunarDay target) { + int aYear = month.getYear().getYear(); + LunarMonth targetMonth = target.getMonth(); + int bYear = targetMonth.getYear().getYear(); + if (aYear == bYear) { + int aMonth = month.getMonth(); + int bMonth = targetMonth.getMonth(); + if (aMonth == bMonth) { + if (month.isLeap() && !targetMonth.isLeap()) { + return true; + } + return day > target.getDay(); + } + return aMonth > bMonth; + } + return aYear > bYear; + } + + /** + * 星期 + * + * @return 星期 + */ + public Week getWeek() { + return getSolarDay().getJulianDay().getWeek(); + } + + /** + * 当天的年干支 + * + * @return 干支 + */ + public SixtyCycle getYearSixtyCycle() { + SolarDay solarDay = getSolarDay(); + int solarYear = solarDay.getMonth().getYear().getYear(); + SolarDay springSolarDay = SolarTerm.fromIndex(solarYear, 3).getJulianDay().getSolarDay(); + LunarYear lunarYear = month.getYear(); + int year = lunarYear.getYear(); + SixtyCycle sixtyCycle = lunarYear.getSixtyCycle(); + if (year == solarYear) { + if (solarDay.isBefore(springSolarDay)) { + sixtyCycle = sixtyCycle.next(-1); + } + } else if (year < solarYear) { + if (!solarDay.isBefore(springSolarDay)) { + sixtyCycle = sixtyCycle.next(1); + } + } + return sixtyCycle; + } + + /** + * 当天的月干支 + * + * @return 干支 + */ + public SixtyCycle getMonthSixtyCycle() { + SolarDay solarDay = getSolarDay(); + int year = solarDay.getMonth().getYear().getYear(); + SolarTerm term = solarDay.getTerm(); + int index = term.getIndex() - 3; + if (index < 0 && term.getJulianDay().getSolarDay().isAfter(SolarTerm.fromIndex(year, 3).getJulianDay().getSolarDay())) { + index += 24; + } + return LunarMonth.fromYm(year, 1).getSixtyCycle().next((int) Math.floor(index * 1D / 2)); + } + + /** + * 干支 + * + * @return 干支 + */ + public SixtyCycle getSixtyCycle() { + int offset = (int) month.getFirstJulianDay().next(day - 12).getDay(); + return SixtyCycle.fromName(HeavenStem.fromIndex(offset).getName() + EarthBranch.fromIndex(offset).getName()); + } + + /** + * 建除十二值神 + * + * @return 建除十二值神 + */ + public Duty getDuty() { + return Duty.fromIndex(getSixtyCycle().getEarthBranch().getIndex() - getMonthSixtyCycle().getEarthBranch().getIndex()); + } + + /** + * 黄道黑道十二神 + * + * @return 黄道黑道十二神 + */ + public TwelveStar getTwelveStar() { + return TwelveStar.fromIndex(getSixtyCycle().getEarthBranch().getIndex() + (8 - getMonthSixtyCycle().getEarthBranch().getIndex() % 6) * 2); + } + + /** + * 九星 + * + * @return 九星 + */ + public NineStar getNineStar() { + SolarDay solar = getSolarDay(); + SolarTerm dongZhi = SolarTerm.fromIndex(solar.getMonth().getYear().getYear(), 0); + SolarTerm xiaZhi = dongZhi.next(12); + SolarTerm dongZhi2 = dongZhi.next(24); + SolarDay dongZhiSolar = dongZhi.getJulianDay().getSolarDay(); + SolarDay xiaZhiSolar = xiaZhi.getJulianDay().getSolarDay(); + SolarDay dongZhiSolar2 = dongZhi2.getJulianDay().getSolarDay(); + int dongZhiIndex = dongZhiSolar.getLunarDay().getSixtyCycle().getIndex(); + int xiaZhiIndex = xiaZhiSolar.getLunarDay().getSixtyCycle().getIndex(); + int dongZhiIndex2 = dongZhiSolar2.getLunarDay().getSixtyCycle().getIndex(); + SolarDay solarShunBai = dongZhiSolar.next(dongZhiIndex > 29 ? 60 - dongZhiIndex : -dongZhiIndex); + SolarDay solarShunBai2 = dongZhiSolar2.next(dongZhiIndex2 > 29 ? 60 - dongZhiIndex2 : -dongZhiIndex2); + SolarDay solarNiZi = xiaZhiSolar.next(xiaZhiIndex > 29 ? 60 - xiaZhiIndex : -xiaZhiIndex); + int offset = 0; + if (!solar.isBefore(solarShunBai) && solar.isBefore(solarNiZi)) { + offset = solar.subtract(solarShunBai); + } else if (!solar.isBefore(solarNiZi) && solar.isBefore(solarShunBai2)) { + offset = 8 - solar.subtract(solarNiZi); + } else if (!solar.isBefore(solarShunBai2)) { + offset = solar.subtract(solarShunBai2); + } else if (solar.isBefore(solarShunBai)) { + offset = 8 + solarShunBai.subtract(solar); + } + return NineStar.fromIndex(offset); + } + + /** + * 太岁方位 + * + * @return 方位 + */ + public Direction getJupiterDirection() { + int index = getSixtyCycle().getIndex(); + if (index % 12 < 6) { + return Direction.fromIndex(new int[]{2, 8, 4, 6, 0}[index / 12]); + } + return month.getYear().getJupiterDirection(); + } + + /** + * 逐日胎神 + * + * @return 逐日胎神 + */ + public FetusDay getFetusDay() { + return FetusDay.fromLunarDay(this); + } + + /** + * 月相 + * + * @return 月相 + */ + public Phase getPhase() { + return Phase.fromIndex(day - 1); + } + + /** + * 公历日 + * + * @return 公历日 + */ + public SolarDay getSolarDay() { + return month.getFirstJulianDay().next(day - 1).getSolarDay(); + } + + /** + * 二十八宿 + * + * @return 二十八宿 + */ + public TwentyEightStar getTwentyEightStar() { + return TwentyEightStar.fromIndex(new int[]{10, 18, 26, 6, 14, 22, 2}[getSolarDay().getWeek().getIndex()]).next(-7 * getSixtyCycle().getEarthBranch().getIndex()); + } + + /** + * 农历传统节日,如果当天不是农历传统节日,返回null + * + * @return 农历传统节日 + */ + public LunarFestival getFestival() { + LunarMonth m = getMonth(); + return LunarFestival.fromYmd(m.getYear().getYear(), m.getMonthWithLeap(), day); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof LunarDay)) { + return false; + } + LunarDay target = (LunarDay) o; + return month.equals(target.getMonth()) && day == target.getDay(); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarFestival.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarFestival.java new file mode 100755 index 0000000000..d8a1c18b63 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarFestival.java @@ -0,0 +1,191 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.lunar; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.solar.SolarTerm; +import org.miaixz.bus.core.lang.EnumMap; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 农历传统节日(依据国家标准《农历的编算和颁行》GB/T 33661-2017) + * + * @author Kimi Liu + * @since Java 17+ + */ +public class LunarFestival extends Loops { + + public static final String[] NAMES = { + "春节", "元宵节", "龙头节", "上巳节", "清明节", "端午节", "七夕节", + "中元节", "中秋节", "重阳节", "冬至节", "腊八节", "除夕" + }; + + public static String DATA = "@0000101@0100115@0200202@0300303@04107@0500505@0600707@0700715@0800815@0900909@10124@1101208@122"; + + /** + * 类型 + */ + protected EnumMap.Festival type; + + /** + * 索引 + */ + protected int index; + + /** + * 农历日 + */ + protected LunarDay day; + + /** + * 节气 + */ + protected SolarTerm solarTerm; + + /** + * 名称 + */ + protected String name; + + public LunarFestival(EnumMap.Festival type, LunarDay day, SolarTerm solarTerm, String data) { + this.type = type; + this.day = day; + this.solarTerm = solarTerm; + index = Integer.parseInt(data.substring(1, 3), 10); + name = NAMES[index]; + } + + public static LunarFestival fromIndex(int year, int index) { + if (index < 0 || index >= NAMES.length) { + throw new IllegalArgumentException(String.format("illegal index: %d", index)); + } + Matcher matcher = Pattern.compile(String.format("@%02d\\d+", index)).matcher(DATA); + if (matcher.find()) { + String data = matcher.group(); + EnumMap.Festival type = EnumMap.Festival.fromCode(data.charAt(3) - '0'); + switch (type) { + case DAY: + return new LunarFestival(type, LunarDay.fromYmd(year, Integer.parseInt(data.substring(4, 6), 10), Integer.parseInt(data.substring(6), 10)), null, data); + case TERM: + SolarTerm solarTerm = SolarTerm.fromIndex(year, Integer.parseInt(data.substring(4), 10)); + return new LunarFestival(type, solarTerm.getJulianDay().getSolarDay().getLunarDay(), solarTerm, data); + case EVE: + return new LunarFestival(type, LunarDay.fromYmd(year + 1, 1, 1).next(-1), null, data); + default: + } + } + return null; + } + + public static LunarFestival fromYmd(int year, int month, int day) { + Matcher matcher = Pattern.compile(String.format("@\\d{2}0%02d%02d", month, day)).matcher(DATA); + if (matcher.find()) { + return new LunarFestival(EnumMap.Festival.DAY, LunarDay.fromYmd(year, month, day), null, matcher.group()); + } + matcher = Pattern.compile("@\\d{2}1\\d{2}").matcher(DATA); + while (matcher.find()) { + String data = matcher.group(); + SolarTerm solarTerm = SolarTerm.fromIndex(year, Integer.parseInt(data.substring(4), 10)); + LunarDay lunarDay = solarTerm.getJulianDay().getSolarDay().getLunarDay(); + LunarMonth lunarMonth = lunarDay.getMonth(); + if (lunarMonth.getYear().getYear() == year && lunarMonth.getMonth() == month && lunarDay.getDay() == day) { + return new LunarFestival(EnumMap.Festival.TERM, lunarDay, solarTerm, data); + } + } + matcher = Pattern.compile("@\\d{2}2").matcher(DATA); + if (matcher.find()) { + LunarDay lunarDay = LunarDay.fromYmd(year, month, day); + LunarDay nextDay = lunarDay.next(1); + if (nextDay.getMonth().getMonth() == 1 && nextDay.getDay() == 1) { + return new LunarFestival(EnumMap.Festival.EVE, lunarDay, null, matcher.group()); + } + } + return null; + } + + public LunarFestival next(int n) { + LunarMonth m = day.getMonth(); + int year = m.getYear().getYear(); + if (n == 0) { + return fromYmd(year, m.getMonthWithLeap(), day.getDay()); + } + int size = NAMES.length; + int t = index + n; + int offset = indexOf(t, size); + if (t < 0) { + t -= size; + } + return fromIndex(year + t / size, offset); + } + + /** + * 类型 + * + * @return 节日类型 + */ + public EnumMap.Festival getType() { + return type; + } + + /** + * 索引 + * + * @return 索引 + */ + public int getIndex() { + return index; + } + + /** + * 农历日 + * + * @return 农历日 + */ + public LunarDay getDay() { + return day; + } + + /** + * 节气,非节气返回null + * + * @return 节气 + */ + public SolarTerm getSolarTerm() { + return solarTerm; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return String.format("%s %s", day, name); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarHour.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarHour.java new file mode 100755 index 0000000000..6e2a2483ed --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarHour.java @@ -0,0 +1,315 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.lunar; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.birth.EightChar; +import org.miaixz.bus.core.center.date.culture.cn.sixty.EarthBranch; +import org.miaixz.bus.core.center.date.culture.cn.sixty.HeavenStem; +import org.miaixz.bus.core.center.date.culture.cn.sixty.SixtyCycle; +import org.miaixz.bus.core.center.date.culture.cn.star.nine.NineStar; +import org.miaixz.bus.core.center.date.culture.solar.SolarDay; +import org.miaixz.bus.core.center.date.culture.solar.SolarMonth; +import org.miaixz.bus.core.center.date.culture.solar.SolarTerm; +import org.miaixz.bus.core.center.date.culture.solar.SolarTime; + +/** + * 时辰 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class LunarHour extends Loops { + + /** + * 农历日 + */ + protected LunarDay day; + + /** + * 时 + */ + protected int hour; + + /** + * 分 + */ + protected int minute; + + /** + * 秒 + */ + protected int second; + + /** + * 初始化 + * + * @param year 农历年 + * @param month 农历月,闰月为负 + * @param day 农历日 + * @param hour 时 + * @param minute 分 + * @param second 秒 + */ + public LunarHour(int year, int month, int day, int hour, int minute, int second) { + if (hour < 0 || hour > 23) { + throw new IllegalArgumentException(String.format("illegal hour: %d", hour)); + } + if (minute < 0 || minute > 59) { + throw new IllegalArgumentException(String.format("illegal minute: %d", minute)); + } + if (second < 0 || second > 59) { + throw new IllegalArgumentException(String.format("illegal second: %d", second)); + } + this.day = LunarDay.fromYmd(year, month, day); + this.hour = hour; + this.minute = minute; + this.second = second; + } + + /** + * 从农历年月日时分秒初始化 + * + * @param year 农历年 + * @param month 农历月,闰月为负 + * @param day 农历日 + * @param hour 时 + * @param minute 分 + * @param second 秒 + */ + public static LunarHour fromYmdHms(int year, int month, int day, int hour, int minute, int second) { + return new LunarHour(year, month, day, hour, minute, second); + } + + /** + * 农历日 + * + * @return 农历日 + */ + public LunarDay getDay() { + return day; + } + + /** + * 时 + * + * @return 时 + */ + public int getHour() { + return hour; + } + + /** + * 分 + * + * @return 分 + */ + public int getMinute() { + return minute; + } + + /** + * 秒 + * + * @return 秒 + */ + public int getSecond() { + return second; + } + + public String getName() { + return EarthBranch.fromIndex(getIndexInDay()).getName() + "时"; + } + + @Override + public String toString() { + return day + getSixtyCycle().getName() + "时"; + } + + public int getIndexInDay() { + return (hour + 1) / 2; + } + + public LunarHour next(int n) { + int h = hour + n * 2; + int diff = h < 0 ? -1 : 1; + int hour = Math.abs(h); + int days = hour / 24 * diff; + hour = (hour % 24) * diff; + if (hour < 0) { + hour += 24; + days--; + } + LunarDay d = day.next(days); + LunarMonth month = d.getMonth(); + return fromYmdHms(month.getYear().getYear(), month.getMonthWithLeap(), d.getDay(), hour, minute, second); + } + + /** + * 是否在指定农历时辰之前 + * + * @param target 农历时辰 + * @return true/false + */ + public boolean isBefore(LunarHour target) { + if (!day.equals(target.getDay())) { + return day.isBefore(target.getDay()); + } + int bHour = target.getHour(); + if (hour == bHour) { + int bMinute = target.getMinute(); + return minute == bMinute ? second < target.getSecond() : minute < bMinute; + } + return hour < bHour; + } + + /** + * 是否在指定农历时辰之后 + * + * @param target 农历时辰 + * @return true/false + */ + public boolean isAfter(LunarHour target) { + if (!day.equals(target.getDay())) { + return day.isAfter(target.getDay()); + } + int bHour = target.getHour(); + if (hour == bHour) { + int bMinute = target.getMinute(); + return minute == bMinute ? second > target.getSecond() : minute > bMinute; + } + return hour > bHour; + } + + /** + * 当时的年干支 + * + * @return 干支 + */ + public SixtyCycle getYearSixtyCycle() { + SolarTime solarTime = getSolarTime(); + int solarYear = day.getSolarDay().getMonth().getYear().getYear(); + SolarTime springSolarTime = SolarTerm.fromIndex(solarYear, 3).getJulianDay().getSolarTime(); + LunarYear lunarYear = day.getMonth().getYear(); + int year = lunarYear.getYear(); + SixtyCycle sixtyCycle = lunarYear.getSixtyCycle(); + if (year == solarYear) { + if (solarTime.isBefore(springSolarTime)) { + sixtyCycle = sixtyCycle.next(-1); + } + } else if (year < solarYear) { + if (!solarTime.isBefore(springSolarTime)) { + sixtyCycle = sixtyCycle.next(1); + } + } + return sixtyCycle; + } + + /** + * 当时的月干支 + * + * @return 干支 + */ + public SixtyCycle getMonthSixtyCycle() { + SolarTime solarTime = getSolarTime(); + int year = solarTime.getDay().getMonth().getYear().getYear(); + SolarTerm term = solarTime.getTerm(); + int index = term.getIndex() - 3; + if (index < 0 && term.getJulianDay().getSolarTime().isAfter(SolarTerm.fromIndex(year, 3).getJulianDay().getSolarTime())) { + index += 24; + } + return LunarMonth.fromYm(year, 1).getSixtyCycle().next((int) Math.floor(index * 1D / 2)); + } + + /** + * 当时的日干支(23:00开始算做第二天) + * + * @return 干支 + */ + public SixtyCycle getDaySixtyCycle() { + SixtyCycle d = day.getSixtyCycle(); + return hour > 22 ? d.next(1) : d; + } + + /** + * 干支 + * + * @return 干支 + */ + public SixtyCycle getSixtyCycle() { + int earthBranchIndex = getIndexInDay() % 12; + int heavenStemIndex = getDaySixtyCycle().getHeavenStem().getIndex() % 5 * 2 + earthBranchIndex; + return SixtyCycle.fromName(HeavenStem.fromIndex(heavenStemIndex).getName() + EarthBranch.fromIndex(earthBranchIndex).getName()); + } + + /** + * 九星(时家紫白星歌诀:三元时白最为佳,冬至阳生顺莫差,孟日七宫仲一白,季日四绿发萌芽,每把时辰起甲子,本时星耀照光华,时星移入中宫去,顺飞八方逐细查。夏至阴生逆回首,孟归三碧季加六,仲在九宫时起甲,依然掌中逆轮跨。) + * + * @return 九星 + */ + public NineStar getNineStar() { + SolarDay solar = day.getSolarDay(); + SolarTerm dongZhi = SolarTerm.fromIndex(solar.getMonth().getYear().getYear(), 0); + SolarTerm xiaZhi = dongZhi.next(12); + boolean asc = !solar.isBefore(dongZhi.getJulianDay().getSolarDay()) && solar.isBefore(xiaZhi.getJulianDay().getSolarDay()); + int start = new int[]{8, 5, 2}[day.getSixtyCycle().getEarthBranch().getIndex() % 3]; + if (asc) { + start = 8 - start; + } + int earthBranchIndex = getIndexInDay() % 12; + return NineStar.fromIndex(start + (asc ? earthBranchIndex : -earthBranchIndex)); + } + + /** + * 公历时刻 + * + * @return 公历时刻 + */ + public SolarTime getSolarTime() { + SolarDay d = day.getSolarDay(); + SolarMonth m = d.getMonth(); + return SolarTime.fromYmdHms(m.getYear().getYear(), m.getMonth(), d.getDay(), hour, minute, second); + } + + /** + * 八字 + * + * @return 八字 + */ + public EightChar getEightChar() { + return new EightChar(getYearSixtyCycle(), getMonthSixtyCycle(), getDaySixtyCycle(), getSixtyCycle()); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof LunarHour)) { + return false; + } + LunarHour target = (LunarHour) o; + return day.equals(target.getDay()) && hour == target.getHour() && minute == target.getMinute() && second == target.getSecond(); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarMonth.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarMonth.java new file mode 100755 index 0000000000..dc909a6d57 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarMonth.java @@ -0,0 +1,357 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.lunar; + +import org.miaixz.bus.core.center.date.culture.Galaxy; +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.Direction; +import org.miaixz.bus.core.center.date.culture.cn.JulianDay; +import org.miaixz.bus.core.center.date.culture.cn.fetus.FetusMonth; +import org.miaixz.bus.core.center.date.culture.cn.sixty.EarthBranch; +import org.miaixz.bus.core.center.date.culture.cn.sixty.HeavenStem; +import org.miaixz.bus.core.center.date.culture.cn.sixty.SixtyCycle; +import org.miaixz.bus.core.center.date.culture.cn.star.nine.NineStar; +import org.miaixz.bus.core.center.date.culture.solar.SolarTerm; + +import java.util.ArrayList; +import java.util.List; + +/** + * 农历月 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class LunarMonth extends Loops { + + public static final String[] NAMES = { + "正月", "二月", "三月", "四月", "五月", "六月", + "七月", "八月", "九月", "十月", "十一月", "腊月" + }; + + /** + * 农历年 + */ + protected LunarYear year; + + /** + * 月 + */ + protected int month; + + /** + * 是否闰月 + */ + protected boolean leap; + + /** + * 天数 + */ + protected int dayCount; + + /** + * 位于当年的索引,0-12 + */ + protected int indexInYear; + + /** + * 初一的儒略日 + */ + protected JulianDay firstJulianDay; + + public LunarMonth(int year, int month) { + LunarYear currentYear = LunarYear.fromYear(year); + int currentLeapMonth = currentYear.getLeapMonth(); + if (month == 0 || month > 12 || month < -12) { + throw new IllegalArgumentException(String.format("illegal lunar month: %d", month)); + } + boolean leap = month < 0; + int m = Math.abs(month); + if (leap && m != currentLeapMonth) { + throw new IllegalArgumentException(String.format("illegal leap month %d in lunar year %d", m, year)); + } + + // 冬至 + SolarTerm dongZhi = SolarTerm.fromIndex(year, 0); + double dongZhiJd = dongZhi.getCursoryJulianDay(); + + // 冬至前的初一,今年首朔的日月黄经差 + double w = Galaxy.calcShuo(dongZhiJd); + if (w > dongZhiJd) { + w -= 29.53; + } + + // 计算正月初一的偏移 + LunarYear prevYear = LunarYear.fromYear(year - 1); + int prevLeapMonth = prevYear.getLeapMonth(); + + // 正常情况正月初一为第3个朔日,但有些特殊的 + int offset = 2; + if (year > 8 && year < 24) { + offset = 1; + } else if (prevLeapMonth > 10 && year != 239 && year != 240) { + offset = 3; + } + + // 位于当年的索引 + int index = m - 1; + if (leap || (currentLeapMonth > 0 && m > currentLeapMonth)) { + index += 1; + } + indexInYear = index; + + // 本月初一 + w += 29.5306 * (offset + index); + double firstDay = Galaxy.calcShuo(w); + firstJulianDay = JulianDay.fromJulianDay(JulianDay.J2000 + firstDay); + // 本月天数 = 下月初一 - 本月初一 + dayCount = (int) (Galaxy.calcShuo(w + 29.5306) - firstDay); + this.year = currentYear; + this.month = m; + this.leap = leap; + } + + /** + * 从农历年月初始化 + * + * @param year 农历年 + * @param month 农历月,闰月为负 + * @return 农历月 + */ + public static LunarMonth fromYm(int year, int month) { + return new LunarMonth(year, month); + } + + /** + * 农历年 + * + * @return 农历年 + */ + public LunarYear getYear() { + return year; + } + + /** + * 月 + * + * @return 月 + */ + public int getMonth() { + return month; + } + + /** + * 月 + * + * @return 月,当月为闰月时,返回负数 + */ + public int getMonthWithLeap() { + return leap ? -month : month; + } + + /** + * 天数(大月30天,小月29天) + * + * @return 天数 + */ + public int getDayCount() { + return dayCount; + } + + /** + * 位于当年的索引(0-12) + * + * @return 索引 + */ + public int getIndexInYear() { + return indexInYear; + } + + /** + * 农历季节 + * + * @return 农历季节 + */ + public LunarSeason getSeason() { + return LunarSeason.fromIndex(month - 1); + } + + /** + * 初一的儒略日 + * + * @return 儒略日 + */ + public JulianDay getFirstJulianDay() { + return firstJulianDay; + } + + /** + * 是否闰月 + * + * @return true/false + */ + public boolean isLeap() { + return leap; + } + + /** + * 周数 + * + * @param start 起始星期,1234560分别代表星期一至星期天 + * @return 周数 + */ + public int getWeekCount(int start) { + return (int) Math.ceil((indexOf(firstJulianDay.getWeek().getIndex() - start, 7) + getDayCount()) / 7D); + } + + /** + * 依据国家标准《农历的编算和颁行》GB/T 33661-2017中农历月的命名方法。 + * + * @return 名称 + */ + public String getName() { + return (leap ? "闰" : "") + NAMES[month - 1]; + } + + @Override + public String toString() { + return year + getName(); + } + + public LunarMonth next(int n) { + if (n == 0) { + return fromYm(year.getYear(), getMonthWithLeap()); + } + int m = indexInYear + 1 + n; + LunarYear y = year; + int leapMonth = y.getLeapMonth(); + int monthSize = 12 + (leapMonth > 0 ? 1 : 0); + boolean forward = n > 0; + int add = forward ? 1 : -1; + while (forward ? (m > monthSize) : (m <= 0)) { + if (forward) { + m -= monthSize; + } + y = y.next(add); + leapMonth = y.getLeapMonth(); + monthSize = 12 + (leapMonth > 0 ? 1 : 0); + if (!forward) { + m += monthSize; + } + } + boolean leap = false; + if (leapMonth > 0) { + if (m == leapMonth + 1) { + leap = true; + } + if (m > leapMonth) { + m--; + } + } + return fromYm(y.getYear(), leap ? -m : m); + } + + /** + * 获取本月的农历日列表 + * + * @return 农历日列表 + */ + public List getDays() { + int size = getDayCount(); + int y = year.getYear(); + int m = getMonthWithLeap(); + List l = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + l.add(LunarDay.fromYmd(y, m, i + 1)); + } + return l; + } + + /** + * 获取本月的农历周列表 + * + * @param start 星期几作为一周的开始,1234560分别代表星期一至星期天 + * @return 周列表 + */ + public List getWeeks(int start) { + int size = getWeekCount(start); + int y = year.getYear(); + int m = getMonthWithLeap(); + List l = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + l.add(LunarWeek.fromYm(y, m, i, start)); + } + return l; + } + + /** + * 干支 + * + * @return 干支 + */ + public SixtyCycle getSixtyCycle() { + return SixtyCycle.fromName(HeavenStem.fromIndex((year.getSixtyCycle().getHeavenStem().getIndex() + 1) * 2 + indexInYear).getName() + EarthBranch.fromIndex(indexInYear + 2).getName()); + } + + /** + * 九星 + * + * @return 九星 + */ + public NineStar getNineStar() { + return NineStar.fromIndex(27 - year.getSixtyCycle().getEarthBranch().getIndex() % 3 * 3 - getSixtyCycle().getEarthBranch().getIndex()); + } + + /** + * 太岁方位 + * + * @return 方位 + */ + public Direction getJupiterDirection() { + SixtyCycle sixtyCycle = getSixtyCycle(); + int n = new int[]{7, -1, 1, 3}[sixtyCycle.getEarthBranch().next(-2).getIndex() % 4]; + return n == -1 ? sixtyCycle.getHeavenStem().getDirection() : Direction.fromIndex(n); + } + + /** + * 逐月胎神 + * + * @return 逐月胎神 + */ + public FetusMonth getFetus() { + return FetusMonth.fromLunarMonth(this); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof LunarMonth)) { + return false; + } + LunarMonth target = (LunarMonth) o; + return year.equals(target.getYear()) && getMonthWithLeap() == target.getMonthWithLeap(); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarSeason.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarSeason.java new file mode 100755 index 0000000000..95b2c19965 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarSeason.java @@ -0,0 +1,63 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.lunar; + +import org.miaixz.bus.core.center.date.culture.Samsara; + +/** + * 农历季节 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class LunarSeason extends Samsara { + + public static final String[] NAMES = { + "孟春", "仲春", "季春", "孟夏", "仲夏", "季夏", + "孟秋", "仲秋", "季秋", "孟冬", "仲冬", "季冬" + }; + + public LunarSeason(int index) { + super(NAMES, index); + } + + public LunarSeason(String name) { + super(NAMES, name); + } + + public static LunarSeason fromIndex(int index) { + return new LunarSeason(index); + } + + public static LunarSeason fromName(String name) { + return new LunarSeason(name); + } + + public LunarSeason next(int n) { + return fromIndex(nextIndex(n)); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarWeek.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarWeek.java new file mode 100755 index 0000000000..99dab24ea9 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarWeek.java @@ -0,0 +1,180 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.lunar; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.Week; + +import java.util.ArrayList; +import java.util.List; + +/** + * 农历周 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class LunarWeek extends Loops { + + /** + * 月 + */ + protected LunarMonth month; + + /** + * 索引,0-5 + */ + protected int index; + + /** + * 起始星期 + */ + protected Week start; + + /** + * 初始化 + * + * @param year 年 + * @param month 月 + * @param index 索引,0-5 + * @param start 起始星期,1234560分别代表星期一至星期天 + */ + public LunarWeek(int year, int month, int index, int start) { + if (index < 0 || index > 5) { + throw new IllegalArgumentException(String.format("illegal lunar week index: %d", index)); + } + if (start < 0 || start > 6) { + throw new IllegalArgumentException(String.format("illegal lunar week start: %d", start)); + } + LunarMonth m = LunarMonth.fromYm(year, month); + if (index >= m.getWeekCount(start)) { + throw new IllegalArgumentException(String.format("illegal lunar week index: %d in month: %s", index, m)); + } + this.month = m; + this.index = index; + this.start = Week.fromIndex(start); + } + + public static LunarWeek fromYm(int year, int month, int index, int start) { + return new LunarWeek(year, month, index, start); + } + + /** + * 月 + * + * @return 月 + */ + public LunarMonth getMonth() { + return month; + } + + /** + * 索引 + * + * @return 索引,0-5 + */ + public int getIndex() { + return index; + } + + /** + * 起始星期 + * + * @return 星期 + */ + public Week getStart() { + return start; + } + + public String getName() { + return Week.WHICH[index]; + } + + @Override + public String toString() { + return month + getName(); + } + + public LunarWeek next(int n) { + int startIndex = start.getIndex(); + if (n == 0) { + return fromYm(month.getYear().getYear(), month.getMonthWithLeap(), index, startIndex); + } + int d = index + n; + LunarMonth m = month; + int weeksInMonth = m.getWeekCount(startIndex); + boolean forward = n > 0; + int add = forward ? 1 : -1; + while (forward ? (d >= weeksInMonth) : (d < 0)) { + if (forward) { + d -= weeksInMonth; + } + if (!forward) { + if (!LunarDay.fromYmd(m.getYear().getYear(), m.getMonthWithLeap(), 1).getWeek().equals(start)) { + d += add; + } + } + m = m.next(add); + if (forward) { + if (!LunarDay.fromYmd(m.getYear().getYear(), m.getMonthWithLeap(), 1).getWeek().equals(start)) { + d += add; + } + } + weeksInMonth = m.getWeekCount(startIndex); + if (!forward) { + d += weeksInMonth; + } + } + return fromYm(m.getYear().getYear(), m.getMonthWithLeap(), d, startIndex); + } + + /** + * 本周第1天 + * + * @return 农历日 + */ + public LunarDay getFirstDay() { + LunarMonth m = getMonth(); + LunarDay firstDay = LunarDay.fromYmd(m.getYear().getYear(), m.getMonthWithLeap(), 1); + return firstDay.next(index * 7 - indexOf(firstDay.getWeek().getIndex() - start.getIndex(), 7)); + } + + /** + * 本周农历日列表 + * + * @return 农历日列表 + */ + public List getDays() { + List l = new ArrayList<>(7); + LunarDay d = getFirstDay(); + l.add(d); + for (int i = 1; i < 7; i++) { + l.add(d.next(i)); + } + return l; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarYear.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarYear.java new file mode 100755 index 0000000000..c9b16a67fb --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/LunarYear.java @@ -0,0 +1,206 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.lunar; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.Direction; +import org.miaixz.bus.core.center.date.culture.cn.Twenty; +import org.miaixz.bus.core.center.date.culture.cn.sixty.SixtyCycle; +import org.miaixz.bus.core.center.date.culture.cn.star.nine.NineStar; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 农历年 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class LunarYear extends Loops { + + /** + * 缓存{闰月:年} + */ + protected static final Map> LEAP = new HashMap<>(12); + + static { + String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_@"; + String[] months = "080b0r0j0j0j0C0j0j0C0j0j0j0C0j0C0j0C0F0j0V0V0V0u0j0j0C0j0j0j0j0V0C0j1v0u0C0V1v0C0b080u110u0C0j0C1v9K1v2z0j1vmZbl1veN3s1v0V0C2S1v0V0C2S2o0C0j1Z1c2S1v0j1c0j2z1v0j1c0j392H0b2_2S0C0V0j1c0j2z0C0C0j0j1c0j0N250j0C0j0b081n080b0C0C0C1c0j0N,0r1v1c1v0V0V0F0V0j0C0j0C0j0V0j0u1O0j0C0V0j0j0j0V0b080u0r0u080b0j0j0C0V0C0V0j0b080V0u080b0j0j0u0j1v0u080b1c0j080b0j0V0j0j0V0C0N1v0j1c0j0j1v2g1v420j1c0j2z1v0j1v5Q9z1v4l0j1vfn1v420j9z4l1v1v2S1c0j1v2S3s1v0V0C2S1v1v2S1c0j1v2S2_0b0j2_2z0j1c0j,0z0j0j0j0C0j0j0C0j0j0j0C0j0C0j0j0j0j0m0j0C0j0j0C0j0j0j0j0b0V0j0j0C0j0j0j0j0V0j0j0j0V0b0V0V0C0V0C0j0j0b080u110u0V0C0j0N0j0b080b080b0j0r0b0r0b0j0j0j0j0C0j0b0r0C0j0b0j0C0C0j0j0j0j0j0j0j0j0j0b110j0b0j0j0j0C0j0C0j0j0j0j0b080b080b0V080b080b0j0j0j0j0j0j0V0j0j0u1v0j0j0j0C0j0j0j0V0C0N1c0j0C0C0j0j0j1n080b0j0V0C0j0C0C2g0j1c0j0j1v2g1v0j0j1v7N0j1c0j3L0j0j1v5Q1Z5Q1v4lfn1v420j1v5Q1Z5Q1v4l1v2z1v,0H140r0N0r140r0u0r0V171c11140C0j0u110j0u0j1v0j0C0j0j0j0b080V0u080b0C1v0j0j0j0C0j0b080V0j0j0b080b0j0j0j0j0b080b0C080j0b080b0j0j0j0j0j0j0b080j0b080C0b080b080b080b0j0j0j0j080b0j0C0j0j0j0b0j0j080C0b0j0j0j0j0j0j0b08080b0j0C0j0j0j0b0j0j0K0b0j0C0j0j0j0b080b080j0C0b0j080b080b0j0j0j0j080b0j0b0r0j0j0j0b0j0C0r0b0j0j0j0j0j0j0j0b080j0b0r0C0j0b0j0j0j0r0b0j0C0j0j0j0u0r0b0C0j080b0j0j0j0j0j0j0j1c0j0b0j0j0j0C0j0j0j0j0j0j0j0b080j1c0u0j0j0j0C0j1c0j0u0j1c0j0j0j0j0j0j0j0j1c0j0u1v0j0j0V0j0j2g0j0j0j0C1v0C1G0j0j0V0C1Z1O0j0V0j0j2g1v0j0j0V0C2g5x1v4l1v421O7N0V0C4l1v2S1c0j1v2S2_,050b080C0j0j0j0C0j0j0C0j0j0j0C0j0C0j0C030j0j0j0j0j0j0j0j0j0C0j0b080u0V080b0j0j0V0j0j0j0j0j0j0j0j0j0V0N0j0C0C0j0j0j0j0j0j0j0j1c0j0u0j1v0j0j0j0j0j0b080b080j0j0j0b080b080b080b080b0j0j0j080b0j0b080j0j0j0j0b080b0j0j0r0b080b0b080j0j0j0j0b080b080j0b080j0b080b080b080b080b0j0j0r0b0j0b080j0j0j0j0b080b0j0j0C080b0b080j0j0j0j0j0j0j0b080u080j0j0b0j0j0j0C0j0b080j0j0j0j0b080b080b080b0C080b080b080b0j0j0j0j0j0j0b0C080j0j0b0j0j0j0C0j0b080j0j0C0b080b080j0b0j0j0C080b0j0j0j0j0j0j0b0j0j080C0b0j080b0j0j0j0j0j0j0j0C0j0j0j0b0j0j0C080b0j0j0j0j0j0j0b080b080b0K0b080b080b0j0j0j0j0j0j0j0C0j0j0u0j0j0V0j080b0j0C0j0j0j0b0j0r0C0b0j0j0j0j0j0j0j0j0j0C0j0b080b080b0j0C0C0j0C0j0j0j0u110u0j0j0j0j0j0j0j0j0C0j0j0u0j1c0j0j0j0j0j0j0j0j0V0C0u0j0C0C0V0C1Z0j0j0j0C0j0j0j1v0u0j1c0j0j0j0C0j0j2g0j1c1v0C1Z0V0j4l0j0V0j0j2g0j1v0j1v2S1c7N1v,0w0j1c0j0V0j0j0V0V0V0j0m0V0j0C1c140j0j0j0C0V0C0j1v0j0N0j0C0j0j0j0V0j0j1v0N0j0j0V0j0j0j0j0j0j080b0j0j0j0j0j0j0j080b0j0C0j0j0j0b0j0j080u080b0j0j0j0j0j0j0b080b080b080C0b0j080b080b0j0j0j0j080b0j0C0j0j0j0b0j0j080u080b0j0j0j0j0j0j0b080b080b080b0r0b0j080b080b0j0j0j0j080b0j0b0r0j0j0b080b0j0j080b0j080b0j080b080b0j0j0j0j0j0b080b0r0C0b080b0j0j0j0j080b0b080b080j0j0j0b080b080b080b0j0j0j0j080b0j0b080j0j0j0j0b080b0j0j0r0b080b0j0j0j0j0j0b080b080j0b0r0b080j0b080b0j0j0j0j080b0j0b080j0j0j0j0b080b0j080b0r0b0j080b080b0j0j0j0j0j0b080b0r0C0b080b0j0j0j0j0j0j0b080j0j0j0b080b080b080b0j0j0j0r0b0j0b080j0j0j0j0b080b0r0b0r0b0j080b080b0j0j0j0j0j0j0b0r0j0j0j0b0j0j0j0j080b0j0b080j0j0j0j0b080b080b0j0r0b0j080b0j0j0j0j0j0j0j0b0r0C0b0j0j0j0j0j0j0j080b0j0C0j0j0j0b0j0C0r0b0j0j0j0j0j0j0b080b080u0r0b0j080b0j0j0j0j0j0j0j0b0r0C0u0j0j0j0C0j080b0j0C0j0j0j0u110b0j0j0j0j0j0j0j0j0j0C0j0b080b0j0j0C0C0j0C0j0j0j0b0j1c0j080b0j0j0j0j0j0j0V0j0j0u0j1c0j0j0j0C0j0j2g0j0j0j0C0j0j0V0j0b080b1c0C0V0j0j2g0j0j0V0j0j1c0j1Z0j0j0C0C0j1v,160j0j0V0j1c0j0C0j0C0j1f0j0V0C0j0j0C0j0j0j1G080b080u0V080b0j0j0V0j1v0j0u0j1c0j0j0j0C0j0j0j0C0C0j1D0b0j080b0j0j0j0j0C0j0b0r0C0j0b0j0C0C0j0j0j0j0j0j0j0j0j0b0r0b0r0j0b0j0j0j0C0j0b0r0j0j0j0b080b080j0b0C0j080b080b0j0j0j0j0j0j0b0C080j0j0b0j0j0j0C0j0b080j0j0j0j0b080b080j0b0C0r0j0b0j0j0j0j0j0j0b0C080j0j0b0j0j0j0C0j0j0j0j0C0j0j0b080b0j0j0C080b0j0j0j0j0j0j0b080b080b080C0b080b080b080b0j0j0j0j0j0b080C0j0j0b080b0j0j0C080b0j0j0j0j0j0j0b080j0b0C080j0j0b0j0j0j0j0j0j0b080j0b080C0b080b080b080b0j0j0j0j080b0j0C0j0j0b080b0j0j0C080b0j0j0j0j0j0j0b080j0b080u080j0j0b0j0j0j0j0j0j0b080C0j0j0b080b0j0j0C0j0j080b0j0j0j0j0j0b080b0C0r0b080b0j0j0j0j0j0j0b080j0b080u080b080b080b0j0j0j0C0j0b080j0j0j0j0b0j0j0j0C0j0j080b0j0j0j0j0j0b080b0C0r0b080b0j0j0j0j0j0j0b080j0b0r0b080b080b080b0j0j0j0r0b0j0b0r0j0j0j0b0j0j0j0r0b0j080b0j0j0j0j0j0j0j0b0r0C0b0j0j0j0j0j0j0j0b080j0C0u080b080b0j0j0j0r0b0j0C0C0j0b0j110b0j080b0j0j0j0j0j0j0u0r0C0b0j0j0j0j0j0j0j0j0j0C0j0j0j0b0j1c0j0C0j0j0j0b0j0814080b080b0j0j0j0j0j0j1c0j0u0j0j0V0j0j0j0j0j0j0j0u110u0j0j0j,020b0r0C0j0j0j0C0j0j0V0j0j0j0j0j0C0j1f0j0C0j0V1G0j0j0j0j0V0C0j0C1v0u0j0j0j0V0j0j0C0j0j0j1v0N0C0V0j0j0j0K0C250b0C0V0j0j0V0j0j2g0C0V0j0j0C0j0j0b081v0N0j0j0V0V0j0j0u0j1c0j080b0j0j0j0j0j0j0V0j0j0u0j0j0V0j0j0j0C0j0b080b080V0b0j080b0j0j0j0j0j0j0j0b0r0C0j0b0j0j0j0C0j080b0j0j0j0j0j0j0u0r0C0u0j0j0j0j0j0j0b080j0C0j0b080b080b0j0C0j080b0j0j0j0j0j0j0b080b110b0j0j0j0j0j0j0j0j0j0b0r0j0j0j0b0j0j0j0r0b0j0b080j0j0j0j0b080b080b080b0r0b0j080b080b0j0j0j0j0j0j0b0r0C0b080b0j0j0j0j080b0j0b080j0j0j0j0b080b080b0j0j0j0r0b0j0j0j0j0j0j0b080b0j080C0b0j080b080b0j0j0j0j080b0j0b0r0C0b080b0j0j0j0j080b0j0j0j0j0j0b080b080b080b0j0j080b0r0b0j0j0j0j0j0j0b0j0j080C0b0j080b080b0j0j0j0j0j0b080C0j0j0b080b0j0j0C0j0b080j0j0j0j0b080b080b080b0C0C080b0j0j0j0j0j0j0b0C0C080b080b080b0j0j0j0j0j0j0b0C080j0j0b0j0j0j0C0j0b080j0b080j0j0b080b080b080b0C0r0b0j0j0j0j0j0j0b080b0r0b0r0b0j080b080b0j0j0j0j0j0j0b0r0C0j0b0j0j0j0j0j0j0b080j0C0j0b080j0b0j0j0K0b0j0C0j0j0j0b080b0j0K0b0j080b0j0j0j0j0j0j0V0j0j0b0j0j0j0C0j0j0j0j,0l0C0K0N0r0N0j0r1G0V0m0j0V1c0C0j0j0j0j1O0N110u0j0j0j0C0j0j0V0C0j0u110u0j0j0j0C0j0j0j0C0C0j250j1c2S1v1v0j5x2g0j1c0j0j1c2z0j1c0j0j1c0j0N1v0V0C1v0C0b0C0V0j0j0C0j0C1v0u0j0C0C0j0j0j0C0j0j0j0u110u0j0j0j0C0j0C0C0C0b080b0j0C0j080b0j0C0j0j0j0u110u0j0j0j0C0j0j0j0C0j0j0j0u0C0r0u0j0j0j0j0j0j0b0r0b0V080b080b0j0C0j0j0j0V0j0j0b0j0j0j0C0j0j0j0j0j0j0j0b080j0b0C0r0j0b0j0j0j0C0j0b0r0b0r0j0b080b080b0j0C0j0j0j0j0j0j0j0j0b0j0C0r0b0j0j0j0j0j0j0b080b080j0b0r0b0r0j0b0j0j0j0j080b0j0b0r0j0j0j0b080b080b0j0j0j0j080b0j0j0j0j0j0j0b0j0j0j0r0b0j0j0j0j0j0j0b080b080b080b0r0C0b080b0j0j0j0j0j0b080b0r0C0b080b080b080b0j0j0j0j080b0j0C0j0j0j0b0j0j0C080b0j0j0j0j0j0j0b080j0b0C080j0j0b0j0j0j0j0j0j0b0r0b080j0j0b080b080b0j0j0j0j0j0j0b080j0j0j0j0b0j0j0j0r0b0j0b080j0j0j0j0j0b080b080b0C0r0b0j0j0j0j0j0j0b080b080j0C0b0j080b080b0j0j0j0j0j0j,0a0j0j0j0j0C0j0j0C0j0C0C0j0j0j0j0j0j0j0m0C0j0j0j0j0u080j0j0j1n0j0j0j0j0C0j0j0j0V0j0j0j1c0u0j0C0V0j0j0V0j0j1v0N0C0V2o1v1O2S2o141v0j1v4l0j1c0j1v2S2o0C0u1v0j0C0C2S1v0j1c0j0j1v0N251c0j1v0b1c1v1n1v0j0j0V0j0j1v0N1v0C0V0j0j1v0b0C0j0j0V1c0j0u0j1c0j0j0j0j0j0j0j0j1c0j0u0j0j0V0j0j0j0j0j0j0b080u110u0j0j0j0j0j0j1c0j0b0j080b0j0C0j0j0j0V0j0j0u0C0V0j0j0j0C0j0b080j1c0j0b0j0j0j0C0j0C0j0j0j0b080b080b0j0C0j080b0j0j0j0j0j0j0j0b0C0r0u0j0j0j0j0j0j0b080j0b0r0C0j0b0j0j0j0r0b0j0b0r0j0j0j0b080b080b0j0r0b0j080b0j0j0j0j0j0j0b0j0r0C0b0j0j0j0j0j0j0b080j0j0C0j0j0b080b0j0j0j0j0j0j0j0j0j0j0b080b080b080b0C0j0j080b0j0j0j0j0j0j0b0j0j0C080b0j0j0j0j0j0j0j0j0b0C080j0j0b0j0j0j0j0j,0n0Q0j1c14010q0V1c171k0u0r140V0j0j1c0C0N1O0j0V0j0j0j1c0j0u110u0C0j0C0V0C0j0j0b671v0j1v5Q1O2S2o2S1v4l1v0j1v2S2o0C1Z0j0C0C1O141v0j1c0j2z1O0j0V0j0j1v0b2H390j1c0j0V0C2z0j1c0j1v2g0C0V0j1O0b0j0j0V0C1c0j0u0j1c0j0j0j0j0j0j0j0j1c0N0j0j0V0j0j0C0j0j0b081v0u0j0j0j0C0j1c0N0j0j0C0j0j0j0C0j0j0j0u0C0r0u0j0j0j0C0j0b080j1c0j0b0j0C0C0j0C0C0j0b080b080u0C0j080b0j0C0j0j0j0u110u0j0j0j0j0j0j0j0j0C0C0j0b0j0j0j0C0j0C0C0j0b080b080b0j0C0j080b0j0C0j0j0j0b0j110b0j0j0j0j0j,0B0j0V0j0j0C0j0j0j0C0j0C0j0j0C0j0m0j0j0j0j0C0j0C0j0j0u0j1c0j0j0C0C0j0j0j0j0j0j0j0j0u110N0j0j0V0C0V0j0b081n080b0CrU1O5e2SbX2_1Z0V2o141v0j0C0C0j2z1v0j1c0j7N1O420j1c0j1v2S1c0j1v2S2_0b0j0V0j0j1v0N1v0j0j1c0j1v140j0V0j0j0C0C0b080u1v0C0V0u110u0j0j0j0C0j0j0j0C0C0N0C0V0j0j0C0j0j0b080u110u0C0j0C0u0r0C0u080b0j0j0C0j0j0j".split(",", -1); + for (int i = 0; i < 12; i++) { + int n = 0; + String m = months[i]; + int size = m.length() / 2; + List l = new ArrayList<>(size); + for (int y = 0; y < size; y++) { + int z = y * 2; + String s = m.substring(z, z + 2); + int t = 0; + int c = 1; + for (int x = 1; x > -1; x--) { + t += c * chars.indexOf(s.charAt(x)); + c *= 64; + } + n += t; + l.add(n); + } + LEAP.put(i + 1, l); + } + } + + /** + * 年 + */ + protected int year; + + public LunarYear(int year) { + if (year < -1 || year > 9999) { + throw new IllegalArgumentException(String.format("illegal lunar year: %d", year)); + } + this.year = year; + } + + /** + * 从年初始化 + * + * @param year 年,支持-1到9999年 + * @return 农历年 + */ + public static LunarYear fromYear(int year) { + return new LunarYear(year); + } + + /** + * 年 + * + * @return 年 + */ + public int getYear() { + return year; + } + + /** + * 天数 + * + * @return 天数 + */ + public int getDayCount() { + int n = 0; + for (LunarMonth m : getMonths()) { + n += m.getDayCount(); + } + return n; + } + + /** + * 依据国家标准《农历的编算和颁行》GB/T 33661-2017,农历年有2种命名方法:干支纪年法和生肖纪年法,这里默认采用干支纪年法。 + * + * @return 名称 + */ + public String getName() { + return String.format("农历%s年", getSixtyCycle()); + } + + public LunarYear next(int n) { + return fromYear(year + n); + } + + /** + * 闰月 + * + * @return 闰月数字,1代表闰1月,0代表无闰月 + */ + public int getLeapMonth() { + if (year == -1) { + return 11; + } + for (Map.Entry> entry : LEAP.entrySet()) { + if (entry.getValue().contains(year)) { + return entry.getKey(); + } + } + return 0; + } + + /** + * 干支 + * + * @return 干支 + */ + public SixtyCycle getSixtyCycle() { + return SixtyCycle.fromIndex(year - 4); + } + + /** + * 运 + * + * @return 运 + */ + public Twenty getTwenty() { + return Twenty.fromIndex((int) Math.floor((year - 1864) / 20D)); + } + + /** + * 九星 + * + * @return 九星 + */ + public NineStar getNineStar() { + return NineStar.fromIndex(63 + getTwenty().getSixty().getIndex() * 3 - getSixtyCycle().getIndex()); + } + + /** + * 太岁方位 + * + * @return 方位 + */ + public Direction getJupiterDirection() { + return Direction.fromIndex(new int[]{0, 7, 7, 2, 3, 3, 8, 1, 1, 6, 0, 0}[getSixtyCycle().getEarthBranch().getIndex()]); + } + + /** + * 月份列表 + * + * @return 月份列表,一般有12个月,当年有闰月时,有13个月。 + */ + public List getMonths() { + List l = new ArrayList<>(13); + LunarMonth m = LunarMonth.fromYm(year, 1); + while (m.getYear().getYear() == year) { + l.add(m); + m = m.next(1); + } + return l; + } + + @Override + public boolean equals(Object o) { + return o instanceof LunarYear && ((LunarYear) o).getYear() == year; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/package-info.java new file mode 100644 index 0000000000..e2bdd1f399 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/lunar/package-info.java @@ -0,0 +1,7 @@ +/** + * 中文农历 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.lunar; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/package-info.java new file mode 100644 index 0000000000..fe6c0dd739 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/package-info.java @@ -0,0 +1,15 @@ +/** + * 民俗文化 + * 由于区域文化差异对于年月日等相关统称也有所不同 + * 其他区域根据相关内容实现或重写相关方法即可 + * cn - 中文 + * en - 英文 + *

+ * 本包部分方法实现来自: + * https://github.com/6tail/lunar-java + *

+ * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarDay.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarDay.java new file mode 100755 index 0000000000..1e4eecddb1 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarDay.java @@ -0,0 +1,385 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.solar; + +import org.miaixz.bus.core.center.date.culture.Holiday; +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.JulianDay; +import org.miaixz.bus.core.center.date.culture.cn.Week; +import org.miaixz.bus.core.center.date.culture.cn.climate.Climate; +import org.miaixz.bus.core.center.date.culture.cn.climate.ClimateDay; +import org.miaixz.bus.core.center.date.culture.cn.dog.Dog; +import org.miaixz.bus.core.center.date.culture.cn.dog.DogDay; +import org.miaixz.bus.core.center.date.culture.cn.nine.Nine; +import org.miaixz.bus.core.center.date.culture.cn.nine.NineDay; +import org.miaixz.bus.core.center.date.culture.en.Constellation; +import org.miaixz.bus.core.center.date.culture.lunar.LunarDay; +import org.miaixz.bus.core.center.date.culture.lunar.LunarMonth; + +/** + * 公历日 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SolarDay extends Loops { + + public static final String[] NAMES = { + "1日", "2日", "3日", "4日", "5日", "6日", "7日", "8日", "9日", "10日", "11日", + "12日", "13日", "14日", "15日", "16日", "17日", "18日", "19日", "20日", "21日", + "22日", "23日", "24日", "25日", "26日", "27日", "28日", "29日", "30日", "31日" + }; + + /** + * 公历月 + */ + protected SolarMonth month; + + /** + * 日 + */ + protected int day; + + /** + * 初始化 + * + * @param year 年 + * @param month 月 + * @param day 日 + */ + public SolarDay(int year, int month, int day) { + if (day < 1) { + throw new IllegalArgumentException(String.format("illegal solar day: %d-%d-%d", year, month, day)); + } + SolarMonth m = SolarMonth.fromYm(year, month); + if (1582 == year && 10 == month) { + if ((day > 4 && day < 15) || day > 31) { + throw new IllegalArgumentException(String.format("illegal solar day: %d-%d-%d", year, month, day)); + } + } else if (day > m.getDayCount()) { + throw new IllegalArgumentException(String.format("illegal solar day: %d-%d-%d", year, month, day)); + } + this.month = m; + this.day = day; + } + + public static SolarDay fromYmd(int year, int month, int day) { + return new SolarDay(year, month, day); + } + + /** + * 月 + * + * @return 月 + */ + public SolarMonth getMonth() { + return month; + } + + /** + * 日 + * + * @return 日 + */ + public int getDay() { + return day; + } + + /** + * 星期 + * + * @return 星期 + */ + public Week getWeek() { + return getJulianDay().getWeek(); + } + + /** + * 星座 + * + * @return 星座 + */ + public Constellation getConstellation() { + int index = 11; + int y = month.getMonth() * 100 + day; + if (y >= 321 && y <= 419) { + index = 0; + } else if (y >= 420 && y <= 520) { + index = 1; + } else if (y >= 521 && y <= 621) { + index = 2; + } else if (y >= 622 && y <= 722) { + index = 3; + } else if (y >= 723 && y <= 822) { + index = 4; + } else if (y >= 823 && y <= 922) { + index = 5; + } else if (y >= 923 && y <= 1023) { + index = 6; + } else if (y >= 1024 && y <= 1122) { + index = 7; + } else if (y >= 1123 && y <= 1221) { + index = 8; + } else if (y >= 1222 || y <= 119) { + index = 9; + } else if (y <= 218) { + index = 10; + } + return Constellation.get(index); + } + + public String getName() { + return NAMES[day - 1]; + } + + @Override + public String toString() { + return month + getName(); + } + + public SolarDay next(int n) { + return getJulianDay().next(n).getSolarDay(); + } + + /** + * 是否在指定公历日之前 + * + * @param target 公历日 + * @return true/false + */ + public boolean isBefore(SolarDay target) { + int aYear = month.getYear().getYear(); + SolarMonth targetMonth = target.getMonth(); + int bYear = targetMonth.getYear().getYear(); + if (aYear == bYear) { + int aMonth = month.getMonth(); + int bMonth = targetMonth.getMonth(); + return aMonth == bMonth ? day < target.getDay() : aMonth < bMonth; + } + return aYear < bYear; + } + + /** + * 是否在指定公历日之后 + * + * @param target 公历日 + * @return true/false + */ + public boolean isAfter(SolarDay target) { + int aYear = month.getYear().getYear(); + SolarMonth targetMonth = target.getMonth(); + int bYear = targetMonth.getYear().getYear(); + if (aYear == bYear) { + int aMonth = month.getMonth(); + int bMonth = targetMonth.getMonth(); + return aMonth == bMonth ? day > target.getDay() : aMonth > bMonth; + } + return aYear > bYear; + } + + /** + * 节气 + * + * @return 节气 + */ + public SolarTerm getTerm() { + SolarTerm term = SolarTerm.fromIndex(month.getYear().getYear() + 1, 0); + while (isBefore(term.getJulianDay().getSolarDay())) { + term = term.next(-1); + } + return term; + } + + /** + * 公历周 + * + * @param start 起始星期,1234560分别代表星期一至星期天 + * @return 公历周 + */ + public SolarWeek getSolarWeek(int start) { + int y = month.getYear().getYear(); + int m = month.getMonth(); + return SolarWeek.fromYm(y, m, (int) Math.ceil((day + SolarDay.fromYmd(y, m, 1).getWeek().next(-start).getIndex()) / 7D) - 1, start); + } + + /** + * 七十二候 + * + * @return 七十二候 + */ + public ClimateDay getPhenologyDay() { + SolarTerm term = getTerm(); + int dayIndex = subtract(term.getJulianDay().getSolarDay()); + int index = dayIndex / 5; + if (index > 2) { + index = 2; + } + dayIndex -= index * 5; + return new ClimateDay(Climate.fromIndex(term.getIndex() * 3 + index), dayIndex); + } + + /** + * 三伏天 + * + * @return 三伏天 + */ + public DogDay getDogDay() { + SolarTerm xiaZhi = SolarTerm.fromIndex(month.getYear().getYear(), 12); + // 第1个庚日 + SolarDay start = xiaZhi.getJulianDay().getSolarDay(); + int add = 6 - start.getLunarDay().getSixtyCycle().getHeavenStem().getIndex(); + if (add < 0) { + add += 10; + } + // 第3个庚日,即初伏第1天 + add += 20; + start = start.next(add); + int days = subtract(start); + // 初伏以前 + if (days < 0) { + return null; + } + if (days < 10) { + return new DogDay(Dog.fromIndex(0), days); + } + // 第4个庚日,中伏第1天 + start = start.next(10); + days = subtract(start); + if (days < 10) { + return new DogDay(Dog.fromIndex(1), days); + } + // 第5个庚日,中伏第11天或末伏第1天 + start = start.next(10); + days = subtract(start); + // 立秋 + if (xiaZhi.next(3).getJulianDay().getSolarDay().isAfter(start)) { + if (days < 10) { + return new DogDay(Dog.fromIndex(1), days + 10); + } + start = start.next(10); + days = subtract(start); + } + if (days < 10) { + return new DogDay(Dog.fromIndex(2), days); + } + return null; + } + + /** + * 数九天 + * + * @return 数九天 + */ + public NineDay getNineDay() { + int year = month.getYear().getYear(); + SolarDay start = SolarTerm.fromIndex(year + 1, 0).getJulianDay().getSolarDay(); + if (isBefore(start)) { + start = SolarTerm.fromIndex(year, 0).getJulianDay().getSolarDay(); + } + SolarDay end = start.next(81); + if (isBefore(start) || !isBefore(end)) { + return null; + } + int days = subtract(start); + return new NineDay(Nine.fromIndex(days / 9), days % 9); + } + + /** + * 位于当年的索引 + * + * @return 索引 + */ + public int getIndexInYear() { + int m = month.getMonth(); + int y = month.getYear().getYear(); + int days = 0; + for (int i = 1; i < m; i++) { + days += SolarMonth.fromYm(y, i).getDayCount(); + } + int d = day; + if (1582 == y && 10 == m) { + if (d >= 15) { + d -= 10; + } + } + return days + d - 1; + } + + /** + * 公历日期相减,获得相差天数 + * + * @param target 公历 + * @return 天数 + */ + public int subtract(SolarDay target) { + return (int) (getJulianDay().getDay() - target.getJulianDay().getDay()); + } + + /** + * 儒略日 + * + * @return 儒略日 + */ + public JulianDay getJulianDay() { + return JulianDay.fromYmdHms(month.getYear().getYear(), month.getMonth(), day, 0, 0, 0); + } + + /** + * 农历日 + * + * @return 农历日 + */ + public LunarDay getLunarDay() { + LunarMonth m = LunarMonth.fromYm(month.getYear().getYear(), month.getMonth()).next(-3); + int days = subtract(m.getFirstJulianDay().getSolarDay()); + while (days >= m.getDayCount()) { + m = m.next(1); + days = subtract(m.getFirstJulianDay().getSolarDay()); + } + return LunarDay.fromYmd(m.getYear().getYear(), m.getMonthWithLeap(), days + 1); + } + + /** + * 法定假日,如果当天不是法定假日,返回null + * + * @return 法定假日 + */ + public Holiday getLegalHoliday() { + SolarMonth m = getMonth(); + return Holiday.fromYmd(m.getYear().getYear(), m.getMonth(), day); + } + + /** + * 公历现代节日,如果当天不是公历现代节日,返回null + * + * @return 公历现代节日 + */ + public SolarFestival getFestival() { + SolarMonth m = getMonth(); + return SolarFestival.fromYmd(m.getYear().getYear(), m.getMonth(), day); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarFestival.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarFestival.java new file mode 100755 index 0000000000..3a3c4d0eec --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarFestival.java @@ -0,0 +1,172 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.solar; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.lang.EnumMap; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 公历现代节日 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SolarFestival extends Loops { + + public static final String[] NAMES = { + "元旦", "三八妇女节", "植树节", "五一劳动节", "五四青年节", + "六一儿童节", "建党节", "八一建军节", "教师节", "国庆节" + }; + + public static String DATA = "@00001011950@01003081950@02003121979@03005011950@04005041950@05006011950@06007011941@07008011933@08009101985@09010011950"; + + /** + * 类型 + */ + protected EnumMap.Festival type; + + /** + * 索引 + */ + protected int index; + + /** + * 公历日 + */ + protected SolarDay day; + + /** + * 名称 + */ + protected String name; + + /** + * 起始年 + */ + protected int startYear; + + public SolarFestival(EnumMap.Festival type, SolarDay day, int startYear, String data) { + this.type = type; + this.day = day; + this.startYear = startYear; + index = Integer.parseInt(data.substring(1, 3), 10); + name = NAMES[index]; + } + + public static SolarFestival fromIndex(int year, int index) { + if (index < 0 || index >= NAMES.length) { + throw new IllegalArgumentException(String.format("illegal index: %d", index)); + } + Matcher matcher = Pattern.compile(String.format("@%02d\\d+", index)).matcher(DATA); + if (matcher.find()) { + String data = matcher.group(); + EnumMap.Festival type = EnumMap.Festival.fromCode(data.charAt(3) - '0'); + if (type == EnumMap.Festival.DAY) { + int startYear = Integer.parseInt(data.substring(8), 10); + if (year >= startYear) { + return new SolarFestival(type, SolarDay.fromYmd(year, Integer.parseInt(data.substring(4, 6), 10), Integer.parseInt(data.substring(6, 8), 10)), startYear, data); + } + } + } + return null; + } + + public static SolarFestival fromYmd(int year, int month, int day) { + Matcher matcher = Pattern.compile(String.format("@\\d{2}0%02d%02d\\d+", month, day)).matcher(DATA); + if (matcher.find()) { + String data = matcher.group(); + int startYear = Integer.parseInt(data.substring(8), 10); + if (year >= startYear) { + return new SolarFestival(EnumMap.Festival.DAY, SolarDay.fromYmd(year, month, day), startYear, data); + } + } + return null; + } + + public SolarFestival next(int n) { + SolarMonth m = day.getMonth(); + int year = m.getYear().getYear(); + if (n == 0) { + return fromYmd(year, m.getMonth(), day.getDay()); + } + int size = NAMES.length; + int t = this.index + n; + int offset = indexOf(t, size); + if (t < 0) { + t -= size; + } + return fromIndex(year + t / size, offset); + } + + /** + * 类型 + * + * @return 节日类型 + */ + public EnumMap.Festival getType() { + return type; + } + + /** + * 索引 + * + * @return 索引 + */ + public int getIndex() { + return index; + } + + /** + * 公历日 + * + * @return 公历日 + */ + public SolarDay getDay() { + return day; + } + + /** + * 起始年 + * + * @return 年 + */ + public int getStartYear() { + return startYear; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return String.format("%s %s", day, name); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarHalfYear.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarHalfYear.java new file mode 100755 index 0000000000..2124aff11f --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarHalfYear.java @@ -0,0 +1,140 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.solar; + +import org.miaixz.bus.core.center.date.culture.Loops; + +import java.util.ArrayList; +import java.util.List; + +/** + * 公历半年 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SolarHalfYear extends Loops { + + public static final String[] NAMES = {"上半年", "下半年"}; + + /** + * 年 + */ + protected SolarYear year; + + /** + * 索引,0-1 + */ + protected int index; + + /** + * 初始化 + * + * @param year 年 + * @param index 索引,0-1 + */ + public SolarHalfYear(int year, int index) { + this.year = SolarYear.fromYear(year); + if (index < 0 || index > 1) { + throw new IllegalArgumentException(String.format("illegal solar half year index: %d", index)); + } + this.index = index; + } + + public static SolarHalfYear fromIndex(int year, int index) { + return new SolarHalfYear(year, index); + } + + /** + * 年 + * + * @return 年 + */ + public SolarYear getYear() { + return year; + } + + /** + * 索引 + * + * @return 索引,0-1 + */ + public int getIndex() { + return index; + } + + public String getName() { + return NAMES[index]; + } + + @Override + public String toString() { + return year + getName(); + } + + public SolarHalfYear next(int n) { + if (n == 0) { + return fromIndex(year.getYear(), index); + } + int i = index + n; + int y = year.getYear() + i / 2; + i %= 2; + if (i < 0) { + i += 2; + y -= 1; + } + return fromIndex(y, i); + } + + /** + * 月份列表 + * + * @return 月份列表,半年有6个月。 + */ + public List getMonths() { + List l = new ArrayList<>(6); + int y = year.getYear(); + for (int i = 0; i < 6; i++) { + l.add(SolarMonth.fromYm(y, index * 6 + i + 1)); + } + return l; + } + + /** + * 季度列表 + * + * @return 季度列表,半年有2个季度。 + */ + public List getSeasons() { + List l = new ArrayList<>(2); + int y = year.getYear(); + for (int i = 0; i < 2; i++) { + l.add(SolarQuarter.fromIndex(y, index * 2 + i)); + } + return l; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarMonth.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarMonth.java new file mode 100755 index 0000000000..96f8699d5f --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarMonth.java @@ -0,0 +1,196 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.solar; + +import org.miaixz.bus.core.center.date.culture.Loops; + +import java.util.ArrayList; +import java.util.List; + +/** + * 公历月 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SolarMonth extends Loops { + + public static final String[] NAMES = { + "1月", "2月", "3月", "4月", "5月", "6月", + "7月", "8月", "9月", "10月", "11月", "12月" + }; + + /** + * 每月天数 + */ + public static final int[] DAYS = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + /** + * 年 + */ + protected SolarYear year; + + /** + * 月 + */ + protected int month; + + /** + * 初始化 + * + * @param year 年 + * @param month 月 + */ + public SolarMonth(int year, int month) { + this.year = SolarYear.fromYear(year); + if (month < 1 || month > 12) { + throw new IllegalArgumentException(String.format("illegal solar month: %d", month)); + } + this.month = month; + } + + public static SolarMonth fromYm(int year, int month) { + return new SolarMonth(year, month); + } + + /** + * 年 + * + * @return 年 + */ + public SolarYear getYear() { + return year; + } + + /** + * 月 + * + * @return 月 + */ + public int getMonth() { + return month; + } + + /** + * 天数(1582年10月只有21天) + * + * @return 天数 + */ + public int getDayCount() { + if (1582 == year.getYear() && 10 == month) { + return 21; + } + int d = DAYS[getIndexInYear()]; + //公历闰年2月多一天 + if (2 == month && year.isLeap()) { + d++; + } + return d; + } + + /** + * 位于当年的索引(0-11) + * + * @return 索引 + */ + public int getIndexInYear() { + return month - 1; + } + + /** + * 公历季度 + * + * @return 公历季度 + */ + public SolarQuarter getSeason() { + return SolarQuarter.fromIndex(year.getYear(), getIndexInYear() / 3); + } + + /** + * 周数 + * + * @param start 起始星期,1234560分别代表星期一至星期天 + * @return 周数 + */ + public int getWeekCount(int start) { + return (int) Math.ceil((indexOf(SolarDay.fromYmd(year.getYear(), month, 1).getWeek().getIndex() - start, 7) + getDayCount()) / 7D); + } + + public String getName() { + return NAMES[getIndexInYear()]; + } + + @Override + public String toString() { + return year + getName(); + } + + public SolarMonth next(int n) { + if (n == 0) { + return fromYm(year.getYear(), month); + } + int m = month + n; + int y = year.getYear() + m / 12; + m %= 12; + if (m < 1) { + m += 12; + y--; + } + return fromYm(y, m); + } + + /** + * 获取本月的公历周列表 + * + * @param start 星期几作为一周的开始,1234560分别代表星期一至星期天 + * @return 周列表 + */ + public List getWeeks(int start) { + int size = getWeekCount(start); + int y = year.getYear(); + List l = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + l.add(SolarWeek.fromYm(y, month, i, start)); + } + return l; + } + + /** + * 获取本月的公历日列表 + * + * @return 公历日列表 + */ + public List getDays() { + int size = getDayCount(); + int y = year.getYear(); + List l = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + l.add(SolarDay.fromYmd(y, month, i + 1)); + } + return l; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarQuarter.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarQuarter.java new file mode 100755 index 0000000000..f30e9db627 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarQuarter.java @@ -0,0 +1,125 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.solar; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.en.Quarter; + +import java.util.ArrayList; +import java.util.List; + +/** + * 公历季度 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SolarQuarter extends Loops { + + /** + * 年 + */ + protected SolarYear year; + + /** + * 索引,0-3 + */ + protected int index; + + /** + * 初始化 + * + * @param year 年 + * @param index 索引,0-3 + */ + public SolarQuarter(int year, int index) { + this.year = SolarYear.fromYear(year); + if (index < 0 || index > 3) { + throw new IllegalArgumentException(String.format("illegal solar season index: %d", index)); + } + this.index = index; + } + + public static SolarQuarter fromIndex(int year, int index) { + return new SolarQuarter(year, index); + } + + /** + * 年 + * + * @return 年 + */ + public SolarYear getYear() { + return year; + } + + /** + * 索引 + * + * @return 索引,0-3 + */ + public int getIndex() { + return index; + } + + public String getName() { + return Quarter.getName(index); + } + + @Override + public String toString() { + return year + getName(); + } + + public SolarQuarter next(int n) { + if (n == 0) { + return fromIndex(year.getYear(), index); + } + int i = index + n; + int y = year.getYear() + i / 4; + i %= 4; + if (i < 0) { + i += 4; + y -= 1; + } + return fromIndex(y, i); + } + + /** + * 月份列表 + * + * @return 月份列表,1季度有3个月。 + */ + public List getMonths() { + List l = new ArrayList<>(3); + int y = year.getYear(); + for (int i = 0; i < 3; i++) { + l.add(SolarMonth.fromYm(y, index * 3 + i + 1)); + } + return l; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarTerm.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarTerm.java new file mode 100755 index 0000000000..31995dec24 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarTerm.java @@ -0,0 +1,130 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.solar; + +import org.miaixz.bus.core.center.date.culture.Galaxy; +import org.miaixz.bus.core.center.date.culture.Samsara; +import org.miaixz.bus.core.center.date.culture.cn.JulianDay; + +/** + * 节气 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SolarTerm extends Samsara { + + public static final String[] NAMES = { + "冬至", "小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", + "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", + "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪" + }; + + /** + * 粗略的儒略日 + */ + protected double cursoryJulianDay; + + public SolarTerm(int year, int index) { + super(NAMES, index); + initByYear(year, index); + } + + public SolarTerm(int year, String name) { + super(NAMES, name); + initByYear(year, index); + } + + public SolarTerm(double cursoryJulianDay, int index) { + super(NAMES, index); + this.cursoryJulianDay = cursoryJulianDay; + } + + public static void main(String[] args) { + // 冬至在去年,2022-12-22 05:48:11 + SolarTerm dongZhi = SolarTerm.fromName(3001, "冬至"); + System.out.println(dongZhi.getJulianDay().getSolarTime()); + } + + public static SolarTerm fromIndex(int year, int index) { + return new SolarTerm(year, index); + } + + public static SolarTerm fromName(int year, String name) { + return new SolarTerm(year, name); + } + + protected void initByYear(int year, int offset) { + double jd = Math.floor((year - 2000) * 365.2422 + 180); + // 355是2000.12冬至,得到较靠近jd的冬至估计值 + double w = Math.floor((jd - 355 + 183) / 365.2422) * 365.2422 + 355; + if (Galaxy.calcQi(w) > jd) { + w -= 365.2422; + } + cursoryJulianDay = Galaxy.calcQi(w + 15.2184 * offset); + } + + public SolarTerm next(int n) { + return new SolarTerm(cursoryJulianDay + 15.2184 * n, nextIndex(n)); + } + + /** + * 是否节 + * + * @return true/false + */ + public boolean isJie() { + return index % 2 == 1; + } + + /** + * 是否气 + * + * @return true/false + */ + public boolean isQi() { + return index % 2 == 0; + } + + /** + * 儒略日 + * + * @return 儒略日 + */ + public JulianDay getJulianDay() { + return JulianDay.fromJulianDay(Galaxy.qiAccurate2(cursoryJulianDay) + JulianDay.J2000); + } + + /** + * 粗略的儒略日 + * + * @return 儒略日数 + */ + public double getCursoryJulianDay() { + return cursoryJulianDay; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarTime.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarTime.java new file mode 100755 index 0000000000..43beffc951 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarTime.java @@ -0,0 +1,262 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.solar; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.JulianDay; +import org.miaixz.bus.core.center.date.culture.lunar.LunarDay; +import org.miaixz.bus.core.center.date.culture.lunar.LunarHour; +import org.miaixz.bus.core.center.date.culture.lunar.LunarMonth; + +/** + * 公历时刻 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SolarTime extends Loops { + + /** + * 公历日 + */ + protected SolarDay day; + + /** + * 时 + */ + protected int hour; + + /** + * 分 + */ + protected int minute; + + /** + * 秒 + */ + protected int second; + + /** + * 初始化 + * + * @param year 年 + * @param month 月 + * @param day 日 + * @param hour 时 + * @param minute 分 + * @param second 秒 + */ + public SolarTime(int year, int month, int day, int hour, int minute, int second) { + if (hour < 0 || hour > 23) { + throw new IllegalArgumentException(String.format("illegal hour: %d", hour)); + } + if (minute < 0 || minute > 59) { + throw new IllegalArgumentException(String.format("illegal minute: %d", minute)); + } + if (second < 0 || second > 59) { + throw new IllegalArgumentException(String.format("illegal second: %d", second)); + } + this.day = SolarDay.fromYmd(year, month, day); + this.hour = hour; + this.minute = minute; + this.second = second; + } + + public static SolarTime fromYmdHms(int year, int month, int day, int hour, int minute, int second) { + return new SolarTime(year, month, day, hour, minute, second); + } + + /** + * 日 + * + * @return 日 + */ + public SolarDay getDay() { + return day; + } + + /** + * 时 + * + * @return 时 + */ + public int getHour() { + return hour; + } + + /** + * 分 + * + * @return 分 + */ + public int getMinute() { + return minute; + } + + /** + * 秒 + * + * @return 秒 + */ + public int getSecond() { + return second; + } + + public String getName() { + return String.format("%02d:%02d:%02d", hour, minute, second); + } + + @Override + public String toString() { + return String.format("%s %s", day, getName()); + } + + /** + * 是否在指定公历时刻之前 + * + * @param target 公历时刻 + * @return true/false + */ + public boolean isBefore(SolarTime target) { + if (!day.equals(target.getDay())) { + return day.isBefore(target.getDay()); + } + int bHour = target.getHour(); + if (hour == bHour) { + int bMinute = target.getMinute(); + return minute == bMinute ? second < target.getSecond() : minute < bMinute; + } + return hour < bHour; + } + + /** + * 是否在指定公历时刻之后 + * + * @param target 公历时刻 + * @return true/false + */ + public boolean isAfter(SolarTime target) { + if (!day.equals(target.getDay())) { + return day.isAfter(target.getDay()); + } + int bHour = target.getHour(); + if (hour == bHour) { + int bMinute = target.getMinute(); + return minute == bMinute ? second > target.getSecond() : minute > bMinute; + } + return hour > bHour; + } + + /** + * 节气 + * + * @return 节气 + */ + public SolarTerm getTerm() { + SolarTerm term = SolarTerm.fromIndex(day.getMonth().getYear().getYear() + 1, 0); + while (isBefore(term.getJulianDay().getSolarTime())) { + term = term.next(-1); + } + return term; + } + + /** + * 儒略日 + * + * @return 儒略日 + */ + public JulianDay getJulianDay() { + SolarMonth month = day.getMonth(); + return JulianDay.fromYmdHms(month.getYear().getYear(), month.getMonth(), day.getDay(), hour, minute, second); + } + + /** + * 公历时刻相减,获得相差秒数 + * + * @param target 公历时刻 + * @return 秒数 + */ + public int subtract(SolarTime target) { + int days = day.subtract(target.getDay()); + int cs = hour * 3600 + minute * 60 + second; + int ts = target.getHour() * 3600 + target.getMinute() * 60 + target.getSecond(); + int seconds = cs - ts; + if (seconds < 0) { + seconds += 86400; + days--; + } + seconds += days * 86400; + return seconds; + } + + /** + * 推移 + * + * @param n 推移秒数 + * @return 公历时刻 + */ + public SolarTime next(int n) { + if (n == 0) { + SolarMonth month = day.getMonth(); + return SolarTime.fromYmdHms(month.getYear().getYear(), month.getMonth(), day.getDay(), hour, minute, second); + } + int ts = second + n; + int tm = minute + ts / 60; + ts %= 60; + if (ts < 0) { + ts += 60; + tm -= 1; + } + int th = hour + tm / 60; + tm %= 60; + if (tm < 0) { + tm += 60; + th -= 1; + } + int td = th / 24; + th %= 24; + if (th < 0) { + th += 24; + td -= 1; + } + + SolarDay d = day.next(td); + SolarMonth m = d.getMonth(); + return SolarTime.fromYmdHms(m.getYear().getYear(), m.getMonth(), d.getDay(), th, tm, ts); + } + + /** + * 时辰 + * + * @return 农历时辰 + */ + public LunarHour getLunarHour() { + LunarDay d = day.getLunarDay(); + LunarMonth m = d.getMonth(); + return LunarHour.fromYmdHms(m.getYear().getYear(), m.getMonthWithLeap(), d.getDay(), hour, minute, second); + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarWeek.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarWeek.java new file mode 100755 index 0000000000..196add629c --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarWeek.java @@ -0,0 +1,196 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.solar; + +import org.miaixz.bus.core.center.date.culture.Loops; +import org.miaixz.bus.core.center.date.culture.cn.Week; + +import java.util.ArrayList; +import java.util.List; + +/** + * 公历周 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SolarWeek extends Loops { + + /** + * 月 + */ + protected SolarMonth month; + + /** + * 索引,0-5 + */ + protected int index; + + /** + * 起始星期 + */ + protected Week start; + + /** + * 初始化 + * + * @param year 年 + * @param month 月 + * @param index 索引,0-5 + * @param start 起始星期,1234560分别代表星期一至星期天 + */ + public SolarWeek(int year, int month, int index, int start) { + if (index < 0 || index > 5) { + throw new IllegalArgumentException(String.format("illegal solar week index: %d", index)); + } + if (start < 0 || start > 6) { + throw new IllegalArgumentException(String.format("illegal solar week start: %d", start)); + } + SolarMonth m = SolarMonth.fromYm(year, month); + if (index >= m.getWeekCount(start)) { + throw new IllegalArgumentException(String.format("illegal solar week index: %d in month: %s", index, m)); + } + this.month = m; + this.index = index; + this.start = Week.fromIndex(start); + } + + public static SolarWeek fromYm(int year, int month, int index, int start) { + return new SolarWeek(year, month, index, start); + } + + /** + * 月 + * + * @return 月 + */ + public SolarMonth getMonth() { + return month; + } + + /** + * 索引 + * + * @return 索引,0-5 + */ + public int getIndex() { + return index; + } + + /** + * 位于当年的索引 + * + * @return 索引 + */ + public int getIndexInYear() { + int i = 0; + // 今年第1周 + SolarWeek w = SolarWeek.fromYm(month.getYear().getYear(), 1, 0, start.getIndex()); + while (!w.equals(this)) { + w = w.next(1); + i++; + } + return i; + } + + /** + * 起始星期 + * + * @return 星期 + */ + public Week getStart() { + return start; + } + + public String getName() { + return Week.WHICH[index]; + } + + @Override + public String toString() { + return month + getName(); + } + + public SolarWeek next(int n) { + if (n == 0) { + return fromYm(month.getYear().getYear(), month.getMonth(), index, start.getIndex()); + } + int d = index + n; + SolarMonth m = month; + int startIndex = start.getIndex(); + int weeksInMonth = m.getWeekCount(startIndex); + boolean forward = n > 0; + int add = forward ? 1 : -1; + while (forward ? (d >= weeksInMonth) : (d < 0)) { + if (forward) { + d -= weeksInMonth; + } + if (!forward) { + if (!SolarDay.fromYmd(m.getYear().getYear(), m.getMonth(), 1).getWeek().equals(start)) { + d += add; + } + } + m = m.next(add); + if (forward) { + if (!SolarDay.fromYmd(m.getYear().getYear(), m.getMonth(), 1).getWeek().equals(start)) { + d += add; + } + } + weeksInMonth = m.getWeekCount(startIndex); + if (!forward) { + d += weeksInMonth; + } + } + return fromYm(m.getYear().getYear(), m.getMonth(), d, startIndex); + } + + /** + * 本周第1天 + * + * @return 公历日 + */ + public SolarDay getFirstDay() { + SolarMonth m = getMonth(); + SolarDay firstDay = SolarDay.fromYmd(m.getYear().getYear(), m.getMonth(), 1); + return firstDay.next(index * 7 - indexOf(firstDay.getWeek().getIndex() - start.getIndex(), 7)); + } + + /** + * 本周公历日列表 + * + * @return 公历日列表 + */ + public List getDays() { + List l = new ArrayList<>(7); + SolarDay d = getFirstDay(); + l.add(d); + for (int i = 1; i < 7; i++) { + l.add(d.next(i)); + } + return l; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarYear.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarYear.java new file mode 100755 index 0000000000..38a4a59818 --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/SolarYear.java @@ -0,0 +1,143 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org 6tail and other contributors. * + * * + * 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 org.miaixz.bus.core.center.date.culture.solar; + +import org.miaixz.bus.core.center.date.culture.Loops; + +import java.util.ArrayList; +import java.util.List; + +/** + * 公历年 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class SolarYear extends Loops { + + /** + * 年 + */ + protected int year; + + public SolarYear(int year) { + if (year < 1 || year > 9999) { + throw new IllegalArgumentException(String.format("illegal solar year: %d", year)); + } + this.year = year; + } + + /** + * 从年初始化 + * + * @param year 年,支持1到9999年 + * @return 公历年 + */ + public static SolarYear fromYear(int year) { + return new SolarYear(year); + } + + /** + * 年 + * + * @return 年 + */ + public int getYear() { + return year; + } + + /** + * 天数(1582年355天,平年365天,闰年366天) + * + * @return 天数 + */ + public int getDayCount() { + if (1582 == year) { + return 355; + } + return isLeap() ? 366 : 365; + } + + /** + * 是否闰年(1582年以前,使用儒略历,能被4整除即为闰年。以后采用格里历,四年一闰,百年不闰,四百年再闰。) + * + * @return true/false + */ + public boolean isLeap() { + if (year < 1600) { + return year % 4 == 0; + } + return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); + } + + public String getName() { + return String.format("%d年", year); + } + + public SolarYear next(int n) { + return fromYear(year + n); + } + + /** + * 月份列表 + * + * @return 月份列表,1年有12个月。 + */ + public List getMonths() { + List l = new ArrayList<>(12); + for (int i = 0; i < 12; i++) { + l.add(SolarMonth.fromYm(year, i + 1)); + } + return l; + } + + /** + * 季度列表 + * + * @return 季度列表,1年有4个季度。 + */ + public List getSeasons() { + List l = new ArrayList<>(4); + for (int i = 0; i < 4; i++) { + l.add(SolarQuarter.fromIndex(year, i)); + } + return l; + } + + /** + * 半年列表 + * + * @return 半年列表,1年有2个半年。 + */ + public List getHalfYears() { + List l = new ArrayList<>(2); + for (int i = 0; i < 2; i++) { + l.add(SolarHalfYear.fromIndex(year, i)); + } + return l; + } + +} diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/package-info.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/package-info.java new file mode 100644 index 0000000000..c442e0427e --- /dev/null +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/culture/solar/package-info.java @@ -0,0 +1,7 @@ +/** + * 中文公历/阳历 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.core.center.date.culture.solar; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatBuilder.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatBuilder.java index 3d5548980c..d5faf3e3d0 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatBuilder.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatBuilder.java @@ -30,6 +30,7 @@ import org.miaixz.bus.core.center.date.printer.FastDatePrinter; import org.miaixz.bus.core.center.date.printer.FormatPrinter; import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.DateException; import java.text.DateFormat; @@ -447,7 +448,7 @@ public int hashCode() { @Override public String toString() { - return "FastFormat[" + printer.getPattern() + "," + printer.getLocale() + "," + printer.getTimeZone().getID() + "]"; + return "FastFormat[" + printer.getPattern() + Symbol.COMMA + printer.getLocale() + Symbol.COMMA + printer.getTimeZone().getID() + "]"; } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatCache.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatCache.java index 608674c774..f1c3e9e3ec 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatCache.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatCache.java @@ -39,6 +39,7 @@ /** * 日期格式化器缓存 * + * @param 对象类型 * @author Kimi Liu * @since Java 17+ */ diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatPeriod.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatPeriod.java index 91ca871d65..a707b89f9a 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatPeriod.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/FormatPeriod.java @@ -25,7 +25,7 @@ ********************************************************************************/ package org.miaixz.bus.core.center.date.format; -import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.center.date.culture.en.Units; import org.miaixz.bus.core.xyz.StringKit; import java.io.Serializable; @@ -107,12 +107,12 @@ public static FormatPeriod of(final long betweenMs, final Level level, final int public String format() { final StringBuilder sb = new StringBuilder(); if (betweenMs > 0) { - final long day = betweenMs / Fields.Units.DAY.getMillis(); - final long hour = betweenMs / Fields.Units.HOUR.getMillis() - day * 24; - final long minute = betweenMs / Fields.Units.MINUTE.getMillis() - day * 24 * 60 - hour * 60; + final long day = betweenMs / Units.DAY.getMillis(); + final long hour = betweenMs / Units.HOUR.getMillis() - day * 24; + final long minute = betweenMs / Units.MINUTE.getMillis() - day * 24 * 60 - hour * 60; final long BetweenOfSecond = ((day * 24 + hour) * 60 + minute) * 60; - final long second = betweenMs / Fields.Units.SECOND.getMillis() - BetweenOfSecond; + final long second = betweenMs / Units.SECOND.getMillis() - BetweenOfSecond; final long millisecond = betweenMs - (BetweenOfSecond + second) * 1000; final int level = this.level.ordinal(); diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/FastDateParser.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/FastDateParser.java index 2cafa8b0d3..dcc9f6e5ed 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/FastDateParser.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/FastDateParser.java @@ -176,7 +176,7 @@ private static StringBuilder simpleQuote(final StringBuilder sb, final String va case '?': case Symbol.C_STAR: case Symbol.C_PLUS: - case '(': + case Symbol.C_PARENTHESE_LEFT: case ')': case '[': case '{': @@ -515,7 +515,7 @@ private static class CaseInsensitiveTextStrategy extends PatternStrategy { regex.append("((?iu)"); lKeyValues = appendDisplayNames(definingCalendar, locale, field, regex); regex.setLength(regex.length() - 1); - regex.append(")"); + regex.append(Symbol.PARENTHESE_RIGHT); createPattern(regex); } @@ -663,7 +663,7 @@ static class TimeZoneStrategy extends PatternStrategy { for (final String zoneName : sorted) { simpleQuote(sb.append('|'), zoneName); } - sb.append(")"); + sb.append(Symbol.PARENTHESE_RIGHT); createPattern(sb); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/PatternsDateParser.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/PatternsDateParser.java index a702e69e40..7f965990e4 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/PatternsDateParser.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/PatternsDateParser.java @@ -25,17 +25,16 @@ ********************************************************************************/ package org.miaixz.bus.core.center.date.format.parser; -import org.miaixz.bus.core.center.date.Calendars; +import org.miaixz.bus.core.center.date.Calendar; import org.miaixz.bus.core.center.date.DateTime; import org.miaixz.bus.core.center.date.printer.DefaultDatePrinter; import org.miaixz.bus.core.lang.exception.DateException; -import java.util.Calendar; import java.util.Locale; /** * 通过给定的日期格式解析日期时间字符串。 - * 传入的日期格式会逐个尝试,直到解析成功,返回{@link Calendar}对象,否则抛出{@link DateException}异常。 + * 传入的日期格式会逐个尝试,直到解析成功,返回{@link java.util.Calendar}对象,否则抛出{@link DateException}异常。 * * @author Kimi Liu * @since Java 17+ @@ -95,7 +94,7 @@ public PatternsDateParser setLocale(final Locale locale) { @Override public DateTime parse(final String source) { - return new DateTime(Calendars.parseByPatterns(source, this.locale, this.parsePatterns)); + return new DateTime(Calendar.parseByPatterns(source, this.locale, this.parsePatterns)); } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/RFC2822DateParser.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/RFC2822DateParser.java index 5fcd20aab1..cc1a041b83 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/RFC2822DateParser.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/format/parser/RFC2822DateParser.java @@ -30,6 +30,7 @@ import org.miaixz.bus.core.center.date.format.FormatBuilder; import org.miaixz.bus.core.center.date.printer.DefaultDatePrinter; import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.StringKit; import java.util.Locale; @@ -73,7 +74,7 @@ public boolean test(final CharSequence dateStr) { @Override public DateTime parse(final String source) { - if (StringKit.contains(source, ',')) { + if (StringKit.contains(source, Symbol.C_COMMA)) { if (StringKit.contains(source, KEYWORDS_LOCALE_CHINA)) { // 例如:星期四, 28 三月 2024 14:33:49 GMT return new DateTime(source, FormatBuilder.getInstance(Fields.HTTP_DATETIME, Locale.CHINA)); diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/date/printer/SimpleDatePrinter.java b/bus-core/src/main/java/org/miaixz/bus/core/center/date/printer/SimpleDatePrinter.java index d20cc2fcb5..92bfcf3fef 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/date/printer/SimpleDatePrinter.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/date/printer/SimpleDatePrinter.java @@ -25,6 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.core.center.date.printer; +import org.miaixz.bus.core.lang.Symbol; + import java.io.Serializable; import java.util.Locale; import java.util.TimeZone; @@ -96,7 +98,7 @@ public int hashCode() { @Override public String toString() { - return "SimpleDatePrinter[" + pattern + "," + locale + "," + timeZone.getID() + "]"; + return "SimpleDatePrinter[" + pattern + Symbol.COMMA + locale + Symbol.COMMA + timeZone.getID() + "]"; } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/map/Dictionary.java b/bus-core/src/main/java/org/miaixz/bus/core/center/map/Dictionary.java index 0d7d956aa3..1dc50a2801 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/map/Dictionary.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/map/Dictionary.java @@ -375,15 +375,6 @@ public T getBean(final String attr) { *
  • .表达式,可以获取Bean对象中的属性(字段)值或者Map中key对应的值
  • *
  • []表达式,可以获取集合等对象中对应index的值
  • * - *

    - * 表达式栗子: - * - *

    -     * persion
    -     * persion.name
    -     * persons[3]
    -     * person.friends[5].name
    -     * 
    * * @param 目标类型 * @param expression 表达式 @@ -400,16 +391,6 @@ public T getByPath(final String expression) { *
  • .表达式,可以获取Bean对象中的属性(字段)值或者Map中key对应的值
  • *
  • []表达式,可以获取集合等对象中对应index的值
  • * - *

    - * 表达式栗子: - * - *

    -     * persion
    -     * persion.name
    -     * persons[3]
    -     * person.friends[5].name
    -     * 
    - *

    * 获取表达式对应值后转换为对应类型的值 * * @param 返回值类型 diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/map/LinkedForestMap.java b/bus-core/src/main/java/org/miaixz/bus/core/center/map/LinkedForestMap.java index a275bc922e..3e7e3c1253 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/map/LinkedForestMap.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/map/LinkedForestMap.java @@ -346,6 +346,7 @@ public void unlinkNode(final K parentKey, final K childKey) { * 树节点 * * @param key类型 + * @param 值类型 */ public static class TreeEntryNode implements TreeEntry { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/map/MapGets.java b/bus-core/src/main/java/org/miaixz/bus/core/center/map/MapGets.java index 38c0ec7cf7..84df5b1762 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/map/MapGets.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/map/MapGets.java @@ -161,7 +161,7 @@ public static Short getShort(final Map map, final Object key, final Short * @param key 键 * @return 值 */ - public static Boolean getBool(final Map map, final Object key) { + public static Boolean getBoolean(final Map map, final Object key) { return get(map, key, Boolean.class); } @@ -173,7 +173,7 @@ public static Boolean getBool(final Map map, final Object key) { * @param defaultValue 默认值 * @return 值 */ - public static Boolean getBool(final Map map, final Object key, final Boolean defaultValue) { + public static Boolean getBoolean(final Map map, final Object key, final Boolean defaultValue) { return get(map, key, Boolean.class, defaultValue); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/map/concurrent/ConcurrentLinkedHashMap.java b/bus-core/src/main/java/org/miaixz/bus/core/center/map/concurrent/ConcurrentLinkedHashMap.java index f0b4664e0d..bcc183b4ba 100755 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/map/concurrent/ConcurrentLinkedHashMap.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/map/concurrent/ConcurrentLinkedHashMap.java @@ -92,10 +92,7 @@ * * @param the type of keys maintained by this map * @param the type of mapped values - * ben.manes@gmail.com (Ben Manes) * @author Kimi Liu - * @see - * http://code.google.com/p/concurrentlinkedhashmap/ * @since Java 17+ */ public final class ConcurrentLinkedHashMap extends AbstractMap @@ -1177,6 +1174,9 @@ Object readResolve() { * .weigher(Weighers.set()) * .build(); * } + * + * @param key类型 + * @param 值类型 */ public static final class Builder { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/map/multi/AbstractTable.java b/bus-core/src/main/java/org/miaixz/bus/core/center/map/multi/AbstractTable.java index 578f86e406..567cf4a71c 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/map/multi/AbstractTable.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/map/multi/AbstractTable.java @@ -26,6 +26,7 @@ package org.miaixz.bus.core.center.map.multi; import org.miaixz.bus.core.center.iterator.TransIterator; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.IteratorKit; import org.miaixz.bus.core.xyz.ObjectKit; @@ -150,7 +151,7 @@ public int hashCode() { @Override public String toString() { - return "(" + rowKey + "," + columnKey + ")=" + value; + return Symbol.PARENTHESE_LEFT + rowKey + Symbol.COMMA + columnKey + ")=" + value; } } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/queue/CheckedLinkedBlockingQueue.java b/bus-core/src/main/java/org/miaixz/bus/core/center/queue/CheckedLinkedBlockingQueue.java index 2e94237e05..c1e49325ed 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/queue/CheckedLinkedBlockingQueue.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/queue/CheckedLinkedBlockingQueue.java @@ -34,6 +34,7 @@ * 自定义加入前检查的{@link LinkedBlockingQueue},给定一个检查函数,在加入元素前检查此函数 * 原理是通过Runtime#freeMemory()获取剩余内存,当剩余内存低于指定的阈值时,不再加入。 * + * @param 对象类型 * @author Kimi Liu * @since Java 17+ */ diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/stream/EasyStream.java b/bus-core/src/main/java/org/miaixz/bus/core/center/stream/EasyStream.java index 1732795f75..672b1df3b0 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/stream/EasyStream.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/stream/EasyStream.java @@ -448,6 +448,8 @@ public OptionalDouble avg(final ToLongFunction mapper) { /** * 建造者 + * + * @param 对象类型 */ public interface Builder extends Consumer, org.miaixz.bus.core.Builder> { @@ -458,11 +460,6 @@ public interface Builder extends Consumer, org.miaixz.bus.core.Builder{@code - * accept(t) - * return this; - * } */ default Builder add(final T t) { accept(t); diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/DropWhileSpliterator.java b/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/DropWhileSpliterator.java index f516b250b8..21fbb7ae83 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/DropWhileSpliterator.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/DropWhileSpliterator.java @@ -33,6 +33,7 @@ /** * 借鉴自StreamEx * + * @param 对象类型 * @author Kimi Liu * @since Java 17+ */ diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/IterateSpliterator.java b/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/IterateSpliterator.java index f412826efe..6b6fa35413 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/IterateSpliterator.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/IterateSpliterator.java @@ -35,6 +35,7 @@ /** * 无限有序流的Spliterator * + * @param 对象类型 * @author Kimi Liu * @since Java 17+ */ diff --git a/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/TakeWhileSpliterator.java b/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/TakeWhileSpliterator.java index ac04a7d4f7..26c67d0039 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/TakeWhileSpliterator.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/center/stream/spliterators/TakeWhileSpliterator.java @@ -33,6 +33,7 @@ /** * takeWhile 的 Spliterator * + * @param 对象类型 * @author Kimi Liu * @since Java 17+ */ diff --git a/bus-core/src/main/java/org/miaixz/bus/core/codec/Morse.java b/bus-core/src/main/java/org/miaixz/bus/core/codec/Morse.java index 70ad8e0ec2..09f1c824d5 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/codec/Morse.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/codec/Morse.java @@ -87,12 +87,12 @@ public class Morse { registerMorse('9', "11110"); // Punctuation registerMorse('.', "010101"); - registerMorse(',', "110011"); + registerMorse(Symbol.C_COMMA, "110011"); registerMorse('?', "001100"); registerMorse('\'', "011110"); registerMorse(Symbol.C_NOT, "101011"); registerMorse('/', "10010"); - registerMorse('(', "10110"); + registerMorse(Symbol.C_PARENTHESE_LEFT, "10110"); registerMorse(')', "101101"); registerMorse(Symbol.C_AND, "01000"); registerMorse(Symbol.C_COLON, "111000"); diff --git a/bus-core/src/main/java/org/miaixz/bus/core/codec/PercentCodec.java b/bus-core/src/main/java/org/miaixz/bus/core/codec/PercentCodec.java index ac2fa65e19..76e4bafb93 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/codec/PercentCodec.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/codec/PercentCodec.java @@ -47,7 +47,7 @@ * *

    * 百分号编码会对 URI 中不允许出现的字符或者其他特殊情况的允许的字符进行编码,对于被编码的字符,最终会转为以百分号"%“开头,后面跟着两位16进制数值的形式。 - * 举个例子,空格符(SP)是不允许的字符,在 ASCII 码对应的二进制值是"00100000”,最终转为"%20"。 + * 举个例,空格符(SP)是不允许的字符,在 ASCII 码对应的二进制值是"00100000”,最终转为"%20"。 *

    *

    * 对于不同场景应遵循不同规范: diff --git a/bus-core/src/main/java/org/miaixz/bus/core/instance/Instances.java b/bus-core/src/main/java/org/miaixz/bus/core/instance/Instances.java index cad4ffa986..08203b1a19 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/instance/Instances.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/instance/Instances.java @@ -41,6 +41,9 @@ /** * 单例类 * 提供单例对象的统一管理,当调用get方法时,如果对象池中存在此对象,返回此对象,否则创建新对象返回 + * + * @author Kimi Liu + * @since Java 17+ */ @ThreadSafe public final class Instances { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/ByteOrderMark.java b/bus-core/src/main/java/org/miaixz/bus/core/io/ByteOrderMark.java index 58a3ed0af3..65833f1f4c 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/io/ByteOrderMark.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/ByteOrderMark.java @@ -27,6 +27,7 @@ import org.miaixz.bus.core.lang.Assert; import org.miaixz.bus.core.lang.Charset; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.ArrayKit; import java.io.Serializable; @@ -192,7 +193,7 @@ public String toString() { builder.append(": "); for (int i = 0; i < bytes.length; i++) { if (i > 0) { - builder.append(","); + builder.append(Symbol.COMMA); } builder.append("0x"); builder.append(Integer.toHexString(0xFF & bytes[i]).toUpperCase()); diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/ByteString.java b/bus-core/src/main/java/org/miaixz/bus/core/io/ByteString.java index a2f83c35de..18028b6fda 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/io/ByteString.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/ByteString.java @@ -378,7 +378,7 @@ public ByteString substring(int beginIndex) { public ByteString substring(int beginIndex, int endIndex) { if (beginIndex < 0) throw new IllegalArgumentException("beginIndex < 0"); if (endIndex > data.length) { - throw new IllegalArgumentException("endIndex > length(" + data.length + ")"); + throw new IllegalArgumentException("endIndex > length(" + data.length + Symbol.PARENTHESE_RIGHT); } int subLen = endIndex - beginIndex; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/LineReader.java b/bus-core/src/main/java/org/miaixz/bus/core/io/LineReader.java index 645f1c4a4d..009dc1b46d 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/io/LineReader.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/LineReader.java @@ -45,13 +45,6 @@ *

  • 如果想读取转义符,必须定义为'\\'
  • *
  • 多行转义后的换行符和空格都会被忽略
  • * - *

    - * 例子: - *

    - * a=1\
    - *   2
    - * 
    - * 读出后就是{@code a=12} * * @author Kimi Liu * @since Java 17+ diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/buffer/Buffer.java b/bus-core/src/main/java/org/miaixz/bus/core/io/buffer/Buffer.java index 276eb69eca..63eeb62949 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/io/buffer/Buffer.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/buffer/Buffer.java @@ -921,7 +921,7 @@ public int readUtf8CodePoint() throws EOFException { if (size < byteCount) { throw new EOFException("size < " + byteCount + ": " + size - + " (to read code point prefixed 0x" + Integer.toHexString(b0) + ")"); + + " (to read code point prefixed 0x" + Integer.toHexString(b0) + Symbol.PARENTHESE_RIGHT); } for (int i = 1; i < byteCount; i++) { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileName.java b/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileName.java index c3642ec44e..f87f6ce540 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileName.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileName.java @@ -131,67 +131,6 @@ public static String getName(final String filePath) { return filePath.substring(begin, len); } - /** - * 获取文件后缀名,扩展名不带“.” - * - * @param file 文件 - * @return 扩展名 - * @see #extName(File) - */ - public static String getSuffix(final File file) { - return extName(file); - } - - /** - * 获得文件后缀名,扩展名不带“.” - * - * @param fileName 文件名 - * @return 扩展名 - * @see #extName(String) - */ - public static String getSuffix(final String fileName) { - return extName(fileName); - } - - /** - * 增加临时扩展名 - * - * @param fileName 文件名 - * @param suffix 临时扩展名,如果为空,使用`.temp` - * @return 临时文件名 - */ - public static String addTempSuffix(final String fileName, String suffix) { - if (StringKit.isBlank(suffix)) { - suffix = ".temp"; - } else { - suffix = StringKit.addPrefixIfNot(suffix, Symbol.DOT); - } - - return fileName + suffix; - } - - /** - * 返回主文件名 - * - * @param file 文件 - * @return 主文件名 - * @see #mainName(File) - */ - public static String getPrefix(final File file) { - return mainName(file); - } - - /** - * 返回主文件名 - * - * @param fileName 完整文件名 - * @return 主文件名 - * @see #mainName(String) - */ - public static String getPrefix(final String fileName) { - return mainName(fileName); - } - /** * 返回主文件名 * @@ -292,6 +231,67 @@ public static String extName(final String fileName) { } } + /** + * 获取文件后缀名,扩展名不带“.” + * + * @param file 文件 + * @return 扩展名 + * @see #extName(File) + */ + public static String getSuffix(final File file) { + return extName(file); + } + + /** + * 获得文件后缀名,扩展名不带“.” + * + * @param fileName 文件名 + * @return 扩展名 + * @see #extName(String) + */ + public static String getSuffix(final String fileName) { + return extName(fileName); + } + + /** + * 返回主文件名 + * + * @param file 文件 + * @return 主文件名 + * @see #mainName(File) + */ + public static String getPrefix(final File file) { + return mainName(file); + } + + /** + * 返回主文件名 + * + * @param fileName 完整文件名 + * @return 主文件名 + * @see #mainName(String) + */ + public static String getPrefix(final String fileName) { + return mainName(fileName); + } + + /** + * 增加临时扩展名 + * + * @param fileName 文件名 + * @param suffix 临时扩展名,如果为空,使用`.temp` + * @return 临时文件名 + */ + public static String addTempSuffix(final String fileName, String suffix) { + if (StringKit.isBlank(suffix)) { + suffix = ".temp"; + } else { + suffix = StringKit.addPrefixIfNot(suffix, Symbol.DOT); + } + + return fileName + suffix; + } + /** * 清除文件名中的在Windows下不支持的非法字符,包括: \ / : * ? " < > | * @@ -333,9 +333,7 @@ public static boolean isType(final String fileName, final String... extNames) { *
  • 4. .. 和 . 转换为绝对路径,当..多于已有路径时,直接返回根路径
  • *
  • 5. SMB路径保留,如\\127.0.0.0\a\b.zip
  • * - *

    - * 栗子: - * + * 示例: *

          * "/foo//" = "/foo/"
          * "/foo/./" = "/foo/"
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileTailer.java b/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileTailer.java
    index ea49935023..178eb7a250 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileTailer.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileTailer.java
    @@ -25,13 +25,13 @@
      ********************************************************************************/
     package org.miaixz.bus.core.io.file;
     
    +import org.miaixz.bus.core.center.date.culture.en.Units;
     import org.miaixz.bus.core.center.function.ConsumerX;
     import org.miaixz.bus.core.io.watch.SimpleWatcher;
     import org.miaixz.bus.core.io.watch.WatchKind;
     import org.miaixz.bus.core.io.watch.WatchMonitor;
     import org.miaixz.bus.core.lang.Charset;
     import org.miaixz.bus.core.lang.Console;
    -import org.miaixz.bus.core.lang.Fields;
     import org.miaixz.bus.core.lang.Symbol;
     import org.miaixz.bus.core.lang.exception.InternalException;
     import org.miaixz.bus.core.xyz.FileKit;
    @@ -80,9 +80,9 @@ public class FileTailer implements Serializable {
         private final String filePath;
         private final RandomAccessFile randomAccessFile;
         private final ScheduledExecutorService executorService;
    -    private WatchMonitor fileDeleteWatchMonitor;
    +    private WatchMonitor fileWatchMonitor;
     
    -    private boolean stopOnDelete;
    +    private boolean stopOnRemove;
     
         /**
          * 构造,默认UTF-8编码
    @@ -102,7 +102,7 @@ public FileTailer(final File file, final ConsumerX lineHandler) {
          * @param initReadLine 启动时预读取的行数
          */
         public FileTailer(final File file, final ConsumerX lineHandler, final int initReadLine) {
    -        this(file, Charset.UTF_8, lineHandler, initReadLine, Fields.Units.SECOND.getMillis());
    +        this(file, Charset.UTF_8, lineHandler, initReadLine, Units.SECOND.getMillis());
         }
     
         /**
    @@ -113,7 +113,7 @@ public FileTailer(final File file, final ConsumerX lineHandler, final in
          * @param lineHandler 行处理器
          */
         public FileTailer(final File file, final java.nio.charset.Charset charset, final ConsumerX lineHandler) {
    -        this(file, charset, lineHandler, 0, Fields.Units.SECOND.getMillis());
    +        this(file, charset, lineHandler, 0, Units.SECOND.getMillis());
         }
     
         /**
    @@ -153,10 +153,10 @@ private static void checkFile(final File file) {
         /**
          * 设置删除文件后是否退出并抛出异常
          *
    -     * @param stopOnDelete 删除文件后是否退出并抛出异常
    +     * @param stopOnRemove 删除文件后是否退出并抛出异常
          */
    -    public void setStopOnDelete(final boolean stopOnDelete) {
    -        this.stopOnDelete = stopOnDelete;
    +    public void setStopOnRemove(final boolean stopOnRemove) {
    +        this.stopOnRemove = stopOnRemove;
         }
     
         /**
    @@ -187,9 +187,9 @@ public void start(final boolean async) {
             );
     
             // 监听删除
    -        if (stopOnDelete) {
    -            fileDeleteWatchMonitor = WatchKit.of(this.filePath, WatchKind.DELETE.getValue());
    -            fileDeleteWatchMonitor.setWatcher(new SimpleWatcher() {
    +        if (stopOnRemove) {
    +            fileWatchMonitor = WatchKit.of(this.filePath, WatchKind.DELETE.getValue());
    +            fileWatchMonitor.setWatcher(new SimpleWatcher() {
     
                     private static final long serialVersionUID = -1L;
     
    @@ -200,7 +200,7 @@ public void onDelete(final WatchEvent event, final WatchKey key) {
                         throw new InternalException("{} has been deleted", filePath);
                     }
                 });
    -            fileDeleteWatchMonitor.start();
    +            fileWatchMonitor.start();
             }
     
             if (!async) {
    @@ -222,7 +222,7 @@ public void stop() {
                 this.executorService.shutdown();
             } finally {
                 IoKit.closeQuietly(this.randomAccessFile);
    -            IoKit.closeQuietly(this.fileDeleteWatchMonitor);
    +            IoKit.closeQuietly(this.fileWatchMonitor);
             }
         }
     
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileType.java b/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileType.java
    index f34912692f..c8b2051b08 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileType.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/file/FileType.java
    @@ -50,7 +50,821 @@
      */
     public class FileType {
     
    -    private static final Map FILE_TYPE_MAP = new ConcurrentSkipListMap<>();
    +    /**
    +     * Class文件扩展名
    +     */
    +    public static final String CLASS = ".class";
    +    /**
    +     * Jar文件扩展名
    +     */
    +    public static final String JAR = ".jar";
    +    /**
    +     * 在Jar中的路径jar的扩展名形式
    +     */
    +    public static final String JAR_PATH_EXT = ".jar!";
    +    /**
    +     * 微软excel文档
    +     */
    +    public static final String TYPE_XLS = ".xls";
    +    public static final String TYPE_XLSX = ".xlsx";
    +    /**
    +     * 微软word文档
    +     */
    +    public static final String TYPE_DOC = ".doc";
    +    public static final String TYPE_DOCX = ".docx";
    +    /**
    +     * 微软ppt文档
    +     */
    +    public static final String TYPE_PPT = ".ppt";
    +    public static final String TYPE_PPTX = ".pptx";
    +    public static final String TYPE_PPS = ".pps";
    +    public static final String TYPE_PPSX = ".ppsx";
    +    /**
    +     * XML格式
    +     */
    +    public static final String TYPE_XML = ".xml";
    +
    +    /**
    +     * psd格式,Photoshop的专用格式Photoshop
    +     */
    +    public static final String TYPE_PSD = "psd";
    +    /**
    +     * gif格式
    +     */
    +    public static final String TYPE_GIF = "gif";
    +    /**
    +     * jpg格式
    +     */
    +    public static final String TYPE_JPG = "jpg";
    +    /**
    +     * jpeg格式
    +     */
    +    public static final String TYPE_JPEG = "jpeg";
    +    /**
    +     * bmp格式
    +     */
    +    public static final String TYPE_BMP = "bmp";
    +    /**
    +     * png格式
    +     */
    +    public static final String TYPE_PNG = "png";
    +
    +    /**
    +     * csv格式
    +     */
    +    public static final String TYPE_CSV = "csv";
    +
    +    /**
    +     * pdf格式
    +     */
    +    public static final String TYPE_PDF = "pdf";
    +
    +    /**
    +     * dcm格式
    +     */
    +    public static final String TYPE_DCM = "dcm";
    +
    +    /**
    +     * svg格式
    +     */
    +    public static final String TYPE_SVG = "svg";
    +
    +    /**
    +     * txt格式
    +     */
    +    public static final String TYPE_TXT = "txt";
    +
    +    public static final Map FILE_TYPE = new ConcurrentSkipListMap<>() {
    +
    +        /**
    +         * 图片格式
    +         */ {
    +            put(".jpe", "image/jpeg");
    +            put(".jpeg", "image/jpeg");
    +            put(".jpg", "image/jpeg");
    +            put(".bmp", "image/bmp");
    +            put(".png", "image/png");
    +            put(".gif", "image/gif");
    +            put(".jfif", "image/pjpeg");
    +            put(".dib", "image/bmp");
    +            put(".pnz", "image/png");
    +            put(".art", "image/x-jg");
    +            put(".cmx", "image/x-cmx");
    +            put(".ico", "image/x-icon");
    +            put(".ppm", "image/x-portable-pixmap");
    +            put(".mac", "image/x-macpaint");
    +            put(".pbm", "image/x-portable-bitmap");
    +            put(".pgm", "image/x-portable-graymap");
    +            put(".pnm", "image/x-portable-anymap");
    +            put(".pnt", "image/x-macpaint");
    +            put(".pntg", "image/x-macpaint");
    +            put(".qti", "image/x-quicktime");
    +            put(".qtif", "image/x-quicktime");
    +            put(".rgb", "image/x-rgb");
    +            put(".xwd", "image/x-xwindowdump");
    +            put(".ras", "image/x-cmu-raster");
    +            put(".xbm", "image/x-xbitmap");
    +            put(".xpm", "image/x-xpixmap");
    +            put(".cod", "image/cis-cod");
    +            put(".ief", "image/ief");
    +            put(".pct", "image/pict");
    +            put(".pic", "image/pict");
    +            put(".pict", "image/pict");
    +            put(".rf", "image/vnd.rn-realflash");
    +            put(".wbmp", "image/vnd.wap.wbmp");
    +            put(".wdp", "image/vnd.ms-photo");
    +            put(".tif", "image/tiff");
    +            put(".tiff", "image/tiff");
    +        }
    +
    +        /**
    +         * 文档
    +         */ {
    +            // txt
    +            put(".txt", "text/plain");
    +            // css
    +            put(".css", "text/css");
    +            // html
    +            put(".htm", "text/html");
    +            put(".html", "text/html");
    +            put(".shtml", "text/html");
    +            // xml
    +            put(".wsdl", "text/xml");
    +            put(".xml", "text/xml");
    +            // pdf
    +            put(".pdf", "application/pdf");
    +            // ppt
    +            put(".ppt", "application/vnd.ms-powerpoint");
    +            put(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
    +            // doc
    +            put(".doc", "application/msword");
    +            put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    +            // excel
    +            put(".xlm", "application/vnd.ms-excel");
    +            put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    +            // not
    +            put(".one", "application/onenote");
    +            // access
    +            put(".accdb", "application/msaccess");
    +            // visio
    +            put(".vsd", "application/vnd.visio");
    +            /** 不常用 */
    +            put(".323", "text/h323");
    +            put(".rqy", "text/x-ms-rqy");
    +            put(".rtx", "text/richtext");
    +            put(".rc", "text/plain");
    +            put(".XOML", "text/plain");
    +            put(".sln", "text/plain");
    +            put(".rgs", "text/plain");
    +            put(".pkgdef", "text/plain");
    +            put(".pkgundef", "text/plain");
    +            put(".sol", "text/plain");
    +            put(".sor", "text/plain");
    +            put(".srf", "text/plain");
    +            put(".xdr", "text/plain");
    +            put(".rc2", "text/plain");
    +            put(".rct", "text/plain");
    +            put(".s", "text/plain");
    +            put(".asm", "text/plain");
    +            put(".c", "text/plain");
    +            put(".cc", "text/plain");
    +            put(".cd", "text/plain");
    +            put(".def", "text/plain");
    +            put(".cxx", "text/plain");
    +            put(".cnf", "text/plain");
    +            put(".cpp", "text/plain");
    +            put(".cs", "text/plain");
    +            put(".csdproj", "text/plain");
    +            put(".csproj", "text/plain");
    +            put(".dbproj", "text/plain");
    +            put(".bas", "text/plain");
    +            put(".dsw", "text/plain");
    +            put(".inc", "text/plain");
    +            put(".hxx", "text/plain");
    +            put(".i", "text/plain");
    +            put(".idl", "text/plain");
    +            put(".inl", "text/plain");
    +            put(".lst", "text/plain");
    +            put(".jsxbin", "text/plain");
    +            put(".mak", "text/plain");
    +            put(".map", "text/plain");
    +            put(".h", "text/plain");
    +            put(".hpp", "text/plain");
    +            put(".ipproj", "text/plain");
    +            put(".mk", "text/plain");
    +            put(".odh", "text/plain");
    +            put(".odl", "text/plain");
    +            put(".tsv", "text/tab-separated-values");
    +            put(".uls", "text/iuls");
    +            put(".user", "text/plain");
    +            put(".tlh", "text/plain");
    +            put(".tli", "text/plain");
    +            put(".vb", "text/plain");
    +            put(".vbdproj", "text/plain");
    +            put(".vbproj", "text/plain");
    +            put(".vcs", "text/plain");
    +            put(".vddproj", "text/plain");
    +            put(".vdp", "text/plain");
    +            put(".vdproj", "text/plain");
    +            put(".vspscc", "text/plain");
    +            put(".vsscc", "text/plain");
    +            put(".vssscc", "text/plain");
    +            put(".hxt", "text/html");
    +            put(".vssettings", "text/xml");
    +            put(".vstemplate", "text/xml");
    +            put(".vml", "text/xml");
    +            put(".vsct", "text/xml");
    +            put(".vsixlangpack", "text/xml");
    +            put(".vsixmanifest", "text/xml");
    +            put(".exe.config", "text/xml");
    +            put(".disco", "text/xml");
    +            put(".dll.config", "text/xml");
    +            put(".AddIn", "text/xml");
    +            put(".dtd", "text/xml");
    +            put(".dtsConfig", "text/xml");
    +            put(".mno", "text/xml");
    +            put(".xrm-ms", "text/xml");
    +            put(".xsd", "text/xml");
    +            put(".xsf", "text/xml");
    +            put(".xsl", "text/xml");
    +            put(".xslt", "text/xml");
    +            put(".SSISDeploymentManifest", "text/xml");
    +            put(".iqy", "text/x-ms-iqy");
    +            put(".contact", "text/x-ms-contact");
    +            put(".etx", "text/x-setext");
    +            put(".hdml", "text/x-hdml");
    +            put(".htc", "text/x-component");
    +            put(".group", "text/x-ms-group");
    +            put(".vcf", "text/x-vcard");
    +            put(".odc", "text/x-ms-odc");
    +            put(".qht", "text/x-html-insertion");
    +            put(".qhtm", "text/x-html-insertion");
    +            put(".wml", "text/vnd.wap.wml");
    +            put(".wmls", "text/vnd.wap.wmlscript");
    +            put(".vbs", "text/vbscript");
    +            put(".jsx", "text/jscript");
    +            put(".sct", "text/scriptlet");
    +            put(".csv", "text/csv");
    +            put(".323", "text/h323");
    +            put(".dlm", "text/dlm");
    +            put(".htt", "text/webviewhtml");
    +            put(".wsc", "text/scriptlet");
    +            put(".sgml", "text/sgml");
    +            // ppt
    +            put(".pot", "application/vnd.ms-powerpoint");
    +            put(".ppa", "application/vnd.ms-powerpoint");
    +            put(".pwz", "application/vnd.ms-powerpoint");
    +            put(".pps", "application/vnd.ms-powerpoint");
    +            put(".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12");
    +            put(".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12");
    +            put(".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12");
    +            put(".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12");
    +            put(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
    +            put(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
    +            put(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
    +            // doc
    +            put(".wbk", "application/msword");
    +            put(".wiz", "application/msword");
    +            put(".dot", "application/msword");
    +            put(".docm", "application/vnd.ms-word.document.macroEnabled.12");
    +            put(".dotm", "application/vnd.ms-word.template.macroEnabled.12");
    +            put(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
    +            // excel
    +            put(".xla", "application/vnd.ms-excel");
    +            put(".xlc", "application/vnd.ms-excel");
    +            put(".xld", "application/vnd.ms-excel");
    +            put(".xlk", "application/vnd.ms-excel");
    +            put(".xll", "application/vnd.ms-excel");
    +            put(".xls", "application/vnd.ms-excel");
    +            put(".xlt", "application/vnd.ms-excel");
    +            put(".xlw", "application/vnd.ms-excel");
    +            put(".slk", "application/vnd.ms-excel");
    +            put(".xlam", "application/vnd.ms-excel.addin.macroEnabled.12");
    +            put(".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12");
    +            put(".xltm", "application/vnd.ms-excel.template.macroEnabled.12");
    +            put(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12");
    +            put(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
    +            // access
    +            put(".accde", "application/msaccess");
    +            put(".accdt", "application/msaccess");
    +            put(".adp", "application/msaccess");
    +            put(".mda", "application/msaccess");
    +            put(".mde", "application/msaccess");
    +            put(".accda", "application/msaccess.addin");
    +            put(".accdc", "application/msaccess.cab");
    +            put(".accdr", "application/msaccess.runtime");
    +            put(".accdw", "application/msaccess.webapplication");
    +            put(".accft", "application/msaccess.ftemplate");
    +            put(".ade", "application/msaccess");
    +            // visio
    +            put(".thmx", "application/vnd.ms-officetheme");
    +            put(".vdx", "application/vnd.ms-visio.viewer");
    +            put(".vss", "application/vnd.visio");
    +            put(".vst", "application/vnd.visio");
    +            put(".vsw", "application/vnd.visio");
    +            put(".vsx", "application/vnd.visio");
    +            put(".vtx", "application/vnd.visio");
    +            // note类型文本
    +            put(".onea", "application/onenote");
    +            put(".onepkg", "application/onenote");
    +            put(".onetmp", "application/onenote");
    +            put(".onetoc", "application/onenote");
    +            put(".onetoc2", "application/onenote");
    +            // 其他
    +            put(".pko", "application/vnd.ms-pki.pko");
    +            put(".cat", "application/vnd.ms-pki.seccat");
    +            put(".sst", "application/vnd.ms-pki.certstore");
    +            put(".stl", "application/vnd.ms-pki.stl");
    +            put(".mpf", "application/vnd.ms-mediapackage");
    +            put(".mpp", "application/vnd.ms-project");
    +            put(".wpl", "application/vnd.ms-wpl");
    +            put(".wks", "application/vnd.ms-works");
    +            put(".wps", "application/vnd.ms-works");
    +            put(".wcm", "application/vnd.ms-works");
    +            put(".wdb", "application/vnd.ms-works");
    +            put(".calx", "application/vnd.ms-office.calx");
    +            put(".xps", "application/vnd.ms-xpsdocument");
    +            put(".odp", "application/vnd.oasis.opendocument.presentation");
    +            put(".odt", "application/vnd.oasis.opendocument.text");
    +            put(".rm", "application/vnd.rn-realmedia");
    +            put(".rmp", "application/vnd.rn-rn_music_package");
    +            put(".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide");
    +            put(".air", "application/vnd.adobe.air-application-installer-package+zip");
    +            put(".wmlsc", "application/vnd.wap.wmlscriptc");
    +            put(".wmlc", "application/vnd.wap.wmlc");
    +            put(".m13", "application/x-msmediaview");
    +            put(".m14", "application/x-msmediaview");
    +            put(".wmf", "application/x-msmetafile");
    +            put(".wri", "application/x-mswrite");
    +            put(".mdb", "application/x-msaccess");
    +            put(".wmd", "application/x-ms-wmd");
    +            put(".wmz", "application/x-ms-wmz");
    +        }
    +
    +        /**
    +         * 压缩文档
    +         */ {
    +            put(".7z", "application/x-7z-compressed");
    +            put(".z", "application/x-compress");
    +            put(".zip", "application/x-zip-compressed");
    +            put(".tgz", "application/x-compressed");
    +            put(".jar", "application/java-archive");
    +            put(".rar", "application/octet-stream");
    +            put(".war", "application/octet-stream");
    +            put(".tar", "application/x-tar");
    +        }
    +
    +
    +        /**
    +         * 视频
    +         */ {
    +            put(".flv", "video/x-flv");
    +            put(".3gp", "video/3gpp");
    +            put(".avi", "video/x-msvideo");
    +            put(".3g2", "video/3gpp2");
    +            put(".3gp2", "video/3gpp2");
    +            put(".3gpp", "video/3gpp");
    +            put(".asf", "video/x-ms-asf");
    +            put(".asr", "video/x-ms-asf");
    +            put(".asx", "video/x-ms-asf");
    +            put(".dif", "video/x-dv");
    +            put(".mod", "video/mpeg");
    +            put(".mov", "video/quicktime");
    +            put(".movie", "video/x-sgi-movie");
    +            put(".mp2", "video/mpeg");
    +            put(".mp2v", "video/mpeg");
    +            put(".dv", "video/x-dv");
    +            put(".IVF", "video/x-ivf");
    +            put(".lsf", "video/x-la-asf");
    +            put(".lsx", "video/x-la-asf");
    +            put(".m1v", "video/mpeg");
    +            put(".m2t", "video/vnd.dlna.mpeg-tts");
    +            put(".m2ts", "video/vnd.dlna.mpeg-tts");
    +            put(".m2v", "video/mpeg");
    +            put(".m4v", "video/x-m4v");
    +            put(".mp4", "video/mp4");
    +            put(".mp4v", "video/mp4");
    +            put(".mpa", "video/mpeg");
    +            put(".mpe", "video/mpeg");
    +            put(".mpeg", "video/mpeg");
    +            put(".wm", "video/x-ms-wm");
    +            put(".mpg", "video/mpeg");
    +            put(".mpv2", "video/mpeg");
    +            put(".mqv", "video/quicktime");
    +            put(".nsc", "video/x-ms-asf");
    +            put(".qt", "video/quicktime");
    +            put(".ts", "video/vnd.dlna.mpeg-tts");
    +            put(".vbk", "video/mpeg");
    +            put(".wmp", "video/x-ms-wmp");
    +            put(".wmv", "video/x-ms-wmv");
    +            put(".wmx", "video/x-ms-wmx");
    +            put(".wvx", "video/x-ms-wvx");
    +            put(".mts", "video/vnd.dlna.mpeg-tts");
    +            put(".tts", "video/vnd.dlna.mpeg-tts");
    +        }
    +
    +        /**
    +         * 音频
    +         */ {
    +            put(".mp3", "audio/mpeg");
    +            put(".wma", "audio/x-ms-wma");
    +            put(".aa", "audio/audible");
    +            put(".AAC", "audio/aac");
    +            put(".aax", "audio/vnd.audible.aax");
    +            put(".ac3", "audio/ac3");
    +            put(".ADT", "audio/vnd.dlna.adts");
    +            put(".ADTS", "audio/aac");
    +            put(".aif", "audio/x-aiff");
    +            put(".aifc", "audio/aiff");
    +            put(".aiff", "audio/aiff");
    +            put(".cdda", "audio/aiff");
    +            put(".au", "audio/basic");
    +            put(".m3u", "audio/x-mpegurl");
    +            put(".m3u8", "audio/x-mpegurl");
    +            put(".m4a", "audio/m4a");
    +            put(".m4b", "audio/m4b");
    +            put(".m4p", "audio/m4p");
    +            put(".m4r", "audio/x-m4r");
    +            put(".caf", "audio/x-caf");
    +            put(".gsm", "audio/x-gsm");
    +            put(".mid", "audio/mid");
    +            put(".midi", "audio/mid");
    +            put(".pls", "audio/scpls");
    +            put(".ra", "audio/x-pn-realaudio");
    +            put(".ram", "audio/x-pn-realaudio");
    +            put(".rmi", "audio/mid");
    +            put(".rpm", "audio/x-pn-realaudio-plugin");
    +            put(".sd2", "audio/x-sd2");
    +            put(".smd", "audio/x-smd");
    +            put(".smx", "audio/x-smd");
    +            put(".smz", "audio/x-smd");
    +            put(".snd", "audio/basic");
    +            put(".wav", "audio/wav");
    +            put(".wave", "audio/wav");
    +            put(".wax", "audio/x-ms-wax");
    +        }
    +
    +        /**
    +         * 其他
    +         */ {
    +            // xml类型文件
    +            put(".asa", "application/xml");
    +            put(".asax", "application/xml");
    +            put(".ascx", "application/xml");
    +            put(".ashx", "application/xml");
    +            put(".asmx", "application/xml");
    +            put(".aspx", "application/xml");
    +            put(".config", "application/xml");
    +            put(".coverage", "application/xml");
    +            put(".datasource", "application/xml");
    +            put(".dgml", "application/xml");
    +            put(".generictest", "application/xml");
    +            put(".hxa", "application/xml");
    +            put(".hxc", "application/xml");
    +            put(".hxe", "application/xml");
    +            put(".hxf", "application/xml");
    +            put(".hxk", "application/xml");
    +            put(".svc", "application/xml");
    +            put(".rdlc", "application/xml");
    +            put(".resx", "application/xml");
    +            put(".ruleset", "application/xml");
    +            put(".settings", "application/xml");
    +            put(".snippet", "application/xml");
    +            put(".testrunconfig", "application/xml");
    +            put(".testsettings", "application/xml");
    +            put(".xss", "application/xml");
    +            put(".xsc", "application/xml");
    +            put(".hxv", "application/xml");
    +            put(".loadtest", "application/xml");
    +            put(".trx", "application/xml");
    +            put(".psess", "application/xml");
    +            put(".mtx", "application/xml");
    +            put(".master", "application/xml");
    +            put(".orderedtest", "application/xml");
    +            put(".sitemap", "application/xml");
    +            put(".skin", "application/xml");
    +            put(".vscontent", "application/xml");
    +            put(".vsmdi", "application/xml");
    +            put(".webtest", "application/xml");
    +            put(".wiq", "application/xml");
    +            put(".xmta", "application/xml");
    +            put(".filters", "Application/xml");
    +            put(".vcproj", "Application/xml");
    +            put(".vcxproj", "Application/xml");
    +            // 文件流类型
    +            put(".thn", "application/octet-stream");
    +            put(".toc", "application/octet-stream");
    +            put(".ttf", "application/octet-stream");
    +            put(".u32", "application/octet-stream");
    +            put(".xsn", "application/octet-stream");
    +            put(".xtp", "application/octet-stream");
    +            put(".aaf", "application/octet-stream");
    +            put(".aca", "application/octet-stream");
    +            put(".afm", "application/octet-stream");
    +            put(".asd", "application/octet-stream");
    +            put(".asi", "application/octet-stream");
    +            put(".cab", "application/octet-stream");
    +            put(".bin", "application/octet-stream");
    +            put(".chm", "application/octet-stream");
    +            put(".cur", "application/octet-stream");
    +            put(".dat", "application/octet-stream");
    +            put(".deploy", "application/octet-stream");
    +            put(".dwp", "application/octet-stream");
    +            put(".dsp", "application/octet-stream");
    +            put(".emz", "application/octet-stream");
    +            put(".eot", "application/octet-stream");
    +            put(".exe", "application/octet-stream");
    +            put(".hxd", "application/octet-stream");
    +            put(".hxh", "application/octet-stream");
    +            put(".hxi", "application/octet-stream");
    +            put(".hxq", "application/octet-stream");
    +            put(".hxr", "application/octet-stream");
    +            put(".hxs", "application/octet-stream");
    +            put(".hxw", "application/octet-stream");
    +            put(".ics", "application/octet-stream");
    +            put(".hhk", "application/octet-stream");
    +            put(".hhp", "application/octet-stream");
    +            put(".inf", "application/octet-stream");
    +            put(".fla", "application/octet-stream");
    +            put(".java", "application/octet-stream");
    +            put(".jpb", "application/octet-stream");
    +            put(".mdp", "application/octet-stream");
    +            put(".mix", "application/octet-stream");
    +            put(".msi", "application/octet-stream");
    +            put(".mso", "application/octet-stream");
    +            put(".ocx", "application/octet-stream");
    +            put(".pcx", "application/octet-stream");
    +            put(".pcz", "application/octet-stream");
    +            put(".pfb", "application/octet-stream");
    +            put(".pfm", "application/octet-stream");
    +            put(".lzh", "application/octet-stream");
    +            put(".lpk", "application/octet-stream");
    +            put(".qxd", "application/octet-stream");
    +            put(".prm", "application/octet-stream");
    +            put(".prx", "application/octet-stream");
    +            put(".psd", "application/octet-stream");
    +            put(".psm", "application/octet-stream");
    +            put(".psp", "application/octet-stream");
    +            put(".sea", "application/octet-stream");
    +            put(".smi", "application/octet-stream");
    +            put(".snp", "application/octet-stream");
    +            put(".acx", "application/internet-property-stream");
    +            put(".ai", "application/postscript");
    +            put(".atom", "application/atom+xml");
    +            put(".axs", "application/olescript");
    +            put(".ustar", "application/x-ustar");
    +            put(".bcpio", "application/x-bcpio");
    +            put(".xhtml", "application/xhtml+xml");
    +            put(".crl", "application/pkix-crl");
    +            put(".amc", "application/x-mpeg");
    +            put(".cdf", "application/x-cdf");
    +            put(".cer", "application/x-x509-ca-cert");
    +            put(".class", "application/x-java-applet");
    +            put(".clp", "application/x-msclip");
    +            put(".application", "application/x-ms-application");
    +            put(".adobebridge", "application/x-bridge-url");
    +            put(".cpio", "application/x-cpio");
    +            put(".crd", "application/x-mscardfile");
    +            put(".crt", "application/x-x509-ca-cert");
    +            put(".der", "application/x-x509-ca-cert");
    +            put(".csh", "application/x-csh");
    +            put(".dcr", "application/x-director");
    +            put(".dir", "application/x-director");
    +            put(".dll", "application/x-msdownload");
    +            put(".dvi", "application/x-dvi");
    +            put(".dwf", "drawing/x-dwf");
    +            put(".dxr", "application/x-director");
    +            put(".flr", "x-world/x-vrml");
    +            put(".gtar", "application/x-gtar");
    +            put(".gz", "application/x-gzip");
    +            put(".hdf", "application/x-hdf");
    +            put(".hhc", "application/x-oleobject");
    +            put(".mmf", "application/x-smaf");
    +            put(".mny", "application/x-msmoney");
    +            put(".ms", "application/x-troff-ms");
    +            put(".mvb", "application/x-msmediaview");
    +            put(".mvc", "application/x-miva-compiled");
    +            put(".mxp", "application/x-mmxp");
    +            put(".nc", "application/x-netcdf");
    +            put(".pcast", "application/x-podcast");
    +            put(".ins", "application/x-internet-signup");
    +            put(".jnlp", "application/x-java-jnlp-file");
    +            put(".js", "application/x-javascript");
    +            put(".latex", "application/x-latex");
    +            put(".lit", "application/x-ms-reader");
    +            put(".manifest", "application/x-ms-manifest");
    +            put(".man", "application/x-troff-man");
    +            put(".me", "application/x-troff-me");
    +            put(".mfp", "application/x-shockwave-flash");
    +            put(".pfx", "application/x-pkcs12");
    +            put(".p7r", "application/x-pkcs7-certreqresp");
    +            put(".p12", "application/x-pkcs12");
    +            put(".p7b", "application/x-pkcs7-certificates");
    +            put(".pma", "application/x-perfmon");
    +            put(".pmc", "application/x-perfmon");
    +            put(".pml", "application/x-perfmon");
    +            put(".pmr", "application/x-perfmon");
    +            put(".pmw", "application/x-perfmon");
    +            put(".iii", "application/x-iphone");
    +            put(".ipa", "application/x-itunes-ipa");
    +            put(".ipg", "application/x-itunes-ipg");
    +            put(".ipsw", "application/x-itunes-ipsw");
    +            put(".isp", "application/x-internet-signup");
    +            put(".ite", "application/x-itunes-ite");
    +            put(".itlp", "application/x-itunes-itlp");
    +            put(".itms", "application/x-itunes-itms");
    +            put(".itpc", "application/x-itunes-itpc");
    +            put(".eps", "application/postscript");
    +            put(".etl", "application/etl");
    +            put(".evy", "application/envoy");
    +            put(".fdf", "application/vnd.fdf");
    +            put(".fif", "application/fractals");
    +            put(".fsscript", "application/fsharp-script");
    +            put(".fsx", "application/fsharp-script");
    +            put(".hlp", "application/winhlp");
    +            put(".hqx", "application/mac-binhex40");
    +            put(".hta", "application/hta");
    +            put(".jck", "application/liquidmotion");
    +            put(".jcz", "application/liquidmotion");
    +            put(".library-ms", "application/windows-library+xml");
    +            put(".mht", "message/rfc822");
    +            put(".mhtml", "message/rfc822");
    +            put(".nws", "message/rfc822");
    +            put(".eml", "message/rfc822");
    +            put(".oda", "application/oda");
    +            put(".ods", "application/oleobject");
    +            put(".osdx", "application/opensearchdescription+xml");
    +            put(".p10", "application/pkcs10");
    +            put(".p7c", "application/pkcs7-mime");
    +            put(".p7m", "application/pkcs7-mime");
    +            put(".p7s", "application/pkcs7-signature");
    +            put(".prf", "application/pics-rules");
    +            put(".ps", "application/postscript");
    +            put(".psc1", "application/PowerShell");
    +            put(".pub", "application/x-mspublisher");
    +            put(".qtl", "application/x-quicktimeplayer");
    +            put(".rat", "application/rat-file");
    +            put(".roff", "application/x-troff");
    +            put(".rtf", "application/rtf");
    +            put(".safariextz", "application/x-safari-safariextz");
    +            put(".scd", "application/x-msschedule");
    +            put(".sdp", "application/sdp");
    +            put(".searchConnector-ms", "application/windows-search-connector+xml");
    +            put(".setpay", "application/set-payment-initiation");
    +            put(".setreg", "application/set-registration-initiation");
    +            put(".sgimb", "application/x-sgimb");
    +            put(".sh", "application/x-sh");
    +            put(".shar", "application/x-shar");
    +            put(".sit", "application/x-stuffit");
    +            put(".slupkg-ms", "application/x-ms-license");
    +            put(".spc", "application/x-pkcs7-certificates");
    +            put(".spl", "application/futuresplash");
    +            put(".src", "application/x-wais-source");
    +            put(".ssm", "application/streamingmedia");
    +            put(".sv4cpio", "application/x-sv4cpio");
    +            put(".sv4crc", "application/x-sv4crc");
    +            put(".swf", "application/x-shockwave-flash");
    +            put(".t", "application/x-troff");
    +            put(".tcl", "application/x-tcl");
    +            put(".tex", "application/x-tex");
    +            put(".texi", "application/x-texinfo");
    +            put(".texinfo", "application/x-texinfo");
    +            put(".tr", "application/x-troff");
    +            put(".trm", "application/x-msterminal");
    +            put(".vsi", "application/ms-vsi");
    +            put(".vsix", "application/vsix");
    +            put(".vsto", "application/x-ms-vsto");
    +            put(".webarchive", "application/x-safari-webarchive");
    +            put(".WLMP", "application/wlmoviemaker");
    +            put(".wlpginstall", "application/x-wlpg-detect");
    +            put(".wlpginstall3", "application/x-wlpg3-detect");
    +            put(".x", "application/directx");
    +            put(".xaml", "application/xaml+xml");
    +            put(".xht", "application/xhtml+xml");
    +            put(".xap", "application/x-silverlight-app");
    +            put(".xbap", "application/x-ms-xbap");
    +            put(".xaf", "x-world/x-vrml");
    +            put(".xof", "x-world/x-vrml");
    +            put(".wrl", "x-world/x-vrml");
    +            put(".wrz", "x-world/x-vrml");
    +        }
    +
    +        /**
    +         * 文件信息头
    +         */ {
    +            // JPEG (jpg)
    +            put("ffd8ffe", "jpg");
    +            // PNG (png)
    +            put("89504e470d0a1a0a0000", "png");
    +            // GIF (gif)
    +            put("47494638396126026f01", "gif");
    +            // TIFF (tif)
    +            put("49492a00227105008037", "tif");
    +            // 位图(bmp)
    +            put("424d", "bmp");
    +            // CAD (dwg)
    +            put("41433130313500000000", "dwg");
    +            put("3c21444f435459504520", "html");
    +            put("3c21646f637479706520", "htm");
    +            put("48544d4c207b0d0a0942", "css");
    +            put("696b2e71623d696b2e71", "js");
    +            // Rich Text Format (rtf)
    +            put("7b5c727466315c616e73", "rtf");
    +            // Photoshop (psd)
    +            put("38425053000100000000", "psd");
    +            // Email [Outlook Express 6] (eml)
    +            put("46726f6d3a203d3f6762", "eml");
    +            // MS Excel 注意:word、msi 和 excel的文件头一样
    +            put("d0cf11e0a1b11ae10000", "doc");
    +            // Visio 绘图
    +            put("d0cf11e0a1b11ae10000", "vsd");
    +            // MS Access (mdb)
    +            put("5374616E64617264204A", "mdb");
    +            put("252150532D41646F6265", "ps");
    +            // Adobe Acrobat (pdf)
    +            put("255044462d312e", "pdf");
    +            // rmvb/rm相同
    +            put("2e524d46000000120001", "rmvb");
    +            // flv与f4v相同
    +            put("464c5601050000000900", "flv");
    +            put("0000001C66747970", "mp4");
    +            put("00000020667479706", "mp4");
    +            put("00000018667479706D70", "mp4");
    +            put("49443303000000002176", "mp3");
    +            put("000001ba210001000180", "mpg");
    +            put("3026b2758e66cf11a6d9", "wmv");
    +            put("52494646e27807005741", "wav");
    +            put("52494646d07d60074156", "avi");
    +            put("4d546864000000060001", "mid");
    +            put("526172211a0700cf9073", "rar");
    +            put("235468697320636f6e66", "ini");
    +            put("504B03040a0000000000", "jar");
    +            put("504B0304140008000800", "jar");
    +            put("504B0304140006000800", "docx");
    +            put("504B0304140006000800", "xlsx");
    +            put("D0CF11E0A1B11AE10", "xls");
    +            put("504B0304", "zip");
    +            put("4d5a9000030000000400", "exe");
    +            put("3c25402070616765206c", "jsp");
    +            put("4d616e69666573742d56", "mf");
    +            put("3c3f786d6c2076657273", "xml");
    +            put("494e5345525420494e54", "sql");
    +            put("7061636b616765207765", "java");
    +            put("406563686f206f66660d", "bat");
    +            put("1f8b0800000000000000", "gz");
    +            put("6c6f67346a2e726f6f74", "properties");
    +            put("cafebabe0000002e0041", "class");
    +            put("49545346030000006000", "chm");
    +            put("04000000010000001300", "mxp");
    +            // WPS文字wps、表格et、演示dps都是一样的
    +            put("d0cf11e0a1b11ae10000", "wps");
    +            put("6431303a637265617465", "torrent");
    +            // Quicktime (mov)
    +            put("6D6F6F76", "mov");
    +            // WordPerfect (wpd)
    +            put("FF575043", "wpd");
    +            // Outlook Express (dbx)
    +            put("CFAD12FEC5FD746F", "dbx");
    +            // Outlook (pst)
    +            put("2142444E", "pst");
    +            // Quicken (qdf)
    +            put("AC9EBD8F", "qdf");
    +            // Windows Password (pwl)
    +            put("E3828596", "pwl");
    +            // Real Audio (ram)
    +            put("2E7261FD", "ram");
    +            put("52494646", "webp");
    +
    +            // 2-byte signatures
    +            // https://github.com/sindresorhus/file-type/blob/main/core.js#L90
    +            put("424D", "bmp"); // 位图(bmp)
    +            put("0B77", "ac3");
    +            put("7801", "dmg");
    +            put("4D5A", "exe");
    +            put("1FA0", "Z");
    +            put("1F9D", "Z");
    +
    +            // 3-byte signatures
    +            // https://github.com/sindresorhus/file-type/blob/main/core.js#L149
    +            put("474946", "gif"); // GIF (gif)
    +            put("FFd8FF", "jpg"); // JPEG (jpg)
    +            put("4949BC", "jxr"); // jxr
    +            put("1F8B08", "gz"); //  gzip
    +            put("425A68", "bz2"); // bz2
    +
    +            // check string
    +            put(HexKit.encodeString("MP+"), "mpc");
    +            put(HexKit.encodeString("FLIF"), "flif");
    +            put(HexKit.encodeString("8BPS"), "psd");// Photoshop (psd)
    +            put(HexKit.encodeString("MPCK"), "mpc");
    +            put(HexKit.encodeString("FORM"), "aif");// Musepack, SV8
    +            put(HexKit.encodeString("icns"), "icns");
    +        }
    +    };
    +
    +    private FileType() {
    +
    +    }
     
         /**
          * 增加文件类型映射
    @@ -61,7 +875,7 @@ public class FileType {
          * @return 之前已经存在的文件扩展名
          */
         public static String putFileType(final String fileStreamHexHead, final String extName) {
    -        return FILE_TYPE_MAP.put(fileStreamHexHead, extName);
    +        return FILE_TYPE.put(fileStreamHexHead, extName);
         }
     
         /**
    @@ -71,7 +885,7 @@ public static String putFileType(final String fileStreamHexHead, final String ex
          * @return 移除的文件扩展名
          */
         public static String removeFileType(final String fileStreamHexHead) {
    -        return FILE_TYPE_MAP.remove(fileStreamHexHead);
    +        return FILE_TYPE.remove(fileStreamHexHead);
         }
     
         /**
    @@ -81,7 +895,7 @@ public static String removeFileType(final String fileStreamHexHead) {
          * @return 文件类型,未找到为{@code null}
          */
         public static String getType(final String fileStreamHexHead) {
    -        for (final Entry fileTypeEntry : FILE_TYPE_MAP.entrySet()) {
    +        for (final Entry fileTypeEntry : FILE_TYPE.entrySet()) {
                 if (StringKit.startWithIgnoreCase(fileStreamHexHead, fileTypeEntry.getKey())) {
                     return fileTypeEntry.getValue();
                 }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/file/LineSeparator.java b/bus-core/src/main/java/org/miaixz/bus/core/io/file/LineSeparator.java
    index cf5d3d5a44..72e020f22e 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/file/LineSeparator.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/file/LineSeparator.java
    @@ -41,6 +41,7 @@
      * @since Java 17+
      */
     public enum LineSeparator {
    +
         /**
          * Mac系统换行符:"\r"
          */
    @@ -63,4 +64,5 @@ public enum LineSeparator {
         public String getValue() {
             return this.value;
         }
    +
     }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathCopier.java b/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathCopier.java
    index b22e688f62..a697a1d96d 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathCopier.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathCopier.java
    @@ -99,7 +99,7 @@ public static PathCopier of(final Path src, final Path target, final CopyOption[
          * @return Path
          * @throws InternalException IO异常
          */
    -    private static Path _copyContent(final Path src, final Path target, final CopyOption... options) throws InternalException {
    +    private static Path copyContent(final Path src, final Path target, final CopyOption... options) throws InternalException {
             try {
                 Files.walkFileTree(src, new CopyVisitor(src, target, options));
             } catch (final IOException e) {
    @@ -152,14 +152,14 @@ public Path copy() throws InternalException {
             if (PathResolve.isDirectory(src)) {
                 if (PathResolve.exists(target, false)) {
                     if (PathResolve.isDirectory(target)) {
    -                    return _copyContent(src, target.resolve(src.getFileName()), options);
    +                    return copyContent(src, target.resolve(src.getFileName()), options);
                     } else {
                         // src目录,target文件,无法拷贝
                         throw new IllegalArgumentException("Can not copier directory to a file!");
                     }
                 } else {
                     // 目标不存在,按照重命名对待
    -                return _copyContent(src, target, options);
    +                return copyContent(src, target, options);
                 }
             }
             return copyFile(src, target, options);
    @@ -182,7 +182,7 @@ public Path copy() throws InternalException {
          */
         public Path copyContent() throws InternalException {
             if (PathResolve.isDirectory(src, false)) {
    -            return _copyContent(src, target, options);
    +            return copyContent(src, target, options);
             }
             return copyFile(src, target, options);
         }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathMover.java b/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathMover.java
    index 426cf7a6e2..699d040983 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathMover.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathMover.java
    @@ -152,7 +152,7 @@ public Path move() throws IllegalArgumentException {
                 // 移动失败,可能是跨分区移动导致的,采用递归移动方式
                 walkMove(src, target, options);
                 // 移动后删除空目录
    -            PathResolve.del(src);
    +            PathResolve.remove(src);
                 return target;
             }
         }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathDeleter.java b/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathRemover.java
    similarity index 90%
    rename from bus-core/src/main/java/org/miaixz/bus/core/io/file/PathDeleter.java
    rename to bus-core/src/main/java/org/miaixz/bus/core/io/file/PathRemover.java
    index 8ebdf4a537..da3082d843 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathDeleter.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathRemover.java
    @@ -41,7 +41,7 @@
      * @author Kimi Liu
      * @since Java 17+
      */
    -public class PathDeleter {
    +public class PathRemover {
     
         private final Path path;
     
    @@ -50,7 +50,7 @@ public class PathDeleter {
          *
          * @param path 文件或目录,不能为{@code null}且必须存在
          */
    -    public PathDeleter(final Path path) {
    +    public PathRemover(final Path path) {
             this.path = Assert.notNull(path, "Path must be not null !");
         }
     
    @@ -60,8 +60,8 @@ public PathDeleter(final Path path) {
          * @param src 源文件或目录
          * @return {@code PathMover}
          */
    -    public static PathDeleter of(final Path src) {
    -        return new PathDeleter(src);
    +    public static PathRemover of(final Path src) {
    +        return new PathRemover(src);
         }
     
         /**
    @@ -69,7 +69,7 @@ public static PathDeleter of(final Path src) {
          *
          * @param path 目录路径
          */
    -    private static void _del(final Path path) {
    +    private static void remove(final Path path) {
             try {
                 Files.walkFileTree(path, DeleteVisitor.INSTANCE);
             } catch (final IOException e) {
    @@ -83,7 +83,7 @@ private static void _del(final Path path) {
          * @param path 文件对象
          * @throws InternalException IO异常
          */
    -    private static void delFile(final Path path) throws InternalException {
    +    private static void removeFile(final Path path) throws InternalException {
             try {
                 Files.delete(path);
             } catch (final IOException e) {
    @@ -104,16 +104,16 @@ private static void delFile(final Path path) throws InternalException {
          *
          * @throws InternalException IO异常
          */
    -    public void del() throws InternalException {
    +    public void remove() throws InternalException {
             final Path path = this.path;
             if (Files.notExists(path)) {
                 return;
             }
     
             if (PathResolve.isDirectory(path)) {
    -            _del(path);
    +            remove(path);
             } else {
    -            delFile(path);
    +            removeFile(path);
             }
         }
     
    @@ -122,7 +122,7 @@ public void del() throws InternalException {
          */
         public void clean() {
             try (final Stream list = Files.list(this.path)) {
    -            list.forEach(PathResolve::del);
    +            list.forEach(PathResolve::remove);
             } catch (final IOException e) {
                 throw new InternalException(e);
             }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathResolve.java b/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathResolve.java
    index d805e75467..5f116c1147 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathResolve.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/file/PathResolve.java
    @@ -217,8 +217,8 @@ public static void walkFiles(final Path start, int maxDepth, final boolean isFol
          * @param path 文件对象
          * @throws InternalException IO异常
          */
    -    public static void del(final Path path) throws InternalException {
    -        PathDeleter.of(path).del();
    +    public static void remove(final Path path) throws InternalException {
    +        PathRemover.of(path).remove();
         }
     
         /**
    @@ -227,7 +227,7 @@ public static void del(final Path path) throws InternalException {
          * @param path 目录路径
          */
         public static void clean(final Path path) {
    -        PathDeleter.of(path).clean();
    +        PathRemover.of(path).clean();
         }
     
         /**
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/sink/DeflaterSink.java b/bus-core/src/main/java/org/miaixz/bus/core/io/sink/DeflaterSink.java
    index 08895b00f2..76108803e4 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/sink/DeflaterSink.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/sink/DeflaterSink.java
    @@ -29,6 +29,7 @@
     import org.miaixz.bus.core.io.SectionBuffer;
     import org.miaixz.bus.core.io.buffer.Buffer;
     import org.miaixz.bus.core.io.timout.Timeout;
    +import org.miaixz.bus.core.lang.Symbol;
     import org.miaixz.bus.core.xyz.IoKit;
     
     import java.io.IOException;
    @@ -162,7 +163,7 @@ public Timeout timeout() {
     
         @Override
         public String toString() {
    -        return "DeflaterSink(" + sink + ")";
    +        return "DeflaterSink(" + sink + Symbol.PARENTHESE_RIGHT;
         }
     
     }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/sink/RealSink.java b/bus-core/src/main/java/org/miaixz/bus/core/io/sink/RealSink.java
    index 49b5bfa58b..432793bd11 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/sink/RealSink.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/sink/RealSink.java
    @@ -30,6 +30,7 @@
     import org.miaixz.bus.core.io.buffer.Buffer;
     import org.miaixz.bus.core.io.source.Source;
     import org.miaixz.bus.core.io.timout.Timeout;
    +import org.miaixz.bus.core.lang.Symbol;
     import org.miaixz.bus.core.xyz.IoKit;
     
     import java.io.EOFException;
    @@ -322,7 +323,7 @@ public Timeout timeout() {
     
         @Override
         public String toString() {
    -        return "buffer(" + sink + ")";
    +        return "buffer(" + sink + Symbol.PARENTHESE_RIGHT;
         }
     
     }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/source/RealSource.java b/bus-core/src/main/java/org/miaixz/bus/core/io/source/RealSource.java
    index 730b808aaf..4df88e3f1d 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/source/RealSource.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/source/RealSource.java
    @@ -573,7 +573,7 @@ public Timeout timeout() {
     
         @Override
         public String toString() {
    -        return "buffer(" + source + ")";
    +        return "buffer(" + source + Symbol.PARENTHESE_RIGHT;
         }
     
     }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/io/timout/AsyncTimeout.java b/bus-core/src/main/java/org/miaixz/bus/core/io/timout/AsyncTimeout.java
    index 4ffbc7c74e..bc9171c55e 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/io/timout/AsyncTimeout.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/io/timout/AsyncTimeout.java
    @@ -29,6 +29,7 @@
     import org.miaixz.bus.core.io.buffer.Buffer;
     import org.miaixz.bus.core.io.sink.Sink;
     import org.miaixz.bus.core.io.source.Source;
    +import org.miaixz.bus.core.lang.Symbol;
     import org.miaixz.bus.core.xyz.IoKit;
     
     import java.io.IOException;
    @@ -279,7 +280,7 @@ public Timeout timeout() {
     
                 @Override
                 public String toString() {
    -                return "AsyncTimeout.sink(" + sink + ")";
    +                return "AsyncTimeout.sink(" + sink + Symbol.PARENTHESE_RIGHT;
                 }
             };
         }
    @@ -326,7 +327,7 @@ public Timeout timeout() {
     
                 @Override
                 public String toString() {
    -                return "AsyncTimeout.source(" + source + ")";
    +                return "AsyncTimeout.source(" + source + Symbol.PARENTHESE_RIGHT;
                 }
             };
         }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/EnumMap.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/EnumMap.java
    index 879ffad3f7..93f01a1384 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/EnumMap.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/EnumMap.java
    @@ -388,11 +388,11 @@ enum Naming {
             /**
              * 名称
              */
    -        private final String name;
    +        private final String desc;
     
    -        Naming(long code, String name) {
    +        Naming(long code, String desc) {
                 this.code = code;
    -            this.name = name;
    +            this.desc = desc;
             }
     
             /**
    @@ -405,8 +405,70 @@ public long getCode() {
             /**
              * @return 对应的名称
              */
    +        public String getDesc() {
    +            return this.desc;
    +        }
    +
    +    }
    +
    +    /**
    +     * 节日类型
    +     */
    +    enum Festival {
    +        DAY(0, "日期"),
    +        TERM(1, "节气"),
    +        EVE(2, "除夕");
    +
    +        /**
    +         * 代码
    +         */
    +        private final int code;
    +
    +        /**
    +         * 名称
    +         */
    +        private final String name;
    +
    +        Festival(int code, String name) {
    +            this.code = code;
    +            this.name = name;
    +        }
    +
    +        public static Festival fromCode(Integer code) {
    +            if (null == code) {
    +                return null;
    +            }
    +            for (Festival item : values()) {
    +                if (item.getCode() == code) {
    +                    return item;
    +                }
    +            }
    +            return null;
    +        }
    +
    +        public static Festival fromName(String name) {
    +            if (null == name) {
    +                return null;
    +            }
    +            for (Festival item : values()) {
    +                if (item.getName().equals(name)) {
    +                    return item;
    +                }
    +            }
    +            return null;
    +        }
    +
    +        public int getCode() {
    +            return code;
    +        }
    +
             public String getName() {
    -            return this.name;
    +            return name;
    +        }
    +
    +        @Override
    +        public String toString() {
    +            return getName();
             }
     
         }
    diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/Fields.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/Fields.java
    index 70a2ffa2c0..033ca7c41b 100644
    --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/Fields.java
    +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/Fields.java
    @@ -25,19 +25,9 @@
      ********************************************************************************/
     package org.miaixz.bus.core.lang;
     
    -import java.time.DayOfWeek;
    -import java.time.format.DateTimeFormatter;
    -import java.time.format.TextStyle;
    -import java.time.temporal.ChronoUnit;
    -import java.util.Calendar;
    -import java.util.Locale;
    -
     /**
      * 日期场景属性
    - *
    - * 

    * 工具类,提供格式化字符串很多,但是对于具体什么含义,不够清晰,这里进行说明: - *

    * 常见日期格式模式字符串: *
      *
    • yyyy-MM-dd 示例:2022-08-05
    • @@ -59,26 +49,6 @@ *
    • EEE MMM dd HH:mm:ss zzz yyyy 示例:周五 8月 05 12:59:00 UTC+08:00 2022,其中z表示UTC时区,但:1~3个z没有任何区别
    • *
    • EEE, dd MMM yyyy HH:mm:ss z 示例:周五, 05 8月 2022 12:59:59 UTC+08:00
    • *
    - *

    - * 系统提供的,请查看,有大量定义好的格式化对象,可以直接使用,如: - * {@link DateTimeFormatter#ISO_DATE} - * {@link DateTimeFormatter#ISO_DATE_TIME} - * 查看更多,请参阅上述官方文档 - *

    - * - *

    - * 特殊说明:UTC时间,世界标准时间,0时区的时间,伦敦时间,可以直接加Z表示不加空格, - * 如:“09:30 UTC”表示为“09:30Z”或“T0930Z”,其中:Z 是 +00:00 的缩写,意思是 UTC(零时分秒的偏移量). - *

    - *
      - *
    • yyyy-MM-dd'T'HH:mm:ss'Z'
    • - *
    • 2022-08-23T15:20:46UTC
    • - *
    • 2022-08-23T15:20:46 UTC
    • - *
    • 2022-08-23T15:20:46+0000
    • - *
    • 2022-08-23T15:20:46 +0000
    • - *
    • 2022-08-23T15:20:46Z
    • - *
    - *

    * * @author Kimi Liu * @since Java 17+ @@ -104,6 +74,11 @@ public class Fields { */ public static final String NORM_DATE = "yyyy-MM-dd"; + /** + * 格式化通配符: HH:mm + */ + public static final String NORM_HOUR_MINUTE = "HH:mm"; + /** * 标准时间格式:HH:mm:ss */ @@ -129,6 +104,11 @@ public class Fields { */ public static final String NORM_DATETIME_COMMA_MS = "yyyy-MM-dd HH:mm:ss,SSS"; + /** + * 中文日期格式: M月d日 + */ + public static final String CN_MONTH = "M月d日"; + /** * 标准日期格式:yyyy年MM月dd日 */ @@ -144,6 +124,10 @@ public class Fields { */ public static final String PURE_DATE = "yyyyMMdd"; + /** + * 标准日期格式: HHmm + */ + public static final String PURE_HOUR_MINUTE = "HHmm"; /** * 标准日期格式:HHmmss */ @@ -215,823 +199,5 @@ public class Fields { * ISO8601时间:yyyy-MM-dd'T'HH:mm:ss.SSSXXX */ public static final String ISO8601_MS_WITH_XXX_OFFSET = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - - /** - * 星期枚举 - * 与Calendar中的星期int值对应 - * - * @see #SUNDAY - * @see #MONDAY - * @see #TUESDAY - * @see #WEDNESDAY - * @see #THURSDAY - * @see #FRIDAY - * @see #SATURDAY - */ - public enum Week { - - /** - * 周日 - */ - SUNDAY(Calendar.SUNDAY), - /** - * 周一 - */ - MONDAY(Calendar.MONDAY), - /** - * 周二 - */ - TUESDAY(Calendar.TUESDAY), - /** - * 周三 - */ - WEDNESDAY(Calendar.WEDNESDAY), - /** - * 周四 - */ - THURSDAY(Calendar.THURSDAY), - /** - * 周五 - */ - FRIDAY(Calendar.FRIDAY), - /** - * 周六 - */ - SATURDAY(Calendar.SATURDAY); - - private static final Week[] ENUMS = Week.values(); - - /** - * 星期对应{@link Calendar} 中的Week值 - */ - private final int value; - - /** - * 构造 - * - * @param value 星期对应{@link Calendar} 中的Week值 - */ - Week(final int value) { - this.value = value; - } - - /** - * 将 {@link Calendar}星期相关值转换为Week枚举对象 - * - * @param calendarWeekIntValue Calendar中关于Week的int值,1表示Sunday - * @return Week - * @see #SUNDAY - * @see #MONDAY - * @see #TUESDAY - * @see #WEDNESDAY - * @see #THURSDAY - * @see #FRIDAY - * @see #SATURDAY - */ - public static Week of(final int calendarWeekIntValue) { - if (calendarWeekIntValue > ENUMS.length || calendarWeekIntValue < 1) { - return null; - } - return ENUMS[calendarWeekIntValue - 1]; - } - - /** - * 解析别名为Week对象,别名如:sun或者SUNDAY,不区分大小写 - * 参考:https://github.com/sisyphsu/dateparser/blob/master/src/main/java/com/github/sisyphsu/dateparser/DateParser.java#L319 - * - * @param name 别名值 - * @return 周枚举Week,非空 - * @throws IllegalArgumentException 如果别名无对应的枚举,抛出此异常 - */ - public static Week of(final String name) throws IllegalArgumentException { - if (null != name && name.length() > 1) { - switch (Character.toLowerCase(name.charAt(0))) { - case 'm': - return MONDAY; // monday - case 'w': - return WEDNESDAY; // wednesday - case 'f': - return FRIDAY; // friday - case 't': - switch (Character.toLowerCase(name.charAt(1))) { - case 'u': - return TUESDAY; // tuesday - case 'h': - return THURSDAY; // thursday - } - break; - case 's': - switch (Character.toLowerCase(name.charAt(1))) { - case 'a': - return SATURDAY; // saturday - case 'u': - return SUNDAY; // sunday - } - break; - } - } - - throw new IllegalArgumentException("Invalid Week name: " + name); - } - - /** - * 将 {@link DayOfWeek}星期相关值转换为Week枚举对象 - * - * @param dayOfWeek DayOfWeek星期值 - * @return Week - * @see #SUNDAY - * @see #MONDAY - * @see #TUESDAY - * @see #WEDNESDAY - * @see #THURSDAY - * @see #FRIDAY - * @see #SATURDAY - */ - public static Week of(final DayOfWeek dayOfWeek) { - Assert.notNull(dayOfWeek); - int week = dayOfWeek.getValue() + 1; - if (8 == week) { - // 周日 - week = 1; - } - return of(week); - } - - /** - * 获得星期对应{@link Calendar} 中的Week值 - * - * @return 星期对应 {@link Calendar} 中的Week值 - */ - public int getValue() { - return this.value; - } - - /** - * 获取ISO8601规范的int值,from 1 (Monday) to 7 (Sunday). - * - * @return ISO8601规范的int值 - */ - public int getIso8601Value() { - int iso8601IntValue = getValue() - 1; - if (0 == iso8601IntValue) { - iso8601IntValue = 7; - } - return iso8601IntValue; - } - - /** - * 转换为中文名 - * - * @return 星期的中文名 - */ - public String toChinese() { - return toChinese("星期"); - } - - /** - * 转换为中文名 - * - * @param weekNamePre 表示星期的前缀,例如前缀为“星期”,则返回结果为“星期一”;前缀为”周“,结果为“周一” - * @return 星期的中文名 - */ - public String toChinese(final String weekNamePre) { - switch (this) { - case SUNDAY: - return weekNamePre + "日"; - case MONDAY: - return weekNamePre + "一"; - case TUESDAY: - return weekNamePre + "二"; - case WEDNESDAY: - return weekNamePre + "三"; - case THURSDAY: - return weekNamePre + "四"; - case FRIDAY: - return weekNamePre + "五"; - case SATURDAY: - return weekNamePre + "六"; - default: - return null; - } - } - - /** - * 转换为{@link DayOfWeek} - * - * @return {@link DayOfWeek} - */ - public DayOfWeek toJdkDayOfWeek() { - return DayOfWeek.of(getIso8601Value()); - } - } - - /** - * 季度枚举 - * - * @see #Q1 - * @see #Q2 - * @see #Q3 - * @see #Q4 - */ - public enum Quarter { - - /** - * 第一季度 - */ - Q1(1), - /** - * 第二季度 - */ - Q2(2), - /** - * 第三季度 - */ - Q3(3), - /** - * 第四季度 - */ - Q4(4); - - private final int value; - - Quarter(final int value) { - this.value = value; - } - - /** - * 将 季度int转换为Season枚举对象 - * - * @param intValue 季度int表示 - * @return {@code Quarter} - * @see #Q1 - * @see #Q2 - * @see #Q3 - * @see #Q4 - */ - public static Quarter of(final int intValue) { - switch (intValue) { - case 1: - return Q1; - case 2: - return Q2; - case 3: - return Q3; - case 4: - return Q4; - default: - return null; - } - } - - /** - * 获取季度值 - * - * @return 季度值 - */ - public int getValue() { - return this.value; - } - } - - /** - * 月份枚举 - * 与Calendar中的月份int值对应 - * - * @see Calendar#JANUARY - * @see Calendar#FEBRUARY - * @see Calendar#MARCH - * @see Calendar#APRIL - * @see Calendar#MAY - * @see Calendar#JUNE - * @see Calendar#JULY - * @see Calendar#AUGUST - * @see Calendar#SEPTEMBER - * @see Calendar#OCTOBER - * @see Calendar#NOVEMBER - * @see Calendar#DECEMBER - * @see Calendar#UNDECIMBER - */ - public enum Month { - /** - * 一月 - */ - JANUARY(Calendar.JANUARY), - /** - * 二月 - */ - FEBRUARY(Calendar.FEBRUARY), - /** - * 三月 - */ - MARCH(Calendar.MARCH), - /** - * 四月 - */ - APRIL(Calendar.APRIL), - /** - * 五月 - */ - MAY(Calendar.MAY), - /** - * 六月 - */ - JUNE(Calendar.JUNE), - /** - * 七月 - */ - JULY(Calendar.JULY), - /** - * 八月 - */ - AUGUST(Calendar.AUGUST), - /** - * 九月 - */ - SEPTEMBER(Calendar.SEPTEMBER), - /** - * 十月 - */ - OCTOBER(Calendar.OCTOBER), - /** - * 十一月 - */ - NOVEMBER(Calendar.NOVEMBER), - /** - * 十二月 - */ - DECEMBER(Calendar.DECEMBER), - /** - * 十三月,仅用于农历 - */ - UNDECIMBER(Calendar.UNDECIMBER); - - private static final Month[] ENUMS = Month.values(); - - /** - * 对应值,见{@link Calendar} - */ - private final int value; - - /** - * 构造 - * - * @param value 对应值,见{@link Calendar} - */ - Month(final int value) { - this.value = value; - } - - /** - * 将 {@link Calendar}月份相关值转换为Month枚举对象 - * 未找到返回{@code null} - * - * @param calendarMonthIntValue Calendar中关于Month的int值,从0开始 - * @return Month - * @see Calendar#JANUARY - * @see Calendar#FEBRUARY - * @see Calendar#MARCH - * @see Calendar#APRIL - * @see Calendar#MAY - * @see Calendar#JUNE - * @see Calendar#JULY - * @see Calendar#AUGUST - * @see Calendar#SEPTEMBER - * @see Calendar#OCTOBER - * @see Calendar#NOVEMBER - * @see Calendar#DECEMBER - * @see Calendar#UNDECIMBER - */ - public static Month of(final int calendarMonthIntValue) { - if (calendarMonthIntValue >= ENUMS.length || calendarMonthIntValue < 0) { - return null; - } - return ENUMS[calendarMonthIntValue]; - } - - /** - * 解析别名为Month对象,别名如:jan或者JANUARY,不区分大小写 - * - * @param name 别名值 - * @return 月份枚举Month,非空 - * @throws IllegalArgumentException 如果别名无对应的枚举,抛出此异常 - */ - public static Month of(final String name) throws IllegalArgumentException { - if (null != name && name.length() > 2) { - switch (Character.toLowerCase(name.charAt(0))) { - case 'a': - switch (Character.toLowerCase(name.charAt(1))) { - case 'p': - return APRIL; // april - case 'u': - return AUGUST; // august - } - break; - case 'j': - if (Character.toLowerCase(name.charAt(1)) == 'a') { - return JANUARY; // january - } - switch (Character.toLowerCase(name.charAt(2))) { - case 'n': - return JUNE; // june - case 'l': - return JULY; // july - } - break; - case 'f': - return FEBRUARY; // february - case 'm': - switch (Character.toLowerCase(name.charAt(2))) { - case 'r': - return MARCH; // march - case 'y': - return MAY; // may - } - break; - case 's': - return SEPTEMBER; // september - case 'o': - return OCTOBER; // october - case 'n': - return NOVEMBER; // november - case 'd': - return DECEMBER; // december - } - } - - throw new IllegalArgumentException("Invalid Month name: " + name); - } - - /** - * {@link java.time.Month}转换为Month对象 - * - * @param month {@link java.time.Month} - * @return Month - */ - public static Month of(final java.time.Month month) { - return of(month.ordinal()); - } - - /** - * 获得指定月的最后一天 - * - * @param month 月份,从0开始 - * @param isLeapYear 是否为闰年,闰年只对二月有影响 - * @return 最后一天,可能为28,29,30,31 - */ - public static int getLastDay(final int month, final boolean isLeapYear) { - final Month of = of(month); - Assert.notNull(of, "Invalid Month base 0: " + month); - return of.getLastDay(isLeapYear); - } - - /** - * 获取{@link Calendar}中的对应值 - * 此值从0开始,即0表示一月 - * - * @return {@link Calendar}中的对应月份值,从0开始计数 - */ - public int getValue() { - return this.value; - } - - /** - * 获取月份值,此值与{@link java.time.Month}对应 - * 此值从1开始,即1表示一月 - * - * @return 月份值,对应{@link java.time.Month},从1开始计数 - */ - public int getValueBaseOne() { - Assert.isFalse(this == UNDECIMBER, "Unsupported UNDECIMBER Field"); - return getValue() + 1; - } - - /** - * 获取此月份最后一天的值 - * 不支持 {@link #UNDECIMBER} - * - * @param isLeapYear 是否闰年 - * @return 此月份最后一天的值 - */ - public int getLastDay(final boolean isLeapYear) { - switch (this) { - case FEBRUARY: - return isLeapYear ? 29 : 28; - case APRIL: - case JUNE: - case SEPTEMBER: - case NOVEMBER: - return 30; - default: - return 31; - } - } - - /** - * 转换为{@link java.time.Month} - * - * @return {@link java.time.Month} - */ - public java.time.Month toJdkMonth() { - return java.time.Month.of(getValueBaseOne()); - } - - /** - * 获取显示名称 - * - * @param style 名称风格 - * @return 显示名称 - */ - public String getDisplayName(final TextStyle style) { - return getDisplayName(style, Locale.getDefault()); - } - - /** - * 获取显示名称 - * - * @param style 名称风格 - * @param locale {@link Locale} - * @return 显示名称 - */ - public String getDisplayName(final TextStyle style, final Locale locale) { - return toJdkMonth().getDisplayName(style, locale); - } - } - - /** - * 日期时间单位,每个单位都是以毫秒为基数 - */ - public enum Units { - /** - * 一毫秒 - */ - MS(1), - /** - * 一秒的毫秒数 - */ - SECOND(1000), - /** - * 一分钟的毫秒数 - */ - MINUTE(SECOND.getMillis() * 60), - /** - * 一小时的毫秒数 - */ - HOUR(MINUTE.getMillis() * 60), - /** - * 一天的毫秒数 - */ - DAY(HOUR.getMillis() * 24), - /** - * 一周的毫秒数 - */ - WEEK(DAY.getMillis() * 7); - - private final long millis; - - Units(final long millis) { - this.millis = millis; - } - - /** - * 单位兼容转换,将{@link ChronoUnit}转换为对应的DateUnit - * - * @param unit {@link ChronoUnit} - * @return Units,null表示不支持此单位 - */ - public static Units of(final ChronoUnit unit) { - switch (unit) { - case MICROS: - return Units.MS; - case SECONDS: - return Units.SECOND; - case MINUTES: - return Units.MINUTE; - case HOURS: - return Units.HOUR; - case DAYS: - return Units.DAY; - case WEEKS: - return Units.WEEK; - } - return null; - } - - /** - * 单位兼容转换,将DateUnit转换为对应的{@link ChronoUnit} - * - * @param unit Units - * @return {@link ChronoUnit} - */ - public static ChronoUnit toChronoUnit(final Units unit) { - switch (unit) { - case MS: - return ChronoUnit.MICROS; - case SECOND: - return ChronoUnit.SECONDS; - case MINUTE: - return ChronoUnit.MINUTES; - case HOUR: - return ChronoUnit.HOURS; - case DAY: - return ChronoUnit.DAYS; - case WEEK: - return ChronoUnit.WEEKS; - } - return null; - } - - /** - * @return 单位对应的毫秒数 - */ - public long getMillis() { - return this.millis; - } - - /** - * 单位兼容转换,将DateUnit转换为对应的{@link ChronoUnit} - * - * @return {@link ChronoUnit} - */ - public ChronoUnit toChronoUnit() { - return Units.toChronoUnit(this); - } - } - - /** - * 修改类型 - */ - public enum Modify { - /** - * 取指定日期短的起始值. - */ - TRUNCATE, - - /** - * 指定日期属性按照四舍五入处理 - */ - ROUND, - - /** - * 指定日期属性按照进一法处理 - */ - CEILING - } - - /** - * 日期各个部分的枚举 - * 与Calendar相应值对应 - */ - public enum Type { - - /** - * 世纪 - * - * @see Calendar#ERA - */ - ERA(Calendar.ERA), - /** - * 年 - * - * @see Calendar#YEAR - */ - YEAR(Calendar.YEAR), - /** - * 月 - * - * @see Calendar#MONTH - */ - MONTH(Calendar.MONTH), - /** - * 一年中第几周 - * - * @see Calendar#WEEK_OF_YEAR - */ - WEEK_OF_YEAR(Calendar.WEEK_OF_YEAR), - /** - * 一月中第几周 - * - * @see Calendar#WEEK_OF_MONTH - */ - WEEK_OF_MONTH(Calendar.WEEK_OF_MONTH), - /** - * 一月中的第几天 - * - * @see Calendar#DAY_OF_MONTH - */ - DAY_OF_MONTH(Calendar.DAY_OF_MONTH), - /** - * 一年中的第几天 - * - * @see Calendar#DAY_OF_YEAR - */ - DAY_OF_YEAR(Calendar.DAY_OF_YEAR), - /** - * 周几,1表示周日,2表示周一 - * - * @see Calendar#DAY_OF_WEEK - */ - DAY_OF_WEEK(Calendar.DAY_OF_WEEK), - /** - * 天所在的周是这个月的第几周 - * - * @see Calendar#DAY_OF_WEEK_IN_MONTH - */ - DAY_OF_WEEK_IN_MONTH(Calendar.DAY_OF_WEEK_IN_MONTH), - /** - * 上午或者下午 - * - * @see Calendar#AM_PM - */ - AM_PM(Calendar.AM_PM), - /** - * 小时,用于12小时制 - * - * @see Calendar#HOUR - */ - HOUR(Calendar.HOUR), - /** - * 小时,用于24小时制 - * - * @see Calendar#HOUR - */ - HOUR_OF_DAY(Calendar.HOUR_OF_DAY), - /** - * 分钟 - * - * @see Calendar#MINUTE - */ - MINUTE(Calendar.MINUTE), - /** - * 秒 - * - * @see Calendar#SECOND - */ - SECOND(Calendar.SECOND), - /** - * 毫秒 - * - * @see Calendar#MILLISECOND - */ - MILLISECOND(Calendar.MILLISECOND); - - private final int value; - - Type(final int value) { - this.value = value; - } - - /** - * 将 {@link Calendar}相关值转换为DatePart枚举对象 - * - * @param calendarPartIntValue Calendar中关于Week的int值 - * @return Type - */ - public static Type of(final int calendarPartIntValue) { - switch (calendarPartIntValue) { - case Calendar.ERA: - return ERA; - case Calendar.YEAR: - return YEAR; - case Calendar.MONTH: - return MONTH; - case Calendar.WEEK_OF_YEAR: - return WEEK_OF_YEAR; - case Calendar.WEEK_OF_MONTH: - return WEEK_OF_MONTH; - case Calendar.DAY_OF_MONTH: - return DAY_OF_MONTH; - case Calendar.DAY_OF_YEAR: - return DAY_OF_YEAR; - case Calendar.DAY_OF_WEEK: - return DAY_OF_WEEK; - case Calendar.DAY_OF_WEEK_IN_MONTH: - return DAY_OF_WEEK_IN_MONTH; - case Calendar.AM_PM: - return AM_PM; - case Calendar.HOUR: - return HOUR; - case Calendar.HOUR_OF_DAY: - return HOUR_OF_DAY; - case Calendar.MINUTE: - return MINUTE; - case Calendar.SECOND: - return SECOND; - case Calendar.MILLISECOND: - return MILLISECOND; - default: - return null; - } - } - - /** - * 获取{@link Calendar}中对应的值 - * - * @return {@link Calendar}中对应的值 - */ - public int getValue() { - return this.value; - } - - } - + } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/MediaType.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/MediaType.java index 5fe8de6590..5f4e5f5ec1 100755 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/MediaType.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/MediaType.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.core.lang; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.miaixz.bus.core.xyz.MapKit; import java.util.*; @@ -39,7 +40,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter public class MediaType { /** diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/Normal.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/Normal.java index bfa9518fd7..510c089d8b 100755 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/Normal.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/Normal.java @@ -67,12 +67,27 @@ public class Normal { * The number 32 */ public static final int _32 = 32; - + /** + * The number 24 + */ + public static final int _24 = 24; + /** + * The number 20 + */ + public static final int _20 = 20; + /** + * The number 18 + */ + public static final int _18 = 18; /** * The number 16 */ public static final int _16 = 16; + /** + * The number 12 + */ + public static final int _12 = 12; /** * The number 9 */ diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/RegEx.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/Regex.java similarity index 100% rename from bus-core/src/main/java/org/miaixz/bus/core/lang/RegEx.java rename to bus-core/src/main/java/org/miaixz/bus/core/lang/Regex.java diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/Validator.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/Validator.java index 1459f9dcaf..27a3a55a8c 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/Validator.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/Validator.java @@ -363,7 +363,7 @@ public static boolean isGeneral(final CharSequence value, int min, final int max if (min < 0) { min = 0; } - String reg = "^\\w{" + min + "," + max + "}$"; + String reg = "^\\w{" + min + Symbol.COMMA + max + "}$"; if (max <= 0) { reg = "^\\w{" + min + ",}$"; } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/exception/RelevantException.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/exception/RelevantException.java index 53b0150b58..5ff689558a 100755 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/exception/RelevantException.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/exception/RelevantException.java @@ -25,8 +25,9 @@ ********************************************************************************/ package org.miaixz.bus.core.lang.exception; -import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -34,7 +35,8 @@ /** * 类型: IO相关异常 */ -@Data +@Getter +@Setter @EqualsAndHashCode(callSuper = false) public class RelevantException extends IOException { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/exception/UncheckedException.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/exception/UncheckedException.java index 353f62f550..1a2e605186 100755 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/exception/UncheckedException.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/exception/UncheckedException.java @@ -26,15 +26,17 @@ package org.miaixz.bus.core.lang.exception; import lombok.Builder; -import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; import java.lang.reflect.InvocationTargetException; /** * 类型: 未受检异常 */ -@Data +@Getter +@Setter @Builder @EqualsAndHashCode(callSuper = false) public class UncheckedException extends RuntimeException { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/classloader/JarClassLoader.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/classloader/JarClassLoader.java index 225c0d5a7a..99a0903598 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/classloader/JarClassLoader.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/classloader/JarClassLoader.java @@ -26,6 +26,7 @@ package org.miaixz.bus.core.lang.loader.classloader; import org.miaixz.bus.core.io.file.FileName; +import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.lang.exception.InternalException; import org.miaixz.bus.core.xyz.ClassKit; import org.miaixz.bus.core.xyz.FileKit; @@ -149,7 +150,7 @@ private static List loopJar(final File file) { */ private static boolean isJarFile(final File file) { return FileKit.isFile(file) && - FileName.isType(file.getName(), FileName.EXT_JAR); + FileName.isType(file.getName(), Normal.URL_PROTOCOL_JAR); } /** diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/AbsServiceLoader.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/AbstractServiceLoader.java similarity index 88% rename from bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/AbsServiceLoader.java rename to bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/AbstractServiceLoader.java index 5018f8eda7..764906e67b 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/AbsServiceLoader.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/AbstractServiceLoader.java @@ -37,11 +37,23 @@ * @author Kimi Liu * @since Java 17+ */ -public abstract class AbsServiceLoader implements ServiceLoader { +public abstract class AbstractServiceLoader implements ServiceLoader { + /** + * 路径前缀 + */ protected final String pathPrefix; + /** + * 服务类 + */ protected final Class serviceClass; + /** + * 类加载器 + */ protected final ClassLoader classLoader; + /** + * 字符集 + */ protected final Charset charset; /** @@ -52,8 +64,8 @@ public abstract class AbsServiceLoader implements ServiceLoader { * @param classLoader 自定义类加载器, {@code null}表示使用默认当前的类加载器 * @param charset 编码,默认UTF-8 */ - public AbsServiceLoader(final String pathPrefix, final Class serviceClass, - final ClassLoader classLoader, final Charset charset) { + public AbstractServiceLoader(final String pathPrefix, final Class serviceClass, + final ClassLoader classLoader, final Charset charset) { this.pathPrefix = StringKit.addSuffixIfNot(pathPrefix, Symbol.SLASH); this.serviceClass = serviceClass; this.classLoader = classLoader; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/ListServiceLoader.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/ListServiceLoader.java index 36d8637c8c..1a14fdb59a 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/ListServiceLoader.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/ListServiceLoader.java @@ -65,7 +65,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class ListServiceLoader extends AbsServiceLoader { +public class ListServiceLoader extends AbstractServiceLoader { private final List serviceNames; // data: className, value: service instance diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/MapServiceLoader.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/MapServiceLoader.java index 93f22afbdd..05ed83c42d 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/MapServiceLoader.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/loader/spi/MapServiceLoader.java @@ -50,7 +50,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class MapServiceLoader extends AbsServiceLoader { +public class MapServiceLoader extends AbstractServiceLoader { // TODO update const private static final String PREFIX = Normal.META_INF + "/bus/"; diff --git a/bus-core/src/main/java/org/miaixz/bus/core/lang/reflect/method/MethodReflect.java b/bus-core/src/main/java/org/miaixz/bus/core/lang/reflect/method/MethodReflect.java index 1a295b53d3..4f7d9db147 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/lang/reflect/method/MethodReflect.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/lang/reflect/method/MethodReflect.java @@ -87,7 +87,7 @@ private static String getUniqueKey(final Method method) { if (i == 0) { sb.append(Symbol.C_COLON); } else { - sb.append(','); + sb.append(Symbol.C_COMMA); } sb.append(parameters[i].getName()); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/math/Calculator.java b/bus-core/src/main/java/org/miaixz/bus/core/math/Calculator.java index c03c3aaf85..16074a8146 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/math/Calculator.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/math/Calculator.java @@ -76,13 +76,13 @@ private static String transform(String expression) { arr[i] = Symbol.C_TILDE; } else { final char c = arr[i - 1]; - if (c == Symbol.C_PLUS || c == Symbol.C_MINUS || c == Symbol.C_STAR || c == '/' || c == '(' || c == 'E' || c == 'e') { + if (c == Symbol.C_PLUS || c == Symbol.C_MINUS || c == Symbol.C_STAR || c == '/' || c == Symbol.C_PARENTHESE_LEFT || c == 'E' || c == 'e') { arr[i] = Symbol.C_TILDE; } } } } - if (arr[0] == Symbol.C_TILDE && (arr.length > 1 && arr[1] == '(')) { + if (arr[0] == Symbol.C_TILDE && (arr.length > 1 && arr[1] == Symbol.C_PARENTHESE_LEFT)) { arr[0] = Symbol.C_MINUS; return "0" + new String(arr); } else { @@ -131,7 +131,7 @@ public double calculate(final String expression) { */ private void prepare(final String expression) { final Stack opStack = new Stack<>(); - opStack.push(',');// 运算符放入栈底元素逗号,此符号优先级最低 + opStack.push(Symbol.C_COMMA);// 运算符放入栈底元素逗号,此符号优先级最低 final char[] arr = expression.toCharArray(); int currentIndex = 0;// 当前字符的位置 int count = 0;// 上次算术运算符到本次算术运算符的字符的长度便于或者之间的数值 @@ -144,12 +144,12 @@ private void prepare(final String expression) { } peekOp = opStack.peek(); if (currentOp == ')') {// 遇到反括号则将运算符栈中的元素移除到后缀式栈中直到遇到左括号 - while (opStack.peek() != '(') { + while (opStack.peek() != Symbol.C_PARENTHESE_LEFT) { postfixStack.push(String.valueOf(opStack.pop())); } opStack.pop(); } else { - while (currentOp != '(' && peekOp != ',' && compare(currentOp, peekOp)) { + while (currentOp != Symbol.C_PARENTHESE_LEFT && peekOp != Symbol.C_COMMA && compare(currentOp, peekOp)) { postfixStack.push(String.valueOf(opStack.pop())); peekOp = opStack.peek(); } @@ -165,7 +165,7 @@ private void prepare(final String expression) { postfixStack.push(new String(arr, currentIndex, count)); } - while (opStack.peek() != ',') { + while (opStack.peek() != Symbol.C_COMMA) { postfixStack.push(String.valueOf(opStack.pop()));// 将操作符栈中的剩余的元素添加到后缀式栈中 } } @@ -177,7 +177,7 @@ private void prepare(final String expression) { * @return 是否为算术符号 */ private boolean isOperator(final char c) { - return c == Symbol.C_PLUS || c == Symbol.C_MINUS || c == Symbol.C_STAR || c == '/' || c == '(' || c == ')' || c == Symbol.C_PERCENT; + return c == Symbol.C_PLUS || c == Symbol.C_MINUS || c == Symbol.C_STAR || c == '/' || c == Symbol.C_PARENTHESE_LEFT || c == ')' || c == Symbol.C_PERCENT; } /** diff --git a/bus-core/src/main/java/org/miaixz/bus/core/net/url/UrlQuery.java b/bus-core/src/main/java/org/miaixz/bus/core/net/url/UrlQuery.java index aea4eb079d..46506de2c9 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/net/url/UrlQuery.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/net/url/UrlQuery.java @@ -163,9 +163,9 @@ public static UrlQuery of(final Map queryMap, final E private static String toString(final Object value) { final String result; if (value instanceof Iterable) { - result = CollKit.join((Iterable) value, ","); + result = CollKit.join((Iterable) value, Symbol.COMMA); } else if (value instanceof Iterator) { - result = IteratorKit.join((Iterator) value, ","); + result = IteratorKit.join((Iterator) value, Symbol.COMMA); } else { result = Convert.toString(value); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/text/AntPathMatcher.java b/bus-core/src/main/java/org/miaixz/bus/core/text/AntPathMatcher.java index e383c6ad1f..bd307dab39 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/text/AntPathMatcher.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/text/AntPathMatcher.java @@ -47,7 +47,7 @@ *

  • {@code {bus:[a-z]+}} 匹配以"bus"命名的正则 {@code [a-z]+}
  • * * - *

    例子:

    + *

    示例:

    *
      *
    • {@code com/t?st.jsp} — 匹配 {@code com/test.jsp} 或 {@code com/tast.jsp} 或 {@code com/txst.jsp}
    • *
    • {@code com/*.jsp} — 匹配{@code com}目录下全部 {@code .jsp}文件
    • @@ -679,9 +679,9 @@ public AntPathStringMatcher(final String pattern, final boolean caseSensitive) { this.variableNames.add(matcher.group(1)); } else { final String variablePattern = match.substring(colonIdx + 1, match.length() - 1); - patternBuilder.append('('); + patternBuilder.append(Symbol.C_PARENTHESE_LEFT); patternBuilder.append(variablePattern); - patternBuilder.append(')'); + patternBuilder.append(Symbol.C_PARENTHESE_RIGHT); final String variableName = match.substring(1, colonIdx); this.variableNames.add(variableName); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/text/CharsBacker.java b/bus-core/src/main/java/org/miaixz/bus/core/text/CharsBacker.java index b0d14d52ce..a40d3e79b7 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/text/CharsBacker.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/text/CharsBacker.java @@ -552,12 +552,12 @@ public static boolean endWith(final CharSequence text, final CharSequence suffix /** * 指定字符是否在字符串中出现过 * - * @param text 字符串 - * @param searchChar 被查找的字符 + * @param text 字符串 + * @param args 被查找的字符 * @return 是否包含 */ - public static boolean contains(final CharSequence text, final char searchChar) { - return indexOf(text, searchChar) > -1; + public static boolean contains(final CharSequence text, final char args) { + return indexOf(text, args) > -1; } /** @@ -605,11 +605,13 @@ public static boolean containsAny(final CharSequence text, final char... args) { } /** - * 检查指定字符串中是否只包含给定的字符 + * 检查指定字符串中是否只包含给定的字符
      + * 这里的containsOnly并不是必须全部给定的args都需要有,而是一个子集。 + * args是个限定集合,检查字符串中的字符是否在这个限定集合中。 *
        - *
      • text 是 null,testChars 也是 null,直接返回 true
      • - *
      • text 是 null,testChars 不是 null,直接返回 true
      • - *
      • text 不是 null,testChars 是 null,直接返回 false
      • + *
      • text 是 null,args 也是 null,直接返回 true
      • + *
      • text 是 null,args 不是 null,直接返回 true
      • + *
      • text 不是 null,args 是 null,直接返回 false
      • *
      * * @param text 字符串 @@ -920,7 +922,7 @@ public static int lastIndexOf(final CharSequence text, final CharSequence args, * 如果 text1=null 或 args=null 或 ordinal≤0 则返回-1 * 此方法来自:Apache-Commons-Lang *

      - * 例子(*代表任意字符): + * 示例(*代表任意字符): * *

            * ordinalIndexOf(null, *, *)          = -1
      @@ -969,7 +971,7 @@ public static int ordinalIndexOf(final CharSequence text, final CharSequence arg
            * @return 移除后的字符串
            */
           public static String removeAll(final CharSequence text, final CharSequence args) {
      -        // strToRemove如果为空, 也不用继续后面的逻辑
      +        // args如果为空, 也不用继续后面的逻辑
               if (isEmpty(text) || isEmpty(args)) {
                   return toString(text);
               }
      @@ -1654,9 +1656,6 @@ public static String subAfter(final CharSequence text, final char separator, fin
       
           /**
            * 截取指定字符串中间部分,不包括标识字符串
      -     * 

      - * 栗子: - * *

            * subBetween("wx[b]yz", "[", "]") = "b"
            * subBetween(null, *, *)          = null
      @@ -1696,9 +1695,6 @@ public static String subBetween(final CharSequence text, final CharSequence befo
       
           /**
            * 截取指定字符串中间部分,不包括标识字符串
      -     * 

      - * 栗子: - * *

            * subBetween(null, *)            = null
            * subBetween("", "")             = ""
      @@ -1718,9 +1714,6 @@ public static String subBetween(final CharSequence text, final CharSequence befo
       
           /**
            * 截取指定字符串多段中间部分,不包括标识字符串
      -     * 

      - * 栗子: - * *

            * subBetweenAll("wx[b]y[z]", "[", "]") 		= ["b","z"]
            * subBetweenAll(null, *, *)          			= []
      @@ -1771,9 +1764,6 @@ public static String[] subBetweenAll(final CharSequence text, final CharSequence
       
           /**
            * 截取指定字符串多段中间部分,不包括标识字符串
      -     * 

      - * 栗子: - * *

            * subBetweenAll(null, *)          			= []
            * subBetweenAll(*, null)          			= []
      diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/BeanKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/BeanKit.java
      index dccd0ac334..761276a6ba 100644
      --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/BeanKit.java
      +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/BeanKit.java
      @@ -614,18 +614,17 @@ public static  T edit(final T bean, final UnaryOperator editor) {
       
           /**
            * 把Bean里面的String属性做trim操作。此方法直接对传入的Bean做修改。
      -     * 

      * 通常bean直接用来绑定页面的input,用户的输入可能首尾存在空格,通常保存数据库前需要把首尾空格去掉 * - * @param Bean类型 - * @param bean Bean对象 - * @param ignoreFields 不需要trim的Field名称列表(不区分大小写) + * @param Bean类型 + * @param bean Bean对象 + * @param ignoreField 不需要trim的Field名称列表(不区分大小写) * @return 处理后的Bean对象 */ - public static T trimStrFields(final T bean, final String... ignoreFields) { + public static T trimStringField(final T bean, final String... ignoreField) { return edit(bean, (field) -> { - if (ignoreFields != null && ArrayKit.containsIgnoreCase(ignoreFields, field.getName())) { - // 不处理忽略的Fields + if (ignoreField != null && ArrayKit.containsIgnoreCase(ignoreField, field.getName())) { + // 不处理忽略的Field return field; } if (String.class.equals(field.getType())) { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/CollKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/CollKit.java index c199be26ee..2672de7e70 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/CollKit.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/CollKit.java @@ -47,6 +47,7 @@ import java.util.Map.Entry; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; @@ -235,14 +236,26 @@ public static boolean isNotEmpty(final Map map) { return MapKit.isNotEmpty(map); } + /** + * 去重集合 + * + * @param 集合元素类型 + * @param key 属性名 + * @return {@link List} + */ + public static Predicate distinct(final Function key) { + Map map = new ConcurrentHashMap<>(); + return t -> map.putIfAbsent(key.apply(t), Boolean.TRUE) == null; + } + /** * 去重集合 * * @param 集合元素类型 * @param collection 集合 - * @return {@link ArrayList} + * @return {@link List} */ - public static ArrayList distinct(final Collection collection) { + public static List distinct(final Collection collection) { if (isEmpty(collection)) { return new ArrayList<>(); } else if (collection instanceof Set) { @@ -256,19 +269,19 @@ public static ArrayList distinct(final Collection collection) { * 根据函数生成的KEY去重集合,如根据Bean的某个或者某些字段完成去重。 * 去重可选是保留最先加入的值还是后加入的值 * - * @param 集合元素类型 - * @param 唯一键类型 - * @param collection 集合 - * @param uniqueGenerator 唯一键生成器 - * @param override 是否覆盖模式,如果为{@code true},加入的新值会覆盖相同key的旧值,否则会忽略新加值 - * @return {@link ArrayList} + * @param 集合元素类型 + * @param 唯一键类型 + * @param collection 集合 + * @param key 唯一标识 + * @param override 是否覆盖模式,如果为{@code true},加入的新值会覆盖相同key的旧值,否则会忽略新加值 + * @return {@link List} */ - public static List distinct(final Collection collection, final Function uniqueGenerator, final boolean override) { + public static List distinct(final Collection collection, final Function key, final boolean override) { if (isEmpty(collection)) { return new ArrayList<>(); } - final UniqueKeySet set = new UniqueKeySet<>(true, uniqueGenerator); + final UniqueKeySet set = new UniqueKeySet<>(true, key); if (override) { set.addAll(collection); } else { diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/ColorKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/ColorKit.java index 0ed2e8dc91..7ad0ca9760 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/ColorKit.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/ColorKit.java @@ -87,9 +87,9 @@ public class ColorKit { public static String toCssRgb(final Color color) { return StringKit.builder() .append("rgb(") - .append(color.getRed()).append(",") - .append(color.getGreen()).append(",") - .append(color.getBlue()).append(")") + .append(color.getRed()).append(Symbol.COMMA) + .append(color.getGreen()).append(Symbol.COMMA) + .append(color.getBlue()).append(Symbol.PARENTHESE_RIGHT) .toString(); } @@ -102,10 +102,10 @@ public static String toCssRgb(final Color color) { public static String toCssRgba(final Color color) { return StringKit.builder() .append("rgba(") - .append(color.getRed()).append(",") - .append(color.getGreen()).append(",") - .append(color.getBlue()).append(",") - .append(color.getAlpha() / 255D).append(")") + .append(color.getRed()).append(Symbol.COMMA) + .append(color.getGreen()).append(Symbol.COMMA) + .append(color.getBlue()).append(Symbol.COMMA) + .append(color.getAlpha() / 255D).append(Symbol.PARENTHESE_RIGHT) .toString(); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/DateKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/DateKit.java index 0d78f5fdc1..17499d3276 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/DateKit.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/DateKit.java @@ -25,13 +25,15 @@ ********************************************************************************/ package org.miaixz.bus.core.xyz; +import org.miaixz.bus.core.center.date.Calendar; import org.miaixz.bus.core.center.date.Formatter; import org.miaixz.bus.core.center.date.*; +import org.miaixz.bus.core.center.date.culture.cn.Zodiac; +import org.miaixz.bus.core.center.date.culture.en.*; import org.miaixz.bus.core.center.date.format.CustomFormat; import org.miaixz.bus.core.center.date.format.FormatBuilder; import org.miaixz.bus.core.center.date.format.FormatPeriod; import org.miaixz.bus.core.center.date.format.parser.NormalDateParser; -import org.miaixz.bus.core.center.date.format.parser.PositionDateParser; import org.miaixz.bus.core.center.date.format.parser.RegisterDateParser; import org.miaixz.bus.core.center.date.printer.FormatPrinter; import org.miaixz.bus.core.lang.Assert; @@ -62,7 +64,113 @@ * @see Fields 日期常用格式工具类 * @since Java 17+ */ -public class DateKit extends Calendars { +public class DateKit extends Calendar { + + /** + * 是否为上午 + * + * @param date 日期 + * @return 是否为上午 + */ + public static boolean isAM(final Date date) { + return DateTime.of(date).isAM(); + } + + /** + * 是否为下午 + * + * @param date 日期 + * @return 是否为下午 + */ + public static boolean isPM(final Date date) { + return DateTime.of(date).isPM(); + } + + /** + * 是否为相同时间 + * 此方法比较两个日期的时间戳是否相同 + * + * @param date1 日期1 + * @param date2 日期2 + * @return 是否为相同时间 + */ + public static boolean isSameTime(final Date date1, final Date date2) { + return date1.compareTo(date2) == 0; + } + + /** + * 比较两个日期是否为同一天 + * + * @param date1 日期1 + * @param date2 日期2 + * @return 是否为同一天 + */ + public static boolean isSameDay(final Date date1, final Date date2) { + if (date1 == null || date2 == null) { + throw new IllegalArgumentException("The date must not be null"); + } + return Calendar.isSameDay(calendar(date1), calendar(date2)); + } + + /** + * 比较两个日期是否为同一周 + * + * @param date1 日期1 + * @param date2 日期2 + * @param isMon 是否为周一。国内第一天为星期一,国外第一天为星期日 + * @return 是否为同一周 + */ + public static boolean isSameWeek(final Date date1, final Date date2, final boolean isMon) { + if (date1 == null || date2 == null) { + throw new IllegalArgumentException("The date must not be null"); + } + return Calendar.isSameWeek(calendar(date1), calendar(date2), isMon); + } + + /** + * 比较两个日期是否为同一月 + * + * @param date1 日期1 + * @param date2 日期2 + * @return 是否为同一月 + */ + public static boolean isSameMonth(final Date date1, final Date date2) { + if (date1 == null || date2 == null) { + throw new IllegalArgumentException("The date must not be null"); + } + return Calendar.isSameMonth(calendar(date1), calendar(date2)); + } + + /** + * 当前日期是否在日期指定范围内 + * 起始日期和结束日期可以互换 + * + * @param date 被检查的日期 + * @param beginDate 起始日期(包含) + * @param endDate 结束日期(包含) + * @return 是否在范围内 + */ + public static boolean isIn(final Date date, final Date beginDate, final Date endDate) { + return isIn(date, beginDate, endDate, true, true); + } + + /** + * 当前日期是否在日期指定范围内 + * 起始日期和结束日期可以互换 + * 通过includeBegin, includeEnd参数控制日期范围区间是否为开区间,例如:传入参数:includeBegin=true, includeEnd=false, + * 则本方法会判断 date ∈ (beginDate, endDate] 是否成立 + * + * @param date 被检查的日期 + * @param beginDate 起始日期 + * @param endDate 结束日期 + * @param includeBegin 时间范围是否包含起始日期 + * @param includeEnd 时间范围是否包含结束日期 + * @return 是否在范围内 + */ + public static boolean isIn(final Date date, final Date beginDate, final Date endDate, + final boolean includeBegin, final boolean includeEnd) { + return new DateTime().isIn(date, beginDate, endDate, includeBegin, includeEnd); + } /** * 当前时间,转换为{@link DateTime}对象 @@ -79,7 +187,7 @@ public static DateTime now() { * @return 当天开始的时间 */ public static DateTime today() { - return new DateTime(beginOfDay(Calendar.getInstance())); + return new DateTime(beginOfDay(java.util.Calendar.getInstance())); } /** @@ -160,13 +268,13 @@ public static DateTime date(final long date) { } /** - * {@link Calendar}类型时间转为{@link DateTime} - * 始终根据已有{@link Calendar} 产生新的{@link DateTime}对象 + * {@link java.util.Calendar}类型时间转为{@link DateTime} + * 始终根据已有{@link java.util.Calendar} 产生新的{@link DateTime}对象 * - * @param calendar {@link Calendar},如果传入{@code null},返回{@code null} + * @param calendar {@link java.util.Calendar},如果传入{@code null},返回{@code null} * @return 时间对象 */ - public static DateTime date(final Calendar calendar) { + public static DateTime date(final java.util.Calendar calendar) { if (calendar == null) { return null; } @@ -249,7 +357,7 @@ public static int quarter(final Date date) { * @param date 日期 * @return 第几个季度枚举 */ - public static Fields.Quarter quarterEnum(final Date date) { + public static Quarter quarterEnum(final Date date) { return DateTime.of(date).quarterEnum(); } @@ -267,9 +375,9 @@ public static int month(final Date date) { * 获得月份 * * @param date 日期 - * @return {@link Fields.Month} + * @return {@link Month} */ - public static Fields.Month monthEnum(final Date date) { + public static Month monthEnum(final Date date) { return DateTime.of(date).monthEnum(); } @@ -282,7 +390,7 @@ public static Fields.Month monthEnum(final Date date) { * * @param date 日期 * @return 周 - * @see DateTime#setFirstDayOfWeek(Fields.Week) + * @see DateTime#setFirstDayOfWeek(Week) */ public static int weekOfYear(final Date date) { return DateTime.of(date).weekOfYear(); @@ -332,9 +440,9 @@ public static int dayOfWeek(final Date date) { * 获得指定日期是星期几 * * @param date 日期 - * @return {@link Fields.Week} + * @return {@link Week} */ - public static Fields.Week dayOfWeekEnum(final Date date) { + public static Week dayOfWeekEnum(final Date date) { return DateTime.of(date).dayOfWeekEnum(); } @@ -345,8 +453,8 @@ public static Fields.Week dayOfWeekEnum(final Date date) { * @return 是否为周末(周六或周日) */ public static boolean isWeekend(final Date date) { - final Fields.Week week = dayOfWeekEnum(date); - return Fields.Week.SATURDAY == week || Fields.Week.SUNDAY == week; + final Week week = dayOfWeekEnum(date); + return Week.SATURDAY == week || Week.SUNDAY == week; } /** @@ -362,7 +470,7 @@ public static int hour(final Date date, final boolean is24HourClock) { /** * 获得指定日期的分钟数部分 - * 例如:10:04:15.250 =》 4 + * 例如:10:04:15.250 = 4 * * @param date 日期 * @return 分钟数 @@ -391,26 +499,6 @@ public static int millisecond(final Date date) { return DateTime.of(date).millisecond(); } - /** - * 是否为上午 - * - * @param date 日期 - * @return 是否为上午 - */ - public static boolean isAM(final Date date) { - return DateTime.of(date).isAM(); - } - - /** - * 是否为下午 - * - * @param date 日期 - * @return 是否为下午 - */ - public static boolean isPM(final Date date) { - return DateTime.of(date).isPM(); - } - /** * @return 今年 */ @@ -426,9 +514,9 @@ public static int thisMonth() { } /** - * @return 当前月份 {@link Fields.Month} + * @return 当前月份 {@link Month} */ - public static Fields.Month thisMonthEnum() { + public static Month thisMonthEnum() { return monthEnum(now()); } @@ -461,9 +549,9 @@ public static int thisDayOfWeek() { } /** - * @return 当前日期是星期几 {@link Fields.Week} + * @return 当前日期是星期几 {@link Week} */ - public static Fields.Week thisDayOfWeekEnum() { + public static Week thisDayOfWeekEnum() { return dayOfWeekEnum(now()); } @@ -507,28 +595,6 @@ public static String yearAndQuarter(final Date date) { return yearAndQuarter(calendar(date)); } - /** - * 格式化日期时间 - * 格式 yyyy-MM-dd HH:mm:ss - * - * @param localDateTime 被格式化的日期 - * @return 格式化后的字符串 - */ - public static String formatLocalDateTime(final LocalDateTime localDateTime) { - return Formatter.formatNormal(localDateTime); - } - - /** - * 根据特定格式格式化日期 - * - * @param localDateTime 被格式化的日期 - * @param format 日期格式,常用格式见: {@link Fields} - * @return 格式化后的字符串 - */ - public static String format(final LocalDateTime localDateTime, final String format) { - return Formatter.format(localDateTime, format); - } - /** * 根据特定格式格式化日期 * @@ -654,7 +720,7 @@ public static String formatHttpDate(final Date date) { } /** - * 格式化为中文日期格式,如果isUppercase为false,则返回类似:2018年10月24日,否则返回二〇一八年十月二十四日 + * 格式化为中文日期格式,如果isUppercase为false,则返回类似:2024年05月20日,否则返回二〇二四年五月二十日 * * @param date 被格式化的日期 * @param isUppercase 是否采用大写形式 @@ -670,93 +736,7 @@ public static String formatChineseDate(final Date date, final boolean isUppercas return (withTime ? Formatter.CN_DATE_TIME_FORMAT : Formatter.CN_DATE_FORMAT).format(date); } - return Calendars.formatChineseDate(Calendars.calendar(date), withTime); - } - - /** - * 构建DateTime对象 - * - * @param dateStr Date字符串 - * @param dateFormat 格式化器 {@link SimpleDateFormat} - * @return DateTime对象 - */ - public static DateTime parse(final CharSequence dateStr, final DateFormat dateFormat) { - return new DateTime(dateStr, dateFormat); - } - - /** - * 构建DateTime对象 - * - * @param dateStr Date字符串 - * @param parser 格式化器,{@link FormatBuilder} - * @return DateTime对象 - */ - public static DateTime parse(final CharSequence dateStr, final PositionDateParser parser) { - return new DateTime(dateStr, parser); - } - - /** - * 构建DateTime对象 - * - * @param dateStr Date字符串 - * @param parser 格式化器,{@link FormatBuilder} - * @param lenient 是否宽容模式 - * @return DateTime对象 - */ - public static DateTime parse(final CharSequence dateStr, final PositionDateParser parser, final boolean lenient) { - return new DateTime(dateStr, parser, lenient); - } - - /** - * 构建DateTime对象 - * - * @param dateStr Date字符串 - * @param formatter 格式化器,{@link DateTimeFormatter} - * @return DateTime对象 - */ - public static DateTime parse(final CharSequence dateStr, final DateTimeFormatter formatter) { - return new DateTime(dateStr, formatter); - } - - /** - * 将特定格式的日期转换为Date对象 - * - * @param dateStr 特定格式的日期 - * @param format 格式,例如yyyy-MM-dd - * @return 日期对象 - */ - public static DateTime parse(final CharSequence dateStr, final String format) { - return new DateTime(dateStr, format); - } - - /** - * 将特定格式的日期转换为Date对象 - * - * @param dateStr 特定格式的日期 - * @param format 格式,例如yyyy-MM-dd - * @param locale 区域信息 - * @return 日期对象 - */ - public static DateTime parse(final CharSequence dateStr, final String format, final Locale locale) { - if (CustomFormat.isCustomFormat(format)) { - // 自定义格式化器忽略Locale - return new DateTime(CustomFormat.parse(dateStr, format)); - } - return new DateTime(dateStr, newSimpleFormat(format, locale, null)); - } - - /** - * 通过给定的日期格式解析日期时间字符串 - * 传入的日期格式会逐个尝试,直到解析成功,返回{@link DateTime}对象,否则抛出{@link DateException}异常 - * - * @param text 日期时间字符串,非空 - * @param parsePatterns 需要尝试的日期时间格式数组,非空, 见SimpleDateFormat - * @return 解析后的Date - * @throws IllegalArgumentException if the date string or pattern array is null - * @throws DateException if none of the date patterns were suitable - */ - public static DateTime parse(final String text, final String... parsePatterns) throws DateException { - return date(Calendars.parseByPatterns(text, parsePatterns)); + return Calendar.formatChineseDate(Calendar.calendar(date), withTime); } /** @@ -815,34 +795,34 @@ public static DateTime parse(final CharSequence dateCharSequence) { /** * 修改日期为某个时间字段起始时间 * - * @param date {@link Date} - * @param type 保留到的时间字段,如定义为 {@link Fields.Type#SECOND},表示这个字段不变,这个字段以下字段全部归0 + * @param date {@link Date} + * @param various 保留到的时间字段,如定义为 {@link Various#SECOND},表示这个字段不变,这个字段以下字段全部归0 * @return {@link DateTime} */ - public static DateTime truncate(final Date date, final Fields.Type type) { - return new DateTime(truncate(calendar(date), type)); + public static DateTime truncate(final Date date, final Various various) { + return new DateTime(truncate(calendar(date), various)); } /** * 修改日期为某个时间字段四舍五入时间 * - * @param date {@link Date} - * @param type 时间字段 + * @param date {@link Date} + * @param various 时间字段 * @return {@link DateTime} */ - public static DateTime round(final Date date, final Fields.Type type) { - return new DateTime(round(calendar(date), type)); + public static DateTime round(final Date date, final Various various) { + return new DateTime(round(calendar(date), various)); } /** * 修改日期为某个时间字段结束时间 * - * @param date {@link Date} - * @param type 保留到的时间字段,如定义为 {@link Fields.Type#SECOND},表示这个字段不变,这个字段以下字段全部取最大值 + * @param date {@link Date} + * @param various 保留到的时间字段,如定义为 {@link Various#SECOND},表示这个字段不变,这个字段以下字段全部取最大值 * @return {@link DateTime} */ - public static DateTime ceiling(final Date date, final Fields.Type type) { - return new DateTime(ceiling(calendar(date), type)); + public static DateTime ceiling(final Date date, final Various various) { + return new DateTime(ceiling(calendar(date), various)); } /** @@ -854,12 +834,12 @@ public static DateTime ceiling(final Date date, final Fields.Type type) { *

      * * @param date {@link Date} - * @param type 时间字段 + * @param various 时间字段 * @param truncateMillisecond 是否毫秒归零 * @return {@link DateTime} */ - public static DateTime ceiling(final Date date, final Fields.Type type, final boolean truncateMillisecond) { - return new DateTime(ceiling(calendar(date), type, truncateMillisecond)); + public static DateTime ceiling(final Date date, final Various various, final boolean truncateMillisecond) { + return new DateTime(ceiling(calendar(date), various, truncateMillisecond)); } /** @@ -1106,7 +1086,7 @@ public static DateTime nextMonth() { * @return 偏移后的日期 */ public static DateTime offsetMillisecond(final Date date, final int offset) { - return offset(date, Fields.Type.MILLISECOND, offset); + return offset(date, Various.MILLISECOND, offset); } /** @@ -1117,7 +1097,7 @@ public static DateTime offsetMillisecond(final Date date, final int offset) { * @return 偏移后的日期 */ public static DateTime offsetSecond(final Date date, final int offset) { - return offset(date, Fields.Type.SECOND, offset); + return offset(date, Various.SECOND, offset); } /** @@ -1128,7 +1108,7 @@ public static DateTime offsetSecond(final Date date, final int offset) { * @return 偏移后的日期 */ public static DateTime offsetMinute(final Date date, final int offset) { - return offset(date, Fields.Type.MINUTE, offset); + return offset(date, Various.MINUTE, offset); } /** @@ -1139,7 +1119,7 @@ public static DateTime offsetMinute(final Date date, final int offset) { * @return 偏移后的日期 */ public static DateTime offsetHour(final Date date, final int offset) { - return offset(date, Fields.Type.HOUR_OF_DAY, offset); + return offset(date, Various.HOUR_OF_DAY, offset); } /** @@ -1150,7 +1130,7 @@ public static DateTime offsetHour(final Date date, final int offset) { * @return 偏移后的日期 */ public static DateTime offsetDay(final Date date, final int offset) { - return offset(date, Fields.Type.DAY_OF_YEAR, offset); + return offset(date, Various.DAY_OF_YEAR, offset); } /** @@ -1161,7 +1141,7 @@ public static DateTime offsetDay(final Date date, final int offset) { * @return 偏移后的日期 */ public static DateTime offsetWeek(final Date date, final int offset) { - return offset(date, Fields.Type.WEEK_OF_YEAR, offset); + return offset(date, Various.WEEK_OF_YEAR, offset); } /** @@ -1172,19 +1152,30 @@ public static DateTime offsetWeek(final Date date, final int offset) { * @return 偏移后的日期 */ public static DateTime offsetMonth(final Date date, final int offset) { - return offset(date, Fields.Type.MONTH, offset); + return offset(date, Various.MONTH, offset); + } + + /** + * 偏移年 + * + * @param date 日期 + * @param offset 偏移月数,正数向未来偏移,负数向历史偏移 + * @return 偏移后的日期 + */ + public static DateTime offsetYear(final Date date, final int offset) { + return offset(date, Various.YEAR, offset); } /** * 获取指定日期偏移指定时间后的时间,生成的偏移日期不影响原日期 * - * @param date 基准日期 - * @param type 偏移的粒度大小(小时、天、月等){@link Fields.Type} - * @param offset 偏移量,正数为向后偏移,负数为向前偏移 + * @param date 基准日期 + * @param various 偏移的粒度大小(小时、天、月等){@link Various} + * @param offset 偏移量,正数为向后偏移,负数为向前偏移 * @return 偏移后的日期 */ - public static DateTime offset(final Date date, final Fields.Type type, final int offset) { - return dateNew(date).offset(type, offset); + public static DateTime offset(final Date date, final Various various, final int offset) { + return dateNew(date).offset(various, offset); } /** @@ -1192,10 +1183,10 @@ public static DateTime offset(final Date date, final Fields.Type type, final int * * @param beginDate 起始日期 * @param endDate 结束日期 - * @param unit 相差的单位:相差 天{@link Fields.Units#DAY}、小时{@link Fields.Units#HOUR} 等 + * @param unit 相差的单位:相差 天{@link Units#DAY}、小时{@link Units#HOUR} 等 * @return 日期差 */ - public static long between(final Date beginDate, final Date endDate, final Fields.Units unit) { + public static long between(final Date beginDate, final Date endDate, final Units unit) { return between(beginDate, endDate, unit, true); } @@ -1204,11 +1195,11 @@ public static long between(final Date beginDate, final Date endDate, final Field * * @param beginDate 起始日期 * @param endDate 结束日期 - * @param unit 相差的单位:相差 天{@link Fields.Units#DAY}、小时{@link Fields.Units#HOUR} 等 + * @param unit 相差的单位:相差 天{@link Units#DAY}、小时{@link Units#HOUR} 等 * @param isAbs 日期间隔是否只保留绝对值正数 * @return 日期差 */ - public static long between(final Date beginDate, final Date endDate, final Fields.Units unit, final boolean isAbs) { + public static long between(final Date beginDate, final Date endDate, final Units unit, final boolean isAbs) { return new Between(beginDate, endDate, isAbs).between(unit); } @@ -1220,7 +1211,7 @@ public static long between(final Date beginDate, final Date endDate, final Field * @return 日期差 */ public static long betweenMs(final Date beginDate, final Date endDate) { - return new Between(beginDate, endDate).between(Fields.Units.MS); + return new Between(beginDate, endDate).between(Units.MS); } /** @@ -1243,7 +1234,7 @@ public static long betweenDay(Date beginDate, Date endDate, final boolean isRese beginDate = beginOfDay(beginDate); endDate = beginOfDay(endDate); } - return between(beginDate, endDate, Fields.Units.DAY); + return between(beginDate, endDate, Units.DAY); } /** @@ -1259,7 +1250,7 @@ public static long betweenWeek(Date beginDate, Date endDate, final boolean isRes beginDate = beginOfDay(beginDate); endDate = beginOfDay(endDate); } - return between(beginDate, endDate, Fields.Units.WEEK); + return between(beginDate, endDate, Units.WEEK); } /** @@ -1297,7 +1288,7 @@ public static long betweenYear(final Date beginDate, final Date endDate, final b * @return XX天XX小时XX分XX秒 */ public static String formatBetween(final Date beginDate, final Date endDate, final FormatPeriod.Level level) { - return formatBetween(between(beginDate, endDate, Fields.Units.MS), level); + return formatBetween(between(beginDate, endDate, Units.MS), level); } /** @@ -1308,7 +1299,7 @@ public static String formatBetween(final Date beginDate, final Date endDate, fin * @return XX天XX小时XX分XX秒 */ public static String formatBetween(final Date beginDate, final Date endDate) { - return formatBetween(between(beginDate, endDate, Fields.Units.MS)); + return formatBetween(between(beginDate, endDate, Units.MS)); } /** @@ -1332,92 +1323,6 @@ public static String formatBetween(final long betweenMs) { return FormatPeriod.of(betweenMs, FormatPeriod.Level.MILLISECOND).format(); } - /** - * 当前日期是否在日期指定范围内 - * 起始日期和结束日期可以互换 - * - * @param date 被检查的日期 - * @param beginDate 起始日期(包含) - * @param endDate 结束日期(包含) - * @return 是否在范围内 - */ - public static boolean isIn(final Date date, final Date beginDate, final Date endDate) { - return isIn(date, beginDate, endDate, true, true); - } - - /** - * 当前日期是否在日期指定范围内 - * 起始日期和结束日期可以互换 - * 通过includeBegin, includeEnd参数控制日期范围区间是否为开区间,例如:传入参数:includeBegin=true, includeEnd=false, - * 则本方法会判断 date ∈ (beginDate, endDate] 是否成立 - * - * @param date 被检查的日期 - * @param beginDate 起始日期 - * @param endDate 结束日期 - * @param includeBegin 时间范围是否包含起始日期 - * @param includeEnd 时间范围是否包含结束日期 - * @return 是否在范围内 - */ - public static boolean isIn(final Date date, final Date beginDate, final Date endDate, - final boolean includeBegin, final boolean includeEnd) { - return new DateTime().isIn(date, beginDate, endDate, includeBegin, includeEnd); - } - - /** - * 是否为相同时间 - * 此方法比较两个日期的时间戳是否相同 - * - * @param date1 日期1 - * @param date2 日期2 - * @return 是否为相同时间 - */ - public static boolean isSameTime(final Date date1, final Date date2) { - return date1.compareTo(date2) == 0; - } - - /** - * 比较两个日期是否为同一天 - * - * @param date1 日期1 - * @param date2 日期2 - * @return 是否为同一天 - */ - public static boolean isSameDay(final Date date1, final Date date2) { - if (date1 == null || date2 == null) { - throw new IllegalArgumentException("The date must not be null"); - } - return Calendars.isSameDay(calendar(date1), calendar(date2)); - } - - /** - * 比较两个日期是否为同一周 - * - * @param date1 日期1 - * @param date2 日期2 - * @param isMon 是否为周一。国内第一天为星期一,国外第一天为星期日 - * @return 是否为同一周 - */ - public static boolean isSameWeek(final Date date1, final Date date2, final boolean isMon) { - if (date1 == null || date2 == null) { - throw new IllegalArgumentException("The date must not be null"); - } - return Calendars.isSameWeek(calendar(date1), calendar(date2), isMon); - } - - /** - * 比较两个日期是否为同一月 - * - * @param date1 日期1 - * @param date2 日期2 - * @return 是否为同一月 - */ - public static boolean isSameMonth(final Date date1, final Date date2) { - if (date1 == null || date2 == null) { - throw new IllegalArgumentException("The date must not be null"); - } - return Calendars.isSameMonth(calendar(date1), calendar(date2)); - } - /** * 计时,常用于记录某段代码的执行时间,单位:纳秒 * @@ -1522,16 +1427,6 @@ public static int ageOfNow(final Date birthDay) { return age(birthDay, now()); } - /** - * 是否闰年 - * - * @param year 年 - * @return 是否闰年 - */ - public static boolean isLeapYear(final int year) { - return Year.isLeap(year); - } - /** * 计算相对于dateToCompare的年龄,常用于计算指定生日在某年的年龄 * 按照《最高人民法院关于审理未成年人刑事案件具体应用法律若干问题的解释》第二条规定刑法第十七条规定的“周岁”,按照公历的年、月、日计算,从周岁生日的第二天起算。 @@ -1615,7 +1510,7 @@ public static String secondToTime(final int seconds) { * @param unit 步进单位 * @return {@link Boundary} */ - public static Boundary range(final Date start, final Date end, final Fields.Type unit) { + public static Boundary range(final Date start, final Date end, final Various unit) { return new Boundary(start, end, unit); } @@ -1655,7 +1550,7 @@ public static List rangeNotContains(final Boundary start, final Bounda * @param Date经过函数处理结果类型 * @return 结果列表 */ - public static List rangeFunc(final Date start, final Date end, final Fields.Type unit, final Function func) { + public static List rangeFunc(final Date start, final Date end, final Various unit, final Function func) { if (start == null || end == null || start.after(end)) { return Collections.emptyList(); } @@ -1674,7 +1569,7 @@ public static List rangeFunc(final Date start, final Date end, final Fiel * @param unit 步进单位 * @param consumer 每次遍历要执行的 consumer */ - public static void rangeConsume(final Date start, final Date end, final Fields.Type unit, final Consumer consumer) { + public static void rangeConsume(final Date start, final Date end, final Various unit, final Consumer consumer) { if (start == null || end == null || start.after(end)) { return; } @@ -1689,7 +1584,7 @@ public static void rangeConsume(final Date start, final Date end, final Fields.T * @param unit 步进单位 * @return {@link Boundary} */ - public static List rangeToList(final Date start, final Date end, final Fields.Type unit) { + public static List rangeToList(final Date start, final Date end, final Various unit) { return ListKit.of((Iterable) range(start, end, unit)); } @@ -1702,7 +1597,7 @@ public static List rangeToList(final Date start, final Date end, final * @param step 步进 * @return {@link Boundary} */ - public static List rangeToList(final Date start, final Date end, final Fields.Type unit, final int step) { + public static List rangeToList(final Date start, final Date end, final Various unit, final int step) { return ListKit.of((Iterable) new Boundary(start, end, unit, step)); } @@ -1713,29 +1608,18 @@ public static List rangeToList(final Date start, final Date end, final * @param day 天 * @return 星座名 */ - public static String getZodiac(final int month, final int day) { - return Zodiac.getZodiac(month, day); + public static String getConstellation(final int month, final int day) { + return Constellation.getName(month, day); } /** - * 计算生肖,只计算1900年后出生的人 + * 计算生肖 * * @param year 农历年 * @return 生肖名 */ - public static String getChineseZodiac(final int year) { - return Zodiac.getChineseZodiac(year); - } - - /** - * {@code null}安全的日期比较,{@code null}对象排在末尾 - * - * @param date1 日期1 - * @param date2 日期2 - * @return 比较结果,如果date1 < date2,返回数小于0,date1==date2返回0,date1 > date2 大于0 - */ - public static int compare(final Date date1, final Date date2) { - return CompareKit.compare(date1, date2); + public static String getZodiac(final int year) { + return Zodiac.getName(year); } /** @@ -1795,7 +1679,7 @@ public static Instant toInstant(final Date date) { * @return {@link Instant}对象 */ public static Instant toInstant(final TemporalAccessor temporalAccessor) { - return Almanac.toInstant(temporalAccessor); + return Calculate.toInstant(temporalAccessor); } /** @@ -1814,10 +1698,9 @@ public static LocalDateTime toLocalDateTime(final Instant instant) { * * @param date {@link Date} * @return {@link LocalDateTime} - * @see Resolver#of(Date) */ public static LocalDateTime toLocalDateTime(final Date date) { - return Resolver.of(date); + return of(date); } /** @@ -1842,35 +1725,20 @@ public static int lengthOfMonth(final int month, final boolean isLeapYear) { } /** - * 创建{@link SimpleDateFormat},注意此对象非线程安全! - * 此对象默认为严格格式模式,即parse时如果格式不正确会报错。 - * - * @param pattern 表达式 - * @return {@link SimpleDateFormat} - */ - public static SimpleDateFormat newSimpleFormat(final String pattern) { - return newSimpleFormat(pattern, null, null); - } - - /** - * 创建{@link SimpleDateFormat},注意此对象非线程安全! - * 此对象默认为严格格式模式,即parse时如果格式不正确会报错。 + * {@link Date}转{@link LocalDateTime},使用默认时区 * - * @param pattern 表达式 - * @param locale {@link Locale},{@code null}表示默认 - * @param timeZone {@link TimeZone},{@code null}表示默认 - * @return {@link SimpleDateFormat} + * @param date Date对象 + * @return {@link LocalDateTime} */ - public static SimpleDateFormat newSimpleFormat(final String pattern, Locale locale, final TimeZone timeZone) { - if (null == locale) { - locale = Locale.getDefault(Locale.Category.FORMAT); + public static LocalDateTime of(final Date date) { + if (null == date) { + return null; } - final SimpleDateFormat format = new SimpleDateFormat(pattern, locale); - if (null != timeZone) { - format.setTimeZone(timeZone); + + if (date instanceof DateTime) { + return of(date.toInstant(), ((DateTime) date).getZoneId()); } - format.setLenient(false); - return format; + return of(date.toInstant()); } /** @@ -1942,69 +1810,6 @@ public static int getLastDayOfMonth(final Date date) { return date(date).getLastDayOfMonth(); } - /** - * 标准化日期,默认处理以空格区分的日期时间格式,空格前为日期,空格后为时间: - * 将以下字符替换为"-" - * - *
      -     * "."
      -     * "/"
      -     * "年"
      -     * "月"
      -     * 
      - *

      - * 将以下字符去除 - * - *

      -     * "日"
      -     * 
      - *

      - * 将以下字符替换为":" - * - *

      -     * "时"
      -     * "分"
      -     * "秒"
      -     * 
      - *

      - * 当末位是":"时去除之(不存在毫秒时) - * - * @param dateStr 日期时间字符串 - * @return 格式化后的日期字符串 - */ - private static String normalize(final CharSequence dateStr) { - if (StringKit.isBlank(dateStr)) { - return StringKit.toString(dateStr); - } - - // 日期时间分开处理 - final List dateAndTime = CharsBacker.splitTrim(dateStr, Symbol.SPACE); - final int size = dateAndTime.size(); - if (size < 1 || size > 2) { - // 非可被标准处理的格式 - return StringKit.toString(dateStr); - } - - final StringBuilder builder = StringKit.builder(); - - // 日期部分("\"、"/"、"."、"年"、"月"都替换为"-") - String datePart = dateAndTime.get(0).replaceAll("[/.年月]", Symbol.MINUS); - datePart = StringKit.removeSuffix(datePart, "日"); - builder.append(datePart); - - // 时间部分 - if (size == 2) { - builder.append(Symbol.C_SPACE); - String timePart = dateAndTime.get(1).replaceAll("[时分秒]", Symbol.COLON); - timePart = StringKit.removeSuffix(timePart, Symbol.COLON); - //将ISO8601中的逗号替换为. - timePart = timePart.replace(',', '.'); - builder.append(timePart); - } - - return builder.toString(); - } - /** * 当前日期是否在日期指定范围内 * 起始日期和结束日期可以互换 diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/FileKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/FileKit.java index edc9582fc3..483cbff3e0 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/FileKit.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/FileKit.java @@ -700,8 +700,8 @@ public static File mkParentDirs(final String path) { * @param fullFileOrDirPath 文件或者目录的路径 * @throws InternalException IO异常 */ - public static void del(final String fullFileOrDirPath) throws InternalException { - del(file(fullFileOrDirPath)); + public static void remove(final String fullFileOrDirPath) throws InternalException { + remove(file(fullFileOrDirPath)); } /** @@ -713,9 +713,9 @@ public static void del(final String fullFileOrDirPath) throws InternalException * @throws InternalException IO异常 * @see Files#delete(Path) */ - public static void del(final File file) throws InternalException { + public static void remove(final File file) throws InternalException { Assert.notNull(file, "File must be not null!"); - del(file.toPath()); + remove(file.toPath()); } /** @@ -1442,9 +1442,6 @@ public static boolean isModified(final File file, final long lastModifyTime) { *

    • 4. .. 和 . 转换为绝对路径,当..多于已有路径时,直接返回根路径
    • *
    • 5. SMB路径保留,如\\127.0.0.0\a\b.zip
    • * - *

      - * 栗子: - * *

            * "/foo//" = "/foo/"
            * "/foo/./" = "/foo/"
      @@ -1472,9 +1469,6 @@ public static String normalize(final String path) {
       
           /**
            * 获得相对子路径
      -     * 

      - * 栗子: - * *

            * dirPath: d:/aaa/bbb    filePath: d:/aaa/bbb/ccc         =    ccc
            * dirPath: d:/Aaa/bbb    filePath: d:/aaa/bbb/ccc.txt     =    ccc.txt
      @@ -1494,9 +1488,6 @@ public static String subPath(final String rootDir, final File file) {
       
           /**
            * 获得相对子路径,忽略大小写
      -     * 

      - * 栗子: - * *

            * dirPath: d:/aaa/bbb    filePath: d:/aaa/bbb/ccc        =    ccc
            * dirPath: d:/Aaa/bbb    filePath: d:/aaa/bbb/ccc.txt    =    ccc.txt
      diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/IoKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/IoKit.java
      index ac42527f0f..f784b5bb84 100644
      --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/IoKit.java
      +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/IoKit.java
      @@ -1053,7 +1053,7 @@ public Timeout timeout() {
       
                   @Override
                   public String toString() {
      -                return "sink(" + out + ")";
      +                return "sink(" + out + Symbol.PARENTHESE_RIGHT;
                   }
               };
           }
      @@ -1143,7 +1143,7 @@ public Timeout timeout() {
       
                   @Override
                   public String toString() {
      -                return "source(" + in + ")";
      +                return "source(" + in + Symbol.PARENTHESE_RIGHT;
                   }
               };
           }
      diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/ListKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/ListKit.java
      index a970bbcb6b..b9cd841d46 100644
      --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/ListKit.java
      +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/ListKit.java
      @@ -678,4 +678,75 @@ public static  List splice(final List list, int start, int deleteCount,
               return resList;
           }
       
      +    /**
      +     * 对指定List分页取值
      +     *
      +     * @param       集合元素类型
      +     * @param pageNo   页码,从1开始计数,0和1效果相同
      +     * @param pageSize 每页的条目数
      +     * @param list     列表
      +     * @return 分页后的段落内容
      +     */
      +    public static  List page(int pageNo, int pageSize, List list) {
      +        if (CollKit.isEmpty(list)) {
      +            return new ArrayList<>(0);
      +        }
      +
      +        int resultSize = list.size();
      +        // 每页条目数大于总数直接返回所有
      +        if (resultSize <= pageSize) {
      +            if (pageNo <= 1) {
      +                return unmodifiable(list);
      +            } else {
      +                // 越界直接返回空
      +                return new ArrayList<>(0);
      +            }
      +        }
      +
      +        if (pageNo < 1) {
      +            pageNo = 1;
      +        }
      +
      +        if (pageSize < 1) {
      +            pageSize = 0;
      +        }
      +
      +        int start = (pageNo - 1) * pageSize;
      +        int end = start + pageSize;
      +
      +
      +        final int[] startEnd = new int[]{start, end};
      +        if (startEnd[1] > resultSize) {
      +            startEnd[1] = resultSize;
      +            if (startEnd[0] > startEnd[1]) {
      +                return new ArrayList<>(0);
      +            }
      +        }
      +        return sub(list, startEnd[0], startEnd[1]);
      +    }
      +
      +    /**
      +     * 将元素移动到指定列表的新位置。
      +     * 
        + *
      • 如果元素不在列表中,则将其添加到新位置。
      • + *
      • 如果元素已在列表中,则先移除它,然后再将其添加到新位置。
      • + *
      + * + * @param list 原始列表,元素将在这个列表上进行操作。 + * @param element 需要移动的元素。 + * @param newPosition 元素的新位置,从0开始计数,位置计算是以移除元素后的列表位置计算的 + * @param 列表和元素的通用类型。 + * @return the list + */ + public static List move(final List list, final T element, final int newPosition) { + Assert.notNull(list); + if (!list.contains(element)) { + list.add(newPosition, element); + } else { + list.remove(element); + list.add(newPosition, element); + } + return list; + } + } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/MathKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/MathKit.java index 76600e2f81..081036036f 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/MathKit.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/MathKit.java @@ -1110,12 +1110,31 @@ public static BigDecimal pow(final Number number, final int n) { /** * 提供精确的幂运算 + * 如果n为负数,则返回1/a的-n次方,默认四舍五入 * * @param number 底数 - * @param n 指数 + * @param n 指数,如果为负数,则返回1/a的-n次方 * @return 幂的积 */ public static BigDecimal pow(final BigDecimal number, final int n) { + return pow(number, n, 2, RoundingMode.HALF_UP); + } + + /** + * 提供精确的幂运算 + * 如果n为负数,则返回1/a的-n次方,默认四舍五入 + * + * @param number 底数 + * @param scale 保留小数位数 + * @param roundingMode 舍入模式 + * @param n 指数,如果为负数,则返回1/a的-n次方 + * @return 幂的积 + */ + public static BigDecimal pow(final BigDecimal number, final int n, final int scale, final RoundingMode roundingMode) { + if (n < 0) { + // a的n次方,如果n为负数,则返回1/a的-n次方 + return BigDecimal.ONE.divide(pow(number, -n), scale, roundingMode); + } return number.pow(n); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/PhoneKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/PhoneKit.java index 108777b3cb..60e4aa2b0f 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/PhoneKit.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/PhoneKit.java @@ -114,7 +114,6 @@ public static boolean isPhone(final CharSequence value) { /** * 隐藏手机号前7位 替换字符为"*" - * 栗子 * * @param phone 手机号码 * @return 替换后的字符串 diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/RandomKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/RandomKit.java index 71be2d6367..055e23c757 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/RandomKit.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/RandomKit.java @@ -26,8 +26,8 @@ package org.miaixz.bus.core.xyz; import org.miaixz.bus.core.center.date.DateTime; +import org.miaixz.bus.core.center.date.culture.en.Various; import org.miaixz.bus.core.lang.Assert; -import org.miaixz.bus.core.lang.Fields; import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.lang.exception.InternalException; import org.miaixz.bus.core.lang.selector.WeightObject; @@ -579,7 +579,7 @@ public static int[] randomPickInts(final int size, final int[] seed) { * @throws IllegalArgumentException 需要的长度大于给定集合非重复总数 */ public static Set randomEleSet(final Collection collection, final int count) { - final ArrayList source = CollKit.distinct(collection); + final List source = CollKit.distinct(collection); if (count > source.size()) { throw new IllegalArgumentException("Count is larger than collection distinct size !"); } @@ -741,24 +741,24 @@ public static WeightRandomSelector weightRandom(final Iterable[] parameterTypes = methodOrConstructor.getParameterTypes(); @@ -267,7 +267,7 @@ public static String getDesc(final Executable methodOrConstructor, final boolean } // 返回类型或构造标记 - ret.append(')'); + ret.append(Symbol.C_PARENTHESE_RIGHT); if (methodOrConstructor instanceof Method) { ret.append(getDesc(((Method) methodOrConstructor).getReturnType())); } else { @@ -317,7 +317,7 @@ public static String getName(Class c) { * @return 名称 */ public static String getName(final Executable executable) { - final StringBuilder ret = new StringBuilder("("); + final StringBuilder ret = new StringBuilder(Symbol.PARENTHESE_LEFT); if (executable instanceof Method) { ret.append(getName(((Method) executable).getReturnType())).append(Symbol.C_SPACE); @@ -327,12 +327,12 @@ public static String getName(final Executable executable) { final Class[] parameterTypes = executable.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if (i > 0) { - ret.append(','); + ret.append(Symbol.C_COMMA); } ret.append(getName(parameterTypes[i])); } - ret.append(')'); + ret.append(Symbol.C_PARENTHESE_RIGHT); return ret.toString(); } diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/StringKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/StringKit.java index 6cff974192..649dd8c656 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/StringKit.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/StringKit.java @@ -54,15 +54,12 @@ public class StringKit extends CharsBacker { *
    • 空字符串:{@code ""}
    • *
    • 空格、全角空格、制表符、换行符,等不可见字符
    • * - * - * 例: *
        *
      • {@code StringKit.isBlankIfString(null) // true}
      • *
      • {@code StringKit.isBlankIfString("") // true}
      • *
      • {@code StringKit.isBlankIfString(" \t\n") // true}
      • *
      • {@code StringKit.isBlankIfString("abc") // false}
      • *
      - * * 注意:该方法与 {@link #isEmptyIfString(Object)} 的区别是: * 该方法会校验空白字符,且性能相对于 {@link #isEmptyIfString(Object)} 略慢。 * @@ -85,8 +82,6 @@ public static boolean isBlankIfString(final Object obj) { *
    • {@code null}
    • *
    • 空字符串:{@code ""}
    • * - * - * 例: *
        *
      • {@code StringKit.isEmptyIfString(null) // true}
      • *
      • {@code StringKit.isEmptyIfString("") // true}
      • diff --git a/bus-core/src/main/java/org/miaixz/bus/core/xyz/UrlKit.java b/bus-core/src/main/java/org/miaixz/bus/core/xyz/UrlKit.java index aea615dffe..3e328a2135 100644 --- a/bus-core/src/main/java/org/miaixz/bus/core/xyz/UrlKit.java +++ b/bus-core/src/main/java/org/miaixz/bus/core/xyz/UrlKit.java @@ -580,7 +580,7 @@ public static String getDataUri(final String mimeType, final java.nio.charset.Ch if (StringKit.isNotBlank(encoding)) { builder.append(Symbol.C_SEMICOLON).append(encoding); } - builder.append(',').append(data); + builder.append(Symbol.C_COMMA).append(data); return builder.toString(); } diff --git a/bus-cron/pom.xml b/bus-cron/pom.xml index 8aee07cc9f..42f70dbc96 100755 --- a/bus-cron/pom.xml +++ b/bus-cron/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-cron - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-cron/src/main/java/org/miaixz/bus/cron/CronTimer.java b/bus-cron/src/main/java/org/miaixz/bus/cron/CronTimer.java index 6ea0808563..df0545e5bc 100644 --- a/bus-cron/src/main/java/org/miaixz/bus/cron/CronTimer.java +++ b/bus-cron/src/main/java/org/miaixz/bus/cron/CronTimer.java @@ -25,7 +25,7 @@ ********************************************************************************/ package org.miaixz.bus.cron; -import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.center.date.culture.en.Units; import org.miaixz.bus.core.xyz.ThreadKit; import org.miaixz.bus.logger.Logger; @@ -45,11 +45,11 @@ public class CronTimer extends Thread implements Serializable { /** * 定时单元:秒 */ - private final long TIMER_UNIT_SECOND = Fields.Units.SECOND.getMillis(); + private final long TIMER_UNIT_SECOND = Units.SECOND.getMillis(); /** * 定时单元:分 */ - private final long TIMER_UNIT_MINUTE = Fields.Units.MINUTE.getMillis(); + private final long TIMER_UNIT_MINUTE = Units.MINUTE.getMillis(); private final Scheduler scheduler; /** * 定时任务是否已经被强制关闭 diff --git a/bus-cron/src/main/java/org/miaixz/bus/cron/Expression.java b/bus-cron/src/main/java/org/miaixz/bus/cron/Expression.java index 5d2d705490..9ef3c5a4b7 100644 --- a/bus-cron/src/main/java/org/miaixz/bus/cron/Expression.java +++ b/bus-cron/src/main/java/org/miaixz/bus/cron/Expression.java @@ -298,8 +298,7 @@ protected void buildExpression(String expression) throws ParseException { } catch (ParseException pe) { throw pe; } catch (Exception e) { - throw new ParseException("Illegal cron expression format (" - + e + ")", 0); + throw new ParseException("Illegal cron expression format (" + e + ")", 0); } } diff --git a/bus-cron/src/main/java/org/miaixz/bus/cron/annotation/package-info.java b/bus-cron/src/main/java/org/miaixz/bus/cron/annotation/package-info.java deleted file mode 100644 index 6aa1a9eebd..0000000000 --- a/bus-cron/src/main/java/org/miaixz/bus/cron/annotation/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * 提供cron增强型注解 - * - * @author Kimi Liu - * @since Java 17+ - */ -package org.miaixz.bus.cron.annotation; \ No newline at end of file diff --git a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/CronPattern.java b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/CronPattern.java index 57888ef926..e31953921d 100644 --- a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/CronPattern.java +++ b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/CronPattern.java @@ -25,9 +25,9 @@ ********************************************************************************/ package org.miaixz.bus.cron.pattern; -import org.miaixz.bus.core.center.date.Calendars; +import org.miaixz.bus.core.center.date.Calendar; +import org.miaixz.bus.core.center.date.culture.en.Week; import org.miaixz.bus.core.lang.Assert; -import org.miaixz.bus.core.lang.Fields; import org.miaixz.bus.core.xyz.CompareKit; import org.miaixz.bus.core.xyz.DateKit; import org.miaixz.bus.cron.pattern.matcher.PatternMatcher; @@ -80,7 +80,7 @@ * 例如 2,3,6/3中,由于“/”优先级高,因此相当于2,3,(6/3),结果与 2,3,6等价 * *

        - * 一些例子: + * 一些示例: *

          *
        • 5 * * * * :每个点钟的5分执行,00:05,01:05……
        • *
        • * * * * * :每分钟执行
        • @@ -126,7 +126,7 @@ public static CronPattern of(final String pattern) { * @return 日期 */ public static Date nextDateAfter(final CronPattern pattern, final Date start) { - return DateKit.date(pattern.nextMatchAfter(Calendars.calendar(start))); + return DateKit.date(pattern.nextMatchAfter(Calendar.calendar(start))); } /** @@ -181,7 +181,7 @@ public static List matchedDates(final CronPattern pattern, final long star final List result = new ArrayList<>(count); - Calendar calendar = pattern.nextMatchAfter(Calendars.calendar(start)); + java.util.Calendar calendar = pattern.nextMatchAfter(Calendar.calendar(start)); while (calendar.getTimeInMillis() < end) { result.add(DateKit.date(calendar)); if (result.size() >= count) { @@ -197,7 +197,7 @@ public static List matchedDates(final CronPattern pattern, final long star * 获取处理后的字段列表 * 月份从1开始,周从0开始 * - * @param dateTime {@link Calendar} + * @param dateTime {@link java.util.Calendar} * @param isMatchSecond 是否匹配秒,{@link false}则秒返回-1 * @return 字段值列表 */ @@ -207,7 +207,7 @@ static int[] getFields(final LocalDateTime dateTime, final boolean isMatchSecond final int hour = dateTime.getHour(); final int dayOfMonth = dateTime.getDayOfMonth(); final int month = dateTime.getMonthValue();// 月份从1开始 - final int dayOfWeek = Fields.Week.of(dateTime.getDayOfWeek()).getValue() - 1; // 星期从0开始,0和7都表示周日 + final int dayOfWeek = Week.of(dateTime.getDayOfWeek()).getCode() - 1; // 星期从0开始,0和7都表示周日 final int year = dateTime.getYear(); return new int[]{second, minute, hour, dayOfMonth, month, dayOfWeek, year}; } @@ -216,18 +216,18 @@ static int[] getFields(final LocalDateTime dateTime, final boolean isMatchSecond * 获取处理后的字段列表 * 月份从1开始,周从0开始 * - * @param calendar {@link Calendar} + * @param calendar {@link java.util.Calendar} * @param isMatchSecond 是否匹配秒,{@link false}则秒返回-1 * @return 字段值列表 */ - static int[] getFields(final Calendar calendar, final boolean isMatchSecond) { - final int second = isMatchSecond ? calendar.get(Calendar.SECOND) : -1; - final int minute = calendar.get(Calendar.MINUTE); - final int hour = calendar.get(Calendar.HOUR_OF_DAY); - final int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); - final int monthBase1 = calendar.get(Calendar.MONTH) + 1;// 月份从1开始 - final int dayOfWeekBase0 = calendar.get(Calendar.DAY_OF_WEEK) - 1; // 星期从0开始,0和7都表示周日 - final int year = calendar.get(Calendar.YEAR); + static int[] getFields(final java.util.Calendar calendar, final boolean isMatchSecond) { + final int second = isMatchSecond ? calendar.get(java.util.Calendar.SECOND) : -1; + final int minute = calendar.get(java.util.Calendar.MINUTE); + final int hour = calendar.get(java.util.Calendar.HOUR_OF_DAY); + final int dayOfMonth = calendar.get(java.util.Calendar.DAY_OF_MONTH); + final int monthBase1 = calendar.get(java.util.Calendar.MONTH) + 1;// 月份从1开始 + final int dayOfWeekBase0 = calendar.get(java.util.Calendar.DAY_OF_WEEK) - 1; // 星期从0开始,0和7都表示周日 + final int year = calendar.get(java.util.Calendar.YEAR); return new int[]{second, minute, hour, dayOfMonth, monthBase1, dayOfWeekBase0, year}; } @@ -263,7 +263,7 @@ public boolean match(final TimeZone timezone, final long millis, final boolean i * @param isMatchSecond 是否匹配秒 * @return 如果匹配返回 {@code true}, 否则返回 {@code false} */ - public boolean match(final Calendar calendar, final boolean isMatchSecond) { + public boolean match(final java.util.Calendar calendar, final boolean isMatchSecond) { return match(getFields(calendar, isMatchSecond)); } @@ -284,18 +284,18 @@ public boolean match(final LocalDateTime dateTime, final boolean isMatchSecond) * @param calendar 时间 * @return 匹配到的下一个时间 */ - public Calendar nextMatchAfter(Calendar calendar) { + public java.util.Calendar nextMatchAfter(java.util.Calendar calendar) { // 当提供的时间已经匹配表达式时,增加1秒以匹配下一个时间 if (match(calendar, true)) { - final Calendar newCalendar = Calendar.getInstance(calendar.getTimeZone()); + final java.util.Calendar newCalendar = java.util.Calendar.getInstance(calendar.getTimeZone()); newCalendar.setTimeInMillis(calendar.getTimeInMillis() + 1000); calendar = newCalendar; } - Calendar next = nextMatchAfter(getFields(calendar, true), calendar.getTimeZone()); + java.util.Calendar next = nextMatchAfter(getFields(calendar, true), calendar.getTimeZone()); if (!match(next, true)) { - next.set(Calendar.DAY_OF_MONTH, next.get(Calendar.DAY_OF_MONTH) + 1); - next = Calendars.beginOfDay(next); + next.set(java.util.Calendar.DAY_OF_MONTH, next.get(java.util.Calendar.DAY_OF_MONTH) + 1); + next = Calendar.beginOfDay(next); return nextMatchAfter(next); } return next; @@ -343,10 +343,10 @@ private boolean match(final int[] fields) { * * @param values 时间字段值,{second, minute, hour, dayOfMonth, monthBase1, dayOfWeekBase0, year} * @param zone 时区 - * @return {@link Calendar},毫秒数为0 + * @return {@link java.util.Calendar},毫秒数为0 */ - private Calendar nextMatchAfter(final int[] values, final TimeZone zone) { - Calendar minMatch = null; + private java.util.Calendar nextMatchAfter(final int[] values, final TimeZone zone) { + java.util.Calendar minMatch = null; for (final PatternMatcher matcher : matchers) { if (null == minMatch) { minMatch = matcher.nextMatchAfter(values, zone); diff --git a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/CronPatternBuilder.java b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/CronPatternBuilder.java index af532ea5aa..a9ab9204a8 100644 --- a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/CronPatternBuilder.java +++ b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/CronPatternBuilder.java @@ -64,7 +64,7 @@ public CronPatternBuilder setValues(final Part part, final int... values) { for (final int value : values) { part.checkValue(value); } - return set(part, ArrayKit.join(values, ",")); + return set(part, ArrayKit.join(values, Symbol.COMMA)); } /** diff --git a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/Part.java b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/Part.java index ba5eaa270f..5cd1eefe4d 100644 --- a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/Part.java +++ b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/Part.java @@ -25,8 +25,9 @@ ********************************************************************************/ package org.miaixz.bus.cron.pattern; +import org.miaixz.bus.core.center.date.culture.en.Month; +import org.miaixz.bus.core.center.date.culture.en.Week; import org.miaixz.bus.core.lang.Assert; -import org.miaixz.bus.core.lang.Fields; import org.miaixz.bus.core.lang.exception.CrontabException; import java.util.Calendar; @@ -49,8 +50,8 @@ public enum Part { MINUTE(Calendar.MINUTE, 0, 59), HOUR(Calendar.HOUR_OF_DAY, 0, 23), DAY_OF_MONTH(Calendar.DAY_OF_MONTH, 1, 31), - MONTH(Calendar.MONTH, Fields.Month.JANUARY.getValueBaseOne(), Fields.Month.DECEMBER.getValueBaseOne()), - DAY_OF_WEEK(Calendar.DAY_OF_WEEK, Fields.Week.SUNDAY.ordinal(), Fields.Week.SATURDAY.ordinal()), + MONTH(Calendar.MONTH, Month.JANUARY.getIsoValue(), Month.DECEMBER.getIsoValue()), + DAY_OF_WEEK(Calendar.DAY_OF_WEEK, Week.SUNDAY.ordinal(), Week.SATURDAY.ordinal()), YEAR(Calendar.YEAR, 1970, 2099); private static final Part[] ENUMS = Part.values(); diff --git a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/matcher/DayOfMonthMatcher.java b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/matcher/DayOfMonthMatcher.java index 3302594d81..3206934d1f 100644 --- a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/matcher/DayOfMonthMatcher.java +++ b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/matcher/DayOfMonthMatcher.java @@ -25,7 +25,7 @@ ********************************************************************************/ package org.miaixz.bus.cron.pattern.matcher; -import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.center.date.culture.en.Month; import java.util.List; @@ -55,7 +55,7 @@ public DayOfMonthMatcher(final List intValueList) { * @return 最后一天 */ private static int getLastDay(final int month, final boolean isLeapYear) { - return Fields.Month.getLastDay(month - 1, isLeapYear); + return Month.getLastDay(month - 1, isLeapYear); } /** diff --git a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/parser/PartParser.java b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/parser/PartParser.java index 2f6058c7e2..3b5546ba56 100644 --- a/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/parser/PartParser.java +++ b/bus-cron/src/main/java/org/miaixz/bus/cron/pattern/parser/PartParser.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.cron.pattern.parser; -import org.miaixz.bus.core.lang.Fields; +import org.miaixz.bus.core.center.date.culture.en.Month; +import org.miaixz.bus.core.center.date.culture.en.Week; import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.CrontabException; import org.miaixz.bus.core.text.CharsBacker; @@ -271,8 +272,8 @@ private int parseNumber(final String value, final boolean checkValue) throws Cro } // 周日可以用0或7表示,统一转换为0 - if (Part.DAY_OF_WEEK.equals(this.part) && Fields.Week.SUNDAY.getIso8601Value() == i) { - i = Fields.Week.SUNDAY.ordinal(); + if (Part.DAY_OF_WEEK.equals(this.part) && Week.SUNDAY.getIsoValue() == i) { + i = Week.SUNDAY.ordinal(); } return checkValue ? part.checkValue(i) : i; @@ -298,10 +299,10 @@ private int parseAlias(final String name) throws CrontabException { switch (this.part) { case MONTH: // 月份从1开始 - return Fields.Month.of(name).getValueBaseOne(); + return Month.of(name).getIsoValue(); case DAY_OF_WEEK: // 周从0开始,0表示周日 - return Fields.Week.of(name).ordinal(); + return Week.of(name).ordinal(); } throw new CrontabException("Invalid alias value: [{}]", name); diff --git a/bus-crypto/pom.xml b/bus-crypto/pom.xml index 209899390f..5d821e2190 100755 --- a/bus-crypto/pom.xml +++ b/bus-crypto/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-crypto - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/Builder.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/Builder.java index d720dd62a8..c62c1bf952 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/Builder.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/Builder.java @@ -53,13 +53,12 @@ import org.miaixz.bus.core.lang.exception.InternalException; import org.miaixz.bus.core.xyz.*; import org.miaixz.bus.crypto.builtin.digest.Digester; -import org.miaixz.bus.crypto.builtin.digest.mac.BCHMacEngine; -import org.miaixz.bus.crypto.builtin.digest.mac.MacEngine; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.digest.mac.BCHMac; +import org.miaixz.bus.crypto.builtin.digest.mac.Mac; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; import org.miaixz.bus.crypto.center.*; import javax.crypto.Cipher; -import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.*; import java.io.ByteArrayInputStream; @@ -137,7 +136,7 @@ public static AES aes() { *
      * * @param key 密钥 - * @return {@link SymmetricCrypto} + * @return {@link Crypto} */ public static AES aes(final byte[] key) { return new AES(key); @@ -611,17 +610,17 @@ public static MessageDigest createJdkMessageDigest(final String algorithm) { } /** - * 创建{@link Mac} + * 创建{@link javax.crypto.Mac} * * @param algorithm 算法 - * @return {@link Mac} + * @return {@link javax.crypto.Mac} */ - public static Mac createMac(final String algorithm) { + public static javax.crypto.Mac createMac(final String algorithm) { final java.security.Provider provider = Holder.getProvider(); - final Mac mac; + final javax.crypto.Mac mac; try { - mac = (null == provider) ? Mac.getInstance(algorithm) : Mac.getInstance(algorithm, provider); + mac = (null == provider) ? javax.crypto.Mac.getInstance(algorithm) : javax.crypto.Mac.getInstance(algorithm, provider); } catch (final NoSuchAlgorithmException e) { throw new CryptoException(e); } @@ -633,10 +632,10 @@ public static Mac createMac(final String algorithm) { * RC4算法 * * @param key 密钥 - * @return {@link SymmetricCrypto} + * @return {@link Crypto} */ - public static SymmetricCrypto rc4(final byte[] key) { - return new SymmetricCrypto(Algorithm.RC4, key); + public static Crypto rc4(final byte[] key) { + return new Crypto(Algorithm.RC4, key); } /** @@ -807,7 +806,7 @@ public static String sm3(final File dataFile) { } /** - * SM4加密,生成随机KEY。注意解密时必须使用相同 {@link SymmetricCrypto}对象或者使用相同KEY + * SM4加密,生成随机KEY。注意解密时必须使用相同 {@link Crypto}对象或者使用相同KEY * 例: * *
      @@ -815,7 +814,7 @@ public static String sm3(final File dataFile) {
            * SM4解密:sm4().decrypt(data)
            * 
      * - * @return {@link SymmetricCrypto} + * @return {@link Crypto} */ public static SM4 sm4() { return new SM4(); @@ -913,13 +912,13 @@ public static byte[] rsPlainToAsn1(final byte[] sign) { } /** - * 创建HmacSM3算法的{@link MacEngine} + * 创建HmacSM3算法的{@link Mac} * * @param key 密钥 - * @return {@link MacEngine} + * @return {@link Mac} */ - public static MacEngine createHmacSm3Engine(final byte[] key) { - return new BCHMacEngine(new SM3Digest(), key); + public static Mac createHmacSm3Engine(final byte[] key) { + return new BCHMac(new SM3Digest(), key); } /** @@ -1035,7 +1034,7 @@ public static Sign sign(final Algorithm algorithm, final byte[] privateKey, fina * @param otherParams 其它附加参数字符串(例如密钥) * @return 签名 */ - public static String signParams(final SymmetricCrypto crypto, final Map params, final String... otherParams) { + public static String signParams(final Crypto crypto, final Map params, final String... otherParams) { return signParams(crypto, params, Normal.EMPTY, Normal.EMPTY, true, otherParams); } @@ -1051,7 +1050,7 @@ public static String signParams(final SymmetricCrypto crypto, final Map pa * @param otherParams 其它附加参数字符串(例如密钥) * @return 签名 */ - public static String signParams(final SymmetricCrypto crypto, final Map params, final String separator, + public static String signParams(final Crypto crypto, final Map params, final String separator, final String keyValueSeparator, final boolean isIgnoreNull, final String... otherParams) { return crypto.encryptHex(MapKit.sortJoin(params, separator, keyValueSeparator, isIgnoreNull, otherParams)); } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/Provider.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/Provider.java index 088e972766..44d28a1091 100755 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/Provider.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/Provider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2023 aoju.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AbstractAsymmetricCrypto.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AbstractCrypto.java similarity index 90% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AbstractAsymmetricCrypto.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AbstractCrypto.java index cf7a58513d..f8f2fd2b66 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AbstractAsymmetricCrypto.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AbstractCrypto.java @@ -35,9 +35,9 @@ * @author Kimi Liu * @since Java 17+ */ -public abstract class AbstractAsymmetricCrypto> - extends BaseAsymmetric - implements AsymmetricEncryptor, AsymmetricDecryptor { +public abstract class AbstractCrypto> + extends Asymmetric + implements Encryptor, Decryptor { private static final long serialVersionUID = -1L; @@ -51,7 +51,7 @@ public abstract class AbstractAsymmetricCrypto> implements Serializable { +public class Asymmetric> implements Serializable { + private static final long serialVersionUID = -1L; /** @@ -75,7 +76,7 @@ public class BaseAsymmetric> implements Serializable * @param privateKey 私钥 * @param publicKey 公钥 */ - public BaseAsymmetric(final String algorithm, final PrivateKey privateKey, final PublicKey publicKey) { + public Asymmetric(final String algorithm, final PrivateKey privateKey, final PublicKey publicKey) { init(algorithm, privateKey, publicKey); } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AsymmetricCrypto.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/Crypto.java similarity index 91% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AsymmetricCrypto.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/Crypto.java index 8bad17c580..1bedcefbc9 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AsymmetricCrypto.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/Crypto.java @@ -57,7 +57,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class AsymmetricCrypto extends AbstractAsymmetricCrypto { +public class Crypto extends AbstractCrypto { private static final long serialVersionUID = -1L; @@ -88,7 +88,7 @@ public class AsymmetricCrypto extends AbstractAsymmetricCrypto * * @param algorithm {@link Algorithm} */ - public AsymmetricCrypto(final Algorithm algorithm) { + public Crypto(final Algorithm algorithm) { this(algorithm, null, (byte[]) null); } @@ -97,7 +97,7 @@ public AsymmetricCrypto(final Algorithm algorithm) { * * @param algorithm 算法 */ - public AsymmetricCrypto(final String algorithm) { + public Crypto(final String algorithm) { this(algorithm, null, (byte[]) null); } @@ -109,7 +109,7 @@ public AsymmetricCrypto(final String algorithm) { * @param privateKeyStr 私钥Hex或Base64表示 * @param publicKeyStr 公钥Hex或Base64表示 */ - public AsymmetricCrypto(final Algorithm algorithm, final String privateKeyStr, final String publicKeyStr) { + public Crypto(final Algorithm algorithm, final String privateKeyStr, final String publicKeyStr) { this(algorithm.getValue(), Builder.decode(privateKeyStr), Builder.decode(publicKeyStr)); } @@ -121,7 +121,7 @@ public AsymmetricCrypto(final Algorithm algorithm, final String privateKeyStr, f * @param privateKey 私钥 * @param publicKey 公钥 */ - public AsymmetricCrypto(final Algorithm algorithm, final byte[] privateKey, final byte[] publicKey) { + public Crypto(final Algorithm algorithm, final byte[] privateKey, final byte[] publicKey) { this(algorithm.getValue(), privateKey, publicKey); } @@ -133,7 +133,7 @@ public AsymmetricCrypto(final Algorithm algorithm, final byte[] privateKey, fina * @param privateKey 私钥 * @param publicKey 公钥 */ - public AsymmetricCrypto(final Algorithm algorithm, final PrivateKey privateKey, final PublicKey publicKey) { + public Crypto(final Algorithm algorithm, final PrivateKey privateKey, final PublicKey publicKey) { this(algorithm.getValue(), privateKey, publicKey); } @@ -145,7 +145,7 @@ public AsymmetricCrypto(final Algorithm algorithm, final PrivateKey privateKey, * @param privateKeyBase64 私钥Base64 * @param publicKeyBase64 公钥Base64 */ - public AsymmetricCrypto(final String algorithm, final String privateKeyBase64, final String publicKeyBase64) { + public Crypto(final String algorithm, final String privateKeyBase64, final String publicKeyBase64) { this(algorithm, Base64.decode(privateKeyBase64), Base64.decode(publicKeyBase64)); } @@ -159,7 +159,7 @@ public AsymmetricCrypto(final String algorithm, final String privateKeyBase64, f * @param privateKey 私钥 * @param publicKey 公钥 */ - public AsymmetricCrypto(final String algorithm, final byte[] privateKey, final byte[] publicKey) { + public Crypto(final String algorithm, final byte[] privateKey, final byte[] publicKey) { this(algorithm, // Keeper.generatePrivateKey(algorithm, privateKey), // Keeper.generatePublicKey(algorithm, publicKey)// @@ -176,7 +176,7 @@ public AsymmetricCrypto(final String algorithm, final byte[] privateKey, final b * @param privateKey 私钥 * @param publicKey 公钥 */ - public AsymmetricCrypto(final String algorithm, final PrivateKey privateKey, final PublicKey publicKey) { + public Crypto(final String algorithm, final PrivateKey privateKey, final PublicKey publicKey) { super(algorithm, privateKey, publicKey); } @@ -233,7 +233,7 @@ public AlgorithmParameterSpec getAlgorithmParameterSpec() { * @param algorithmParameterSpec {@link AlgorithmParameterSpec} * @return this */ - public AsymmetricCrypto setAlgorithmParameterSpec(final AlgorithmParameterSpec algorithmParameterSpec) { + public Crypto setAlgorithmParameterSpec(final AlgorithmParameterSpec algorithmParameterSpec) { this.algorithmParameterSpec = algorithmParameterSpec; return this; } @@ -244,13 +244,13 @@ public AsymmetricCrypto setAlgorithmParameterSpec(final AlgorithmParameterSpec a * @param random 随机数生成器,可自定义随机数种子 * @return this */ - public AsymmetricCrypto setRandom(final SecureRandom random) { + public Crypto setRandom(final SecureRandom random) { this.random = random; return this; } @Override - public AsymmetricCrypto init(final String algorithm, final PrivateKey privateKey, final PublicKey publicKey) { + public Crypto init(final String algorithm, final PrivateKey privateKey, final PublicKey publicKey) { super.init(algorithm, privateKey, publicKey); initCipher(); return this; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AsymmetricDecryptor.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/Decryptor.java similarity index 99% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AsymmetricDecryptor.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/Decryptor.java index 022f1965e7..5bc9689109 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AsymmetricDecryptor.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/Decryptor.java @@ -44,7 +44,7 @@ * @author Kimi Liu * @since Java 17+ */ -public interface AsymmetricDecryptor { +public interface Decryptor { /** * 解密 diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AsymmetricEncryptor.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/Encryptor.java similarity index 99% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AsymmetricEncryptor.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/Encryptor.java index 78eb913ae5..2fd4823bd3 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/AsymmetricEncryptor.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/Encryptor.java @@ -45,7 +45,7 @@ * @author Kimi Liu * @since Java 17+ */ -public interface AsymmetricEncryptor { +public interface Encryptor { /** * 加密 diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/KeyType.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/KeyType.java index 4bb15b301a..2d6fba6a19 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/KeyType.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/asymmetric/KeyType.java @@ -47,7 +47,6 @@ public enum KeyType { */ SecretKey(Cipher.SECRET_KEY); - private final int value; /** @@ -67,4 +66,5 @@ public enum KeyType { public int getValue() { return this.value; } + } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCHMacEngine.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCHMac.java similarity index 90% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCHMacEngine.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCHMac.java index 814b15e0b0..65099929e4 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCHMacEngine.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCHMac.java @@ -39,7 +39,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class BCHMacEngine extends BCMacEngine { +public class BCHMac extends BCMac { /** * 构造 @@ -48,7 +48,7 @@ public class BCHMacEngine extends BCMacEngine { * @param key 密钥 * @param iv 加盐 */ - public BCHMacEngine(final Digest digest, final byte[] key, final byte[] iv) { + public BCHMac(final Digest digest, final byte[] key, final byte[] iv) { this(digest, new ParametersWithIV(new KeyParameter(key), iv)); } @@ -58,7 +58,7 @@ public BCHMacEngine(final Digest digest, final byte[] key, final byte[] iv) { * @param digest 摘要算法,为{@link Digest} 的接口实现 * @param key 密钥 */ - public BCHMacEngine(final Digest digest, final byte[] key) { + public BCHMac(final Digest digest, final byte[] key) { this(digest, new KeyParameter(key)); } @@ -68,7 +68,7 @@ public BCHMacEngine(final Digest digest, final byte[] key) { * @param digest 摘要算法 * @param params 参数,例如密钥可以用{@link KeyParameter} */ - public BCHMacEngine(final Digest digest, final CipherParameters params) { + public BCHMac(final Digest digest, final CipherParameters params) { this(new HMac(digest), params); } @@ -78,7 +78,7 @@ public BCHMacEngine(final Digest digest, final CipherParameters params) { * @param mac {@link HMac} * @param params 参数,例如密钥可以用{@link KeyParameter} */ - public BCHMacEngine(final HMac mac, final CipherParameters params) { + public BCHMac(final HMac mac, final CipherParameters params) { super(mac, params); } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCMacEngine.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCMac.java similarity index 87% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCMacEngine.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCMac.java index 4bf425d9b8..a82d14f676 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCMacEngine.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/BCMac.java @@ -26,26 +26,25 @@ package org.miaixz.bus.crypto.builtin.digest.mac; import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.params.KeyParameter; import org.miaixz.bus.core.lang.wrapper.SimpleWrapper; /** - * BouncyCastle的MAC算法实现引擎,使用{@link Mac} 实现摘要 + * BouncyCastle的MAC算法实现引擎,使用{@link org.bouncycastle.crypto.Mac} 实现摘要 * 当引入BouncyCastle库时自动使用其作为Provider * * @author Kimi Liu * @since Java 17+ */ -public class BCMacEngine extends SimpleWrapper implements MacEngine { +public class BCMac extends SimpleWrapper implements Mac { /** * 构造 * - * @param mac {@link Mac} + * @param mac {@link org.bouncycastle.crypto.Mac} * @param params 参数,例如密钥可以用{@link KeyParameter} */ - public BCMacEngine(final Mac mac, final CipherParameters params) { + public BCMac(final org.bouncycastle.crypto.Mac mac, final CipherParameters params) { super(initMac(mac, params)); } @@ -56,7 +55,7 @@ public BCMacEngine(final Mac mac, final CipherParameters params) { * @param params 参数,例如密钥可以用{@link KeyParameter} * @return this */ - private static Mac initMac(final Mac mac, final CipherParameters params) { + private static org.bouncycastle.crypto.Mac initMac(final org.bouncycastle.crypto.Mac mac, final CipherParameters params) { mac.init(params); return mac; } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/CBCBlockCipherMacEngine.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/CBCBlockCipherMac.java similarity index 80% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/CBCBlockCipherMacEngine.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/CBCBlockCipherMac.java index 3c712701a4..575600c137 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/CBCBlockCipherMacEngine.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/CBCBlockCipherMac.java @@ -28,19 +28,18 @@ import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.macs.CBCBlockCipherMac; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import java.security.Key; /** - * {@link CBCBlockCipherMac}实现的MAC算法,使用CBC Block方式 + * {@link org.bouncycastle.crypto.macs.CBCBlockCipherMac}实现的MAC算法,使用CBC Block方式 * * @author Kimi Liu * @since Java 17+ */ -public class CBCBlockCipherMacEngine extends BCMacEngine { +public class CBCBlockCipherMac extends BCMac { /** * 构造 @@ -50,7 +49,7 @@ public class CBCBlockCipherMacEngine extends BCMacEngine { * @param key 密钥 * @param iv 加盐 */ - public CBCBlockCipherMacEngine(final BlockCipher digest, final int macSizeInBits, final Key key, final byte[] iv) { + public CBCBlockCipherMac(final BlockCipher digest, final int macSizeInBits, final Key key, final byte[] iv) { this(digest, macSizeInBits, key.getEncoded(), iv); } @@ -62,7 +61,7 @@ public CBCBlockCipherMacEngine(final BlockCipher digest, final int macSizeInBits * @param key 密钥 * @param iv 加盐 */ - public CBCBlockCipherMacEngine(final BlockCipher digest, final int macSizeInBits, final byte[] key, final byte[] iv) { + public CBCBlockCipherMac(final BlockCipher digest, final int macSizeInBits, final byte[] key, final byte[] iv) { this(digest, macSizeInBits, new ParametersWithIV(new KeyParameter(key), iv)); } @@ -73,7 +72,7 @@ public CBCBlockCipherMacEngine(final BlockCipher digest, final int macSizeInBits * @param macSizeInBits mac结果的bits长度,必须为8的倍数 * @param key 密钥 */ - public CBCBlockCipherMacEngine(final BlockCipher cipher, final int macSizeInBits, final Key key) { + public CBCBlockCipherMac(final BlockCipher cipher, final int macSizeInBits, final Key key) { this(cipher, macSizeInBits, key.getEncoded()); } @@ -84,7 +83,7 @@ public CBCBlockCipherMacEngine(final BlockCipher cipher, final int macSizeInBits * @param macSizeInBits mac结果的bits长度,必须为8的倍数 * @param key 密钥 */ - public CBCBlockCipherMacEngine(final BlockCipher cipher, final int macSizeInBits, final byte[] key) { + public CBCBlockCipherMac(final BlockCipher cipher, final int macSizeInBits, final byte[] key) { this(cipher, macSizeInBits, new KeyParameter(key)); } @@ -95,17 +94,17 @@ public CBCBlockCipherMacEngine(final BlockCipher cipher, final int macSizeInBits * @param macSizeInBits mac结果的bits长度,必须为8的倍数 * @param params 参数,例如密钥可以用{@link KeyParameter} */ - public CBCBlockCipherMacEngine(final BlockCipher cipher, final int macSizeInBits, final CipherParameters params) { - this(new CBCBlockCipherMac(cipher, macSizeInBits), params); + public CBCBlockCipherMac(final BlockCipher cipher, final int macSizeInBits, final CipherParameters params) { + this(new org.bouncycastle.crypto.macs.CBCBlockCipherMac(cipher, macSizeInBits), params); } /** * 构造 * - * @param mac {@link CBCBlockCipherMac} + * @param mac {@link org.bouncycastle.crypto.macs.CBCBlockCipherMac} * @param params 参数,例如密钥可以用{@link KeyParameter} */ - public CBCBlockCipherMacEngine(final CBCBlockCipherMac mac, final CipherParameters params) { + public CBCBlockCipherMac(final org.bouncycastle.crypto.macs.CBCBlockCipherMac mac, final CipherParameters params) { super(mac, params); } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/JCEMacEngine.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/JCEMac.java similarity index 89% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/JCEMacEngine.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/JCEMac.java index ad9ef482c3..bece6f9ae1 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/JCEMacEngine.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/JCEMac.java @@ -30,20 +30,19 @@ import org.miaixz.bus.crypto.Builder; import org.miaixz.bus.crypto.Keeper; -import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.Key; import java.security.spec.AlgorithmParameterSpec; /** - * JDK提供的的MAC算法实现引擎,使用{@link Mac} 实现摘要 + * JDK提供的的MAC算法实现引擎,使用{@link javax.crypto.Mac} 实现摘要 * 当引入BouncyCastle库时自动使用其作为Provider * * @author Kimi Liu * @since Java 17+ */ -public class JCEMacEngine extends SimpleWrapper implements MacEngine { +public class JCEMac extends SimpleWrapper implements Mac { /** * 构造 @@ -51,7 +50,7 @@ public class JCEMacEngine extends SimpleWrapper implements MacEngine { * @param algorithm 算法 * @param key 密钥 */ - public JCEMacEngine(final String algorithm, final byte[] key) { + public JCEMac(final String algorithm, final byte[] key) { this(algorithm, (null == key) ? null : new SecretKeySpec(key, algorithm)); } @@ -61,7 +60,7 @@ public JCEMacEngine(final String algorithm, final byte[] key) { * @param algorithm 算法 * @param key 密钥 */ - public JCEMacEngine(final String algorithm, final Key key) { + public JCEMac(final String algorithm, final Key key) { this(algorithm, key, null); } @@ -72,7 +71,7 @@ public JCEMacEngine(final String algorithm, final Key key) { * @param key 密钥 * @param spec {@link AlgorithmParameterSpec} */ - public JCEMacEngine(final String algorithm, final Key key, final AlgorithmParameterSpec spec) { + public JCEMac(final String algorithm, final Key key, final AlgorithmParameterSpec spec) { super(initMac(algorithm, key, spec)); } @@ -85,8 +84,8 @@ public JCEMacEngine(final String algorithm, final Key key, final AlgorithmParame * @return this * @throws CryptoException Cause by IOException */ - private static Mac initMac(final String algorithm, Key key, final AlgorithmParameterSpec spec) { - final Mac mac; + private static javax.crypto.Mac initMac(final String algorithm, Key key, final AlgorithmParameterSpec spec) { + final javax.crypto.Mac mac; try { mac = Builder.createMac(algorithm); if (null == key) { diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/MacEngine.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/Mac.java similarity index 99% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/MacEngine.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/Mac.java index e89d5cf0f3..685a88d8de 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/MacEngine.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/Mac.java @@ -37,7 +37,7 @@ * @author Kimi Liu * @since Java 17+ */ -public interface MacEngine { +public interface Mac { /** * 加入需要被摘要的内容 diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/MacEngineFactory.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/MacFactory.java similarity index 84% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/MacEngineFactory.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/MacFactory.java index a32d1f29da..0e51a5f63e 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/MacEngineFactory.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/MacFactory.java @@ -32,38 +32,38 @@ import java.security.spec.AlgorithmParameterSpec; /** - * {@link MacEngine} 简单工厂类 + * {@link Mac} 简单工厂类 * * @author Kimi Liu * @since Java 17+ */ -public class MacEngineFactory { +public class MacFactory { /** - * 根据给定算法和密钥生成对应的{@link MacEngine} + * 根据给定算法和密钥生成对应的{@link Mac} * * @param algorithm 算法,见{@link Algorithm} * @param key 密钥 - * @return {@link MacEngine} + * @return {@link Mac} */ - public static MacEngine createEngine(final String algorithm, final Key key) { + public static Mac createEngine(final String algorithm, final Key key) { return createEngine(algorithm, key, null); } /** - * 根据给定算法和密钥生成对应的{@link MacEngine} + * 根据给定算法和密钥生成对应的{@link Mac} * * @param algorithm 算法,见{@link Algorithm} * @param key 密钥 * @param spec spec - * @return {@link MacEngine} + * @return {@link Mac} */ - public static MacEngine createEngine(final String algorithm, final Key key, final AlgorithmParameterSpec spec) { + public static Mac createEngine(final String algorithm, final Key key, final AlgorithmParameterSpec spec) { if (algorithm.equalsIgnoreCase(Algorithm.HMACSM3.getValue())) { // HmacSM3算法是BC库实现的,忽略加盐 return Builder.createHmacSm3Engine(key.getEncoded()); } - return new JCEMacEngine(algorithm, key, spec); + return new JCEMac(algorithm, key, spec); } } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/SM4MacEngine.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/SM4Mac.java similarity index 95% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/SM4MacEngine.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/SM4Mac.java index e9ceca0d39..6c0764a0d2 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/SM4MacEngine.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/digest/mac/SM4Mac.java @@ -34,7 +34,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class SM4MacEngine extends CBCBlockCipherMacEngine { +public class SM4Mac extends CBCBlockCipherMac { private static final int MAC_SIZE = 128; @@ -43,7 +43,7 @@ public class SM4MacEngine extends CBCBlockCipherMacEngine { * * @param params {@link CipherParameters} */ - public SM4MacEngine(final CipherParameters params) { + public SM4Mac(final CipherParameters params) { super(new SM4Engine(), MAC_SIZE, params); } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/SymmetricCrypto.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/Crypto.java similarity index 93% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/SymmetricCrypto.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/Crypto.java index 36c87ce6ed..8a092ff7d9 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/SymmetricCrypto.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/Crypto.java @@ -62,7 +62,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class SymmetricCrypto implements SymmetricEncryptor, SymmetricDecryptor, Serializable { +public class Crypto implements Encryptor, Decryptor, Serializable { private static final long serialVersionUID = -1L; @@ -96,7 +96,7 @@ public class SymmetricCrypto implements SymmetricEncryptor, SymmetricDecryptor, * * @param algorithm {@link Algorithm} */ - public SymmetricCrypto(final Algorithm algorithm) { + public Crypto(final Algorithm algorithm) { this(algorithm, (byte[]) null); } @@ -105,7 +105,7 @@ public SymmetricCrypto(final Algorithm algorithm) { * * @param algorithm 算法,可以是"algorithm/mode/padding"或者"algorithm" */ - public SymmetricCrypto(final String algorithm) { + public Crypto(final String algorithm) { this(algorithm, (byte[]) null); } @@ -115,7 +115,7 @@ public SymmetricCrypto(final String algorithm) { * @param algorithm 算法 {@link Algorithm} * @param key 自定义KEY */ - public SymmetricCrypto(final Algorithm algorithm, final byte[] key) { + public Crypto(final Algorithm algorithm, final byte[] key) { this(algorithm.getValue(), key); } @@ -125,7 +125,7 @@ public SymmetricCrypto(final Algorithm algorithm, final byte[] key) { * @param algorithm 算法 {@link Algorithm} * @param key 自定义KEY */ - public SymmetricCrypto(final Algorithm algorithm, final SecretKey key) { + public Crypto(final Algorithm algorithm, final SecretKey key) { this(algorithm.getValue(), key); } @@ -135,7 +135,7 @@ public SymmetricCrypto(final Algorithm algorithm, final SecretKey key) { * @param algorithm 算法 * @param key 密钥 */ - public SymmetricCrypto(final String algorithm, final byte[] key) { + public Crypto(final String algorithm, final byte[] key) { this(algorithm, Keeper.generateKey(algorithm, key)); } @@ -145,7 +145,7 @@ public SymmetricCrypto(final String algorithm, final byte[] key) { * @param algorithm 算法 * @param key 密钥 */ - public SymmetricCrypto(final String algorithm, final SecretKey key) { + public Crypto(final String algorithm, final SecretKey key) { this(algorithm, key, null); } @@ -156,7 +156,7 @@ public SymmetricCrypto(final String algorithm, final SecretKey key) { * @param key 密钥 * @param paramsSpec 算法参数,例如加盐等 */ - public SymmetricCrypto(final String algorithm, final SecretKey key, final AlgorithmParameterSpec paramsSpec) { + public Crypto(final String algorithm, final SecretKey key, final AlgorithmParameterSpec paramsSpec) { init(algorithm, key); initParams(algorithm, paramsSpec); } @@ -207,7 +207,7 @@ private static void copyForZeroPadding(final CipherInputStream in, final OutputS * @param key 密钥,如果为{@code null}自动生成一个key * @return SymmetricCrypto的子对象,即子对象自身 */ - public SymmetricCrypto init(String algorithm, final SecretKey key) { + public Crypto init(String algorithm, final SecretKey key) { Assert.notBlank(algorithm, "'algorithm' must be not blank !"); this.secretKey = key; @@ -245,7 +245,7 @@ public Cipher getCipher() { * @param algorithmParameterSpec {@link AlgorithmParameterSpec} * @return this */ - public SymmetricCrypto setAlgorithmParameterSpec(final AlgorithmParameterSpec algorithmParameterSpec) { + public Crypto setAlgorithmParameterSpec(final AlgorithmParameterSpec algorithmParameterSpec) { this.algorithmParameterSpec = algorithmParameterSpec; return this; } @@ -256,7 +256,7 @@ public SymmetricCrypto setAlgorithmParameterSpec(final AlgorithmParameterSpec al * @param iv {@link IvParameterSpec}偏移向量 * @return 自身 */ - public SymmetricCrypto setIv(final IvParameterSpec iv) { + public Crypto setIv(final IvParameterSpec iv) { return setAlgorithmParameterSpec(iv); } @@ -266,7 +266,7 @@ public SymmetricCrypto setIv(final IvParameterSpec iv) { * @param iv 偏移向量,加盐 * @return 自身 */ - public SymmetricCrypto setIv(final byte[] iv) { + public Crypto setIv(final byte[] iv) { return setIv(new IvParameterSpec(iv)); } @@ -276,7 +276,7 @@ public SymmetricCrypto setIv(final byte[] iv) { * @param random 随机数生成器,可自定义随机数种子 * @return this */ - public SymmetricCrypto setRandom(final SecureRandom random) { + public Crypto setRandom(final SecureRandom random) { this.random = random; return this; } @@ -287,7 +287,7 @@ public SymmetricCrypto setRandom(final SecureRandom random) { * @param mode 模式枚举 * @return this */ - public SymmetricCrypto setMode(final Algorithm.Type mode) { + public Crypto setMode(final Algorithm.Type mode) { return setMode(mode, null); } @@ -298,7 +298,7 @@ public SymmetricCrypto setMode(final Algorithm.Type mode) { * @param salt 加盐值,用于 * @return this */ - public SymmetricCrypto setMode(final Algorithm.Type mode, final byte[] salt) { + public Crypto setMode(final Algorithm.Type mode, final byte[] salt) { lock.lock(); try { initMode(mode, salt); @@ -453,7 +453,7 @@ public void decrypt(final InputStream data, final OutputStream out, final boolea * @param paramsSpec 用户定义的{@link AlgorithmParameterSpec} * @return this */ - private SymmetricCrypto initParams(final String algorithm, AlgorithmParameterSpec paramsSpec) { + private Crypto initParams(final String algorithm, AlgorithmParameterSpec paramsSpec) { if (null == paramsSpec) { byte[] iv = Optional.ofNullable(cipher) .map(JceCipher::getRaw).map(Cipher::getIV).get(); diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/SymmetricDecryptor.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/Decryptor.java similarity index 99% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/SymmetricDecryptor.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/Decryptor.java index cfb83b9f16..5e92d6082b 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/SymmetricDecryptor.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/Decryptor.java @@ -45,7 +45,7 @@ * @author Kimi Liu * @since Java 17+ */ -public interface SymmetricDecryptor { +public interface Decryptor { /** * 解密 diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/SymmetricEncryptor.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/Encryptor.java similarity index 99% rename from bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/SymmetricEncryptor.java rename to bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/Encryptor.java index ccf8a0a473..acbf0813bc 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/SymmetricEncryptor.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/builtin/symmetric/Encryptor.java @@ -46,7 +46,7 @@ * @author Kimi Liu * @since Java 17+ */ -public interface SymmetricEncryptor { +public interface Encryptor { /** * 加密 diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/AES.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/AES.java index 79d447a3cc..1906ef8051 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/AES.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/AES.java @@ -30,7 +30,7 @@ import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.crypto.Keeper; import org.miaixz.bus.crypto.Padding; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; @@ -55,7 +55,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class AES extends SymmetricCrypto { +public class AES extends Crypto { private static final long serialVersionUID = -1L; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ChaCha20.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ChaCha20.java index 60c41cc638..b98ac57c44 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ChaCha20.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ChaCha20.java @@ -27,7 +27,7 @@ import org.miaixz.bus.core.xyz.RandomKit; import org.miaixz.bus.crypto.Keeper; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; import javax.crypto.spec.IvParameterSpec; @@ -38,7 +38,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class ChaCha20 extends SymmetricCrypto { +public class ChaCha20 extends Crypto { /** * 算法名称:ChaCha20 diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/DES.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/DES.java index c37d171cb0..1c4168f8b0 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/DES.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/DES.java @@ -29,7 +29,7 @@ import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.crypto.Keeper; import org.miaixz.bus.crypto.Padding; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; @@ -42,7 +42,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class DES extends SymmetricCrypto { +public class DES extends Crypto { private static final long serialVersionUID = -1L; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ECIES.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ECIES.java index 453079e77f..f9c01e0758 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ECIES.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ECIES.java @@ -25,7 +25,7 @@ ********************************************************************************/ package org.miaixz.bus.crypto.center; -import org.miaixz.bus.crypto.builtin.asymmetric.AsymmetricCrypto; +import org.miaixz.bus.crypto.builtin.asymmetric.Crypto; import java.security.PrivateKey; import java.security.PublicKey; @@ -41,7 +41,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class ECIES extends AsymmetricCrypto { +public class ECIES extends Crypto { private static final long serialVersionUID = -1L; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/HMac.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/HMac.java index f3ce6c32dc..db491d59af 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/HMac.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/HMac.java @@ -26,8 +26,8 @@ package org.miaixz.bus.crypto.center; import org.miaixz.bus.core.lang.Algorithm; -import org.miaixz.bus.crypto.builtin.digest.mac.MacEngine; -import org.miaixz.bus.crypto.builtin.digest.mac.MacEngineFactory; +import org.miaixz.bus.crypto.builtin.digest.mac.Mac; +import org.miaixz.bus.crypto.builtin.digest.mac.MacFactory; import javax.crypto.spec.SecretKeySpec; import java.security.Key; @@ -44,7 +44,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class HMac extends Mac { +public class HMac extends org.miaixz.bus.crypto.center.Mac { private static final long serialVersionUID = -1L; @@ -105,7 +105,7 @@ public HMac(final String algorithm, final Key key) { * @param spec {@link AlgorithmParameterSpec} */ public HMac(final String algorithm, final Key key, final AlgorithmParameterSpec spec) { - this(MacEngineFactory.createEngine(algorithm, key, spec)); + this(MacFactory.createEngine(algorithm, key, spec)); } /** @@ -113,7 +113,7 @@ public HMac(final String algorithm, final Key key, final AlgorithmParameterSpec * * @param engine MAC算法实现引擎 */ - public HMac(final MacEngine engine) { + public HMac(final Mac engine) { super(engine); } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/Mac.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/Mac.java index 78977dac75..ff9db28e84 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/Mac.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/Mac.java @@ -33,7 +33,6 @@ import org.miaixz.bus.core.xyz.FileKit; import org.miaixz.bus.core.xyz.HexKit; import org.miaixz.bus.core.xyz.IoKit; -import org.miaixz.bus.crypto.builtin.digest.mac.MacEngine; import java.io.ByteArrayInputStream; import java.io.File; @@ -57,14 +56,14 @@ public class Mac implements Serializable { /** * Mac引擎 */ - private final MacEngine engine; + private final org.miaixz.bus.crypto.builtin.digest.mac.Mac engine; /** * 构造 * * @param engine MAC算法实现引擎 */ - public Mac(final MacEngine engine) { + public Mac(final org.miaixz.bus.crypto.builtin.digest.mac.Mac engine) { this.engine = engine; } @@ -73,7 +72,7 @@ public Mac(final MacEngine engine) { * * @return MAC算法引擎 */ - public MacEngine getEngine() { + public org.miaixz.bus.crypto.builtin.digest.mac.Mac getEngine() { return this.engine; } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/RSA.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/RSA.java index 9d76912a2e..339cc982a3 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/RSA.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/RSA.java @@ -29,7 +29,7 @@ import org.miaixz.bus.core.lang.exception.CryptoException; import org.miaixz.bus.crypto.Holder; import org.miaixz.bus.crypto.Keeper; -import org.miaixz.bus.crypto.builtin.asymmetric.AsymmetricCrypto; +import org.miaixz.bus.crypto.builtin.asymmetric.Crypto; import org.miaixz.bus.crypto.builtin.asymmetric.KeyType; import java.math.BigInteger; @@ -50,7 +50,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class RSA extends AsymmetricCrypto { +public class RSA extends Crypto { private static final long serialVersionUID = -1L; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/SM2.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/SM2.java index a52da59f5e..c29b90b634 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/SM2.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/SM2.java @@ -45,7 +45,7 @@ import org.miaixz.bus.core.xyz.HexKit; import org.miaixz.bus.crypto.Builder; import org.miaixz.bus.crypto.Keeper; -import org.miaixz.bus.crypto.builtin.asymmetric.AbstractAsymmetricCrypto; +import org.miaixz.bus.crypto.builtin.asymmetric.AbstractCrypto; import org.miaixz.bus.crypto.builtin.asymmetric.KeyType; import java.math.BigInteger; @@ -68,7 +68,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class SM2 extends AbstractAsymmetricCrypto { +public class SM2 extends AbstractCrypto { private static final long serialVersionUID = -1L; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/SM4.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/SM4.java index c68906c990..c39ba54f37 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/SM4.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/SM4.java @@ -30,7 +30,7 @@ import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.crypto.Keeper; import org.miaixz.bus.crypto.Padding; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; @@ -49,7 +49,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class SM4 extends SymmetricCrypto { +public class SM4 extends Crypto { private static final long serialVersionUID = -1L; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/Sign.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/Sign.java index 27c3edcd8c..cac0c63091 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/Sign.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/Sign.java @@ -35,8 +35,8 @@ import org.miaixz.bus.core.xyz.HexKit; import org.miaixz.bus.crypto.Builder; import org.miaixz.bus.crypto.Keeper; -import org.miaixz.bus.crypto.builtin.asymmetric.AsymmetricCrypto; -import org.miaixz.bus.crypto.builtin.asymmetric.BaseAsymmetric; +import org.miaixz.bus.crypto.builtin.asymmetric.Asymmetric; +import org.miaixz.bus.crypto.builtin.asymmetric.Crypto; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -52,7 +52,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class Sign extends BaseAsymmetric { +public class Sign extends Asymmetric { private static final long serialVersionUID = -1L; @@ -372,7 +372,7 @@ public Signature getSignature() { * 设置签名 * * @param signature 签名对象 {@link Signature} - * @return 自身 {@link AsymmetricCrypto} + * @return 自身 {@link Crypto} */ public Sign setSignature(final Signature signature) { this.signature = signature; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/TDEA.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/TDEA.java index a6c8264991..6f2b3e1a7b 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/TDEA.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/TDEA.java @@ -29,7 +29,7 @@ import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.crypto.Keeper; import org.miaixz.bus.crypto.Padding; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; @@ -43,7 +43,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class TDEA extends SymmetricCrypto { +public class TDEA extends Crypto { private static final long serialVersionUID = -1L; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/XXTEA.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/XXTEA.java index 412bdc6fd6..e04101fed2 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/XXTEA.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/XXTEA.java @@ -26,8 +26,8 @@ package org.miaixz.bus.crypto.center; import org.miaixz.bus.core.xyz.IoKit; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricDecryptor; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricEncryptor; +import org.miaixz.bus.crypto.builtin.symmetric.Decryptor; +import org.miaixz.bus.crypto.builtin.symmetric.Encryptor; import java.io.InputStream; import java.io.OutputStream; @@ -40,7 +40,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class XXTEA implements SymmetricEncryptor, SymmetricDecryptor, Serializable { +public class XXTEA implements Encryptor, Decryptor, Serializable { private static final long serialVersionUID = -1L; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ZUC.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ZUC.java index 8aa3b34dd6..9e498da179 100644 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ZUC.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/center/ZUC.java @@ -27,7 +27,7 @@ import org.miaixz.bus.core.xyz.RandomKit; import org.miaixz.bus.crypto.Keeper; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; import javax.crypto.spec.IvParameterSpec; @@ -37,7 +37,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class ZUC extends SymmetricCrypto { +public class ZUC extends Crypto { private static final long serialVersionUID = -1L; diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/AESProvider.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/AESProvider.java index 60be7a37b5..ef333d5ed6 100755 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/AESProvider.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/AESProvider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2023 aoju.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/DESProvider.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/DESProvider.java index 565fb9c396..73a961d6b9 100755 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/DESProvider.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/DESProvider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2023 aoju.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/RC4Provider.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/RC4Provider.java index c39247307e..6242ed8c07 100755 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/RC4Provider.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/RC4Provider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2023 aoju.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -30,7 +30,7 @@ import org.miaixz.bus.core.lang.exception.InternalException; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.crypto.Provider; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; /** * 高级加密标准,是下一代的加密算法标准,速度快,安全级别高; @@ -55,7 +55,7 @@ public byte[] encrypt(String key, byte[] content) { if (StringKit.isEmpty(key)) { throw new InternalException("key is null!"); } - SymmetricCrypto rc4 = new SymmetricCrypto(Algorithm.RC4, key.getBytes()); + Crypto rc4 = new Crypto(Algorithm.RC4, key.getBytes()); return rc4.encrypt(StringKit.toString(content, Charset.UTF_8)); } @@ -70,7 +70,7 @@ public byte[] decrypt(String key, byte[] content) { if (StringKit.isEmpty(key)) { throw new InternalException("key is null!"); } - SymmetricCrypto rc4 = new SymmetricCrypto(Algorithm.RC4, key.getBytes()); + Crypto rc4 = new Crypto(Algorithm.RC4, key.getBytes()); return rc4.decrypt(content); } diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/RSAProvider.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/RSAProvider.java index 6b37950cd5..dd3573e62f 100755 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/RSAProvider.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/RSAProvider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2023 aoju.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/SM2Provider.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/SM2Provider.java index aec7977252..914e18cc31 100755 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/SM2Provider.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/SM2Provider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2023 aoju.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * diff --git a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/SM4Provider.java b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/SM4Provider.java index c1f5cb5592..7c26763b60 100755 --- a/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/SM4Provider.java +++ b/bus-crypto/src/main/java/org/miaixz/bus/crypto/metric/SM4Provider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2023 aoju.org and other contributors. * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * diff --git a/bus-extra/pom.xml b/bus-extra/pom.xml index 7531c3a666..df29013691 100644 --- a/bus-extra/pom.xml +++ b/bus-extra/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-extra - 8.0.0 + 8.0.1 jar ${project.artifactId} @@ -45,8 +45,8 @@ 21 1.18.32 2.0.49 - 2.10.1 - 2.17.0 + 2.11.0 + 2.17.1 1.1.8 2.5.1 2.0.3.RELEASE @@ -57,7 +57,7 @@ 3.5.3 3.10.0 5.1.1 - 1.26.1 + 1.26.2 2.1.3 3.15.14.RELEASE 2.3.32 @@ -135,6 +135,20 @@ sshj ${sshj.version} true + + + org.slf4j + slf4j-api + + + org.bouncycastle + bcpkix-jdk18on + + + org.bouncycastle + bcprov-jdk18on + + com.google.zxing @@ -169,7 +183,7 @@ org.apache.commons commons-compress - ${compress.vetsion} + ${compress.version} true @@ -181,6 +195,16 @@ org.apache.sshd sshd-core 2.12.0 + + + org.slf4j + slf4j-api + + + org.slf4j + jcl-over-slf4j + + com.ibeetl @@ -198,14 +222,17 @@ org.thymeleaf thymeleaf ${thymeleaf.version} - compile + true slf4j-api org.slf4j + + org.javassist + javassist + - true org.ansj @@ -273,6 +300,7 @@ org.apdplat word 1.3.1 + true logback-classic @@ -298,14 +326,27 @@ jedis redis.clients + + org.apache.lucene + lucene-suggest + + + org.apache.lucene + lucene-queryparser + - true com.mayabot.mynlp mynlp-all 4.0.0 true + + + org.jetbrains + annotations + + diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/AbstractCaptcha.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/AbstractProvider.java similarity index 89% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/AbstractCaptcha.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/AbstractProvider.java index 2224e6a840..0ccfac2b44 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/AbstractCaptcha.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/AbstractProvider.java @@ -31,8 +31,8 @@ import org.miaixz.bus.core.xyz.FileKit; import org.miaixz.bus.core.xyz.IoKit; import org.miaixz.bus.core.xyz.UrlKit; -import org.miaixz.bus.extra.captcha.generator.CodeGenerator; -import org.miaixz.bus.extra.captcha.generator.RandomGenerator; +import org.miaixz.bus.extra.captcha.strategy.CodeStrategy; +import org.miaixz.bus.extra.captcha.strategy.RandomStrategy; import org.miaixz.bus.extra.image.ImageKit; import java.awt.*; @@ -50,7 +50,7 @@ * @author Kimi Liu * @since Java 17+ */ -public abstract class AbstractCaptcha implements ICaptcha { +public abstract class AbstractProvider implements CaptchaProvider { private static final long serialVersionUID = -1L; @@ -81,7 +81,7 @@ public abstract class AbstractCaptcha implements ICaptcha { /** * 验证码生成器 */ - protected CodeGenerator generator; + protected CodeStrategy generator; /** * 背景色 */ @@ -99,8 +99,8 @@ public abstract class AbstractCaptcha implements ICaptcha { * @param codeCount 字符个数 * @param interfereCount 验证码干扰元素个数 */ - public AbstractCaptcha(final int width, final int height, final int codeCount, final int interfereCount) { - this(width, height, new RandomGenerator(codeCount), interfereCount); + public AbstractProvider(final int width, final int height, final int codeCount, final int interfereCount) { + this(width, height, new RandomStrategy(codeCount), interfereCount); } /** @@ -111,7 +111,7 @@ public AbstractCaptcha(final int width, final int height, final int codeCount, f * @param generator 验证码生成器 * @param interfereCount 验证码干扰元素个数 */ - public AbstractCaptcha(final int width, final int height, final CodeGenerator generator, final int interfereCount) { + public AbstractProvider(final int width, final int height, final CodeStrategy generator, final int interfereCount) { this(width, height, generator, interfereCount, Normal.DEFAULT_LOAD_FACTOR); } @@ -124,7 +124,7 @@ public AbstractCaptcha(final int width, final int height, final CodeGenerator ge * @param interfereCount 验证码干扰元素个数 * @param sizeBaseHeight 字体的大小 高度的倍数 */ - public AbstractCaptcha(final int width, final int height, final CodeGenerator generator, final int interfereCount, final float sizeBaseHeight) { + public AbstractProvider(final int width, final int height, final CodeStrategy generator, final int interfereCount, final float sizeBaseHeight) { this.width = width; this.height = height; this.generator = generator; @@ -134,7 +134,7 @@ public AbstractCaptcha(final int width, final int height, final CodeGenerator ge } @Override - public void createCode() { + public void create() { generateCode(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -166,16 +166,16 @@ protected void generateCode() { protected abstract Image createImage(String code); @Override - public String getCode() { + public String get() { if (null == this.code) { - createCode(); + create(); } return this.code; } @Override public boolean verify(final String userInputCode) { - return this.generator.verify(getCode(), userInputCode); + return this.generator.verify(get(), userInputCode); } /** @@ -214,7 +214,7 @@ public void write(final OutputStream out) { */ public byte[] getImageBytes() { if (null == this.imageBytes) { - createCode(); + create(); } return this.imageBytes; } @@ -261,7 +261,7 @@ public void setFont(final Font font) { * * @return 验证码生成器 */ - public CodeGenerator getGenerator() { + public CodeStrategy getGenerator() { return generator; } @@ -270,7 +270,7 @@ public CodeGenerator getGenerator() { * * @param generator 验证码生成器 */ - public void setGenerator(final CodeGenerator generator) { + public void setGenerator(final CodeStrategy generator) { this.generator = generator; } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CaptchaKit.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CaptchaBuilder.java similarity index 61% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CaptchaKit.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CaptchaBuilder.java index 1130f54ce7..a667f84567 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CaptchaKit.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CaptchaBuilder.java @@ -25,23 +25,28 @@ ********************************************************************************/ package org.miaixz.bus.extra.captcha; +import org.miaixz.bus.extra.captcha.provider.CircleProvider; +import org.miaixz.bus.extra.captcha.provider.GifProvider; +import org.miaixz.bus.extra.captcha.provider.LineProvider; +import org.miaixz.bus.extra.captcha.provider.ShearProvider; + /** * 图形验证码工具 * * @author Kimi Liu * @since Java 17+ */ -public class CaptchaKit { +public class CaptchaBuilder { /** * 创建线干扰的验证码,默认5位验证码,150条干扰线 * * @param width 图片宽 * @param height 图片高 - * @return {@link LineCaptcha} + * @return {@link LineProvider} */ - public static LineCaptcha ofLineCaptcha(final int width, final int height) { - return new LineCaptcha(width, height); + public static LineProvider ofLineCaptcha(final int width, final int height) { + return new LineProvider(width, height); } /** @@ -51,10 +56,10 @@ public static LineCaptcha ofLineCaptcha(final int width, final int height) { * @param height 图片高 * @param codeCount 字符个数 * @param lineCount 干扰线条数 - * @return {@link LineCaptcha} + * @return {@link LineProvider} */ - public static LineCaptcha ofLineCaptcha(final int width, final int height, final int codeCount, final int lineCount) { - return new LineCaptcha(width, height, codeCount, lineCount); + public static LineProvider ofLineCaptcha(final int width, final int height, final int codeCount, final int lineCount) { + return new LineProvider(width, height, codeCount, lineCount); } /** @@ -65,11 +70,11 @@ public static LineCaptcha ofLineCaptcha(final int width, final int height, final * @param codeCount 字符个数 * @param lineCount 干扰线条数 * @param sizeBaseHeight 字体的大小 高度的倍数 - * @return {@link LineCaptcha} + * @return {@link LineProvider} */ - public static LineCaptcha ofLineCaptcha(final int width, final int height, final int codeCount, - final int lineCount, final float sizeBaseHeight) { - return new LineCaptcha(width, height, codeCount, lineCount, sizeBaseHeight); + public static LineProvider ofLineCaptcha(final int width, final int height, final int codeCount, + final int lineCount, final float sizeBaseHeight) { + return new LineProvider(width, height, codeCount, lineCount, sizeBaseHeight); } /** @@ -77,10 +82,10 @@ public static LineCaptcha ofLineCaptcha(final int width, final int height, final * * @param width 图片宽 * @param height 图片高 - * @return {@link CircleCaptcha} + * @return {@link CircleProvider} */ - public static CircleCaptcha ofCircleCaptcha(final int width, final int height) { - return new CircleCaptcha(width, height); + public static CircleProvider ofCircleCaptcha(final int width, final int height) { + return new CircleProvider(width, height); } /** @@ -90,10 +95,10 @@ public static CircleCaptcha ofCircleCaptcha(final int width, final int height) { * @param height 图片高 * @param codeCount 字符个数 * @param circleCount 干扰圆圈条数 - * @return {@link CircleCaptcha} + * @return {@link CircleProvider} */ - public static CircleCaptcha ofCircleCaptcha(final int width, final int height, final int codeCount, final int circleCount) { - return new CircleCaptcha(width, height, codeCount, circleCount); + public static CircleProvider ofCircleCaptcha(final int width, final int height, final int codeCount, final int circleCount) { + return new CircleProvider(width, height, codeCount, circleCount); } /** @@ -104,11 +109,11 @@ public static CircleCaptcha ofCircleCaptcha(final int width, final int height, f * @param codeCount 字符个数 * @param circleCount 干扰圆圈条数 * @param size 字体的大小 高度的倍数 - * @return {@link CircleCaptcha} + * @return {@link CircleProvider} */ - public static CircleCaptcha ofCircleCaptcha(final int width, final int height, final int codeCount, - final int circleCount, final float size) { - return new CircleCaptcha(width, height, codeCount, circleCount, size); + public static CircleProvider ofCircleCaptcha(final int width, final int height, final int codeCount, + final int circleCount, final float size) { + return new CircleProvider(width, height, codeCount, circleCount, size); } /** @@ -116,10 +121,10 @@ public static CircleCaptcha ofCircleCaptcha(final int width, final int height, f * * @param width 图片宽 * @param height 图片高 - * @return {@link ShearCaptcha} + * @return {@link ShearProvider} */ - public static ShearCaptcha ofShearCaptcha(final int width, final int height) { - return new ShearCaptcha(width, height); + public static ShearProvider ofShearCaptcha(final int width, final int height) { + return new ShearProvider(width, height); } /** @@ -129,10 +134,10 @@ public static ShearCaptcha ofShearCaptcha(final int width, final int height) { * @param height 图片高 * @param codeCount 字符个数 * @param thickness 干扰线宽度 - * @return {@link ShearCaptcha} + * @return {@link ShearProvider} */ - public static ShearCaptcha ofShearCaptcha(final int width, final int height, final int codeCount, final int thickness) { - return new ShearCaptcha(width, height, codeCount, thickness); + public static ShearProvider ofShearCaptcha(final int width, final int height, final int codeCount, final int thickness) { + return new ShearProvider(width, height, codeCount, thickness); } /** @@ -143,10 +148,10 @@ public static ShearCaptcha ofShearCaptcha(final int width, final int height, fin * @param codeCount 字符个数 * @param thickness 干扰线宽度 * @param sizeBaseHeight 字体的大小 高度的倍数 - * @return {@link ShearCaptcha} + * @return {@link ShearProvider} */ - public static ShearCaptcha ofShearCaptcha(final int width, final int height, final int codeCount, final int thickness, final float sizeBaseHeight) { - return new ShearCaptcha(width, height, codeCount, thickness, sizeBaseHeight); + public static ShearProvider ofShearCaptcha(final int width, final int height, final int codeCount, final int thickness, final float sizeBaseHeight) { + return new ShearProvider(width, height, codeCount, thickness, sizeBaseHeight); } /** @@ -154,10 +159,10 @@ public static ShearCaptcha ofShearCaptcha(final int width, final int height, fin * * @param width 宽 * @param height 高 - * @return {@link GifCaptcha} + * @return {@link GifProvider} */ - public static GifCaptcha ofGifCaptcha(final int width, final int height) { - return new GifCaptcha(width, height); + public static GifProvider ofGifCaptcha(final int width, final int height) { + return new GifProvider(width, height); } /** @@ -166,10 +171,10 @@ public static GifCaptcha ofGifCaptcha(final int width, final int height) { * @param width 宽 * @param height 高 * @param codeCount 字符个数 - * @return {@link GifCaptcha} + * @return {@link GifProvider} */ - public static GifCaptcha ofGifCaptcha(final int width, final int height, final int codeCount) { - return new GifCaptcha(width, height, codeCount); + public static GifProvider ofGifCaptcha(final int width, final int height, final int codeCount) { + return new GifProvider(width, height, codeCount); } /** @@ -180,11 +185,11 @@ public static GifCaptcha ofGifCaptcha(final int width, final int height, final i * @param codeCount 字符个数 * @param thickness 验证码干扰元素个数 * @param sizeBaseHeight 字体的大小 高度的倍数 - * @return {@link GifCaptcha} + * @return {@link GifProvider} */ - public static GifCaptcha ofGifCaptcha(final int width, final int height, final int codeCount, - final int thickness, final float sizeBaseHeight) { - return new GifCaptcha(width, height, codeCount, thickness, sizeBaseHeight); + public static GifProvider ofGifCaptcha(final int width, final int height, final int codeCount, + final int thickness, final float sizeBaseHeight) { + return new GifProvider(width, height, codeCount, thickness, sizeBaseHeight); } } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/ICaptcha.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CaptchaProvider.java similarity index 96% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/ICaptcha.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CaptchaProvider.java index 7b8d347b68..368d3b0ea9 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/ICaptcha.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CaptchaProvider.java @@ -34,19 +34,19 @@ * @author Kimi Liu * @since Java 17+ */ -public interface ICaptcha extends Serializable { +public interface CaptchaProvider extends Serializable { /** * 创建验证码,实现类需同时生成随机验证码字符串和验证码图片 */ - void createCode(); + void create(); /** * 获取验证码的文字内容 * * @return 验证码文字内容 */ - String getCode(); + String get(); /** * 验证验证码是否正确,建议忽略大小写 diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CircleCaptcha.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/CircleProvider.java similarity index 83% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CircleCaptcha.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/CircleProvider.java index 1311a5ebf0..db849a154e 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/CircleCaptcha.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/CircleProvider.java @@ -23,12 +23,13 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.extra.captcha; +package org.miaixz.bus.extra.captcha.provider; import org.miaixz.bus.core.xyz.ColorKit; import org.miaixz.bus.core.xyz.RandomKit; -import org.miaixz.bus.extra.captcha.generator.CodeGenerator; -import org.miaixz.bus.extra.captcha.generator.RandomGenerator; +import org.miaixz.bus.extra.captcha.AbstractProvider; +import org.miaixz.bus.extra.captcha.strategy.CodeStrategy; +import org.miaixz.bus.extra.captcha.strategy.RandomStrategy; import org.miaixz.bus.extra.image.ImageKit; import java.awt.*; @@ -41,7 +42,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class CircleCaptcha extends AbstractCaptcha { +public class CircleProvider extends AbstractProvider { private static final long serialVersionUID = -1L; @@ -51,7 +52,7 @@ public class CircleCaptcha extends AbstractCaptcha { * @param width 图片宽 * @param height 图片高 */ - public CircleCaptcha(final int width, final int height) { + public CircleProvider(final int width, final int height) { this(width, height, 5); } @@ -62,7 +63,7 @@ public CircleCaptcha(final int width, final int height) { * @param height 图片高 * @param codeCount 字符个数 */ - public CircleCaptcha(final int width, final int height, final int codeCount) { + public CircleProvider(final int width, final int height, final int codeCount) { this(width, height, codeCount, 15); } @@ -74,8 +75,8 @@ public CircleCaptcha(final int width, final int height, final int codeCount) { * @param codeCount 字符个数 * @param interfereCount 验证码干扰元素个数 */ - public CircleCaptcha(final int width, final int height, final int codeCount, final int interfereCount) { - this(width, height, new RandomGenerator(codeCount), interfereCount); + public CircleProvider(final int width, final int height, final int codeCount, final int interfereCount) { + this(width, height, new RandomStrategy(codeCount), interfereCount); } /** @@ -86,7 +87,7 @@ public CircleCaptcha(final int width, final int height, final int codeCount, fin * @param generator 验证码生成器 * @param interfereCount 验证码干扰元素个数 */ - public CircleCaptcha(final int width, final int height, final CodeGenerator generator, final int interfereCount) { + public CircleProvider(final int width, final int height, final CodeStrategy generator, final int interfereCount) { super(width, height, generator, interfereCount); } @@ -99,8 +100,8 @@ public CircleCaptcha(final int width, final int height, final CodeGenerator gene * @param interfereCount 验证码干扰元素个数 * @param sizeBaseHeight 字体的大小 高度的倍数 */ - public CircleCaptcha(final int width, final int height, final int codeCount, final int interfereCount, final float sizeBaseHeight) { - super(width, height, new RandomGenerator(codeCount), interfereCount, sizeBaseHeight); + public CircleProvider(final int width, final int height, final int codeCount, final int interfereCount, final float sizeBaseHeight) { + super(width, height, new RandomStrategy(codeCount), interfereCount, sizeBaseHeight); } @Override diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/redis/RedisLock.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/ClickWordProvider.java old mode 100755 new mode 100644 similarity index 72% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/redis/RedisLock.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/ClickWordProvider.java index 83072e7ca7..5f3228913f --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/redis/RedisLock.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/ClickWordProvider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2023 aoju.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,41 +23,43 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.support.lock.redis; +package org.miaixz.bus.extra.captcha.provider; -import org.miaixz.bus.limiter.support.lock.Lock; -import org.redisson.api.RLock; -import org.redisson.api.RedissonClient; +import org.miaixz.bus.extra.captcha.AbstractProvider; +import org.miaixz.bus.extra.captcha.strategy.CodeStrategy; + +import java.awt.*; /** + * 点选文字验证码 + * * @author Kimi Liu * @since Java 17+ */ -public class RedisLock extends Lock { +public class ClickWordProvider extends AbstractProvider { - private RedissonClient redisson; - private String lockName; + public ClickWordProvider(int width, int height, int codeCount, int interfereCount) { + super(width, height, codeCount, interfereCount); + } - public RedisLock(RedissonClient redisson, String lockName) { - this.redisson = redisson; - this.lockName = lockName; + public ClickWordProvider(int width, int height, CodeStrategy generator, int interfereCount) { + super(width, height, generator, interfereCount); } @Override - public boolean lock(Object key) { - RLock rLock = redisson.getLock(key.toString()); - return rLock.tryLock(); + protected Image createImage(String code) { + return null; } @Override - public void unlock(Object key) { - RLock rLock = redisson.getLock(key.toString()); - rLock.unlock(); + public String get() { + return null; } @Override - public String getLimiterName() { - return lockName; + public boolean verify(String inputCode) { + return false; } + } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/GifCaptcha.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/GifProvider.java similarity index 85% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/GifCaptcha.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/GifProvider.java index 8acd5674a8..4984c357c8 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/GifCaptcha.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/GifProvider.java @@ -23,11 +23,12 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.extra.captcha; +package org.miaixz.bus.extra.captcha.provider; import org.miaixz.bus.core.xyz.RandomKit; -import org.miaixz.bus.extra.captcha.generator.CodeGenerator; -import org.miaixz.bus.extra.captcha.generator.RandomGenerator; +import org.miaixz.bus.extra.captcha.AbstractProvider; +import org.miaixz.bus.extra.captcha.strategy.CodeStrategy; +import org.miaixz.bus.extra.captcha.strategy.RandomStrategy; import org.miaixz.bus.extra.image.ImageKit; import org.miaixz.bus.extra.image.gif.AnimatedGifEncoder; @@ -36,32 +37,39 @@ import java.io.ByteArrayOutputStream; /** - * Gif验证码类 + * Gif验证码 * * @author Kimi Liu * @since Java 17+ */ -public class GifCaptcha extends AbstractCaptcha { +public class GifProvider extends AbstractProvider { private static final long serialVersionUID = -1L; - //量化器取样间隔 - 默认是10ms + /** + * 量化器取样间隔 - 默认是10ms + */ private int quality = 10; - // 帧循环次数 + /** + * 帧循环次数 + */ private int repeat = 0; - //设置随机颜色时,最小的取色范围 + /** + * 设置随机颜色时,最小的取色范围 + */ private int minColor = 0; - //设置随机颜色时,最大的取色范围 + /** + * 设置随机颜色时,最大的取色范围 + */ private int maxColor = 255; - /** * 可以设置验证码宽度,高度的构造函数 * * @param width 验证码宽度 * @param height 验证码高度 */ - public GifCaptcha(final int width, final int height) { + public GifProvider(final int width, final int height) { this(width, height, 5); } @@ -70,7 +78,7 @@ public GifCaptcha(final int width, final int height) { * @param height 验证码高度 * @param codeCount 验证码个数 */ - public GifCaptcha(final int width, final int height, final int codeCount) { + public GifProvider(final int width, final int height, final int codeCount) { this(width, height, codeCount, 10); } @@ -80,8 +88,8 @@ public GifCaptcha(final int width, final int height, final int codeCount) { * @param codeCount 验证码个数 * @param interfereCount 干扰个数 */ - public GifCaptcha(final int width, final int height, final int codeCount, final int interfereCount) { - this(width, height, new RandomGenerator(codeCount), interfereCount); + public GifProvider(final int width, final int height, final int codeCount, final int interfereCount) { + this(width, height, new RandomStrategy(codeCount), interfereCount); } /** @@ -92,7 +100,7 @@ public GifCaptcha(final int width, final int height, final int codeCount, final * @param generator 验证码生成器 * @param interfereCount 验证码干扰元素个数 */ - public GifCaptcha(final int width, final int height, final CodeGenerator generator, final int interfereCount) { + public GifProvider(final int width, final int height, final CodeStrategy generator, final int interfereCount) { super(width, height, generator, interfereCount); } @@ -105,8 +113,8 @@ public GifCaptcha(final int width, final int height, final CodeGenerator generat * @param interfereCount 验证码干扰元素个数 * @param sizeBaseHeight 字体的大小 高度的倍数 */ - public GifCaptcha(final int width, final int height, final int codeCount, final int interfereCount, final float sizeBaseHeight) { - super(width, height, new RandomGenerator(codeCount), interfereCount, sizeBaseHeight); + public GifProvider(final int width, final int height, final int codeCount, final int interfereCount, final float sizeBaseHeight) { + super(width, height, new RandomStrategy(codeCount), interfereCount, sizeBaseHeight); } /** @@ -118,7 +126,7 @@ public GifCaptcha(final int width, final int height, final int codeCount, final * @param quality 大于1 * @return this */ - public GifCaptcha setQuality(int quality) { + public GifProvider setQuality(int quality) { if (quality < 1) { quality = 1; } @@ -134,7 +142,7 @@ public GifCaptcha setQuality(int quality) { * @param repeat 必须大于等于0 * @return this */ - public GifCaptcha setRepeat(final int repeat) { + public GifProvider setRepeat(final int repeat) { if (repeat >= 0) { this.repeat = repeat; } @@ -147,7 +155,7 @@ public GifCaptcha setRepeat(final int repeat) { * @param maxColor 颜色 * @return this */ - public GifCaptcha setMaxColor(final int maxColor) { + public GifProvider setMaxColor(final int maxColor) { this.maxColor = maxColor; return this; } @@ -158,13 +166,13 @@ public GifCaptcha setMaxColor(final int maxColor) { * @param minColor 颜色 * @return this */ - public GifCaptcha setMinColor(final int minColor) { + public GifProvider setMinColor(final int minColor) { this.minColor = minColor; return this; } @Override - public void createCode() { + public void create() { generateCode(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/LineCaptcha.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/LineProvider.java similarity index 85% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/LineCaptcha.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/LineProvider.java index c21ef661a4..d79314421e 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/LineCaptcha.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/LineProvider.java @@ -23,12 +23,13 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.extra.captcha; +package org.miaixz.bus.extra.captcha.provider; import org.miaixz.bus.core.xyz.ColorKit; import org.miaixz.bus.core.xyz.RandomKit; -import org.miaixz.bus.extra.captcha.generator.CodeGenerator; -import org.miaixz.bus.extra.captcha.generator.RandomGenerator; +import org.miaixz.bus.extra.captcha.AbstractProvider; +import org.miaixz.bus.extra.captcha.strategy.CodeStrategy; +import org.miaixz.bus.extra.captcha.strategy.RandomStrategy; import org.miaixz.bus.extra.image.ImageKit; import java.awt.*; @@ -41,7 +42,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class LineCaptcha extends AbstractCaptcha { +public class LineProvider extends AbstractProvider { private static final long serialVersionUID = -1L; @@ -51,7 +52,7 @@ public class LineCaptcha extends AbstractCaptcha { * @param width 图片宽 * @param height 图片高 */ - public LineCaptcha(final int width, final int height) { + public LineProvider(final int width, final int height) { this(width, height, 5, 150); } @@ -63,8 +64,8 @@ public LineCaptcha(final int width, final int height) { * @param codeCount 字符个数 * @param lineCount 干扰线条数 */ - public LineCaptcha(final int width, final int height, final int codeCount, final int lineCount) { - this(width, height, new RandomGenerator(codeCount), lineCount); + public LineProvider(final int width, final int height, final int codeCount, final int lineCount) { + this(width, height, new RandomStrategy(codeCount), lineCount); } /** @@ -75,7 +76,7 @@ public LineCaptcha(final int width, final int height, final int codeCount, final * @param generator 验证码生成器 * @param interfereCount 验证码干扰元素个数 */ - public LineCaptcha(final int width, final int height, final CodeGenerator generator, final int interfereCount) { + public LineProvider(final int width, final int height, final CodeStrategy generator, final int interfereCount) { super(width, height, generator, interfereCount); } @@ -88,8 +89,8 @@ public LineCaptcha(final int width, final int height, final CodeGenerator genera * @param interfereCount 验证码干扰元素个数 * @param sizeBaseHeight 字体的大小 高度的倍数 */ - public LineCaptcha(final int width, final int height, final int codeCount, final int interfereCount, final float sizeBaseHeight) { - super(width, height, new RandomGenerator(codeCount), interfereCount, sizeBaseHeight); + public LineProvider(final int width, final int height, final int codeCount, final int interfereCount, final float sizeBaseHeight) { + super(width, height, new RandomStrategy(codeCount), interfereCount, sizeBaseHeight); } @Override diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/invoker/DuckInvoker.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/PuzzleProvider.java old mode 100755 new mode 100644 similarity index 59% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/invoker/DuckInvoker.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/PuzzleProvider.java index 3d9b8a3298..c6ee606a52 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/invoker/DuckInvoker.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/PuzzleProvider.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2023 aoju.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -23,43 +23,62 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.invoker; +package org.miaixz.bus.extra.captcha.provider; import org.miaixz.bus.core.lang.Symbol; -import org.miaixz.bus.proxy.Invoker; -import org.miaixz.bus.proxy.Provider; +import org.miaixz.bus.extra.captcha.AbstractProvider; +import org.miaixz.bus.extra.captcha.strategy.CodeStrategy; -import java.lang.reflect.Method; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; /** - * 支持的调用程序,这意味着它在从目标提供程序返回的对象上找到匹配的方法并调用它。 - * 该类有助于将现有类调整为它没有实现的接口 + * 滑动验证码 * * @author Kimi Liu * @since Java 17+ */ -public class DuckInvoker implements Invoker { +public class PuzzleProvider extends AbstractProvider { - private final Provider targetProvider; + public PuzzleProvider(int width, int height, int codeCount, int interfereCount) { + super(width, height, codeCount, interfereCount); + } + + public PuzzleProvider(int width, int height, CodeStrategy generator, int interfereCount) { + super(width, height, generator, interfereCount); + } - public DuckInvoker(final Provider targetProvider) { - this.targetProvider = targetProvider; + @Override + protected Image createImage(String code) { + return null; } - public Object invoke(final Object proxy, final Method method, final Object[] arguments) throws Throwable { - final Object target = targetProvider.getObject(); - final Class targetClass = target.getClass(); - try { - final Method targetMethod = targetClass.getMethod(method.getName(), method.getParameterTypes()); - if (method.getReturnType().isAssignableFrom(targetMethod.getReturnType())) { - return targetMethod.invoke(target, arguments); + @Override + public String get() { + return null; + } + + @Override + public boolean verify(String inputCode) { + List list = new ArrayList<>(); + for (int i = 0; i < inputCode.length(); i++) { + char c = inputCode.charAt(i); + if (c >= Symbol.C_ZERO && c <= Symbol.C_NINE) { + list.add(Integer.valueOf(String.valueOf(c))); } - throw new UnsupportedOperationException( - "Target type " + targetClass.getName() + " method has incompatible return type."); - } catch (NoSuchMethodException e) { - throw new UnsupportedOperationException( - "Target type " + targetClass.getName() + " does not have a method matching " + method + Symbol.DOT); } + int sum = 0; + for (Integer data : list) { + sum += data; + } + double avg = sum * 1.0 / list.size(); + double sum2 = 0.0; + for (Integer data : list) { + sum2 += Math.pow(data - avg, 2); + } + double stddev = sum2 / list.size(); + return stddev != 0; } } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/ShearCaptcha.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/ShearProvider.java similarity index 89% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/ShearCaptcha.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/ShearProvider.java index ba08484c2e..03f3cabe99 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/ShearCaptcha.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/provider/ShearProvider.java @@ -23,13 +23,14 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.extra.captcha; +package org.miaixz.bus.extra.captcha.provider; import org.miaixz.bus.core.xyz.ColorKit; import org.miaixz.bus.core.xyz.ObjectKit; import org.miaixz.bus.core.xyz.RandomKit; -import org.miaixz.bus.extra.captcha.generator.CodeGenerator; -import org.miaixz.bus.extra.captcha.generator.RandomGenerator; +import org.miaixz.bus.extra.captcha.AbstractProvider; +import org.miaixz.bus.extra.captcha.strategy.CodeStrategy; +import org.miaixz.bus.extra.captcha.strategy.RandomStrategy; import org.miaixz.bus.extra.image.ImageKit; import java.awt.*; @@ -41,7 +42,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class ShearCaptcha extends AbstractCaptcha { +public class ShearProvider extends AbstractProvider { private static final long serialVersionUID = -1L; @@ -51,7 +52,7 @@ public class ShearCaptcha extends AbstractCaptcha { * @param width 图片宽 * @param height 图片高 */ - public ShearCaptcha(final int width, final int height) { + public ShearProvider(final int width, final int height) { this(width, height, 5); } @@ -62,7 +63,7 @@ public ShearCaptcha(final int width, final int height) { * @param height 图片高 * @param codeCount 字符个数 */ - public ShearCaptcha(final int width, final int height, final int codeCount) { + public ShearProvider(final int width, final int height, final int codeCount) { this(width, height, codeCount, 4); } @@ -74,8 +75,8 @@ public ShearCaptcha(final int width, final int height, final int codeCount) { * @param codeCount 字符个数 * @param thickness 干扰线宽度 */ - public ShearCaptcha(final int width, final int height, final int codeCount, final int thickness) { - this(width, height, new RandomGenerator(codeCount), thickness); + public ShearProvider(final int width, final int height, final int codeCount, final int thickness) { + this(width, height, new RandomStrategy(codeCount), thickness); } /** @@ -86,7 +87,7 @@ public ShearCaptcha(final int width, final int height, final int codeCount, fina * @param generator 验证码生成器 * @param interfereCount 验证码干扰元素个数 */ - public ShearCaptcha(final int width, final int height, final CodeGenerator generator, final int interfereCount) { + public ShearProvider(final int width, final int height, final CodeStrategy generator, final int interfereCount) { super(width, height, generator, interfereCount); } @@ -99,8 +100,8 @@ public ShearCaptcha(final int width, final int height, final CodeGenerator gener * @param interfereCount 验证码干扰元素个数 * @param sizeBaseHeight 字体的大小 高度的倍数 */ - public ShearCaptcha(final int width, final int height, final int codeCount, final int interfereCount, final float sizeBaseHeight) { - super(width, height, new RandomGenerator(codeCount), interfereCount, sizeBaseHeight); + public ShearProvider(final int width, final int height, final int codeCount, final int interfereCount, final float sizeBaseHeight) { + super(width, height, new RandomStrategy(codeCount), interfereCount, sizeBaseHeight); } @Override diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/AbstractGenerator.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/AbstractStrategy.java similarity index 91% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/AbstractGenerator.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/AbstractStrategy.java index f2879d9415..55dcb4658c 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/AbstractGenerator.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/AbstractStrategy.java @@ -23,18 +23,18 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.extra.captcha.generator; +package org.miaixz.bus.extra.captcha.strategy; import org.miaixz.bus.core.lang.Normal; /** - * 随机字符验证码生成器 + * 随机字符验证码生成策略 * 可以通过传入的基础集合和长度随机生成验证码字符 * * @author Kimi Liu * @since Java 17+ */ -public abstract class AbstractGenerator implements CodeGenerator { +public abstract class AbstractStrategy implements CodeStrategy { private static final long serialVersionUID = -1L; @@ -52,7 +52,7 @@ public abstract class AbstractGenerator implements CodeGenerator { * * @param count 生成验证码长度 */ - public AbstractGenerator(final int count) { + public AbstractStrategy(final int count) { this(Normal.LOWER_ALPHABET_NUMBER, count); } @@ -62,7 +62,7 @@ public AbstractGenerator(final int count) { * @param baseStr 基础字符集合,用于随机获取字符串的字符集合 * @param length 生成验证码长度 */ - public AbstractGenerator(final String baseStr, final int length) { + public AbstractStrategy(final String baseStr, final int length) { this.baseStr = baseStr; this.length = length; } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/CodeGenerator.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/CodeStrategy.java similarity index 95% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/CodeGenerator.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/CodeStrategy.java index 671dcc61ff..6551bd682b 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/CodeGenerator.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/CodeStrategy.java @@ -23,17 +23,17 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.extra.captcha.generator; +package org.miaixz.bus.extra.captcha.strategy; import java.io.Serializable; /** - * 验证码文字生成器 + * 验证码文字生成策略 * * @author Kimi Liu * @since Java 17+ */ -public interface CodeGenerator extends Serializable { +public interface CodeStrategy extends Serializable { /** * 生成验证码 diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/MathGenerator.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/MathStrategy.java similarity index 95% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/MathGenerator.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/MathStrategy.java index b6e9ad500c..d607a2426d 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/MathGenerator.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/MathStrategy.java @@ -23,7 +23,7 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.extra.captcha.generator; +package org.miaixz.bus.extra.captcha.strategy; import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.math.Calculator; @@ -31,12 +31,12 @@ import org.miaixz.bus.core.xyz.StringKit; /** - * 数字计算验证码生成器 + * 数字计算验证码生成策略 * * @author Kimi Liu * @since Java 17+ */ -public class MathGenerator implements CodeGenerator { +public class MathStrategy implements CodeStrategy { private static final long serialVersionUID = -1L; @@ -50,7 +50,7 @@ public class MathGenerator implements CodeGenerator { /** * 构造 */ - public MathGenerator() { + public MathStrategy() { this(2); } @@ -59,7 +59,7 @@ public MathGenerator() { * * @param numberLength 参与计算最大数字位数 */ - public MathGenerator(final int numberLength) { + public MathStrategy(final int numberLength) { this.numberLength = numberLength; } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/RandomGenerator.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/RandomStrategy.java similarity index 92% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/RandomGenerator.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/RandomStrategy.java index a68db0a874..1fbcca7d02 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/RandomGenerator.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/RandomStrategy.java @@ -23,19 +23,19 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.extra.captcha.generator; +package org.miaixz.bus.extra.captcha.strategy; import org.miaixz.bus.core.xyz.RandomKit; import org.miaixz.bus.core.xyz.StringKit; /** - * 随机字符验证码生成器 + * 随机字符验证码生成策略 * 可以通过传入的基础集合和长度随机生成验证码字符 * * @author Kimi Liu * @since Java 17+ */ -public class RandomGenerator extends AbstractGenerator { +public class RandomStrategy extends AbstractStrategy { private static final long serialVersionUID = -1L; @@ -44,7 +44,7 @@ public class RandomGenerator extends AbstractGenerator { * * @param count 生成验证码长度 */ - public RandomGenerator(final int count) { + public RandomStrategy(final int count) { super(count); } @@ -54,7 +54,7 @@ public RandomGenerator(final int count) { * @param baseStr 基础字符集合,用于随机获取字符串的字符集合 * @param length 生成验证码长度 */ - public RandomGenerator(final String baseStr, final int length) { + public RandomStrategy(final String baseStr, final int length) { super(baseStr, length); } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/package-info.java b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/package-info.java similarity index 62% rename from bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/package-info.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/package-info.java index 1bdd896634..bb489248d4 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/generator/package-info.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/captcha/strategy/package-info.java @@ -4,4 +4,4 @@ * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.extra.captcha.generator; +package org.miaixz.bus.extra.captcha.strategy; diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/compress/CompressKit.java b/bus-extra/src/main/java/org/miaixz/bus/extra/compress/CompressBuilder.java similarity index 99% rename from bus-extra/src/main/java/org/miaixz/bus/extra/compress/CompressKit.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/compress/CompressBuilder.java index 46470c7b55..79c5d9099b 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/compress/CompressKit.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/compress/CompressBuilder.java @@ -53,7 +53,7 @@ * @author Kimi Liu * @since Java 17+ */ -public class CompressKit { +public class CompressBuilder { /** * 获取压缩输出流,用于压缩指定内容,支持的格式例如: diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/ftp/AbstractFtp.java b/bus-extra/src/main/java/org/miaixz/bus/extra/ftp/AbstractFtp.java index 7bd41591f9..ce065f554d 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/ftp/AbstractFtp.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/ftp/AbstractFtp.java @@ -165,7 +165,7 @@ public void download(final String path, File outFile, String tempFileSuffix) { FileKit.rename(outFile, fileName, true); } catch (final Throwable e) { // 异常则删除临时文件 - FileKit.del(outFile); + FileKit.remove(outFile); throw new InternalException(e); } } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/qrcode/QrCodeKit.java b/bus-extra/src/main/java/org/miaixz/bus/extra/qrcode/QrCodeKit.java index b915289273..f63bff602d 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/qrcode/QrCodeKit.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/qrcode/QrCodeKit.java @@ -30,7 +30,12 @@ import com.google.zxing.common.BitMatrix; import com.google.zxing.common.GlobalHistogramBinarizer; import com.google.zxing.common.HybridBinarizer; +import org.miaixz.bus.core.codec.binary.Base64; +import org.miaixz.bus.core.io.file.FileName; +import org.miaixz.bus.core.xyz.FileKit; +import org.miaixz.bus.core.xyz.IoKit; import org.miaixz.bus.core.xyz.ObjectKit; +import org.miaixz.bus.core.xyz.UrlKit; import org.miaixz.bus.extra.image.ImageKit; import java.awt.*; @@ -71,16 +76,23 @@ public class QrCodeKit { * * @param content 内容 * @param qrConfig 二维码配置,包括宽度、高度、边距、颜色等 - * @param imageType 图片类型(图片扩展名),见{@link ImageKit} + * @param imageType 类型(图片扩展名),见{@link #QR_TYPE_SVG}、 {@link #QR_TYPE_TXT}、{@link ImageKit} * @return 图片 Base64 编码字符串 */ public static String generateAsBase64DataUri(final String content, final QrConfig qrConfig, final String imageType) { - BufferedImage img = null; - try { - img = generate(content, qrConfig); - return ImageKit.toBase64DataUri(img, imageType); - } finally { - ImageKit.flush(img); + switch (imageType) { + case QR_TYPE_SVG: + return svgToBase64DataUri(generateAsSvg(content, qrConfig)); + case QR_TYPE_TXT: + return txtToBase64DataUri(generateAsAsciiArt(content, qrConfig)); + default: + BufferedImage img = null; + try { + img = generate(content, qrConfig); + return ImageKit.toBase64DataUri(img, imageType); + } finally { + ImageKit.flush(img); + } } } @@ -115,20 +127,13 @@ public static byte[] generatePng(final String content, final QrConfig config) { * 生成二维码到文件,二维码图片格式取决于文件的扩展名 * * @param content 文本内容 - * @param width 宽度 - * @param height 高度 + * @param width 宽度(单位:类型为一般图片或SVG时,单位是像素,类型为 Ascii Art 字符画时,单位是字符▄或▀的大小) + * @param height 高度(单位:类型为一般图片或SVG时,单位是像素,类型为 Ascii Art 字符画时,单位是字符▄或▀的大小) * @param targetFile 目标文件,扩展名决定输出格式 * @return 目标文件 */ public static File generate(final String content, final int width, final int height, final File targetFile) { - BufferedImage image = null; - try { - image = generate(content, width, height); - ImageKit.write(image, targetFile); - } finally { - ImageKit.flush(image); - } - return targetFile; + return generate(content, QrConfig.of(width, height), targetFile); } /** @@ -140,13 +145,24 @@ public static File generate(final String content, final int width, final int hei * @return 目标文件 */ public static File generate(final String content, final QrConfig config, final File targetFile) { - BufferedImage image = null; - try { - image = generate(content, config); - ImageKit.write(image, targetFile); - } finally { - ImageKit.flush(image); + final String extName = FileName.extName(targetFile); + switch (extName) { + case QR_TYPE_SVG: + FileKit.writeUtf8String(generateAsSvg(content, config), targetFile); + break; + case QR_TYPE_TXT: + FileKit.writeUtf8String(generateAsAsciiArt(content, config), targetFile); + break; + default: + BufferedImage image = null; + try { + image = generate(content, config); + ImageKit.write(image, targetFile); + } finally { + ImageKit.flush(image); + } } + return targetFile; } @@ -154,19 +170,13 @@ public static File generate(final String content, final QrConfig config, final F * 生成二维码到输出流 * * @param content 文本内容 - * @param width 宽度 - * @param height 高度 - * @param imageType 图片类型(图片扩展名),见{@link ImageKit} + * @param width 宽度(单位:类型为一般图片或SVG时,单位是像素,类型为 Ascii Art 字符画时,单位是字符▄或▀的大小) + * @param height 高度(单位:类型为一般图片或SVG时,单位是像素,类型为 Ascii Art 字符画时,单位是字符▄或▀的大小) + * @param imageType 类型(图片扩展名),见{@link #QR_TYPE_SVG}、 {@link #QR_TYPE_TXT}、{@link ImageKit} * @param out 目标流 */ public static void generate(final String content, final int width, final int height, final String imageType, final OutputStream out) { - BufferedImage img = null; - try { - img = generate(content, width, height); - ImageKit.write(img, imageType, out); - } finally { - ImageKit.flush(img); - } + generate(content, QrConfig.of(width, height), imageType, out); } /** @@ -178,12 +188,21 @@ public static void generate(final String content, final int width, final int hei * @param out 目标流 */ public static void generate(final String content, final QrConfig config, final String imageType, final OutputStream out) { - BufferedImage image = null; - try { - image = generate(content, config); - ImageKit.write(image, imageType, out); - } finally { - ImageKit.flush(image); + switch (imageType) { + case QR_TYPE_SVG: + IoKit.writeUtf8(out, false, generateAsSvg(content, config)); + break; + case QR_TYPE_TXT: + IoKit.writeUtf8(out, false, generateAsAsciiArt(content, config)); + break; + default: + BufferedImage img = null; + try { + img = generate(content, config); + ImageKit.write(img, imageType, out); + } finally { + ImageKit.flush(img); + } } } @@ -356,4 +375,26 @@ public static String generateAsAsciiArt(final String content, final QrConfig qrC public static String toAsciiArt(final BitMatrix bitMatrix, final QrConfig qrConfig) { return new QrAsciiArt(bitMatrix, qrConfig).toString(); } + + /** + * 将文本转换为Base64编码的Data URI。 + * + * @param txt 需要转换为Base64编码Data URI的文本。 + * @return 转换后的Base64编码Data URI字符串。 + */ + private static String txtToBase64DataUri(final String txt) { + return UrlKit.getDataUriBase64("text/plain", Base64.encode(txt)); + } + + /** + * 将SVG字符串转换为Base64数据URI格式。 + *

      此方法通过将SVG内容编码为Base64,并将其封装在数据URI中,以便于在HTML或CSS中直接嵌入SVG图像。

      + * + * @param svg SVG图像的内容,为字符串形式。 + * @return 转换后的Base64数据URI字符串,可用于直接在HTML或CSS中显示SVG图像。 + */ + private static String svgToBase64DataUri(final String svg) { + return UrlKit.getDataUriBase64("image/svg+xml", Base64.encode(svg)); + } + } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/qrcode/QrSVG.java b/bus-extra/src/main/java/org/miaixz/bus/extra/qrcode/QrSVG.java index d9ba7b1796..e0845477d2 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/qrcode/QrSVG.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/qrcode/QrSVG.java @@ -69,7 +69,7 @@ public String toString() { for (int y = 0; y < qrHeight; y++) { for (int x = 0; x < qrWidth; x++) { if (matrix.get(x, y)) { - sb.append(" M").append(x).append(",").append(y).append("h1v").append(moduleHeight).append("h-1z"); + sb.append(" M").append(x).append(Symbol.COMMA).append(y).append("h1v").append(moduleHeight).append("h-1z"); } } } diff --git a/bus-extra/src/main/java/org/miaixz/bus/extra/ssh/JSchKit.java b/bus-extra/src/main/java/org/miaixz/bus/extra/ssh/JschKit.java similarity index 98% rename from bus-extra/src/main/java/org/miaixz/bus/extra/ssh/JSchKit.java rename to bus-extra/src/main/java/org/miaixz/bus/extra/ssh/JschKit.java index 084ebf1e2b..d2d42ca4fc 100644 --- a/bus-extra/src/main/java/org/miaixz/bus/extra/ssh/JSchKit.java +++ b/bus-extra/src/main/java/org/miaixz/bus/extra/ssh/JschKit.java @@ -35,7 +35,8 @@ /** * Jsch工具类 - * Jsch是Java Secure Channel的缩写。JSch是一个SSH2的纯Java实现。 + * Jsch是Java Secure Channel的缩写。 + * JSch是一个SSH2的纯Java实现。 * 它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等。 * * @author Kimi Liu diff --git a/bus-gitlab/pom.xml b/bus-gitlab/pom.xml index 707891f43a..6f7a05ecaf 100755 --- a/bus-gitlab/pom.xml +++ b/bus-gitlab/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-gitlab - 8.0.0 + 8.0.1 jar ${project.artifactId} @@ -43,17 +43,12 @@ UTF-8 21 21 - 1.2.2 - 2.39.1 + 2.43 6.1.0-M2 + 2.17.1 - - jakarta.activation - jakarta.activation-api - ${activation.version} - jakarta.servlet jakarta.servlet-api @@ -61,9 +56,10 @@ true - org.glassfish.jersey.inject - jersey-hk2 - ${jersey.version} + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + true org.glassfish.jersey.core @@ -71,8 +67,8 @@ ${jersey.version} - org.glassfish.jersey.connectors - jersey-apache-connector + org.glassfish.jersey.inject + jersey-hk2 ${jersey.version} @@ -80,10 +76,39 @@ jersey-media-multipart ${jersey.version} + + org.glassfish.jersey.connectors + jersey-apache-connector + ${jersey.version} + + + commons-logging + commons-logging + + + commons-codec + commons-codec + + + org.glassfish.jersey.media jersey-media-json-jackson ${jersey.version} + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.module + jackson-module-jaxb-annotations + + diff --git a/bus-gitlab/src/main/java/org/miaixz/bus/gitlab/support/MaskingLoggingFilter.java b/bus-gitlab/src/main/java/org/miaixz/bus/gitlab/support/MaskingLoggingFilter.java index 39ab4f4f66..5efe4d77a1 100644 --- a/bus-gitlab/src/main/java/org/miaixz/bus/gitlab/support/MaskingLoggingFilter.java +++ b/bus-gitlab/src/main/java/org/miaixz/bus/gitlab/support/MaskingLoggingFilter.java @@ -27,7 +27,6 @@ import org.glassfish.jersey.message.MessageUtils; -import javax.annotation.Priority; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; @@ -54,7 +53,6 @@ * This class was patterned after org.glassfish.jersey.logging.LoggingInterceptor, but written in * such a way that it could be sub-classed and have its behavior modified. */ -@Priority(Integer.MIN_VALUE) public class MaskingLoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor { /** diff --git a/bus-goalie/pom.xml b/bus-goalie/pom.xml index 1e0b981d41..e6c596759f 100644 --- a/bus-goalie/pom.xml +++ b/bus-goalie/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-goalie - 8.0.0 + 8.0.1 jar ${project.artifactId} @@ -43,9 +43,9 @@ UTF-8 21 21 - 3.0.5 + 3.3.0 1.18.32 - 33.1.0-jre + 33.2.1-jre diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/Assets.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/Assets.java index d3b891d645..6b9a66044d 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/Assets.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/Assets.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.goalie; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.springframework.http.HttpMethod; import java.util.List; @@ -37,7 +38,8 @@ * @author Justubborn * @since Java 17+ */ -@Data +@Getter +@Setter public class Assets { private String id; @@ -89,8 +91,18 @@ public class Assets { * 描述 */ private String description; + /** + * 角色 + */ private List roleIds; + /** + * 请求方式 + */ private HttpMethod httpMethod; + /** + * 超时时间 + */ + private long timeout = 10000; @Override public boolean equals(Object o) { diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/Config.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/Config.java index 1370ecebb6..938c27f2fc 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/Config.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/Config.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.goalie; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; /** * 服务端配置 @@ -33,7 +34,8 @@ * @author Justubborn * @since Java 17+ */ -@Data +@Getter +@Setter public class Config { /** @@ -66,7 +68,7 @@ public class Config { /** * 默认数据大小 */ - public static final Integer MAX_INMEMORY_SIZE = 2 * 2048 * 4096; + public static final Integer MAX_INMEMORY_SIZE = 100 * 1024 * 1024; private final Encrypt encrypt = new Encrypt(); private final Decrypt decrypt = new Decrypt(); @@ -74,7 +76,8 @@ public class Config { private String path; private int port; - @Data + @Getter + @Setter public static class Encrypt { private boolean enabled; private String key; @@ -82,7 +85,8 @@ public static class Encrypt { private String offset; } - @Data + @Getter + @Setter public static class Decrypt { private boolean enabled; private String key; @@ -90,7 +94,8 @@ public static class Decrypt { private String offset; } - @Data + @Getter + @Setter public static class Limit { private boolean enabled; } diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/Context.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/Context.java index 777a5bf96a..795e7c465f 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/Context.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/Context.java @@ -26,9 +26,9 @@ package org.miaixz.bus.goalie; import lombok.AllArgsConstructor; -import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.Setter; import org.miaixz.bus.goalie.support.JsonProvider; import org.miaixz.bus.goalie.support.XmlProvider; import org.springframework.http.MediaType; @@ -46,7 +46,8 @@ * @author Justubborn * @since Java 17+ */ -@Data +@Getter +@Setter public class Context { /** diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/AuthorizeFilter.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/AuthorizeFilter.java index b20274d273..f65b61e471 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/AuthorizeFilter.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/AuthorizeFilter.java @@ -27,9 +27,10 @@ import org.miaixz.bus.base.entity.OAuth2; import org.miaixz.bus.base.normal.ErrorCode; +import org.miaixz.bus.core.beans.copier.CopyOptions; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.BusinessException; import org.miaixz.bus.core.xyz.BeanKit; -import org.miaixz.bus.core.xyz.CollKit; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.goalie.Assets; import org.miaixz.bus.goalie.Config; @@ -48,6 +49,7 @@ import reactor.core.publisher.Mono; import java.net.InetSocketAddress; +import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -89,6 +91,8 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { checkMethod(exchange.getRequest(), assets); //校验参数 checkTokenIfNecessary(context, assets, params); + //校验 appid + checkAppId(assets, params); //填充Ip fillXParam(exchange, params); @@ -131,16 +135,12 @@ private void checkTokenIfNecessary(Context context, Assets assets, Map map = BeanKit.beanToMap(auth2, false, true); + Map map = new HashMap<>(); + BeanKit.beanToMap(auth2, map, CopyOptions.of().setTransientSupport(false).ignoreNullValue()); map.forEach((k, v) -> params.put(k, v.toString())); } else { throw new BusinessException(delegate.getMessage().errcode, delegate.getMessage().errmsg); @@ -169,36 +169,33 @@ private void cleanParam(Map params) { private void fillXParam(ServerWebExchange exchange, Map requestParam) { String ip = exchange.getRequest().getHeaders().getFirst("x_remote_ip"); if (StringKit.isBlank(ip)) { - InetSocketAddress address = exchange.getRequest().getRemoteAddress(); - if (null != address) { - ip = address.getAddress().getHostAddress(); + ip = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For"); + if (!StringKit.isBlank(ip)) { + ip = ip.contains(Symbol.COMMA) ? ip.split(Symbol.COMMA)[0] : ip; + } else { + InetSocketAddress address = exchange.getRequest().getRemoteAddress(); + if (null != address) { + ip = address.getAddress().getHostAddress(); + } } + requestParam.put("x_remote_ip", ip); } - requestParam.put("x_remote_ip", ip); } /** - * 是否有权限 + * 设置appid * - * @param oAuth2 认证 - * @param assets 路由 - * @return 是否 + * @param assets 资源 + * @param requestParam 参数 */ - private boolean apiPermissions(OAuth2 oAuth2, Assets assets) { - if (CollKit.isEmpty(assets.getRoleIds())) { - return false; + private void checkAppId(Assets assets, Map requestParam) { + String appId = assets.getMethod().split("\\.")[0]; + requestParam.putIfAbsent("x_app_id", appId); + String xAppId = requestParam.get("x_app_id"); + if (StringKit.isNotBlank(xAppId) && !appId.equals(xAppId)) { + throw new BusinessException(ErrorCode.EM_100511); } - if (StringKit.isEmpty(oAuth2.getX_role_id())) { - return false; - } - boolean result = false; - for (String roleId : assets.getRoleIds()) { - if (oAuth2.getX_role_id().contains(roleId)) { - result = true; - break; - } - } - return result; + } } diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/DecryptFilter.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/DecryptFilter.java index 04d236f01d..ece652878f 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/DecryptFilter.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/DecryptFilter.java @@ -31,7 +31,7 @@ import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.crypto.Padding; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; import org.miaixz.bus.crypto.center.AES; import org.miaixz.bus.goalie.Config; import org.miaixz.bus.goalie.Context; @@ -54,7 +54,7 @@ public class DecryptFilter implements WebFilter { private Config.Decrypt decrypt; - private SymmetricCrypto crypto; + private Crypto crypto; public DecryptFilter(Config.Decrypt decrypt) { this.decrypt = decrypt; diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/EncryptFilter.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/EncryptFilter.java index 9480164857..cb7ee0cb37 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/EncryptFilter.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/filter/EncryptFilter.java @@ -31,7 +31,7 @@ import org.miaixz.bus.core.lang.Charset; import org.miaixz.bus.core.xyz.ObjectKit; import org.miaixz.bus.crypto.Padding; -import org.miaixz.bus.crypto.builtin.symmetric.SymmetricCrypto; +import org.miaixz.bus.crypto.builtin.symmetric.Crypto; import org.miaixz.bus.crypto.center.AES; import org.miaixz.bus.extra.json.JsonKit; import org.miaixz.bus.goalie.Config; @@ -60,7 +60,7 @@ public class EncryptFilter implements WebFilter { private Config.Encrypt encrypt; - private SymmetricCrypto crypto; + private Crypto crypto; public EncryptFilter(Config.Encrypt encrypt) { this.encrypt = encrypt; diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/handler/ApiRouterHandler.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/handler/ApiRouterHandler.java index 29bf9351d5..52b3900e1b 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/handler/ApiRouterHandler.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/handler/ApiRouterHandler.java @@ -31,6 +31,7 @@ import org.miaixz.bus.goalie.Assets; import org.miaixz.bus.goalie.Config; import org.miaixz.bus.goalie.Context; +import org.miaixz.bus.logger.Logger; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -46,8 +47,10 @@ import org.springframework.web.util.UriComponentsBuilder; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.netty.http.client.HttpClientRequest; import reactor.util.annotation.NonNull; +import java.time.Duration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -105,12 +108,18 @@ public Mono handle(ServerRequest request) { } } } - return bodySpec.retrieve().toEntity(DataBuffer.class) + long start_time = System.currentTimeMillis(); + return bodySpec.httpRequest(clientHttpRequest -> { + //设置超时 + HttpClientRequest reactorRequest = clientHttpRequest.getNativeRequest(); + reactorRequest.responseTimeout(Duration.ofMillis(assets.getTimeout())); + }).retrieve().toEntity(DataBuffer.class) .flatMap(responseEntity -> ServerResponse.ok().headers(headers -> { headers.addAll(responseEntity.getHeaders()); headers.remove(HttpHeaders.CONTENT_LENGTH); }).body(null == responseEntity.getBody() ? BodyInserters.empty() - : BodyInserters.fromDataBuffers(Flux.just(responseEntity.getBody())))); + : BodyInserters.fromDataBuffers(Flux.just(responseEntity.getBody())))) + .doOnTerminate(() -> Logger.info("method:{} 请求耗时:{} ms", context.getAssets().getMethod(), System.currentTimeMillis() - start_time)); } } diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/handler/GlobalExceptionHandler.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/handler/GlobalExceptionHandler.java index d8b40a2176..160573337a 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/handler/GlobalExceptionHandler.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/handler/GlobalExceptionHandler.java @@ -2,7 +2,7 @@ * * * The MIT License (MIT) * * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * Copyright (c) 2015-2022 aoju.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * @@ -25,13 +25,14 @@ ********************************************************************************/ package org.miaixz.bus.goalie.handler; -import org.miaixz.bus.base.normal.ErrorCode; +import io.netty.handler.timeout.ReadTimeoutException; import org.miaixz.bus.base.spring.Controller; import org.miaixz.bus.core.lang.exception.BusinessException; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.goalie.Config; import org.miaixz.bus.goalie.Context; import org.miaixz.bus.goalie.Provider; +import org.miaixz.bus.goalie.metric.ErrorCode; import org.miaixz.bus.logger.Logger; import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler; import org.springframework.core.io.buffer.DataBuffer; @@ -66,12 +67,14 @@ public Mono handle(ServerWebExchange exchange, Throwable ex) { method = map.get(Config.METHOD); } Logger.error("traceId:{},request: {},error:{}", exchange.getLogPrefix(), method, ex.getMessage()); - Logger.error(ex); Object message; if (ex instanceof WebClientException) { - message = Controller.write(ErrorCode.EM_FAILURE); - } else if (ex instanceof BusinessException) { - BusinessException e = (BusinessException) ex; + if (ex.getCause() instanceof ReadTimeoutException) { + message = Controller.write(ErrorCode.EM_80010003); + } else { + message = Controller.write(ErrorCode.EM_80010004); + } + } else if (ex instanceof BusinessException e) { if (StringKit.isNotBlank(e.getErrcode())) { message = Controller.write(e.getErrcode()); } else { diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Delegate.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Delegate.java index c39ef23e6e..e9fdb0d742 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Delegate.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Delegate.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.goalie.metric; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.miaixz.bus.base.entity.Message; import org.miaixz.bus.base.entity.OAuth2; import org.miaixz.bus.base.normal.Consts; @@ -36,7 +37,8 @@ * @author Justubborn * @since Java 17+ */ -@Data +@Getter +@Setter public class Delegate { private Message message; diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/ErrorCode.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/ErrorCode.java new file mode 100644 index 0000000000..852c157450 --- /dev/null +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/ErrorCode.java @@ -0,0 +1,32 @@ +package org.miaixz.bus.goalie.metric; + +/** + * 自定义错误码 + */ +public class ErrorCode extends org.miaixz.bus.base.normal.ErrorCode { + + /** + * 没有API权限 + */ + public static String EM_80010001 = "80010001"; + /** + * 没有角色 + */ + public static String EM_80010002 = "80010002"; + /** + * 服务端超时 + */ + public static String EM_80010003 = "80010003"; + /** + * 服务端未响应 + */ + public static String EM_80010004 = "80010004"; + + static { + register(EM_80010001, "没有API权限"); + register(EM_80010002, "没有角色"); + register(EM_80010003, "服务端超时"); + register(EM_80010004, "服务端未响应"); + } + +} diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Limiter.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Limiter.java index 9fc0d875dc..1ef692151e 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Limiter.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Limiter.java @@ -26,7 +26,8 @@ package org.miaixz.bus.goalie.metric; import com.google.common.util.concurrent.RateLimiter; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; /** * 限流器 @@ -34,7 +35,8 @@ * @author Justubborn * @since Java 17+ */ -@Data +@Getter +@Setter public class Limiter { private String ip; diff --git a/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Token.java b/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Token.java index ae6ca9ec7d..069d360126 100644 --- a/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Token.java +++ b/bus-goalie/src/main/java/org/miaixz/bus/goalie/metric/Token.java @@ -26,7 +26,10 @@ package org.miaixz.bus.goalie.metric; import lombok.AllArgsConstructor; -import lombok.Data; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import org.miaixz.bus.goalie.Assets; /** * token参数 @@ -34,12 +37,27 @@ * @author Justubborn * @since Java 17+ */ +@Getter +@Setter @AllArgsConstructor -@Data +@RequiredArgsConstructor public class Token { - String token; - - int channel; + /** + * 授权标识 + */ + public final String token; + /** + * 授权 + */ + public final int channel; + /** + * 资源信息 + */ + public final Assets assets; + /** + * 租户 + */ + public transient String orgId; } diff --git a/bus-health/pom.xml b/bus-health/pom.xml index b3465a433b..2d5622fa0e 100755 --- a/bus-health/pom.xml +++ b/bus-health/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-health - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-health/src/main/java/org/miaixz/bus/health/Builder.java b/bus-health/src/main/java/org/miaixz/bus/health/Builder.java index a640f2b868..1743b25c28 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/Builder.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/Builder.java @@ -170,7 +170,7 @@ public static List loadAndParseFileSystemConfig(String configProper public static List parseFileSystemConfig(String config) { FileSystem fs = FileSystems.getDefault(); // can't be closed List patterns = new ArrayList<>(); - for (String item : config.split(",")) { + for (String item : config.split(Symbol.COMMA)) { if (item.length() > 0) { // Using glob: prefix as the defult unless user has specified glob or regex. See // https://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String- diff --git a/bus-health/src/main/java/org/miaixz/bus/health/Parsing.java b/bus-health/src/main/java/org/miaixz/bus/health/Parsing.java index d299a2772b..c4bbf65042 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/Parsing.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/Parsing.java @@ -979,7 +979,7 @@ public static long parseLspciMemorySize(String line) { */ public static List parseHyphenatedIntList(String str) { List result = new ArrayList<>(); - String[] csvTokens = str.split(","); + String[] csvTokens = str.split(Symbol.COMMA); for (String csvToken : csvTokens) { csvToken = csvToken.trim(); for (String s : Regex.SPACES.split(csvToken)) { diff --git a/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/HWPartition.java b/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/HWPartition.java index 2e18a4fb78..94ff921d8e 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/HWPartition.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/HWPartition.java @@ -167,7 +167,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getIdentification()).append(": "); sb.append(getName()).append(Symbol.SPACE); - sb.append("(").append(getType()).append(") "); + sb.append(Symbol.PARENTHESE_LEFT).append(getType()).append(") "); sb.append("Maj:Min=").append(getMajor()).append(Symbol.COLON).append(getMinor()).append(", "); sb.append("size: ").append(Formats.formatBytesDecimal(getSize())); sb.append(getMountPoint().isEmpty() ? Normal.EMPTY : " @ " + getMountPoint()); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/common/AbstractNetworkIF.java b/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/common/AbstractNetworkIF.java index 0e0f40b582..e22c1daebc 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/common/AbstractNetworkIF.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/common/AbstractNetworkIF.java @@ -233,7 +233,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: ").append(getName()); if (!getName().equals(getDisplayName())) { - sb.append(" (").append(getDisplayName()).append(")"); + sb.append(" (").append(getDisplayName()).append(Symbol.PARENTHESE_RIGHT); } if (!getIfAlias().isEmpty()) { sb.append(" [IfAlias=").append(getIfAlias()).append("]"); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/common/AbstractUsbDevice.java b/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/common/AbstractUsbDevice.java index b5faf5e162..f6d87d1bcb 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/common/AbstractUsbDevice.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/builtin/hardware/common/AbstractUsbDevice.java @@ -27,6 +27,7 @@ import org.miaixz.bus.core.annotation.Immutable; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.health.builtin.hardware.UsbDevice; import java.util.Collections; @@ -74,7 +75,7 @@ private static String indentUsb(UsbDevice usbDevice, int indent) { StringBuilder sb = new StringBuilder(String.format(Locale.ROOT, indentFmt, Normal.EMPTY)); sb.append(usbDevice.getName()); if (!usbDevice.getVendor().isEmpty()) { - sb.append(" (").append(usbDevice.getVendor()).append(')'); + sb.append(" (").append(usbDevice.getVendor()).append(Symbol.C_PARENTHESE_RIGHT); } if (!usbDevice.getSerialNumber().isEmpty()) { sb.append(" [s/n: ").append(usbDevice.getSerialNumber()).append(']'); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/OSSession.java b/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/OSSession.java index 623a4a89e1..48df7659f1 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/OSSession.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/OSSession.java @@ -28,6 +28,7 @@ import org.miaixz.bus.core.annotation.Immutable; import org.miaixz.bus.core.lang.Fields; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import java.time.Instant; import java.time.LocalDateTime; @@ -101,7 +102,7 @@ public String toString() { : LocalDateTime.ofInstant(Instant.ofEpochMilli(loginTime), ZoneId.systemDefault()).format(LOGIN_FORMAT); String hostStr = Normal.EMPTY; if (!host.isEmpty() && !host.equals("::") && !host.equals("0.0.0.0")) { - hostStr = ", (" + host + ")"; + hostStr = ", (" + host + Symbol.PARENTHESE_RIGHT; } return String.format(Locale.ROOT, "%s, %s, %s%s", userName, terminalDevice, loginStr, hostStr); } diff --git a/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/OperatingSystem.java b/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/OperatingSystem.java index c07c0a1009..e39fbcfb0e 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/OperatingSystem.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/OperatingSystem.java @@ -28,6 +28,7 @@ import org.miaixz.bus.core.annotation.Immutable; import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.health.IdGroup; import org.miaixz.bus.health.unix.driver.Who; @@ -399,7 +400,7 @@ public OSVersionInfo(String version, String codeName, String buildNumber) { StringBuilder sb = new StringBuilder(getVersion() != null ? getVersion() : Normal.UNKNOWN); if (!StringKit.isBlank(getCodeName())) { - sb.append(" (").append(getCodeName()).append(')'); + sb.append(" (").append(getCodeName()).append(Symbol.C_PARENTHESE_RIGHT); } if (!StringKit.isBlank(getBuildNumber())) { sb.append(" build ").append(getBuildNumber()); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/common/AbstractFileSystem.java b/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/common/AbstractFileSystem.java index 2da9a5a707..c816641255 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/common/AbstractFileSystem.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/builtin/software/common/AbstractFileSystem.java @@ -27,6 +27,7 @@ import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.health.Config; import org.miaixz.bus.health.builtin.software.FileSystem; import org.miaixz.bus.health.builtin.software.OSFileStore; @@ -47,10 +48,10 @@ public abstract class AbstractFileSystem implements FileSystem { * FileSystem types which are network-based and should be excluded from local-only lists */ protected static final List NETWORK_FS_TYPES = Arrays - .asList(Config.get(Config._NETWORK_FILESYSTEM_TYPES, Normal.EMPTY).split(",")); + .asList(Config.get(Config._NETWORK_FILESYSTEM_TYPES, Normal.EMPTY).split(Symbol.COMMA)); protected static final List PSEUDO_FS_TYPES = Arrays - .asList(Config.get(Config._PSEUDO_FILESYSTEM_TYPES, Normal.EMPTY).split(",")); + .asList(Config.get(Config._PSEUDO_FILESYSTEM_TYPES, Normal.EMPTY).split(Symbol.COMMA)); @Override public List getFileStores() { diff --git a/bus-health/src/main/java/org/miaixz/bus/health/linux/driver/Sysfs.java b/bus-health/src/main/java/org/miaixz/bus/health/linux/driver/Sysfs.java index 0825b0e3c6..619caf49eb 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/linux/driver/Sysfs.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/linux/driver/Sysfs.java @@ -27,6 +27,7 @@ import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.health.Builder; import org.miaixz.bus.health.Parsing; @@ -68,7 +69,7 @@ public static String queryProductModel() { } } else { if (!productVersion.isEmpty() && !"None".equals(productVersion)) { - return productName + " (version: " + productVersion + ")"; + return productName + " (version: " + productVersion + Symbol.PARENTHESE_RIGHT; } return productName; } @@ -192,7 +193,7 @@ public static String queryBiosDescription() { public static String queryBiosVersion(String biosRevision) { final String biosVersion = Builder.getStringFromFile(SysPath.DMI_ID + "bios_version").trim(); if (!biosVersion.isEmpty()) { - return biosVersion + (StringKit.isBlank(biosRevision) ? Normal.EMPTY : " (revision " + biosRevision + ")"); + return biosVersion + (StringKit.isBlank(biosRevision) ? Normal.EMPTY : " (revision " + biosRevision + Symbol.PARENTHESE_RIGHT); } return null; } diff --git a/bus-health/src/main/java/org/miaixz/bus/health/linux/driver/proc/ProcessStat.java b/bus-health/src/main/java/org/miaixz/bus/health/linux/driver/proc/ProcessStat.java index a30e18138b..44668e18cf 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/linux/driver/proc/ProcessStat.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/linux/driver/proc/ProcessStat.java @@ -57,7 +57,7 @@ public final class ProcessStat { static { String stat = Builder.getStringFromFile(ProcPath.SELF_STAT); - if (stat.contains(")")) { + if (stat.contains(Symbol.PARENTHESE_RIGHT)) { // add 3 to account for pid, process name in prarenthesis, and state PROC_PID_STAT_LENGTH = Parsing.countStringToLongArray(stat, Symbol.C_SPACE) + 3; } else { @@ -86,8 +86,8 @@ public static Triplet> getPidStats(int pid return null; } // Get process name from between parentheses and state immediately after - int nameStart = stat.indexOf('(') + 1; - int nameEnd = stat.indexOf(')'); + int nameStart = stat.indexOf(Symbol.C_PARENTHESE_LEFT) + 1; + int nameEnd = stat.indexOf(Symbol.C_PARENTHESE_RIGHT); String name = stat.substring(nameStart, nameEnd); Character state = stat.charAt(nameEnd + 2); // Split everything after the state diff --git a/bus-health/src/main/java/org/miaixz/bus/health/linux/hardware/LinuxCentralProcessor.java b/bus-health/src/main/java/org/miaixz/bus/health/linux/hardware/LinuxCentralProcessor.java index f5b088c5b1..20695bc6f2 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/linux/hardware/LinuxCentralProcessor.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/linux/hardware/LinuxCentralProcessor.java @@ -224,7 +224,7 @@ private static Map mapNumaNodesFromLscpu() { // 1,0 for (String line : lscpu) { if (!line.startsWith(Symbol.SHAPE)) { - int pos = line.indexOf(','); + int pos = line.indexOf(Symbol.C_COMMA); if (pos > 0 && pos < line.length()) { numaNodeMap.put(Parsing.parseIntOrDefault(line.substring(0, pos), 0), Parsing.parseIntOrDefault(line.substring(pos + 1), 0)); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/linux/hardware/LinuxGraphicsCard.java b/bus-health/src/main/java/org/miaixz/bus/health/linux/hardware/LinuxGraphicsCard.java index 9435952314..2ec685315a 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/linux/hardware/LinuxGraphicsCard.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/linux/hardware/LinuxGraphicsCard.java @@ -111,7 +111,7 @@ private static List getGraphicsCardsFromLspci() { } else if (prefix.equals("Vendor")) { Pair pair = Parsing.parseLspciMachineReadable(split[1].trim()); if (pair != null) { - vendor = pair.getLeft() + " (0x" + pair.getRight() + ")"; + vendor = pair.getLeft() + " (0x" + pair.getRight() + Symbol.PARENTHESE_RIGHT; } else { vendor = split[1].trim(); } diff --git a/bus-health/src/main/java/org/miaixz/bus/health/linux/software/LinuxOSProcess.java b/bus-health/src/main/java/org/miaixz/bus/health/linux/software/LinuxOSProcess.java index 979fb103b7..44e4d94580 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/linux/software/LinuxOSProcess.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/linux/software/LinuxOSProcess.java @@ -119,7 +119,7 @@ private static void getMissingDetails(Map status, String stat) { return; } - int nameStart = stat.indexOf('('); + int nameStart = stat.indexOf(Symbol.C_PARENTHESE_LEFT); int nameEnd = stat.indexOf(')'); if (StringKit.isBlank(status.get("Name")) && nameStart > 0 && nameStart < nameEnd) { // remove leading and trailing parentheses diff --git a/bus-health/src/main/java/org/miaixz/bus/health/mac/driver/WindowInfo.java b/bus-health/src/main/java/org/miaixz/bus/health/mac/driver/WindowInfo.java index 82e87657d4..6c1cf3a581 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/mac/driver/WindowInfo.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/mac/driver/WindowInfo.java @@ -28,6 +28,7 @@ import com.sun.jna.Pointer; import com.sun.jna.platform.mac.CoreFoundation.*; import org.miaixz.bus.core.annotation.ThreadSafe; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.health.Formats; import org.miaixz.bus.health.builtin.software.OSDesktopWindow; import org.miaixz.bus.health.mac.CFKit; @@ -103,7 +104,7 @@ public static List queryDesktopWindows(boolean visibleOnly) { if (windowName.isEmpty()) { windowName = windowOwnerName; } else { - windowName = windowName + "(" + windowOwnerName + ")"; + windowName = windowName + Symbol.PARENTHESE_LEFT + windowOwnerName + Symbol.PARENTHESE_RIGHT; } windowList.add(new OSDesktopWindow(windowNumber, windowName, windowOwnerName, windowBounds, diff --git a/bus-health/src/main/java/org/miaixz/bus/health/mac/software/MacFileSystem.java b/bus-health/src/main/java/org/miaixz/bus/health/mac/software/MacFileSystem.java index bd3674bdc5..a96f377b89 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/mac/software/MacFileSystem.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/mac/software/MacFileSystem.java @@ -42,6 +42,7 @@ import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.lang.Charset; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.health.Builder; import org.miaixz.bus.health.Config; import org.miaixz.bus.health.builtin.software.OSFileStore; @@ -188,9 +189,9 @@ private static List getFileStoreMatching(String nameToMatch, boolea StringBuilder options = new StringBuilder((MNT_RDONLY & flags) == 0 ? "rw" : "ro"); String moreOptions = OPTIONS_MAP.entrySet().stream().filter(e -> (e.getKey() & flags) > 0) - .map(Map.Entry::getValue).collect(Collectors.joining(",")); + .map(Map.Entry::getValue).collect(Collectors.joining(Symbol.COMMA)); if (!moreOptions.isEmpty()) { - options.append(',').append(moreOptions); + options.append(Symbol.C_COMMA).append(moreOptions); } String uuid = Normal.EMPTY; diff --git a/bus-health/src/main/java/org/miaixz/bus/health/mac/software/MacOperatingSystem.java b/bus-health/src/main/java/org/miaixz/bus/health/mac/software/MacOperatingSystem.java index cd77a48f6f..e82e635f54 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/mac/software/MacOperatingSystem.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/mac/software/MacOperatingSystem.java @@ -28,6 +28,7 @@ import com.sun.jna.platform.mac.SystemB; import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.tuple.Pair; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.health.Config; @@ -65,7 +66,7 @@ public class MacOperatingSystem extends AbstractOperatingSystem { // Usually this works. If it doesn't, fall back to text parsing. // Boot time will be the first consecutive string of digits. BOOTTIME = Parsing.parseLongOrDefault( - Executor.getFirstAnswer("sysctl -n kern.boottime").split(",")[0].replaceAll("\\D", Normal.EMPTY), + Executor.getFirstAnswer("sysctl -n kern.boottime").split(Symbol.COMMA)[0].replaceAll("\\D", Normal.EMPTY), System.currentTimeMillis() / 1000); } else { // tv now points to a 64-bit timeval structure for boot time. diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/aix/hardware/AixComputerSystem.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/aix/hardware/AixComputerSystem.java index 23059f1a46..d02d8c5e3f 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/aix/hardware/AixComputerSystem.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/aix/hardware/AixComputerSystem.java @@ -28,6 +28,7 @@ import org.miaixz.bus.core.annotation.Immutable; import org.miaixz.bus.core.center.regex.Pattern; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.health.Executor; import org.miaixz.bus.health.Memoizer; @@ -81,7 +82,7 @@ private static LsattrStrings readLsattr() { for (final String checkLine : Executor.runNative("lsattr -El sys0")) { if (checkLine.startsWith(fwVersionMarker)) { fwVersion = checkLine.split(fwVersionMarker)[1].trim(); - int comma = fwVersion.indexOf(','); + int comma = fwVersion.indexOf(Symbol.C_COMMA); if (comma > 0 && fwVersion.length() > comma) { fwVendor = fwVersion.substring(0, comma); fwVersion = fwVersion.substring(comma + 1); @@ -89,7 +90,7 @@ private static LsattrStrings readLsattr() { fwVersion = Pattern.SPACES_PATTERN.split(fwVersion)[0]; } else if (checkLine.startsWith(modelMarker)) { model = checkLine.split(modelMarker)[1].trim(); - int comma = model.indexOf(','); + int comma = model.indexOf(Symbol.C_COMMA); if (comma > 0 && model.length() > comma) { manufacturer = model.substring(0, comma); model = model.substring(comma + 1); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/aix/hardware/AixGraphicsCard.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/aix/hardware/AixGraphicsCard.java index 2200a98994..d0dd835e29 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/aix/hardware/AixGraphicsCard.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/aix/hardware/AixGraphicsCard.java @@ -86,7 +86,7 @@ public static List getGraphicsCards(Supplier> lscfg) } else if (s.startsWith("Hardware Location Code")) { cardList.add(new AixGraphicsCard(name, Normal.UNKNOWN, StringKit.isBlank(vendor) ? Normal.UNKNOWN : vendor, - versionInfo.isEmpty() ? Normal.UNKNOWN : String.join(",", versionInfo), 0L)); + versionInfo.isEmpty() ? Normal.UNKNOWN : String.join(Symbol.COMMA, versionInfo), 0L)); display = false; } } diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/hardware/FreeBsdCentralProcessor.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/hardware/FreeBsdCentralProcessor.java index 8a727c55c4..8429f91c4e 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/hardware/FreeBsdCentralProcessor.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/hardware/FreeBsdCentralProcessor.java @@ -115,7 +115,7 @@ private static List parseTopology() { if (m.matches()) { // If csv of hex values like "f,0,0,0", parse the first value String csvMatch = m.group(1); - String[] csvTokens = csvMatch.split(","); + String[] csvTokens = csvMatch.split(Symbol.COMMA); String firstVal = csvTokens[0]; // Regex guarantees parsing digits so we won't get a diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/hardware/FreeBsdGraphicsCard.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/hardware/FreeBsdGraphicsCard.java index ffc93a5a8c..07d8408726 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/hardware/FreeBsdGraphicsCard.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/hardware/FreeBsdGraphicsCard.java @@ -115,7 +115,7 @@ public static List getGraphicsCards() { String key = split[0].trim(); if (key.equals("vendor")) { vendorId = Parsing.getSingleQuoteStringValue(line) - + (vendorId.equals(Normal.UNKNOWN) ? Normal.EMPTY : " (" + vendorId + ")"); + + (vendorId.equals(Normal.UNKNOWN) ? Normal.EMPTY : " (" + vendorId + Symbol.PARENTHESE_RIGHT); } else if (key.equals("device")) { name = Parsing.getSingleQuoteStringValue(line); } diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/software/FreeBsdOSProcess.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/software/FreeBsdOSProcess.java index cc5154d1b1..b039e0af80 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/software/FreeBsdOSProcess.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/software/FreeBsdOSProcess.java @@ -61,7 +61,7 @@ public class FreeBsdOSProcess extends AbstractOSProcess { static final String PS_THREAD_COLUMNS = Arrays.stream(PsThreadColumns.values()).map(Enum::name) - .map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.joining(",")); + .map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.joining(Symbol.COMMA)); private static final int ARGMAX = BsdSysctlKit.sysctl("kern.argmax", 0); private final FreeBsdOperatingSystem os; private final Supplier bitness = Memoizer.memoize(this::queryBitness); @@ -278,7 +278,7 @@ public long getAffinityMask() { // cpuset: getaffinity: No such process String[] split = cpuset.split(Symbol.COLON); if (split.length > 1) { - String[] bits = split[1].split(","); + String[] bits = split[1].split(Symbol.COMMA); for (String bit : bits) { int bitToSet = Parsing.parseIntOrDefault(bit.trim(), -1); if (bitToSet >= 0) { diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/software/FreeBsdOperatingSystem.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/software/FreeBsdOperatingSystem.java index a5dba510af..07aafbc5fe 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/software/FreeBsdOperatingSystem.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/freebsd/software/FreeBsdOperatingSystem.java @@ -57,7 +57,7 @@ public class FreeBsdOperatingSystem extends AbstractOperatingSystem { static final String PS_COMMAND_ARGS = Arrays.stream(PsKeywords.values()).map(Enum::name) - .map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.joining(",")); + .map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.joining(Symbol.COMMA)); private static final long BOOTTIME = querySystemBootTime(); private static long querySystemBootTime() { @@ -66,7 +66,7 @@ private static long querySystemBootTime() { // Usually this works. If it doesn't, fall back to text parsing. // Boot time will be the first consecutive string of digits. return Parsing.parseLongOrDefault( - Executor.getFirstAnswer("sysctl -n kern.boottime").split(",")[0].replaceAll("\\D", Normal.EMPTY), + Executor.getFirstAnswer("sysctl -n kern.boottime").split(Symbol.COMMA)[0].replaceAll("\\D", Normal.EMPTY), System.currentTimeMillis() / 1000); } // tv now points to a 128-bit timeval structure for boot time. diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/driver/disk/Disklabel.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/driver/disk/Disklabel.java index 340b30b5cd..f5610e84fb 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/driver/disk/Disklabel.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/driver/disk/Disklabel.java @@ -156,7 +156,7 @@ private static Pair getMajorMinor(String diskName, String name int major = 0; int minor = 0; String majorMinor = Executor.getFirstAnswer("stat -f %Hr,%Lr /dev/" + diskName + name); - int comma = majorMinor.indexOf(','); + int comma = majorMinor.indexOf(Symbol.C_COMMA); if (comma > 0 && comma < majorMinor.length()) { major = Parsing.parseIntOrDefault(majorMinor.substring(0, comma), 0); minor = Parsing.parseIntOrDefault(majorMinor.substring(comma + 1), 0); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdCentralProcessor.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdCentralProcessor.java index 44d7a48959..e0e711134d 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdCentralProcessor.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdCentralProcessor.java @@ -30,6 +30,7 @@ import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.center.regex.Pattern; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.tuple.Pair; import org.miaixz.bus.core.lang.tuple.Triplet; import org.miaixz.bus.core.lang.tuple.Tuple; @@ -234,7 +235,7 @@ protected Tuple initProcessorCounts() { } else { Matcher n = q.matcher(s); if (n.matches()) { - for (String cacheStr : n.group(1).split(",")) { + for (String cacheStr : n.group(1).split(Symbol.COMMA)) { CentralProcessor.ProcessorCache cache = parseCacheStr(cacheStr); if (cache != null) { caches.add(cache); @@ -244,7 +245,7 @@ protected Tuple initProcessorCounts() { } if (s.startsWith("cpu")) { String[] ss = s.trim().split(": "); - if (ss.length == 2 && ss[1].split(",").length > 3) { + if (ss.length == 2 && ss[1].split(Symbol.COMMA).length > 3) { featureFlags.add(ss[1]); } } diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdHWDiskStore.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdHWDiskStore.java index fc04043b45..e11f0e670b 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdHWDiskStore.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdHWDiskStore.java @@ -78,7 +78,7 @@ public static List getDisks() { // Get list of disks from sysctl // hw.disknames=sd0:2cf69345d371cd82,cd0:,sd1: - String[] devices = OpenBsdSysctlKit.sysctl("hw.disknames", Normal.EMPTY).split(","); + String[] devices = OpenBsdSysctlKit.sysctl("hw.disknames", Normal.EMPTY).split(Symbol.COMMA); OpenBsdHWDiskStore store; String diskName; for (String device : devices) { diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdUsbDevice.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdUsbDevice.java index a4f06dad47..e3767c5fc9 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdUsbDevice.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/hardware/OpenBsdUsbDevice.java @@ -99,9 +99,9 @@ private static List getUsbDevices() { parent = line.substring(11); } else if (line.startsWith("addr ")) { // addr 01: 8086:0000 Intel, EHCI root hub - if (line.indexOf(Symbol.C_COLON) == 7 && line.indexOf(',') >= 18) { + if (line.indexOf(Symbol.C_COLON) == 7 && line.indexOf(Symbol.C_COMMA) >= 18) { key = parent + line.substring(0, 7); - String[] split = line.substring(8).trim().split(","); + String[] split = line.substring(8).trim().split(Symbol.COMMA); if (split.length > 1) { // 0 = vid:pid vendor String vendorStr = split[0].trim(); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/software/OpenBsdOSProcess.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/software/OpenBsdOSProcess.java index f0eca97f1f..68c962afd5 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/software/OpenBsdOSProcess.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/software/OpenBsdOSProcess.java @@ -60,7 +60,7 @@ public class OpenBsdOSProcess extends AbstractOSProcess { static final String PS_THREAD_COLUMNS = Arrays.stream(PsThreadColumns.values()).map(Enum::name) - .map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.joining(",")); + .map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.joining(Symbol.COMMA)); private static final int ARGMAX; static { @@ -318,7 +318,7 @@ public long getAffinityMask() { // cpuset: getaffinity: No such process String[] split = cpuset.split(Symbol.COLON); if (split.length > 1) { - String[] bits = split[1].split(","); + String[] bits = split[1].split(Symbol.COMMA); for (String bit : bits) { int bitToSet = Parsing.parseIntOrDefault(bit.trim(), -1); if (bitToSet >= 0) { diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/software/OpenBsdOperatingSystem.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/software/OpenBsdOperatingSystem.java index a8b1c60f65..006be14cde 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/software/OpenBsdOperatingSystem.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/openbsd/software/OpenBsdOperatingSystem.java @@ -52,13 +52,13 @@ public class OpenBsdOperatingSystem extends AbstractOperatingSystem { static final String PS_COMMAND_ARGS = Arrays.stream(PsKeywords.values()).map(Enum::name) - .map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.joining(",")); + .map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.joining(Symbol.COMMA)); private static final long BOOTTIME = querySystemBootTime(); private static long querySystemBootTime() { // Boot time will be the first consecutive string of digits. return Parsing.parseLongOrDefault( - Executor.getFirstAnswer("sysctl -n kern.boottime").split(",")[0].replaceAll("\\D", Normal.EMPTY), + Executor.getFirstAnswer("sysctl -n kern.boottime").split(Symbol.COMMA)[0].replaceAll("\\D", Normal.EMPTY), System.currentTimeMillis() / 1000); } diff --git a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/solaris/driver/disk/Iostat.java b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/solaris/driver/disk/Iostat.java index 34ea206f5a..e20b17bd52 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/solaris/driver/disk/Iostat.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/unix/platform/solaris/driver/disk/Iostat.java @@ -28,6 +28,7 @@ import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.center.regex.Pattern; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.tuple.Tuple; import org.miaixz.bus.health.Executor; import org.miaixz.bus.health.Parsing; @@ -86,10 +87,10 @@ public static Map queryPartitionToMountMap() { for (int i = 0; i < mountNames.size() && i < mountPoints.size(); i++) { // Map disk disk = mountNames.get(i); - String[] diskSplit = disk.split(","); + String[] diskSplit = disk.split(Symbol.COMMA); if (diskSplit.length >= 5 && !DEVICE_HEADER.equals(diskSplit[0])) { String mount = mountPoints.get(i); - String[] mountSplit = mount.split(","); + String[] mountSplit = mount.split(Symbol.COMMA); if (mountSplit.length >= 5 && !DEVICE_HEADER.equals(mountSplit[4])) { deviceMap.put(diskSplit[0], mountSplit[4]); } @@ -119,7 +120,7 @@ public static Map queryDeviceStrings(Set diskSet) { // The -r switch enables comma delimited for easy parsing! // No guarantees on which line the results appear so we'll nest // a loop iterating on the comma splits - String[] split = line.split(","); + String[] split = line.split(Symbol.COMMA); for (String keyValue : split) { keyValue = keyValue.trim(); // If entry is tne name of a disk, this is beginning of new diff --git a/bus-health/src/main/java/org/miaixz/bus/health/windows/PerfDataKit.java b/bus-health/src/main/java/org/miaixz/bus/health/windows/PerfDataKit.java index 887af8635f..0fd352efdc 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/windows/PerfDataKit.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/windows/PerfDataKit.java @@ -35,6 +35,7 @@ import com.sun.jna.platform.win32.WinNT.HANDLEByReference; import org.miaixz.bus.core.annotation.Immutable; import org.miaixz.bus.core.annotation.ThreadSafe; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.health.Builder; import org.miaixz.bus.health.Formats; import org.miaixz.bus.health.Parsing; @@ -263,7 +264,7 @@ public String getCounterPath() { StringBuilder sb = new StringBuilder(); sb.append('\\').append(object); if (instance != null) { - sb.append('(').append(instance).append(')'); + sb.append(Symbol.C_PARENTHESE_LEFT).append(instance).append(Symbol.C_PARENTHESE_RIGHT); } sb.append('\\').append(counter); return sb.toString(); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/windows/WmiKit.java b/bus-health/src/main/java/org/miaixz/bus/health/windows/WmiKit.java index 5fc3bce254..5e0905cad1 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/windows/WmiKit.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/windows/WmiKit.java @@ -31,6 +31,7 @@ import com.sun.jna.platform.win32.Variant; import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.health.Builder; import org.miaixz.bus.health.Parsing; @@ -68,7 +69,7 @@ public static > String queryToString(WmiQuery query) { StringBuilder sb = new StringBuilder("SELECT "); sb.append(props[0].name()); for (int i = 1; i < props.length; i++) { - sb.append(',').append(props[i].name()); + sb.append(Symbol.C_COMMA).append(props[i].name()); } sb.append(" FROM ").append(query.getWmiClassName()); return sb.toString(); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/windows/driver/DeviceTree.java b/bus-health/src/main/java/org/miaixz/bus/health/windows/driver/DeviceTree.java index 95d0316bc7..e7ec063dcb 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/windows/driver/DeviceTree.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/windows/driver/DeviceTree.java @@ -31,6 +31,7 @@ import com.sun.jna.platform.win32.WinNT.HANDLE; import com.sun.jna.ptr.IntByReference; import org.miaixz.bus.core.annotation.ThreadSafe; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.tuple.Tuple; import org.miaixz.bus.health.builtin.jna.ByRef; import org.miaixz.bus.health.builtin.jna.Struct; @@ -101,7 +102,7 @@ public static Tuple queryDeviceTree( name = getDevNodeProperty(node, Cfgmgr32.CM_DRP_CLASS, buf, size); String svc = getDevNodeProperty(node, Cfgmgr32.CM_DRP_SERVICE, buf, size); if (!svc.isEmpty()) { - name = name + " (" + svc + ")"; + name = name + " (" + svc + Symbol.PARENTHESE_RIGHT; } } nameMap.put(node, name); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/windows/hardware/WindowsCentralProcessor.java b/bus-health/src/main/java/org/miaixz/bus/health/windows/hardware/WindowsCentralProcessor.java index 057657828a..270027e596 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/windows/hardware/WindowsCentralProcessor.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/windows/hardware/WindowsCentralProcessor.java @@ -34,6 +34,7 @@ import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.center.regex.Pattern; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.tuple.Pair; import org.miaixz.bus.core.lang.tuple.Triplet; import org.miaixz.bus.core.lang.tuple.Tuple; @@ -251,7 +252,7 @@ public long[] queryCurrentFreq() { long maxFreq = this.getMaxFreq(); long[] freqs = new long[getLogicalProcessorCount()]; for (String instance : instances) { - int cpu = instance.contains(",") ? numaNodeProcToLogicalProcMap.getOrDefault(instance, 0) + int cpu = instance.contains(Symbol.COMMA) ? numaNodeProcToLogicalProcMap.getOrDefault(instance, 0) : Parsing.parseIntOrDefault(instance, 0); if (cpu >= getLogicalProcessorCount()) { continue; @@ -407,7 +408,7 @@ public long[][] queryProcessorCpuLoadTicks() { return ticks; } for (String instance : instances) { - int cpu = instance.contains(",") ? numaNodeProcToLogicalProcMap.getOrDefault(instance, 0) + int cpu = instance.contains(Symbol.COMMA) ? numaNodeProcToLogicalProcMap.getOrDefault(instance, 0) : Parsing.parseIntOrDefault(instance, 0); if (cpu >= ncpu) { continue; diff --git a/bus-health/src/main/java/org/miaixz/bus/health/windows/hardware/WindowsGraphicsCard.java b/bus-health/src/main/java/org/miaixz/bus/health/windows/hardware/WindowsGraphicsCard.java index f0b3887a91..009750b8de 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/windows/hardware/WindowsGraphicsCard.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/windows/hardware/WindowsGraphicsCard.java @@ -29,6 +29,7 @@ import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiResult; import org.miaixz.bus.core.annotation.Immutable; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.tuple.Triplet; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.health.Parsing; @@ -149,7 +150,7 @@ private static List getGraphicsCardsFromWmi() { if (StringKit.isBlank(vendor)) { deviceId = idPair.getLeft(); } else { - vendor = vendor + " (" + idPair.getLeft() + ")"; + vendor = vendor + " (" + idPair.getLeft() + Symbol.PARENTHESE_RIGHT; } } String versionInfo = WmiKit.getString(cards, VideoControllerProperty.DRIVERVERSION, index); diff --git a/bus-health/src/main/java/org/miaixz/bus/health/windows/software/WindowsFileSystem.java b/bus-health/src/main/java/org/miaixz/bus/health/windows/software/WindowsFileSystem.java index 2b933f4793..b40c9679ba 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/windows/software/WindowsFileSystem.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/windows/software/WindowsFileSystem.java @@ -32,6 +32,7 @@ import com.sun.jna.platform.win32.WinNT; import org.miaixz.bus.core.annotation.ThreadSafe; import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.health.Parsing; import org.miaixz.bus.health.builtin.jna.ByRef; import org.miaixz.bus.health.builtin.software.OSFileStore; @@ -168,9 +169,9 @@ static ArrayList getLocalVolumes(String volumeToMatch) { StringBuilder options = new StringBuilder((FILE_READ_ONLY_VOLUME & flags) == 0 ? "rw" : "ro"); String moreOptions = OPTIONS_MAP.entrySet().stream().filter(e -> (e.getKey() & flags) > 0) - .map(Map.Entry::getValue).collect(Collectors.joining(",")); + .map(Map.Entry::getValue).collect(Collectors.joining(Symbol.COMMA)); if (!moreOptions.isEmpty()) { - options.append(',').append(moreOptions); + options.append(Symbol.C_COMMA).append(moreOptions); } Kernel32.INSTANCE.GetDiskFreeSpaceEx(volume, userFreeBytes, totalBytes, systemFreeBytes); // Parse uuid from volume name diff --git a/bus-health/src/main/java/org/miaixz/bus/health/windows/software/WindowsOperatingSystem.java b/bus-health/src/main/java/org/miaixz/bus/health/windows/software/WindowsOperatingSystem.java index 5c1aa66ffb..39c1657eb3 100644 --- a/bus-health/src/main/java/org/miaixz/bus/health/windows/software/WindowsOperatingSystem.java +++ b/bus-health/src/main/java/org/miaixz/bus/health/windows/software/WindowsOperatingSystem.java @@ -158,7 +158,7 @@ private static String parseCodeName(int suiteMask) { if ((suiteMask & 0x00008000) != 0) { suites.add("Home Server"); } - return String.join(",", suites); + return String.join(Symbol.COMMA, suites); } private static Map queryProcessMapFromPerfCounters() { diff --git a/bus-http/README.md b/bus-http/README.md index d5e2fa2a47..05f5699eb1 100644 --- a/bus-http/README.md +++ b/bus-http/README.md @@ -279,7 +279,7 @@ interceptor 被保存在 List interceptors 集合中,按照添加 RealCall#getResponseWithInterceptorChain() 方法。通过 Httpd.Builder#addNetworkInterceptor(Interceptor) 传入; -这里举一个简单的例子,例如有这样一个需求,我要监控App通过 Httpd 发出的所有原始请求,以及整个请求所耗费的时间,针对这样的需求就可以使用第一类全局的 +这里举一个简单的示例,例如有这样一个需求,我要监控App通过 Httpd 发出的所有原始请求,以及整个请求所耗费的时间,针对这样的需求就可以使用第一类全局的 interceptor 在拦截器链头去做。 ```java @@ -697,7 +697,7 @@ get(); ### 实现断点续传 -Httpv 对断点续传并没有再做更高层次的封装,因为这是app该去做的事情,它在设计上使各种网络问题的处理变简单的同时力求纯粹。下面的例子可以看到,Httpv +Httpv 对断点续传并没有再做更高层次的封装,因为这是app该去做的事情,它在设计上使各种网络问题的处理变简单的同时力求纯粹。下面的示例可以看到,Httpv 通过一个失败回调拿到 **断点**,便将复杂的问题变得简单: ```java diff --git a/bus-http/pom.xml b/bus-http/pom.xml index e2ba6ffb27..c5e64be6db 100755 --- a/bus-http/pom.xml +++ b/bus-http/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-http - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-http/src/main/java/org/miaixz/bus/http/Headers.java b/bus-http/src/main/java/org/miaixz/bus/http/Headers.java index cd19bd1048..dc9d2ac8f8 100644 --- a/bus-http/src/main/java/org/miaixz/bus/http/Headers.java +++ b/bus-http/src/main/java/org/miaixz/bus/http/Headers.java @@ -200,7 +200,7 @@ public static Set varyFields(Headers responseHeaders) { if (result.isEmpty()) { result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); } - for (String varyField : value.split(",")) { + for (String varyField : value.split(Symbol.COMMA)) { result.add(varyField.trim()); } } @@ -336,7 +336,7 @@ private static boolean skipWhitespaceAndCommas(Buffer buffer) { boolean commaFound = false; while (!buffer.exhausted()) { byte b = buffer.getByte(0); - if (b == ',') { + if (b == Symbol.C_COMMA) { buffer.readByte(); // Consume ','. commaFound = true; } else if (b == Symbol.C_SPACE || b == '\t') { diff --git a/bus-http/src/main/java/org/miaixz/bus/http/accord/ConnectionSuite.java b/bus-http/src/main/java/org/miaixz/bus/http/accord/ConnectionSuite.java index db0160e78c..24b3ad639c 100644 --- a/bus-http/src/main/java/org/miaixz/bus/http/accord/ConnectionSuite.java +++ b/bus-http/src/main/java/org/miaixz/bus/http/accord/ConnectionSuite.java @@ -25,6 +25,7 @@ ********************************************************************************/ package org.miaixz.bus.http.accord; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.net.tls.TlsVersion; import org.miaixz.bus.http.secure.CipherSuite; @@ -232,7 +233,7 @@ public String toString() { + "cipherSuites=" + Objects.toString(cipherSuites(), "[all enabled]") + ", tlsVersions=" + Objects.toString(tlsVersions(), "[all enabled]") + ", supportsTlsExtensions=" + supportsTlsExtensions - + ")"; + + Symbol.PARENTHESE_RIGHT; } public static class Builder { diff --git a/bus-http/src/main/java/org/miaixz/bus/http/cache/CacheControl.java b/bus-http/src/main/java/org/miaixz/bus/http/cache/CacheControl.java index 2ecb2cc2f0..d652d1be40 100644 --- a/bus-http/src/main/java/org/miaixz/bus/http/cache/CacheControl.java +++ b/bus-http/src/main/java/org/miaixz/bus/http/cache/CacheControl.java @@ -171,7 +171,7 @@ public static CacheControl parse(Headers headers) { String directive = value.substring(tokenStart, pos).trim(); String parameter; - if (pos == value.length() || value.charAt(pos) == ',' || value.charAt(pos) == Symbol.C_SEMICOLON) { + if (pos == value.length() || value.charAt(pos) == Symbol.C_COMMA || value.charAt(pos) == Symbol.C_SEMICOLON) { pos++; // consume ',' or ';' (if necessary) parameter = null; } else { diff --git a/bus-http/src/main/java/org/miaixz/bus/http/plugin/httpv/ResultBody.java b/bus-http/src/main/java/org/miaixz/bus/http/plugin/httpv/ResultBody.java index eca9a34976..73da4d21a7 100644 --- a/bus-http/src/main/java/org/miaixz/bus/http/plugin/httpv/ResultBody.java +++ b/bus-http/src/main/java/org/miaixz/bus/http/plugin/httpv/ResultBody.java @@ -348,14 +348,14 @@ private String resolveFilePath(String dirPath, String fileName) { private String indexFileName(String fileName, int index) { int i = fileName.lastIndexOf(Symbol.C_DOT); if (i < 0) { - return fileName + Symbol.PARENTHESE_LEFT + index + ")"; + return fileName + Symbol.PARENTHESE_LEFT + index + Symbol.PARENTHESE_RIGHT; } String ext = fileName.substring(i); if (i > 0) { String name = fileName.substring(0, i); - return name + Symbol.PARENTHESE_LEFT + index + ")" + ext; + return name + Symbol.PARENTHESE_LEFT + index + Symbol.PARENTHESE_RIGHT + ext; } - return Symbol.PARENTHESE_LEFT + index + ")" + ext; + return Symbol.PARENTHESE_LEFT + index + Symbol.PARENTHESE_RIGHT + ext; } private String resolveFileName() { diff --git a/bus-image/pom.xml b/bus-image/pom.xml index 313692797e..0435b19223 100755 --- a/bus-image/pom.xml +++ b/bus-image/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-image - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-image/src/main/java/org/miaixz/bus/image/Args.java b/bus-image/src/main/java/org/miaixz/bus/image/Args.java index 9ce5a9b4b9..39d85fddc1 100755 --- a/bus-image/src/main/java/org/miaixz/bus/image/Args.java +++ b/bus-image/src/main/java/org/miaixz/bus/image/Args.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.image; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.miaixz.bus.image.galaxy.data.ElementDictionary; import org.miaixz.bus.image.metric.ApplicationEntity; import org.miaixz.bus.image.metric.Connection; @@ -44,7 +45,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter public class Args { public static String[] IVR_LE_FIRST = { diff --git a/bus-image/src/main/java/org/miaixz/bus/image/Node.java b/bus-image/src/main/java/org/miaixz/bus/image/Node.java index 8a3fff02a4..5e5011ed64 100755 --- a/bus-image/src/main/java/org/miaixz/bus/image/Node.java +++ b/bus-image/src/main/java/org/miaixz/bus/image/Node.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.image; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.miaixz.bus.core.lang.Http; import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.xyz.StringKit; @@ -42,7 +43,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter public class Node { private final String aet; diff --git a/bus-image/src/main/java/org/miaixz/bus/image/Option.java b/bus-image/src/main/java/org/miaixz/bus/image/Option.java index b56c9384a4..50fefc3506 100755 --- a/bus-image/src/main/java/org/miaixz/bus/image/Option.java +++ b/bus-image/src/main/java/org/miaixz/bus/image/Option.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.image; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.miaixz.bus.core.lang.Http; import org.miaixz.bus.image.metric.Connection; import org.miaixz.bus.image.metric.internal.pdu.ExtendedNegotiate; @@ -38,7 +39,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter public class Option { /** diff --git a/bus-image/src/main/java/org/miaixz/bus/image/Status.java b/bus-image/src/main/java/org/miaixz/bus/image/Status.java index 9e617918da..4dc2c48e53 100755 --- a/bus-image/src/main/java/org/miaixz/bus/image/Status.java +++ b/bus-image/src/main/java/org/miaixz/bus/image/Status.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.image; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.image.galaxy.data.Attributes; @@ -40,7 +41,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter public class Status { public static final int Success = 0x0000; diff --git a/bus-image/src/main/java/org/miaixz/bus/image/metric/AttributeContext.java b/bus-image/src/main/java/org/miaixz/bus/image/metric/AttributeContext.java index 8203ed0f57..c536bac957 100755 --- a/bus-image/src/main/java/org/miaixz/bus/image/metric/AttributeContext.java +++ b/bus-image/src/main/java/org/miaixz/bus/image/metric/AttributeContext.java @@ -25,14 +25,16 @@ ********************************************************************************/ package org.miaixz.bus.image.metric; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.miaixz.bus.image.Node; /** * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter public class AttributeContext { private final String tsuid; diff --git a/bus-image/src/main/java/org/miaixz/bus/image/nimble/opencv/ImageParameters.java b/bus-image/src/main/java/org/miaixz/bus/image/nimble/opencv/ImageParameters.java index 33a4ba0a4b..5c2f1939ee 100755 --- a/bus-image/src/main/java/org/miaixz/bus/image/nimble/opencv/ImageParameters.java +++ b/bus-image/src/main/java/org/miaixz/bus/image/nimble/opencv/ImageParameters.java @@ -25,14 +25,16 @@ ********************************************************************************/ package org.miaixz.bus.image.nimble.opencv; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.miaixz.bus.core.lang.Normal; /** * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter public class ImageParameters { public static final int DEFAULT_TILE_SIZE = Normal._512; diff --git a/bus-limiter/README.md b/bus-limiter/README.md index 5cfb0428e0..7416f68a87 100755 --- a/bus-limiter/README.md +++ b/bus-limiter/README.md @@ -1,530 +1,76 @@ -#### 项目说明 +### 介绍 -## Quick Start + 轻量级本地化热点检测/降级框架,适用于大流量场景,可轻松解决业务中超高流量的并发查询等场景。并且接入和使用极其简单,10秒钟即可接入使用! -添加`@EnableLimiter` 注解 +### 使用 -```java -@SpringBootApplication -@EnableLimiter -public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} -``` - -## How To Use - -以`Lock`组件为例 - -**Step 0. 定义锁资源** - -下面的代码向`BeanFactory`中注册了一个`BeanId`为 `jdkLock`的实例 - -```java -@Bean -Lock jdkLock(){ - JdkLock jdkLock=new JdkLock("mnyJdkLock"); - return jdkLock; - } -``` - -**Step 1. 编写业务接口** - -我们假设有这样一个业务场景,用户可以使用一个Vip兑换码来延长自己的VIP期限,理所当然的是,每个兑换码只能被使用一次,通常情况下,我们会在数据库中查询该兑换码是否存在并且是否已经使用。 - -```java -@RequestMapping(method = RequestMethod.POST, value = "/exchangeVip") -public ResponseMessage exchangeVip(@RequestBody ExchangeVipRequest request){ - return demoService.exchangeVip(request,SpringAware.getCurrentUser()); - } -``` - -**Step 2.添加`HLock`注解** - -上面的接口并不安全,假如在极短的的时间内用户发起了多次相同兑换的请求,由于数据库的事务隔离特性,该兑换码便会被多次兑换,这个漏洞可能被用户恶意使用,造成损失。 -这里涉及的重放攻击问题此处不再深入讨论,( -欢迎移步我的[博客](https://blog.higgs.site/2019/06/24/从接口幂等性到重放攻击/#))。现在我们添加HLock注解保护该接口。 - -```java -@RequestMapping(method = RequestMethod.POST, value = "/exchangeVip") -@HLock(limiter = "jdkLock", key = "#request.vipCode", fallback = "fallbackToBusy") -public ResponseMessage exchangeVip(@RequestBody ExchangeVipRequest request){ - return demoService.exchangeVip(request,SpringAware.getCurrentUser()); - } -``` - -该注解的含义是,在请求到达时,使用`jdkLock`这个锁锁住`#request.vipCode` -这个资源,如果锁成功了,后面的逻辑继续进行,在业务逻辑完成后便会释放该资源,如果`#request.vipCode` -这个资源已经被锁定,便会降级到`fallbackToBusy`方法进行。这样其他相同 `#request.vipCode`的请求便会被拦截, - -在同一class下添加降级方法 `fallbackToBusy` - -```java -ResponseMessage fallbackToBusy(ExchangeVipRequest request){ - return ResponseMessage.error("服务繁忙,请稍后再试!"); - } -``` - -**Step 3. 使用分布式锁** - -随着业务发展,单实例应用不能再满足业务的需求,分布式改造开始了。上面的jdkLock是一个存储在内存的锁,这意味着切换到多实例环境后,仍然可能在多个实例上同时发起多个相同的请求。要解决这个问题,只需要将锁切换至分布式锁即可,这里我们以RedisLock为例。 - -注入一个RedisLock - -```java -@Bean - Lock redisLock(){ - Config config=new Config(); - config.useSingleServer().setAddress("redis://127.0.0.1:6379") - .setDatabase(1); - RedissonClient redissonClient=null; - try{ - redissonClient=Redisson.create(config); - }catch(Exception e){ - logger.info("redis连接失败"); - - } - logger.info("redis连接成功"); - RedisLock redisLock=new RedisLock(redissonClient,"myRedisLock"); - - return redisLock; - } -``` - -修改注解 - -```java -@HLock(limiter = "redisLock", key = "#request.vipCode", fallback = "fallback") -``` - -**Step 4. star this niubility project** - -## Document - -`limiter`是作为顶层抽象,所有类型的限制组件均实现自该接口。limiter的定义非常简单 - -```java -public interface Limiter { - - String getLimiterName(); - - boolean limit(Object key, Map args); - - void release(Object key, Map args); -} -``` - -- `limit`表示锁定key值指定的资源,返回值作为是否锁定成功,锁定失败会立即进入降级逻辑。 -- `release`表示释放已锁定的资源,会在正常的业务逻辑执行后执行。 - -具体类型的组件在继承limiter后进行更细粒度的抽象。例如Lock在作为进一步抽象,而用RedisLock和ZookeeperLock进行进一步的实现。 - -## 自带组件介绍 - -### 1. Lock - -资源锁组件,用于限制资源的并发数量为1,抽象接口为 `Lock` - -对应的注解为`HLock` - -```java -public abstract class Lock implements Limiter { - - public abstract boolean lock(Object key); - - public abstract void unlock(Object key); - - @Override - public boolean limit(Object key, Map args) { - return lock(key); - } - - @Override - public void release(Object key, Map args) { - unlock(key); - } -} -``` - -**提供三种实现**: - -- 以`ConcurrentHashMap`和`ReentrantLock` 为基础的`JdkLock`,适应于单实例环境。 -- 以Redis 为基础的`RedisLock`,适应于对资源容量和速度要求较高的分布式环境。底层为`redisson`实现,有完善的锁延期和防死锁机制。 -- 以Zookeeper为基础的`ZookeeperLock`,适应于对一致性要求极高的分布式环境,速度和容量不及Redis实现 - -### 2. RateLimiter - -频率限制器,用于限制某一资源的访问频率,抽象接口为`RateLimiter`,对应的注解为`HRateLimiter` - -```java -public abstract class RateLimiter implements Limiter { - - public abstract boolean acquire(Object key, double rate, long capacity); - - @Override - public boolean limit(Object key, Map args) { - double pps = (double) args.get("rate"); - long capacity = (long) args.get("capacity"); - return acquire(key, pps, capacity); - } - - @Override - public void release(Object key, Map args) { - // do noting - } -} - -``` - -**提供两种实现:** - -- 以`GuavaCache`和令牌桶算法为基础的`JdkRateLimiter` -- 以`Redis`和令牌桶算法为基础的`RedisRatelimiter` - -### 3. Peak - -限制一个资源的并发数小于固定值,抽象接口为`PeakLimiter`,对应的注解为 - -`HPeak` - -```java -public abstract class PeakLimiter implements Limiter { - - public abstract boolean acquire(Object key, int max); - - public abstract void release(Object key, int max); - - @Override - public boolean limit(Object key, Map args) { - return acquire(key, (int) args.get("max")); - } - - @Override - public void release(Object key, Map args) { - release(key, (int) args.get("max")); - } -} -``` - -**提供两种实现:** - -- 以`GuavaCache`和`Semaphore`为基础的`JdkPeakLimiter`,适应于单实例环境。 -- 以`Redis`为基础的`RedisPeakLimiter`,适应于多实例环境。 +引入依赖: -## 注解介绍 - -### 1. 注解通用基础属性 - -所有类型的注解都默认包含下面5个属性 - -- **limiter** : 使用的限流器的BeanId,将会从Spring的BeanFacotry中获取,不能为空。 例如:设置limiter="jdkLock" 便会使用该限流组件 - -```java - @Bean - Lock jdkLock(){ - JdkLock jdkLock=new JdkLock("mnyJdkLock"); - return jdkLock; - - } -``` - -```java -@HLock(limiter = "jdkLock") -``` - -- **key** : - 资源限制键,为空时将使用类名+方法名作为key,可以实现某一类需求。key中可以使用的参数包括方法的入参,参数注入器注入的参数。具体语法参考`SPEL` - 的语法。 - -- **fallback** : 在锁定资源失败时,触发的降级策略,默认为`defaultFallbackResolver`。limiter工作时, - - 会优先寻找同一Class下相同入参的且方法名为指定值得方法作为降级方法,如果未找到该方法, - - 在从`BeanFactory`中查找,该对象应该实现 `LimitedFallbackResolver`接口,例如 - -```java - public class MyFallback implements LimitedFallbackResolver { - @Override - public Object resolve(Method method, Class clazz, Object[] args, LimitedResource limitedResource, Object target) { - return null; - } - } -``` - -- **errorHandler** : 从BeanFactory中获取。 - 限流组件出现错误时的处理方法,比如使用RedisLock作为分布式锁时,Redis宕机了,如果不想影响业务进行可以选择跳过该限流器。更好的策略应该在具体的限流实现中处理,此处作为一个兜底方法, - 默认策略为`defaultErrorHandler`,即抛出异常。该对象应该实现 接口 - -```java - public class MyErrorHandler implements ErrorHandler { - @Override - public boolean resolve(Throwable throwable, LimiterExecutionContext executionContext) { - // 返回true为跳过该限制器 - return true; - } - } - -``` - -- **argumentInjectors** - :从BeanFactory中获取,可配置多个。参数注入器。如果我们想要使用方法入参之外的参数作为key的变量,可以使用参数注入器注入,比如从用户上下文中注入用户id、从请求上下文中注入ip。该对象应该实现`ArgumentInjector` - 接口 - -```java - public class UserInfoArgumentInjector implements ArgumentInjector { - @Override - public Map inject(Object... args) { - Map ret = new HashMap<>(); - ret.put("userInfo", SpringAware.getCurrentUser()); - return ret; - } - } -``` - -```java - @Bean - ArgumentInjector userInfoArgumentInjector(){ - return new UserInfoArgumentInjector(); - } -``` - -```java - // 注入userInfo 信息 并在key中使用 -@HLock(limiter = "jdkLock", key = "#request.vipCode + #userInfo.userId", fallback = "fallback", argumentInjectors = "userInfoArgumentInjector") -public ResponseMessage exchangeVipOnJDKLock(@RequestBody ExchangeVipRequest request){ - // ... - } -``` - -#### 2. @HLock 注解 - -业务中最常见的需要,限制某一个资源的并发数量。下面的例子即为限制相同`vipCode`的请求最大并发数为1 - -```java -@RequestMapping(method = RequestMethod.POST, value = "/exchangeVip") -@HLock(limiter = "jdkLock", key = "#request.vipCode", fallback = "fallbackToBusy") -public ResponseMessage exchangeVip(@RequestBody ExchangeVipRequest request){ - return demoService.exchangeVip(request,SpringAware.getCurrentUser()); - } +```xml + + org.miaixz + bus-limiter + x.x.x + ``` -#### 3. @HPeak 注解 - -如果你对Java中的信号量(`Semaphore`)熟悉,则你会很容易理解这个注解。该注解的含义是限制一个资源的并发数量。 - -- **max** : 最多的并发数量,默认值为10. - -#### 4. @HRateLimiter注解 - -从名字便可以看出,这是用来限制调用频率的,额外的配置 - -- **rate** : 限制该资源的调用频率,单位为 次/秒,默认值为10 -- **capacity** : 该资源最多可累计的数量, - 比如该资源限制调用的频率为10次/秒,但是该资源已经3秒没有被调用过了,如果最大可累计数量为20,那该资源可在短期内超出10次/秒的限制。更多细节可以参考令牌桶算法。 - -## 如何扩展 - -Limiter提供了标准的扩展方式,开发者可以添加自定义组件。 - -- 定义组件的注解 -- 定义新的限流组件 -- 定义该组件的resource和meta -- 定义注解解析器 -- 添加一个实现 -- 使该组件生效 - -假设我们需要一个黑名单限制组件,我们想要实现一个简单的效果:在请求到达时,检查请求发起者是否是该接口的黑名单用户,如果是黑名单用户,则降级该请求。我们开始实现一个简陋的黑名单校验。 +#### 对任意方法进行热点处理 -**SETP 0. 添加黑名单的注解** +只需要加上`@Hotspot`这个标注,任意方法均可以获得热点检测,并在热点期间用热点数据进行返回,在热点过后,又会自动调用原本业务逻辑。 -```java -public @interface HBlacklist { - String limiter() default ""; - - // 默认的key应该是用户id,用户信息可以用参数注入的方法注入 - String key() default "#userInfo.userId"; - - // 我们可以指定默认的降级方法 - String fallback() default "defaultFallbackResolver"; - String errorHandler() default "defaultErrorHandler"; +举例:比如有一个商品查询的业务,传入tid,返回商品信息。当某个商品进行促销时,访问的量就会增加,但是对于相同的tid而言,其短时间窗口内返回的信息是一致的,框架能够在短时间内把这个tid提为热点数据,并通过对其进行缓存返回来降低对下游业务的压力。而当热点值过后,框架又能够自动摘除这个热点值,使其按照原有方式进行查询。 - String[] argumentInjectors() default {}; +其本质相当于实时的监测了热点,并对其热点数据做了一个短时间内的缓存。 - // 我们用这个值区分不同的接口 - String serviceId() default ""; -} -``` +以下示例代表了:当相同的tid在5秒内超过50次调用时,会自动把这个tid的值提为热点,并用最后一次的返回值直接返回。当调用低于5秒50次调用时,框架会自动的摘除掉这个热点。使其正常的调用你原有代码进行逻辑计算并返回。这一切都是自动的。 -**STEP 1.定义黑名单抽象类** ```java -public abstract class BlacklistLimiter implements Limiter { - - - // 检查userId是否是serviceId的黑名单用户 - public abstract boolean checkExist(Object userId, String serviceId); - - @Override - public boolean limit(Object key, Map args) { - // key值解析出来的应该是userId 这里需要在使用时注意 - // 注意下文关于@LimiterParameter解释,你便会理解 args.get("serviceId")从哪里而来 - return !checkExist(key, (String) args.get("serviceId")); - } - - @Override - public void release(Object key, Map args) { - - //do nothing - } +@Hotspot(grade = FlowGrade.FLOW_GRADE_QPS, count = 50, duration = 5) +public Object get(String tid){ + return tid; } ``` -**STEP 2. 定义该组件的resource和meta** - -所谓resource即将该注解解析出来后的一个容器,meta即将该resource在Spring工厂的配合下进行组装后的产物 -serviceId用`@LimiterParameter`标注,在装配成meta时,会作为限流器的参数放入map中 +其中`grade`参数除了有以`QPS`作为维度统计,还有以`Thread`个数作为维度统计。比如: ```java -public class BlacklistResource extends AbstractLimitedResource { - - - @LimiterParameter - String serviceId; - - public BlacklistResource(String key, Collection argumentInjectors, String fallback, String errorHandler, String limiter, String serviceId) { - super(key, argumentInjectors, fallback, errorHandler, limiter); - this.serviceId = serviceId; - } - - - @Override - public LimitedResourceMetadata createMetadata(BeanFactory beanFactory, Class targetClass, Method targetMethod) { - return new BlacklistLimiterResourceMetadata(this, targetClass, targetMethod, beanFactory); - } +@Hotspot(grade = FlowGrade.FLOW_GRADE_THREAD, count = 50, duration = 5) +public Object get(String tid){ + return tid; } - ``` -```java -public class BlacklistLimiterResourceMetadata extends AbstractLimitedResourceMetadata { +这就代表了,如果某个tid在5秒之内有超过50个线程正在运行,那么就提为热点,并用热点数据直接返回。 - public BlacklistLimiterResourceMetadata(BlacklistResource limitedResource, Class targetClass, Method targetMethod, BeanFactory beanFactory) { - super(limitedResource, targetClass, targetMethod, beanFactory); - } +#### 对任意方法进行降级 - @Override - protected void parseInternal(BlacklistResource limitedResource) { +只需要加上`@Downgrade`注解。任意方法均可获得降级功能。 - } -} -``` +举例:某一个方法需要调用外部的接口,但是外部的接口性能不佳,耗时高。当并发一高时,线程池就会吃满,线程池队列也会逐渐堆积从而导致超时,或者丢弃,严重时会拖垮整个系统。 -**SETP 3. 定义注解解析器** +这时,我们只要对这个方法加上`@Downgrade`标注,即可解决。 -下面的逻辑即为解析`HBlacklist`注解的过程,解析的结果是一个`BlacklistResource` ```java -public class BlacklistAnnotationParser extends AbstractLimiterAnnotationParser { - @Override - public LimitedResource parseLimiterAnnotation(AnnotationAttributes attributes) { - return new BlacklistResource(getKey(attributes), - getArgumentInjectors(attributes), - getFallback(attributes), - getErrorHandler(attributes), - getLimiter(attributes), - attributes.getString("serviceId") - ); - - } +@Downgrade(grade = FlowGrade.FLOW_GRADE_THREAD, count = 100) +public String get(String name){ + return name; } -``` - -**SETP 4. 添加一个实现** -我们添加一个简单的实现,从Redis中检查该用户是否是该serciceId的该黑名单用户。 - -```java -public class RedisBlacklistLimiter extends BlacklistLimiter { - - String name; - - RedisClient redisClient; - - public RedisBlacklistLimiter(String name, RedisClient redisClient) { - this.name = name; - this.redisClient = redisClient; - } - - @Override - public boolean checkExist(Object userId, String serviceId) { - // 查询redis - // 返回是否存在 - return false; - } - - @Override - public String getLimiterName() { - return name; - } +public String getFallback(String name){ + return "fallback"; } ``` -**STEP 5.使该组件生效** - -***在注解中指定注解解析器的全限定类名,启用该组件*** - -```java -@EnableLimiter(annotationParser = "org.miaixz.bus.limiter.limitertest.extend.BlacklistAnnotationParser") -``` - -## 性能测试 - -### 测试环境 - -- Docker 1.13.1 8核16G -- Redis CGroup 2核4G -- Application CGroup 2核4G - -#### 1. Lock组件测试 - -- 4线程1000连接压测120秒 -- tomcat.max-threads=1000, -- 业务代码执行时间均为1000ms -- Java 17+ -- Zoookeeper和Redis和应用处于同一主机 -- Zookeeper为3节点 - -| | AVG RT | AVG-QPS | -|---------------|-----------|---------| -| None | 1008.38ms | 986.26 | -| JdkLock | 1012.50ms | 984.79 | -| RedisLock | 1034.64ms | 960.39 | -| ZookeeperLock | 1096.42ms | 914.52 | - -#### 2. RateLimiter性能测试 - -- 4线程1000连接压测120秒 -- tomcat.max-threads=1000, -- 业务代码执行时间均为1000ms -- Java 17+ -- Zoookeeper和Redis和应用处于同一主机 - -| | AVG RT | AVG-QPS | -|------------------|-----------|---------| -| None | 1008.38ms | 986.26 | -| jdkRateLimiter | 1008.50ms | 979.16 | -| RedisRatelimiter | 1022.01ms | 976.51 | - -### 未来可能增加的feature - -- 增加配置中心接入,支持动态修改注解配置 -- 增加一些组件类型 +以上注解表示了,当这个方法的同时运行的线程超过100个时,触发降级,降级会自动调用`原方法名+Fallback`方法名(并且参数要一致),当降级触发后会直接返回`fallback`,当线程数小于100时,框架也会自动摘除降级,还是输出`name`。 +如果你的类中没有定义fallback方法,那么触发降级时会报错,当然你可以在降级方法中去抛错,来让上游系统知道你这个方法已经达到了瓶颈。 +### 注意事项 +只针对于Springboot,Spring环境,并且所有标注了`@Hotspot`或者`@Downgrade`的类一定得注册到spring上下文中 \ No newline at end of file diff --git a/bus-limiter/pom.xml b/bus-limiter/pom.xml index 4229ed6992..df04af6890 100755 --- a/bus-limiter/pom.xml +++ b/bus-limiter/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-limiter - 8.0.0 + 8.0.1 jar ${project.artifactId} @@ -43,10 +43,9 @@ UTF-8 21 21 - 3.0.5 - 5.6.0 - 3.17.4 - 33.1.0-jre + 1.18.32 + 1.8.7 + 1.12.23 @@ -56,68 +55,25 @@ ${project.version}
      - com.google.guava - guava - ${guava.version} - true + ${project.groupId} + bus-crypto + ${project.version} - org.redisson - redisson - ${redisson.version} + org.projectlombok + lombok + ${lombok.version} true - - - io.netty - netty-common - - - io.netty - netty-codec - - - io.netty - netty-buffer - - - io.netty - netty-transport - - - io.netty - netty-resolver-dns - - - io.netty - netty-handler - - - org.apache.curator - curator-recipes - ${curator.version} - true - - - log4j - log4j - - - com.google.guava - guava - - - org.slf4j - slf4j-api - - + net.bytebuddy + byte-buddy + ${bytebuddy.version} - org.springframework.boot - spring-boot-starter-web - ${spring.boot.version} - true + com.alibaba.csp + sentinel-parameter-flow-control + ${sentinel.version} diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/factory/ProxyClassCache.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Builder.java old mode 100755 new mode 100644 similarity index 51% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/factory/ProxyClassCache.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/Builder.java index aec0953f08..7d2a77e2ea --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/factory/ProxyClassCache.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Builder.java @@ -23,71 +23,79 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.factory; +package org.miaixz.bus.limiter; import org.miaixz.bus.core.lang.Symbol; -import java.lang.ref.WeakReference; -import java.util.HashMap; +import java.lang.reflect.Method; import java.util.Map; -import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; /** - * 用于存储基于特定类型{@link AbstractProxyClass}的代理的实现类的缓存。 - * 代理类缓存确保每个{@link AbstractProxyClass}/{@link ClassLoader}/代理类数组组合只有一个类 + * 构造信息 * * @author Kimi Liu * @since Java 17+ */ -public class ProxyClassCache { +public class Builder { - private final Map loaderToClassCache = new WeakHashMap(); - private final ProxyClass proxyClassGenerator; + private static final Map MAP = new ConcurrentHashMap<>(); + private static final Object LOCK = new Object(); - public ProxyClassCache(ProxyClass proxyClassGenerator) { - this.proxyClassGenerator = proxyClassGenerator; + public static Class getUserClass(Class clazz) { + if (isCglibProxyClass(clazz)) { + Class superclass = clazz.getSuperclass(); + return getUserClass(superclass); + } + return clazz; } - public synchronized Class getProxyClass(ClassLoader classLoader, Class[] proxyClasses) { - final Map classCache = getClassCache(classLoader); - final String key = toClassCacheKey(proxyClasses); - Class proxyClass; - WeakReference proxyClassReference = (WeakReference) classCache.get(key); - if (null == proxyClassReference) { - proxyClass = proxyClassGenerator.createProxy(classLoader, proxyClasses); - classCache.put(key, new WeakReference(proxyClass)); - } else { - synchronized (proxyClassReference) { - proxyClass = (Class) proxyClassReference.get(); - if (null == proxyClass) { - proxyClass = proxyClassGenerator.createProxy(classLoader, proxyClasses); - classCache.put(key, new WeakReference(proxyClass)); - } - } - } - return proxyClass; + public static boolean isCglibProxyClass(Class clazz) { + return (clazz != null && isCglibProxyClassName(clazz.getName())); } - private Map getClassCache(ClassLoader classLoader) { - Map cache = (Map) loaderToClassCache.get(classLoader); - if (null == cache) { - cache = new HashMap(); - loaderToClassCache.put(classLoader, cache); - } - return cache; + private static boolean isCglibProxyClassName(String className) { + return (className != null && className.contains("$$")); } - private String toClassCacheKey(Class[] proxyClasses) { - final StringBuffer sb = new StringBuffer(); - for (int i = 0; i < proxyClasses.length; i++) { - Class proxyInterface = proxyClasses[i]; - sb.append(proxyInterface.getName()); - if (i != proxyClasses.length - 1) { - sb.append(Symbol.COMMA); + /** + * 解析并解析方法名,然后缓存到map中 + * + * @param method 方法实例 + * @return the string + */ + public static String resolveMethodName(Method method) { + if (method == null) { + throw new IllegalArgumentException("Null method"); + } + String methodName = MAP.get(method); + if (methodName == null) { + synchronized (LOCK) { + methodName = MAP.get(method); + if (methodName == null) { + StringBuilder sb = new StringBuilder(); + + String className = method.getDeclaringClass().getName(); + String name = method.getName(); + Class[] params = method.getParameterTypes(); + sb.append(className).append(Symbol.COLON).append(name); + sb.append(Symbol.PARENTHESE_LEFT); + + int paramPos = 0; + for (Class clazz : params) { + sb.append(clazz.getCanonicalName()); + if (++paramPos < params.length) { + sb.append(Symbol.COMMA); + } + } + sb.append(Symbol.PARENTHESE_RIGHT); + methodName = sb.toString(); + + MAP.put(method, methodName); + } } } - return sb.toString(); + return methodName; } } - diff --git a/bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/StackEntity.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Context.java similarity index 83% rename from bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/StackEntity.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/Context.java index 8e6fc1b9a4..54704fa9cb 100644 --- a/bus-tracer/src/main/java/org/miaixz/bus/tracer/monitor/StackEntity.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Context.java @@ -23,25 +23,37 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.tracer.monitor; +package org.miaixz.bus.limiter; -import lombok.AllArgsConstructor; -import lombok.Data; +import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.Setter; +import org.miaixz.bus.core.lang.Normal; /** + * 上下文配置类 + * * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @NoArgsConstructor -@AllArgsConstructor -public class StackEntity { +public class Context { - private String id; - private int total; - private int runnable; - private int timed_waiting; - private int waiting; + /** + * 热点缓存默认时长 + */ + private int seconds = 60; + + /** + * 是否启动日志 + */ + private boolean logger = true; + + /** + * 用户标识提供者全限定类名 + */ + private String supplier = Normal.EMPTY; } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Handler.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Handler.java deleted file mode 100755 index 99eb92994d..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Handler.java +++ /dev/null @@ -1,49 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter; - - -import org.miaixz.bus.limiter.execute.LimiterExecutionContext; - -/** - * 当limiter由于其他原因不能正常工作(如Redis宕机) - * 该接口将会被调用,如果你不希望这些异常影响接口提供服务 - * return true,这样将会跳过该limiter,实际上,更好的 - * limiter 降级策略应该由limiter本身实现,这里只是一个简单的替代方案 - * - * @author Kimi Liu - * @since Java 17+ - */ -public interface Handler { - - /** - * @param throwable 异常 - * @param executionContext 上下文 - * @return true/false - */ - boolean resolve(Throwable throwable, LimiterExecutionContext executionContext); - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Resolver.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Holder.java old mode 100755 new mode 100644 similarity index 90% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/Resolver.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/Holder.java index 6797ebe2d7..ce8c852965 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Resolver.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Holder.java @@ -25,16 +25,22 @@ ********************************************************************************/ package org.miaixz.bus.limiter; -import org.miaixz.bus.limiter.resource.LimitedResource; - -import java.lang.reflect.Method; - /** + * 全局上下文 + * * @author Kimi Liu * @since Java 17+ */ -public interface Resolver { +public class Holder { + + private static Context context; + + public static void set(Context context) { + Holder.context = context; + } - T resolve(Method method, Class clazz, Object[] args, LimitedResource limitedResource, Object target); + public static Context load() { + return context; + } } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Parser.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Provider.java old mode 100755 new mode 100644 similarity index 83% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/Parser.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/Provider.java index 7cc2e8fb81..865205fc80 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Parser.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Provider.java @@ -25,19 +25,31 @@ ********************************************************************************/ package org.miaixz.bus.limiter; -import org.miaixz.bus.limiter.resource.LimitedResource; -import org.springframework.core.annotation.AnnotationAttributes; +import org.miaixz.bus.limiter.magic.StrategyMode; -import java.lang.annotation.Annotation; +import java.lang.reflect.Method; /** + * 执行规则 + * * @author Kimi Liu * @since Java 17+ */ -public interface Parser { +public interface Provider { - Class getSupportAnnotation(); + /** + * 获取规则 + * + * @return the strategy + */ + StrategyMode get(); - LimitedResource parseLimiterAnnotation(AnnotationAttributes attributes); + /** + * @param bean 对象信息 + * @param method 执行方法 + * @param args 执行参数 + * @return the object + */ + Object process(Object bean, Method method, Object[] args); } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Registry.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Registry.java new file mode 100644 index 0000000000..51ed28a7b5 --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Registry.java @@ -0,0 +1,104 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.limiter; + +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager; +import org.miaixz.bus.core.xyz.ListKit; +import org.miaixz.bus.limiter.magic.annotation.Downgrade; +import org.miaixz.bus.limiter.magic.annotation.Hotspot; +import org.miaixz.bus.limiter.magic.annotation.Limiting; +import org.miaixz.bus.limiter.metric.ResourceManager; +import org.miaixz.bus.logger.Logger; + +/** + * 管控规则 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Registry { + + /** + * 请求降级 + * + * @param downgrade 降级注解 + * @param resourceKey 资源标识 + */ + public static void register(Downgrade downgrade, String resourceKey) { + + if (!FlowRuleManager.hasConfig(resourceKey)) { + FlowRule rule = new FlowRule(); + + rule.setResource(resourceKey); + rule.setGrade(downgrade.grade().getGrade()); + rule.setCount(downgrade.count()); + rule.setLimitApp("default"); + + FlowRuleManager.loadRules(ListKit.of(rule)); + Logger.info("Add Fallback Rule [{}]", resourceKey); + } + } + + /** + * 提升热点 + * + * @param hotspot 热点注解 + * @param resourceKey 资源标识 + */ + public static void register(Hotspot hotspot, String resourceKey) { + // 仅在未配置时进行注册 + if (!ParamFlowRuleManager.hasRules(resourceKey)) { + // 设置规则(base sentinel) + ParamFlowRule rule = new ParamFlowRule(); + + rule.setResource(resourceKey); + rule.setGrade(hotspot.grade().getGrade()); + rule.setCount(hotspot.count()); + rule.setDurationInSec(hotspot.duration()); + rule.setParamIdx(0); + + ParamFlowRuleManager.loadRules(ListKit.of(rule)); + Logger.info("Add Hot Rule [{}]", rule.getResource()); + } + } + + /** + * 请求限流 + * + * @param limiting 限流注解 + * @param resourceKey 资源标识 + */ + public static void register(Limiting limiting, String resourceKey) { + if (!ResourceManager.contain(resourceKey)) { + ResourceManager.add(resourceKey); + Logger.info("Add Request Limit [{}]", resourceKey); + } + } + +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Sentinel.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Sentinel.java new file mode 100644 index 0000000000..535e193c89 --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Sentinel.java @@ -0,0 +1,107 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.limiter; + +import com.alibaba.csp.sentinel.Entry; +import com.alibaba.csp.sentinel.EntryType; +import com.alibaba.csp.sentinel.SphO; +import com.alibaba.csp.sentinel.SphU; +import com.alibaba.csp.sentinel.slots.block.BlockException; +import org.miaixz.bus.core.lang.exception.InternalException; +import org.miaixz.bus.core.xyz.MethodKit; +import org.miaixz.bus.crypto.Builder; +import org.miaixz.bus.extra.json.JsonKit; +import org.miaixz.bus.limiter.magic.StrategyMode; +import org.miaixz.bus.limiter.metric.StrategyManager; +import org.miaixz.bus.logger.Logger; + +import java.lang.reflect.Method; + +/** + * 管控执行 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class Sentinel { + + /** + * 执行对应方法及相关规则 + * + * @param bean 对象信息 + * @param method 执行方法 + * @param args 参数 + * @param name 方法名称 + * @param strategyMode 规则 + * @return the object + */ + public static Object process(Object bean, Method method, Object[] args, String name, StrategyMode strategyMode) { + // 进行各种策略的处理 + switch (strategyMode) { + case FALLBACK: + // 允许进入则直接调用 + if (SphO.entry(name)) { + try { + return MethodKit.invoke(bean, method, args); + } finally { + SphO.exit(); + } + } else { + if (Holder.load().isLogger()) { + Logger.info("Trigger fallback strategy for [{}], args: [{}]", name, JsonKit.toJsonString(args)); + } + // 进行回调fallback方法 + return StrategyManager.get(strategyMode).process(bean, method, args); + } + case HOT_METHOD: + // 参数转换 + String convertParam = Builder.md5Hex(JsonKit.toJsonString(args)); + Entry entry = null; + try { + // 判断是否进行限流 + entry = SphU.entry(name, EntryType.IN, 1, convertParam); + return MethodKit.invoke(bean, method, args); + } catch (BlockException e) { + if (Holder.load().isLogger()) { + Logger.info(" Trigger hotspot strategy for [{}], args: [{}]", name, JsonKit.toJsonString(args)); + } + return StrategyManager.get(strategyMode).process(bean, method, args); + } finally { + if (entry != null) { + entry.exit(1, convertParam); + } + } + case REQUEST_LIMIT: + if (Holder.load().isLogger()) { + Logger.info("Trigger requestLimit strategy for [{}], args: [{}]", name, JsonKit.toJsonString(args)); + } + return StrategyManager.get(strategyMode).process(bean, method, args); + default: + throw new InternalException("Strategy error!"); + } + } + +} diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/Invocation.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Supplier.java old mode 100755 new mode 100644 similarity index 81% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/Invocation.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/Supplier.java index 386ce9dd94..40b9abe678 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/Invocation.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/Supplier.java @@ -23,45 +23,36 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy; +package org.miaixz.bus.limiter; +import java.io.Serializable; import java.lang.reflect.Method; /** - * 调用者方法 + * 标识提供者 * * @author Kimi Liu * @since Java 17+ */ -public interface Invocation { +public abstract class Supplier { /** - * 获取目标实例 + * 获取当前用户标识 * - * @return 目标实例 + * @return 用户表示 */ - Object getProxy(); + public abstract Serializable get(); /** - * 获取方法 + * 拦截请求的结果 * - * @return Method + * @param bean 对象信息 + * @param method 执行方法 + * @param args 参数 + * @return the serializable */ - Method getMethod(); - - /** - * 获取参数值 - * - * @return 参数 - */ - Object[] getArguments(); - - /** - * 执行方法 - * - * @return 执行结果 - * @throws Throwable Throwable - */ - Object proceed() throws Throwable; + public Serializable intercept(Object bean, Method method, Object[] args) { + return "Your request is frequent. Please wait..."; + } } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/Lock.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/Lock.java deleted file mode 100755 index b0592cdf1d..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/Lock.java +++ /dev/null @@ -1,53 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.annotation; - -import org.miaixz.bus.core.lang.Normal; - -import java.lang.annotation.*; - -/** - * 锁 - * - * @author Kimi Liu - * @since Java 17+ - */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Repeatable(Locks.class) -public @interface Lock { - - String limiter() default Normal.EMPTY; - - String key() default Normal.EMPTY; - - String fallback() default "defaultFallbackResolver"; - - String errorHandler() default "defaultErrorHandler"; - - String[] argumentInjectors() default {}; - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/execute/LimiterExecutionContext.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/execute/LimiterExecutionContext.java deleted file mode 100755 index 45631da619..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/execute/LimiterExecutionContext.java +++ /dev/null @@ -1,183 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.execute; - -import org.miaixz.bus.core.lang.Assert; -import org.miaixz.bus.core.lang.Symbol; -import org.miaixz.bus.core.xyz.ArrayKit; -import org.miaixz.bus.core.xyz.CollKit; -import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.limiter.Injector; -import org.miaixz.bus.limiter.expression.LimiterOperationExpressionEvaluator; -import org.miaixz.bus.limiter.metadata.LimitedResourceMetadata; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.context.expression.AnnotatedElementKey; -import org.springframework.expression.EvaluationContext; - -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -/** - * limiter 上下文信息 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class LimiterExecutionContext { - - private static final HashMap emptyMap = new HashMap<>(); - - private LimitedResourceMetadata metadata; - - private Object[] args; - - private Object target; - - private Map injectArgs; - - private LimiterOperationExpressionEvaluator evaluator; - - private BeanFactory beanFactory; - - private Object key; - - private Object fallbackResult; - - private Throwable throwable; - - public LimiterExecutionContext(LimitedResourceMetadata metadata, Object[] args, Object target, BeanFactory beanFactory) { - this.metadata = metadata; - this.args = extractArgs(metadata.getTargetMethod(), args); - this.target = target; - this.injectArgs = generateInjectArgs(); - this.beanFactory = beanFactory; - this.evaluator = new LimiterOperationExpressionEvaluator(); - this.key = generateKey(); - } - - public static HashMap getEmptyMap() { - return emptyMap; - } - - public Throwable getThrowable() { - return throwable; - } - - public boolean limit() { - boolean ret; - try { - ret = this.metadata.getLimiter().limit(this.key, this.metadata.getLimiterParameters()); - } catch (Throwable throwable) { - this.throwable = throwable; - ret = this.metadata.getErrorHandler().resolve(throwable, this); - } - - if (!ret) { - this.fallbackResult = this.metadata.getFallback().resolve(this.metadata.getTargetMethod(), this.metadata.getTargetClass(), this.args, this.metadata.getLimitedResource(), this.target); - } - return ret; - } - - public void release() { - this.metadata.getLimiter().release(this.key, this.metadata.getLimiterParameters()); - } - - public Object getFallbackResult() { - return fallbackResult; - } - - private Object[] extractArgs(Method method, Object[] args) { - if (!method.isVarArgs()) { - return args; - } else { - Object[] varArgs = ArrayKit.ofArray(args[args.length - 1]); - Object[] combinedArgs = new Object[args.length - 1 + varArgs.length]; - System.arraycopy(args, 0, combinedArgs, 0, args.length - 1); - System.arraycopy(varArgs, 0, combinedArgs, args.length - 1, varArgs.length); - return combinedArgs; - } - } - - private Object generateKey() { - if (StringKit.hasText(this.metadata.getLimitedResource().getKey())) { - EvaluationContext evaluationContext = evaluator.createEvaluationContext(this.metadata.getLimiter(), this.metadata.getTargetMethod(), this.args, - this.target, this.metadata.getTargetClass(), this.metadata.getTargetMethod(), injectArgs, beanFactory); - Object evalKey = evaluator.key(this.metadata.getLimitedResource().getKey(), new AnnotatedElementKey(this.metadata.getTargetMethod(), this.metadata.getTargetClass()), evaluationContext); - Assert.notNull(evalKey, "key值计算为null!"); - return evalKey; - } - return this.metadata.getTargetClass().getName() + Symbol.SHAPE + - this.metadata.getTargetMethod().getName(); - - } - - private Map generateInjectArgs() { - - if (CollKit.isEmpty(this.metadata.getArgumentInjectors())) { - return emptyMap; - } - Map retVal = new HashMap<>(); - Collection argumentInjectors = this.metadata.getArgumentInjectors(); - for (Injector argumentInjector : argumentInjectors) { - Map tempMap = argumentInjector.inject(this.args); - if (!tempMap.isEmpty()) { - retVal.putAll(tempMap); - } - } - return retVal; - } - - public LimitedResourceMetadata getMetadata() { - return metadata; - } - - public Object[] getArgs() { - return args; - } - - public Object getTarget() { - return target; - } - - public Map getInjectArgs() { - return injectArgs; - } - - public LimiterOperationExpressionEvaluator getEvaluator() { - return evaluator; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public Object getKey() { - return key; - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/expression/LimiterOperationExpressionEvaluator.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/expression/LimiterOperationExpressionEvaluator.java deleted file mode 100755 index 4111cdf056..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/expression/LimiterOperationExpressionEvaluator.java +++ /dev/null @@ -1,136 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.expression; - -import org.miaixz.bus.core.lang.Symbol; -import org.miaixz.bus.core.xyz.ObjectKit; -import org.miaixz.bus.limiter.Limiter; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.context.expression.AnnotatedElementKey; -import org.springframework.context.expression.BeanFactoryResolver; -import org.springframework.context.expression.MethodBasedEvaluationContext; -import org.springframework.core.DefaultParameterNameDiscoverer; -import org.springframework.core.ParameterNameDiscoverer; -import org.springframework.expression.EvaluationContext; -import org.springframework.expression.Expression; -import org.springframework.expression.spel.standard.SpelExpressionParser; - -import java.lang.reflect.Method; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class LimiterOperationExpressionEvaluator { - - private final SpelExpressionParser parser = new SpelExpressionParser(); - - private final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); - - - private final Map keyCache = new ConcurrentHashMap<>(64); - - - public EvaluationContext createEvaluationContext(Limiter limiter, Method method, Object[] args, Object target, Class targetClass, Method targetMethod, - Map injectArgs, BeanFactory beanFactory) { - - LimiterExpressionRootObject rootObject = new LimiterExpressionRootObject(limiter, method, args, target, targetClass); - MethodBasedEvaluationContext evaluationContext = new MethodBasedEvaluationContext(rootObject, targetMethod, args, this.parameterNameDiscoverer); - for (String key : injectArgs.keySet()) { - evaluationContext.setVariable(key, injectArgs.get(key)); - } - - if (null != beanFactory) { - evaluationContext.setBeanResolver(new BeanFactoryResolver(beanFactory)); - } - return evaluationContext; - } - - public Object key(String keyExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) { - return getExpression(methodKey, keyExpression).getValue(evalContext); - } - - protected Expression getExpression(AnnotatedElementKey elementKey, String expression) { - - ExpressionKey expressionKey = new ExpressionKey(elementKey, expression); - Expression expr = keyCache.get(expressionKey); - if (null == expr) { - expr = this.parser.parseExpression(expression); - keyCache.put(expressionKey, expr); - } - return expr; - } - - - protected static class ExpressionKey implements Comparable { - - private final AnnotatedElementKey element; - - private final String expression; - - protected ExpressionKey(AnnotatedElementKey element, String expression) { - - this.element = element; - this.expression = expression; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof ExpressionKey)) { - return false; - } - ExpressionKey otherKey = (ExpressionKey) other; - return (this.element.equals(otherKey.element) && - ObjectKit.nullSafeEquals(this.expression, otherKey.expression)); - } - - @Override - public int hashCode() { - return this.element.hashCode() * 29 + this.expression.hashCode(); - } - - @Override - public String toString() { - return this.element + " with expression \"" + this.expression + Symbol.DOUBLE_QUOTES; - } - - @Override - public int compareTo(ExpressionKey other) { - int result = this.element.toString().compareTo(other.element.toString()); - if (result == 0) { - result = this.expression.compareTo(other.expression); - } - return result; - } - } - - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/LimitedResourceSourcePointcut.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/LimitedResourceSourcePointcut.java deleted file mode 100755 index 6ba7efe57e..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/LimitedResourceSourcePointcut.java +++ /dev/null @@ -1,77 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.intercept; - -import org.miaixz.bus.core.xyz.CollKit; -import org.miaixz.bus.core.xyz.ObjectKit; -import org.miaixz.bus.limiter.resource.LimitedResourceSource; -import org.springframework.aop.support.StaticMethodMatcherPointcut; - -import java.io.Serializable; -import java.lang.reflect.Method; - -/** - * 切点抽象定义 - * - * @author Kimi Liu - * @since Java 17+ - */ -abstract class LimitedResourceSourcePointcut extends StaticMethodMatcherPointcut implements Serializable { - - public LimitedResourceSourcePointcut() { - } - - @Override - public boolean matches(Method method, Class aClass) { - LimitedResourceSource limitedResourceSource = this.getLimitedResourceSource(); - boolean matched = null != limitedResourceSource && !CollKit.isEmpty(limitedResourceSource.getLimitedResource(aClass, method)); - if (matched == true) { - return matched; - } - return matched; - } - - public boolean equals(Object other) { - if (this == other) { - return true; - } else if (!(other instanceof LimitedResourceSourcePointcut)) { - return false; - } else { - LimitedResourceSourcePointcut otherPc = (LimitedResourceSourcePointcut) other; - return ObjectKit.nullSafeEquals(this.getLimitedResourceSource(), otherPc.getLimitedResourceSource()); - } - } - - public int hashCode() { - return LimitedResourceSourcePointcut.class.hashCode(); - } - - public String toString() { - return this.getClass().getName() + ": " + this.getLimitedResourceSource(); - } - - protected abstract LimitedResourceSource getLimitedResourceSource(); -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/LimiterAspectSupport.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/LimiterAspectSupport.java deleted file mode 100755 index 68d9dc3ae2..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/LimiterAspectSupport.java +++ /dev/null @@ -1,160 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.intercept; - -import org.aopalliance.intercept.MethodInvocation; -import org.miaixz.bus.core.xyz.CollKit; -import org.miaixz.bus.limiter.execute.LimitContextsValueWrapper; -import org.miaixz.bus.limiter.execute.LimiterExecutionContext; -import org.miaixz.bus.limiter.metadata.LimitedResourceMetadata; -import org.miaixz.bus.limiter.metadata.LimitedResourceMetadataCache; -import org.miaixz.bus.limiter.resource.LimitedResource; -import org.miaixz.bus.limiter.resource.LimitedResourceSource; -import org.springframework.aop.framework.AopProxyUtils; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.SmartInitializingSingleton; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; - -/** - * 实际的advisor - * 使用beanfactory的一些基础设施 - * - * @author Kimi Liu - * @since Java 17+ - */ -public abstract class LimiterAspectSupport implements BeanFactoryAware, InitializingBean, SmartInitializingSingleton { - - private BeanFactory beanFactory; - - private boolean initialized = false; - - private LimitedResourceSource limitedResourceSource; - - private LimitedResourceMetadataCache limitedResourceMetadataCache; - - /** - * 执行 - * - * @param invocation 反射 - * @param target 目标 - * @param method 方法 - * @param args 参数 - * @return the object - * @throws Throwable 异常 - */ - protected Object execute(final MethodInvocation invocation, Object target, Method method, Object[] args) throws Throwable { - - if (this.initialized) { - Class targetClass = AopProxyUtils.ultimateTargetClass(target); - LimitedResourceSource limitedResourceSource = getLimitedResourceSource(); - if (null != limitedResourceSource) { - Collection limitedResources = limitedResourceSource.getLimitedResource(targetClass, method); - if (!CollKit.isEmpty(limitedResources)) { - Collection contexts = getLimiterOperationContexts(limitedResources, method, args, target, targetClass); - LimitContextsValueWrapper limitContextsValueWrapper = limitContexts(contexts); - if (limitContextsValueWrapper.value()) { - try { - return invocation.proceed(); - } catch (Throwable e) { - throw e; - } finally { - releaseContexts(contexts); - } - } else { - return limitContextsValueWrapper.getLimiterFailResolveResult(); - } - - } - } - } - return invocation.proceed(); - } - - @Override - public void afterSingletonsInstantiated() { - this.initialized = true; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - this.limitedResourceMetadataCache = new LimitedResourceMetadataCache(beanFactory); - } - - protected LimitContextsValueWrapper limitContexts(Collection contexts) { - Collection limited = new ArrayList<>(); - for (LimiterExecutionContext context : contexts) { - if (context.limit() && null == context.getThrowable()) { - limited.add(context); - } else { - releaseContexts(limited); - Object result = context.getFallbackResult(); - return new LimitContextsValueWrapper(false, result); - } - - } - return new LimitContextsValueWrapper(true, null); - } - - protected void releaseContexts(Collection contexts) { - if (null != contexts && !contexts.isEmpty()) { - for (LimiterExecutionContext context : contexts) { - context.release(); - } - } - } - - - protected Collection getLimiterOperationContexts(Collection limitedResources, Method method, Object[] args, Object target, Class targetClass) { - Collection retVal = new ArrayList<>(); - for (LimitedResource limitedResource : limitedResources) { - LimitedResourceMetadata metadata = limitedResourceMetadataCache.getLimitedResourceMetadata(limitedResource, method, targetClass); - retVal.add(new LimiterExecutionContext(metadata, args, target, this.beanFactory)); - } - return retVal; - } - - - public LimitedResourceSource getLimitedResourceSource() { - return limitedResourceSource; - } - - public void setLimitedResourceSource(LimitedResourceSource limitedResourceSource) { - this.limitedResourceSource = limitedResourceSource; - } - - @Override - public void afterPropertiesSet() { - - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/LimiterInterceptor.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/LimiterInterceptor.java deleted file mode 100755 index 92c31b4656..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/intercept/LimiterInterceptor.java +++ /dev/null @@ -1,46 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.intercept; - -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; - -import java.io.Serializable; -import java.lang.reflect.Method; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class LimiterInterceptor extends LimiterAspectSupport implements MethodInterceptor, Serializable { - - @Override - public Object invoke(MethodInvocation methodInvocation) throws Throwable { - Method method = methodInvocation.getMethod(); - return execute(methodInvocation, methodInvocation.getThis(), method, methodInvocation.getArguments()); - } - -} diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/AlwaysProvider.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/FlowGrade.java old mode 100755 new mode 100644 similarity index 84% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/AlwaysProvider.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/FlowGrade.java index 426602b7ef..63a8b7f8e7 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/provider/AlwaysProvider.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/FlowGrade.java @@ -23,27 +23,37 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.provider; - -import org.miaixz.bus.proxy.Provider; +package org.miaixz.bus.limiter.magic; /** - * 总是返回相同的对象 + * 流量等级 * * @author Kimi Liu * @since Java 17+ */ -public class AlwaysProvider implements Provider { +public enum FlowGrade { + + /** + * 流量线程 + */ + FLOW_GRADE_THREAD(0), + /** + * 流量QPS + */ + FLOW_GRADE_QPS(1); - private final Object constant; + private int grade; - public AlwaysProvider(Object constant) { - this.constant = constant; + FlowGrade(int grade) { + this.grade = grade; } - public Object getObject() { - return constant; + public int getGrade() { + return grade; } -} + public void setGrade(int grade) { + this.grade = grade; + } +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Injector.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/StrategyMode.java old mode 100755 new mode 100644 similarity index 94% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/Injector.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/StrategyMode.java index a6a9740984..b8fd1f5e82 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/Injector.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/StrategyMode.java @@ -23,16 +23,17 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter; - -import java.util.Map; +package org.miaixz.bus.limiter.magic; /** + * 规则模式 + * * @author Kimi Liu * @since Java 17+ */ -public interface Injector { - - Map inject(Object... args); +public enum StrategyMode { + FALLBACK, + HOT_METHOD, + REQUEST_LIMIT } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/LimiterParameter.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/Downgrade.java old mode 100755 new mode 100644 similarity index 88% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/LimiterParameter.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/Downgrade.java index d0a40b1ee4..a30353d944 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/LimiterParameter.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/Downgrade.java @@ -23,21 +23,25 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.annotation; +package org.miaixz.bus.limiter.magic.annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import org.miaixz.bus.limiter.magic.FlowGrade; + +import java.lang.annotation.*; /** - * 限流参数 + * 降级服务请求 * * @author Kimi Liu * @since Java 17+ */ -@Target(ElementType.FIELD) +@Inherited +@Documented +@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) -public @interface LimiterParameter { +public @interface Downgrade { + + FlowGrade grade(); + int count(); } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/Locks.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/Hotspot.java old mode 100755 new mode 100644 similarity index 87% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/Locks.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/Hotspot.java index 3ab3eb41c3..44349c398f --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/annotation/Locks.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/Hotspot.java @@ -23,23 +23,28 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.annotation; +package org.miaixz.bus.limiter.magic.annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import org.miaixz.bus.limiter.magic.FlowGrade; + +import java.lang.annotation.*; /** - * 锁 + * 提升热点请求 * * @author Kimi Liu * @since Java 17+ */ -@Target({ElementType.METHOD, ElementType.TYPE}) +@Inherited +@Documented +@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) -public @interface Locks { +public @interface Hotspot { + + FlowGrade grade(); + + int count(); - Lock[] value(); + int duration(); } diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/MethodFilter.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/Limiting.java old mode 100755 new mode 100644 similarity index 89% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/MethodFilter.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/Limiting.java index a87bc5ae84..9c8bf87760 --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/intercept/MethodFilter.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/Limiting.java @@ -23,19 +23,24 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.intercept; +package org.miaixz.bus.limiter.magic.annotation; -import java.lang.reflect.Method; +import java.lang.annotation.*; /** - * 一个MethodFilter决定一个方法是否被接受 + * 限制请求数量 * * @author Kimi Liu * @since Java 17+ */ -public interface MethodFilter { +@Inherited +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Limiting { - boolean accepts(Method method); + int count(); -} + int duration(); +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/package-info.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/package-info.java new file mode 100644 index 0000000000..e71a799f48 --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/annotation/package-info.java @@ -0,0 +1,7 @@ +/** + * 流量注解 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.limiter.magic.annotation; \ No newline at end of file diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/package-info.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/package-info.java new file mode 100644 index 0000000000..341466b05b --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/magic/package-info.java @@ -0,0 +1,7 @@ +/** + * 流量管控 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.limiter.magic; \ No newline at end of file diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/AbstractLimitedResourceMetadata.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/AbstractLimitedResourceMetadata.java deleted file mode 100755 index aecb5e215b..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/AbstractLimitedResourceMetadata.java +++ /dev/null @@ -1,179 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.metadata; - -import org.miaixz.bus.core.xyz.AnnoKit; -import org.miaixz.bus.core.xyz.CollKit; -import org.miaixz.bus.limiter.Handler; -import org.miaixz.bus.limiter.Injector; -import org.miaixz.bus.limiter.Limiter; -import org.miaixz.bus.limiter.Resolver; -import org.miaixz.bus.limiter.annotation.LimiterParameter; -import org.miaixz.bus.limiter.resource.LimitedResource; -import org.springframework.beans.factory.BeanFactory; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.*; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public abstract class AbstractLimitedResourceMetadata implements LimitedResourceMetadata, Observer { - - private final BeanFactory beanFactory; - - private final T limitedResource; - - private Limiter limiter; - - private Handler errorHandler; - - private Resolver limitedFallbackResolver; - - private Collection argumentInjectors; - - private Map limiterParameters; - - private Class targetClass; - - private Method targetMethod; - - - public AbstractLimitedResourceMetadata(T limitedResource, Class targetClass, Method targetMethod, BeanFactory beanFactory) { - this.limitedResource = limitedResource; - this.beanFactory = beanFactory; - this.targetClass = targetClass; - this.targetMethod = targetMethod; - parse(limitedResource); - } - - protected abstract void parseInternal(T limitedResource); - - private void parse(T limitedResource) { - this.limiter = (Limiter) this.beanFactory.getBean(limitedResource.getLimiter()); - this.errorHandler = (Handler) this.beanFactory.getBean(limitedResource.getErrorHandler()); - // 优先获取本类中的同名方法 而后从BeanFactory中获取 - try { - final Method fallbackMethod = this.targetClass.getDeclaredMethod(limitedResource.getFallback(), this.targetMethod.getParameterTypes()); - fallbackMethod.setAccessible(true); - this.limitedFallbackResolver = (method, clazz, args, limitedResource1, target) -> { - try { - return fallbackMethod.invoke(target, args); - } catch (IllegalAccessException e) { - return null; - } catch (InvocationTargetException e) { - return null; - } - }; - } catch (NoSuchMethodException e) { - this.limitedFallbackResolver = (Resolver) this.beanFactory.getBean(limitedResource.getFallback()); - } - - if (!CollKit.isEmpty(limitedResource.getArgumentInjectors())) { - argumentInjectors = new ArrayList<>(); - Collection injectors = limitedResource.getArgumentInjectors(); - for (String si : injectors) { - argumentInjectors.add((Injector) this.beanFactory.getBean(si)); - } - } - this.limiterParameters = findLimiterParameters(); - this.parseInternal(limitedResource); - if (limitedResource instanceof Observable) { - ((Observable) limitedResource).addObserver(this); - } - - } - - private Map findLimiterParameters() { - // 获取所有LimiterParameter标记的字段 - Field[] fields = this.getLimitedResource().getClass().getDeclaredFields(); - Map retVal = null; - for (int i = 0; i < fields.length; i++) { - Field field = fields[i]; - field.setAccessible(true); - if (AnnoKit.hasAnnotation(field, LimiterParameter.class)) { - if (null == retVal) { - retVal = new HashMap<>(); - } - try { - retVal.put(field.getName(), field.get(this.getLimitedResource())); - } catch (IllegalAccessException e) { - } - } - } - return retVal; - } - - @Override - public Map getLimiterParameters() { - return limiterParameters; - } - - @Override - public T getLimitedResource() { - return this.limitedResource; - } - - @Override - public void update(Observable o, Object arg) { - parse(this.limitedResource); - } - - - @Override - public Limiter getLimiter() { - return limiter; - } - - @Override - public Resolver getFallback() { - return limitedFallbackResolver; - } - - @Override - public Handler getErrorHandler() { - return errorHandler; - } - - @Override - public Collection getArgumentInjectors() { - return argumentInjectors; - } - - - @Override - public Class getTargetClass() { - return targetClass; - } - - @Override - public Method getTargetMethod() { - return targetMethod; - } -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/LimitedResourceKey.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/LimitedResourceKey.java deleted file mode 100755 index 52575288f3..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/LimitedResourceKey.java +++ /dev/null @@ -1,79 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.metadata; - -import org.miaixz.bus.limiter.resource.LimitedResource; -import org.springframework.context.expression.AnnotatedElementKey; - -import java.lang.reflect.Method; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class LimitedResourceKey implements Comparable { - - private final LimitedResource limitedResource; - private final AnnotatedElementKey methodCacheKey; - - public LimitedResourceKey(LimitedResource limitedResource, Method method, Class targetClass) { - this.limitedResource = limitedResource; - this.methodCacheKey = new AnnotatedElementKey(method, targetClass); - } - - public LimitedResource getLimitedResource() { - return limitedResource; - } - - public AnnotatedElementKey getMethodCacheKey() { - return methodCacheKey; - } - - public boolean equals(Object other) { - if (this == other) { - return true; - } else if (!(other instanceof LimitedResourceKey)) { - return false; - } else { - LimitedResourceKey otherKey = (LimitedResourceKey) other; - return this.limitedResource.equals(otherKey.limitedResource) && this.methodCacheKey.equals(otherKey.methodCacheKey); - } - } - - public int hashCode() { - return this.limitedResource.hashCode() * 31 + this.methodCacheKey.hashCode(); - } - - public String toString() { - return this.limitedResource + " on " + this.methodCacheKey; - } - - @Override - public int compareTo(LimitedResourceKey o) { - return 0; - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/LimitedResourceMetadata.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/LimitedResourceMetadata.java deleted file mode 100755 index 48512b4ff1..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/LimitedResourceMetadata.java +++ /dev/null @@ -1,60 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.metadata; - -import org.miaixz.bus.limiter.Handler; -import org.miaixz.bus.limiter.Injector; -import org.miaixz.bus.limiter.Limiter; -import org.miaixz.bus.limiter.Resolver; -import org.miaixz.bus.limiter.resource.LimitedResource; - -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.Map; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public interface LimitedResourceMetadata { - - Class getTargetClass(); - - Method getTargetMethod(); - - T getLimitedResource(); - - Limiter getLimiter(); - - Handler getErrorHandler(); - - Resolver getFallback(); - - Collection getArgumentInjectors(); - - Map getLimiterParameters(); - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/LimitedResourceMetadataCache.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/FallbackProvider.java old mode 100755 new mode 100644 similarity index 63% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/LimitedResourceMetadataCache.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/FallbackProvider.java index a1bb20952e..dddfcb5c91 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metadata/LimitedResourceMetadataCache.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/FallbackProvider.java @@ -23,38 +23,52 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.metadata; +package org.miaixz.bus.limiter.metric; -import org.miaixz.bus.core.lang.Normal; -import org.miaixz.bus.limiter.resource.LimitedResource; -import org.springframework.beans.factory.BeanFactory; +import org.miaixz.bus.core.xyz.MethodKit; +import org.miaixz.bus.core.xyz.ObjectKit; +import org.miaixz.bus.core.xyz.StringKit; +import org.miaixz.bus.limiter.Provider; +import org.miaixz.bus.limiter.magic.StrategyMode; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** + * FALLBACK 模式处理 + * * @author Kimi Liu * @since Java 17+ */ -public class LimitedResourceMetadataCache { +public class FallbackProvider implements Provider { - private final Map metadataCache = new ConcurrentHashMap<>(Normal._1024); + private final Map map = new ConcurrentHashMap<>(); - private BeanFactory beanFactory; - - public LimitedResourceMetadataCache(BeanFactory beanFactory) { - this.beanFactory = beanFactory; + @Override + public StrategyMode get() { + return StrategyMode.FALLBACK; } - public LimitedResourceMetadata getLimitedResourceMetadata(LimitedResource limitedResource, Method method, Class targetClass) { - LimitedResourceKey limitedResourceKey = new LimitedResourceKey(limitedResource, method, targetClass); - LimitedResourceMetadata metadata = this.metadataCache.get(limitedResourceKey); - if (null == metadata) { - metadata = limitedResource.createMetadata(this.beanFactory, targetClass, method); - this.metadataCache.put(limitedResourceKey, metadata); + @Override + public Object process(Object bean, Method method, Object[] args) { + // 合成方法名称 + String fallbackMethodName = StringKit.format("{}Fallback", method.getName()); + + Method fallbackMethod; + // 缓存操作 + if (map.containsKey(fallbackMethodName)) { + fallbackMethod = map.get(fallbackMethodName); + } else { + fallbackMethod = MethodKit.getMethod(bean.getClass(), fallbackMethodName, method.getParameterTypes()); + map.put(fallbackMethodName, fallbackMethod); } - return metadata; + + if (ObjectKit.isNull(fallbackMethod)) { + throw new RuntimeException(StringKit.format("Can't find fallback method [{}] in bean [{}]", fallbackMethodName, bean.getClass().getName())); + } + + return MethodKit.invoke(bean, fallbackMethod, args); } } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiter.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/MethodManager.java old mode 100755 new mode 100644 similarity index 73% rename from bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiter.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/MethodManager.java index c695a8321e..996615ef20 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiter.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/MethodManager.java @@ -23,29 +23,37 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.limiter.support.rate; +package org.miaixz.bus.limiter.metric; -import org.miaixz.bus.limiter.Limiter; +import org.miaixz.bus.core.lang.tuple.Pair; +import org.miaixz.bus.limiter.magic.StrategyMode; +import org.miaixz.bus.logger.Logger; +import java.lang.annotation.Annotation; +import java.util.HashMap; import java.util.Map; /** + * 处理模式管理 + * * @author Kimi Liu * @since Java 17+ */ -public abstract class RateLimiter implements Limiter { +public class MethodManager { - public abstract boolean acquire(Object key, double rate, long capacity); + private static final Map> map = new HashMap<>(); - @Override - public boolean limit(Object key, Map args) { - double pps = (double) args.get("rate"); - long capacity = (long) args.get("capacity"); - return acquire(key, pps, capacity); + public static void addMethod(String name, Pair pair) { + Logger.info("Register method:[{}][{}]", pair.getLeft().name(), name); + map.put(name, pair); } - @Override - public void release(Object key, Map args) { + public static Pair getAnnoInfo(String name) { + return map.get(name); + } + + public static boolean contain(String name) { + return map.containsKey(name); } } diff --git a/bus-proxy/src/main/java/org/miaixz/bus/proxy/invoker/NullInvoker.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/MethodProvider.java old mode 100755 new mode 100644 similarity index 62% rename from bus-proxy/src/main/java/org/miaixz/bus/proxy/invoker/NullInvoker.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/MethodProvider.java index d5b3fdb06c..67a969ba8b --- a/bus-proxy/src/main/java/org/miaixz/bus/proxy/invoker/NullInvoker.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/MethodProvider.java @@ -23,44 +23,54 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.proxy.invoker; +package org.miaixz.bus.limiter.metric; -import org.miaixz.bus.proxy.Invoker; +import org.miaixz.bus.core.cache.provider.TimedCache; +import org.miaixz.bus.core.xyz.CacheKit; +import org.miaixz.bus.core.xyz.MethodKit; +import org.miaixz.bus.core.xyz.StringKit; +import org.miaixz.bus.extra.json.JsonKit; +import org.miaixz.bus.limiter.Builder; +import org.miaixz.bus.limiter.Holder; +import org.miaixz.bus.limiter.Provider; +import org.miaixz.bus.limiter.magic.StrategyMode; import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; /** - * 一个仅为所有方法调用返回null的{@link Invoker}实现 - * 这个类对于需要“空对象”设计模式的场景非常有用 + * HOT_METHOD 模式处理 * * @author Kimi Liu * @since Java 17+ */ -public class NullInvoker implements Invoker { +public class MethodProvider implements Provider { - private static Map primitiveValueMap = new HashMap(); + private final TimedCache cache; - static { - primitiveValueMap.put(Integer.TYPE, new Integer(0)); - primitiveValueMap.put(Long.TYPE, new Long(0)); - primitiveValueMap.put(Short.TYPE, new Short((short) 0)); - primitiveValueMap.put(Byte.TYPE, new Byte((byte) 0)); - primitiveValueMap.put(Float.TYPE, new Float(0.0f)); - primitiveValueMap.put(Double.TYPE, new Double(0.0)); - primitiveValueMap.put(Character.TYPE, new Character((char) 0)); - primitiveValueMap.put(Boolean.TYPE, Boolean.FALSE); + public MethodProvider() { + cache = CacheKit.newTimedCache(1000L * Holder.load().getSeconds()); + cache.schedulePrune(1000); } - public Object invoke(Object proxy, Method method, Object[] args) { - final Class returnType = method.getReturnType(); - if (returnType.isPrimitive()) { - return primitiveValueMap.get(returnType); + @Override + public StrategyMode get() { + return StrategyMode.HOT_METHOD; + } + + @Override + public Object process(Object bean, Method method, Object[] args) { + // 获取方法对应的key + String hotKey = StringKit.format("{}-{}", Builder.resolveMethodName(method), org.miaixz.bus.crypto.Builder.md5Hex(JsonKit.toJsonString(args))); + + // 缓存操作 + if (cache.containsKey(hotKey)) { + return cache.get(hotKey, false); } else { - return null; + // 执行后缓存 + Object result = MethodKit.invoke(bean, method, args); + cache.put(hotKey, result); + return result; } } } - diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/RequestProvider.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/RequestProvider.java new file mode 100644 index 0000000000..028f994913 --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/RequestProvider.java @@ -0,0 +1,127 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.limiter.metric; + +import org.miaixz.bus.core.data.UUID; +import org.miaixz.bus.core.xyz.MethodKit; +import org.miaixz.bus.core.xyz.ThreadKit; +import org.miaixz.bus.limiter.Builder; +import org.miaixz.bus.limiter.Provider; +import org.miaixz.bus.limiter.Supplier; +import org.miaixz.bus.limiter.magic.StrategyMode; +import org.miaixz.bus.limiter.magic.annotation.Limiting; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; + +/** + * REQUEST_LIMIT 模式处理 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class RequestProvider implements Provider { + + private final ExecutorService cleaner = ThreadKit.newFixedExecutor(1, 5, "L-", false); + + private final Map map = new ConcurrentHashMap<>(); + + /** + * 默认的user标识提供者 + */ + private Supplier supplier = new Supplier() { + + @Override + public Serializable get() { + return UUID.fastUUID(); + } + + }; + + /** + * 设置新的用户标识提供者 + * + * @param supplier 提供者 + */ + public void setMarkSupplier(Supplier supplier) { + this.supplier = supplier; + } + + @Override + public StrategyMode get() { + return StrategyMode.REQUEST_LIMIT; + } + + @Override + public Object process(Object bean, Method method, Object[] args) { + // 获取当前用户标识 + Serializable mark = supplier.get(); + ResourceManager resourceManager = map.get(mark); + + // 缓存操作 + if (Objects.isNull(resourceManager)) { + resourceManager = new ResourceManager(); + map.put(mark, resourceManager); + } + + // 获取方法配置参数 + String name = Builder.resolveMethodName(method); + Limiting limiting = (Limiting) MethodManager.getAnnoInfo(name).getRight(); + if (!resourceManager.entry(name, limiting)) { + // 拦截方法 + return supplier.intercept(bean, method, args); + } + + // 允许执行 + return MethodKit.invoke(bean, method, args); + } + + /** + * 清理存在的资源管理 + */ + private void clears() { + cleaner.submit(this::clear); + } + + /** + * 清理资源,最多10个 + */ + private void clear() { + int count = 0; + for (Serializable mark : map.keySet()) { + count++; + ResourceManager resourceManager = map.get(mark); + if (Objects.isNull(resourceManager)) continue; + if (resourceManager.isClear()) map.remove(mark); + if (count > 9) return; + } + } + +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/ResourceManager.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/ResourceManager.java new file mode 100644 index 0000000000..c3da299402 --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/ResourceManager.java @@ -0,0 +1,168 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.limiter.metric; + +import org.miaixz.bus.limiter.magic.annotation.Limiting; + +import java.time.LocalDateTime; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 资源管理 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class ResourceManager { + + /** + * 用于判断是否添加过方法(打印日志需要...) + */ + private static final Set PROTECTED_METHODS = new HashSet<>(); + /** + * 资源缓存 + */ + private final Map map = new ConcurrentHashMap<>(); + + /** + * 判断资源是否是保护的 + * + * @param resourceKey 资源标识 + * @return the true/false + */ + public static boolean contain(String resourceKey) { + return PROTECTED_METHODS.contains(resourceKey); + } + + /** + * 添加到保护资源 + * + * @param resourceKey 资源标识 + */ + public static void add(String resourceKey) { + PROTECTED_METHODS.add(resourceKey); + } + + /** + * 查看资源是否可以执行 + * + * @param resourceKey 资源标识 + * @param limiting 限流注解 + * @return the true/false + */ + public boolean entry(String resourceKey, Limiting limiting) throws IllegalStateException { + Protection protection = map.get(resourceKey); + + // 缓存操作 + if (Objects.isNull(protection)) { + protection = new Protection(limiting); + map.put(resourceKey, protection); + } + + // 判断是否过期 + if (protection.isExpire()) { + protection.reset(); + } + + // 判断次数是否超出 + if (!protection.isAllow()) { + return false; + } + + protection.allowCount -= 1; + return true; + } + + /** + * 清理 + * + * @return the true/false + */ + public boolean isClear() { + map.keySet().forEach(key -> { + Protection protection = map.get(key); + if (Objects.nonNull(protection) && protection.isExpire()) { + map.remove(key); + } + }); + return map.size() == 0; + } + + /** + * 资源保护 + */ + static class Protection { + + /** + * 注解对象 + */ + Limiting limiting; + /** + * 保护到期的时间 + */ + LocalDateTime targetTime; + /** + * 剩余的请求次数 + */ + int allowCount; + + public Protection(Limiting limiting) { + this.limiting = limiting; + this.reset(); + } + + /** + * 是否过期 + * + * @return the true/false + */ + public boolean isExpire() { + return targetTime.compareTo(LocalDateTime.now()) < 0; + } + + /** + * 重置 + */ + public void reset() { + this.allowCount = limiting.count(); + this.targetTime = LocalDateTime.now().plusSeconds(limiting.duration()); + } + + /** + * 是否允许访问 + * + * @return the true/false + */ + public boolean isAllow() { + return allowCount > 0; + } + } + +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/StrategyManager.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/StrategyManager.java new file mode 100644 index 0000000000..0801e5e690 --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/StrategyManager.java @@ -0,0 +1,66 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.limiter.metric; + +import org.miaixz.bus.limiter.Provider; +import org.miaixz.bus.limiter.magic.StrategyMode; + +import java.util.HashMap; +import java.util.Map; + +/** + * 规则管理 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class StrategyManager { + + /** + * 规则缓存 + */ + private static final Map map = new HashMap<>(); + + /** + * 添加规则管理 + * + * @param provider 服务提供者 + */ + public static void add(Provider provider) { + map.put(provider.get(), provider); + } + + /** + * 获取规则执行者 + * + * @param strategyMode 执行规则 + * @return the provider + */ + public static Provider get(StrategyMode strategyMode) { + return map.get(strategyMode); + } + +} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/package-info.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/package-info.java new file mode 100644 index 0000000000..0d36c17eda --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/metric/package-info.java @@ -0,0 +1,7 @@ +/** + * 管控规则 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.limiter.metric; \ No newline at end of file diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/package-info.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/package-info.java new file mode 100644 index 0000000000..47aa41f760 --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/package-info.java @@ -0,0 +1,7 @@ +/** + * 服务请求流量管控 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.limiter; \ No newline at end of file diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/proxy/ByteBuddyHandler.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/proxy/ByteBuddyHandler.java new file mode 100644 index 0000000000..7f4d4c3d56 --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/proxy/ByteBuddyHandler.java @@ -0,0 +1,95 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.limiter.proxy; + +import org.miaixz.bus.core.xyz.MethodKit; +import org.miaixz.bus.limiter.Builder; +import org.miaixz.bus.limiter.Registry; +import org.miaixz.bus.limiter.Sentinel; +import org.miaixz.bus.limiter.magic.StrategyMode; +import org.miaixz.bus.limiter.magic.annotation.Downgrade; +import org.miaixz.bus.limiter.magic.annotation.Hotspot; +import org.miaixz.bus.limiter.magic.annotation.Limiting; +import org.miaixz.bus.limiter.metric.MethodManager; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + * 规则拦截处理 + * + * @author Kimi Liu + * @since Java 17+ + */ +public class ByteBuddyHandler implements InvocationHandler { + + private final ByteBuddyProxy byteBuddyProxy; + private Map methodCache = new HashMap<>(); + + public ByteBuddyHandler(ByteBuddyProxy byteBuddyProxy) { + this.byteBuddyProxy = byteBuddyProxy; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + // 获取方法标记 + String name = Builder.resolveMethodName(method); + // 此对象内是否有缓存方法 + Method realMethod; + if (methodCache.containsKey(name)) { + realMethod = methodCache.get(name); + } else { + // 获取bean的方法且进行缓存到此对象 + realMethod = MethodKit.getMethod(byteBuddyProxy.bean.getClass(), method.getName(), method.getParameterTypes()); + methodCache.put(name, realMethod); + } + + if (MethodManager.contain(name)) { + // 获取方法缓存的策略和注解信息 + StrategyMode strategyMode = MethodManager.getAnnoInfo(name).getLeft(); + Annotation anno = MethodManager.getAnnoInfo(name).getRight(); + + // 判断注解类型 + if (anno instanceof Downgrade) { + Registry.register((Downgrade) anno, name); + } else if (anno instanceof Hotspot) { + Registry.register((Hotspot) anno, name); + } else if (anno instanceof Limiting) { + Registry.register((Limiting) anno, name); + } else { + throw new RuntimeException("annotation type error"); + } + // 通过 + return Sentinel.process(byteBuddyProxy.bean, realMethod, args, name, strategyMode); + } else { + return MethodKit.invoke(byteBuddyProxy.bean, realMethod, args); + } + } + +} diff --git a/bus-tracer/src/main/java/org/miaixz/bus/tracer/binding/apache/dubbo/BaseDubboFilter.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/proxy/ByteBuddyProxy.java similarity index 60% rename from bus-tracer/src/main/java/org/miaixz/bus/tracer/binding/apache/dubbo/BaseDubboFilter.java rename to bus-limiter/src/main/java/org/miaixz/bus/limiter/proxy/ByteBuddyProxy.java index ebf9bdd28d..a43cdfeb37 100644 --- a/bus-tracer/src/main/java/org/miaixz/bus/tracer/binding/apache/dubbo/BaseDubboFilter.java +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/proxy/ByteBuddyProxy.java @@ -23,40 +23,47 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.tracer.binding.apache.dubbo; +package org.miaixz.bus.limiter.proxy; -import org.apache.dubbo.rpc.Filter; -import org.miaixz.bus.core.lang.Normal; +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; +import net.bytebuddy.implementation.InvocationHandlerAdapter; +import net.bytebuddy.implementation.attribute.MethodAttributeAppender; +import net.bytebuddy.matcher.ElementMatchers; +import org.miaixz.bus.core.xyz.DateKit; import org.miaixz.bus.core.xyz.StringKit; +import org.miaixz.bus.logger.Logger; /** - * 基础dubbo过滤器 + * 代理信息 * * @author Kimi Liu * @since Java 17+ */ -public abstract class BaseDubboFilter implements Filter, Filter.Listener { +public class ByteBuddyProxy { - private static final String[] DUBBO_INNER_SERVICE_NAMES = new String[]{ - "com.alibaba.cloud.dubbo.service.DubboMetadataService", - "org.apache.dubbo.rpc.service.GenericService" - }; + public final Object bean; - boolean isDubboInnerService(String serviceName) { - for (String dubboInnerServiceName : DUBBO_INNER_SERVICE_NAMES) { - if (dubboInnerServiceName.equals(serviceName)) { - return true; - } - } - return false; - } + private final Class originalClazz; - String withUnknown(String text) { - return StringKit.isBlank(text) ? "unknown" : text; + public ByteBuddyProxy(Object bean, Class originalClazz) { + this.bean = bean; + this.originalClazz = originalClazz; } - String getAsyncIdTrace(String asyncId) { - return null != asyncId ? "-[异步ID: " + asyncId + "]" : Normal.EMPTY; + public Object proxy() throws Exception { + Logger.debug("proxy {}.", originalClazz.getSimpleName()); + return new ByteBuddy().subclass(originalClazz) + .name(StringKit.format("{}$ByteBuddy${}", originalClazz.getName(), DateKit.current())) + .method(ElementMatchers.any()) + .intercept(InvocationHandlerAdapter.of(new ByteBuddyHandler(this))) + .attribute(MethodAttributeAppender.ForInstrumentedMethod.INCLUDING_RECEIVER) + .annotateType(bean.getClass().getAnnotations()) + .make() + .load(ByteBuddyProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION) + .getLoaded() + .getConstructor() + .newInstance(); } } diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/proxy/package-info.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/proxy/package-info.java new file mode 100644 index 0000000000..2fcd5d62b4 --- /dev/null +++ b/bus-limiter/src/main/java/org/miaixz/bus/limiter/proxy/package-info.java @@ -0,0 +1,7 @@ +/** + * 管控代理 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.limiter.proxy; \ No newline at end of file diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/resource/AbstractLimitedResource.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/resource/AbstractLimitedResource.java deleted file mode 100755 index 95698edec8..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/resource/AbstractLimitedResource.java +++ /dev/null @@ -1,82 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.resource; - -import java.util.Collection; -import java.util.Observable; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public abstract class AbstractLimitedResource extends Observable implements LimitedResource { - - protected String key; - - protected Collection argumentInjectors; - - protected String fallback; - - protected String errorHandler; - - protected String limiter; - - public AbstractLimitedResource(String key, Collection argumentInjectors, String fallback, String errorHandler, String limiter) { - this.key = key; - this.argumentInjectors = argumentInjectors; - this.fallback = fallback; - this.errorHandler = errorHandler; - this.limiter = limiter; - } - - - @Override - public String getKey() { - return key; - } - - - @Override - public String getLimiter() { - return limiter; - } - - @Override - public String getFallback() { - return fallback; - } - - @Override - public String getErrorHandler() { - return errorHandler; - } - - @Override - public Collection getArgumentInjectors() { - return argumentInjectors; - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/resource/DefaultLimitedResourceSource.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/resource/DefaultLimitedResourceSource.java deleted file mode 100755 index 7458ce5702..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/resource/DefaultLimitedResourceSource.java +++ /dev/null @@ -1,133 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.resource; - -import org.miaixz.bus.core.lang.Normal; -import org.miaixz.bus.core.xyz.CollKit; -import org.miaixz.bus.core.xyz.MethodKit; -import org.miaixz.bus.limiter.Parser; -import org.springframework.aop.support.AopUtils; -import org.springframework.core.MethodClassKey; -import org.springframework.core.annotation.AnnotationAttributes; -import org.springframework.core.annotation.AnnotationUtils; - -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class DefaultLimitedResourceSource implements LimitedResourceSource { - - private static final Collection NULL_CACHING_ATTRIBUTE = Collections.emptyList(); - - private final Map> cache = new ConcurrentHashMap(Normal._1024); - - private final Set annotationParsers; - - - public DefaultLimitedResourceSource(Parser... annotationParsers) { - Set parsers = new LinkedHashSet<>(annotationParsers.length); - Collections.addAll(parsers, annotationParsers); - this.annotationParsers = parsers; - } - - @Override - public Collection getLimitedResource(Class targetClass, Method method) { - MethodClassKey key = new MethodClassKey(method, targetClass); - Collection retVal = cache.get(key); - if (null != retVal) { - return retVal; - } - retVal = computeLimitedResource(method, targetClass); - if (CollKit.isEmpty(retVal)) { - cache.put(key, NULL_CACHING_ATTRIBUTE); - return null; - } else { - cache.put(key, retVal); - return retVal; - } - } - - private Collection computeLimitedResource(Method method, Class targetClass) { - // 从代理前的方法上获取 - Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass); - Collection reDef = findLimitedResource(specificMethod); - if (!CollKit.isEmpty(reDef)) { - return reDef; - } - // 代理前class对象 - reDef = findLimitedResource(specificMethod.getDeclaringClass()); - if (!CollKit.isEmpty(reDef) && MethodKit.isUserLevelMethod(specificMethod)) { - return reDef; - } - if (specificMethod != method) { - // 代理后的方法 - reDef = findLimitedResource(method); - if (!CollKit.isEmpty(reDef)) { - return reDef; - } - // 代理后的class对象 - reDef = findLimitedResource(method.getDeclaringClass()); - if (!CollKit.isEmpty(reDef) && MethodKit.isUserLevelMethod(method)) { - return reDef; - } - } - - return null; - } - - private Collection findLimitedResource(Method method) { - return findLimitedResourceFromAnnotatedElement(method); - } - - private Collection findLimitedResource(Class clazz) { - return findLimitedResourceFromAnnotatedElement(clazz); - } - - private Collection findLimitedResourceFromAnnotatedElement(AnnotatedElement ae) { - Annotation[] annotations = ae.getAnnotations(); - Collection retVal = null; - for (Parser parser : annotationParsers) { - for (Annotation ai : annotations) { - if (ai.annotationType().equals(parser.getSupportAnnotation())) { - if (null == retVal) { - retVal = new ArrayList<>(); - } - AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(ae, ai); - retVal.add(parser.parseLimiterAnnotation(attributes)); - } - - } - } - return retVal; - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/resource/LimitedResource.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/resource/LimitedResource.java deleted file mode 100755 index f7d3f8cdbe..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/resource/LimitedResource.java +++ /dev/null @@ -1,53 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.resource; - -import org.miaixz.bus.limiter.Limiter; -import org.miaixz.bus.limiter.metadata.LimitedResourceMetadata; -import org.springframework.beans.factory.BeanFactory; - -import java.lang.reflect.Method; -import java.util.Collection; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public interface LimitedResource { - - String getKey(); - - String getLimiter(); - - String getFallback(); - - String getErrorHandler(); - - Collection getArgumentInjectors(); - - LimitedResourceMetadata createMetadata(BeanFactory beanFactory, Class targetClass, Method targetMethod); - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/LockAnnotationParser.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/LockAnnotationParser.java deleted file mode 100755 index 4b39950890..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/LockAnnotationParser.java +++ /dev/null @@ -1,50 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.lock; - -import org.miaixz.bus.limiter.annotation.Lock; -import org.miaixz.bus.limiter.resource.LimitedResource; -import org.miaixz.bus.limiter.support.rate.AbstractParser; -import org.springframework.core.annotation.AnnotationAttributes; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class LockAnnotationParser extends AbstractParser { - - @Override - public LimitedResource parseLimiterAnnotation(AnnotationAttributes attributes) { - return new LockResource( - getKey(attributes), - getArgumentInjectors(attributes), - getFallback(attributes), - getErrorHandler(attributes), - getLimiter(attributes) - ); - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/LockResource.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/LockResource.java deleted file mode 100755 index a36fd9e3aa..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/LockResource.java +++ /dev/null @@ -1,50 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.lock; - -import org.miaixz.bus.limiter.metadata.LimitedResourceMetadata; -import org.miaixz.bus.limiter.resource.AbstractLimitedResource; -import org.springframework.beans.factory.BeanFactory; - -import java.lang.reflect.Method; -import java.util.Collection; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class LockResource extends AbstractLimitedResource { - - public LockResource(String key, Collection argumentInjectors, String fallback, String errorHandler, String limiter) { - super(key, argumentInjectors, fallback, errorHandler, limiter); - } - - @Override - public LimitedResourceMetadata createMetadata(BeanFactory beanFactory, Class targetClass, Method targetMethod) { - return new LockResourceMetadata(this, targetClass, targetMethod, beanFactory); - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/LockResourceMetadata.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/LockResourceMetadata.java deleted file mode 100755 index e113639235..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/LockResourceMetadata.java +++ /dev/null @@ -1,47 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.lock; - -import org.miaixz.bus.limiter.metadata.AbstractLimitedResourceMetadata; -import org.springframework.beans.factory.BeanFactory; - -import java.lang.reflect.Method; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class LockResourceMetadata extends AbstractLimitedResourceMetadata { - - public LockResourceMetadata(LockResource limitedResource, Class targetClass, Method targetMethod, BeanFactory beanFactory) { - super(limitedResource, targetClass, targetMethod, beanFactory); - } - - @Override - protected void parseInternal(LockResource limitedResource) { - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/jdk/JdkLock.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/jdk/JdkLock.java deleted file mode 100755 index dbd797f286..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/jdk/JdkLock.java +++ /dev/null @@ -1,93 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.lock.jdk; - -import org.miaixz.bus.logger.Logger; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * 基于ConcurrentHashMap和ReentrantLock实现的一个简单的锁组件 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class JdkLock extends org.miaixz.bus.limiter.support.lock.Lock { - - private String lockName; - - private ConcurrentHashMap locks; - - public JdkLock(String lockName, int initialCapacity, float loadFactor, int concurrencyLevel) { - this.lockName = lockName; - locks = new ConcurrentHashMap<>(initialCapacity, loadFactor, concurrencyLevel); - } - - public JdkLock(String lockName) { - this.lockName = lockName; - locks = new ConcurrentHashMap<>(); - } - - @Override - public boolean lock(Object key) { - // 对于一个良好的资源 竞态条件的不应该频繁产生 - Lock lock = new ReentrantLock(); - Lock oldLock = locks.putIfAbsent(key, lock); - if (null != oldLock) { - boolean ret = oldLock.tryLock(); - if (ret) { - Logger.info("acquire lock on {} success", key); - } else { - Logger.info("acquire lock on {} fail", key); - } - return ret; - } else { - boolean ret = lock.tryLock(); - if (ret) { - Logger.info("acquire lock on {} success", key); - } else { - Logger.info("acquire lock on {} fail", key); - } - return ret; - } - } - - @Override - public void unlock(Object key) { - Lock lock = locks.remove(key); - if (null == lock) { - throw new RuntimeException("未找到该锁!"); - } - lock.unlock(); - } - - @Override - public String getLimiterName() { - return lockName; - } -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/zookeeper/ZookeeperLock.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/zookeeper/ZookeeperLock.java deleted file mode 100755 index 63354f80b5..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/lock/zookeeper/ZookeeperLock.java +++ /dev/null @@ -1,93 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.lock.zookeeper; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.imps.CuratorFrameworkState; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.miaixz.bus.core.lang.exception.InternalException; -import org.miaixz.bus.limiter.support.lock.Lock; -import org.miaixz.bus.logger.Logger; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class ZookeeperLock extends Lock { - - private String lockName; - - private String basePath; - - private CuratorFramework client; - - - public ZookeeperLock(String lockName, String basePath, CuratorFramework client) { - this.lockName = lockName; - this.basePath = basePath; - this.client = client; - if (!client.getState().equals(CuratorFrameworkState.STARTED)) { - client.start(); - } - - Logger.info("zookeeper lock named {} start success!", lockName); - } - - public ZookeeperLock(String lockName, CuratorFramework client) { - this(lockName, "/locks/", client); - } - - @Override - public boolean lock(Object key) { - try { - client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(basePath + key.toString()); - return true; - } catch (KeeperException.NodeExistsException e) { - Logger.info("lock fail on {}", key); - return false; - } catch (Exception e) { - throw new RuntimeException(e.getMessage()); - } - } - - @Override - public void unlock(Object key) { - - try { - client.delete().forPath(basePath + key.toString()); - } catch (KeeperException.NodeExistsException e) { - throw new IllegalMonitorStateException("You do not own the lock: " + key); - } catch (Exception e) { - throw new InternalException(e); - } - } - - @Override - public String getLimiterName() { - return lockName; - } -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiter.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiter.java deleted file mode 100755 index 9ef1bcae78..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiter.java +++ /dev/null @@ -1,53 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.peak; - -import org.miaixz.bus.limiter.Limiter; -import org.miaixz.bus.limiter.annotation.Peak; - -import java.util.Map; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public abstract class PeakLimiter implements Limiter { - - public abstract boolean acquire(Object key, int max); - - public abstract void release(Object key, int max); - - @Override - public boolean limit(Object key, Map args) { - return acquire(key, (int) args.get("max")); - } - - @Override - public void release(Object key, Map args) { - release(key, (int) args.get("max")); - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiterAnnotationParser.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiterAnnotationParser.java deleted file mode 100755 index a234e9d4ab..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiterAnnotationParser.java +++ /dev/null @@ -1,52 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.peak; - -import org.miaixz.bus.limiter.annotation.Peak; -import org.miaixz.bus.limiter.resource.LimitedResource; -import org.miaixz.bus.limiter.support.rate.AbstractParser; -import org.springframework.core.annotation.AnnotationAttributes; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class PeakLimiterAnnotationParser extends AbstractParser { - - @Override - public LimitedResource parseLimiterAnnotation(AnnotationAttributes attributes) { - - return new PeakLimiterResource( - getKey(attributes), - getArgumentInjectors(attributes), - getFallback(attributes), - getErrorHandler(attributes), - getLimiter(attributes), - attributes.getNumber("max") - ); - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiterResource.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiterResource.java deleted file mode 100755 index 7021eced37..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiterResource.java +++ /dev/null @@ -1,54 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.peak; - -import org.miaixz.bus.limiter.annotation.LimiterParameter; -import org.miaixz.bus.limiter.metadata.LimitedResourceMetadata; -import org.miaixz.bus.limiter.resource.AbstractLimitedResource; -import org.springframework.beans.factory.BeanFactory; - -import java.lang.reflect.Method; -import java.util.Collection; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class PeakLimiterResource extends AbstractLimitedResource { - - @LimiterParameter - private int max; - - public PeakLimiterResource(String key, Collection argumentInjectors, String fallback, String errorHandler, String limiter, int max) { - super(key, argumentInjectors, fallback, errorHandler, limiter); - this.max = max; - } - - @Override - public LimitedResourceMetadata createMetadata(BeanFactory beanFactory, Class targetClass, Method targetMethod) { - return new PeakLimiterResourceMetadata(this, targetClass, targetMethod, beanFactory); - } -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiterResourceMetadata.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiterResourceMetadata.java deleted file mode 100755 index 641e6d6fb0..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/PeakLimiterResourceMetadata.java +++ /dev/null @@ -1,47 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.peak; - -import org.miaixz.bus.limiter.metadata.AbstractLimitedResourceMetadata; -import org.springframework.beans.factory.BeanFactory; - -import java.lang.reflect.Method; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class PeakLimiterResourceMetadata extends AbstractLimitedResourceMetadata { - - public PeakLimiterResourceMetadata(PeakLimiterResource limitedResource, Class targetClass, Method targetMethod, BeanFactory beanFactory) { - super(limitedResource, targetClass, targetMethod, beanFactory); - } - - @Override - protected void parseInternal(PeakLimiterResource limitedResource) { - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/jdk/JdkPeakLimiter.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/jdk/JdkPeakLimiter.java deleted file mode 100755 index 03889e9be8..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/jdk/JdkPeakLimiter.java +++ /dev/null @@ -1,106 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.peak.jdk; - -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import org.miaixz.bus.core.lang.Normal; -import org.miaixz.bus.limiter.support.peak.PeakLimiter; - -import java.util.Objects; -import java.util.concurrent.Semaphore; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class JdkPeakLimiter extends PeakLimiter { - - private String limiterName; - - private LoadingCache cache; - - public JdkPeakLimiter(String limiterName) { - this.limiterName = limiterName; - this.cache = CacheBuilder.newBuilder() - .concurrencyLevel(Normal._16) - .initialCapacity(2048) - .build(new CacheLoader<>() { - @Override - public Semaphore load(CacheKey key) { - return new Semaphore(key.max); - } - }); - } - - @Override - public boolean acquire(Object key, int max) { - CacheKey cacheKey = new CacheKey(key, max); - return cache.getIfPresent(cacheKey).tryAcquire(); - } - - @Override - public void release(Object key, int max) { - CacheKey cacheKey = new CacheKey(key, max); - Semaphore semaphore = cache.getIfPresent(cacheKey); - if (null != semaphore) { - semaphore.release(); - } - } - - @Override - public String getLimiterName() { - return limiterName; - } - - public static class CacheKey { - - private Object key; - - private int max; - - public CacheKey(Object key, int max) { - this.key = key; - this.max = max; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (null == o || getClass() != o.getClass()) return false; - CacheKey cacheKey = (CacheKey) o; - return max == cacheKey.max && - Objects.equals(key, cacheKey.key); - } - - @Override - public int hashCode() { - return Objects.hash(key, max); - } - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/redis/RedisPeakLimiter.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/redis/RedisPeakLimiter.java deleted file mode 100755 index 4b4b78604f..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/peak/redis/RedisPeakLimiter.java +++ /dev/null @@ -1,63 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.peak.redis; - -import org.miaixz.bus.limiter.support.peak.PeakLimiter; -import org.redisson.Redisson; -import org.redisson.api.RSemaphore; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class RedisPeakLimiter extends PeakLimiter { - - private Redisson redisson; - - private String limiterName; - - public RedisPeakLimiter(Redisson redisson, String limiterName) { - this.redisson = redisson; - this.limiterName = limiterName; - } - - @Override - public boolean acquire(Object key, int max) { - RSemaphore rSemaphore = redisson.getSemaphore(key.toString()); - return rSemaphore.tryAcquire(); - } - - @Override - public void release(Object key, int max) { - RSemaphore rSemaphore = redisson.getSemaphore(key.toString()); - rSemaphore.release(); - } - - @Override - public String getLimiterName() { - return limiterName; - } -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/AbstractParser.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/AbstractParser.java deleted file mode 100755 index 09c0d3b70c..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/AbstractParser.java +++ /dev/null @@ -1,82 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.rate; - -import org.miaixz.bus.limiter.Limiter; -import org.miaixz.bus.limiter.Parser; -import org.springframework.core.annotation.AnnotationAttributes; - -import java.lang.annotation.Annotation; -import java.lang.reflect.ParameterizedType; -import java.util.Arrays; -import java.util.Collection; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public abstract class AbstractParser, V extends Annotation> implements Parser { - - private Class supportAnnotation; - - // 不需要同步 - private synchronized Class computeSupportAnnotation() { - if (null != supportAnnotation) { - return supportAnnotation; - } - supportAnnotation = (Class) ((ParameterizedType) (this.getClass().getGenericSuperclass())).getActualTypeArguments()[1]; - return supportAnnotation; - } - - @Override - public Class getSupportAnnotation() { - if (null != supportAnnotation) { - return supportAnnotation; - } - return computeSupportAnnotation(); - } - - public String getLimiter(AnnotationAttributes attributes) { - return attributes.getString("limiter"); - } - - public String getKey(AnnotationAttributes attributes) { - return attributes.getString("key"); - } - - public String getFallback(AnnotationAttributes attributes) { - return attributes.getString("fallback"); - } - - public String getErrorHandler(AnnotationAttributes attributes) { - return attributes.getString("errorHandler"); - } - - public Collection getArgumentInjectors(AnnotationAttributes attributes) { - return Arrays.asList(attributes.getStringArray("argumentInjectors")); - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiterAnnotationParser.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiterAnnotationParser.java deleted file mode 100755 index 5b8907b203..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiterAnnotationParser.java +++ /dev/null @@ -1,49 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.rate; - -import org.miaixz.bus.limiter.resource.LimitedResource; -import org.springframework.core.annotation.AnnotationAttributes; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class RateLimiterAnnotationParser extends AbstractParser { - - @Override - public LimitedResource parseLimiterAnnotation(AnnotationAttributes attributes) { - return new RateLimiterResource(getKey(attributes), - getArgumentInjectors(attributes), - getFallback(attributes), - getErrorHandler(attributes), - getLimiter(attributes), - attributes.getNumber("rate"), - attributes.getNumber("capacity") - ); - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiterResource.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiterResource.java deleted file mode 100755 index af58be61bf..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiterResource.java +++ /dev/null @@ -1,59 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.rate; - -import org.miaixz.bus.limiter.annotation.LimiterParameter; -import org.miaixz.bus.limiter.metadata.LimitedResourceMetadata; -import org.miaixz.bus.limiter.resource.AbstractLimitedResource; -import org.springframework.beans.factory.BeanFactory; - -import java.lang.reflect.Method; -import java.util.Collection; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class RateLimiterResource extends AbstractLimitedResource { - - @LimiterParameter - private double rate; - - @LimiterParameter - private long capacity; - - public RateLimiterResource(String key, Collection argumentInjectors, String fallback, String errorHandler, String limiter, double rate, long capacity) { - super(key, argumentInjectors, fallback, errorHandler, limiter); - this.rate = rate; - this.capacity = capacity; - } - - @Override - public LimitedResourceMetadata createMetadata(BeanFactory beanFactory, Class targetClass, Method targetMethod) { - return new RateLimiterResourceMetadata(this, targetClass, targetMethod, beanFactory); - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiterResourceMetadata.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiterResourceMetadata.java deleted file mode 100755 index aa48309647..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/RateLimiterResourceMetadata.java +++ /dev/null @@ -1,47 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.rate; - -import org.miaixz.bus.limiter.metadata.AbstractLimitedResourceMetadata; -import org.springframework.beans.factory.BeanFactory; - -import java.lang.reflect.Method; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class RateLimiterResourceMetadata extends AbstractLimitedResourceMetadata { - - public RateLimiterResourceMetadata(RateLimiterResource limitedResource, Class targetClass, Method targetMethod, BeanFactory beanFactory) { - super(limitedResource, targetClass, targetMethod, beanFactory); - } - - @Override - protected void parseInternal(RateLimiterResource limitedResource) { - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/jdk/JdkRateLimiter.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/jdk/JdkRateLimiter.java deleted file mode 100755 index b60adb0ce1..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/jdk/JdkRateLimiter.java +++ /dev/null @@ -1,108 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.rate.jdk; - -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import org.miaixz.bus.core.lang.Normal; -import org.miaixz.bus.limiter.support.rate.RateLimiter; - -import java.util.Objects; -import java.util.concurrent.TimeUnit; - -/** - * 一个RateLimiter组件 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class JdkRateLimiter extends RateLimiter { - - private String rateLimiterName; - - private LoadingCache - cache; - - /** - * @param rateLimiterName 名称 - * @param expireAfterAccess 过期时间 - * @param expireAfterAccessUnit 过期数量 - */ - public JdkRateLimiter(String rateLimiterName, long expireAfterAccess, TimeUnit expireAfterAccessUnit) { - this.rateLimiterName = rateLimiterName; - this.cache = CacheBuilder.newBuilder() - .expireAfterAccess(expireAfterAccess, expireAfterAccessUnit) - .concurrencyLevel(Normal._16) - .build(new CacheLoader() { - @Override - public RateLimiterObject load(CacheKey key) { - return new RateLimiterObject(); - } - }); - } - - @Override - public boolean acquire(Object key, double rate, long capacity) { - CacheKey cacheKey = new CacheKey(key, rate, capacity); - RateLimiterObject rateLimiterObject = cache.getUnchecked(cacheKey); - return rateLimiterObject.tryAcquire(1, rate, capacity); - } - - @Override - public String getLimiterName() { - return rateLimiterName; - } - - private static class CacheKey { - - private Object key; - private double rate; - private long capacity; - - public CacheKey(Object key, double rate, long capacity) { - this.key = key; - this.rate = rate; - this.capacity = capacity; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (null == o || getClass() != o.getClass()) return false; - CacheKey cacheKey = (CacheKey) o; - return Double.compare(cacheKey.rate, rate) == 0 && - capacity == cacheKey.capacity && - Objects.equals(key, cacheKey.key); - } - - @Override - public int hashCode() { - return Objects.hash(key, rate, capacity); - } - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/jdk/RateLimiterObject.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/jdk/RateLimiterObject.java deleted file mode 100755 index dd7dbcdac4..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/jdk/RateLimiterObject.java +++ /dev/null @@ -1,68 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.rate.jdk; - -/** - * 基于令牌桶实现的速率限制器 - * - * @author Kimi Liu - * @since Java 17+ - */ -public class RateLimiterObject { - - private double rate; - - private long capacity; - - private long lastSyncTime; - - private double storedPermits; - - public synchronized boolean tryAcquire(long permits, double rate, long capacity) { - if (permits > capacity) return false; - long now = System.currentTimeMillis(); - if (rate != this.rate || capacity != this.capacity) { - this.rate = rate; - this.capacity = capacity; - this.storedPermits = capacity - permits; - this.lastSyncTime = now; - return true; - } - resync(now); - if (storedPermits >= permits) { - storedPermits = storedPermits - permits; - return true; - } - return false; - } - - private void resync(long nowMicros) { - double newPermits = (nowMicros - lastSyncTime) * rate / 1000 + storedPermits; - storedPermits = Math.max(newPermits, capacity); - this.lastSyncTime = nowMicros; - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/redis/RedisRatelimiter.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/redis/RedisRatelimiter.java deleted file mode 100755 index 293e3acc27..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/redis/RedisRatelimiter.java +++ /dev/null @@ -1,80 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.rate.redis; - -import org.miaixz.bus.limiter.support.rate.RateLimiter; -import org.miaixz.bus.logger.Logger; -import org.redisson.Redisson; -import org.redisson.config.Config; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class RedisRatelimiter extends RateLimiter { - - private String limiterName; - - private RateLimiterRedission ratelimiterRedission; - - /** - * @param limiterName 名称 - * @param config 配置 - */ - public RedisRatelimiter(String limiterName, Config config) { - this.limiterName = limiterName; - this.ratelimiterRedission = new RateLimiterRedission(config); - Logger.info("RedisRateLimiter named {} start success!", limiterName); - - } - - @Override - public boolean acquire(Object key, double rate, long capacity) { - RedisRatelimiterObject rateLimiterObject = ratelimiterRedission.getRedisRatelimiterObject(key.toString()); - return rateLimiterObject.tryAcquire(1, rate, capacity); - } - - @Override - public String getLimiterName() { - return limiterName; - } - - - /** - * 继承自Redisson 实现自定义api - */ - public static class RateLimiterRedission extends Redisson { - - public RateLimiterRedission(Config config) { - super(config); - } - - public RedisRatelimiterObject getRedisRatelimiterObject(String name) { - return new RedisRatelimiterObject(commandExecutor, name); - } - } - -} diff --git a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/redis/RedisRatelimiterObject.java b/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/redis/RedisRatelimiterObject.java deleted file mode 100755 index 9f05e32147..0000000000 --- a/bus-limiter/src/main/java/org/miaixz/bus/limiter/support/rate/redis/RedisRatelimiterObject.java +++ /dev/null @@ -1,97 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.limiter.support.rate.redis; - -import org.miaixz.bus.core.lang.Normal; -import org.redisson.RedissonObject; -import org.redisson.api.RFuture; -import org.redisson.client.codec.Codec; -import org.redisson.client.codec.LongCodec; -import org.redisson.client.protocol.RedisCommand; -import org.redisson.client.protocol.RedisCommands; -import org.redisson.command.CommandAsyncExecutor; - -import java.util.Arrays; -import java.util.Objects; - -/** - * @author Kimi Liu - * @since Java 17+ - */ -public class RedisRatelimiterObject extends RedissonObject { - - - public RedisRatelimiterObject(Codec codec, CommandAsyncExecutor commandExecutor, String name) { - super(codec, commandExecutor, name); - } - - public RedisRatelimiterObject(CommandAsyncExecutor commandExecutor, String name) { - super(commandExecutor, name); - } - - public boolean tryAcquire(long permits, double rate, long capacity) { - if (permits > capacity) return false; - return get(tryAcquireAsync(RedisCommands.EVAL_LONG, permits, rate, capacity)) != -1; - } - - private RFuture tryAcquireAsync(RedisCommand command, long permits, double rate, long capacity) { - String hash = Objects.hash(rate, capacity) + Normal.EMPTY; - return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command, - "local capacity = tonumber(ARGV[1])\n" + - "local rate = tonumber(ARGV[2])\n" + - "local acq = tonumber(ARGV[3])\n" + - "if (redis.call('exists',KEYS[1]) == 0 or redis.call('hget',KEYS[1],'hash') ~= ARGV[4]) then\n" + - " -- create\n" + - " redis.call('hset', KEYS[1], 'capacity ', capacity)\n" + - " redis.call('hset', KEYS[1], 'rate', rate)\n" + - " redis.call('hset', KEYS[1], 'permit', capacity-acq)\n" + - " redis.call('hset', KEYS[1], 'hash', ARGV[4])\n" + - " redis.call('expire', KEYS[1],3153600000000)\n" + - " redis.call('hset', KEYS[1], 'pttl',3153600000000000)\n" + - " return capacity-acq\n" + - "end\n" + - "local rate = tonumber(redis.call('hget', KEYS[1],'rate'))\n" + - "local now = redis.call('pttl', KEYS[1])\n" + - "local pttl = tonumber(redis.call('hget', KEYS[1], 'pttl'))\n" + - "local permit = tonumber(redis.call('hget', KEYS[1], 'permit'))\n" + - "local newPermit = permit + ((pttl-now)/1000*rate)\n" + - "if(newPermit >= capacity) then\n" + - " redis.call('hset', KEYS[1], 'permit', capacity-acq)\n" + - " redis.call('hset', KEYS[1], 'pttl', now)\n" + - " return capacity-acq\n" + - "end\n" + - "if(newPermit >= acq) then\n" + - " redis.call('hset', KEYS[1], 'permit', newPermit-acq)\n" + - " redis.call('hset', KEYS[1], 'pttl', now)\n" + - " return newPermit-acq\n" + - "end\n" + - "return -1 ", - Arrays.asList(getName()), - permits, rate, capacity, hash); - } - - -} diff --git a/bus-logger/pom.xml b/bus-logger/pom.xml index d87326df3e..0980740273 100644 --- a/bus-logger/pom.xml +++ b/bus-logger/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-logger - 8.0.0 + 8.0.1 jar ${project.artifactId} @@ -43,10 +43,10 @@ UTF-8 21 21 - 1.3.1 - 3.5.3.Final + 1.3.2 + 3.6.0.Final 1.5.6 - 2.23.1 + 2.23.1 2.0.13 2.7.0 @@ -72,7 +72,7 @@ org.apache.logging.log4j log4j-core - ${log4j2.version} + ${log4j.version} ch.qos.logback diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/Factory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/Factory.java index 7c60b5c1bf..51eb174c45 100755 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/Factory.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/Factory.java @@ -25,193 +25,57 @@ ********************************************************************************/ package org.miaixz.bus.logger; -import org.miaixz.bus.core.xyz.CallerKit; -import org.miaixz.bus.core.xyz.ResourceKit; -import org.miaixz.bus.logger.magic.Log; -import org.miaixz.bus.logger.metric.console.ConsoleFactory; -import org.miaixz.bus.logger.metric.jdk.JdkFactory; - -import java.net.URL; -import java.util.Map; -import java.util.ServiceLoader; -import java.util.concurrent.ConcurrentHashMap; +import org.miaixz.bus.core.instance.Instances; /** - * 日志工厂类 + * 日志工厂接口 * * @author Kimi Liu * @since Java 17+ */ -public abstract class Factory { - - /** - * 日志对象缓存 - */ - private final Map logCache; - /** - * 日志框架名,用于打印当前所用日志框架 - */ - protected String name; - - /** - * 构造 - * - * @param name 日志框架名 - */ - public Factory(String name) { - this.name = name; - logCache = new ConcurrentHashMap<>(); - } - - /** - * 决定日志实现 - * 依次按照顺序检查日志库的jar是否被引入,如果未引入任何日志库, - * 则检查ClassPath下的logging.properties,存在则使用JdkLogFactory, - * 否则使用ConsoleLogFactory - * - * @return 日志实现类 - */ - public static Factory of() { - final Factory factory = create(); - factory.getLog(Factory.class).debug("Use [{}] Logger As Default.", factory.name); - return factory; - } - - /** - * 决定日志实现 - * 依次按照顺序检查日志库的jar是否被引入,如果未引入任何日志库,则检查ClassPath下的logging.properties,存在则使用JdkLogFactory,否则使用ConsoleLogFactory - * - * @return 日志实现类 - */ - private static Factory create() { - final ServiceLoader factories = ServiceLoader.load(Factory.class); - for (Factory factory : factories) { - return factory; - } - - // 未找到任何可支持的日志库时判断依据:当JDK Logging的配置文件位于classpath中,使用JDK Logging,否则使用Console - final URL url = ResourceKit.getResourceUrl("logging.properties"); - return (null != url) ? new JdkFactory() : new ConsoleFactory(); - } - - /** - * @return 当前使用的日志工厂 - */ - public static Factory getCurrentLogFactory() { - return Holder.get(); - } +public interface Factory { /** - * 自定义日志实现 - * - * @param logFactoryClass 日志工厂类 - * @return 自定义的日志工厂类 - */ - public static Factory setCurrentLogFactory(Class logFactoryClass) { - return Holder.set(logFactoryClass); - } - - /** - * 自定义日志实现 - * - * @param factory 日志工厂类对象 - * @return 自定义的日志工厂类 - */ - public static Factory setCurrentLogFactory(Factory factory) { - return Holder.set(factory); - } - - /** - * 获得日志对象 - * - * @param name 日志对象名 - * @return 日志对象 - */ - public static Log get(String name) { - return getCurrentLogFactory().getLog(name); - } - - /** - * 获得日志对象 - * - * @param clazz 日志对应类 - * @return 日志对象 - */ - public static Log get(Class clazz) { - return getCurrentLogFactory().getLog(clazz); - } - - /** - * @return 获得调用者的日志 - */ - public static Log get() { - return get(CallerKit.getCallers()); - } - - /** - * 获取日志框架名,用于打印当前所用日志框架 + * 获取日志框架名,用于打印当前所用日志框架 * * @return 日志框架名 */ - public String getName() { - return this.name; - } + String getName(); /** - * 获得日志对象 + * 创建日志对象 * * @param name 日志对象名 * @return 日志对象 */ - public Log getLog(String name) { - Log log = logCache.get(name); - if (null == log) { - log = createLog(name); - logCache.put(name, log); - } - return log; - } + Supplier create(String name); /** - * 获得日志对象 + * 创建日志对象 * * @param clazz 日志对应类 * @return 日志对象 */ - public Log getLog(Class clazz) { - Log log = logCache.get(clazz); - if (null == log) { - log = createLog(clazz); - logCache.put(clazz, log); - } - return log; - } + Supplier create(Class clazz); /** - * 创建日志对象 + * 获得日志对象(单例) * * @param name 日志对象名 * @return 日志对象 */ - public abstract Log createLog(String name); + default Supplier get(final String name) { + return Instances.get(getName() + name, () -> create(name)); + } /** - * 创建日志对象 + * 获得日志对象(单例) * * @param clazz 日志对应类 * @return 日志对象 */ - public abstract Log createLog(Class clazz); - - /** - * 检查日志实现是否存在 - * 此方法仅用于检查所提供的日志相关类是否存在,当传入的日志类类不存在时抛出ClassNotFoundException - * 此方法的作用是在detectLogFactory方法自动检测所用日志时,如果实现类不存在,调用此方法会自动抛出异常,从而切换到下一种日志的检测 - * - * @param logClassName 日志实现相关类 - */ - protected void checkLogExist(Class logClassName) { - + default Supplier get(final Class clazz) { + return Instances.get(getName() + clazz.getName(), () -> create(clazz)); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/Holder.java b/bus-logger/src/main/java/org/miaixz/bus/logger/Holder.java index db336dd999..9719e54b99 100755 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/Holder.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/Holder.java @@ -25,55 +25,56 @@ ********************************************************************************/ package org.miaixz.bus.logger; -import org.miaixz.bus.logger.metric.commons.ApacheCommonsFactory; +import org.miaixz.bus.core.instance.Instances; +import org.miaixz.bus.core.xyz.ReflectKit; +import org.miaixz.bus.core.xyz.ResourceKit; +import org.miaixz.bus.core.xyz.SPIKit; +import org.miaixz.bus.logger.metric.commons.CommonsFactory; import org.miaixz.bus.logger.metric.console.ConsoleFactory; import org.miaixz.bus.logger.metric.jdk.JdkFactory; -import org.miaixz.bus.logger.metric.log4j2.Log4J2Factory; +import org.miaixz.bus.logger.metric.log4j.Log4JFactory; import org.miaixz.bus.logger.metric.slf4j.Slf4JFactory; +import java.net.URL; + /** - * 全局日志提供者 - * 用于减少日志提供者创建,减少日志库探测 + * 日志引擎简单工厂(静态工厂)类 * * @author Kimi Liu * @since Java 17+ */ public class Holder { - private static final Object lock = new Object(); - private static volatile Factory currentFactory; + /** + * 默认构造 + */ + public Holder() { + + } /** - * 获取单例日志提供者类,如果不存在创建之 + * 根据用户引入的模板引擎jar,自动创建对应的模板引擎对象 * - * @return 当前使用的日志提供者 + * @return the factory */ public static Factory get() { - if (null == currentFactory) { - synchronized (lock) { - if (null == currentFactory) { - currentFactory = Factory.of(); - } - } - } - return currentFactory; + return InstanceHolder.INSTANCE; } /** - * 自定义日志实现 + * 自定义默认日志实现 * - * @param logFactoryClass 日志提供者类 - * @return 自定义的日志提供者类 + * @param clazz 日志工厂类 * @see Slf4JFactory - * @see Log4J2Factory - * @see ApacheCommonsFactory + * @see Log4JFactory + * @see CommonsFactory * @see JdkFactory * @see ConsoleFactory */ - public static Factory set(Class logFactoryClass) { + public static void set(final Class clazz) { try { - return set(logFactoryClass.getConstructor().newInstance()); - } catch (Exception e) { + set(ReflectKit.newInstance(clazz)); + } catch (final Exception e) { throw new IllegalArgumentException("Can not instance LogFactory class!", e); } } @@ -81,18 +82,65 @@ public static Factory set(Class logFactoryClass) { /** * 自定义日志实现 * - * @param factory 日志提供者类对象 - * @return 自定义的日志提供者类 + * @param factory 日志工厂对象 * @see Slf4JFactory - * @see Log4J2Factory - * @see ApacheCommonsFactory + * @see Log4JFactory + * @see CommonsFactory * @see JdkFactory * @see ConsoleFactory */ - public static Factory set(Factory factory) { - factory.getLog(Holder.class).debug("Custom Use [{}] Logger.", factory.name); - currentFactory = factory; - return currentFactory; + public static void set(final Factory factory) { + Instances.put(Holder.class.getName(), factory); + factory.create(Holder.class).debug("Custom Use [{}] Logger.", factory.getName()); + } + + /** + * 创建指定日志实现引擎 + * + * @param clazz 引擎类 + * @return {@link Factory} + */ + public static Factory create(final Class clazz) { + return ReflectKit.newInstance(clazz); + } + + /** + * 决定日志实现 + * 依次按照顺序检查日志库的jar是否被引入,如果未引入任何日志库,则检查ClassPath下的logging.properties, + * 存在则使用JdkLogFactory,否则使用ConsoleLogFactory + * + * @return 日志实现类 + */ + public static Factory create() { + final Factory engine = doCreate(); + engine.create(Registry.class).debug("Use [{}] Logger As Default.", engine.getName()); + return engine; + } + + /** + * 决定日志实现 + * 依次按照顺序检查日志库的jar是否被引入,如果未引入任何日志库,则检查ClassPath下的logging.properties,存在则使用JdkLogFactory,否则使用ConsoleLogFactory + * + * @return 日志实现类 + */ + private static Factory doCreate() { + final Factory engine = SPIKit.loadFirstAvailable(Factory.class); + if (null != engine) { + return engine; + } + + // 未找到任何可支持的日志库时判断依据:当JDK Logging的配置文件位于classpath中,使用JDK Logging,否则使用Console + final URL url = ResourceKit.getResourceUrl("logging.properties"); + return (null != url) ? new JdkFactory() : new ConsoleFactory(); + } + + /** + * 嵌套使用Instances.get时在JDK9+会引起Recursive update问题,此处日志单独使用单例 + */ + private static class InstanceHolder { + + public static final Factory INSTANCE = create(); + } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/Level.java b/bus-logger/src/main/java/org/miaixz/bus/logger/Level.java old mode 100755 new mode 100644 index ad2488cf4f..dfce104655 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/Level.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/Level.java @@ -65,4 +65,5 @@ public enum Level { * 'OFF' log. */ OFF + } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/Logger.java b/bus-logger/src/main/java/org/miaixz/bus/logger/Logger.java old mode 100755 new mode 100644 index d6682c2777..c8cbf821af --- a/bus-logger/src/main/java/org/miaixz/bus/logger/Logger.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/Logger.java @@ -27,237 +27,241 @@ import org.miaixz.bus.core.xyz.CallerKit; import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.magic.Log; /** - * 静态日志类,用于在不引入日志对象的情况下打印日志 + * 静态日志类,用于在不引入日志对象的情况下打印日志 * * @author Kimi Liu * @since Java 17+ */ -public final class Logger { +public class Logger { private static final String FQCN = Logger.class.getName(); - private Logger() { + /** + * 默认构造 + */ + public Logger() { } /** - * Trace等级日志,小于debug - * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!! + * Trace等级日志,小于debug + * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用 * - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void trace(String format, Object... arguments) { - trace(Factory.get(CallerKit.getCallers()), format, arguments); + public static void trace(final String format, final Object... args) { + trace(get(), format, args); } /** - * Trace等级日志,小于Debug + * Trace等级日志,小于Debug * - * @param log 日志对象 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param supplier 日志对象 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void trace(Log log, String format, Object... arguments) { - log.trace(FQCN, null, format, arguments); + public static void trace(final Supplier supplier, final String format, final Object... args) { + supplier.trace(FQCN, null, format, args); } /** - * Debug等级日志,小于Info - * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!! + * Debug等级日志,小于Info + * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用 * - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void debug(String format, Object... arguments) { - debug(Factory.get(CallerKit.getCallers()), format, arguments); + public static void debug(final String format, final Object... args) { + debug(get(), format, args); } /** - * Debug等级日志,小于Info + * Debug等级日志,小于Info * - * @param log 日志对象 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param supplier 日志对象 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void debug(Log log, String format, Object... arguments) { - log.debug(FQCN, null, format, arguments); + public static void debug(final Supplier supplier, final String format, final Object... args) { + supplier.debug(FQCN, null, format, args); } /** - * Info等级日志,小于Warn - * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!! + * Info等级日志,小于Warn + * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用 * - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void info(String format, Object... arguments) { - info(Factory.get(CallerKit.getCallers()), format, arguments); + public static void info(final String format, final Object... args) { + info(get(), format, args); } /** - * Info等级日志,小于Warn + * Info等级日志,小于Warn * - * @param log 日志对象 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param supplier 日志对象 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void info(Log log, String format, Object... arguments) { - log.info(FQCN, null, format, arguments); + public static void info(final Supplier supplier, final String format, final Object... args) { + supplier.info(FQCN, null, format, args); } /** - * Warn等级日志,小于Error - * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!! + * Warn等级日志,小于Error + * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用 * - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void warn(String format, Object... arguments) { - warn(Factory.get(CallerKit.getCallers()), format, arguments); + public static void warn(final String format, final Object... args) { + warn(get(), format, args); } /** - * Warn等级日志,小于Error - * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!! + * Warn等级日志,小于Error + * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用 * - * @param e 需在日志中堆栈打印的异常 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param e 需在日志中堆栈打印的异常 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void warn(Throwable e, String format, Object... arguments) { - warn(Factory.get(CallerKit.getCallers()), e, StringKit.format(format, arguments)); + public static void warn(final Throwable e, final String format, final Object... args) { + warn(get(), e, StringKit.format(format, args)); } /** - * Warn等级日志,小于Error + * Warn等级日志,小于Error * - * @param log 日志对象 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param supplier 日志对象 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void warn(Log log, String format, Object... arguments) { - warn(log, null, format, arguments); + public static void warn(final Supplier supplier, final String format, final Object... args) { + warn(supplier, null, format, args); } /** - * Warn等级日志,小于Error + * Warn等级日志,小于Error * - * @param log 日志对象 - * @param e 需在日志中堆栈打印的异常 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param supplier 日志对象 + * @param e 需在日志中堆栈打印的异常 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void warn(Log log, Throwable e, String format, Object... arguments) { - log.warn(FQCN, e, format, arguments); + public static void warn(final Supplier supplier, final Throwable e, final String format, final Object... args) { + supplier.warn(FQCN, e, format, args); } /** * Error等级日志 - * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!! + * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用 * * @param e 需在日志中堆栈打印的异常 */ - public static void error(Throwable e) { - error(Factory.get(CallerKit.getCallers()), e); + public static void error(final Throwable e) { + error(get(), e); } /** * Error等级日志 - * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!! + * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用 * - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void error(String format, Object... arguments) { - error(Factory.get(CallerKit.getCallers()), format, arguments); + public static void error(final String format, final Object... args) { + error(get(), format, args); } /** * Error等级日志 - * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!! + * 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用 * - * @param e 需在日志中堆栈打印的异常 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param e 需在日志中堆栈打印的异常 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void error(Throwable e, String format, Object... arguments) { - error(Factory.get(CallerKit.getCallers()), e, format, arguments); + public static void error(final Throwable e, final String format, final Object... args) { + error(get(), e, format, args); } /** * Error等级日志 * - * @param log 日志对象 - * @param e 需在日志中堆栈打印的异常 + * @param supplier 日志对象 + * @param e 需在日志中堆栈打印的异常 */ - public static void error(Log log, Throwable e) { - error(log, e, e.getMessage()); + public static void error(final Supplier supplier, final Throwable e) { + error(supplier, e, e.getMessage()); } /** * Error等级日志 * - * @param log 日志对象 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param supplier 日志对象 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void error(Log log, String format, Object... arguments) { - error(log, null, format, arguments); + public static void error(final Supplier supplier, final String format, final Object... args) { + error(supplier, null, format, args); } /** * Error等级日志 * - * @param log 日志对象 - * @param e 需在日志中堆栈打印的异常 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param supplier 日志对象 + * @param e 需在日志中堆栈打印的异常 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void error(Log log, Throwable e, String format, Object... arguments) { - log.error(FQCN, e, format, arguments); + public static void error(final Supplier supplier, final Throwable e, final String format, final Object... args) { + supplier.error(FQCN, e, format, args); } /** * 打印日志 * - * @param level 日志级别 - * @param t 需在日志中堆栈打印的异常 - * @param format 格式文本,{} 代表变量 - * @param arguments 变量对应的参数 + * @param level 日志级别 + * @param t 需在日志中堆栈打印的异常 + * @param format 格式文本,{} 代表变量 + * @param args 变量对应的参数 */ - public static void log(Level level, Throwable t, String format, Object... arguments) { - Factory.get(CallerKit.getCallers()).log(FQCN, level, t, format, arguments); + public static void log(final Level level, final Throwable t, final String format, final Object... args) { + get().log(FQCN, level, t, format, args); } /** - * 获得Log + * 获得日志, 自动判定日志发出者 * - * @param clazz 日志发出的类 - * @return Log + * @return the supplier */ - public static Log get(Class clazz) { - return Factory.get(clazz); + public static Supplier get() { + return get(CallerKit.getCallers()); } /** - * 获得Log + * 获得日志 * - * @param name 自定义的日志发出者名称 - * @return Log + * @param clazz 日志发出的类 + * @return the supplier */ - public static Log get(String name) { - return Factory.get(name); + public static Supplier get(Class clazz) { + return Registry.get(clazz); } /** - * @return 获得日志, 自动判定日志发出者 + * 获得日志 + * + * @param name 日志发出者名称 + * @return the supplier */ - public static Log get() { - return get(CallerKit.getCallers()); + public static Supplier get(String name) { + return Registry.get(name); } /** diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/AbstractAware.java b/bus-logger/src/main/java/org/miaixz/bus/logger/Provider.java old mode 100755 new mode 100644 similarity index 52% rename from bus-logger/src/main/java/org/miaixz/bus/logger/AbstractAware.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/Provider.java index efb8da7fba..b6e3e1cf91 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/AbstractAware.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/Provider.java @@ -25,9 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.logger; -import org.miaixz.bus.core.lang.Normal; +import org.miaixz.bus.core.xyz.ExceptionKit; import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.magic.Log; import java.io.Serializable; @@ -38,12 +37,26 @@ * @author Kimi Liu * @since Java 17+ */ -public abstract class AbstractAware implements Log, Serializable { +public abstract class Provider implements Supplier, Serializable { - private static final String FQCN = AbstractAware.class.getName(); + private static final long serialVersionUID = -1L; + + private static final String FQCN = Provider.class.getName(); + + /** + * 日志框架名 + */ + protected String name; + + /** + * 默认构造 + */ + public Provider() { + + } @Override - public boolean isEnabled(Level level) { + public boolean isEnabled(final Level level) { switch (level) { case TRACE: return isTrace(); @@ -61,108 +74,108 @@ public boolean isEnabled(Level level) { } @Override - public void trace(Throwable t) { - trace(t, (null == t) ? Normal.NULL : t.getMessage()); + public void trace(final Throwable t) { + trace(t, ExceptionKit.getSimpleMessage(t)); } @Override - public void trace(String format, Object... arguments) { - trace(null, format, arguments); + public void trace(final String format, final Object... args) { + trace(null, format, args); } @Override - public void trace(Throwable t, String format, Object... arguments) { - trace(FQCN, t, format, arguments); + public void trace(final Throwable t, final String format, final Object... args) { + trace(FQCN, t, format, args); } @Override - public void debug(Throwable t) { - debug(t, (null == t) ? Normal.NULL : t.getMessage()); + public void debug(final Throwable t) { + debug(t, ExceptionKit.getSimpleMessage(t)); } @Override - public void debug(String format, Object... arguments) { - if (null != arguments && 1 == arguments.length && arguments[0] instanceof Throwable) { - debug((Throwable) arguments[0], format); + public void debug(final String format, final Object... args) { + if (null != args && 1 == args.length && args[0] instanceof Throwable) { + debug((Throwable) args[0], format); } else { - debug(null, format, arguments); + debug(null, format, args); } } @Override - public void debug(Throwable t, String format, Object... arguments) { - debug(FQCN, t, format, arguments); + public void debug(final Throwable t, final String format, final Object... args) { + debug(FQCN, t, format, args); } @Override - public void info(Throwable t) { - info(t, (null == t) ? Normal.NULL : t.getMessage()); + public void info(final Throwable t) { + info(t, ExceptionKit.getSimpleMessage(t)); } @Override - public void info(String format, Object... arguments) { - if (null != arguments && 1 == arguments.length && arguments[0] instanceof Throwable) { - info((Throwable) arguments[0], format); + public void info(final String format, final Object... args) { + if (null != args && 1 == args.length && args[0] instanceof Throwable) { + info((Throwable) args[0], format); } else { - info(null, format, arguments); + info(null, format, args); } } @Override - public void info(Throwable t, String format, Object... arguments) { - info(FQCN, t, format, arguments); + public void info(final Throwable t, final String format, final Object... args) { + info(FQCN, t, format, args); } @Override - public void warn(Throwable t) { - warn(t, (null == t) ? Normal.NULL : t.getMessage()); + public void warn(final Throwable t) { + warn(t, ExceptionKit.getSimpleMessage(t)); } @Override - public void warn(String format, Object... arguments) { - if (null != arguments && 1 == arguments.length && arguments[0] instanceof Throwable) { - warn((Throwable) arguments[0], format); + public void warn(final String format, final Object... args) { + if (null != args && 1 == args.length && args[0] instanceof Throwable) { + warn((Throwable) args[0], format); } else { - warn(null, format, arguments); + warn(null, format, args); } } @Override - public void warn(Throwable t, String format, Object... arguments) { - warn(FQCN, t, format, arguments); + public void warn(final Throwable t, final String format, final Object... args) { + warn(FQCN, t, format, args); } @Override - public void error(Throwable t) { - this.error(t, (null == t) ? Normal.NULL : t.getMessage()); + public void error(final Throwable t) { + this.error(t, ExceptionKit.getSimpleMessage(t)); } @Override - public void error(String format, Object... arguments) { - if (null != arguments && 1 == arguments.length && arguments[0] instanceof Throwable) { - error((Throwable) arguments[0], format); + public void error(final String format, final Object... args) { + if (null != args && 1 == args.length && args[0] instanceof Throwable) { + error((Throwable) args[0], format); } else { - error(null, format, arguments); + error(null, format, args); } } @Override - public void error(Throwable t, String format, Object... arguments) { - error(FQCN, t, format, arguments); + public void error(final Throwable t, final String format, final Object... args) { + error(FQCN, t, format, args); } @Override - public void log(Level level, String format, Object... arguments) { - if (null != arguments && 1 == arguments.length && arguments[0] instanceof Throwable) { - log(level, (Throwable) arguments[0], format); + public void log(final Level level, final String format, final Object... args) { + if (null != args && 1 == args.length && args[0] instanceof Throwable) { + log(level, (Throwable) args[0], format); } else { - log(level, null, format, arguments); + log(level, null, format, args); } } @Override - public void log(Level level, Throwable t, String format, Object... arguments) { - this.log(FQCN, level, t, format, arguments); + public void log(final Level level, final Throwable t, final String format, final Object... args) { + this.log(FQCN, level, t, format, args); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/Registry.java b/bus-logger/src/main/java/org/miaixz/bus/logger/Registry.java new file mode 100644 index 0000000000..2666925dac --- /dev/null +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/Registry.java @@ -0,0 +1,63 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.logger; + +/** + * 日志简单工厂类,提供带有缓存的日志对象创建 + * + * @author Kimi Liu + * @since Java 17+ + */ +public abstract class Registry { + + /** + * 默认构造 + */ + public Registry() { + + } + + /** + * 获得日志对象 + * + * @param name 日志对象名 + * @return 日志对象 + */ + public static Supplier get(final String name) { + return Holder.get().get(name); + } + + /** + * 获得日志对象 + * + * @param clazz 日志对应类 + * @return 日志对象 + */ + public static Supplier get(final Class clazz) { + return Holder.get().get(clazz); + } + +} diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/Log.java b/bus-logger/src/main/java/org/miaixz/bus/logger/Supplier.java old mode 100755 new mode 100644 similarity index 62% rename from bus-logger/src/main/java/org/miaixz/bus/logger/magic/Log.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/Supplier.java index 8b8663b0af..bb6adc379d --- a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/Log.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/Supplier.java @@ -23,9 +23,11 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.logger.magic; +package org.miaixz.bus.logger; -import org.miaixz.bus.logger.Level; +import org.miaixz.bus.core.xyz.CallerKit; +import org.miaixz.bus.logger.magic.level.Error; +import org.miaixz.bus.logger.magic.level.*; /** * 日志统一接口 @@ -33,10 +35,41 @@ * @author Kimi Liu * @since Java 17+ */ -public interface Log extends TraceLog, DebugLog, InfoLog, WarnLog, ErrorLog { +public interface Supplier extends Trace, Debug, Info, Warn, Error { /** - * @return 日志对象的Name + * 获得Log + * + * @param clazz 日志发出的类 + * @return the supplier + */ + static Supplier get(final Class clazz) { + return Registry.get(clazz); + } + + /** + * 获得Log + * + * @param name 自定义的日志发出者名称 + * @return the supplier + */ + static Supplier get(final String name) { + return Registry.get(name); + } + + /** + * 获得日志,自动判定日志发出者 + * + * @return the supplier + */ + static Supplier get() { + return Registry.get(CallerKit.getCallers()); + } + + /** + * 日志对象名称 + * + * @return the string */ String getName(); @@ -44,38 +77,38 @@ public interface Log extends TraceLog, DebugLog, InfoLog, WarnLog, ErrorLog { * 是否开启指定日志 * * @param level 日志级别 - * @return 是否开启指定级别 + * @return the true/false */ boolean isEnabled(Level level); /** * 打印指定级别的日志 * - * @param level 级别 - * @param format 消息模板 - * @param arguments 参数 + * @param level 级别 + * @param format 消息模板 + * @param args 参数 */ - void log(Level level, String format, Object... arguments); + void log(Level level, String format, Object... args); /** - * 打印 指定级别的日志 + * 打印指定级别的日志 * - * @param level 级别 - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param level 级别 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void log(Level level, Throwable t, String format, Object... arguments); + void log(Level level, Throwable t, String format, Object... args); /** - * 打印 ERROR 等级的日志 + * 打印ERROR等级的日志 * - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 - * @param level 级别 - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 + * @param level 级别 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void log(String fqcn, Level level, Throwable t, String format, Object... arguments); + void log(String fqcn, Level level, Throwable t, String format, Object... args); } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/AbstractFactory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/AbstractFactory.java new file mode 100755 index 0000000000..329da23b5e --- /dev/null +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/AbstractFactory.java @@ -0,0 +1,72 @@ +/********************************************************************************* + * * + * The MIT License (MIT) * + * * + * Copyright (c) 2015-2024 miaixz.org and other contributors. * + * * + * 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 org.miaixz.bus.logger.magic; + +import org.miaixz.bus.logger.Factory; + +/** + * 抽象日志 + * + * @author Kimi Liu + * @since Java 17+ + */ +public abstract class AbstractFactory implements Factory { + + /** + * 日志框架名,用于打印当前所用日志框架 + */ + private final String name; + + /** + * 构造 + * + * @param name 日志框架名 + */ + public AbstractFactory(final String name) { + this.name = name; + } + + /** + * 获取日志框架名,用于打印当前所用日志框架 + * + * @return 日志框架名 + */ + public String getName() { + return this.name; + } + + /** + * 检查日志实现是否存在 + * 此方法仅用于检查所提供的日志相关类是否存在,当传入的日志类类不存在时抛出ClassNotFoundException + * 此方法的作用是在detectLogFactory方法自动检测所用日志时,如果实现类不存在,调用此方法会自动抛出异常,从而切换到下一种日志的检测。 + * + * @param clazz 日志实现相关类 + */ + protected void check(final Class clazz) { + // 不做任何操作 + } + +} diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/DebugLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Debug.java old mode 100755 new mode 100644 similarity index 79% rename from bus-logger/src/main/java/org/miaixz/bus/logger/magic/DebugLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Debug.java index b96692c2dc..a0d3e031e7 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/DebugLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Debug.java @@ -23,18 +23,20 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.logger.magic; +package org.miaixz.bus.logger.magic.level; /** - * DEBUG级别日志接口 + * DEBUG 级别日志 * * @author Kimi Liu * @since Java 17+ */ -public interface DebugLog { +public interface Debug { /** - * @return DEBUG 等级是否开启 + * DEBUG 等级是否开启 + * + * @return the true/false */ boolean isDebug(); @@ -48,28 +50,28 @@ public interface DebugLog { /** * 打印 DEBUG 等级的日志 * - * @param format 消息模板 - * @param arguments 参数 + * @param format 消息模板 + * @param args 参数 */ - void debug(String format, Object... arguments); + void debug(String format, Object... args); /** * 打印 DEBUG 等级的日志 * - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void debug(Throwable t, String format, Object... arguments); + void debug(Throwable t, String format, Object... args); /** * 打印 DEBUG 等级的日志 * - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void debug(String fqcn, Throwable t, String format, Object... arguments); + void debug(String fqcn, Throwable t, String format, Object... args); } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/ErrorLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Error.java old mode 100755 new mode 100644 similarity index 79% rename from bus-logger/src/main/java/org/miaixz/bus/logger/magic/ErrorLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Error.java index 34f4703805..1e832a9779 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/ErrorLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Error.java @@ -23,18 +23,20 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.logger.magic; +package org.miaixz.bus.logger.magic.level; /** - * ERROR级别日志接口 + * ERROR级别日志 * * @author Kimi Liu * @since Java 17+ */ -public interface ErrorLog { +public interface Error { /** - * @return ERROR 等级是否开启 + * ERROR 等级是否开启 + * + * @return the true/false */ boolean isError(); @@ -48,28 +50,28 @@ public interface ErrorLog { /** * 打印 ERROR 等级的日志 * - * @param format 消息模板 - * @param arguments 参数 + * @param format 消息模板 + * @param args 参数 */ - void error(String format, Object... arguments); + void error(String format, Object... args); /** * 打印 ERROR 等级的日志 * - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void error(Throwable t, String format, Object... arguments); + void error(Throwable t, String format, Object... args); /** * 打印 ERROR 等级的日志 * - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void error(String fqcn, Throwable t, String format, Object... arguments); + void error(String fqcn, Throwable t, String format, Object... args); } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/InfoLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Info.java old mode 100755 new mode 100644 similarity index 80% rename from bus-logger/src/main/java/org/miaixz/bus/logger/magic/InfoLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Info.java index 3454f224b8..34269e0e87 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/InfoLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Info.java @@ -23,18 +23,20 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.logger.magic; +package org.miaixz.bus.logger.magic.level; /** - * INFO级别日志接口 + * INFO 级别日志 * * @author Kimi Liu * @since Java 17+ */ -public interface InfoLog { +public interface Info { /** - * @return INFO 等级是否开启 + * INFO 等级是否开启 + * + * @return the true/false */ boolean isInfo(); @@ -48,28 +50,28 @@ public interface InfoLog { /** * 打印 INFO 等级的日志 * - * @param format 消息模板 - * @param arguments 参数 + * @param format 消息模板 + * @param args 参数 */ - void info(String format, Object... arguments); + void info(String format, Object... args); /** * 打印 INFO 等级的日志 * - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void info(Throwable t, String format, Object... arguments); + void info(Throwable t, String format, Object... args); /** * 打印 INFO 等级的日志 * - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void info(String fqcn, Throwable t, String format, Object... arguments); + void info(String fqcn, Throwable t, String format, Object... args); } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/TraceLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Trace.java old mode 100755 new mode 100644 similarity index 79% rename from bus-logger/src/main/java/org/miaixz/bus/logger/magic/TraceLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Trace.java index f963c9d921..050af55f62 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/TraceLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Trace.java @@ -23,18 +23,20 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.logger.magic; +package org.miaixz.bus.logger.magic.level; /** - * TRACE级别日志接口 + * TRACE 级别日志 * * @author Kimi Liu * @since Java 17+ */ -public interface TraceLog { +public interface Trace { /** - * @return TRACE 等级是否开启 + * TRACE 等级是否开启 + * + * @return the true/false */ boolean isTrace(); @@ -48,28 +50,28 @@ public interface TraceLog { /** * 打印 TRACE 等级的日志 * - * @param format 消息模板 - * @param arguments 参数 + * @param format 消息模板 + * @param args 参数 */ - void trace(String format, Object... arguments); + void trace(String format, Object... args); /** * 打印 TRACE 等级的日志 * - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void trace(Throwable t, String format, Object... arguments); + void trace(Throwable t, String format, Object... args); /** * 打印 TRACE 等级的日志 * - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void trace(String fqcn, Throwable t, String format, Object... arguments); + void trace(String fqcn, Throwable t, String format, Object... args); } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/WarnLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Warn.java old mode 100755 new mode 100644 similarity index 80% rename from bus-logger/src/main/java/org/miaixz/bus/logger/magic/WarnLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Warn.java index 55ffca0ed1..631ec66010 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/WarnLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/Warn.java @@ -23,18 +23,20 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.logger.magic; +package org.miaixz.bus.logger.magic.level; /** - * WARN级别日志接口 + * WARN级别日志 * * @author Kimi Liu * @since Java 17+ */ -public interface WarnLog { +public interface Warn { /** - * @return WARN 等级是否开启 + * WARN 等级是否开启 + * + * @return the true/false */ boolean isWarn(); @@ -48,28 +50,28 @@ public interface WarnLog { /** * 打印 WARN 等级的日志 * - * @param format 消息模板 - * @param arguments 参数 + * @param format 消息模板 + * @param args 参数 */ - void warn(String format, Object... arguments); + void warn(String format, Object... args); /** * 打印 WARN 等级的日志 * - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void warn(Throwable t, String format, Object... arguments); + void warn(Throwable t, String format, Object... args); /** * 打印 WARN 等级的日志 * - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 - * @param t 错误对象 - * @param format 消息模板 - * @param arguments 参数 + * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 + * @param t 错误对象 + * @param format 消息模板 + * @param args 参数 */ - void warn(String fqcn, Throwable t, String format, Object... arguments); + void warn(String fqcn, Throwable t, String format, Object... args); } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/package-info.java new file mode 100644 index 0000000000..4c119db6ce --- /dev/null +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/level/package-info.java @@ -0,0 +1,7 @@ +/** + * 日志级别打印接口 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.logger.magic.level; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/package-info.java index 071c57111e..8a0c5efc3c 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/magic/package-info.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/magic/package-info.java @@ -1,7 +1,7 @@ /** - * 按照日志级别定义的日志打印接口定义 + * 日志级别级相关 * * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.logger.magic; \ No newline at end of file +package org.miaixz.bus.logger.magic; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/ApacheCommonsFactory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/CommonsFactory.java old mode 100755 new mode 100644 similarity index 78% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/ApacheCommonsFactory.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/CommonsFactory.java index f76a40fb07..3a40c710bf --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/ApacheCommonsFactory.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/CommonsFactory.java @@ -25,36 +25,39 @@ ********************************************************************************/ package org.miaixz.bus.logger.metric.commons; -import org.miaixz.bus.logger.Factory; -import org.miaixz.bus.logger.magic.Log; +import org.miaixz.bus.logger.Supplier; +import org.miaixz.bus.logger.magic.AbstractFactory; /** - * Apache Commons Logging + * commons logging * * @author Kimi Liu * @since Java 17+ */ -public class ApacheCommonsFactory extends Factory { +public class CommonsFactory extends AbstractFactory { - public ApacheCommonsFactory() { - super("Apache Common Logging"); - checkLogExist(org.apache.commons.logging.LogFactory.class); + /** + * 构造 + */ + public CommonsFactory() { + super("Common Logging"); + check(org.apache.commons.logging.LogFactory.class); } @Override - public Log createLog(String name) { - return new ApacheCommonsLog(name); + public Supplier create(final String name) { + return new CommonsProvider(name); } @Override - public Log createLog(Class clazz) { - return new ApacheCommonsLog(clazz); + public Supplier create(final Class clazz) { + return new CommonsProvider(clazz); } @Override - protected void checkLogExist(Class logClassName) { - super.checkLogExist(logClassName); - getLog(ApacheCommonsFactory.class); + protected void check(final Class clazz) { + super.check(clazz); + create(CommonsFactory.class); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/ApacheCommonsLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/CommonsProvider.java old mode 100755 new mode 100644 similarity index 66% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/ApacheCommonsLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/CommonsProvider.java index a119a22f8b..4dc93b2c7b --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/ApacheCommonsLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/CommonsProvider.java @@ -29,33 +29,53 @@ import org.apache.commons.logging.LogFactory; import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.AbstractAware; import org.miaixz.bus.logger.Level; +import org.miaixz.bus.logger.Provider; /** - * Apache Commons Logging log. + * commons logging * * @author Kimi Liu * @since Java 17+ */ -public class ApacheCommonsLog extends AbstractAware { +public class CommonsProvider extends Provider { - private final transient Log logger; - private final String name; + private static final long serialVersionUID = -1L; - public ApacheCommonsLog(Log logger, String name) { - this.logger = logger; - this.name = name; - } + /** + * 日志门面 + */ + private final transient Log logger; - public ApacheCommonsLog(Class clazz) { + /** + * 构造 + * + * @param clazz 日志实现类 + */ + public CommonsProvider(final Class clazz) { this(LogFactory.getLog(clazz), null == clazz ? Normal.NULL : clazz.getName()); } - public ApacheCommonsLog(String name) { + /** + * 构造 + * + * @param name 名称 + */ + public CommonsProvider(final String name) { this(LogFactory.getLog(name), name); } + /** + * 构造 + * + * @param logger 日志对象 + * @param name 名称 + */ + public CommonsProvider(final Log logger, final String name) { + this.logger = logger; + this.name = name; + } + @Override public String getName() { return this.name; @@ -67,9 +87,9 @@ public boolean isTrace() { } @Override - public void trace(String fqcn, Throwable t, String format, Object... arguments) { + public void trace(final String fqcn, final Throwable t, final String format, final Object... args) { if (isTrace()) { - logger.trace(StringKit.format(format, arguments), t); + logger.trace(StringKit.format(format, args), t); } } @@ -79,9 +99,9 @@ public boolean isDebug() { } @Override - public void debug(String fqcn, Throwable t, String format, Object... arguments) { + public void debug(final String fqcn, final Throwable t, final String format, final Object... args) { if (isDebug()) { - logger.debug(StringKit.format(format, arguments), t); + logger.debug(StringKit.format(format, args), t); } } @@ -91,9 +111,9 @@ public boolean isInfo() { } @Override - public void info(String fqcn, Throwable t, String format, Object... arguments) { + public void info(final String fqcn, final Throwable t, final String format, final Object... args) { if (isInfo()) { - logger.info(StringKit.format(format, arguments), t); + logger.info(StringKit.format(format, args), t); } } @@ -103,20 +123,20 @@ public boolean isWarn() { } @Override - public void warn(String format, Object... arguments) { + public void warn(final String format, final Object... args) { if (isWarn()) { - logger.warn(StringKit.format(format, arguments)); + logger.warn(StringKit.format(format, args)); } } @Override - public void warn(Throwable t, String format, Object... arguments) { + public void warn(final Throwable t, final String format, final Object... args) { } @Override - public void warn(String fqcn, Throwable t, String format, Object... arguments) { + public void warn(final String fqcn, final Throwable t, final String format, final Object... args) { if (isWarn()) { - logger.warn(StringKit.format(format, arguments), t); + logger.warn(StringKit.format(format, args), t); } } @@ -126,29 +146,30 @@ public boolean isError() { } @Override - public void error(String fqcn, Throwable t, String format, Object... arguments) { + public void error(final String fqcn, final Throwable t, final String format, final Object... args) { if (isError()) { - logger.warn(StringKit.format(format, arguments), t); + logger.warn(StringKit.format(format, args), t); } + } @Override - public void log(String fqcn, Level level, Throwable t, String format, Object... arguments) { + public void log(final String fqcn, final Level level, final Throwable t, final String format, final Object... args) { switch (level) { case TRACE: - trace(t, format, arguments); + trace(t, format, args); break; case DEBUG: - debug(t, format, arguments); + debug(t, format, args); break; case INFO: - info(t, format, arguments); + info(t, format, args); break; case WARN: - warn(t, format, arguments); + warn(t, format, args); break; case ERROR: - error(t, format, arguments); + error(t, format, args); break; default: throw new Error(StringKit.format("Can not identify level: {}", level)); diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/package-info.java index 1a230553e3..b35911e307 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/package-info.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/commons/package-info.java @@ -1,7 +1,7 @@ /** - * Apache-Commons-Logging日志库的实现封装 + * commons-logging 实现封装 * * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.logger.metric.commons; \ No newline at end of file +package org.miaixz.bus.logger.metric.commons; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorFactory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorFactory.java old mode 100755 new mode 100644 index 37ae06b01b..04218ba217 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorFactory.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorFactory.java @@ -25,29 +25,32 @@ ********************************************************************************/ package org.miaixz.bus.logger.metric.console; -import org.miaixz.bus.logger.Factory; -import org.miaixz.bus.logger.magic.Log; +import org.miaixz.bus.logger.Supplier; +import org.miaixz.bus.logger.magic.AbstractFactory; /** - * 利用System.out.println()打印彩色日志 + * System.out.println 打印彩色日志 * * @author Kimi Liu * @since Java 17+ */ -public class ConsoleColorFactory extends Factory { +public class ConsoleColorFactory extends AbstractFactory { + /** + * 构造 + */ public ConsoleColorFactory() { - super("Console Ansi4BitColor Logging"); + super("Console Color Logging"); } @Override - public Log createLog(String name) { - return new ConsoleColorLog(name); + public Supplier create(final String name) { + return new ConsoleColorProvider(name); } @Override - public Log createLog(Class clazz) { - return new ConsoleColorLog(clazz); + public Supplier create(final Class clazz) { + return new ConsoleColorProvider(clazz); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorProvider.java old mode 100755 new mode 100644 similarity index 83% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorProvider.java index e3f5c4db6b..a240f1e752 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleColorProvider.java @@ -35,12 +35,14 @@ import java.util.function.Function; /** - * 利用System.out.println()打印彩色日志 + * System.out.println 打印彩色日志 * * @author Kimi Liu * @since Java 17+ */ -public class ConsoleColorLog extends ConsoleLog { +public class ConsoleColorProvider extends ConsoleProvider { + + private static final long serialVersionUID = 1L; /** * 控制台打印类名的颜色代码 @@ -78,16 +80,16 @@ public class ConsoleColorLog extends ConsoleLog { * * @param name 类名 */ - public ConsoleColorLog(String name) { + public ConsoleColorProvider(final String name) { super(name); } /** * 构造 * - * @param clazz 类 + * @param clazz 日志实现类 */ - public ConsoleColorLog(Class clazz) { + public ConsoleColorProvider(final Class clazz) { super(clazz); } @@ -96,18 +98,18 @@ public ConsoleColorLog(Class clazz) { * * @param colorFactory 颜色工厂函数 */ - public static void setColorFactory(Function colorFactory) { - ConsoleColorLog.colorFactory = colorFactory; + public static void setColorFactory(final Function colorFactory) { + ConsoleColorProvider.colorFactory = colorFactory; } @Override - public synchronized void log(String fqcn, Level level, Throwable t, String format, Object... arguments) { - if (false == isEnabled(level)) { + public synchronized void log(final String fqcn, final Level level, final Throwable t, final String format, final Object... args) { + if (!isEnabled(level)) { return; } final String template = AnsiEncoder.encode(COLOR_TIME, "[%s]", colorFactory.apply(level), "[%-5s]%s", COLOR_CLASSNAME, "%-30s: ", COLOR_NONE, "%s%n"); - System.out.format(template, DateKit.now(), level.name(), " - ", ClassKit.getShortClassName(getName()), StringKit.format(format, arguments)); + System.out.format(template, DateKit.formatNow(), level.name(), " - ", ClassKit.getShortClassName(getName()), StringKit.format(format, args)); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleFactory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleFactory.java old mode 100755 new mode 100644 index c56c2780c4..7db6740e86 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleFactory.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleFactory.java @@ -25,29 +25,32 @@ ********************************************************************************/ package org.miaixz.bus.logger.metric.console; -import org.miaixz.bus.logger.Factory; -import org.miaixz.bus.logger.magic.Log; +import org.miaixz.bus.logger.Supplier; +import org.miaixz.bus.logger.magic.AbstractFactory; /** - * 利用System.out.println()打印日志 + * System.out.println 打印日志 * * @author Kimi Liu * @since Java 17+ */ -public class ConsoleFactory extends Factory { +public class ConsoleFactory extends AbstractFactory { + /** + * 构造 + */ public ConsoleFactory() { super("Console Logging"); } @Override - public Log createLog(String name) { - return new ConsoleLog(name); + public Supplier create(final String name) { + return new ConsoleProvider(name); } @Override - public Log createLog(Class clazz) { - return new ConsoleLog(clazz); + public Supplier create(final Class clazz) { + return new ConsoleProvider(clazz); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleProvider.java old mode 100755 new mode 100644 similarity index 67% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleProvider.java index 8729f0e57e..c56dd6e6b4 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/ConsoleProvider.java @@ -31,27 +31,30 @@ import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.xyz.DateKit; import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.AbstractAware; import org.miaixz.bus.logger.Level; +import org.miaixz.bus.logger.Provider; /** - * 利用System.out.println()打印日志 + * System.out.println 打印日志 * * @author Kimi Liu * @since Java 17+ */ -public class ConsoleLog extends AbstractAware { +public class ConsoleProvider extends Provider { - private static final String logFormat = "[{date}] [{level}] {name}: {msg}"; - private static Level currentLevel = Level.DEBUG; - private final String name; + private static final long serialVersionUID = -1L; + + /** + * 日志级别 + */ + private static Level _level = Level.DEBUG; /** * 构造 * * @param clazz 类 */ - public ConsoleLog(Class clazz) { + public ConsoleProvider(final Class clazz) { this.name = (null == clazz) ? Normal.NULL : clazz.getName(); } @@ -60,18 +63,18 @@ public ConsoleLog(Class clazz) { * * @param name 类名 */ - public ConsoleLog(String name) { + public ConsoleProvider(final String name) { this.name = name; } /** * 设置自定义的日志显示级别 * - * @param customLevel 自定义级别 + * @param level 自定义级别 */ - public static void setLevel(Level customLevel) { - Assert.notNull(customLevel); - currentLevel = customLevel; + public static void setLevel(final Level level) { + Assert.notNull(level); + _level = level; } @Override @@ -85,8 +88,8 @@ public boolean isTrace() { } @Override - public void trace(String fqcn, Throwable t, String format, Object... arguments) { - log(fqcn, Level.TRACE, t, format, arguments); + public void trace(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.TRACE, t, format, args); } @Override @@ -95,8 +98,8 @@ public boolean isDebug() { } @Override - public void debug(String fqcn, Throwable t, String format, Object... arguments) { - log(fqcn, Level.DEBUG, t, format, arguments); + public void debug(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.DEBUG, t, format, args); } @Override @@ -105,8 +108,8 @@ public boolean isInfo() { } @Override - public void info(String fqcn, Throwable t, String format, Object... arguments) { - log(fqcn, Level.INFO, t, format, arguments); + public void info(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.INFO, t, format, args); } @Override @@ -115,8 +118,8 @@ public boolean isWarn() { } @Override - public void warn(String fqcn, Throwable t, String format, Object... arguments) { - log(fqcn, Level.WARN, t, format, arguments); + public void warn(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.WARN, t, format, args); } @Override @@ -125,24 +128,24 @@ public boolean isError() { } @Override - public void error(String fqcn, Throwable t, String format, Object... arguments) { - log(fqcn, Level.ERROR, t, format, arguments); + public void error(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.ERROR, t, format, args); } @Override - public void log(String fqcn, Level level, Throwable t, String format, Object... arguments) { - if (false == isEnabled(level)) { + public void log(final String fqcn, final Level level, final Throwable t, final String format, final Object... args) { + if (!isEnabled(level)) { return; } - - final Dictionary dictionary = Dictionary.of() - .set("date", DateKit.now()) + final Dictionary dict = Dictionary.of() + .set("date", DateKit.formatNow()) .set("level", level.toString()) .set("name", this.name) - .set("msg", StringKit.format(format, arguments)); + .set("msg", StringKit.format(format, args)); - final String logMsg = StringKit.format(logFormat, dictionary); + final String logMsg = StringKit.format("[{date}] [{level}] {name}: {msg}", dict); + //WARN以上级别打印至System.err if (level.ordinal() >= Level.WARN.ordinal()) { Console.error(t, logMsg); } else { @@ -151,8 +154,8 @@ public void log(String fqcn, Level level, Throwable t, String format, Object... } @Override - public boolean isEnabled(Level level) { - return currentLevel.compareTo(level) <= 0; + public boolean isEnabled(final Level level) { + return _level.compareTo(level) <= 0; } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/package-info.java index b32ac9ee67..39fa37dbf5 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/package-info.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/console/package-info.java @@ -1,7 +1,7 @@ /** - * 控制台输出的实现封装 + * console 实现封装 * * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.logger.metric.console; \ No newline at end of file +package org.miaixz.bus.logger.metric.console; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossFactory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossFactory.java old mode 100755 new mode 100644 index 045c8db9cb..14f27ea109 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossFactory.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossFactory.java @@ -25,30 +25,33 @@ ********************************************************************************/ package org.miaixz.bus.logger.metric.jboss; -import org.miaixz.bus.logger.Factory; -import org.miaixz.bus.logger.magic.Log; +import org.miaixz.bus.logger.Supplier; +import org.miaixz.bus.logger.magic.AbstractFactory; /** - * Jboss-Logging + * jboss-logging * * @author Kimi Liu * @since Java 17+ */ -public class JbossFactory extends Factory { +public class JbossFactory extends AbstractFactory { + /** + * 构造 + */ public JbossFactory() { super("JBoss Logging"); - checkLogExist(org.jboss.logging.Logger.class); + check(org.jboss.logging.Logger.class); } @Override - public Log createLog(String name) { - return new JbossLog(name); + public Supplier create(final String name) { + return new JbossProvider(name); } @Override - public Log createLog(Class clazz) { - return new JbossLog(clazz); + public Supplier create(final Class clazz) { + return new JbossProvider(clazz); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossProvider.java old mode 100755 new mode 100644 similarity index 70% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossProvider.java index 105fdb8a44..1377311215 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/JbossProvider.java @@ -28,43 +28,48 @@ import org.jboss.logging.Logger; import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.AbstractAware; import org.miaixz.bus.logger.Level; +import org.miaixz.bus.logger.Provider; /** - * Jboss-Logging log. + * jboss-logging * * @author Kimi Liu * @since Java 17+ */ -public class JbossLog extends AbstractAware { +public class JbossProvider extends Provider { + private static final long serialVersionUID = -1L; + + /** + * 日志门面 + */ private final transient Logger logger; /** * 构造 * - * @param logger {@link Logger} + * @param logger 日志对象 */ - public JbossLog(Logger logger) { + public JbossProvider(final Logger logger) { this.logger = logger; } /** * 构造 * - * @param clazz 日志打印所在类 + * @param clazz 日志实现类 */ - public JbossLog(Class clazz) { + public JbossProvider(final Class clazz) { this((null == clazz) ? Normal.NULL : clazz.getName()); } /** * 构造 * - * @param name 日志打印所在类名 + * @param name 日志实现类名 */ - public JbossLog(String name) { + public JbossProvider(final String name) { this(Logger.getLogger(name)); } @@ -79,9 +84,9 @@ public boolean isTrace() { } @Override - public void trace(String fqcn, Throwable t, String format, Object... arguments) { + public void trace(final String fqcn, final Throwable t, final String format, final Object... args) { if (isTrace()) { - logger.trace(fqcn, StringKit.format(format, arguments), t); + logger.trace(fqcn, StringKit.format(format, args), t); } } @@ -91,9 +96,9 @@ public boolean isDebug() { } @Override - public void debug(String fqcn, Throwable t, String format, Object... arguments) { + public void debug(final String fqcn, final Throwable t, final String format, final Object... args) { if (isDebug()) { - logger.debug(fqcn, StringKit.format(format, arguments), t); + logger.debug(fqcn, StringKit.format(format, args), t); } } @@ -103,9 +108,9 @@ public boolean isInfo() { } @Override - public void info(String fqcn, Throwable t, String format, Object... arguments) { + public void info(final String fqcn, final Throwable t, final String format, final Object... args) { if (isInfo()) { - logger.info(fqcn, StringKit.format(format, arguments), t); + logger.info(fqcn, StringKit.format(format, args), t); } } @@ -115,9 +120,9 @@ public boolean isWarn() { } @Override - public void warn(String fqcn, Throwable t, String format, Object... arguments) { + public void warn(final String fqcn, final Throwable t, final String format, final Object... args) { if (isWarn()) { - logger.warn(fqcn, StringKit.format(format, arguments), t); + logger.warn(fqcn, StringKit.format(format, args), t); } } @@ -127,29 +132,29 @@ public boolean isError() { } @Override - public void error(String fqcn, Throwable t, String format, Object... arguments) { + public void error(final String fqcn, final Throwable t, final String format, final Object... args) { if (isError()) { - logger.error(fqcn, StringKit.format(format, arguments), t); + logger.error(fqcn, StringKit.format(format, args), t); } } @Override - public void log(String fqcn, Level level, Throwable t, String format, Object... arguments) { + public void log(final String fqcn, final Level level, final Throwable t, final String format, final Object... args) { switch (level) { case TRACE: - trace(fqcn, t, format, arguments); + trace(fqcn, t, format, args); break; case DEBUG: - debug(fqcn, t, format, arguments); + debug(fqcn, t, format, args); break; case INFO: - info(fqcn, t, format, arguments); + info(fqcn, t, format, args); break; case WARN: - warn(fqcn, t, format, arguments); + warn(fqcn, t, format, args); break; case ERROR: - error(fqcn, t, format, arguments); + error(fqcn, t, format, args); break; default: throw new Error(StringKit.format("Can not identify level: {}", level)); diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/package-info.java index 5b627f5083..d11ed08567 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/package-info.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jboss/package-info.java @@ -1,7 +1,7 @@ /** - * jboss-logging实现 + * jboss-logging 实现 * * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.logger.metric.jboss; \ No newline at end of file +package org.miaixz.bus.logger.metric.jboss; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkFactory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkFactory.java old mode 100755 new mode 100644 index 306df4d5c6..cdb565c0a2 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkFactory.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkFactory.java @@ -28,41 +28,44 @@ import org.miaixz.bus.core.lang.Console; import org.miaixz.bus.core.xyz.IoKit; import org.miaixz.bus.core.xyz.ResourceKit; -import org.miaixz.bus.logger.Factory; -import org.miaixz.bus.logger.magic.Log; +import org.miaixz.bus.logger.Supplier; +import org.miaixz.bus.logger.magic.AbstractFactory; import java.io.InputStream; import java.util.logging.LogManager; /** - * JDK日志工厂类 * java.util.logging * * @author Kimi Liu * @since Java 17+ */ -public class JdkFactory extends Factory { +public class JdkFactory extends AbstractFactory { + /** + * 构造 + */ public JdkFactory() { super("JDK Logging"); readConfig(); } @Override - public Log createLog(String name) { - return new JdkLog(name); + public Supplier create(final String name) { + return new JdkProvider(name); } @Override - public Log createLog(Class clazz) { - return new JdkLog(clazz); + public Supplier create(final Class clazz) { + return new JdkProvider(clazz); } /** * 读取ClassPath下的logging.properties配置文件 */ private void readConfig() { - InputStream in = ResourceKit.getStreamSafe("logging.properties"); + // 避免循环引用,Log初始化的时候不使用相关工具类 + final InputStream in = ResourceKit.getStreamSafe("logging.properties"); if (null == in) { System.err.println("[WARN] Can not find [logging.properties], use [%JRE_HOME%/lib/logging.properties] as default!"); return; @@ -70,11 +73,11 @@ private void readConfig() { try { LogManager.getLogManager().readConfiguration(in); - } catch (Exception e) { + } catch (final Exception e) { Console.error(e, "Read [logging.properties] from classpath error!"); try { LogManager.getLogManager().readConfiguration(); - } catch (Exception e1) { + } catch (final Exception e1) { Console.error(e, "Read [logging.properties] from [%JRE_HOME%/lib/logging.properties] error!"); } } finally { diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkProvider.java old mode 100755 new mode 100644 similarity index 64% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkProvider.java index 80bcf58e81..8b81d40e6e --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/JdkProvider.java @@ -27,58 +27,52 @@ import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.AbstractAware; +import org.miaixz.bus.logger.Provider; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** - * java.util.logging log. + * java.util.logging * * @author Kimi Liu * @since Java 17+ */ -public class JdkLog extends AbstractAware { +public class JdkProvider extends Provider { + private static final long serialVersionUID = -1L; + + /** + * 日志门面 + */ private final transient Logger logger; - public JdkLog(Logger logger) { + /** + * 构造 + * + * @param logger 日志对象 + */ + public JdkProvider(final Logger logger) { this.logger = logger; } - public JdkLog(Class clazz) { + /** + * 构造 + * + * @param clazz 日志实现类 + */ + public JdkProvider(final Class clazz) { this((null == clazz) ? Normal.NULL : clazz.getName()); } - public JdkLog(String name) { - this(Logger.getLogger(name)); - } - /** - * 传入调用日志类的信息 + * 构造 * - * @param callerFQCN 调用者全限定类名 - * @param record The record to update + * @param name 日志实现类名 */ - private static void fillCallerData(String callerFQCN, LogRecord record) { - StackTraceElement[] steArray = Thread.currentThread().getStackTrace(); - - int found = -1; - String className; - for (int i = steArray.length - 2; i > -1; i--) { - className = steArray[i].getClassName(); - if (callerFQCN.equals(className)) { - found = i; - break; - } - } - - if (found > -1) { - StackTraceElement ste = steArray[found + 1]; - record.setSourceClassName(ste.getClassName()); - record.setSourceMethodName(ste.getMethodName()); - } + public JdkProvider(final String name) { + this(Logger.getLogger(name)); } @Override @@ -92,8 +86,8 @@ public boolean isTrace() { } @Override - public void trace(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.FINEST, t, format, arguments); + public void trace(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.FINEST, t, format, args); } @Override @@ -102,8 +96,8 @@ public boolean isDebug() { } @Override - public void debug(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.FINE, t, format, arguments); + public void debug(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.FINE, t, format, args); } @Override @@ -112,8 +106,8 @@ public boolean isInfo() { } @Override - public void info(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.INFO, t, format, arguments); + public void info(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.INFO, t, format, args); } @Override @@ -122,8 +116,8 @@ public boolean isWarn() { } @Override - public void warn(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.WARNING, t, format, arguments); + public void warn(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.WARNING, t, format, args); } @Override @@ -132,13 +126,13 @@ public boolean isError() { } @Override - public void error(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.SEVERE, t, format, arguments); + public void error(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.SEVERE, t, format, args); } @Override - public void log(String fqcn, org.miaixz.bus.logger.Level level, Throwable t, String format, Object... arguments) { - Level jdkLevel; + public void log(final String fqcn, final org.miaixz.bus.logger.Level level, final Throwable t, final String format, final Object... args) { + final Level jdkLevel; switch (level) { case TRACE: jdkLevel = Level.FINEST; @@ -158,26 +152,53 @@ public void log(String fqcn, org.miaixz.bus.logger.Level level, Throwable t, Str default: throw new Error(StringKit.format("Can not identify level: {}", level)); } - logIfEnabled(fqcn, jdkLevel, t, format, arguments); + log(fqcn, jdkLevel, t, format, args); } /** * 打印对应等级的日志 * - * @param callerFQCN 调用者的完全限定类名(Fully Qualified Class Name) - * @param level 等级 - * @param throwable 异常对象 - * @param format 消息模板 - * @param arguments 参数 + * @param fqcn 调用者的完全限定类名(Fully Qualified Class Name) + * @param level 等级 + * @param throwable 异常对象 + * @param format 消息格式 + * @param args 参数 */ - private void logIfEnabled(String callerFQCN, Level level, Throwable throwable, String format, Object[] arguments) { + private void log(final String fqcn, final Level level, final Throwable throwable, final String format, final Object[] args) { if (logger.isLoggable(level)) { - LogRecord record = new LogRecord(level, StringKit.format(format, arguments)); + final LogRecord record = new LogRecord(level, StringKit.format(format, args)); record.setLoggerName(getName()); record.setThrown(throwable); - fillCallerData(callerFQCN, record); + fill(fqcn, record); logger.log(record); } } + /** + * 传入调用日志类的信息 + * + * @param fqcn 调用者全限定类名 + * @param record 要更新的记录 + */ + private static void fill(final String fqcn, final LogRecord record) { + final StackTraceElement[] steArray = Thread.currentThread().getStackTrace(); + + int found = -1; + String className; + for (int i = steArray.length - 2; i > -1; i--) { + // 此处初始值为length-2,表示从倒数第二个堆栈开始检查,如果是倒数第一个,那调用者就获取不到 + className = steArray[i].getClassName(); + if (fqcn.equals(className)) { + found = i; + break; + } + } + + if (found > -1) { + final StackTraceElement ste = steArray[found + 1]; + record.setSourceClassName(ste.getClassName()); + record.setSourceMethodName(ste.getMethodName()); + } + } + } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/package-info.java index d0c069851b..5e8b2627c5 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/package-info.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/jdk/package-info.java @@ -1,7 +1,7 @@ /** - * JDK-Logging的实现封装 + * java.util.logging 实现封装 * * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.logger.metric.jdk; \ No newline at end of file +package org.miaixz.bus.logger.metric.jdk; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j2/Log4J2Factory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j/Log4JFactory.java old mode 100755 new mode 100644 similarity index 80% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j2/Log4J2Factory.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j/Log4JFactory.java index 513fe674e7..8fad735dd9 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j2/Log4J2Factory.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j/Log4JFactory.java @@ -23,32 +23,35 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.logger.metric.log4j2; +package org.miaixz.bus.logger.metric.log4j; -import org.miaixz.bus.logger.Factory; -import org.miaixz.bus.logger.magic.Log; +import org.miaixz.bus.logger.Supplier; +import org.miaixz.bus.logger.magic.AbstractFactory; /** - * Apache Log4J 2 + * log4j * * @author Kimi Liu * @since Java 17+ */ -public class Log4J2Factory extends Factory { +public class Log4JFactory extends AbstractFactory { - public Log4J2Factory() { - super("Log4j2"); - checkLogExist(org.apache.logging.log4j.LogManager.class); + /** + * 构造 + */ + public Log4JFactory() { + super("Log4j"); + check(org.apache.logging.log4j.LogManager.class); } @Override - public Log createLog(String name) { - return new Log4j2Log(name); + public Supplier create(final String name) { + return new Log4jProvider(name); } @Override - public Log createLog(Class clazz) { - return new Log4j2Log(clazz); + public Supplier create(final Class clazz) { + return new Log4jProvider(clazz); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j2/Log4j2Log.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j/Log4jProvider.java old mode 100755 new mode 100644 similarity index 64% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j2/Log4j2Log.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j/Log4jProvider.java index aaab739c6e..40900fcd5a --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j2/Log4j2Log.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j/Log4jProvider.java @@ -23,34 +23,54 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.logger.metric.log4j2; +package org.miaixz.bus.logger.metric.log4j; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.spi.AbstractLogger; import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.AbstractAware; +import org.miaixz.bus.logger.Provider; /** - * Apache Log4J 2 log. + * log4j * * @author Kimi Liu * @since Java 17+ */ -public class Log4j2Log extends AbstractAware { +public class Log4jProvider extends Provider { + private static final long serialVersionUID = -1L; + + /** + * 日志门面 + */ private final transient Logger logger; - public Log4j2Log(Logger logger) { + /** + * 构造 + * + * @param logger 日志对象 + */ + public Log4jProvider(final Logger logger) { this.logger = logger; } - public Log4j2Log(Class clazz) { + /** + * 构造 + * + * @param clazz 日志实现类 + */ + public Log4jProvider(final Class clazz) { this(LogManager.getLogger(clazz)); } - public Log4j2Log(String name) { + /** + * 构造 + * + * @param name 日志实现类名 + */ + public Log4jProvider(final String name) { this(LogManager.getLogger(name)); } @@ -65,8 +85,8 @@ public boolean isTrace() { } @Override - public void trace(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.TRACE, t, format, arguments); + public void trace(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.TRACE, t, format, args); } @Override @@ -75,13 +95,8 @@ public boolean isDebug() { } @Override - public void debug(String format, Object... arguments) { - debug(null, format, arguments); - } - - @Override - public void debug(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.DEBUG, t, format, arguments); + public void debug(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.DEBUG, t, format, args); } @Override @@ -90,8 +105,8 @@ public boolean isInfo() { } @Override - public void info(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.INFO, t, format, arguments); + public void info(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.INFO, t, format, args); } @Override @@ -100,8 +115,8 @@ public boolean isWarn() { } @Override - public void warn(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.WARN, t, format, arguments); + public void warn(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.WARN, t, format, args); } @Override @@ -110,13 +125,13 @@ public boolean isError() { } @Override - public void error(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.ERROR, t, format, arguments); + public void error(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, Level.ERROR, t, format, args); } @Override - public void log(String fqcn, org.miaixz.bus.logger.Level level, Throwable t, String format, Object... arguments) { - Level log4j2Level; + public void log(final String fqcn, final org.miaixz.bus.logger.Level level, final Throwable t, final String format, final Object... args) { + final Level log4j2Level; switch (level) { case TRACE: log4j2Level = Level.TRACE; @@ -136,25 +151,25 @@ public void log(String fqcn, org.miaixz.bus.logger.Level level, Throwable t, Str default: throw new Error(StringKit.format("Can not identify level: {}", level)); } - logIfEnabled(fqcn, log4j2Level, t, format, arguments); + log(fqcn, log4j2Level, t, format, args); } /** * 打印日志 - * 此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题 + * 此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题 * - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于纠正定位错误行号 - * @param level 日志级别,使用org.apache.logging.log4j.Level中的常量 - * @param t 异常 - * @param msgTemplate 消息模板 - * @param arguments 参数 + * @param fqcn 完全限定类名(Fully Qualified Class Name),用于纠正定位错误行号 + * @param level 日志级别,使用org.apache.logging.log4j.Level中的常量 + * @param t 异常 + * @param format 消息格式 + * @param args 参数 */ - private void logIfEnabled(String fqcn, Level level, Throwable t, String msgTemplate, Object... arguments) { + private void log(final String fqcn, final Level level, final Throwable t, final String format, final Object... args) { if (this.logger.isEnabled(level)) { if (this.logger instanceof AbstractLogger) { - ((AbstractLogger) this.logger).logIfEnabled(fqcn, level, null, StringKit.format(msgTemplate, arguments), t); + ((AbstractLogger) this.logger).logIfEnabled(fqcn, level, null, StringKit.format(format, args), t); } else { - this.logger.log(level, StringKit.format(msgTemplate, arguments), t); + this.logger.log(level, StringKit.format(format, args), t); } } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j/package-info.java new file mode 100644 index 0000000000..b497eaa408 --- /dev/null +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j/package-info.java @@ -0,0 +1,7 @@ +/** + * log4j 实现封装 + * + * @author Kimi Liu + * @since Java 17+ + */ +package org.miaixz.bus.logger.metric.log4j; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j2/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j2/package-info.java deleted file mode 100644 index f52e911241..0000000000 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/log4j2/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Log4j2的实现封装 - * - * @author Kimi Liu - * @since Java 17+ - */ -package org.miaixz.bus.logger.metric.log4j2; \ No newline at end of file diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/package-info.java index 1c6ce74351..b698ee7dc9 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/package-info.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/package-info.java @@ -4,4 +4,4 @@ * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.logger.metric; \ No newline at end of file +package org.miaixz.bus.logger.metric; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4JFactory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4JFactory.java old mode 100755 new mode 100644 index 3f3434806d..5898cf2807 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4JFactory.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4JFactory.java @@ -25,24 +25,26 @@ ********************************************************************************/ package org.miaixz.bus.logger.metric.slf4j; -import org.miaixz.bus.core.lang.Charset; -import org.miaixz.bus.logger.Factory; -import org.miaixz.bus.logger.magic.Log; +import org.miaixz.bus.logger.Supplier; +import org.miaixz.bus.logger.magic.AbstractFactory; import org.slf4j.LoggerFactory; import org.slf4j.helpers.NOPLoggerFactory; import java.io.OutputStream; import java.io.PrintStream; +import java.io.UnsupportedEncodingException; /** - * SLF4J - * 无缝支持LogBack + * slf4j and logback * * @author Kimi Liu * @since Java 17+ */ -public class Slf4JFactory extends Factory { +public class Slf4JFactory extends AbstractFactory { + /** + * 构造 + */ public Slf4JFactory() { this(true); } @@ -50,23 +52,26 @@ public Slf4JFactory() { /** * 构造 * - * @param failIfNOP 如果未找到桥接包是否报错 + * @param fail 如果未找到桥接包是否报错 */ - public Slf4JFactory(boolean failIfNOP) { + public Slf4JFactory(final boolean fail) { super("Slf4j"); - checkLogExist(LoggerFactory.class); - if (false == failIfNOP) { + check(LoggerFactory.class); + if (!fail) { return; } - final StringBuilder buf = new StringBuilder(); final PrintStream err = System.err; - System.setErr(new PrintStream(new OutputStream() { - @Override - public void write(int b) { - buf.append((char) b); - } - }, true, Charset.US_ASCII)); + try { + System.setErr(new PrintStream(new OutputStream() { + @Override + public void write(final int b) { + buf.append((char) b); + } + }, true, "US-ASCII")); + } catch (final UnsupportedEncodingException e) { + throw new Error(e); + } try { if (LoggerFactory.getILoggerFactory() instanceof NOPLoggerFactory) { @@ -81,13 +86,13 @@ public void write(int b) { } @Override - public Log createLog(String name) { - return new Slf4jLog(name); + public Supplier create(final String name) { + return new Slf4jProvider(name); } @Override - public Log createLog(Class clazz) { - return new Slf4jLog(clazz); + public Supplier create(final Class clazz) { + return new Slf4jProvider(clazz); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4jLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4jProvider.java old mode 100755 new mode 100644 similarity index 58% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4jLog.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4jProvider.java index d4968faabb..bfcfa5603c --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4jLog.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/Slf4jProvider.java @@ -27,48 +27,57 @@ import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.AbstractAware; import org.miaixz.bus.logger.Level; +import org.miaixz.bus.logger.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.spi.LocationAwareLogger; /** - * SLF4J log. - * 无缝支持 LogBack + * slf4j and logback * * @author Kimi Liu * @since Java 17+ */ -public class Slf4jLog extends AbstractAware { +public class Slf4jProvider extends Provider { + private static final long serialVersionUID = -1L; + + /** + * 日志门面 + */ private final transient Logger logger; /** - * 是否为 LocationAwareLogger ,用于判断是否可以传递FQCN + * 是否为 LocationAwareLogger ,用于判断是否可以传递FQCN */ private final boolean isLocationAwareLogger; - public Slf4jLog(Logger logger) { + /** + * 构造 + * + * @param logger 日志对象 + */ + public Slf4jProvider(final Logger logger) { this.logger = logger; this.isLocationAwareLogger = (logger instanceof LocationAwareLogger); } - public Slf4jLog(Class clazz) { - this(getSlf4jLogger(clazz)); - } - - public Slf4jLog(String name) { - this(LoggerFactory.getLogger(name)); + /** + * 构造 + * + * @param clazz 日志实现类 + */ + public Slf4jProvider(final Class clazz) { + this(null == clazz ? LoggerFactory.getLogger(Normal.EMPTY) : LoggerFactory.getLogger(clazz)); } /** - * 获取Slf4j Logger对象 + * 构造 * - * @param clazz 打印日志所在类,当为{@code null}时使用“null”表示 - * @return {@link Logger} + * @param name 日志实现类名 */ - private static Logger getSlf4jLogger(Class clazz) { - return (null == clazz) ? LoggerFactory.getLogger(Normal.EMPTY) : LoggerFactory.getLogger(clazz); + public Slf4jProvider(final String name) { + this(LoggerFactory.getLogger(name)); } @Override @@ -82,12 +91,12 @@ public boolean isTrace() { } @Override - public void trace(String fqcn, Throwable t, String format, Object... arguments) { + public void trace(final String fqcn, final Throwable t, final String format, final Object... args) { if (isTrace()) { if (this.isLocationAwareLogger) { - locationAwareLog((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.TRACE_INT, t, format, arguments); + log((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.TRACE_INT, t, format, args); } else { - logger.trace(StringKit.format(format, arguments), t); + logger.trace(StringKit.format(format, args), t); } } } @@ -98,12 +107,12 @@ public boolean isDebug() { } @Override - public void debug(String fqcn, Throwable t, String format, Object... arguments) { + public void debug(final String fqcn, final Throwable t, final String format, final Object... args) { if (isDebug()) { if (this.isLocationAwareLogger) { - locationAwareLog((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.DEBUG_INT, t, format, arguments); + log((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.DEBUG_INT, t, format, args); } else { - logger.debug(StringKit.format(format, arguments), t); + logger.debug(StringKit.format(format, args), t); } } } @@ -114,12 +123,12 @@ public boolean isInfo() { } @Override - public void info(String fqcn, Throwable t, String format, Object... arguments) { + public void info(final String fqcn, final Throwable t, final String format, final Object... args) { if (isInfo()) { if (this.isLocationAwareLogger) { - locationAwareLog((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.INFO_INT, t, format, arguments); + log((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.INFO_INT, t, format, args); } else { - logger.info(StringKit.format(format, arguments), t); + logger.info(StringKit.format(format, args), t); } } } @@ -130,12 +139,12 @@ public boolean isWarn() { } @Override - public void warn(String fqcn, Throwable t, String format, Object... arguments) { + public void warn(final String fqcn, final Throwable t, final String format, final Object... args) { if (isWarn()) { if (this.isLocationAwareLogger) { - locationAwareLog((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.WARN_INT, t, format, arguments); + log((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.WARN_INT, t, format, args); } else { - logger.warn(StringKit.format(format, arguments), t); + logger.warn(StringKit.format(format, args), t); } } } @@ -146,33 +155,33 @@ public boolean isError() { } @Override - public void error(String fqcn, Throwable t, String format, Object... arguments) { + public void error(final String fqcn, final Throwable t, final String format, final Object... args) { if (isError()) { if (this.isLocationAwareLogger) { - locationAwareLog((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.ERROR_INT, t, format, arguments); + log((LocationAwareLogger) this.logger, fqcn, LocationAwareLogger.ERROR_INT, t, format, args); } else { - logger.error(StringKit.format(format, arguments), t); + logger.error(StringKit.format(format, args), t); } } } @Override - public void log(String fqcn, Level level, Throwable t, String format, Object... arguments) { + public void log(final String fqcn, final Level level, final Throwable t, final String format, final Object... args) { switch (level) { case TRACE: - trace(fqcn, t, format, arguments); + trace(fqcn, t, format, args); break; case DEBUG: - debug(fqcn, t, format, arguments); + debug(fqcn, t, format, args); break; case INFO: - info(fqcn, t, format, arguments); + info(fqcn, t, format, args); break; case WARN: - warn(fqcn, t, format, arguments); + warn(fqcn, t, format, args); break; case ERROR: - error(fqcn, t, format, arguments); + error(fqcn, t, format, args); break; default: throw new Error(StringKit.format("Can not identify level: {}", level)); @@ -181,17 +190,17 @@ public void log(String fqcn, Level level, Throwable t, String format, Object... /** * 打印日志 - * 此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题 + * 此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题 * - * @param logger {@link LocationAwareLogger} 实现 - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于纠正定位错误行号 - * @param level_int 日志级别,使用LocationAwareLogger中的常量 - * @param t 异常 - * @param msgTemplate 消息模板 - * @param arguments 参数 + * @param logger {@link LocationAwareLogger} 实现 + * @param fqcn 完全限定类名(Fully Qualified Class Name),用于纠正定位错误行号 + * @param level 日志级别,使用LocationAwareLogger中的常量 + * @param t 异常 + * @param format 消息格式 + * @param args 参数 */ - private void locationAwareLog(LocationAwareLogger logger, String fqcn, int level_int, Throwable t, String msgTemplate, Object[] arguments) { - logger.log(null, fqcn, level_int, StringKit.format(msgTemplate, arguments), null, t); + private void log(final LocationAwareLogger logger, final String fqcn, final int level, final Throwable t, final String format, final Object[] args) { + logger.log(null, fqcn, level, StringKit.format(format, args), null, t); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/package-info.java index df6dcb6a3f..10be80d344 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/package-info.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/slf4j/package-info.java @@ -1,7 +1,7 @@ /** - * Slf4j的实现封装 + * slf4j/logback 实现封装 * * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.logger.metric.slf4j; \ No newline at end of file +package org.miaixz.bus.logger.metric.slf4j; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLog.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLog.java deleted file mode 100755 index d73ba23db2..0000000000 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLog.java +++ /dev/null @@ -1,196 +0,0 @@ -/********************************************************************************* - * * - * The MIT License (MIT) * - * * - * Copyright (c) 2015-2024 miaixz.org and other contributors. * - * * - * 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 org.miaixz.bus.logger.metric.tinylog; - -import org.miaixz.bus.core.lang.Normal; -import org.miaixz.bus.core.xyz.ArrayKit; -import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.AbstractAware; -import org.tinylog.Level; -import org.tinylog.configuration.Configuration; -import org.tinylog.format.AdvancedMessageFormatter; -import org.tinylog.format.MessageFormatter; -import org.tinylog.provider.LoggingProvider; -import org.tinylog.provider.ProviderRegistry; - -/** - * tinylog2 log. - * - * @author Kimi Liu - * @since Java 17+ - */ -public class TinyLog extends AbstractAware { - - /** - * 堆栈增加层数,因为封装因此多了两层,此值用于正确获取当前类名 - */ - private static final int DEPTH = 5; - private static final LoggingProvider provider = ProviderRegistry.getLoggingProvider(); - private static final MessageFormatter formatter = new AdvancedMessageFormatter( - Configuration.getLocale(), - Configuration.isEscapingEnabled() - ); - private final int level; - private final String name; - - public TinyLog(Class clazz) { - this(null == clazz ? Normal.NULL : clazz.getName()); - } - - public TinyLog(String name) { - this.name = name; - this.level = provider.getMinimumLevel().ordinal(); - } - - /** - * 如果最后一个参数为异常参数,则获取之,否则返回null - * - * @param arguments 参数 - * @return 最后一个异常参数 - */ - private static Throwable getLastArgumentIfThrowable(Object... arguments) { - if (ArrayKit.isNotEmpty(arguments) && arguments[arguments.length - 1] instanceof Throwable) { - return (Throwable) arguments[arguments.length - 1]; - } else { - return null; - } - } - - @Override - public String getName() { - return this.name; - } - - @Override - public boolean isTrace() { - return this.level <= Level.TRACE.ordinal(); - } - - @Override - public void trace(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.TRACE, t, format, arguments); - } - - @Override - public boolean isDebug() { - return this.level <= Level.DEBUG.ordinal(); - } - - @Override - public void debug(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.DEBUG, t, format, arguments); - } - - @Override - public boolean isInfo() { - return this.level <= Level.INFO.ordinal(); - } - - @Override - public void info(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.INFO, t, format, arguments); - } - - @Override - public boolean isWarn() { - return this.level <= Level.WARN.ordinal(); - } - - @Override - public boolean isError() { - return this.level <= Level.ERROR.ordinal(); - } - - @Override - public void error(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.ERROR, t, format, arguments); - } - - @Override - public void log(String fqcn, org.miaixz.bus.logger.Level level, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, toTinyLevel(level), t, format, arguments); - } - - @Override - public boolean isEnabled(org.miaixz.bus.logger.Level level) { - return this.level <= toTinyLevel(level).ordinal(); - } - - @Override - public void warn(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.WARN, t, format, arguments); - } - - /** - * 在对应日志级别打开情况下打印日志 - * - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 - * @param level 日志级别 - * @param t 异常,null则检查最后一个参数是否为Throwable类型,是则取之,否则不打印堆栈 - * @param format 日志消息模板 - * @param arguments 日志消息参数 - */ - private void logIfEnabled(String fqcn, Level level, Throwable t, String format, Object... arguments) { - if (null == t) { - t = getLastArgumentIfThrowable(arguments); - } - provider.log(DEPTH, null, level, t, formatter, StringKit.toString(format), arguments); - } - - /** - * Tinylog的Level等级 - * - * @param level Level等级 - * @return Tinylog的Level - */ - private Level toTinyLevel(org.miaixz.bus.logger.Level level) { - Level tinyLevel; - switch (level) { - case TRACE: - tinyLevel = Level.TRACE; - break; - case DEBUG: - tinyLevel = Level.DEBUG; - break; - case INFO: - tinyLevel = Level.INFO; - break; - case WARN: - tinyLevel = Level.WARN; - break; - case ERROR: - tinyLevel = Level.ERROR; - break; - case OFF: - tinyLevel = Level.OFF; - break; - default: - throw new Error(StringKit.format("Can not identify level: {}", level)); - } - return tinyLevel; - } - -} diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/Tiny2Factory.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLogFactory.java similarity index 84% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/Tiny2Factory.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLogFactory.java index e91fa23593..d72cef6bf8 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/Tiny2Factory.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLogFactory.java @@ -25,33 +25,33 @@ ********************************************************************************/ package org.miaixz.bus.logger.metric.tinylog; -import org.miaixz.bus.logger.Factory; -import org.miaixz.bus.logger.magic.Log; +import org.miaixz.bus.logger.Supplier; +import org.miaixz.bus.logger.magic.AbstractFactory; /** - * TinyLog2 logger. + * tinylog * * @author Kimi Liu * @since Java 17+ */ -public class Tiny2Factory extends Factory { +public class TinyLogFactory extends AbstractFactory { /** * 构造 */ - public Tiny2Factory() { + public TinyLogFactory() { super("TinyLog"); - checkLogExist(org.tinylog.Logger.class); + check(org.tinylog.Logger.class); } @Override - public Log createLog(String name) { - return new TinyLog2(name); + public Supplier create(final String name) { + return new TinyLogProvider(name); } @Override - public Log createLog(Class clazz) { - return new TinyLog2(clazz); + public Supplier create(final Class clazz) { + return new TinyLogProvider(clazz); } } diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLog2.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLogProvider.java old mode 100755 new mode 100644 similarity index 57% rename from bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLog2.java rename to bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLogProvider.java index 0ef3e0fe4f..5a5343b3d6 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLog2.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/TinyLogProvider.java @@ -28,8 +28,8 @@ import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.xyz.ArrayKit; import org.miaixz.bus.core.xyz.StringKit; -import org.miaixz.bus.logger.AbstractAware; -import org.tinylog.Level; +import org.miaixz.bus.logger.Level; +import org.miaixz.bus.logger.Provider; import org.tinylog.configuration.Configuration; import org.tinylog.format.AdvancedMessageFormatter; import org.tinylog.format.MessageFormatter; @@ -37,33 +37,46 @@ import org.tinylog.provider.ProviderRegistry; /** - * tinylog logger. + * tinylog * * @author Kimi Liu * @since Java 17+ */ -public class TinyLog2 extends AbstractAware { +public class TinyLogProvider extends Provider { - private static final long serialVersionUID = -1L; + private static final long serialVersionUID = 1L; /** - * 堆栈增加层数,因为封装因此多了两层,此值用于正确获取当前类名 + * 日志框架实现提供者 */ - private static final int DEPTH = 5; private static final LoggingProvider provider = ProviderRegistry.getLoggingProvider(); + /** + * 文本消息格式化程序 + */ private static final MessageFormatter formatter = new AdvancedMessageFormatter( Configuration.getLocale(), Configuration.isEscapingEnabled() ); + /** + * 日志级别 + */ private final int level; - private final String name; - - public TinyLog2(Class clazz) { + /** + * 构造 + * + * @param clazz 日志实现类 + */ + public TinyLogProvider(final Class clazz) { this(null == clazz ? Normal.NULL : clazz.getName()); } - public TinyLog2(String name) { + /** + * 构造 + * + * @param name 名称 + */ + public TinyLogProvider(final String name) { this.name = name; this.level = provider.getMinimumLevel().ordinal(); } @@ -71,12 +84,12 @@ public TinyLog2(String name) { /** * 如果最后一个参数为异常参数,则获取之,否则返回null * - * @param arguments 参数 + * @param args 参数 * @return 最后一个异常参数 */ - private static Throwable getLastArgumentIfThrowable(Object... arguments) { - if (ArrayKit.isNotEmpty(arguments) && arguments[arguments.length - 1] instanceof Throwable) { - return (Throwable) arguments[arguments.length - 1]; + private static Throwable getLastArgumentIfThrowable(final Object... args) { + if (ArrayKit.isNotEmpty(args) && args[args.length - 1] instanceof Throwable) { + return (Throwable) args[args.length - 1]; } else { return null; } @@ -89,108 +102,106 @@ public String getName() { @Override public boolean isTrace() { - return this.level <= Level.TRACE.ordinal(); + return this.level <= org.tinylog.Level.TRACE.ordinal(); } - @Override - public void trace(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.TRACE, t, format, arguments); + public void trace(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, org.tinylog.Level.TRACE, t, format, args); } @Override public boolean isDebug() { - return this.level <= Level.DEBUG.ordinal(); + return this.level <= org.tinylog.Level.DEBUG.ordinal(); } @Override - public void debug(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.DEBUG, t, format, arguments); + public void debug(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, org.tinylog.Level.DEBUG, t, format, args); } @Override public boolean isInfo() { - return this.level <= Level.INFO.ordinal(); + return this.level <= org.tinylog.Level.INFO.ordinal(); } @Override - public void info(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.INFO, t, format, arguments); + public void info(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, org.tinylog.Level.INFO, t, format, args); } @Override public boolean isWarn() { - return this.level <= Level.WARN.ordinal(); + return this.level <= org.tinylog.Level.WARN.ordinal(); } @Override - public void warn(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.WARN, t, format, arguments); + public void warn(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, org.tinylog.Level.WARN, t, format, args); } @Override public boolean isError() { - return this.level <= Level.ERROR.ordinal(); + return this.level <= org.tinylog.Level.ERROR.ordinal(); } @Override - public void error(String fqcn, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, Level.ERROR, t, format, arguments); + public void error(final String fqcn, final Throwable t, final String format, final Object... args) { + log(fqcn, org.tinylog.Level.ERROR, t, format, args); } @Override - public void log(String fqcn, org.miaixz.bus.logger.Level level, Throwable t, String format, Object... arguments) { - logIfEnabled(fqcn, toTinyLevel(level), t, format, arguments); + public void log(final String fqcn, final Level level, final Throwable t, final String format, final Object... args) { + log(fqcn, toTinyLevel(level), t, format, args); } @Override - public boolean isEnabled(org.miaixz.bus.logger.Level level) { + public boolean isEnabled(final Level level) { return this.level <= toTinyLevel(level).ordinal(); } /** * 在对应日志级别打开情况下打印日志 * - * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 - * @param level 日志级别 - * @param t 异常,null则检查最后一个参数是否为Throwable类型,是则取之,否则不打印堆栈 - * @param format 日志消息模板 - * @param arguments 日志消息参数 + * @param fqcn 完全限定类名(Fully Qualified Class Name),用于定位日志位置 + * @param level 日志级别 + * @param t 异常,null则检查最后一个参数是否为Throwable类型,是则取之,否则不打印堆栈 + * @param format 日志消息模板 + * @param args 日志消息参数 */ - private void logIfEnabled(String fqcn, Level level, Throwable t, String format, Object... arguments) { - // fqcn 无效 + private void log(final String fqcn, final org.tinylog.Level level, Throwable t, final String format, final Object... args) { if (null == t) { - t = getLastArgumentIfThrowable(arguments); + t = getLastArgumentIfThrowable(args); } - provider.log(DEPTH, null, level, t, formatter, StringKit.toString(format), arguments); + provider.log(Normal._5, null, level, t, formatter, StringKit.toString(format), args); } /** * 将Level等级转换为Tinylog的Level等级 * * @param level Level等级 - * @return Tinylog的Level + * @return the level */ - private Level toTinyLevel(org.miaixz.bus.logger.Level level) { - Level tinyLevel; + private org.tinylog.Level toTinyLevel(final Level level) { + final org.tinylog.Level tinyLevel; switch (level) { case TRACE: - tinyLevel = Level.TRACE; + tinyLevel = org.tinylog.Level.TRACE; break; case DEBUG: - tinyLevel = Level.DEBUG; + tinyLevel = org.tinylog.Level.DEBUG; break; case INFO: - tinyLevel = Level.INFO; + tinyLevel = org.tinylog.Level.INFO; break; case WARN: - tinyLevel = Level.WARN; + tinyLevel = org.tinylog.Level.WARN; break; case ERROR: - tinyLevel = Level.ERROR; + tinyLevel = org.tinylog.Level.ERROR; break; case OFF: - tinyLevel = Level.OFF; + tinyLevel = org.tinylog.Level.OFF; break; default: throw new Error(StringKit.format("Can not identify level: {}", level)); diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/package-info.java index 6d338d94d2..4d9b6dfc38 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/package-info.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/metric/tinylog/package-info.java @@ -1,8 +1,7 @@ /** - * tinylog的实现封装 - * 封装包括TinyLog和TinyLog2 + * tinylog 实现封装 * * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.logger.metric.tinylog; \ No newline at end of file +package org.miaixz.bus.logger.metric.tinylog; diff --git a/bus-logger/src/main/java/org/miaixz/bus/logger/package-info.java b/bus-logger/src/main/java/org/miaixz/bus/logger/package-info.java index a29456f76b..3d5c5f8534 100644 --- a/bus-logger/src/main/java/org/miaixz/bus/logger/package-info.java +++ b/bus-logger/src/main/java/org/miaixz/bus/logger/package-info.java @@ -1,8 +1,7 @@ /** - * logger只是一个日志的通用门面,功能类似于Slf4j - * 根据加入ClassPath中的jar包动态检测日志实现的方式,使日志使用个更加便利灵活 + * 日志通用门面,功能类似于slf4j * * @author Kimi Liu * @since Java 17+ */ -package org.miaixz.bus.logger; \ No newline at end of file +package org.miaixz.bus.logger; diff --git a/bus-logger/src/main/resources/META-INF/services/org.miaixz.bus.logger.Factory b/bus-logger/src/main/resources/META-INF/services/org.miaixz.bus.logger.Factory index 74a9669354..04c5ae964e 100644 --- a/bus-logger/src/main/resources/META-INF/services/org.miaixz.bus.logger.Factory +++ b/bus-logger/src/main/resources/META-INF/services/org.miaixz.bus.logger.Factory @@ -24,9 +24,8 @@ # # ################################################################################ -org.miaixz.bus.logger.metric.slf4j.Slf4JFactory -org.miaixz.bus.logger.metric.log4j2.Log4J2Factory -org.miaixz.bus.logger.metric.commons.ApacheCommonsFactory -org.miaixz.bus.logger.metric.tinylog.Tiny2Factory -org.miaixz.bus.logger.metric.tinylog.TinyFactory +org.miaixz.bus.logger.metric.commons.CommonsFactory org.miaixz.bus.logger.metric.jboss.JbossFactory +org.miaixz.bus.logger.metric.log4j.Log4JFactory +org.miaixz.bus.logger.metric.slf4j.Slf4JFactory +org.miaixz.bus.logger.metric.tinylog.TinyLogFactory diff --git a/bus-mapper/pom.xml b/bus-mapper/pom.xml index 6d92437af7..bdd42d6dfa 100755 --- a/bus-mapper/pom.xml +++ b/bus-mapper/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-mapper - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-mapper/src/main/java/org/miaixz/bus/mapper/additional/upsert/BatchUpsertProvider.java b/bus-mapper/src/main/java/org/miaixz/bus/mapper/additional/upsert/BatchUpsertProvider.java index 3c1a5b52ff..e4bacfc1d4 100644 --- a/bus-mapper/src/main/java/org/miaixz/bus/mapper/additional/upsert/BatchUpsertProvider.java +++ b/bus-mapper/src/main/java/org/miaixz/bus/mapper/additional/upsert/BatchUpsertProvider.java @@ -26,6 +26,7 @@ package org.miaixz.bus.mapper.additional.upsert; import org.apache.ibatis.mapping.MappedStatement; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.mapper.builder.EntityBuilder; import org.miaixz.bus.mapper.builder.MapperBuilder; import org.miaixz.bus.mapper.builder.MapperTemplate; @@ -61,7 +62,7 @@ public String batchUpsert(MappedStatement ms) { primaryKeyColumn = column.getColumn(); } if (column.isInsertable()) { - sql.append(column.getColumn() + ","); + sql.append(column.getColumn() + Symbol.COMMA); } } sql.append(""); @@ -82,10 +83,10 @@ public String batchUpsert(MappedStatement ms) { continue; } if (logicDeleteColumn != null && logicDeleteColumn == column) { - sql.append(SqlBuilder.getLogicDeletedValue(column, false)).append(","); + sql.append(SqlBuilder.getLogicDeletedValue(column, false)).append(Symbol.COMMA); continue; } - sql.append(column.getColumnHolder("record") + ","); + sql.append(column.getColumnHolder("record") + Symbol.COMMA); } sql.append(""); sql.append(" ON CONFLICT (" + primaryKeyColumn + ") DO UPDATE "); diff --git a/bus-mapper/src/main/java/org/miaixz/bus/mapper/additional/upsert/UpsertProvider.java b/bus-mapper/src/main/java/org/miaixz/bus/mapper/additional/upsert/UpsertProvider.java index c3d377cc59..93bb6e53fb 100644 --- a/bus-mapper/src/main/java/org/miaixz/bus/mapper/additional/upsert/UpsertProvider.java +++ b/bus-mapper/src/main/java/org/miaixz/bus/mapper/additional/upsert/UpsertProvider.java @@ -26,6 +26,7 @@ package org.miaixz.bus.mapper.additional.upsert; import org.apache.ibatis.mapping.MappedStatement; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.mapper.builder.EntityBuilder; import org.miaixz.bus.mapper.builder.MapperBuilder; import org.miaixz.bus.mapper.builder.MapperTemplate; @@ -60,7 +61,7 @@ public String upsert(MappedStatement ms) { primaryKeyColumn = column.getColumn(); } if (column.isInsertable()) { - sql.append(column.getColumn() + ","); + sql.append(column.getColumn() + Symbol.COMMA); } } sql.append(""); @@ -81,10 +82,10 @@ public String upsert(MappedStatement ms) { continue; } if (logicDeleteColumn != null && logicDeleteColumn == column) { - sql.append(SqlBuilder.getLogicDeletedValue(column, false)).append(","); + sql.append(SqlBuilder.getLogicDeletedValue(column, false)).append(Symbol.COMMA); continue; } - sql.append(column.getColumnHolder() + ","); + sql.append(column.getColumnHolder() + Symbol.COMMA); } sql.append(""); sql.append(" ON CONFLICT (" + primaryKeyColumn + ") DO UPDATE "); diff --git a/bus-mapper/src/main/java/org/miaixz/bus/mapper/builder/SqlBuilder.java b/bus-mapper/src/main/java/org/miaixz/bus/mapper/builder/SqlBuilder.java index e28e230e06..c818867b40 100644 --- a/bus-mapper/src/main/java/org/miaixz/bus/mapper/builder/SqlBuilder.java +++ b/bus-mapper/src/main/java/org/miaixz/bus/mapper/builder/SqlBuilder.java @@ -498,11 +498,11 @@ public static String updateSetColumns(Class entityClass, String entityName, b sql.append(column.getProperty()).append(")\"/>"); sql.append(column.getColumn()).append(" = #{").append(column.getProperty()).append("Version},"); } else if (column == logicDeleteColumn) { - sql.append(logicDeleteColumnEqualsValue(column, false)).append(","); + sql.append(logicDeleteColumnEqualsValue(column, false)).append(Symbol.COMMA); } else if (notNull) { - sql.append(SqlBuilder.getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + ",", notEmpty)); + sql.append(SqlBuilder.getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + Symbol.COMMA, notEmpty)); } else { - sql.append(column.getColumnEqualsHolder(entityName) + ","); + sql.append(column.getColumnEqualsHolder(entityName) + Symbol.COMMA); } } } diff --git a/bus-mapper/src/main/java/org/miaixz/bus/mapper/entity/Condition.java b/bus-mapper/src/main/java/org/miaixz/bus/mapper/entity/Condition.java index bdeb2a9b4e..373d17261b 100644 --- a/bus-mapper/src/main/java/org/miaixz/bus/mapper/entity/Condition.java +++ b/bus-mapper/src/main/java/org/miaixz/bus/mapper/entity/Condition.java @@ -342,7 +342,7 @@ public OrderBy orderBy(String property) { return this; } if (StringKit.isNotEmpty(condition.getOrderByClause())) { - condition.setOrderByClause(condition.getOrderByClause() + "," + column); + condition.setOrderByClause(condition.getOrderByClause() + Symbol.COMMA + column); } else { condition.setOrderByClause(column); } diff --git a/bus-mapper/src/main/java/org/miaixz/bus/mapper/provider/SaveProvider.java b/bus-mapper/src/main/java/org/miaixz/bus/mapper/provider/SaveProvider.java index 3076b46c3d..9b06a8db93 100644 --- a/bus-mapper/src/main/java/org/miaixz/bus/mapper/provider/SaveProvider.java +++ b/bus-mapper/src/main/java/org/miaixz/bus/mapper/provider/SaveProvider.java @@ -1,6 +1,7 @@ package org.miaixz.bus.mapper.provider; import org.apache.ibatis.mapping.MappedStatement; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.MapperException; import org.miaixz.bus.mapper.builder.*; import org.miaixz.bus.mapper.entity.EntityColumn; @@ -75,17 +76,17 @@ public String insert(MappedStatement ms) { // 优先使用传入的属性值,当原属性property!=null时,用原属性 // 自增的情况下,如果默认有值,就会备份到property_cache中,所以这里需要先判断备份的值是否存在 if (column.isIdentity()) { - sql.append(SqlBuilder.getIfCacheNotNull(column, column.getColumnHolder(null, "_cache", ","))); + sql.append(SqlBuilder.getIfCacheNotNull(column, column.getColumnHolder(null, "_cache", Symbol.COMMA))); } else { // 其他情况值仍然存在原property中 - sql.append(SqlBuilder.getIfNotNull(column, column.getColumnHolder(null, null, ","), isNotEmpty())); + sql.append(SqlBuilder.getIfNotNull(column, column.getColumnHolder(null, null, Symbol.COMMA), isNotEmpty())); } // 当属性为null时,如果存在主键策略,会自动获取值,如果不存在,则使用null if (column.isIdentity()) { - sql.append(SqlBuilder.getIfCacheIsNull(column, column.getColumnHolder() + ",")); + sql.append(SqlBuilder.getIfCacheIsNull(column, column.getColumnHolder() + Symbol.COMMA)); } else { // 当null的时候,如果不指定jdbcType,oracle可能会报异常,指定VARCHAR不影响其他 - sql.append(SqlBuilder.getIfIsNull(column, column.getColumnHolder(null, null, ","), isNotEmpty())); + sql.append(SqlBuilder.getIfIsNull(column, column.getColumnHolder(null, null, Symbol.COMMA), isNotEmpty())); } } sql.append(""); diff --git a/bus-mapper/src/main/java/org/miaixz/bus/mapper/provider/SpecialProvider.java b/bus-mapper/src/main/java/org/miaixz/bus/mapper/provider/SpecialProvider.java index c84a39c8a2..0d0c4e4f21 100644 --- a/bus-mapper/src/main/java/org/miaixz/bus/mapper/provider/SpecialProvider.java +++ b/bus-mapper/src/main/java/org/miaixz/bus/mapper/provider/SpecialProvider.java @@ -26,6 +26,7 @@ package org.miaixz.bus.mapper.provider; import org.apache.ibatis.mapping.MappedStatement; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.mapper.builder.EntityBuilder; import org.miaixz.bus.mapper.builder.MapperBuilder; import org.miaixz.bus.mapper.builder.MapperTemplate; @@ -66,7 +67,7 @@ public String insertList(MappedStatement ms) { //当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值 for (EntityColumn column : columnList) { if (!column.isId() && column.isInsertable()) { - sql.append(column.getColumnHolder("record") + ","); + sql.append(column.getColumnHolder("record") + Symbol.COMMA); } } sql.append(""); diff --git a/bus-notify/pom.xml b/bus-notify/pom.xml index 5f54066edc..a2f1f6d792 100755 --- a/bus-notify/pom.xml +++ b/bus-notify/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-notify - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/Builder.java b/bus-notify/src/main/java/org/miaixz/bus/notify/Builder.java index 30fff8e851..e2fd40ba39 100755 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/Builder.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/Builder.java @@ -37,6 +37,7 @@ * @author Kimi Liu * @since Java 17+ */ +@Getter @Setter public class Builder { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/Context.java b/bus-notify/src/main/java/org/miaixz/bus/notify/Context.java index 500ffe25f5..df01b4e609 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/Context.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/Context.java @@ -26,7 +26,8 @@ package org.miaixz.bus.notify; import lombok.Builder; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; /** * 配置信息 @@ -34,7 +35,8 @@ * @author Justubborn * @since Java 17+ */ -@Data +@Getter +@Setter @Builder public class Context { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/Provider.java b/bus-notify/src/main/java/org/miaixz/bus/notify/Provider.java index 4e15f8f8ed..58a8c42fc0 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/Provider.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/Provider.java @@ -33,7 +33,7 @@ import java.util.List; /** - * 通知器,用于发送通知,如: 短信,邮件,语音,微信等s + * 通知器,用于发送通知,如: 短信,邮件,语音,微信等 * * @author Justubborn * @since Java 17+ diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/magic/Message.java b/bus-notify/src/main/java/org/miaixz/bus/notify/magic/Message.java index f084b5e629..b194f45fec 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/magic/Message.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/magic/Message.java @@ -26,7 +26,8 @@ package org.miaixz.bus.notify.magic; import lombok.Builder; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; /** * 返回消息 @@ -34,7 +35,8 @@ * @author Justubborn * @since Java 17+ */ -@Data +@Getter +@Setter @Builder public class Message { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/aliyun/AliyunProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/aliyun/AliyunProperty.java index 17110837d1..d0bd0bc142 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/aliyun/AliyunProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/aliyun/AliyunProperty.java @@ -1,10 +1,12 @@ package org.miaixz.bus.notify.metric.aliyun; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; -@Data +@Getter +@Setter @SuperBuilder public class AliyunProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/baidu/BaiduProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/baidu/BaiduProperty.java index 6e8c2007b6..b0fb2d19b1 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/baidu/BaiduProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/baidu/BaiduProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.baidu; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class BaiduProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/dingtalk/DingTalkProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/dingtalk/DingTalkProperty.java index 68190bc013..7f474cdb4d 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/dingtalk/DingTalkProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/dingtalk/DingTalkProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.dingtalk; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Justubborn * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class DingTalkProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/generic/GenericProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/generic/GenericProperty.java index e98dd45714..b7fbdb8917 100755 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/generic/GenericProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/generic/GenericProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.generic; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.core.lang.Charset; import org.miaixz.bus.core.lang.Symbol; @@ -40,7 +41,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class GenericProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/huawei/HuaweiProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/huawei/HuaweiProperty.java index 52c910ef47..84a4190165 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/huawei/HuaweiProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/huawei/HuaweiProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.huawei; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class HuaweiProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/jdcloud/JdcloudProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/jdcloud/JdcloudProperty.java index e75d512601..9b982dd777 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/jdcloud/JdcloudProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/jdcloud/JdcloudProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.jdcloud; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class JdcloudProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/jpush/JpushProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/jpush/JpushProperty.java index f7a3b4b788..686d5345ec 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/jpush/JpushProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/jpush/JpushProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.jpush; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class JpushProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/netease/NeteaseProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/netease/NeteaseProperty.java index ffa33171c1..7157af338f 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/netease/NeteaseProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/netease/NeteaseProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.netease; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class NeteaseProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/qiniu/QiniuProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/qiniu/QiniuProperty.java index 2f3156cd39..d8d9d77e4c 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/qiniu/QiniuProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/qiniu/QiniuProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.qiniu; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class QiniuProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/tencent/TencentProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/tencent/TencentProperty.java index 4524fa0470..aa7445a3de 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/tencent/TencentProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/tencent/TencentProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.tencent; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class TencentProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/upyun/UpyunProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/upyun/UpyunProperty.java index d99ccf39f6..672f27f754 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/upyun/UpyunProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/upyun/UpyunProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.upyun; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.notify.magic.Property; @@ -36,7 +37,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class UpyunProperty extends Property { @@ -49,7 +51,8 @@ public class UpyunProperty extends Property { /** * 手机号发送短信的结果 */ - @Data + @Getter + @Setter public static class MessageId { /** diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/wechat/WechatProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/wechat/WechatProperty.java index d9dc931555..cd979f116a 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/wechat/WechatProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/wechat/WechatProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.wechat; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class WechatProperty extends Property { diff --git a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/yunpian/YunpianProperty.java b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/yunpian/YunpianProperty.java index f0c77d68f6..9b9aa5c42f 100644 --- a/bus-notify/src/main/java/org/miaixz/bus/notify/metric/yunpian/YunpianProperty.java +++ b/bus-notify/src/main/java/org/miaixz/bus/notify/metric/yunpian/YunpianProperty.java @@ -25,7 +25,8 @@ ********************************************************************************/ package org.miaixz.bus.notify.metric.yunpian; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import lombok.experimental.SuperBuilder; import org.miaixz.bus.notify.magic.Property; @@ -35,7 +36,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @SuperBuilder public class YunpianProperty extends Property { diff --git a/bus-oauth/pom.xml b/bus-oauth/pom.xml index 9deedcfb36..44f6562d72 100755 --- a/bus-oauth/pom.xml +++ b/bus-oauth/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-oauth - 8.0.0 + 8.0.1 jar ${project.artifactId} @@ -97,6 +97,22 @@ org.bouncycastle bcprov-jdk15on + + xml-apis + xml-apis + + + commons-logging + commons-logging + + + com.squareup.okhttp3 + okhttp + + + dom4j + dom4j + diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Authorize.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Authorize.java index b97ad72f27..217bb8ba75 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Authorize.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Authorize.java @@ -29,7 +29,6 @@ import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.oauth.magic.ErrorCode; -import org.miaixz.bus.oauth.metric.AuthorizeProvider; import org.miaixz.bus.oauth.metric.DefaultProvider; import java.util.Arrays; @@ -81,7 +80,7 @@ public Authorize complex(Complex... complex) { return this; } - public AuthorizeProvider build() { + public Provider build() { if (StringKit.isEmpty(this.source) || null == this.context) { throw new AuthorizedException(ErrorCode.NOT_IMPLEMENTED.getCode()); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Builder.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Builder.java index f9e347967c..dd2eae307f 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Builder.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Builder.java @@ -25,6 +25,7 @@ ********************************************************************************/ package org.miaixz.bus.oauth; +import lombok.Getter; import lombok.Setter; import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.lang.Symbol; @@ -47,6 +48,7 @@ * @author Kimi Liu * @since Java 17+ */ +@Getter @Setter public class Builder { diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Checker.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Checker.java index 8fe156b8f0..4275d8f865 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Checker.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Checker.java @@ -51,18 +51,18 @@ public static boolean isSupportedAuth(Context context, Complex complex) { boolean isSupported = StringKit.isNotEmpty(context.getAppKey()) && StringKit.isNotEmpty(context.getAppSecret()); if (isSupported && Registry.STACK_OVERFLOW == complex) { - isSupported = StringKit.isNotEmpty(context.getStackOverflowKey()); + isSupported = StringKit.isNotEmpty(context.getUnionId()); } if (isSupported && Registry.WECHAT_EE == complex) { - isSupported = StringKit.isNotEmpty(context.getAgentId()); + isSupported = StringKit.isNotEmpty(context.getUnionId()); } if (isSupported && (Registry.CODING == complex || Registry.OKTA == complex)) { isSupported = StringKit.isNotEmpty(context.getPrefix()); } if (isSupported && Registry.XIMALAYA == complex) { - isSupported = StringKit.isNotEmpty(context.getDeviceId()) && null != context.getClientOsType(); + isSupported = StringKit.isNotEmpty(context.getDeviceId()) && null != context.getType(); if (isSupported) { - isSupported = context.getClientOsType() == 3 || StringKit.isNotEmpty(context.getPackId()); + isSupported = "3".equals(context.getType()) || StringKit.isNotEmpty(context.getUnionId()); } } return isSupported; @@ -76,7 +76,7 @@ public static boolean isSupportedAuth(Context context, Complex complex) { */ public static void checkConfig(Context context, Complex complex) { String redirectUri = context.getRedirectUri(); - if (context.isIgnoreCheckRedirectUri()) { + if (context.isIgnoreRedirectUri()) { return; } if (StringKit.isEmpty(redirectUri)) { diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Complex.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Complex.java index 38f2c6f7ae..8437dc129d 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Complex.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Complex.java @@ -28,7 +28,6 @@ import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.oauth.magic.Callback; import org.miaixz.bus.oauth.magic.ErrorCode; -import org.miaixz.bus.oauth.metric.AuthorizeProvider; import org.miaixz.bus.oauth.metric.DefaultProvider; /** @@ -41,7 +40,7 @@ * 注: * ①、如需通过扩展实现第三方授权,请参考{@link Registry}自行创建对应的枚举类并实现{@link Complex}接口 * ②、如果不是使用的枚举类,那么在授权成功后获取用户信息时,需要单独处理source字段的赋值 - * ③、如果扩展了对应枚举类时,在{@link AuthorizeProvider#login(Callback)}中可以通过{@code xx.toString()}获取对应的source + * ③、如果扩展了对应枚举类时,在{@link Provider#login(Callback)}中可以通过{@code xx.toString()}获取对应的source * * @author Kimi Liu * @since Java 17+ diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Context.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Context.java index c42a57fcc7..6c79d72ad8 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Context.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Context.java @@ -27,7 +27,6 @@ import lombok.Builder; import lombok.*; -import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.oauth.magic.Callback; import org.miaixz.bus.oauth.metric.DefaultProvider; @@ -57,31 +56,39 @@ public class Context { private String appSecret; /** - * 登录成功后的回调地址 + * 1. 支付宝 publicKey + * 1. 企业微信,授权方的网页应用agentId + * 2. OktaScope 授权服务器的 ID, 默认为 default + * 3. MicrosoftScope Entra ID(原微软 AAD)中的租户 ID + * 4. 喜马拉雅客户端包名,如果 {@link Context#type} 为1或2时必填。1-对Android客户端是包名,2-对IOS客户端是Bundle ID */ - private String redirectUri; + private String unionId; /** - * 是否需要申请unionid,目前只针对qq登录 - * 注:QQ授权登录时,获取unionid需要单独发送邮件申请权限。如果个人开发者账号中申请了该权限,可以将该值置为true,在获取openId时就会同步获取unionId - * 参考链接:http://wiki.connect.qq.com/unionid%E4%BB%8B%E7%BB%8D + * 设备ID, 设备唯一标识ID */ - private boolean unionId; + private String deviceId; /** - * Stack Overflow Key + * 类型 + * 1. 企业微信第三方授权用户类型,member|admin + * 2. 喜马拉雅客户端操作系统,1-iOS系统,2-Android系统,3-Web */ - private String stackOverflowKey; + private String type; /** - * 企业微信,授权方的网页应用ID + * 标记 + * 1. 是否需要申请unionid,目前只针对qq登录 + * 注:QQ授权登录时,获取unionid需要单独发送邮件申请权限。如果个人开发者账号中申请了该权限,可以将该值置为true,在获取openId时就会同步获取unionId + * 参考链接:http://wiki.connect.qq.com/unionid%E4%BB%8B%E7%BB%8D */ - private String agentId; + private boolean flag; /** - * 企业微信第三方授权用户类型,member|admin + * PKCE 模式 + * 该配置仅用于支持 PKCE 模式的平台,针对无服务应用,不推荐使用隐式授权,推荐使用 PKCE 模式 */ - private String usertype; + private boolean pkce; /** * 域名前缀 @@ -90,7 +97,18 @@ public class Context { private String prefix; /** - * 忽略校验 {@code state} 参数,默认不开启。当 {@code ignoreCheckState} 为 {@code true} 时, + * 回调地址 + */ + private String redirectUri; + + /** + * 自定义授权平台的 scope 内容 + */ + private List scopes; + + /** + * 忽略校验 {@code state} + * 默认不开启。当 {@code ignoreCheckState} 为 {@code true} 时, * {@link DefaultProvider#login(Callback)} 将不会校验 {@code state} 的合法性。 *

      * 使用场景:当且仅当使用自实现 {@code state} 校验逻辑时开启 @@ -102,57 +120,13 @@ public class Context { * * 如非特殊需要,不建议开启这个配置 */ - private boolean ignoreCheckState; + private boolean ignoreState; /** - * 支持自定义授权平台的 scope 内容 - */ - private List scopes; - - /** - * 设备ID, 设备唯一标识ID - */ - private String deviceId; - - /** - * 喜马拉雅:客户端操作系统类型,1-iOS系统,2-Android系统,3-Web - */ - private Integer clientOsType; - - /** - * 喜马拉雅:客户端包名,如果 {@link Context#clientOsType} 为1或2时必填。对Android客户端是包名,对IOS客户端是Bundle ID - */ - private String packId; - - /** - * 是否开启 PKCE 模式,该配置仅用于支持 PKCE 模式的平台,针对无服务应用,不推荐使用隐式授权,推荐使用 PKCE 模式 - */ - private boolean pkce; - - /** - * OktaScope 授权服务器的 ID, 默认为 default。如果要使用自定义授权服务,此处传实际的授权服务器 ID(一个随机串) - * 创建自定义授权服务器,请参考: - * ① https://developer.okta.com/docs/concepts/auth-servers - * ② https://developer.okta.com/docs/guides/customize-authz-server - */ - private String authServerId; - /** - * 忽略校验 {@code redirectUri} 参数,默认不开启。当 {@code ignoreCheckRedirectUri} 为 {@code true} 时, + * 忽略校验 {@code redirectUri} + * {@code redirectUri} 参数,默认不开启。当 {@code ignoreCheckRedirectUri} 为 {@code true} 时, * {@link Checker#checkConfig(Context, Complex)} 将不会校验 {@code redirectUri} 的合法性。 */ - private boolean ignoreCheckRedirectUri; - /** - * MicrosoftScope Entra ID(原微软 AAD)中的租户 ID - */ - private String tenantId; - - /** - * 适配 builder 模式 set 值的情况 - * - * @return authServerId - */ - public String getAuthServerId() { - return StringKit.isEmpty(authServerId) ? "default" : authServerId; - } + private boolean ignoreRedirectUri; } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/AuthorizeProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Provider.java similarity index 93% rename from bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/AuthorizeProvider.java rename to bus-oauth/src/main/java/org/miaixz/bus/oauth/Provider.java index 45f7ee6dba..810ce6e724 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/AuthorizeProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Provider.java @@ -23,7 +23,7 @@ * THE SOFTWARE. * * * ********************************************************************************/ -package org.miaixz.bus.oauth.metric; +package org.miaixz.bus.oauth; import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.oauth.magic.AccToken; @@ -33,15 +33,15 @@ /** * {@code Request}公共接口,所有平台的{@code Request}都需要实现该接口 - * {@link AuthorizeProvider#authorize(String)} - * {@link AuthorizeProvider#login(Callback)} - * {@link AuthorizeProvider#revoke(AccToken)} - * {@link AuthorizeProvider#refresh(AccToken)} + * {@link Provider#authorize(String)} + * {@link Provider#login(Callback)} + * {@link Provider#revoke(AccToken)} + * {@link Provider#refresh(AccToken)} * * @author Kimi Liu * @since Java 17+ */ -public interface AuthorizeProvider { +public interface Provider { /** * 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state} diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Registry.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Registry.java index 8dc70411b3..600dd62ff4 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/Registry.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/Registry.java @@ -1288,16 +1288,25 @@ public String userInfo() { return "https://api.ximalaya.com/profile/user_info"; } - @Deprecated - @Override - public String refresh() { - return "https://oauth.aliyun.com/v1/token"; - } - @Override public Class getTargetClass() { return XimalayaProvider.class; } + }; + + /** + * 根据名称获取第三方授权登录 + * + * @param name 第三方名称简写 + * @return 第三方授权登录, 找不到时直接抛出异常 + */ + public static Registry require(String name) { + for (Registry registry : Registry.values()) { + if (registry.name().equalsIgnoreCase(name)) { + return registry; + } + } + throw new IllegalArgumentException("Unsupported type for " + name); } } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/magic/Message.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/magic/Message.java index 7d3d6d076e..8fbf95d2cb 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/magic/Message.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/magic/Message.java @@ -25,10 +25,7 @@ ********************************************************************************/ package org.miaixz.bus.oauth.magic; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; +import lombok.*; /** * 统一授权响应类 @@ -36,7 +33,8 @@ * @author Kimi Liu * @since Java 17+ */ -@Data +@Getter +@Setter @Builder @NoArgsConstructor @AllArgsConstructor diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/DefaultProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/DefaultProvider.java index 4f81e40c6d..fc8303a84b 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/DefaultProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/DefaultProvider.java @@ -34,10 +34,7 @@ import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.http.Httpx; import org.miaixz.bus.logger.Logger; -import org.miaixz.bus.oauth.Builder; -import org.miaixz.bus.oauth.Checker; -import org.miaixz.bus.oauth.Complex; -import org.miaixz.bus.oauth.Context; +import org.miaixz.bus.oauth.*; import org.miaixz.bus.oauth.cache.OauthCache; import org.miaixz.bus.oauth.magic.*; @@ -51,7 +48,7 @@ * @author Kimi Liu * @since Java 17+ */ -public abstract class DefaultProvider implements AuthorizeProvider { +public abstract class DefaultProvider implements Provider { protected Context context; protected Complex complex; @@ -130,7 +127,7 @@ public static List getScopes(AuthorizeScope... scopes) { public Message login(Callback authCallback) { try { checkCode(authCallback); - if (!context.isIgnoreCheckState()) { + if (!context.isIgnoreState()) { Checker.checkState(authCallback.getState(), complex, authorizeCache); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/alipay/AlipayProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/alipay/AlipayProvider.java index 415097afbb..fb9bdfa443 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/alipay/AlipayProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/alipay/AlipayProvider.java @@ -34,6 +34,7 @@ import com.alipay.api.response.AlipaySystemOauthTokenResponse; import com.alipay.api.response.AlipayUserInfoShareResponse; import org.miaixz.bus.cache.metric.ExtendCache; +import org.miaixz.bus.core.lang.Charset; import org.miaixz.bus.core.lang.Gender; import org.miaixz.bus.core.lang.Http; import org.miaixz.bus.core.lang.exception.AuthorizedException; @@ -58,84 +59,50 @@ public class AlipayProvider extends DefaultProvider { * 支付宝公钥:当选择支付宝登录时,该值可用 * 对应“RSA2(SHA256)密钥”中的“支付宝公钥” */ - private final String alipayPublicKey; private final AlipayClient alipayClient; - /** - * @see AlipayProvider#AlipayProvider(Context, java.lang.String) - * @deprecated 请使用带有"alipayPublicKey"参数的构造方法 - */ - @Deprecated - public AlipayProvider(Context context) { - this(context, (String) null); - } - - /** - * @see AlipayProvider#AlipayProvider(Context, java.lang.String, ExtendCache) - * @deprecated 请使用带有"alipayPublicKey"参数的构造方法 - */ - @Deprecated - public AlipayProvider(Context context, ExtendCache authorizeCache) { - this(context, null, authorizeCache); - } - - /** - * @see AlipayProvider#AlipayProvider(Context, java.lang.String, ExtendCache, java.lang.String, java.lang.Integer) - * @deprecated 请使用带有"alipayPublicKey"参数的构造方法 - */ - @Deprecated - public AlipayProvider(Context context, ExtendCache authorizeCache, String proxyHost, Integer proxyPort) { - this(context, null, authorizeCache, proxyHost, proxyPort); - } - /** * 构造方法,需要设置"alipayPublicKey" * - * @param context 公共的OAuth配置 - * @param alipayPublicKey 支付宝公钥 + * @param context 公共的OAuth配置 * @see AlipayProvider#AlipayProvider(Context) */ - public AlipayProvider(Context context, String alipayPublicKey) { + public AlipayProvider(Context context) { super(context, Registry.ALIPAY); - this.alipayPublicKey = alipayPublicKey; check(context); - this.alipayClient = new DefaultAlipayClient(GATEWAY, context.getAppKey(), context.getAppSecret(), "json", "UTF-8", this.alipayPublicKey, "RSA2"); + this.alipayClient = new DefaultAlipayClient(GATEWAY, context.getAppKey(), context.getAppSecret(), "json", Charset.DEFAULT_UTF_8, context.getUnionId(), "RSA2"); } /** * 构造方法,需要设置"alipayPublicKey" * - * @param context 公共的OAuth配置 - * @param alipayPublicKey 支付宝公钥 + * @param context 公共的OAuth配置 * @see AlipayProvider#AlipayProvider(Context, ExtendCache) */ - public AlipayProvider(Context context, String alipayPublicKey, ExtendCache authorizeCache) { + public AlipayProvider(Context context, ExtendCache authorizeCache) { super(context, Registry.ALIPAY, authorizeCache); - this.alipayPublicKey = alipayPublicKey; check(context); this.alipayClient = new DefaultAlipayClient(GATEWAY, context.getAppKey(), context.getAppSecret(), - "json", "UTF-8", this.alipayPublicKey, "RSA2"); + "json", Charset.DEFAULT_UTF_8, context.getUnionId(), "RSA2"); } /** * 构造方法,需要设置"alipayPublicKey" * - * @param context 公共的OAuth配置 - * @param alipayPublicKey 支付宝公钥 + * @param context 公共的OAuth配置 * @see AlipayProvider#AlipayProvider(Context, ExtendCache, java.lang.String, java.lang.Integer) */ - public AlipayProvider(Context context, String alipayPublicKey, ExtendCache authorizeCache, String proxyHost, Integer proxyPort) { + public AlipayProvider(Context context, ExtendCache authorizeCache, String proxyHost, Integer proxyPort) { super(context, Registry.ALIPAY, authorizeCache); - this.alipayPublicKey = alipayPublicKey; check(context); this.alipayClient = new DefaultAlipayClient(GATEWAY, context.getAppKey(), context.getAppSecret(), - "json", "UTF-8", this.alipayPublicKey, "RSA2", proxyHost, proxyPort); + "json", Charset.DEFAULT_UTF_8, context.getUnionId(), "RSA2", proxyHost, proxyPort); } protected void check(Context context) { Checker.checkConfig(context, Registry.ALIPAY); - if (!StringKit.isNotEmpty(alipayPublicKey)) { + if (!StringKit.isNotEmpty(context.getUnionId())) { throw new AuthorizedException(ErrorCode.PARAMETER_INCOMPLETE.getCode(), Registry.ALIPAY); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/douyin/DouyinProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/douyin/DouyinProvider.java index 419a433140..95de0a9fd5 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/douyin/DouyinProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/douyin/DouyinProvider.java @@ -132,7 +132,7 @@ public String authorize(String state) { .queryParam("response_type", "code") .queryParam("client_key", context.getAppKey()) .queryParam("redirect_uri", context.getRedirectUri()) - .queryParam("scope", this.getScopes(",", true, this.getDefaultScopes(DouyinScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, true, this.getDefaultScopes(DouyinScope.values()))) .queryParam("state", getRealState(state)) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/facebook/FacebookProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/facebook/FacebookProvider.java index 5d54c743cc..58fb6237aa 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/facebook/FacebookProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/facebook/FacebookProvider.java @@ -28,6 +28,7 @@ import com.alibaba.fastjson.JSONObject; import org.miaixz.bus.cache.metric.ExtendCache; import org.miaixz.bus.core.lang.Gender; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.oauth.Builder; import org.miaixz.bus.oauth.Context; @@ -131,7 +132,8 @@ private void checkResponse(JSONObject object) { @Override public String authorize(String state) { return Builder.fromUrl(super.authorize(state)) - .queryParam("scope", this.getScopes(",", false, this.getDefaultScopes(FacebookScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, false, this.getDefaultScopes(FacebookScope.values()))) .build(); } + } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/kujiale/KujialeProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/kujiale/KujialeProvider.java index abf4e782ad..858e277e54 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/kujiale/KujialeProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/kujiale/KujialeProvider.java @@ -27,6 +27,7 @@ import com.alibaba.fastjson.JSONObject; import org.miaixz.bus.cache.metric.ExtendCache; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.http.Httpx; import org.miaixz.bus.oauth.Builder; @@ -61,7 +62,7 @@ public KujialeProvider(Context context, ExtendCache authorizeCache) { @Override public String authorize(String state) { return Builder.fromUrl(super.authorize(state)) - .queryParam("scope", this.getScopes(",", false, this.getDefaultScopes(KujialeScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, false, this.getDefaultScopes(KujialeScope.values()))) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/microsoft/AbstractMicrosoftProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/microsoft/AbstractMicrosoftProvider.java index 8e7dc5e610..339e47977a 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/microsoft/AbstractMicrosoftProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/microsoft/AbstractMicrosoftProvider.java @@ -144,7 +144,7 @@ public Message refresh(AccToken accToken) { @Override public String authorize(String state) { // 兼容 MicrosoftScope Entra ID 登录(原微软 AAD) - String tenantId = StringKit.isEmpty(context.getTenantId()) ? "common" : context.getTenantId(); + String tenantId = StringKit.isEmpty(context.getUnionId()) ? "common" : context.getUnionId(); return Builder.fromUrl(String.format(complex.authorize(), tenantId)) .queryParam("response_type", "code") .queryParam("client_id", context.getAppKey()) @@ -163,7 +163,7 @@ public String authorize(String state) { */ @Override protected String accessTokenUrl(String code) { - String tenantId = StringKit.isEmpty(context.getTenantId()) ? "common" : context.getTenantId(); + String tenantId = StringKit.isEmpty(context.getUnionId()) ? "common" : context.getUnionId(); return Builder.fromUrl(String.format(complex.accessToken(), tenantId)) .queryParam("code", code) .queryParam("client_id", context.getAppKey()) @@ -193,7 +193,7 @@ protected String userInfoUrl(AccToken accToken) { */ @Override protected String refreshTokenUrl(String refreshToken) { - String tenantId = StringKit.isEmpty(context.getTenantId()) ? "common" : context.getTenantId(); + String tenantId = StringKit.isEmpty(context.getUnionId()) ? "common" : context.getUnionId(); return Builder.fromUrl(String.format(complex.refresh(), tenantId)) .queryParam("client_id", context.getAppKey()) .queryParam("client_secret", context.getAppSecret()) diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/okta/OktaProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/okta/OktaProvider.java index 17a23937ba..9ac5246e51 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/okta/OktaProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/okta/OktaProvider.java @@ -31,6 +31,7 @@ import org.miaixz.bus.core.lang.Gender; import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.AuthorizedException; +import org.miaixz.bus.core.xyz.ObjectKit; import org.miaixz.bus.http.Httpx; import org.miaixz.bus.oauth.Builder; import org.miaixz.bus.oauth.Context; @@ -139,7 +140,7 @@ private void checkResponse(JSONObject object) { @Override public String authorize(String state) { - return Builder.fromUrl(String.format(complex.authorize(), context.getPrefix(), context.getAuthServerId())) + return Builder.fromUrl(String.format(complex.authorize(), context.getPrefix(), ObjectKit.defaultIfNull(context.getUnionId(), "default"))) .queryParam("response_type", "code") .queryParam("prompt", "consent") .queryParam("client_id", context.getAppKey()) @@ -151,7 +152,7 @@ public String authorize(String state) { @Override public String accessTokenUrl(String code) { - return Builder.fromUrl(String.format(complex.accessToken(), context.getPrefix(), context.getAuthServerId())) + return Builder.fromUrl(String.format(complex.accessToken(), context.getPrefix(), ObjectKit.defaultIfNull(context.getUnionId(), "default"))) .queryParam("code", code) .queryParam("grant_type", "authorization_code") .queryParam("redirect_uri", context.getRedirectUri()) @@ -160,7 +161,7 @@ public String accessTokenUrl(String code) { @Override protected String refreshTokenUrl(String refreshToken) { - return Builder.fromUrl(String.format(complex.refresh(), context.getPrefix(), context.getAuthServerId())) + return Builder.fromUrl(String.format(complex.refresh(), context.getPrefix(), ObjectKit.defaultIfNull(context.getUnionId(), "default"))) .queryParam("refresh_token", refreshToken) .queryParam("grant_type", "refresh_token") .build(); @@ -168,12 +169,12 @@ protected String refreshTokenUrl(String refreshToken) { @Override protected String revokeUrl(AccToken accToken) { - return String.format(complex.revoke(), context.getPrefix(), context.getAuthServerId()); + return String.format(complex.revoke(), context.getPrefix(), ObjectKit.defaultIfNull(context.getUnionId(), "default")); } @Override public String userInfoUrl(AccToken accToken) { - return String.format(complex.userInfo(), context.getPrefix(), context.getAuthServerId()); + return String.format(complex.userInfo(), context.getPrefix(), ObjectKit.defaultIfNull(context.getUnionId(), "default")); } } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/pinterest/PinterestProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/pinterest/PinterestProvider.java index 18df53b73b..6c7ed305ea 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/pinterest/PinterestProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/pinterest/PinterestProvider.java @@ -109,7 +109,7 @@ private String getAvatarUrl(JSONObject userObj) { @Override public String authorize(String state) { return Builder.fromUrl(super.authorize(state)) - .queryParam("scope", this.getScopes(",", false, this.getDefaultScopes(PinterestScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, false, this.getDefaultScopes(PinterestScope.values()))) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/qq/QqProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/qq/QqProvider.java index ccbf30721f..6ad54daaed 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/qq/QqProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/qq/QqProvider.java @@ -104,7 +104,7 @@ protected Property getUserInfo(AccToken accToken) { private String getOpenId(AccToken accToken) { String response = Httpx.get(Builder.fromUrl("https://graph.qq.com/oauth2.0/me") .queryParam("access_token", accToken.getAccessToken()) - .queryParam("unionid", context.isUnionId() ? 1 : 0) + .queryParam("unionid", context.isFlag() ? 1 : 0) .build()); String removePrefix = response.replace("callback(", ""); String removeSuffix = removePrefix.replace(");", ""); @@ -150,7 +150,7 @@ private AccToken getAuthToken(String response) { @Override public String authorize(String state) { return Builder.fromUrl(super.authorize(state)) - .queryParam("scope", this.getScopes(",", false, this.getDefaultScopes(QqScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, false, this.getDefaultScopes(QqScope.values()))) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/renren/RenrenProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/renren/RenrenProvider.java index c9d30bf520..b8e18e16fe 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/renren/RenrenProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/renren/RenrenProvider.java @@ -29,6 +29,7 @@ import com.alibaba.fastjson.JSONObject; import org.miaixz.bus.cache.metric.ExtendCache; import org.miaixz.bus.core.lang.Gender; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.core.net.url.UrlEncoder; import org.miaixz.bus.http.Httpx; @@ -143,7 +144,7 @@ protected String userInfoUrl(AccToken accToken) { @Override public String authorize(String state) { return Builder.fromUrl(super.authorize(state)) - .queryParam("scope", this.getScopes(",", false, this.getDefaultScopes(RenrenScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, false, this.getDefaultScopes(RenrenScope.values()))) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/slack/SlackProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/slack/SlackProvider.java index 9459389b37..e65044e4bb 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/slack/SlackProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/slack/SlackProvider.java @@ -29,6 +29,7 @@ import com.alibaba.fastjson.JSONObject; import org.miaixz.bus.cache.metric.ExtendCache; import org.miaixz.bus.core.lang.Gender; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.core.xyz.StringKit; import org.miaixz.bus.http.Httpx; @@ -119,7 +120,7 @@ private void checkResponse(JSONObject object) { if (object.containsKey("response_metadata")) { JSONArray array = object.getJSONObject("response_metadata").getJSONArray("messages"); if (null != array && array.size() > 0) { - errorMsg += "; " + StringKit.join(",", array.toArray(new String[0])); + errorMsg += "; " + StringKit.join(Symbol.COMMA, array.toArray(new String[0])); } } throw new AuthorizedException(errorMsg); @@ -145,7 +146,7 @@ public String authorize(String state) { .queryParam("client_id", context.getAppKey()) .queryParam("state", getRealState(state)) .queryParam("redirect_uri", context.getRedirectUri()) - .queryParam("scope", this.getScopes(",", true, this.getDefaultScopes(SlackScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, true, this.getDefaultScopes(SlackScope.values()))) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/stackoverflow/StackOverflowProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/stackoverflow/StackOverflowProvider.java index 99ccf76d7f..2476293f07 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/stackoverflow/StackOverflowProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/stackoverflow/StackOverflowProvider.java @@ -30,6 +30,7 @@ import org.miaixz.bus.core.lang.Charset; import org.miaixz.bus.core.lang.Gender; import org.miaixz.bus.core.lang.Header; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.core.net.url.UrlDecoder; import org.miaixz.bus.http.Httpx; @@ -84,7 +85,7 @@ protected Property getUserInfo(AccToken accToken) { String userInfoUrl = Builder.fromUrl(this.complex.userInfo()) .queryParam("access_token", accToken.getAccessToken()) .queryParam("site", "stackoverflow") - .queryParam("key", this.context.getStackOverflowKey()) + .queryParam("key", this.context.getUnionId()) .build(); String response = Httpx.get(userInfoUrl); JSONObject object = JSONObject.parseObject(response); @@ -113,7 +114,7 @@ protected Property getUserInfo(AccToken accToken) { @Override public String authorize(String state) { return Builder.fromUrl(super.authorize(state)) - .queryParam("scope", this.getScopes(",", false, this.getDefaultScopes(StackoverflowScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, false, this.getDefaultScopes(StackoverflowScope.values()))) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeQrcodeProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeQrcodeProvider.java index 0b422f442d..1218976e1c 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeQrcodeProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeQrcodeProvider.java @@ -50,7 +50,7 @@ public WeChatEeQrcodeProvider(Context context, ExtendCache authorizeCache) { public String authorize(String state) { return Builder.fromUrl(complex.authorize()) .queryParam("appid", context.getAppKey()) - .queryParam("agentid", context.getAgentId()) + .queryParam("agentid", context.getUnionId()) .queryParam("redirect_uri", context.getRedirectUri()) .queryParam("state", getRealState(state)) .build(); diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeThirdQrcodeProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeThirdQrcodeProvider.java index 14d0b7e83e..60bb09b20f 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeThirdQrcodeProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeThirdQrcodeProvider.java @@ -59,14 +59,14 @@ public String authorize(String state) { .queryParam("appid", context.getAppKey()) .queryParam("redirect_uri", context.getRedirectUri()) .queryParam("state", getRealState(state)) - .queryParam("usertype", context.getUsertype()) + .queryParam("usertype", context.getType()) .build(); } @Override public Message login(Callback authCallback) { try { - if (!context.isIgnoreCheckState()) { + if (!context.isIgnoreState()) { Checker.checkState(authCallback.getState(), complex, authorizeCache); } AccToken accToken = this.getAccessToken(authCallback); diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeWebProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeWebProvider.java index f9eedd6eec..8322e9e445 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeWebProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/ee/WeChatEeWebProvider.java @@ -26,6 +26,7 @@ package org.miaixz.bus.oauth.metric.wechat.ee; import org.miaixz.bus.cache.metric.ExtendCache; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.net.url.UrlEncoder; import org.miaixz.bus.oauth.Builder; import org.miaixz.bus.oauth.Context; @@ -51,10 +52,10 @@ public WeChatEeWebProvider(Context context, ExtendCache authorizeCache) { public String authorize(String state) { return Builder.fromUrl(complex.authorize()) .queryParam("appid", context.getAppKey()) - .queryParam("agentid", context.getAgentId()) + .queryParam("agentid", context.getUnionId()) .queryParam("redirect_uri", UrlEncoder.encodeAll(context.getRedirectUri())) .queryParam("response_type", "code") - .queryParam("scope", this.getScopes(",", false, this.getDefaultScopes(WeChatEeWebScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, false, this.getDefaultScopes(WeChatEeWebScope.values()))) .queryParam("state", getRealState(state).concat("#wechat_redirect")) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/mp/WeChatMpProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/mp/WeChatMpProvider.java index fea77b58cf..76b7cd2b18 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/mp/WeChatMpProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/wechat/mp/WeChatMpProvider.java @@ -27,6 +27,7 @@ import com.alibaba.fastjson.JSONObject; import org.miaixz.bus.cache.metric.ExtendCache; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.core.net.url.UrlEncoder; import org.miaixz.bus.core.xyz.StringKit; @@ -155,7 +156,7 @@ public String authorize(String state) { .queryParam("appid", context.getAppKey()) .queryParam("redirect_uri", UrlEncoder.encodeAll(context.getRedirectUri())) .queryParam("response_type", "code") - .queryParam("scope", this.getScopes(",", false, this.getDefaultScopes(WechatMpScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, false, this.getDefaultScopes(WechatMpScope.values()))) .queryParam("state", getRealState(state).concat("#wechat_redirect")) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/weibo/WeiboProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/weibo/WeiboProvider.java index a51ed58ee8..966ef181ca 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/weibo/WeiboProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/weibo/WeiboProvider.java @@ -28,6 +28,7 @@ import com.alibaba.fastjson.JSONObject; import org.miaixz.bus.cache.metric.ExtendCache; import org.miaixz.bus.core.lang.Gender; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.AuthorizedException; import org.miaixz.bus.core.xyz.NetKit; import org.miaixz.bus.core.xyz.StringKit; @@ -119,7 +120,7 @@ protected String userInfoUrl(AccToken accToken) { @Override public String authorize(String state) { return Builder.fromUrl(super.authorize(state)) - .queryParam("scope", this.getScopes(",", false, this.getDefaultScopes(WeiboScope.values()))) + .queryParam("scope", this.getScopes(Symbol.COMMA, false, this.getDefaultScopes(WeiboScope.values()))) .build(); } diff --git a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/ximalaya/XimalayaProvider.java b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/ximalaya/XimalayaProvider.java index 6e7d73a20a..b9ac231a3f 100644 --- a/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/ximalaya/XimalayaProvider.java +++ b/bus-oauth/src/main/java/org/miaixz/bus/oauth/metric/ximalaya/XimalayaProvider.java @@ -31,7 +31,9 @@ import org.miaixz.bus.core.lang.Algorithm; import org.miaixz.bus.core.lang.Charset; import org.miaixz.bus.core.lang.Gender; +import org.miaixz.bus.core.lang.Normal; import org.miaixz.bus.core.lang.exception.AuthorizedException; +import org.miaixz.bus.core.xyz.ObjectKit; import org.miaixz.bus.http.Httpx; import org.miaixz.bus.oauth.Builder; import org.miaixz.bus.oauth.Context; @@ -44,7 +46,6 @@ import java.security.MessageDigest; import java.util.HashMap; import java.util.Map; -import java.util.Optional; import java.util.TreeMap; /** @@ -158,9 +159,9 @@ private void checkResponse(JSONObject object) { public Property getUserInfo(AccToken accToken) { Map map = new TreeMap<>(); map.put("app_key", context.getAppKey()); - map.put("client_os_type", Optional.ofNullable(context.getClientOsType()).orElse(3).toString()); + map.put("client_os_type", ObjectKit.defaultIfNull(context.getType(), Normal._3)); map.put("device_id", context.getDeviceId()); - map.put("pack_id", context.getPackId()); + map.put("pack_id", context.getUnionId()); map.put("access_token", accToken.getAccessToken()); map.put("sig", sign(map, context.getAppSecret())); String rawUserInfo = Httpx.get(complex.userInfo(), map); diff --git a/bus-office/pom.xml b/bus-office/pom.xml index cdbd45281f..9050ea3389 100755 --- a/bus-office/pom.xml +++ b/bus-office/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-office - 8.0.0 + 8.0.1 jar ${project.artifactId} @@ -58,6 +58,24 @@ poi-ooxml ${poi.version} true + + + commons-io + commons-io + + + commons-codec + commons-codec + + + org.apache.commons + commons-compress + + + org.apache.logging.log4j + log4j-api + + org.ofdrw @@ -66,12 +84,28 @@ true - bcpkix-jdk15on org.bouncycastle + bcpkix-jdk15on - bcprov-jdk15on org.bouncycastle + bcprov-jdk15on + + + commons-io + commons-io + + + commons-logging + commons-logging + + + org.slf4j + slf4j-api + + + org.json + json diff --git a/bus-office/src/main/java/org/miaixz/bus/office/csv/CsvWriter.java b/bus-office/src/main/java/org/miaixz/bus/office/csv/CsvWriter.java index 1879ea6804..6b70588df7 100644 --- a/bus-office/src/main/java/org/miaixz/bus/office/csv/CsvWriter.java +++ b/bus-office/src/main/java/org/miaixz/bus/office/csv/CsvWriter.java @@ -276,15 +276,16 @@ public CsvWriter write(final CsvData csvData) { /** * 将一个Bean集合写出到Writer,并自动生成表头 * - * @param beans Bean集合 + * @param beans Bean集合 + * @param properties 可选属性列表,空表示全部属性 * @return this */ - public CsvWriter writeBeans(final Iterable beans) { + public CsvWriter writeBeans(final Iterable beans, final String... properties) { if (CollKit.isNotEmpty(beans)) { boolean isFirst = true; Map map; for (final Object bean : beans) { - map = BeanKit.beanToMap(bean); + map = BeanKit.beanToMap(bean, properties); if (isFirst) { writeHeaderLine(map.keySet().toArray(new String[0])); isFirst = false; diff --git a/bus-office/src/main/java/org/miaixz/bus/office/excel/ExcelWriter.java b/bus-office/src/main/java/org/miaixz/bus/office/excel/ExcelWriter.java index 542410d44f..58ae8e50ee 100644 --- a/bus-office/src/main/java/org/miaixz/bus/office/excel/ExcelWriter.java +++ b/bus-office/src/main/java/org/miaixz/bus/office/excel/ExcelWriter.java @@ -38,6 +38,7 @@ import org.miaixz.bus.core.compare.IndexedCompare; import org.miaixz.bus.core.lang.Assert; import org.miaixz.bus.core.lang.EnumMap; +import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.lang.exception.InternalException; import org.miaixz.bus.core.xyz.*; import org.miaixz.bus.office.excel.cell.CellEditor; @@ -1236,7 +1237,7 @@ public ExcelWriter setRowStyle(final int y, final CellStyle style) { */ public ExcelWriter setRowStyleIfHasData(final int y, final CellStyle style) { if (y < 0) { - throw new IllegalArgumentException("Invalid row number (" + y + ")"); + throw new IllegalArgumentException("Invalid row number (" + y + Symbol.PARENTHESE_RIGHT); } final int columnCount = this.getColumnCount(); for (int i = 0; i < columnCount; i++) { @@ -1271,10 +1272,10 @@ public ExcelWriter setColumnStyle(final int x, final CellStyle style) { */ public ExcelWriter setColumnStyleIfHasData(final int x, final int y, final CellStyle style) { if (x < 0) { - throw new IllegalArgumentException("Invalid column number (" + x + ")"); + throw new IllegalArgumentException("Invalid column number (" + x + Symbol.PARENTHESE_RIGHT); } if (y < 0) { - throw new IllegalArgumentException("Invalid row number (" + y + ")"); + throw new IllegalArgumentException("Invalid row number (" + y + Symbol.PARENTHESE_RIGHT); } final int rowCount = this.getRowCount(); for (int i = y; i < rowCount; i++) { diff --git a/bus-office/src/main/java/org/miaixz/bus/office/excel/cell/CellValue.java b/bus-office/src/main/java/org/miaixz/bus/office/excel/cell/CellValue.java index 46eef50c2e..378ac2e36c 100644 --- a/bus-office/src/main/java/org/miaixz/bus/office/excel/cell/CellValue.java +++ b/bus-office/src/main/java/org/miaixz/bus/office/excel/cell/CellValue.java @@ -27,6 +27,7 @@ /** * 抽象的单元格值接口,用于判断不同类型的单元格值 + * 通过自定义的此接口,对于复杂的单元格值类型,可以自定义读取值的类型,如数字、公式等。 * * @param 值得类型 * @author Kimi Liu diff --git a/bus-opencv/pom.xml b/bus-opencv/pom.xml index 3e26784931..28ca026906 100755 --- a/bus-opencv/pom.xml +++ b/bus-opencv/pom.xml @@ -6,7 +6,7 @@ org.miaixz bus-opencv - 8.0.0 + 8.0.1 jar ${project.artifactId} diff --git a/bus-opencv/src/main/java/org/opencv/core/Algorithm.java b/bus-opencv/src/main/java/org/opencv/core/Algorithm.java index ce7ce9742a..9db4a0a55e 100644 --- a/bus-opencv/src/main/java/org/opencv/core/Algorithm.java +++ b/bus-opencv/src/main/java/org/opencv/core/Algorithm.java @@ -4,43 +4,44 @@ package org.opencv.core; -// C++: class Algorithm +// C++: class Algorithm /** * This is a base class for all more or less complex algorithms in OpenCV - *

      + * * especially for classes of algorithms, for which there can be multiple implementations. The examples * are stereo correspondence (for which there are algorithms like block matching, semi-global block * matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians * models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck * etc.). - *

      + * * Here is example of SimpleBlobDetector use in your application via Algorithm interface: * SNIPPET: snippets/core_various.cpp Algorithm */ public class Algorithm { protected final long nativeObj; - protected Algorithm(long addr) { - nativeObj = addr; - + nativeObj = addr; + long nativeObjCopy = nativeObj; + org.opencv.core.Mat.cleaner.register(this, () -> delete(nativeObjCopy)); } - // internal usage only - public static Algorithm __fromPtr__(long addr) { - return new Algorithm(addr); - } + public long getNativeObjAddr() { return nativeObj; } - // C++: void cv::Algorithm::clear() - private static native void clear_0(long nativeObj); + // internal usage only + public static Algorithm __fromPtr__(long addr) { return new Algorithm(addr); } // // C++: void cv::Algorithm::clear() // - // C++: bool cv::Algorithm::empty() - private static native boolean empty_0(long nativeObj); + /** + * Clears the algorithm state + */ + public void clear() { + clear_0(nativeObj); + } // @@ -68,68 +69,58 @@ public static Algorithm __fromPtr__(long addr) { // C++: bool cv::Algorithm::empty() // - // C++: void cv::Algorithm::save(String filename) - private static native void save_0(long nativeObj, String filename); - - - // - // C++: void cv::Algorithm::save(String filename) - // - - // C++: String cv::Algorithm::getDefaultName() - private static native String getDefaultName_0(long nativeObj); - - - // - // C++: String cv::Algorithm::getDefaultName() - // - - // native support for deleting native object - private static native void delete(long nativeObj); - - public long getNativeObjAddr() { - return nativeObj; - } - - /** - * Clears the algorithm state - */ - public void clear() { - clear_0(nativeObj); - } - /** * Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read - * * @return automatically generated */ public boolean empty() { return empty_0(nativeObj); } + + // + // C++: void cv::Algorithm::save(String filename) + // + /** * Saves the algorithm to a file. * In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). - * * @param filename automatically generated */ public void save(String filename) { save_0(nativeObj, filename); } + + // + // C++: String cv::Algorithm::getDefaultName() + // + /** * Returns the algorithm string identifier. * This string is used as top level xml/yml node tag when the object is saved to a file or string. - * * @return automatically generated */ public String getDefaultName() { return getDefaultName_0(nativeObj); } - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } + + + + // C++: void cv::Algorithm::clear() + private static native void clear_0(long nativeObj); + + // C++: bool cv::Algorithm::empty() + private static native boolean empty_0(long nativeObj); + + // C++: void cv::Algorithm::save(String filename) + private static native void save_0(long nativeObj, String filename); + + // C++: String cv::Algorithm::getDefaultName() + private static native String getDefaultName_0(long nativeObj); + + // native support for deleting native object + private static native void delete(long nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/core/Core.java b/bus-opencv/src/main/java/org/opencv/core/Core.java index 75bd3b7a0a..5130d65a39 100644 --- a/bus-opencv/src/main/java/org/opencv/core/Core.java +++ b/bus-opencv/src/main/java/org/opencv/core/Core.java @@ -10,12 +10,32 @@ // C++: class Core public class Core { + // these constants are wrapped inside functions to prevent inlining + private static String getVersion() { return "4.9.0"; } + private static String getNativeLibraryName() { return "opencv_java"; } + private static int getVersionMajorJ() { return 4; } + private static int getVersionMinorJ() { return 9; } + private static int getVersionRevisionJ() { return 0; } + private static String getVersionStatusJ() { return ""; } + public static final String VERSION = getVersion(); public static final String NATIVE_LIBRARY_NAME = getNativeLibraryName(); public static final int VERSION_MAJOR = getVersionMajorJ(); public static final int VERSION_MINOR = getVersionMinorJ(); public static final int VERSION_REVISION = getVersionRevisionJ(); public static final String VERSION_STATUS = getVersionStatusJ(); + + private static final int + CV_8U = 0, + CV_8S = 1, + CV_16U = 2, + CV_16S = 3, + CV_32S = 4, + CV_32F = 5, + CV_64F = 6, + CV_USRTYPE1 = 7; + + // C++: enum public static final int SVD_MODIFY_A = 1, @@ -28,6 +48,8 @@ public class Core { REDUCE_MIN = 3, RNG_UNIFORM = 0, RNG_NORMAL = 1; + + // C++: enum BorderTypes (cv.BorderTypes) public static final int BORDER_CONSTANT = 0, @@ -39,6 +61,8 @@ public class Core { BORDER_REFLECT101 = BORDER_REFLECT_101, BORDER_DEFAULT = BORDER_REFLECT_101, BORDER_ISOLATED = 16; + + // C++: enum CmpTypes (cv.CmpTypes) public static final int CMP_EQ = 0, @@ -47,6 +71,8 @@ public class Core { CMP_LT = 3, CMP_LE = 4, CMP_NE = 5; + + // C++: enum CovarFlags (cv.CovarFlags) public static final int COVAR_SCRAMBLED = 0, @@ -55,6 +81,8 @@ public class Core { COVAR_SCALE = 4, COVAR_ROWS = 8, COVAR_COLS = 16; + + // C++: enum DecompTypes (cv.DecompTypes) public static final int DECOMP_LU = 0, @@ -63,6 +91,20 @@ public class Core { DECOMP_CHOLESKY = 3, DECOMP_QR = 4, DECOMP_NORMAL = 16; + + + // C++: enum DftFlags (cv.DftFlags) + public static final int + DFT_INVERSE = 1, + DFT_SCALE = 2, + DFT_ROWS = 4, + DFT_COMPLEX_OUTPUT = 16, + DFT_REAL_OUTPUT = 32, + DFT_COMPLEX_INPUT = 64, + DCT_INVERSE = DFT_INVERSE, + DCT_ROWS = DFT_ROWS; + + // C++: enum Code (cv.Error.Code) public static final int StsOk = 0, @@ -120,6 +162,8 @@ public class Core { OpenCLDoubleNotSupported = -221, OpenCLInitError = -222, OpenCLNoAMDBlasFft = -223; + + // C++: enum FormatType (cv.Formatter.FormatType) public static final int Formatter_FMT_DEFAULT = 0, @@ -128,16 +172,22 @@ public class Core { Formatter_FMT_PYTHON = 3, Formatter_FMT_NUMPY = 4, Formatter_FMT_C = 5; + + // C++: enum GemmFlags (cv.GemmFlags) public static final int GEMM_1_T = 1, GEMM_2_T = 2, GEMM_3_T = 4; + + // C++: enum KmeansFlags (cv.KmeansFlags) public static final int KMEANS_RANDOM_CENTERS = 0, KMEANS_PP_CENTERS = 2, KMEANS_USE_INITIAL_LABELS = 1; + + // C++: enum NormTypes (cv.NormTypes) public static final int NORM_INF = 1, @@ -149,11 +199,15 @@ public class Core { NORM_TYPE_MASK = 7, NORM_RELATIVE = 8, NORM_MINMAX = 32; + + // C++: enum Flags (cv.PCA.Flags) public static final int PCA_DATA_AS_ROW = 0, PCA_DATA_AS_COL = 1, PCA_USE_AVG = 2; + + // C++: enum Param (cv.Param) public static final int Param_INT = 0, @@ -168,72 +222,39 @@ public class Core { Param_UINT64 = 9, Param_UCHAR = 11, Param_SCALAR = 12; + + // C++: enum ReduceTypes (cv.ReduceTypes) public static final int - REDUCE_SUM2 = 4; // C++: enum DftFlags (cv.DftFlags) - public static final int - DFT_INVERSE = 1, - DFT_SCALE = 2, - DFT_ROWS = 4, - DFT_COMPLEX_OUTPUT = 16, - DFT_REAL_OUTPUT = 32, - DFT_COMPLEX_INPUT = 64, - DCT_INVERSE = DFT_INVERSE, - DCT_ROWS = DFT_ROWS; + REDUCE_SUM2 = 4; + + // C++: enum RotateFlags (cv.RotateFlags) public static final int ROTATE_90_CLOCKWISE = 0, ROTATE_180 = 1, ROTATE_90_COUNTERCLOCKWISE = 2; + + // C++: enum SortFlags (cv.SortFlags) public static final int SORT_EVERY_ROW = 0, SORT_EVERY_COLUMN = 1, SORT_ASCENDING = 0, SORT_DESCENDING = 16; - private static final int - CV_8U = 0, - CV_8S = 1, - CV_16U = 2, - CV_16S = 3, - CV_32S = 4, - CV_32F = 5, - CV_64F = 6, - CV_USRTYPE1 = 7; - - // these constants are wrapped inside functions to prevent inlining - private static String getVersion() { - return "4.8.0"; - } - - private static String getNativeLibraryName() { - return "opencv_java"; - } - - private static int getVersionMajorJ() { - return 4; - } - - private static int getVersionMinorJ() { - return 8; - } - private static int getVersionRevisionJ() { - return 0; - } - private static String getVersionStatusJ() { - return ""; - } + // + // C++: float cv::cubeRoot(float val) + // /** * Computes the cube root of an argument. - *

      - * The function cubeRoot computes \(\sqrt[3]{\texttt{val}}\). Negative arguments are handled correctly. - * NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for - * single-precision data. * - * @param val A function argument. + * The function cubeRoot computes \(\sqrt[3]{\texttt{val}}\). Negative arguments are handled correctly. + * NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for + * single-precision data. + * @param val A function argument. * @return automatically generated */ public static float cubeRoot(float val) { @@ -242,17 +263,16 @@ public static float cubeRoot(float val) { // - // C++: float cv::cubeRoot(float val) + // C++: float cv::fastAtan2(float y, float x) // /** * Calculates the angle of a 2D vector in degrees. - *

      - * The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is measured - * in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees. * - * @param x x-coordinate of the vector. - * @param y y-coordinate of the vector. + * The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is measured + * in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees. + * @param x x-coordinate of the vector. + * @param y y-coordinate of the vector. * @return automatically generated */ public static float fastAtan2(float y, float x) { @@ -261,12 +281,11 @@ public static float fastAtan2(float y, float x) { // - // C++: float cv::fastAtan2(float y, float x) + // C++: bool cv::ipp::useIPP() // /** * proxy for hal::Cholesky - * * @return automatically generated */ public static boolean useIPP() { @@ -275,7 +294,7 @@ public static boolean useIPP() { // - // C++: bool cv::ipp::useIPP() + // C++: void cv::ipp::setUseIPP(bool flag) // public static void setUseIPP(boolean flag) { @@ -284,7 +303,7 @@ public static void setUseIPP(boolean flag) { // - // C++: void cv::ipp::setUseIPP(bool flag) + // C++: String cv::ipp::getIppVersion() // public static String getIppVersion() { @@ -293,7 +312,7 @@ public static String getIppVersion() { // - // C++: String cv::ipp::getIppVersion() + // C++: bool cv::ipp::useIPP_NotExact() // public static boolean useIPP_NotExact() { @@ -302,7 +321,7 @@ public static boolean useIPP_NotExact() { // - // C++: bool cv::ipp::useIPP_NotExact() + // C++: void cv::ipp::setUseIPP_NotExact(bool flag) // public static void setUseIPP_NotExact(boolean flag) { @@ -311,31 +330,30 @@ public static void setUseIPP_NotExact(boolean flag) { // - // C++: void cv::ipp::setUseIPP_NotExact(bool flag) + // C++: int cv::borderInterpolate(int p, int len, int borderType) // /** * Computes the source location of an extrapolated pixel. - *

      + * * The function computes and returns the coordinate of a donor pixel corresponding to the specified * extrapolated pixel when using the specified extrapolation border mode. For example, if you use * cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and * want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img , it * looks like: * - * float val = img.at<float>(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101), - * borderInterpolate(-5, img.cols, cv::BORDER_WRAP)); + * float val = img.at<float>(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101), + * borderInterpolate(-5, img.cols, cv::BORDER_WRAP)); * * Normally, the function is not called directly. It is used inside filtering functions and also in * copyMakeBorder. - * - * @param p 0-based coordinate of the extrapolated pixel along one of the axes, likely <0 or >= len - * @param len Length of the array along the corresponding axis. + * @param p 0-based coordinate of the extrapolated pixel along one of the axes, likely <0 or >= len + * @param len Length of the array along the corresponding axis. * @param borderType Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and - * #BORDER_ISOLATED . When borderType==#BORDER_CONSTANT , the function always returns -1, regardless - * of p and len. - *

      - * SEE: copyMakeBorder + * #BORDER_ISOLATED . When borderType==#BORDER_CONSTANT , the function always returns -1, regardless + * of p and len. + * + * SEE: copyMakeBorder * @return automatically generated */ public static int borderInterpolate(int p, int len, int borderType) { @@ -344,112 +362,112 @@ public static int borderInterpolate(int p, int len, int borderType) { // - // C++: int cv::borderInterpolate(int p, int len, int borderType) + // C++: void cv::copyMakeBorder(Mat src, Mat& dst, int top, int bottom, int left, int right, int borderType, Scalar value = Scalar()) // /** * Forms a border around an image. - *

      + * * The function copies the source image into the middle of the destination image. The areas to the * left, to the right, above and below the copied source image will be filled with extrapolated * pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but * what other more complex functions, including your own, may do to simplify image boundary handling. - *

      + * * The function supports the mode when src is already in the middle of dst . In this case, the * function does not copy src itself but simply constructs the border, for example: * * - * // let border be the same in all directions - * int border=2; - * // constructs a larger image to fit both the image and the border - * Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); - * // select the middle part of it w/o copying data - * Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); - * // convert image from RGB to grayscale - * cvtColor(rgb, gray, COLOR_RGB2GRAY); - * // form a border in-place - * copyMakeBorder(gray, gray_buf, border, border, - * border, border, BORDER_REPLICATE); - * // now do some custom filtering ... - * ... + * // let border be the same in all directions + * int border=2; + * // constructs a larger image to fit both the image and the border + * Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); + * // select the middle part of it w/o copying data + * Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); + * // convert image from RGB to grayscale + * cvtColor(rgb, gray, COLOR_RGB2GRAY); + * // form a border in-place + * copyMakeBorder(gray, gray_buf, border, border, + * border, border, BORDER_REPLICATE); + * // now do some custom filtering ... + * ... * * Note: When the source image is a part (ROI) of a bigger image, the function will try to use the * pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as * if src was not a ROI, use borderType | #BORDER_ISOLATED. * - * @param src Source image. - * @param dst Destination image of the same type as src and the size Size(src.cols+left+right, - * src.rows+top+bottom) . - * @param top the top pixels - * @param bottom the bottom pixels - * @param left the left pixels - * @param right Parameter specifying how many pixels in each direction from the source image rectangle - * to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs - * to be built. + * @param src Source image. + * @param dst Destination image of the same type as src and the size Size(src.cols+left+right, + * src.rows+top+bottom) . + * @param top the top pixels + * @param bottom the bottom pixels + * @param left the left pixels + * @param right Parameter specifying how many pixels in each direction from the source image rectangle + * to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs + * to be built. * @param borderType Border type. See borderInterpolate for details. - * @param value Border value if borderType==BORDER_CONSTANT . - *

      - * SEE: borderInterpolate + * @param value Border value if borderType==BORDER_CONSTANT . + * + * SEE: borderInterpolate */ public static void copyMakeBorder(Mat src, Mat dst, int top, int bottom, int left, int right, int borderType, Scalar value) { copyMakeBorder_0(src.nativeObj, dst.nativeObj, top, bottom, left, right, borderType, value.val[0], value.val[1], value.val[2], value.val[3]); } - - // - // C++: void cv::copyMakeBorder(Mat src, Mat& dst, int top, int bottom, int left, int right, int borderType, Scalar value = Scalar()) - // - /** * Forms a border around an image. - *

      + * * The function copies the source image into the middle of the destination image. The areas to the * left, to the right, above and below the copied source image will be filled with extrapolated * pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but * what other more complex functions, including your own, may do to simplify image boundary handling. - *

      + * * The function supports the mode when src is already in the middle of dst . In this case, the * function does not copy src itself but simply constructs the border, for example: * * - * // let border be the same in all directions - * int border=2; - * // constructs a larger image to fit both the image and the border - * Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); - * // select the middle part of it w/o copying data - * Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); - * // convert image from RGB to grayscale - * cvtColor(rgb, gray, COLOR_RGB2GRAY); - * // form a border in-place - * copyMakeBorder(gray, gray_buf, border, border, - * border, border, BORDER_REPLICATE); - * // now do some custom filtering ... - * ... + * // let border be the same in all directions + * int border=2; + * // constructs a larger image to fit both the image and the border + * Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); + * // select the middle part of it w/o copying data + * Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); + * // convert image from RGB to grayscale + * cvtColor(rgb, gray, COLOR_RGB2GRAY); + * // form a border in-place + * copyMakeBorder(gray, gray_buf, border, border, + * border, border, BORDER_REPLICATE); + * // now do some custom filtering ... + * ... * * Note: When the source image is a part (ROI) of a bigger image, the function will try to use the * pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as * if src was not a ROI, use borderType | #BORDER_ISOLATED. * - * @param src Source image. - * @param dst Destination image of the same type as src and the size Size(src.cols+left+right, - * src.rows+top+bottom) . - * @param top the top pixels - * @param bottom the bottom pixels - * @param left the left pixels - * @param right Parameter specifying how many pixels in each direction from the source image rectangle - * to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs - * to be built. + * @param src Source image. + * @param dst Destination image of the same type as src and the size Size(src.cols+left+right, + * src.rows+top+bottom) . + * @param top the top pixels + * @param bottom the bottom pixels + * @param left the left pixels + * @param right Parameter specifying how many pixels in each direction from the source image rectangle + * to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs + * to be built. * @param borderType Border type. See borderInterpolate for details. - *

      - * SEE: borderInterpolate + * + * SEE: borderInterpolate */ public static void copyMakeBorder(Mat src, Mat dst, int top, int bottom, int left, int right, int borderType) { copyMakeBorder_1(src.nativeObj, dst.nativeObj, top, bottom, left, right, borderType); } + + // + // C++: void cv::add(Mat src1, Mat src2, Mat& dst, Mat mask = Mat(), int dtype = -1) + // + /** * Calculates the per-element sum of two arrays or an array and a scalar. - *

      + * * The function add calculates: *

        *
      • @@ -469,7 +487,7 @@ public static void copyMakeBorder(Mat src, Mat dst, int top, int bottom, int lef * channel is processed independently. *
      • *
      - *

      + * * The first function in the list above can be replaced with matrix expressions: * * dst = src1 + src2; @@ -483,28 +501,25 @@ public static void copyMakeBorder(Mat src, Mat dst, int top, int bottom, int lef * array, be it src1, src2 or both. * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * - * @param src1 first input array or a scalar. - * @param src2 second input array or a scalar. - * @param dst output array that has the same size and number of channels as the input array(s); the - * depth is defined by dtype or src1/src2. - * @param mask optional operation mask - 8-bit single channel array, that specifies elements of the - * output array to be changed. + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code add(src,X)} means {@code add(src,(X,X,X,X))}. + * {@code add(src,(X,))} means {@code add(src,(X,0,0,0))}. + * @param src1 first input array or a scalar. + * @param src2 second input array or a scalar. + * @param dst output array that has the same size and number of channels as the input array(s); the + * depth is defined by dtype or src1/src2. + * @param mask optional operation mask - 8-bit single channel array, that specifies elements of the + * output array to be changed. * @param dtype optional depth of the output array (see the discussion below). - * SEE: subtract, addWeighted, scaleAdd, Mat::convertTo + * SEE: subtract, addWeighted, scaleAdd, Mat::convertTo */ public static void add(Mat src1, Mat src2, Mat dst, Mat mask, int dtype) { add_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj, dtype); } - - // - // C++: void cv::add(Mat src1, Mat src2, Mat& dst, Mat mask = Mat(), int dtype = -1) - // - /** * Calculates the per-element sum of two arrays or an array and a scalar. - *

      + * * The function add calculates: *

        *
      • @@ -524,7 +539,7 @@ public static void add(Mat src1, Mat src2, Mat dst, Mat mask, int dtype) { * channel is processed independently. *
      • *
      - *

      + * * The first function in the list above can be replaced with matrix expressions: * * dst = src1 + src2; @@ -538,14 +553,16 @@ public static void add(Mat src1, Mat src2, Mat dst, Mat mask, int dtype) { * array, be it src1, src2 or both. * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code add(src,X)} means {@code add(src,(X,X,X,X))}. + * {@code add(src,(X,))} means {@code add(src,(X,0,0,0))}. * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array that has the same size and number of channels as the input array(s); the - * depth is defined by dtype or src1/src2. + * @param dst output array that has the same size and number of channels as the input array(s); the + * depth is defined by dtype or src1/src2. * @param mask optional operation mask - 8-bit single channel array, that specifies elements of the - * output array to be changed. - * SEE: subtract, addWeighted, scaleAdd, Mat::convertTo + * output array to be changed. + * SEE: subtract, addWeighted, scaleAdd, Mat::convertTo */ public static void add(Mat src1, Mat src2, Mat dst, Mat mask) { add_1(src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj); @@ -553,7 +570,7 @@ public static void add(Mat src1, Mat src2, Mat dst, Mat mask) { /** * Calculates the per-element sum of two arrays or an array and a scalar. - *

      + * * The function add calculates: *

        *
      • @@ -573,7 +590,7 @@ public static void add(Mat src1, Mat src2, Mat dst, Mat mask) { * channel is processed independently. *
      • *
      - *

      + * * The first function in the list above can be replaced with matrix expressions: * * dst = src1 + src2; @@ -587,21 +604,28 @@ public static void add(Mat src1, Mat src2, Mat dst, Mat mask) { * array, be it src1, src2 or both. * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code add(src,X)} means {@code add(src,(X,X,X,X))}. + * {@code add(src,(X,))} means {@code add(src,(X,0,0,0))}. * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array that has the same size and number of channels as the input array(s); the - * depth is defined by dtype or src1/src2. - * output array to be changed. - * SEE: subtract, addWeighted, scaleAdd, Mat::convertTo + * @param dst output array that has the same size and number of channels as the input array(s); the + * depth is defined by dtype or src1/src2. + * output array to be changed. + * SEE: subtract, addWeighted, scaleAdd, Mat::convertTo */ public static void add(Mat src1, Mat src2, Mat dst) { add_2(src1.nativeObj, src2.nativeObj, dst.nativeObj); } + + // + // C++: void cv::subtract(Mat src1, Mat src2, Mat& dst, Mat mask = Mat(), int dtype = -1) + // + /** * Calculates the per-element difference between two arrays or array and a scalar. - *

      + * * The function subtract calculates: *

        *
      • @@ -626,7 +650,7 @@ public static void add(Mat src1, Mat src2, Mat dst) { * channel is processed independently. *
      • *
      - *

      + * * The first function in the list above can be replaced with matrix expressions: * * dst = src1 - src2; @@ -639,27 +663,24 @@ public static void add(Mat src1, Mat src2, Mat dst) { * case the output array will have the same depth as the input array, be it src1, src2 or both. * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * - * @param src1 first input array or a scalar. - * @param src2 second input array or a scalar. - * @param dst output array of the same size and the same number of channels as the input array. - * @param mask optional operation mask; this is an 8-bit single channel array that specifies elements - * of the output array to be changed. + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code subtract(src,X)} means {@code subtract(src,(X,X,X,X))}. + * {@code subtract(src,(X,))} means {@code subtract(src,(X,0,0,0))}. + * @param src1 first input array or a scalar. + * @param src2 second input array or a scalar. + * @param dst output array of the same size and the same number of channels as the input array. + * @param mask optional operation mask; this is an 8-bit single channel array that specifies elements + * of the output array to be changed. * @param dtype optional depth of the output array - * SEE: add, addWeighted, scaleAdd, Mat::convertTo + * SEE: add, addWeighted, scaleAdd, Mat::convertTo */ public static void subtract(Mat src1, Mat src2, Mat dst, Mat mask, int dtype) { subtract_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj, dtype); } - - // - // C++: void cv::subtract(Mat src1, Mat src2, Mat& dst, Mat mask = Mat(), int dtype = -1) - // - /** * Calculates the per-element difference between two arrays or array and a scalar. - *

      + * * The function subtract calculates: *

        *
      • @@ -684,7 +705,7 @@ public static void subtract(Mat src1, Mat src2, Mat dst, Mat mask, int dtype) { * channel is processed independently. *
      • *
      - *

      + * * The first function in the list above can be replaced with matrix expressions: * * dst = src1 - src2; @@ -697,13 +718,15 @@ public static void subtract(Mat src1, Mat src2, Mat dst, Mat mask, int dtype) { * case the output array will have the same depth as the input array, be it src1, src2 or both. * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code subtract(src,X)} means {@code subtract(src,(X,X,X,X))}. + * {@code subtract(src,(X,))} means {@code subtract(src,(X,0,0,0))}. * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array of the same size and the same number of channels as the input array. + * @param dst output array of the same size and the same number of channels as the input array. * @param mask optional operation mask; this is an 8-bit single channel array that specifies elements - * of the output array to be changed. - * SEE: add, addWeighted, scaleAdd, Mat::convertTo + * of the output array to be changed. + * SEE: add, addWeighted, scaleAdd, Mat::convertTo */ public static void subtract(Mat src1, Mat src2, Mat dst, Mat mask) { subtract_1(src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj); @@ -711,7 +734,7 @@ public static void subtract(Mat src1, Mat src2, Mat dst, Mat mask) { /** * Calculates the per-element difference between two arrays or array and a scalar. - *

      + * * The function subtract calculates: *

        *
      • @@ -736,7 +759,7 @@ public static void subtract(Mat src1, Mat src2, Mat dst, Mat mask) { * channel is processed independently. *
      • *
      - *

      + * * The first function in the list above can be replaced with matrix expressions: * * dst = src1 - src2; @@ -749,70 +772,76 @@ public static void subtract(Mat src1, Mat src2, Mat dst, Mat mask) { * case the output array will have the same depth as the input array, be it src1, src2 or both. * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code subtract(src,X)} means {@code subtract(src,(X,X,X,X))}. + * {@code subtract(src,(X,))} means {@code subtract(src,(X,0,0,0))}. * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array of the same size and the same number of channels as the input array. - * of the output array to be changed. - * SEE: add, addWeighted, scaleAdd, Mat::convertTo + * @param dst output array of the same size and the same number of channels as the input array. + * of the output array to be changed. + * SEE: add, addWeighted, scaleAdd, Mat::convertTo */ public static void subtract(Mat src1, Mat src2, Mat dst) { subtract_2(src1.nativeObj, src2.nativeObj, dst.nativeObj); } + + // + // C++: void cv::multiply(Mat src1, Mat src2, Mat& dst, double scale = 1, int dtype = -1) + // + /** * Calculates the per-element scaled product of two arrays. - *

      + * * The function multiply calculates the per-element product of two arrays: - *

      + * * \(\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\) - *

      + * * There is also a REF: MatrixExpressions -friendly variant of the first function. See Mat::mul . - *

      + * * For a not-per-element matrix product, see gemm . * * Note: Saturation is not applied when the output array has the depth * CV_32S. You may even get result of an incorrect sign in the case of * overflow. - * - * @param src1 first input array. - * @param src2 second input array of the same size and the same type as src1. - * @param dst output array of the same size and type as src1. + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code multiply(src,X)} means {@code multiply(src,(X,X,X,X))}. + * {@code multiply(src,(X,))} means {@code multiply(src,(X,0,0,0))}. + * @param src1 first input array. + * @param src2 second input array of the same size and the same type as src1. + * @param dst output array of the same size and type as src1. * @param scale optional scale factor. * @param dtype optional depth of the output array - * SEE: add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, - * Mat::convertTo + * SEE: add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, + * Mat::convertTo */ public static void multiply(Mat src1, Mat src2, Mat dst, double scale, int dtype) { multiply_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, scale, dtype); } - - // - // C++: void cv::multiply(Mat src1, Mat src2, Mat& dst, double scale = 1, int dtype = -1) - // - /** * Calculates the per-element scaled product of two arrays. - *

      + * * The function multiply calculates the per-element product of two arrays: - *

      + * * \(\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\) - *

      + * * There is also a REF: MatrixExpressions -friendly variant of the first function. See Mat::mul . - *

      + * * For a not-per-element matrix product, see gemm . * * Note: Saturation is not applied when the output array has the depth * CV_32S. You may even get result of an incorrect sign in the case of * overflow. - * - * @param src1 first input array. - * @param src2 second input array of the same size and the same type as src1. - * @param dst output array of the same size and type as src1. + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code multiply(src,X)} means {@code multiply(src,(X,X,X,X))}. + * {@code multiply(src,(X,))} means {@code multiply(src,(X,0,0,0))}. + * @param src1 first input array. + * @param src2 second input array of the same size and the same type as src1. + * @param dst output array of the same size and type as src1. * @param scale optional scale factor. - * SEE: add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, - * Mat::convertTo + * SEE: add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, + * Mat::convertTo */ public static void multiply(Mat src1, Mat src2, Mat dst, double scale) { multiply_1(src1.nativeObj, src2.nativeObj, dst.nativeObj, scale); @@ -820,39 +849,46 @@ public static void multiply(Mat src1, Mat src2, Mat dst, double scale) { /** * Calculates the per-element scaled product of two arrays. - *

      + * * The function multiply calculates the per-element product of two arrays: - *

      + * * \(\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\) - *

      + * * There is also a REF: MatrixExpressions -friendly variant of the first function. See Mat::mul . - *

      + * * For a not-per-element matrix product, see gemm . * * Note: Saturation is not applied when the output array has the depth * CV_32S. You may even get result of an incorrect sign in the case of * overflow. - * + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code multiply(src,X)} means {@code multiply(src,(X,X,X,X))}. + * {@code multiply(src,(X,))} means {@code multiply(src,(X,0,0,0))}. * @param src1 first input array. * @param src2 second input array of the same size and the same type as src1. - * @param dst output array of the same size and type as src1. - * SEE: add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, - * Mat::convertTo + * @param dst output array of the same size and type as src1. + * SEE: add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, + * Mat::convertTo */ public static void multiply(Mat src1, Mat src2, Mat dst) { multiply_2(src1.nativeObj, src2.nativeObj, dst.nativeObj); } + + // + // C++: void cv::divide(Mat src1, Mat src2, Mat& dst, double scale = 1, int dtype = -1) + // + /** * Performs per-element division of two arrays or a scalar by an array. - *

      + * * The function cv::divide divides one array by another: * \(\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\) * or a scalar by an array when there is no src1 : * \(\texttt{dst(I) = saturate(scale/src2(I))}\) - *

      + * * Different channels of multi-channel arrays are processed independently. - *

      + * * For integer types when src2(I) is zero, dst(I) will also be zero. * * Note: In case of floating point data there is no special defined behavior for zero src2(I) values. @@ -861,34 +897,31 @@ public static void multiply(Mat src1, Mat src2, Mat dst) { * * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * - * @param src1 first input array. - * @param src2 second input array of the same size and type as src1. + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code divide(src,X)} means {@code divide(src,(X,X,X,X))}. + * {@code divide(src,(X,))} means {@code divide(src,(X,0,0,0))}. + * @param src1 first input array. + * @param src2 second input array of the same size and type as src1. * @param scale scalar factor. - * @param dst output array of the same size and type as src2. + * @param dst output array of the same size and type as src2. * @param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in - * case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). - * SEE: multiply, add, subtract + * case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). + * SEE: multiply, add, subtract */ public static void divide(Mat src1, Mat src2, Mat dst, double scale, int dtype) { divide_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, scale, dtype); } - - // - // C++: void cv::divide(Mat src1, Mat src2, Mat& dst, double scale = 1, int dtype = -1) - // - /** * Performs per-element division of two arrays or a scalar by an array. - *

      + * * The function cv::divide divides one array by another: * \(\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\) * or a scalar by an array when there is no src1 : * \(\texttt{dst(I) = saturate(scale/src2(I))}\) - *

      + * * Different channels of multi-channel arrays are processed independently. - *

      + * * For integer types when src2(I) is zero, dst(I) will also be zero. * * Note: In case of floating point data there is no special defined behavior for zero src2(I) values. @@ -897,13 +930,15 @@ public static void divide(Mat src1, Mat src2, Mat dst, double scale, int dtype) * * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * - * @param src1 first input array. - * @param src2 second input array of the same size and type as src1. + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code divide(src,X)} means {@code divide(src,(X,X,X,X))}. + * {@code divide(src,(X,))} means {@code divide(src,(X,0,0,0))}. + * @param src1 first input array. + * @param src2 second input array of the same size and type as src1. * @param scale scalar factor. - * @param dst output array of the same size and type as src2. - * case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). - * SEE: multiply, add, subtract + * @param dst output array of the same size and type as src2. + * case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). + * SEE: multiply, add, subtract */ public static void divide(Mat src1, Mat src2, Mat dst, double scale) { divide_1(src1.nativeObj, src2.nativeObj, dst.nativeObj, scale); @@ -911,14 +946,14 @@ public static void divide(Mat src1, Mat src2, Mat dst, double scale) { /** * Performs per-element division of two arrays or a scalar by an array. - *

      + * * The function cv::divide divides one array by another: * \(\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\) * or a scalar by an array when there is no src1 : * \(\texttt{dst(I) = saturate(scale/src2(I))}\) - *

      + * * Different channels of multi-channel arrays are processed independently. - *

      + * * For integer types when src2(I) is zero, dst(I) will also be zero. * * Note: In case of floating point data there is no special defined behavior for zero src2(I) values. @@ -927,49 +962,55 @@ public static void divide(Mat src1, Mat src2, Mat dst, double scale) { * * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code divide(src,X)} means {@code divide(src,(X,X,X,X))}. + * {@code divide(src,(X,))} means {@code divide(src,(X,0,0,0))}. * @param src1 first input array. * @param src2 second input array of the same size and type as src1. - * @param dst output array of the same size and type as src2. - * case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). - * SEE: multiply, add, subtract + * @param dst output array of the same size and type as src2. + * case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). + * SEE: multiply, add, subtract */ public static void divide(Mat src1, Mat src2, Mat dst) { divide_2(src1.nativeObj, src2.nativeObj, dst.nativeObj); } - public static void divide(double scale, Mat src2, Mat dst, int dtype) { - divide_3(scale, src2.nativeObj, dst.nativeObj, dtype); - } - // // C++: void cv::divide(double scale, Mat src2, Mat& dst, int dtype = -1) // + public static void divide(double scale, Mat src2, Mat dst, int dtype) { + divide_3(scale, src2.nativeObj, dst.nativeObj, dtype); + } + public static void divide(double scale, Mat src2, Mat dst) { divide_4(scale, src2.nativeObj, dst.nativeObj); } + + // + // C++: void cv::scaleAdd(Mat src1, double alpha, Mat src2, Mat& dst) + // + /** * Calculates the sum of a scaled array and another array. - *

      + * * The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY * or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates * the sum of a scaled array and another array: * \(\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\) * The function can also be emulated with a matrix expression, for example: * - * Mat A(3, 3, CV_64F); - * ... - * A.row(0) = A.row(1)*2 + A.row(2); + * Mat A(3, 3, CV_64F); + * ... + * A.row(0) = A.row(1)*2 + A.row(2); * - * - * @param src1 first input array. + * @param src1 first input array. * @param alpha scale factor for the first array. - * @param src2 second input array of the same size and type as src1. - * @param dst output array of the same size and type as src1. - * SEE: add, addWeighted, subtract, Mat::dot, Mat::convertTo + * @param src2 second input array of the same size and type as src1. + * @param dst output array of the same size and type as src1. + * SEE: add, addWeighted, subtract, Mat::dot, Mat::convertTo */ public static void scaleAdd(Mat src1, double alpha, Mat src2, Mat dst) { scaleAdd_0(src1.nativeObj, alpha, src2.nativeObj, dst.nativeObj); @@ -977,72 +1018,70 @@ public static void scaleAdd(Mat src1, double alpha, Mat src2, Mat dst) { // - // C++: void cv::scaleAdd(Mat src1, double alpha, Mat src2, Mat& dst) + // C++: void cv::addWeighted(Mat src1, double alpha, Mat src2, double beta, double gamma, Mat& dst, int dtype = -1) // /** * Calculates the weighted sum of two arrays. - *

      + * * The function addWeighted calculates the weighted sum of two arrays as follows: * \(\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\) * where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each * channel is processed independently. * The function can be replaced with a matrix expression: * - * dst = src1*alpha + src2*beta + gamma; + * dst = src1*alpha + src2*beta + gamma; * * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * - * @param src1 first input array. + * @param src1 first input array. * @param alpha weight of the first array elements. - * @param src2 second input array of the same size and channel number as src1. - * @param beta weight of the second array elements. + * @param src2 second input array of the same size and channel number as src1. + * @param beta weight of the second array elements. * @param gamma scalar added to each sum. - * @param dst output array that has the same size and number of channels as the input arrays. + * @param dst output array that has the same size and number of channels as the input arrays. * @param dtype optional depth of the output array; when both input arrays have the same depth, dtype - * can be set to -1, which will be equivalent to src1.depth(). - * SEE: add, subtract, scaleAdd, Mat::convertTo + * can be set to -1, which will be equivalent to src1.depth(). + * SEE: add, subtract, scaleAdd, Mat::convertTo */ public static void addWeighted(Mat src1, double alpha, Mat src2, double beta, double gamma, Mat dst, int dtype) { addWeighted_0(src1.nativeObj, alpha, src2.nativeObj, beta, gamma, dst.nativeObj, dtype); } - - // - // C++: void cv::addWeighted(Mat src1, double alpha, Mat src2, double beta, double gamma, Mat& dst, int dtype = -1) - // - /** * Calculates the weighted sum of two arrays. - *

      + * * The function addWeighted calculates the weighted sum of two arrays as follows: * \(\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\) * where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each * channel is processed independently. * The function can be replaced with a matrix expression: * - * dst = src1*alpha + src2*beta + gamma; + * dst = src1*alpha + src2*beta + gamma; * * Note: Saturation is not applied when the output array has the depth CV_32S. You may even get * result of an incorrect sign in the case of overflow. - * - * @param src1 first input array. + * @param src1 first input array. * @param alpha weight of the first array elements. - * @param src2 second input array of the same size and channel number as src1. - * @param beta weight of the second array elements. + * @param src2 second input array of the same size and channel number as src1. + * @param beta weight of the second array elements. * @param gamma scalar added to each sum. - * @param dst output array that has the same size and number of channels as the input arrays. - * can be set to -1, which will be equivalent to src1.depth(). - * SEE: add, subtract, scaleAdd, Mat::convertTo + * @param dst output array that has the same size and number of channels as the input arrays. + * can be set to -1, which will be equivalent to src1.depth(). + * SEE: add, subtract, scaleAdd, Mat::convertTo */ public static void addWeighted(Mat src1, double alpha, Mat src2, double beta, double gamma, Mat dst) { addWeighted_1(src1.nativeObj, alpha, src2.nativeObj, beta, gamma, dst.nativeObj); } + + // + // C++: void cv::convertScaleAbs(Mat src, Mat& dst, double alpha = 1, double beta = 0) + // + /** * Scales, calculates absolute values, and converts the result to 8-bit. - *

      + * * On each element of the input array, the function convertScaleAbs * performs three operations sequentially: scaling, taking an absolute * value, conversion to an unsigned 8-bit type: @@ -1053,32 +1092,26 @@ public static void addWeighted(Mat src1, double alpha, Mat src2, double beta, do * expressions) and then by calculating an absolute value of the result. * For example: * - * Mat_<float> A(30,30); - * randu(A, Scalar(-100), Scalar(100)); - * Mat_<float> B = A*5 + 3; - * B = abs(B); - * // Mat_<float> B = abs(A*5+3) will also do the job, - * // but it will allocate a temporary matrix + * Mat_<float> A(30,30); + * randu(A, Scalar(-100), Scalar(100)); + * Mat_<float> B = A*5 + 3; + * B = abs(B); + * // Mat_<float> B = abs(A*5+3) will also do the job, + * // but it will allocate a temporary matrix * - * - * @param src input array. - * @param dst output array. + * @param src input array. + * @param dst output array. * @param alpha optional scale factor. - * @param beta optional delta added to the scaled values. - * SEE: Mat::convertTo, cv::abs(const Mat&) + * @param beta optional delta added to the scaled values. + * SEE: Mat::convertTo, cv::abs(const Mat&) */ public static void convertScaleAbs(Mat src, Mat dst, double alpha, double beta) { convertScaleAbs_0(src.nativeObj, dst.nativeObj, alpha, beta); } - - // - // C++: void cv::convertScaleAbs(Mat src, Mat& dst, double alpha = 1, double beta = 0) - // - /** * Scales, calculates absolute values, and converts the result to 8-bit. - *

      + * * On each element of the input array, the function convertScaleAbs * performs three operations sequentially: scaling, taking an absolute * value, conversion to an unsigned 8-bit type: @@ -1089,18 +1122,17 @@ public static void convertScaleAbs(Mat src, Mat dst, double alpha, double beta) * expressions) and then by calculating an absolute value of the result. * For example: * - * Mat_<float> A(30,30); - * randu(A, Scalar(-100), Scalar(100)); - * Mat_<float> B = A*5 + 3; - * B = abs(B); - * // Mat_<float> B = abs(A*5+3) will also do the job, - * // but it will allocate a temporary matrix + * Mat_<float> A(30,30); + * randu(A, Scalar(-100), Scalar(100)); + * Mat_<float> B = A*5 + 3; + * B = abs(B); + * // Mat_<float> B = abs(A*5+3) will also do the job, + * // but it will allocate a temporary matrix * - * - * @param src input array. - * @param dst output array. + * @param src input array. + * @param dst output array. * @param alpha optional scale factor. - * SEE: Mat::convertTo, cv::abs(const Mat&) + * SEE: Mat::convertTo, cv::abs(const Mat&) */ public static void convertScaleAbs(Mat src, Mat dst, double alpha) { convertScaleAbs_1(src.nativeObj, dst.nativeObj, alpha); @@ -1108,7 +1140,7 @@ public static void convertScaleAbs(Mat src, Mat dst, double alpha) { /** * Scales, calculates absolute values, and converts the result to 8-bit. - *

      + * * On each element of the input array, the function convertScaleAbs * performs three operations sequentially: scaling, taking an absolute * value, conversion to an unsigned 8-bit type: @@ -1119,25 +1151,29 @@ public static void convertScaleAbs(Mat src, Mat dst, double alpha) { * expressions) and then by calculating an absolute value of the result. * For example: * - * Mat_<float> A(30,30); - * randu(A, Scalar(-100), Scalar(100)); - * Mat_<float> B = A*5 + 3; - * B = abs(B); - * // Mat_<float> B = abs(A*5+3) will also do the job, - * // but it will allocate a temporary matrix + * Mat_<float> A(30,30); + * randu(A, Scalar(-100), Scalar(100)); + * Mat_<float> B = A*5 + 3; + * B = abs(B); + * // Mat_<float> B = abs(A*5+3) will also do the job, + * // but it will allocate a temporary matrix * - * * @param src input array. * @param dst output array. - * SEE: Mat::convertTo, cv::abs(const Mat&) + * SEE: Mat::convertTo, cv::abs(const Mat&) */ public static void convertScaleAbs(Mat src, Mat dst) { convertScaleAbs_2(src.nativeObj, dst.nativeObj); } + + // + // C++: void cv::convertFp16(Mat src, Mat& dst) + // + /** * Converts an array to half precision floating number. - *

      + * * This function converts FP32 (single precision floating point) from/to FP16 (half precision floating point). CV_16S format is used to represent FP16 data. * There are two use modes (src -> dst): CV_32F -> CV_16S and CV_16S -> CV_32F. The input array has to have type of CV_32F or * CV_16S to represent the bit depth. If the input array is neither of them, the function will raise an error. @@ -1152,24 +1188,23 @@ public static void convertFp16(Mat src, Mat dst) { // - // C++: void cv::convertFp16(Mat src, Mat& dst) + // C++: void cv::LUT(Mat src, Mat lut, Mat& dst) // /** * Performs a look-up table transform of an array. - *

      + * * The function LUT fills the output array with values from the look-up table. Indices of the entries * are taken from the input array. That is, the function processes each element of src as follows: * \(\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\) * where * \(d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\) - * * @param src input array of 8-bit elements. * @param lut look-up table of 256 elements; in case of multi-channel input array, the table should - * either have a single channel (in this case the same table is used for all channels) or the same - * number of channels as in the input array. + * either have a single channel (in this case the same table is used for all channels) or the same + * number of channels as in the input array. * @param dst output array of the same size and number of channels as src, and the same depth as lut. - * SEE: convertScaleAbs, Mat::convertTo + * SEE: convertScaleAbs, Mat::convertTo */ public static void LUT(Mat src, Mat lut, Mat dst) { LUT_0(src.nativeObj, lut.nativeObj, dst.nativeObj); @@ -1177,17 +1212,16 @@ public static void LUT(Mat src, Mat lut, Mat dst) { // - // C++: void cv::LUT(Mat src, Mat lut, Mat& dst) + // C++: Scalar cv::sum(Mat src) // /** * Calculates the sum of array elements. - *

      + * * The function cv::sum calculates and returns the sum of array elements, * independently for each channel. - * * @param src input array that must have from 1 to 4 channels. - * SEE: countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce + * SEE: countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce * @return automatically generated */ public static Scalar sumElems(Mat src) { @@ -1196,16 +1230,15 @@ public static Scalar sumElems(Mat src) { // - // C++: Scalar cv::sum(Mat src) + // C++: bool cv::hasNonZero(Mat src) // /** * Checks for the presence of at least one non-zero array element. - *

      - * The function returns whether there are non-zero elements in src * + * The function returns whether there are non-zero elements in src * @param src single-channel array. - * SEE: mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix + * SEE: mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix * @return automatically generated */ public static boolean hasNonZero(Mat src) { @@ -1214,17 +1247,16 @@ public static boolean hasNonZero(Mat src) { // - // C++: bool cv::hasNonZero(Mat src) + // C++: int cv::countNonZero(Mat src) // /** * Counts non-zero array elements. - *

      + * * The function returns the number of non-zero elements in src : * \(\sum _{I: \; \texttt{src} (I) \ne0 } 1\) - * * @param src single-channel array. - * SEE: mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix + * SEE: mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix * @return automatically generated */ public static int countNonZero(Mat src) { @@ -1233,34 +1265,33 @@ public static int countNonZero(Mat src) { // - // C++: int cv::countNonZero(Mat src) + // C++: void cv::findNonZero(Mat src, Mat& idx) // /** * Returns the list of locations of non-zero pixels - *

      + * * Given a binary matrix (likely returned from an operation such * as threshold(), compare(), >, ==, etc, return all of * the non-zero indices as a cv::Mat or std::vector<cv::Point> (x,y) * For example: * - * cv::Mat binaryImage; // input, binary image - * cv::Mat locations; // output, locations of non-zero pixels - * cv::findNonZero(binaryImage, locations); - *

      - * // access pixel coordinates - * Point pnt = locations.at<Point>(i); + * cv::Mat binaryImage; // input, binary image + * cv::Mat locations; // output, locations of non-zero pixels + * cv::findNonZero(binaryImage, locations); + * + * // access pixel coordinates + * Point pnt = locations.at<Point>(i); * * or * - * cv::Mat binaryImage; // input, binary image - * vector<Point> locations; // output, locations of non-zero pixels - * cv::findNonZero(binaryImage, locations); - *

      - * // access pixel coordinates - * Point pnt = locations[i]; - * + * cv::Mat binaryImage; // input, binary image + * vector<Point> locations; // output, locations of non-zero pixels + * cv::findNonZero(binaryImage, locations); * + * // access pixel coordinates + * Point pnt = locations[i]; + * * @param src single-channel array * @param idx the output array, type of cv::Mat or std::vector<Point>, corresponding to non-zero indices in the input */ @@ -1270,52 +1301,50 @@ public static void findNonZero(Mat src, Mat idx) { // - // C++: void cv::findNonZero(Mat src, Mat& idx) + // C++: Scalar cv::mean(Mat src, Mat mask = Mat()) // /** * Calculates an average (mean) of array elements. - *

      + * * The function cv::mean calculates the mean value M of array elements, * independently for each channel, and return it: * \(\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\) * When all the mask elements are 0's, the function returns Scalar::all(0) - * - * @param src input array that should have from 1 to 4 channels so that the result can be stored in - * Scalar_ . + * @param src input array that should have from 1 to 4 channels so that the result can be stored in + * Scalar_ . * @param mask optional operation mask. - * SEE: countNonZero, meanStdDev, norm, minMaxLoc + * SEE: countNonZero, meanStdDev, norm, minMaxLoc * @return automatically generated */ public static Scalar mean(Mat src, Mat mask) { return new Scalar(mean_0(src.nativeObj, mask.nativeObj)); } - - // - // C++: Scalar cv::mean(Mat src, Mat mask = Mat()) - // - /** * Calculates an average (mean) of array elements. - *

      + * * The function cv::mean calculates the mean value M of array elements, * independently for each channel, and return it: * \(\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\) * When all the mask elements are 0's, the function returns Scalar::all(0) - * * @param src input array that should have from 1 to 4 channels so that the result can be stored in - * Scalar_ . - * SEE: countNonZero, meanStdDev, norm, minMaxLoc + * Scalar_ . + * SEE: countNonZero, meanStdDev, norm, minMaxLoc * @return automatically generated */ public static Scalar mean(Mat src) { return new Scalar(mean_1(src.nativeObj)); } + + // + // C++: void cv::meanStdDev(Mat src, vector_double& mean, vector_double& stddev, Mat mask = Mat()) + // + /** * Calculates a mean and standard deviation of array elements. - *

      + * * The function cv::meanStdDev calculates the mean and the standard deviation M * of array elements independently for each channel and returns it via the * output parameters: @@ -1327,13 +1356,12 @@ public static Scalar mean(Mat src) { * can reshape the multi-channel array M x N to the single-channel array * M\*N x mtx.channels() (only possible when the matrix is continuous) and * then pass the matrix to calcCovarMatrix . - * - * @param src input array that should have from 1 to 4 channels so that the results can be stored in - * Scalar_ 's. - * @param mean output parameter: calculated mean value. + * @param src input array that should have from 1 to 4 channels so that the results can be stored in + * Scalar_ 's. + * @param mean output parameter: calculated mean value. * @param stddev output parameter: calculated standard deviation. - * @param mask optional operation mask. - * SEE: countNonZero, mean, norm, minMaxLoc, calcCovarMatrix + * @param mask optional operation mask. + * SEE: countNonZero, mean, norm, minMaxLoc, calcCovarMatrix */ public static void meanStdDev(Mat src, MatOfDouble mean, MatOfDouble stddev, Mat mask) { Mat mean_mat = mean; @@ -1341,14 +1369,9 @@ public static void meanStdDev(Mat src, MatOfDouble mean, MatOfDouble stddev, Mat meanStdDev_0(src.nativeObj, mean_mat.nativeObj, stddev_mat.nativeObj, mask.nativeObj); } - - // - // C++: void cv::meanStdDev(Mat src, vector_double& mean, vector_double& stddev, Mat mask = Mat()) - // - /** * Calculates a mean and standard deviation of array elements. - *

      + * * The function cv::meanStdDev calculates the mean and the standard deviation M * of array elements independently for each channel and returns it via the * output parameters: @@ -1360,12 +1383,11 @@ public static void meanStdDev(Mat src, MatOfDouble mean, MatOfDouble stddev, Mat * can reshape the multi-channel array M x N to the single-channel array * M\*N x mtx.channels() (only possible when the matrix is continuous) and * then pass the matrix to calcCovarMatrix . - * - * @param src input array that should have from 1 to 4 channels so that the results can be stored in - * Scalar_ 's. - * @param mean output parameter: calculated mean value. + * @param src input array that should have from 1 to 4 channels so that the results can be stored in + * Scalar_ 's. + * @param mean output parameter: calculated mean value. * @param stddev output parameter: calculated standard deviation. - * SEE: countNonZero, mean, norm, minMaxLoc, calcCovarMatrix + * SEE: countNonZero, mean, norm, minMaxLoc, calcCovarMatrix */ public static void meanStdDev(Mat src, MatOfDouble mean, MatOfDouble stddev) { Mat mean_mat = mean; @@ -1373,87 +1395,87 @@ public static void meanStdDev(Mat src, MatOfDouble mean, MatOfDouble stddev) { meanStdDev_1(src.nativeObj, mean_mat.nativeObj, stddev_mat.nativeObj); } + + // + // C++: double cv::norm(Mat src1, int normType = NORM_L2, Mat mask = Mat()) + // + /** * Calculates the absolute norm of an array. - *

      + * * This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes. - *

      + * * As example for one array consider the function \(r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\). * The \( L_{1}, L_{2} \) and \( L_{\infty} \) norm for the sample value \(r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\) * is calculated as follows * \(align*} - * \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ - * \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ - * \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 + * \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ + * \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ + * \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 * \) * and for \(r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\) the calculation is * \(align*} - * \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ - * \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ - * \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. + * \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ + * \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ + * \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. * \) * The following graphic shows all values for the three norm functions \(\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\) and \(\| r(x) \|_{L_\infty}\). * It is notable that the \( L_{1} \) norm forms the upper and the \( L_{\infty} \) norm forms the lower border for the example function \( r(x) \). * ![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png) - *

      + * * When the mask parameter is specified and it is not empty, the norm is - *

      + * * If normType is not specified, #NORM_L2 is used. * calculated only over the region specified by the mask. - *

      + * * Multi-channel input arrays are treated as single-channel arrays, that is, * the results for all channels are combined. - *

      + * * Hamming norms can only be calculated with CV_8U depth arrays. * - * @param src1 first input array. + * @param src1 first input array. * @param normType type of the norm (see #NormTypes). - * @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. + * @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. * @return automatically generated */ public static double norm(Mat src1, int normType, Mat mask) { return norm_0(src1.nativeObj, normType, mask.nativeObj); } - - // - // C++: double cv::norm(Mat src1, int normType = NORM_L2, Mat mask = Mat()) - // - /** * Calculates the absolute norm of an array. - *

      + * * This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes. - *

      + * * As example for one array consider the function \(r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\). * The \( L_{1}, L_{2} \) and \( L_{\infty} \) norm for the sample value \(r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\) * is calculated as follows * \(align*} - * \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ - * \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ - * \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 + * \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ + * \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ + * \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 * \) * and for \(r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\) the calculation is * \(align*} - * \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ - * \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ - * \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. + * \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ + * \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ + * \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. * \) * The following graphic shows all values for the three norm functions \(\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\) and \(\| r(x) \|_{L_\infty}\). * It is notable that the \( L_{1} \) norm forms the upper and the \( L_{\infty} \) norm forms the lower border for the example function \( r(x) \). * ![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png) - *

      + * * When the mask parameter is specified and it is not empty, the norm is - *

      + * * If normType is not specified, #NORM_L2 is used. * calculated only over the region specified by the mask. - *

      + * * Multi-channel input arrays are treated as single-channel arrays, that is, * the results for all channels are combined. - *

      + * * Hamming norms can only be calculated with CV_8U depth arrays. * - * @param src1 first input array. + * @param src1 first input array. * @param normType type of the norm (see #NormTypes). * @return automatically generated */ @@ -1463,35 +1485,35 @@ public static double norm(Mat src1, int normType) { /** * Calculates the absolute norm of an array. - *

      + * * This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes. - *

      + * * As example for one array consider the function \(r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\). * The \( L_{1}, L_{2} \) and \( L_{\infty} \) norm for the sample value \(r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\) * is calculated as follows * \(align*} - * \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ - * \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ - * \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 + * \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ + * \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ + * \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 * \) * and for \(r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\) the calculation is * \(align*} - * \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ - * \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ - * \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. + * \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ + * \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ + * \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. * \) * The following graphic shows all values for the three norm functions \(\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\) and \(\| r(x) \|_{L_\infty}\). * It is notable that the \( L_{1} \) norm forms the upper and the \( L_{\infty} \) norm forms the lower border for the example function \( r(x) \). * ![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png) - *

      + * * When the mask parameter is specified and it is not empty, the norm is - *

      + * * If normType is not specified, #NORM_L2 is used. * calculated only over the region specified by the mask. - *

      + * * Multi-channel input arrays are treated as single-channel arrays, that is, * the results for all channels are combined. - *

      + * * Hamming norms can only be calculated with CV_8U depth arrays. * * @param src1 first input array. @@ -1501,37 +1523,37 @@ public static double norm(Mat src1) { return norm_2(src1.nativeObj); } + + // + // C++: double cv::norm(Mat src1, Mat src2, int normType = NORM_L2, Mat mask = Mat()) + // + /** * Calculates an absolute difference norm or a relative difference norm. - *

      + * * This version of cv::norm calculates the absolute difference norm * or the relative difference norm of arrays src1 and src2. * The type of norm to calculate is specified using #NormTypes. * - * @param src1 first input array. - * @param src2 second input array of the same size and the same type as src1. + * @param src1 first input array. + * @param src2 second input array of the same size and the same type as src1. * @param normType type of the norm (see #NormTypes). - * @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. + * @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. * @return automatically generated */ public static double norm(Mat src1, Mat src2, int normType, Mat mask) { return norm_3(src1.nativeObj, src2.nativeObj, normType, mask.nativeObj); } - - // - // C++: double cv::norm(Mat src1, Mat src2, int normType = NORM_L2, Mat mask = Mat()) - // - /** * Calculates an absolute difference norm or a relative difference norm. - *

      + * * This version of cv::norm calculates the absolute difference norm * or the relative difference norm of arrays src1 and src2. * The type of norm to calculate is specified using #NormTypes. * - * @param src1 first input array. - * @param src2 second input array of the same size and the same type as src1. + * @param src1 first input array. + * @param src2 second input array of the same size and the same type as src1. * @param normType type of the norm (see #NormTypes). * @return automatically generated */ @@ -1541,7 +1563,7 @@ public static double norm(Mat src1, Mat src2, int normType) { /** * Calculates an absolute difference norm or a relative difference norm. - *

      + * * This version of cv::norm calculates the absolute difference norm * or the relative difference norm of arrays src1 and src2. * The type of norm to calculate is specified using #NormTypes. @@ -1554,47 +1576,47 @@ public static double norm(Mat src1, Mat src2) { return norm_5(src1.nativeObj, src2.nativeObj); } + + // + // C++: double cv::PSNR(Mat src1, Mat src2, double R = 255.) + // + /** * Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric. - *

      + * * This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB), * between two input arrays src1 and src2. The arrays must have the same type. - *

      + * * The PSNR is calculated as follows: - *

      + * * \( * \texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) } * \) - *

      + * * where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data) * and MSE is the mean squared error between the two arrays. * * @param src1 first input array. * @param src2 second input array of the same size as src1. - * @param R the maximum pixel value (255 by default) + * @param R the maximum pixel value (255 by default) * @return automatically generated */ public static double PSNR(Mat src1, Mat src2, double R) { return PSNR_0(src1.nativeObj, src2.nativeObj, R); } - - // - // C++: double cv::PSNR(Mat src1, Mat src2, double R = 255.) - // - /** * Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric. - *

      + * * This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB), * between two input arrays src1 and src2. The arrays must have the same type. - *

      + * * The PSNR is calculated as follows: - *

      + * * \( * \texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) } * \) - *

      + * * where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data) * and MSE is the mean squared error between the two arrays. * @@ -1606,47 +1628,45 @@ public static double PSNR(Mat src1, Mat src2) { return PSNR_1(src1.nativeObj, src2.nativeObj); } + + // + // C++: void cv::batchDistance(Mat src1, Mat src2, Mat& dist, int dtype, Mat& nidx, int normType = NORM_L2, int K = 0, Mat mask = Mat(), int update = 0, bool crosscheck = false) + // + /** * naive nearest neighbor finder - *

      + * * see http://en.wikipedia.org/wiki/Nearest_neighbor_search * TODO: document - * - * @param src1 automatically generated - * @param src2 automatically generated - * @param dist automatically generated - * @param dtype automatically generated - * @param nidx automatically generated - * @param normType automatically generated - * @param K automatically generated - * @param mask automatically generated - * @param update automatically generated + * @param src1 automatically generated + * @param src2 automatically generated + * @param dist automatically generated + * @param dtype automatically generated + * @param nidx automatically generated + * @param normType automatically generated + * @param K automatically generated + * @param mask automatically generated + * @param update automatically generated * @param crosscheck automatically generated */ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat nidx, int normType, int K, Mat mask, int update, boolean crosscheck) { batchDistance_0(src1.nativeObj, src2.nativeObj, dist.nativeObj, dtype, nidx.nativeObj, normType, K, mask.nativeObj, update, crosscheck); } - - // - // C++: void cv::batchDistance(Mat src1, Mat src2, Mat& dist, int dtype, Mat& nidx, int normType = NORM_L2, int K = 0, Mat mask = Mat(), int update = 0, bool crosscheck = false) - // - /** * naive nearest neighbor finder - *

      + * * see http://en.wikipedia.org/wiki/Nearest_neighbor_search * TODO: document - * - * @param src1 automatically generated - * @param src2 automatically generated - * @param dist automatically generated - * @param dtype automatically generated - * @param nidx automatically generated + * @param src1 automatically generated + * @param src2 automatically generated + * @param dist automatically generated + * @param dtype automatically generated + * @param nidx automatically generated * @param normType automatically generated - * @param K automatically generated - * @param mask automatically generated - * @param update automatically generated + * @param K automatically generated + * @param mask automatically generated + * @param update automatically generated */ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat nidx, int normType, int K, Mat mask, int update) { batchDistance_1(src1.nativeObj, src2.nativeObj, dist.nativeObj, dtype, nidx.nativeObj, normType, K, mask.nativeObj, update); @@ -1654,18 +1674,17 @@ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat ni /** * naive nearest neighbor finder - *

      + * * see http://en.wikipedia.org/wiki/Nearest_neighbor_search * TODO: document - * - * @param src1 automatically generated - * @param src2 automatically generated - * @param dist automatically generated - * @param dtype automatically generated - * @param nidx automatically generated + * @param src1 automatically generated + * @param src2 automatically generated + * @param dist automatically generated + * @param dtype automatically generated + * @param nidx automatically generated * @param normType automatically generated - * @param K automatically generated - * @param mask automatically generated + * @param K automatically generated + * @param mask automatically generated */ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat nidx, int normType, int K, Mat mask) { batchDistance_2(src1.nativeObj, src2.nativeObj, dist.nativeObj, dtype, nidx.nativeObj, normType, K, mask.nativeObj); @@ -1673,17 +1692,16 @@ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat ni /** * naive nearest neighbor finder - *

      + * * see http://en.wikipedia.org/wiki/Nearest_neighbor_search * TODO: document - * - * @param src1 automatically generated - * @param src2 automatically generated - * @param dist automatically generated - * @param dtype automatically generated - * @param nidx automatically generated + * @param src1 automatically generated + * @param src2 automatically generated + * @param dist automatically generated + * @param dtype automatically generated + * @param nidx automatically generated * @param normType automatically generated - * @param K automatically generated + * @param K automatically generated */ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat nidx, int normType, int K) { batchDistance_3(src1.nativeObj, src2.nativeObj, dist.nativeObj, dtype, nidx.nativeObj, normType, K); @@ -1691,15 +1709,14 @@ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat ni /** * naive nearest neighbor finder - *

      + * * see http://en.wikipedia.org/wiki/Nearest_neighbor_search * TODO: document - * - * @param src1 automatically generated - * @param src2 automatically generated - * @param dist automatically generated - * @param dtype automatically generated - * @param nidx automatically generated + * @param src1 automatically generated + * @param src2 automatically generated + * @param dist automatically generated + * @param dtype automatically generated + * @param nidx automatically generated * @param normType automatically generated */ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat nidx, int normType) { @@ -1708,145 +1725,144 @@ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat ni /** * naive nearest neighbor finder - *

      + * * see http://en.wikipedia.org/wiki/Nearest_neighbor_search * TODO: document - * - * @param src1 automatically generated - * @param src2 automatically generated - * @param dist automatically generated + * @param src1 automatically generated + * @param src2 automatically generated + * @param dist automatically generated * @param dtype automatically generated - * @param nidx automatically generated + * @param nidx automatically generated */ public static void batchDistance(Mat src1, Mat src2, Mat dist, int dtype, Mat nidx) { batchDistance_5(src1.nativeObj, src2.nativeObj, dist.nativeObj, dtype, nidx.nativeObj); } + + // + // C++: void cv::normalize(Mat src, Mat& dst, double alpha = 1, double beta = 0, int norm_type = NORM_L2, int dtype = -1, Mat mask = Mat()) + // + /** * Normalizes the norm or value range of an array. - *

      + * * The function cv::normalize normalizes scale and shift the input array elements so that * \(\| \texttt{dst} \| _{L_p}= \texttt{alpha}\) * (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that * \(\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\) - *

      + * * when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be * normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this * sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or * min-max but modify the whole array, you can use norm and Mat::convertTo. - *

      + * * In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, * the range transformation for sparse matrices is not allowed since it can shift the zero level. - *

      + * * Possible usage with some positive example data: * - * vector<double> positiveData = { 2.0, 8.0, 10.0 }; - * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; - *

      - * // Norm to probability (total count) - * // sum(numbers) = 20.0 - * // 2.0 0.1 (2.0/20.0) - * // 8.0 0.4 (8.0/20.0) - * // 10.0 0.5 (10.0/20.0) - * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); - *

      - * // Norm to unit vector: ||positiveData|| = 1.0 - * // 2.0 0.15 - * // 8.0 0.62 - * // 10.0 0.77 - * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); - *

      - * // Norm to max element - * // 2.0 0.2 (2.0/10.0) - * // 8.0 0.8 (8.0/10.0) - * // 10.0 1.0 (10.0/10.0) - * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); - *

      - * // Norm to range [0.0;1.0] - * // 2.0 0.0 (shift to left border) - * // 8.0 0.75 (6.0/8.0) - * // 10.0 1.0 (shift to right border) - * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); + * vector<double> positiveData = { 2.0, 8.0, 10.0 }; + * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; + * + * // Norm to probability (total count) + * // sum(numbers) = 20.0 + * // 2.0 0.1 (2.0/20.0) + * // 8.0 0.4 (8.0/20.0) + * // 10.0 0.5 (10.0/20.0) + * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); + * + * // Norm to unit vector: ||positiveData|| = 1.0 + * // 2.0 0.15 + * // 8.0 0.62 + * // 10.0 0.77 + * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); + * + * // Norm to max element + * // 2.0 0.2 (2.0/10.0) + * // 8.0 0.8 (8.0/10.0) + * // 10.0 1.0 (10.0/10.0) + * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); + * + * // Norm to range [0.0;1.0] + * // 2.0 0.0 (shift to left border) + * // 8.0 0.75 (6.0/8.0) + * // 10.0 1.0 (shift to right border) + * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); * * - * @param src input array. - * @param dst output array of the same size as src . - * @param alpha norm value to normalize to or the lower range boundary in case of the range - * normalization. - * @param beta upper range boundary in case of the range normalization; it is not used for the norm - * normalization. + * @param src input array. + * @param dst output array of the same size as src . + * @param alpha norm value to normalize to or the lower range boundary in case of the range + * normalization. + * @param beta upper range boundary in case of the range normalization; it is not used for the norm + * normalization. * @param norm_type normalization type (see cv::NormTypes). - * @param dtype when negative, the output array has the same type as src; otherwise, it has the same - * number of channels as src and the depth =CV_MAT_DEPTH(dtype). - * @param mask optional operation mask. - * SEE: norm, Mat::convertTo, SparseMat::convertTo + * @param dtype when negative, the output array has the same type as src; otherwise, it has the same + * number of channels as src and the depth =CV_MAT_DEPTH(dtype). + * @param mask optional operation mask. + * SEE: norm, Mat::convertTo, SparseMat::convertTo */ public static void normalize(Mat src, Mat dst, double alpha, double beta, int norm_type, int dtype, Mat mask) { normalize_0(src.nativeObj, dst.nativeObj, alpha, beta, norm_type, dtype, mask.nativeObj); } - - // - // C++: void cv::normalize(Mat src, Mat& dst, double alpha = 1, double beta = 0, int norm_type = NORM_L2, int dtype = -1, Mat mask = Mat()) - // - /** * Normalizes the norm or value range of an array. - *

      + * * The function cv::normalize normalizes scale and shift the input array elements so that * \(\| \texttt{dst} \| _{L_p}= \texttt{alpha}\) * (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that * \(\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\) - *

      + * * when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be * normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this * sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or * min-max but modify the whole array, you can use norm and Mat::convertTo. - *

      + * * In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, * the range transformation for sparse matrices is not allowed since it can shift the zero level. - *

      + * * Possible usage with some positive example data: * - * vector<double> positiveData = { 2.0, 8.0, 10.0 }; - * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; - *

      - * // Norm to probability (total count) - * // sum(numbers) = 20.0 - * // 2.0 0.1 (2.0/20.0) - * // 8.0 0.4 (8.0/20.0) - * // 10.0 0.5 (10.0/20.0) - * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); - *

      - * // Norm to unit vector: ||positiveData|| = 1.0 - * // 2.0 0.15 - * // 8.0 0.62 - * // 10.0 0.77 - * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); - *

      - * // Norm to max element - * // 2.0 0.2 (2.0/10.0) - * // 8.0 0.8 (8.0/10.0) - * // 10.0 1.0 (10.0/10.0) - * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); - *

      - * // Norm to range [0.0;1.0] - * // 2.0 0.0 (shift to left border) - * // 8.0 0.75 (6.0/8.0) - * // 10.0 1.0 (shift to right border) - * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); + * vector<double> positiveData = { 2.0, 8.0, 10.0 }; + * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; + * + * // Norm to probability (total count) + * // sum(numbers) = 20.0 + * // 2.0 0.1 (2.0/20.0) + * // 8.0 0.4 (8.0/20.0) + * // 10.0 0.5 (10.0/20.0) + * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); + * + * // Norm to unit vector: ||positiveData|| = 1.0 + * // 2.0 0.15 + * // 8.0 0.62 + * // 10.0 0.77 + * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); + * + * // Norm to max element + * // 2.0 0.2 (2.0/10.0) + * // 8.0 0.8 (8.0/10.0) + * // 10.0 1.0 (10.0/10.0) + * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); + * + * // Norm to range [0.0;1.0] + * // 2.0 0.0 (shift to left border) + * // 8.0 0.75 (6.0/8.0) + * // 10.0 1.0 (shift to right border) + * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); * * - * @param src input array. - * @param dst output array of the same size as src . - * @param alpha norm value to normalize to or the lower range boundary in case of the range - * normalization. - * @param beta upper range boundary in case of the range normalization; it is not used for the norm - * normalization. + * @param src input array. + * @param dst output array of the same size as src . + * @param alpha norm value to normalize to or the lower range boundary in case of the range + * normalization. + * @param beta upper range boundary in case of the range normalization; it is not used for the norm + * normalization. * @param norm_type normalization type (see cv::NormTypes). - * @param dtype when negative, the output array has the same type as src; otherwise, it has the same - * number of channels as src and the depth =CV_MAT_DEPTH(dtype). - * SEE: norm, Mat::convertTo, SparseMat::convertTo + * @param dtype when negative, the output array has the same type as src; otherwise, it has the same + * number of channels as src and the depth =CV_MAT_DEPTH(dtype). + * SEE: norm, Mat::convertTo, SparseMat::convertTo */ public static void normalize(Mat src, Mat dst, double alpha, double beta, int norm_type, int dtype) { normalize_1(src.nativeObj, dst.nativeObj, alpha, beta, norm_type, dtype); @@ -1854,60 +1870,60 @@ public static void normalize(Mat src, Mat dst, double alpha, double beta, int no /** * Normalizes the norm or value range of an array. - *

      + * * The function cv::normalize normalizes scale and shift the input array elements so that * \(\| \texttt{dst} \| _{L_p}= \texttt{alpha}\) * (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that * \(\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\) - *

      + * * when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be * normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this * sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or * min-max but modify the whole array, you can use norm and Mat::convertTo. - *

      + * * In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, * the range transformation for sparse matrices is not allowed since it can shift the zero level. - *

      + * * Possible usage with some positive example data: * - * vector<double> positiveData = { 2.0, 8.0, 10.0 }; - * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; - *

      - * // Norm to probability (total count) - * // sum(numbers) = 20.0 - * // 2.0 0.1 (2.0/20.0) - * // 8.0 0.4 (8.0/20.0) - * // 10.0 0.5 (10.0/20.0) - * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); - *

      - * // Norm to unit vector: ||positiveData|| = 1.0 - * // 2.0 0.15 - * // 8.0 0.62 - * // 10.0 0.77 - * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); - *

      - * // Norm to max element - * // 2.0 0.2 (2.0/10.0) - * // 8.0 0.8 (8.0/10.0) - * // 10.0 1.0 (10.0/10.0) - * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); - *

      - * // Norm to range [0.0;1.0] - * // 2.0 0.0 (shift to left border) - * // 8.0 0.75 (6.0/8.0) - * // 10.0 1.0 (shift to right border) - * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); + * vector<double> positiveData = { 2.0, 8.0, 10.0 }; + * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; + * + * // Norm to probability (total count) + * // sum(numbers) = 20.0 + * // 2.0 0.1 (2.0/20.0) + * // 8.0 0.4 (8.0/20.0) + * // 10.0 0.5 (10.0/20.0) + * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); + * + * // Norm to unit vector: ||positiveData|| = 1.0 + * // 2.0 0.15 + * // 8.0 0.62 + * // 10.0 0.77 + * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); + * + * // Norm to max element + * // 2.0 0.2 (2.0/10.0) + * // 8.0 0.8 (8.0/10.0) + * // 10.0 1.0 (10.0/10.0) + * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); + * + * // Norm to range [0.0;1.0] + * // 2.0 0.0 (shift to left border) + * // 8.0 0.75 (6.0/8.0) + * // 10.0 1.0 (shift to right border) + * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); * * - * @param src input array. - * @param dst output array of the same size as src . - * @param alpha norm value to normalize to or the lower range boundary in case of the range - * normalization. - * @param beta upper range boundary in case of the range normalization; it is not used for the norm - * normalization. + * @param src input array. + * @param dst output array of the same size as src . + * @param alpha norm value to normalize to or the lower range boundary in case of the range + * normalization. + * @param beta upper range boundary in case of the range normalization; it is not used for the norm + * normalization. * @param norm_type normalization type (see cv::NormTypes). - * number of channels as src and the depth =CV_MAT_DEPTH(dtype). - * SEE: norm, Mat::convertTo, SparseMat::convertTo + * number of channels as src and the depth =CV_MAT_DEPTH(dtype). + * SEE: norm, Mat::convertTo, SparseMat::convertTo */ public static void normalize(Mat src, Mat dst, double alpha, double beta, int norm_type) { normalize_2(src.nativeObj, dst.nativeObj, alpha, beta, norm_type); @@ -1915,59 +1931,59 @@ public static void normalize(Mat src, Mat dst, double alpha, double beta, int no /** * Normalizes the norm or value range of an array. - *

      + * * The function cv::normalize normalizes scale and shift the input array elements so that * \(\| \texttt{dst} \| _{L_p}= \texttt{alpha}\) * (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that * \(\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\) - *

      + * * when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be * normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this * sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or * min-max but modify the whole array, you can use norm and Mat::convertTo. - *

      + * * In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, * the range transformation for sparse matrices is not allowed since it can shift the zero level. - *

      + * * Possible usage with some positive example data: * - * vector<double> positiveData = { 2.0, 8.0, 10.0 }; - * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; - *

      - * // Norm to probability (total count) - * // sum(numbers) = 20.0 - * // 2.0 0.1 (2.0/20.0) - * // 8.0 0.4 (8.0/20.0) - * // 10.0 0.5 (10.0/20.0) - * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); - *

      - * // Norm to unit vector: ||positiveData|| = 1.0 - * // 2.0 0.15 - * // 8.0 0.62 - * // 10.0 0.77 - * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); - *

      - * // Norm to max element - * // 2.0 0.2 (2.0/10.0) - * // 8.0 0.8 (8.0/10.0) - * // 10.0 1.0 (10.0/10.0) - * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); - *

      - * // Norm to range [0.0;1.0] - * // 2.0 0.0 (shift to left border) - * // 8.0 0.75 (6.0/8.0) - * // 10.0 1.0 (shift to right border) - * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); + * vector<double> positiveData = { 2.0, 8.0, 10.0 }; + * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; + * + * // Norm to probability (total count) + * // sum(numbers) = 20.0 + * // 2.0 0.1 (2.0/20.0) + * // 8.0 0.4 (8.0/20.0) + * // 10.0 0.5 (10.0/20.0) + * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); + * + * // Norm to unit vector: ||positiveData|| = 1.0 + * // 2.0 0.15 + * // 8.0 0.62 + * // 10.0 0.77 + * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); + * + * // Norm to max element + * // 2.0 0.2 (2.0/10.0) + * // 8.0 0.8 (8.0/10.0) + * // 10.0 1.0 (10.0/10.0) + * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); + * + * // Norm to range [0.0;1.0] + * // 2.0 0.0 (shift to left border) + * // 8.0 0.75 (6.0/8.0) + * // 10.0 1.0 (shift to right border) + * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); * * - * @param src input array. - * @param dst output array of the same size as src . + * @param src input array. + * @param dst output array of the same size as src . * @param alpha norm value to normalize to or the lower range boundary in case of the range - * normalization. - * @param beta upper range boundary in case of the range normalization; it is not used for the norm - * normalization. - * number of channels as src and the depth =CV_MAT_DEPTH(dtype). - * SEE: norm, Mat::convertTo, SparseMat::convertTo + * normalization. + * @param beta upper range boundary in case of the range normalization; it is not used for the norm + * normalization. + * number of channels as src and the depth =CV_MAT_DEPTH(dtype). + * SEE: norm, Mat::convertTo, SparseMat::convertTo */ public static void normalize(Mat src, Mat dst, double alpha, double beta) { normalize_3(src.nativeObj, dst.nativeObj, alpha, beta); @@ -1975,58 +1991,58 @@ public static void normalize(Mat src, Mat dst, double alpha, double beta) { /** * Normalizes the norm or value range of an array. - *

      + * * The function cv::normalize normalizes scale and shift the input array elements so that * \(\| \texttt{dst} \| _{L_p}= \texttt{alpha}\) * (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that * \(\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\) - *

      + * * when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be * normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this * sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or * min-max but modify the whole array, you can use norm and Mat::convertTo. - *

      + * * In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, * the range transformation for sparse matrices is not allowed since it can shift the zero level. - *

      + * * Possible usage with some positive example data: * - * vector<double> positiveData = { 2.0, 8.0, 10.0 }; - * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; - *

      - * // Norm to probability (total count) - * // sum(numbers) = 20.0 - * // 2.0 0.1 (2.0/20.0) - * // 8.0 0.4 (8.0/20.0) - * // 10.0 0.5 (10.0/20.0) - * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); - *

      - * // Norm to unit vector: ||positiveData|| = 1.0 - * // 2.0 0.15 - * // 8.0 0.62 - * // 10.0 0.77 - * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); - *

      - * // Norm to max element - * // 2.0 0.2 (2.0/10.0) - * // 8.0 0.8 (8.0/10.0) - * // 10.0 1.0 (10.0/10.0) - * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); - *

      - * // Norm to range [0.0;1.0] - * // 2.0 0.0 (shift to left border) - * // 8.0 0.75 (6.0/8.0) - * // 10.0 1.0 (shift to right border) - * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); + * vector<double> positiveData = { 2.0, 8.0, 10.0 }; + * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; + * + * // Norm to probability (total count) + * // sum(numbers) = 20.0 + * // 2.0 0.1 (2.0/20.0) + * // 8.0 0.4 (8.0/20.0) + * // 10.0 0.5 (10.0/20.0) + * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); + * + * // Norm to unit vector: ||positiveData|| = 1.0 + * // 2.0 0.15 + * // 8.0 0.62 + * // 10.0 0.77 + * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); + * + * // Norm to max element + * // 2.0 0.2 (2.0/10.0) + * // 8.0 0.8 (8.0/10.0) + * // 10.0 1.0 (10.0/10.0) + * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); + * + * // Norm to range [0.0;1.0] + * // 2.0 0.0 (shift to left border) + * // 8.0 0.75 (6.0/8.0) + * // 10.0 1.0 (shift to right border) + * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); * * - * @param src input array. - * @param dst output array of the same size as src . + * @param src input array. + * @param dst output array of the same size as src . * @param alpha norm value to normalize to or the lower range boundary in case of the range - * normalization. - * normalization. - * number of channels as src and the depth =CV_MAT_DEPTH(dtype). - * SEE: norm, Mat::convertTo, SparseMat::convertTo + * normalization. + * normalization. + * number of channels as src and the depth =CV_MAT_DEPTH(dtype). + * SEE: norm, Mat::convertTo, SparseMat::convertTo */ public static void normalize(Mat src, Mat dst, double alpha) { normalize_4(src.nativeObj, dst.nativeObj, alpha); @@ -2034,62 +2050,67 @@ public static void normalize(Mat src, Mat dst, double alpha) { /** * Normalizes the norm or value range of an array. - *

      + * * The function cv::normalize normalizes scale and shift the input array elements so that * \(\| \texttt{dst} \| _{L_p}= \texttt{alpha}\) * (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that * \(\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\) - *

      + * * when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be * normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this * sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or * min-max but modify the whole array, you can use norm and Mat::convertTo. - *

      + * * In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, * the range transformation for sparse matrices is not allowed since it can shift the zero level. - *

      + * * Possible usage with some positive example data: * - * vector<double> positiveData = { 2.0, 8.0, 10.0 }; - * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; - *

      - * // Norm to probability (total count) - * // sum(numbers) = 20.0 - * // 2.0 0.1 (2.0/20.0) - * // 8.0 0.4 (8.0/20.0) - * // 10.0 0.5 (10.0/20.0) - * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); - *

      - * // Norm to unit vector: ||positiveData|| = 1.0 - * // 2.0 0.15 - * // 8.0 0.62 - * // 10.0 0.77 - * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); - *

      - * // Norm to max element - * // 2.0 0.2 (2.0/10.0) - * // 8.0 0.8 (8.0/10.0) - * // 10.0 1.0 (10.0/10.0) - * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); - *

      - * // Norm to range [0.0;1.0] - * // 2.0 0.0 (shift to left border) - * // 8.0 0.75 (6.0/8.0) - * // 10.0 1.0 (shift to right border) - * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); + * vector<double> positiveData = { 2.0, 8.0, 10.0 }; + * vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; + * + * // Norm to probability (total count) + * // sum(numbers) = 20.0 + * // 2.0 0.1 (2.0/20.0) + * // 8.0 0.4 (8.0/20.0) + * // 10.0 0.5 (10.0/20.0) + * normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); + * + * // Norm to unit vector: ||positiveData|| = 1.0 + * // 2.0 0.15 + * // 8.0 0.62 + * // 10.0 0.77 + * normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); + * + * // Norm to max element + * // 2.0 0.2 (2.0/10.0) + * // 8.0 0.8 (8.0/10.0) + * // 10.0 1.0 (10.0/10.0) + * normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); + * + * // Norm to range [0.0;1.0] + * // 2.0 0.0 (shift to left border) + * // 8.0 0.75 (6.0/8.0) + * // 10.0 1.0 (shift to right border) + * normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); * * * @param src input array. * @param dst output array of the same size as src . - * normalization. - * normalization. - * number of channels as src and the depth =CV_MAT_DEPTH(dtype). - * SEE: norm, Mat::convertTo, SparseMat::convertTo + * normalization. + * normalization. + * number of channels as src and the depth =CV_MAT_DEPTH(dtype). + * SEE: norm, Mat::convertTo, SparseMat::convertTo */ public static void normalize(Mat src, Mat dst) { normalize_5(src.nativeObj, dst.nativeObj); } + + // + // C++: void cv::reduceArgMin(Mat src, Mat& dst, int axis, bool lastIndex = false) + // + /** * Finds indices of min elements along provided axis * @@ -2098,22 +2119,17 @@ public static void normalize(Mat src, Mat dst) { * - NaN handling is left unspecified, see patchNaNs(). * - The returned index is always in bounds of input matrix. * - * @param src input single-channel array. - * @param dst output array of type CV_32SC1 with the same dimensionality as src, - * except for axis being reduced - it should be set to 1. + * @param src input single-channel array. + * @param dst output array of type CV_32SC1 with the same dimensionality as src, + * except for axis being reduced - it should be set to 1. * @param lastIndex whether to get the index of first or last occurrence of min. - * @param axis axis to reduce along. - * SEE: reduceArgMax, minMaxLoc, min, max, compare, reduce + * @param axis axis to reduce along. + * SEE: reduceArgMax, minMaxLoc, min, max, compare, reduce */ public static void reduceArgMin(Mat src, Mat dst, int axis, boolean lastIndex) { reduceArgMin_0(src.nativeObj, dst.nativeObj, axis, lastIndex); } - - // - // C++: void cv::reduceArgMin(Mat src, Mat& dst, int axis, bool lastIndex = false) - // - /** * Finds indices of min elements along provided axis * @@ -2122,16 +2138,21 @@ public static void reduceArgMin(Mat src, Mat dst, int axis, boolean lastIndex) { * - NaN handling is left unspecified, see patchNaNs(). * - The returned index is always in bounds of input matrix. * - * @param src input single-channel array. - * @param dst output array of type CV_32SC1 with the same dimensionality as src, - * except for axis being reduced - it should be set to 1. + * @param src input single-channel array. + * @param dst output array of type CV_32SC1 with the same dimensionality as src, + * except for axis being reduced - it should be set to 1. * @param axis axis to reduce along. - * SEE: reduceArgMax, minMaxLoc, min, max, compare, reduce + * SEE: reduceArgMax, minMaxLoc, min, max, compare, reduce */ public static void reduceArgMin(Mat src, Mat dst, int axis) { reduceArgMin_1(src.nativeObj, dst.nativeObj, axis); } + + // + // C++: void cv::reduceArgMax(Mat src, Mat& dst, int axis, bool lastIndex = false) + // + /** * Finds indices of max elements along provided axis * @@ -2140,22 +2161,17 @@ public static void reduceArgMin(Mat src, Mat dst, int axis) { * - NaN handling is left unspecified, see patchNaNs(). * - The returned index is always in bounds of input matrix. * - * @param src input single-channel array. - * @param dst output array of type CV_32SC1 with the same dimensionality as src, - * except for axis being reduced - it should be set to 1. + * @param src input single-channel array. + * @param dst output array of type CV_32SC1 with the same dimensionality as src, + * except for axis being reduced - it should be set to 1. * @param lastIndex whether to get the index of first or last occurrence of max. - * @param axis axis to reduce along. - * SEE: reduceArgMin, minMaxLoc, min, max, compare, reduce + * @param axis axis to reduce along. + * SEE: reduceArgMin, minMaxLoc, min, max, compare, reduce */ public static void reduceArgMax(Mat src, Mat dst, int axis, boolean lastIndex) { reduceArgMax_0(src.nativeObj, dst.nativeObj, axis, lastIndex); } - - // - // C++: void cv::reduceArgMax(Mat src, Mat& dst, int axis, bool lastIndex = false) - // - /** * Finds indices of max elements along provided axis * @@ -2164,83 +2180,89 @@ public static void reduceArgMax(Mat src, Mat dst, int axis, boolean lastIndex) { * - NaN handling is left unspecified, see patchNaNs(). * - The returned index is always in bounds of input matrix. * - * @param src input single-channel array. - * @param dst output array of type CV_32SC1 with the same dimensionality as src, - * except for axis being reduced - it should be set to 1. + * @param src input single-channel array. + * @param dst output array of type CV_32SC1 with the same dimensionality as src, + * except for axis being reduced - it should be set to 1. * @param axis axis to reduce along. - * SEE: reduceArgMin, minMaxLoc, min, max, compare, reduce + * SEE: reduceArgMin, minMaxLoc, min, max, compare, reduce */ public static void reduceArgMax(Mat src, Mat dst, int axis) { reduceArgMax_1(src.nativeObj, dst.nativeObj, axis); } + + // + // C++: void cv::reduce(Mat src, Mat& dst, int dim, int rtype, int dtype = -1) + // + /** * Reduces a matrix to a vector. - *

      + * * The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of * 1D vectors and performing the specified operation on the vectors until a single row/column is * obtained. For example, the function can be used to compute horizontal and vertical projections of a * raster image. In case of #REDUCE_MAX and #REDUCE_MIN , the output image should have the same type as the source one. * In case of #REDUCE_SUM, #REDUCE_SUM2 and #REDUCE_AVG , the output may have a larger element bit-depth to preserve accuracy. * And multi-channel arrays are also supported in these two reduction modes. - *

      + * * The following code demonstrates its usage for a single channel matrix. * SNIPPET: snippets/core_reduce.cpp example - *

      + * * And the following code demonstrates its usage for a two-channel matrix. * SNIPPET: snippets/core_reduce.cpp example2 * - * @param src input 2D matrix. - * @param dst output vector. Its size and type is defined by dim and dtype parameters. - * @param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to - * a single row. 1 means that the matrix is reduced to a single column. + * @param src input 2D matrix. + * @param dst output vector. Its size and type is defined by dim and dtype parameters. + * @param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to + * a single row. 1 means that the matrix is reduced to a single column. * @param rtype reduction operation that could be one of #ReduceTypes * @param dtype when negative, the output vector will have the same type as the input matrix, - * otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). - * SEE: repeat, reduceArgMin, reduceArgMax + * otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). + * SEE: repeat, reduceArgMin, reduceArgMax */ public static void reduce(Mat src, Mat dst, int dim, int rtype, int dtype) { reduce_0(src.nativeObj, dst.nativeObj, dim, rtype, dtype); } - - // - // C++: void cv::reduce(Mat src, Mat& dst, int dim, int rtype, int dtype = -1) - // - /** * Reduces a matrix to a vector. - *

      + * * The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of * 1D vectors and performing the specified operation on the vectors until a single row/column is * obtained. For example, the function can be used to compute horizontal and vertical projections of a * raster image. In case of #REDUCE_MAX and #REDUCE_MIN , the output image should have the same type as the source one. * In case of #REDUCE_SUM, #REDUCE_SUM2 and #REDUCE_AVG , the output may have a larger element bit-depth to preserve accuracy. * And multi-channel arrays are also supported in these two reduction modes. - *

      + * * The following code demonstrates its usage for a single channel matrix. * SNIPPET: snippets/core_reduce.cpp example - *

      + * * And the following code demonstrates its usage for a two-channel matrix. * SNIPPET: snippets/core_reduce.cpp example2 * - * @param src input 2D matrix. - * @param dst output vector. Its size and type is defined by dim and dtype parameters. - * @param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to - * a single row. 1 means that the matrix is reduced to a single column. + * @param src input 2D matrix. + * @param dst output vector. Its size and type is defined by dim and dtype parameters. + * @param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to + * a single row. 1 means that the matrix is reduced to a single column. * @param rtype reduction operation that could be one of #ReduceTypes - * otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). - * SEE: repeat, reduceArgMin, reduceArgMax + * otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). + * SEE: repeat, reduceArgMin, reduceArgMax */ public static void reduce(Mat src, Mat dst, int dim, int rtype) { reduce_1(src.nativeObj, dst.nativeObj, dim, rtype); } + + // + // C++: void cv::merge(vector_Mat mv, Mat& dst) + // + /** - * @param mv input vector of matrices to be merged; all the matrices in mv must have the same - * size and the same depth. + * + * @param mv input vector of matrices to be merged; all the matrices in mv must have the same + * size and the same depth. * @param dst output array of the same size and the same depth as mv[0]; The number of channels will - * be the total number of channels in the matrix array. + * be the total number of channels in the matrix array. */ public static void merge(List mv, Mat dst) { Mat mv_mat = Converters.vector_Mat_to_Mat(mv); @@ -2249,11 +2271,12 @@ public static void merge(List mv, Mat dst) { // - // C++: void cv::merge(vector_Mat mv, Mat& dst) + // C++: void cv::split(Mat m, vector_Mat& mv) // /** - * @param m input multi-channel array. + * + * @param m input multi-channel array. * @param mv output vector of arrays; the arrays themselves are reallocated, if needed. */ public static void split(Mat m, List mv) { @@ -2265,21 +2288,22 @@ public static void split(Mat m, List mv) { // - // C++: void cv::split(Mat m, vector_Mat& mv) + // C++: void cv::mixChannels(vector_Mat src, vector_Mat dst, vector_int fromTo) // /** - * @param src input array or vector of matrices; all of the matrices must have the same size and the - * same depth. - * @param dst output array or vector of matrices; all the matrices must be allocated; their size and - * depth must be the same as in src[0]. + * + * @param src input array or vector of matrices; all of the matrices must have the same size and the + * same depth. + * @param dst output array or vector of matrices; all the matrices must be allocated; their size and + * depth must be the same as in src[0]. * @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is - * a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in - * dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to - * src[0].channels()-1, the second input image channels are indexed from src[0].channels() to - * src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image - * channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is - * filled with zero . + * a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in + * dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to + * src[0].channels()-1, the second input image channels are indexed from src[0].channels() to + * src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image + * channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is + * filled with zero . */ public static void mixChannels(List src, List dst, MatOfInt fromTo) { Mat src_mat = Converters.vector_Mat_to_Mat(src); @@ -2290,16 +2314,15 @@ public static void mixChannels(List src, List dst, MatOfInt fromTo) { // - // C++: void cv::mixChannels(vector_Mat src, vector_Mat dst, vector_int fromTo) + // C++: void cv::extractChannel(Mat src, Mat& dst, int coi) // /** * Extracts a single channel from src (coi is 0-based index) - * * @param src input array * @param dst output array * @param coi index of channel to extract - * SEE: mixChannels, split + * SEE: mixChannels, split */ public static void extractChannel(Mat src, Mat dst, int coi) { extractChannel_0(src.nativeObj, dst.nativeObj, coi); @@ -2307,16 +2330,15 @@ public static void extractChannel(Mat src, Mat dst, int coi) { // - // C++: void cv::extractChannel(Mat src, Mat& dst, int coi) + // C++: void cv::insertChannel(Mat src, Mat& dst, int coi) // /** * Inserts a single channel to dst (coi is 0-based index) - * * @param src input array * @param dst output array * @param coi index of channel for insertion - * SEE: mixChannels, merge + * SEE: mixChannels, merge */ public static void insertChannel(Mat src, Mat dst, int coi) { insertChannel_0(src.nativeObj, dst.nativeObj, coi); @@ -2324,12 +2346,12 @@ public static void insertChannel(Mat src, Mat dst, int coi) { // - // C++: void cv::insertChannel(Mat src, Mat& dst, int coi) + // C++: void cv::flip(Mat src, Mat& dst, int flipCode) // /** * Flips a 2D array around vertical, horizontal, or both axes. - *

      + * * The function cv::flip flips the array in one of three different ways (row * and column indices are 0-based): * \(\texttt{dst} _{ij} = @@ -2342,24 +2364,23 @@ public static void insertChannel(Mat src, Mat dst, int coi) { * \right.\) * The example scenarios of using the function are the following: * Vertical flipping of the image (flipCode == 0) to switch between - * top-left and bottom-left image origin. This is a typical operation - * in video processing on Microsoft Windows\* OS. + * top-left and bottom-left image origin. This is a typical operation + * in video processing on Microsoft Windows\* OS. * Horizontal flipping of the image with the subsequent horizontal - * shift and absolute difference calculation to check for a - * vertical-axis symmetry (flipCode > 0). + * shift and absolute difference calculation to check for a + * vertical-axis symmetry (flipCode > 0). * Simultaneous horizontal and vertical flipping of the image with - * the subsequent shift and absolute difference calculation to check - * for a central symmetry (flipCode < 0). + * the subsequent shift and absolute difference calculation to check + * for a central symmetry (flipCode < 0). * Reversing the order of point arrays (flipCode > 0 or - * flipCode == 0). - * - * @param src input array. - * @param dst output array of the same size and type as src. + * flipCode == 0). + * @param src input array. + * @param dst output array of the same size and type as src. * @param flipCode a flag to specify how to flip the array; 0 means - * flipping around the x-axis and positive value (for example, 1) means - * flipping around y-axis. Negative value (for example, -1) means flipping - * around both axes. - * SEE: transpose , repeat , completeSymm + * flipping around the x-axis and positive value (for example, 1) means + * flipping around y-axis. Negative value (for example, -1) means flipping + * around both axes. + * SEE: transpose , repeat , completeSymm */ public static void flip(Mat src, Mat dst, int flipCode) { flip_0(src.nativeObj, dst.nativeObj, flipCode); @@ -2367,14 +2388,13 @@ public static void flip(Mat src, Mat dst, int flipCode) { // - // C++: void cv::flip(Mat src, Mat& dst, int flipCode) + // C++: void cv::flipND(Mat src, Mat& dst, int axis) // /** * Flips a n-dimensional at given axis - * - * @param src input array - * @param dst output array that has the same shape of src + * @param src input array + * @param dst output array that has the same shape of src * @param axis axis that performs a flip on. 0 <= axis < src.dims. */ public static void flipND(Mat src, Mat dst, int axis) { @@ -2383,7 +2403,22 @@ public static void flipND(Mat src, Mat dst, int axis) { // - // C++: void cv::flipND(Mat src, Mat& dst, int axis) + // C++: void cv::broadcast(Mat src, Mat shape, Mat& dst) + // + + /** + * Broadcast the given Mat to the given shape. + * @param src input array + * @param shape target shape. Should be a list of CV_32S numbers. Note that negative values are not supported. + * @param dst output array that has the given shape + */ + public static void broadcast(Mat src, Mat shape, Mat dst) { + broadcast_0(src.nativeObj, shape.nativeObj, dst.nativeObj); + } + + + // + // C++: void cv::rotate(Mat src, Mat& dst, int rotateCode) // /** @@ -2392,12 +2427,11 @@ public static void flipND(Mat src, Mat dst, int axis) { * Rotate by 90 degrees clockwise (rotateCode = ROTATE_90_CLOCKWISE). * Rotate by 180 degrees clockwise (rotateCode = ROTATE_180). * Rotate by 270 degrees clockwise (rotateCode = ROTATE_90_COUNTERCLOCKWISE). - * - * @param src input array. - * @param dst output array of the same type as src. The size is the same with ROTATE_180, - * and the rows and cols are switched for ROTATE_90_CLOCKWISE and ROTATE_90_COUNTERCLOCKWISE. + * @param src input array. + * @param dst output array of the same type as src. The size is the same with ROTATE_180, + * and the rows and cols are switched for ROTATE_90_CLOCKWISE and ROTATE_90_COUNTERCLOCKWISE. * @param rotateCode an enum to specify how to rotate the array; see the enum #RotateFlags - * SEE: transpose , repeat , completeSymm, flip, RotateFlags + * SEE: transpose , repeat , completeSymm, flip, RotateFlags */ public static void rotate(Mat src, Mat dst, int rotateCode) { rotate_0(src.nativeObj, dst.nativeObj, rotateCode); @@ -2405,23 +2439,22 @@ public static void rotate(Mat src, Mat dst, int rotateCode) { // - // C++: void cv::rotate(Mat src, Mat& dst, int rotateCode) + // C++: void cv::repeat(Mat src, int ny, int nx, Mat& dst) // /** * Fills the output array with repeated copies of the input array. - *

      + * * The function cv::repeat duplicates the input array one or more times along each of the two axes: * \(\texttt{dst} _{ij}= \texttt{src} _{i\mod src.rows, \; j\mod src.cols }\) * The second variant of the function is more convenient to use with REF: MatrixExpressions. - * * @param src input array to replicate. - * @param ny Flag to specify how many times the {@code src} is repeated along the - * vertical axis. - * @param nx Flag to specify how many times the {@code src} is repeated along the - * horizontal axis. + * @param ny Flag to specify how many times the {@code src} is repeated along the + * vertical axis. + * @param nx Flag to specify how many times the {@code src} is repeated along the + * horizontal axis. * @param dst output array of the same type as {@code src}. - * SEE: cv::reduce + * SEE: cv::reduce */ public static void repeat(Mat src, int ny, int nx, Mat dst) { repeat_0(src.nativeObj, ny, nx, dst.nativeObj); @@ -2429,27 +2462,27 @@ public static void repeat(Mat src, int ny, int nx, Mat dst) { // - // C++: void cv::repeat(Mat src, int ny, int nx, Mat& dst) + // C++: void cv::hconcat(vector_Mat src, Mat& dst) // /** - * - * std::vector<cv::Mat> matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), - * cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), - * cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; - *

      - * cv::Mat out; - * cv::hconcat( matrices, out ); - * //out: - * //[1, 2, 3; - * // 1, 2, 3; - * // 1, 2, 3; - * // 1, 2, 3] - * * - * @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. - * @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. - * same depth. + * + * std::vector<cv::Mat> matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), + * cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), + * cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; + * + * cv::Mat out; + * cv::hconcat( matrices, out ); + * //out: + * //[1, 2, 3; + * // 1, 2, 3; + * // 1, 2, 3; + * // 1, 2, 3] + * + * @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. + * @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. + * same depth. */ public static void hconcat(List src, Mat dst) { Mat src_mat = Converters.vector_Mat_to_Mat(src); @@ -2458,26 +2491,26 @@ public static void hconcat(List src, Mat dst) { // - // C++: void cv::hconcat(vector_Mat src, Mat& dst) + // C++: void cv::vconcat(vector_Mat src, Mat& dst) // /** - * - * std::vector<cv::Mat> matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), - * cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), - * cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; - *

      - * cv::Mat out; - * cv::vconcat( matrices, out ); - * //out: - * //[1, 1, 1, 1; - * // 2, 2, 2, 2; - * // 3, 3, 3, 3] - * * - * @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth - * @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. - * same depth. + * + * std::vector<cv::Mat> matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), + * cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), + * cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; + * + * cv::Mat out; + * cv::vconcat( matrices, out ); + * //out: + * //[1, 1, 1, 1; + * // 2, 2, 2, 2; + * // 3, 3, 3, 3] + * + * @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth + * @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. + * same depth. */ public static void vconcat(List src, Mat dst) { Mat src_mat = Converters.vector_Mat_to_Mat(src); @@ -2486,273 +2519,267 @@ public static void vconcat(List src, Mat dst) { // - // C++: void cv::vconcat(vector_Mat src, Mat& dst) + // C++: void cv::bitwise_and(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) // /** * computes bitwise conjunction of the two arrays (dst = src1 & src2) * Calculates the per-element bit-wise conjunction of two arrays or an * array and a scalar. - *

      + * * The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for: * Two arrays when src1 and src2 have the same size: - * \(\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * \(\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * An array and a scalar when src2 is constructed from Scalar or has - * the same number of elements as {@code src1.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src1.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\) * A scalar and an array when src1 is constructed from Scalar or has - * the same number of elements as {@code src2.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src2.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * In case of floating-point arrays, their machine-specific bit * representations (usually IEEE754-compliant) are used for the operation. * In case of multi-channel arrays, each channel is processed * independently. In the second and third cases above, the scalar is first * converted to the array type. - * * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array that has the same size and type as the input - * arrays. + * @param dst output array that has the same size and type as the input + * arrays. * @param mask optional operation mask, 8-bit single channel array, that - * specifies elements of the output array to be changed. + * specifies elements of the output array to be changed. */ public static void bitwise_and(Mat src1, Mat src2, Mat dst, Mat mask) { bitwise_and_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj); } - - // - // C++: void cv::bitwise_and(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) - // - /** * computes bitwise conjunction of the two arrays (dst = src1 & src2) * Calculates the per-element bit-wise conjunction of two arrays or an * array and a scalar. - *

      + * * The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for: * Two arrays when src1 and src2 have the same size: - * \(\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * \(\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * An array and a scalar when src2 is constructed from Scalar or has - * the same number of elements as {@code src1.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src1.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\) * A scalar and an array when src1 is constructed from Scalar or has - * the same number of elements as {@code src2.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src2.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * In case of floating-point arrays, their machine-specific bit * representations (usually IEEE754-compliant) are used for the operation. * In case of multi-channel arrays, each channel is processed * independently. In the second and third cases above, the scalar is first * converted to the array type. - * * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array that has the same size and type as the input - * arrays. - * specifies elements of the output array to be changed. + * @param dst output array that has the same size and type as the input + * arrays. + * specifies elements of the output array to be changed. */ public static void bitwise_and(Mat src1, Mat src2, Mat dst) { bitwise_and_1(src1.nativeObj, src2.nativeObj, dst.nativeObj); } + + // + // C++: void cv::bitwise_or(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) + // + /** * Calculates the per-element bit-wise disjunction of two arrays or an * array and a scalar. - *

      + * * The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for: * Two arrays when src1 and src2 have the same size: - * \(\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * \(\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * An array and a scalar when src2 is constructed from Scalar or has - * the same number of elements as {@code src1.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src1.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\) * A scalar and an array when src1 is constructed from Scalar or has - * the same number of elements as {@code src2.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src2.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * In case of floating-point arrays, their machine-specific bit * representations (usually IEEE754-compliant) are used for the operation. * In case of multi-channel arrays, each channel is processed * independently. In the second and third cases above, the scalar is first * converted to the array type. - * * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array that has the same size and type as the input - * arrays. + * @param dst output array that has the same size and type as the input + * arrays. * @param mask optional operation mask, 8-bit single channel array, that - * specifies elements of the output array to be changed. + * specifies elements of the output array to be changed. */ public static void bitwise_or(Mat src1, Mat src2, Mat dst, Mat mask) { bitwise_or_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj); } - - // - // C++: void cv::bitwise_or(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) - // - /** * Calculates the per-element bit-wise disjunction of two arrays or an * array and a scalar. - *

      + * * The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for: * Two arrays when src1 and src2 have the same size: - * \(\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * \(\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * An array and a scalar when src2 is constructed from Scalar or has - * the same number of elements as {@code src1.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src1.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\) * A scalar and an array when src1 is constructed from Scalar or has - * the same number of elements as {@code src2.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src2.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * In case of floating-point arrays, their machine-specific bit * representations (usually IEEE754-compliant) are used for the operation. * In case of multi-channel arrays, each channel is processed * independently. In the second and third cases above, the scalar is first * converted to the array type. - * * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array that has the same size and type as the input - * arrays. - * specifies elements of the output array to be changed. + * @param dst output array that has the same size and type as the input + * arrays. + * specifies elements of the output array to be changed. */ public static void bitwise_or(Mat src1, Mat src2, Mat dst) { bitwise_or_1(src1.nativeObj, src2.nativeObj, dst.nativeObj); } + + // + // C++: void cv::bitwise_xor(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) + // + /** * Calculates the per-element bit-wise "exclusive or" operation on two * arrays or an array and a scalar. - *

      + * * The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or" * operation for: * Two arrays when src1 and src2 have the same size: - * \(\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * \(\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * An array and a scalar when src2 is constructed from Scalar or has - * the same number of elements as {@code src1.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src1.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\) * A scalar and an array when src1 is constructed from Scalar or has - * the same number of elements as {@code src2.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src2.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * In case of floating-point arrays, their machine-specific bit * representations (usually IEEE754-compliant) are used for the operation. * In case of multi-channel arrays, each channel is processed * independently. In the 2nd and 3rd cases above, the scalar is first * converted to the array type. - * * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array that has the same size and type as the input - * arrays. + * @param dst output array that has the same size and type as the input + * arrays. * @param mask optional operation mask, 8-bit single channel array, that - * specifies elements of the output array to be changed. + * specifies elements of the output array to be changed. */ public static void bitwise_xor(Mat src1, Mat src2, Mat dst, Mat mask) { bitwise_xor_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj); } - - // - // C++: void cv::bitwise_xor(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) - // - /** * Calculates the per-element bit-wise "exclusive or" operation on two * arrays or an array and a scalar. - *

      + * * The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or" * operation for: * Two arrays when src1 and src2 have the same size: - * \(\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * \(\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * An array and a scalar when src2 is constructed from Scalar or has - * the same number of elements as {@code src1.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src1.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\) * A scalar and an array when src1 is constructed from Scalar or has - * the same number of elements as {@code src2.channels()}: - * \(\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) + * the same number of elements as {@code src2.channels()}: + * \(\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\) * In case of floating-point arrays, their machine-specific bit * representations (usually IEEE754-compliant) are used for the operation. * In case of multi-channel arrays, each channel is processed * independently. In the 2nd and 3rd cases above, the scalar is first * converted to the array type. - * * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array that has the same size and type as the input - * arrays. - * specifies elements of the output array to be changed. + * @param dst output array that has the same size and type as the input + * arrays. + * specifies elements of the output array to be changed. */ public static void bitwise_xor(Mat src1, Mat src2, Mat dst) { bitwise_xor_1(src1.nativeObj, src2.nativeObj, dst.nativeObj); } + + // + // C++: void cv::bitwise_not(Mat src, Mat& dst, Mat mask = Mat()) + // + /** - * Inverts every bit of an array. - *

      + * Inverts every bit of an array. + * * The function cv::bitwise_not calculates per-element bit-wise inversion of the input * array: * \(\texttt{dst} (I) = \neg \texttt{src} (I)\) * In case of a floating-point input array, its machine-specific bit * representation (usually IEEE754-compliant) is used for the operation. In * case of multi-channel arrays, each channel is processed independently. - * - * @param src input array. - * @param dst output array that has the same size and type as the input - * array. + * @param src input array. + * @param dst output array that has the same size and type as the input + * array. * @param mask optional operation mask, 8-bit single channel array, that - * specifies elements of the output array to be changed. + * specifies elements of the output array to be changed. */ public static void bitwise_not(Mat src, Mat dst, Mat mask) { bitwise_not_0(src.nativeObj, dst.nativeObj, mask.nativeObj); } - - // - // C++: void cv::bitwise_not(Mat src, Mat& dst, Mat mask = Mat()) - // - /** - * Inverts every bit of an array. - *

      + * Inverts every bit of an array. + * * The function cv::bitwise_not calculates per-element bit-wise inversion of the input * array: * \(\texttt{dst} (I) = \neg \texttt{src} (I)\) * In case of a floating-point input array, its machine-specific bit * representation (usually IEEE754-compliant) is used for the operation. In * case of multi-channel arrays, each channel is processed independently. - * * @param src input array. * @param dst output array that has the same size and type as the input - * array. - * specifies elements of the output array to be changed. + * array. + * specifies elements of the output array to be changed. */ public static void bitwise_not(Mat src, Mat dst) { bitwise_not_1(src.nativeObj, dst.nativeObj); } + + // + // C++: void cv::absdiff(Mat src1, Mat src2, Mat& dst) + // + /** * Calculates the per-element absolute difference between two arrays or between an array and a scalar. - *

      + * * The function cv::absdiff calculates: * Absolute difference between two arrays when they have the same - * size and type: - * \(\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\) + * size and type: + * \(\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\) * Absolute difference between an array and a scalar when the second - * array is constructed from Scalar or has as many elements as the - * number of channels in {@code src1}: - * \(\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\) + * array is constructed from Scalar or has as many elements as the + * number of channels in {@code src1}: + * \(\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\) * Absolute difference between a scalar and an array when the first - * array is constructed from Scalar or has as many elements as the - * number of channels in {@code src2}: - * \(\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\) - * where I is a multi-dimensional index of array elements. In case of - * multi-channel arrays, each channel is processed independently. + * array is constructed from Scalar or has as many elements as the + * number of channels in {@code src2}: + * \(\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\) + * where I is a multi-dimensional index of array elements. In case of + * multi-channel arrays, each channel is processed independently. * Note: Saturation is not applied when the arrays have the depth CV_32S. * You may even get a negative value in the case of overflow. - * + * Note: (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. + * {@code absdiff(src,X)} means {@code absdiff(src,(X,X,X,X))}. + * {@code absdiff(src,(X,))} means {@code absdiff(src,(X,0,0,0))}. * @param src1 first input array or a scalar. * @param src2 second input array or a scalar. - * @param dst output array that has the same size and type as input arrays. - * SEE: cv::abs(const Mat&) + * @param dst output array that has the same size and type as input arrays. + * SEE: cv::abs(const Mat&) */ public static void absdiff(Mat src1, Mat src2, Mat dst) { absdiff_0(src1.nativeObj, src2.nativeObj, dst.nativeObj); @@ -2760,19 +2787,18 @@ public static void absdiff(Mat src1, Mat src2, Mat dst) { // - // C++: void cv::absdiff(Mat src1, Mat src2, Mat& dst) + // C++: void cv::copyTo(Mat src, Mat& dst, Mat mask) // /** - * This is an overloaded member function, provided for convenience (python) + * This is an overloaded member function, provided for convenience (python) * Copies the matrix to another one. * When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data. - * - * @param src source matrix. - * @param dst Destination matrix. If it does not have a proper size or type before the operation, it is - * reallocated. + * @param src source matrix. + * @param dst Destination matrix. If it does not have a proper size or type before the operation, it is + * reallocated. * @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix - * elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. + * elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. */ public static void copyTo(Mat src, Mat dst, Mat mask) { copyTo_0(src.nativeObj, dst.nativeObj, mask.nativeObj); @@ -2780,12 +2806,12 @@ public static void copyTo(Mat src, Mat dst, Mat mask) { // - // C++: void cv::copyTo(Mat src, Mat& dst, Mat mask) + // C++: void cv::inRange(Mat src, Scalar lowerb, Scalar upperb, Mat& dst) // /** - * Checks if array elements lie between the elements of two other arrays. - *

      + * Checks if array elements lie between the elements of two other arrays. + * * The function checks the range as follows: *

        *
      • @@ -2800,17 +2826,16 @@ public static void copyTo(Mat src, Mat dst, Mat mask) { * and so forth. *
      • *
      - *

      + * * That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the * specified 1D, 2D, 3D, ... box and 0 otherwise. - *

      + * * When the lower and/or upper boundary parameters are scalars, the indexes * (I) at lowerb and upperb in the above formulas should be omitted. - * - * @param src first input array. + * @param src first input array. * @param lowerb inclusive lower boundary array or a scalar. * @param upperb inclusive upper boundary array or a scalar. - * @param dst output array of the same size as src and CV_8U type. + * @param dst output array of the same size as src and CV_8U type. */ public static void inRange(Mat src, Scalar lowerb, Scalar upperb, Mat dst) { inRange_0(src.nativeObj, lowerb.val[0], lowerb.val[1], lowerb.val[2], lowerb.val[3], upperb.val[0], upperb.val[1], upperb.val[2], upperb.val[3], dst.nativeObj); @@ -2818,36 +2843,35 @@ public static void inRange(Mat src, Scalar lowerb, Scalar upperb, Mat dst) { // - // C++: void cv::inRange(Mat src, Scalar lowerb, Scalar upperb, Mat& dst) + // C++: void cv::compare(Mat src1, Mat src2, Mat& dst, int cmpop) // /** * Performs the per-element comparison of two arrays or an array and scalar value. - *

      + * * The function compares: * Elements of two arrays when src1 and src2 have the same size: - * \(\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\) + * \(\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\) * Elements of src1 with a scalar src2 when src2 is constructed from - * Scalar or has a single element: - * \(\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\) + * Scalar or has a single element: + * \(\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\) * src1 with elements of src2 when src1 is constructed from Scalar or - * has a single element: - * \(\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\) + * has a single element: + * \(\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\) * When the comparison result is true, the corresponding element of output * array is set to 255. The comparison operations can be replaced with the * equivalent matrix expressions: * - * Mat dst1 = src1 >= src2; - * Mat dst2 = src1 < 8; - * ... + * Mat dst1 = src1 >= src2; + * Mat dst2 = src1 < 8; + * ... * - * - * @param src1 first input array or a scalar; when it is an array, it must have a single channel. - * @param src2 second input array or a scalar; when it is an array, it must have a single channel. - * @param dst output array of type ref CV_8U that has the same size and the same number of channels as - * the input arrays. + * @param src1 first input array or a scalar; when it is an array, it must have a single channel. + * @param src2 second input array or a scalar; when it is an array, it must have a single channel. + * @param dst output array of type ref CV_8U that has the same size and the same number of channels as + * the input arrays. * @param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes) - * SEE: checkRange, min, max, threshold + * SEE: checkRange, min, max, threshold */ public static void compare(Mat src1, Mat src2, Mat dst, int cmpop) { compare_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, cmpop); @@ -2855,21 +2879,20 @@ public static void compare(Mat src1, Mat src2, Mat dst, int cmpop) { // - // C++: void cv::compare(Mat src1, Mat src2, Mat& dst, int cmpop) + // C++: void cv::min(Mat src1, Mat src2, Mat& dst) // /** * Calculates per-element minimum of two arrays or an array and a scalar. - *

      + * * The function cv::min calculates the per-element minimum of two arrays: * \(\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\) * or array and a scalar: * \(\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\) - * * @param src1 first input array. * @param src2 second input array of the same size and type as src1. - * @param dst output array of the same size and type as src1. - * SEE: max, compare, inRange, minMaxLoc + * @param dst output array of the same size and type as src1. + * SEE: max, compare, inRange, minMaxLoc */ public static void min(Mat src1, Mat src2, Mat dst) { min_0(src1.nativeObj, src2.nativeObj, dst.nativeObj); @@ -2877,21 +2900,20 @@ public static void min(Mat src1, Mat src2, Mat dst) { // - // C++: void cv::min(Mat src1, Mat src2, Mat& dst) + // C++: void cv::max(Mat src1, Mat src2, Mat& dst) // /** * Calculates per-element maximum of two arrays or an array and a scalar. - *

      + * * The function cv::max calculates the per-element maximum of two arrays: * \(\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\) * or array and a scalar: * \(\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\) - * * @param src1 first input array. * @param src2 second input array of the same size and type as src1 . - * @param dst output array of the same size and type as src1. - * SEE: min, compare, inRange, minMaxLoc, REF: MatrixExpressions + * @param dst output array of the same size and type as src1. + * SEE: min, compare, inRange, minMaxLoc, REF: MatrixExpressions */ public static void max(Mat src1, Mat src2, Mat dst) { max_0(src1.nativeObj, src2.nativeObj, dst.nativeObj); @@ -2899,17 +2921,16 @@ public static void max(Mat src1, Mat src2, Mat dst) { // - // C++: void cv::max(Mat src1, Mat src2, Mat& dst) + // C++: void cv::sqrt(Mat src, Mat& dst) // /** * Calculates a square root of array elements. - *

      + * * The function cv::sqrt calculates a square root of each input array element. * In case of multi-channel arrays, each channel is processed * independently. The accuracy is approximately the same as of the built-in * std::sqrt . - * * @param src input floating-point array. * @param dst output array of the same size and type as src. */ @@ -2919,33 +2940,32 @@ public static void sqrt(Mat src, Mat dst) { // - // C++: void cv::sqrt(Mat src, Mat& dst) + // C++: void cv::pow(Mat src, double power, Mat& dst) // /** * Raises every array element to a power. - *

      + * * The function cv::pow raises every element of the input array to power : * \(\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\) - *

      + * * So, for a non-integer power exponent, the absolute values of input array * elements are used. However, it is possible to get true values for * negative values using some extra operations. In the example below, * computing the 5th root of array src shows: * - * Mat mask = src < 0; - * pow(src, 1./5, dst); - * subtract(Scalar::all(0), dst, dst, mask); + * Mat mask = src < 0; + * pow(src, 1./5, dst); + * subtract(Scalar::all(0), dst, dst, mask); * * For some values of power, such as integer values, 0.5 and -0.5, * specialized faster algorithms are used. - *

      - * Special values (NaN, Inf) are not handled. * - * @param src input array. + * Special values (NaN, Inf) are not handled. + * @param src input array. * @param power exponent of power. - * @param dst output array of the same size and type as src. - * SEE: sqrt, exp, log, cartToPolar, polarToCart + * @param dst output array of the same size and type as src. + * SEE: sqrt, exp, log, cartToPolar, polarToCart */ public static void pow(Mat src, double power, Mat dst) { pow_0(src.nativeObj, power, dst.nativeObj); @@ -2953,24 +2973,23 @@ public static void pow(Mat src, double power, Mat dst) { // - // C++: void cv::pow(Mat src, double power, Mat& dst) + // C++: void cv::exp(Mat src, Mat& dst) // /** * Calculates the exponent of every array element. - *

      + * * The function cv::exp calculates the exponent of every element of the input * array: * \(\texttt{dst} [I] = e^{ src(I) }\) - *

      + * * The maximum relative error is about 7e-6 for single-precision input and * less than 1e-10 for double-precision input. Currently, the function * converts denormalized values to zeros on output. Special values (NaN, * Inf) are not handled. - * * @param src input array. * @param dst output array of the same size and type as src. - * SEE: log , cartToPolar , polarToCart , phase , pow , sqrt , magnitude + * SEE: log , cartToPolar , polarToCart , phase , pow , sqrt , magnitude */ public static void exp(Mat src, Mat dst) { exp_0(src.nativeObj, dst.nativeObj); @@ -2978,20 +2997,20 @@ public static void exp(Mat src, Mat dst) { // - // C++: void cv::exp(Mat src, Mat& dst) + // C++: void cv::log(Mat src, Mat& dst) // /** * Calculates the natural logarithm of every array element. - *

      + * * The function cv::log calculates the natural logarithm of every element of the input array: * \(\texttt{dst} (I) = \log (\texttt{src}(I)) \) - *

      + * * Output on zero, negative and special (NaN, Inf) values is undefined. * * @param src input array. * @param dst output array of the same size and type as src . - * SEE: exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude + * SEE: exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude */ public static void log(Mat src, Mat dst) { log_0(src.nativeObj, dst.nativeObj); @@ -2999,177 +3018,170 @@ public static void log(Mat src, Mat dst) { // - // C++: void cv::log(Mat src, Mat& dst) + // C++: void cv::polarToCart(Mat magnitude, Mat angle, Mat& x, Mat& y, bool angleInDegrees = false) // /** * Calculates x and y coordinates of 2D vectors from their magnitude and angle. - *

      + * * The function cv::polarToCart calculates the Cartesian coordinates of each 2D * vector represented by the corresponding elements of magnitude and angle: * \(\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\) - *

      - * The relative accuracy of the estimated coordinates is about 1e-6. * - * @param magnitude input floating-point array of magnitudes of 2D vectors; - * it can be an empty matrix (=Mat()), in this case, the function assumes - * that all the magnitudes are =1; if it is not empty, it must have the - * same size and type as angle. - * @param angle input floating-point array of angles of 2D vectors. - * @param x output array of x-coordinates of 2D vectors; it has the same - * size and type as angle. - * @param y output array of y-coordinates of 2D vectors; it has the same - * size and type as angle. + * The relative accuracy of the estimated coordinates is about 1e-6. + * @param magnitude input floating-point array of magnitudes of 2D vectors; + * it can be an empty matrix (=Mat()), in this case, the function assumes + * that all the magnitudes are =1; if it is not empty, it must have the + * same size and type as angle. + * @param angle input floating-point array of angles of 2D vectors. + * @param x output array of x-coordinates of 2D vectors; it has the same + * size and type as angle. + * @param y output array of y-coordinates of 2D vectors; it has the same + * size and type as angle. * @param angleInDegrees when true, the input angles are measured in - * degrees, otherwise, they are measured in radians. - * SEE: cartToPolar, magnitude, phase, exp, log, pow, sqrt + * degrees, otherwise, they are measured in radians. + * SEE: cartToPolar, magnitude, phase, exp, log, pow, sqrt */ public static void polarToCart(Mat magnitude, Mat angle, Mat x, Mat y, boolean angleInDegrees) { polarToCart_0(magnitude.nativeObj, angle.nativeObj, x.nativeObj, y.nativeObj, angleInDegrees); } - - // - // C++: void cv::polarToCart(Mat magnitude, Mat angle, Mat& x, Mat& y, bool angleInDegrees = false) - // - /** * Calculates x and y coordinates of 2D vectors from their magnitude and angle. - *

      + * * The function cv::polarToCart calculates the Cartesian coordinates of each 2D * vector represented by the corresponding elements of magnitude and angle: * \(\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\) - *

      - * The relative accuracy of the estimated coordinates is about 1e-6. * + * The relative accuracy of the estimated coordinates is about 1e-6. * @param magnitude input floating-point array of magnitudes of 2D vectors; - * it can be an empty matrix (=Mat()), in this case, the function assumes - * that all the magnitudes are =1; if it is not empty, it must have the - * same size and type as angle. - * @param angle input floating-point array of angles of 2D vectors. - * @param x output array of x-coordinates of 2D vectors; it has the same - * size and type as angle. - * @param y output array of y-coordinates of 2D vectors; it has the same - * size and type as angle. - * degrees, otherwise, they are measured in radians. - * SEE: cartToPolar, magnitude, phase, exp, log, pow, sqrt + * it can be an empty matrix (=Mat()), in this case, the function assumes + * that all the magnitudes are =1; if it is not empty, it must have the + * same size and type as angle. + * @param angle input floating-point array of angles of 2D vectors. + * @param x output array of x-coordinates of 2D vectors; it has the same + * size and type as angle. + * @param y output array of y-coordinates of 2D vectors; it has the same + * size and type as angle. + * degrees, otherwise, they are measured in radians. + * SEE: cartToPolar, magnitude, phase, exp, log, pow, sqrt */ public static void polarToCart(Mat magnitude, Mat angle, Mat x, Mat y) { polarToCart_1(magnitude.nativeObj, angle.nativeObj, x.nativeObj, y.nativeObj); } + + // + // C++: void cv::cartToPolar(Mat x, Mat y, Mat& magnitude, Mat& angle, bool angleInDegrees = false) + // + /** * Calculates the magnitude and angle of 2D vectors. - *

      + * * The function cv::cartToPolar calculates either the magnitude, angle, or both * for every 2D vector (x(I),y(I)): * \(\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\) - *

      + * * The angles are calculated with accuracy about 0.3 degrees. For the point * (0,0), the angle is set to 0. - * - * @param x array of x-coordinates; this must be a single-precision or - * double-precision floating-point array. - * @param y array of y-coordinates, that must have the same size and same type as x. - * @param magnitude output array of magnitudes of the same size and type as x. - * @param angle output array of angles that has the same size and type as - * x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). + * @param x array of x-coordinates; this must be a single-precision or + * double-precision floating-point array. + * @param y array of y-coordinates, that must have the same size and same type as x. + * @param magnitude output array of magnitudes of the same size and type as x. + * @param angle output array of angles that has the same size and type as + * x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). * @param angleInDegrees a flag, indicating whether the angles are measured - * in radians (which is by default), or in degrees. - * SEE: Sobel, Scharr + * in radians (which is by default), or in degrees. + * SEE: Sobel, Scharr */ public static void cartToPolar(Mat x, Mat y, Mat magnitude, Mat angle, boolean angleInDegrees) { cartToPolar_0(x.nativeObj, y.nativeObj, magnitude.nativeObj, angle.nativeObj, angleInDegrees); } - - // - // C++: void cv::cartToPolar(Mat x, Mat y, Mat& magnitude, Mat& angle, bool angleInDegrees = false) - // - /** * Calculates the magnitude and angle of 2D vectors. - *

      + * * The function cv::cartToPolar calculates either the magnitude, angle, or both * for every 2D vector (x(I),y(I)): * \(\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\) - *

      + * * The angles are calculated with accuracy about 0.3 degrees. For the point * (0,0), the angle is set to 0. - * - * @param x array of x-coordinates; this must be a single-precision or - * double-precision floating-point array. - * @param y array of y-coordinates, that must have the same size and same type as x. + * @param x array of x-coordinates; this must be a single-precision or + * double-precision floating-point array. + * @param y array of y-coordinates, that must have the same size and same type as x. * @param magnitude output array of magnitudes of the same size and type as x. - * @param angle output array of angles that has the same size and type as - * x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). - * in radians (which is by default), or in degrees. - * SEE: Sobel, Scharr + * @param angle output array of angles that has the same size and type as + * x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). + * in radians (which is by default), or in degrees. + * SEE: Sobel, Scharr */ public static void cartToPolar(Mat x, Mat y, Mat magnitude, Mat angle) { cartToPolar_1(x.nativeObj, y.nativeObj, magnitude.nativeObj, angle.nativeObj); } + + // + // C++: void cv::phase(Mat x, Mat y, Mat& angle, bool angleInDegrees = false) + // + /** * Calculates the rotation angle of 2D vectors. - *

      + * * The function cv::phase calculates the rotation angle of each 2D vector that * is formed from the corresponding elements of x and y : * \(\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\) - *

      + * * The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , * the corresponding angle(I) is set to 0. - * - * @param x input floating-point array of x-coordinates of 2D vectors. - * @param y input array of y-coordinates of 2D vectors; it must have the - * same size and the same type as x. - * @param angle output array of vector angles; it has the same size and - * same type as x . + * @param x input floating-point array of x-coordinates of 2D vectors. + * @param y input array of y-coordinates of 2D vectors; it must have the + * same size and the same type as x. + * @param angle output array of vector angles; it has the same size and + * same type as x . * @param angleInDegrees when true, the function calculates the angle in - * degrees, otherwise, they are measured in radians. + * degrees, otherwise, they are measured in radians. */ public static void phase(Mat x, Mat y, Mat angle, boolean angleInDegrees) { phase_0(x.nativeObj, y.nativeObj, angle.nativeObj, angleInDegrees); } - - // - // C++: void cv::phase(Mat x, Mat y, Mat& angle, bool angleInDegrees = false) - // - /** * Calculates the rotation angle of 2D vectors. - *

      + * * The function cv::phase calculates the rotation angle of each 2D vector that * is formed from the corresponding elements of x and y : * \(\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\) - *

      + * * The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , * the corresponding angle(I) is set to 0. - * - * @param x input floating-point array of x-coordinates of 2D vectors. - * @param y input array of y-coordinates of 2D vectors; it must have the - * same size and the same type as x. + * @param x input floating-point array of x-coordinates of 2D vectors. + * @param y input array of y-coordinates of 2D vectors; it must have the + * same size and the same type as x. * @param angle output array of vector angles; it has the same size and - * same type as x . - * degrees, otherwise, they are measured in radians. + * same type as x . + * degrees, otherwise, they are measured in radians. */ public static void phase(Mat x, Mat y, Mat angle) { phase_1(x.nativeObj, y.nativeObj, angle.nativeObj); } + + // + // C++: void cv::magnitude(Mat x, Mat y, Mat& magnitude) + // + /** * Calculates the magnitude of 2D vectors. - *

      + * * The function cv::magnitude calculates the magnitude of 2D vectors formed * from the corresponding elements of x and y arrays: * \(\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\) - * - * @param x floating-point array of x-coordinates of the vectors. - * @param y floating-point array of y-coordinates of the vectors; it must - * have the same size as x. + * @param x floating-point array of x-coordinates of the vectors. + * @param y floating-point array of y-coordinates of the vectors; it must + * have the same size as x. * @param magnitude output array of the same size and type as x. - * SEE: cartToPolar, polarToCart, phase, sqrt + * SEE: cartToPolar, polarToCart, phase, sqrt */ public static void magnitude(Mat x, Mat y, Mat magnitude) { magnitude_0(x.nativeObj, y.nativeObj, magnitude.nativeObj); @@ -3177,12 +3189,12 @@ public static void magnitude(Mat x, Mat y, Mat magnitude) { // - // C++: void cv::magnitude(Mat x, Mat y, Mat& magnitude) + // C++: bool cv::checkRange(Mat a, bool quiet = true, _hidden_ * pos = 0, double minVal = -DBL_MAX, double maxVal = DBL_MAX) // /** * Checks every element of an input array for invalid values. - *

      + * * The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal > *

        *
      • @@ -3192,11 +3204,10 @@ public static void magnitude(Mat x, Mat y, Mat magnitude) { * function either returns false (when quiet=true) or throws an exception. *
      • *
      - * - * @param a input array. - * @param quiet a flag, indicating whether the functions quietly return false when the array elements - * are out of range or they throw an exception. - * elements. + * @param a input array. + * @param quiet a flag, indicating whether the functions quietly return false when the array elements + * are out of range or they throw an exception. + * elements. * @param minVal inclusive lower boundary of valid values range. * @param maxVal exclusive upper boundary of valid values range. * @return automatically generated @@ -3205,14 +3216,9 @@ public static boolean checkRange(Mat a, boolean quiet, double minVal, double max return checkRange_0(a.nativeObj, quiet, minVal, maxVal); } - - // - // C++: bool cv::checkRange(Mat a, bool quiet = true, _hidden_ * pos = 0, double minVal = -DBL_MAX, double maxVal = DBL_MAX) - // - /** * Checks every element of an input array for invalid values. - *

      + * * The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal > *

        *
      • @@ -3222,11 +3228,10 @@ public static boolean checkRange(Mat a, boolean quiet, double minVal, double max * function either returns false (when quiet=true) or throws an exception. *
      • *
      - * - * @param a input array. - * @param quiet a flag, indicating whether the functions quietly return false when the array elements - * are out of range or they throw an exception. - * elements. + * @param a input array. + * @param quiet a flag, indicating whether the functions quietly return false when the array elements + * are out of range or they throw an exception. + * elements. * @param minVal inclusive lower boundary of valid values range. * @return automatically generated */ @@ -3236,7 +3241,7 @@ public static boolean checkRange(Mat a, boolean quiet, double minVal) { /** * Checks every element of an input array for invalid values. - *

      + * * The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal > *

        *
      • @@ -3246,11 +3251,10 @@ public static boolean checkRange(Mat a, boolean quiet, double minVal) { * function either returns false (when quiet=true) or throws an exception. *
      • *
      - * - * @param a input array. + * @param a input array. * @param quiet a flag, indicating whether the functions quietly return false when the array elements - * are out of range or they throw an exception. - * elements. + * are out of range or they throw an exception. + * elements. * @return automatically generated */ public static boolean checkRange(Mat a, boolean quiet) { @@ -3259,7 +3263,7 @@ public static boolean checkRange(Mat a, boolean quiet) { /** * Checks every element of an input array for invalid values. - *

      + * * The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal > *

        *
      • @@ -3269,115 +3273,115 @@ public static boolean checkRange(Mat a, boolean quiet) { * function either returns false (when quiet=true) or throws an exception. *
      • *
      - * * @param a input array. - * are out of range or they throw an exception. - * elements. + * are out of range or they throw an exception. + * elements. * @return automatically generated */ public static boolean checkRange(Mat a) { return checkRange_4(a.nativeObj); } + + // + // C++: void cv::patchNaNs(Mat& a, double val = 0) + // + /** - * converts NaNs to the given number - * - * @param a input/output matrix (CV_32F type). + * Replaces NaNs by given number + * @param a input/output matrix (CV_32F type). * @param val value to convert the NaNs */ public static void patchNaNs(Mat a, double val) { patchNaNs_0(a.nativeObj, val); } - - // - // C++: void cv::patchNaNs(Mat& a, double val = 0) - // - /** - * converts NaNs to the given number - * + * Replaces NaNs by given number * @param a input/output matrix (CV_32F type). */ public static void patchNaNs(Mat a) { patchNaNs_1(a.nativeObj); } + + // + // C++: void cv::gemm(Mat src1, Mat src2, double alpha, Mat src3, double beta, Mat& dst, int flags = 0) + // + /** * Performs generalized matrix multiplication. - *

      + * * The function cv::gemm performs generalized matrix multiplication similar to the * gemm functions in BLAS level 3. For example, * {@code gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)} * corresponds to * \(\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\) - *

      + * * In case of complex (two-channel) data, performed a complex matrix * multiplication. - *

      + * * The function can be replaced with a matrix expression. For example, the * above call can be replaced with: * - * dst = alpha*src1.t()*src2 + beta*src3.t(); + * dst = alpha*src1.t()*src2 + beta*src3.t(); * - * - * @param src1 first multiplied input matrix that could be real(CV_32FC1, - * CV_64FC1) or complex(CV_32FC2, CV_64FC2). - * @param src2 second multiplied input matrix of the same type as src1. + * @param src1 first multiplied input matrix that could be real(CV_32FC1, + * CV_64FC1) or complex(CV_32FC2, CV_64FC2). + * @param src2 second multiplied input matrix of the same type as src1. * @param alpha weight of the matrix product. - * @param src3 third optional delta matrix added to the matrix product; it - * should have the same type as src1 and src2. - * @param beta weight of src3. - * @param dst output matrix; it has the proper size and the same type as - * input matrices. + * @param src3 third optional delta matrix added to the matrix product; it + * should have the same type as src1 and src2. + * @param beta weight of src3. + * @param dst output matrix; it has the proper size and the same type as + * input matrices. * @param flags operation flags (cv::GemmFlags) - * SEE: mulTransposed , transform + * SEE: mulTransposed , transform */ public static void gemm(Mat src1, Mat src2, double alpha, Mat src3, double beta, Mat dst, int flags) { gemm_0(src1.nativeObj, src2.nativeObj, alpha, src3.nativeObj, beta, dst.nativeObj, flags); } - - // - // C++: void cv::gemm(Mat src1, Mat src2, double alpha, Mat src3, double beta, Mat& dst, int flags = 0) - // - /** * Performs generalized matrix multiplication. - *

      + * * The function cv::gemm performs generalized matrix multiplication similar to the * gemm functions in BLAS level 3. For example, * {@code gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)} * corresponds to * \(\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\) - *

      + * * In case of complex (two-channel) data, performed a complex matrix * multiplication. - *

      + * * The function can be replaced with a matrix expression. For example, the * above call can be replaced with: * - * dst = alpha*src1.t()*src2 + beta*src3.t(); + * dst = alpha*src1.t()*src2 + beta*src3.t(); * - * - * @param src1 first multiplied input matrix that could be real(CV_32FC1, - * CV_64FC1) or complex(CV_32FC2, CV_64FC2). - * @param src2 second multiplied input matrix of the same type as src1. + * @param src1 first multiplied input matrix that could be real(CV_32FC1, + * CV_64FC1) or complex(CV_32FC2, CV_64FC2). + * @param src2 second multiplied input matrix of the same type as src1. * @param alpha weight of the matrix product. - * @param src3 third optional delta matrix added to the matrix product; it - * should have the same type as src1 and src2. - * @param beta weight of src3. - * @param dst output matrix; it has the proper size and the same type as - * input matrices. - * SEE: mulTransposed , transform + * @param src3 third optional delta matrix added to the matrix product; it + * should have the same type as src1 and src2. + * @param beta weight of src3. + * @param dst output matrix; it has the proper size and the same type as + * input matrices. + * SEE: mulTransposed , transform */ public static void gemm(Mat src1, Mat src2, double alpha, Mat src3, double beta, Mat dst) { gemm_1(src1.nativeObj, src2.nativeObj, alpha, src3.nativeObj, beta, dst.nativeObj); } + + // + // C++: void cv::mulTransposed(Mat src, Mat& dst, bool aTa, Mat delta = Mat(), double scale = 1, int dtype = -1) + // + /** * Calculates the product of a matrix and its transposition. - *

      + * * The function cv::mulTransposed calculates the product of src and its * transposition: * \(\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\) @@ -3386,37 +3390,31 @@ public static void gemm(Mat src1, Mat src2, double alpha, Mat src3, double beta, * otherwise. The function is used to calculate the covariance matrix. With * zero delta, it can be used as a faster substitute for general matrix * product A\*B when B=A' - * - * @param src input single-channel matrix. Note that unlike gemm, the - * function can multiply not only floating-point matrices. - * @param dst output square matrix. - * @param aTa Flag specifying the multiplication ordering. See the - * description below. + * @param src input single-channel matrix. Note that unlike gemm, the + * function can multiply not only floating-point matrices. + * @param dst output square matrix. + * @param aTa Flag specifying the multiplication ordering. See the + * description below. * @param delta Optional delta matrix subtracted from src before the - * multiplication. When the matrix is empty ( delta=noArray() ), it is - * assumed to be zero, that is, nothing is subtracted. If it has the same - * size as src , it is simply subtracted. Otherwise, it is "repeated" (see - * repeat ) to cover the full src and then subtracted. Type of the delta - * matrix, when it is not empty, must be the same as the type of created - * output matrix. See the dtype parameter description below. + * multiplication. When the matrix is empty ( delta=noArray() ), it is + * assumed to be zero, that is, nothing is subtracted. If it has the same + * size as src , it is simply subtracted. Otherwise, it is "repeated" (see + * repeat ) to cover the full src and then subtracted. Type of the delta + * matrix, when it is not empty, must be the same as the type of created + * output matrix. See the dtype parameter description below. * @param scale Optional scale factor for the matrix product. * @param dtype Optional type of the output matrix. When it is negative, - * the output matrix will have the same type as src . Otherwise, it will be - * type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . - * SEE: calcCovarMatrix, gemm, repeat, reduce + * the output matrix will have the same type as src . Otherwise, it will be + * type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . + * SEE: calcCovarMatrix, gemm, repeat, reduce */ public static void mulTransposed(Mat src, Mat dst, boolean aTa, Mat delta, double scale, int dtype) { mulTransposed_0(src.nativeObj, dst.nativeObj, aTa, delta.nativeObj, scale, dtype); } - - // - // C++: void cv::mulTransposed(Mat src, Mat& dst, bool aTa, Mat delta = Mat(), double scale = 1, int dtype = -1) - // - /** * Calculates the product of a matrix and its transposition. - *

      + * * The function cv::mulTransposed calculates the product of src and its * transposition: * \(\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\) @@ -3425,23 +3423,22 @@ public static void mulTransposed(Mat src, Mat dst, boolean aTa, Mat delta, doubl * otherwise. The function is used to calculate the covariance matrix. With * zero delta, it can be used as a faster substitute for general matrix * product A\*B when B=A' - * - * @param src input single-channel matrix. Note that unlike gemm, the - * function can multiply not only floating-point matrices. - * @param dst output square matrix. - * @param aTa Flag specifying the multiplication ordering. See the - * description below. + * @param src input single-channel matrix. Note that unlike gemm, the + * function can multiply not only floating-point matrices. + * @param dst output square matrix. + * @param aTa Flag specifying the multiplication ordering. See the + * description below. * @param delta Optional delta matrix subtracted from src before the - * multiplication. When the matrix is empty ( delta=noArray() ), it is - * assumed to be zero, that is, nothing is subtracted. If it has the same - * size as src , it is simply subtracted. Otherwise, it is "repeated" (see - * repeat ) to cover the full src and then subtracted. Type of the delta - * matrix, when it is not empty, must be the same as the type of created - * output matrix. See the dtype parameter description below. + * multiplication. When the matrix is empty ( delta=noArray() ), it is + * assumed to be zero, that is, nothing is subtracted. If it has the same + * size as src , it is simply subtracted. Otherwise, it is "repeated" (see + * repeat ) to cover the full src and then subtracted. Type of the delta + * matrix, when it is not empty, must be the same as the type of created + * output matrix. See the dtype parameter description below. * @param scale Optional scale factor for the matrix product. - * the output matrix will have the same type as src . Otherwise, it will be - * type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . - * SEE: calcCovarMatrix, gemm, repeat, reduce + * the output matrix will have the same type as src . Otherwise, it will be + * type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . + * SEE: calcCovarMatrix, gemm, repeat, reduce */ public static void mulTransposed(Mat src, Mat dst, boolean aTa, Mat delta, double scale) { mulTransposed_1(src.nativeObj, dst.nativeObj, aTa, delta.nativeObj, scale); @@ -3449,7 +3446,7 @@ public static void mulTransposed(Mat src, Mat dst, boolean aTa, Mat delta, doubl /** * Calculates the product of a matrix and its transposition. - *

      + * * The function cv::mulTransposed calculates the product of src and its * transposition: * \(\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\) @@ -3458,22 +3455,21 @@ public static void mulTransposed(Mat src, Mat dst, boolean aTa, Mat delta, doubl * otherwise. The function is used to calculate the covariance matrix. With * zero delta, it can be used as a faster substitute for general matrix * product A\*B when B=A' - * - * @param src input single-channel matrix. Note that unlike gemm, the - * function can multiply not only floating-point matrices. - * @param dst output square matrix. - * @param aTa Flag specifying the multiplication ordering. See the - * description below. + * @param src input single-channel matrix. Note that unlike gemm, the + * function can multiply not only floating-point matrices. + * @param dst output square matrix. + * @param aTa Flag specifying the multiplication ordering. See the + * description below. * @param delta Optional delta matrix subtracted from src before the - * multiplication. When the matrix is empty ( delta=noArray() ), it is - * assumed to be zero, that is, nothing is subtracted. If it has the same - * size as src , it is simply subtracted. Otherwise, it is "repeated" (see - * repeat ) to cover the full src and then subtracted. Type of the delta - * matrix, when it is not empty, must be the same as the type of created - * output matrix. See the dtype parameter description below. - * the output matrix will have the same type as src . Otherwise, it will be - * type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . - * SEE: calcCovarMatrix, gemm, repeat, reduce + * multiplication. When the matrix is empty ( delta=noArray() ), it is + * assumed to be zero, that is, nothing is subtracted. If it has the same + * size as src , it is simply subtracted. Otherwise, it is "repeated" (see + * repeat ) to cover the full src and then subtracted. Type of the delta + * matrix, when it is not empty, must be the same as the type of created + * output matrix. See the dtype parameter description below. + * the output matrix will have the same type as src . Otherwise, it will be + * type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . + * SEE: calcCovarMatrix, gemm, repeat, reduce */ public static void mulTransposed(Mat src, Mat dst, boolean aTa, Mat delta) { mulTransposed_2(src.nativeObj, dst.nativeObj, aTa, delta.nativeObj); @@ -3481,7 +3477,7 @@ public static void mulTransposed(Mat src, Mat dst, boolean aTa, Mat delta) { /** * Calculates the product of a matrix and its transposition. - *

      + * * The function cv::mulTransposed calculates the product of src and its * transposition: * \(\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\) @@ -3490,34 +3486,37 @@ public static void mulTransposed(Mat src, Mat dst, boolean aTa, Mat delta) { * otherwise. The function is used to calculate the covariance matrix. With * zero delta, it can be used as a faster substitute for general matrix * product A\*B when B=A' - * * @param src input single-channel matrix. Note that unlike gemm, the - * function can multiply not only floating-point matrices. + * function can multiply not only floating-point matrices. * @param dst output square matrix. * @param aTa Flag specifying the multiplication ordering. See the - * description below. - * multiplication. When the matrix is empty ( delta=noArray() ), it is - * assumed to be zero, that is, nothing is subtracted. If it has the same - * size as src , it is simply subtracted. Otherwise, it is "repeated" (see - * repeat ) to cover the full src and then subtracted. Type of the delta - * matrix, when it is not empty, must be the same as the type of created - * output matrix. See the dtype parameter description below. - * the output matrix will have the same type as src . Otherwise, it will be - * type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . - * SEE: calcCovarMatrix, gemm, repeat, reduce + * description below. + * multiplication. When the matrix is empty ( delta=noArray() ), it is + * assumed to be zero, that is, nothing is subtracted. If it has the same + * size as src , it is simply subtracted. Otherwise, it is "repeated" (see + * repeat ) to cover the full src and then subtracted. Type of the delta + * matrix, when it is not empty, must be the same as the type of created + * output matrix. See the dtype parameter description below. + * the output matrix will have the same type as src . Otherwise, it will be + * type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . + * SEE: calcCovarMatrix, gemm, repeat, reduce */ public static void mulTransposed(Mat src, Mat dst, boolean aTa) { mulTransposed_3(src.nativeObj, dst.nativeObj, aTa); } + + // + // C++: void cv::transpose(Mat src, Mat& dst) + // + /** * Transposes a matrix. - *

      + * * The function cv::transpose transposes the matrix src : * \(\texttt{dst} (i,j) = \texttt{src} (j,i)\) * Note: No complex conjugation is done in case of a complex matrix. It * should be done separately if needed. - * * @param src input array. * @param dst output array of the same type as src. */ @@ -3527,18 +3526,17 @@ public static void transpose(Mat src, Mat dst) { // - // C++: void cv::transpose(Mat src, Mat& dst) + // C++: void cv::transposeND(Mat src, vector_int order, Mat& dst) // /** * Transpose for n-dimensional matrices. * * Note: Input should be continuous single-channel matrix. - * - * @param src input array. + * @param src input array. * @param order a permutation of [0,1,..,N-1] where N is the number of axes of src. - * The i’th axis of dst will correspond to the axis numbered order[i] of the input. - * @param dst output array of the same type as src. + * The i’th axis of dst will correspond to the axis numbered order[i] of the input. + * @param dst output array of the same type as src. */ public static void transposeND(Mat src, MatOfInt order, Mat dst) { Mat order_mat = order; @@ -3547,34 +3545,33 @@ public static void transposeND(Mat src, MatOfInt order, Mat dst) { // - // C++: void cv::transposeND(Mat src, vector_int order, Mat& dst) + // C++: void cv::transform(Mat src, Mat& dst, Mat m) // /** * Performs the matrix transformation of every array element. - *

      + * * The function cv::transform performs the matrix transformation of every * element of the array src and stores the results in dst : * \(\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\) * (when m.cols=src.channels() ), or * \(\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\) * (when m.cols=src.channels()+1 ) - *

      + * * Every element of the N -channel array src is interpreted as N -element * vector that is transformed using the M x N or M x (N+1) matrix m to * M-element vector - the corresponding element of the output array dst . - *

      + * * The function may be used for geometrical transformation of * N -dimensional points, arbitrary linear color space transformation (such * as various kinds of RGB to YUV transforms), shuffling the image * channels, and so forth. - * * @param src input array that must have as many channels (1 to 4) as - * m.cols or m.cols-1. + * m.cols or m.cols-1. * @param dst output array of the same size and depth as src; it has as - * many channels as m.rows. - * @param m transformation 2x2 or 2x3 floating-point matrix. - * SEE: perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective + * many channels as m.rows. + * @param m transformation 2x2 or 2x3 floating-point matrix. + * SEE: perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective */ public static void transform(Mat src, Mat dst, Mat m) { transform_0(src.nativeObj, dst.nativeObj, m.nativeObj); @@ -3582,12 +3579,12 @@ public static void transform(Mat src, Mat dst, Mat m) { // - // C++: void cv::transform(Mat src, Mat& dst, Mat m) + // C++: void cv::perspectiveTransform(Mat src, Mat& dst, Mat m) // /** * Performs the perspective matrix transformation of vectors. - *

      + * * The function cv::perspectiveTransform transforms every element of src by * treating it as a 2D or 3D vector, in the following way: * \((x, y, z) \rightarrow (x'/w, y'/w, z'/w)\) @@ -3595,7 +3592,7 @@ public static void transform(Mat src, Mat dst, Mat m) { * \((x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\) * and * \(w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\) - *

      + * * Here a 3D vector transformation is shown. In case of a 2D vector * transformation, the z component is omitted. * @@ -3605,12 +3602,11 @@ public static void transform(Mat src, Mat dst, Mat m) { * compute the most probable perspective transformation out of several * pairs of corresponding points, you can use getPerspectiveTransform or * findHomography . - * * @param src input two-channel or three-channel floating-point array; each - * element is a 2D/3D vector to be transformed. + * element is a 2D/3D vector to be transformed. * @param dst output array of the same size and type as src. - * @param m 3x3 or 4x4 floating-point transformation matrix. - * SEE: transform, warpPerspective, getPerspectiveTransform, findHomography + * @param m 3x3 or 4x4 floating-point transformation matrix. + * SEE: transform, warpPerspective, getPerspectiveTransform, findHomography */ public static void perspectiveTransform(Mat src, Mat dst, Mat m) { perspectiveTransform_0(src.nativeObj, dst.nativeObj, m.nativeObj); @@ -3618,12 +3614,12 @@ public static void perspectiveTransform(Mat src, Mat dst, Mat m) { // - // C++: void cv::perspectiveTransform(Mat src, Mat& dst, Mat m) + // C++: void cv::completeSymm(Mat& m, bool lowerToUpper = false) // /** * Copies the lower or the upper half of a square matrix to its another half. - *

      + * * The function cv::completeSymm copies the lower or the upper half of a square matrix to * its another half. The matrix diagonal remains unchanged: *

        @@ -3637,23 +3633,18 @@ public static void perspectiveTransform(Mat src, Mat dst, Mat m) { * *
      * - * @param m input-output floating-point square matrix. + * @param m input-output floating-point square matrix. * @param lowerToUpper operation flag; if true, the lower half is copied to - * the upper half. Otherwise, the upper half is copied to the lower half. - * SEE: flip, transpose + * the upper half. Otherwise, the upper half is copied to the lower half. + * SEE: flip, transpose */ public static void completeSymm(Mat m, boolean lowerToUpper) { completeSymm_0(m.nativeObj, lowerToUpper); } - - // - // C++: void cv::completeSymm(Mat& m, bool lowerToUpper = false) - // - /** * Copies the lower or the upper half of a square matrix to its another half. - *

      + * * The function cv::completeSymm copies the lower or the upper half of a square matrix to * its another half. The matrix diagonal remains unchanged: *

        @@ -3668,73 +3659,75 @@ public static void completeSymm(Mat m, boolean lowerToUpper) { *
      * * @param m input-output floating-point square matrix. - * the upper half. Otherwise, the upper half is copied to the lower half. - * SEE: flip, transpose + * the upper half. Otherwise, the upper half is copied to the lower half. + * SEE: flip, transpose */ public static void completeSymm(Mat m) { completeSymm_1(m.nativeObj); } + + // + // C++: void cv::setIdentity(Mat& mtx, Scalar s = Scalar(1)) + // + /** * Initializes a scaled identity matrix. - *

      + * * The function cv::setIdentity initializes a scaled identity matrix: * \(\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\) - *

      + * * The function can also be emulated using the matrix initializers and the * matrix expressions: * - * Mat A = Mat::eye(4, 3, CV_32F)*5; - * // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] + * Mat A = Mat::eye(4, 3, CV_32F)*5; + * // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] * - * * @param mtx matrix to initialize (not necessarily square). - * @param s value to assign to diagonal elements. - * SEE: Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= + * @param s value to assign to diagonal elements. + * SEE: Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= */ public static void setIdentity(Mat mtx, Scalar s) { setIdentity_0(mtx.nativeObj, s.val[0], s.val[1], s.val[2], s.val[3]); } - - // - // C++: void cv::setIdentity(Mat& mtx, Scalar s = Scalar(1)) - // - /** * Initializes a scaled identity matrix. - *

      + * * The function cv::setIdentity initializes a scaled identity matrix: * \(\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\) - *

      + * * The function can also be emulated using the matrix initializers and the * matrix expressions: * - * Mat A = Mat::eye(4, 3, CV_32F)*5; - * // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] + * Mat A = Mat::eye(4, 3, CV_32F)*5; + * // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] * - * * @param mtx matrix to initialize (not necessarily square). - * SEE: Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= + * SEE: Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= */ public static void setIdentity(Mat mtx) { setIdentity_1(mtx.nativeObj); } + + // + // C++: double cv::determinant(Mat mtx) + // + /** * Returns the determinant of a square floating-point matrix. - *

      + * * The function cv::determinant calculates and returns the determinant of the * specified matrix. For small matrices ( mtx.cols=mtx.rows<=3 ), the * direct method is used. For larger matrices, the function uses LU * factorization with partial pivoting. - *

      + * * For symmetric positively-determined matrices, it is also possible to use * eigen decomposition to calculate the determinant. - * * @param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and - * square size. - * SEE: trace, invert, solve, eigen, REF: MatrixExpressions + * square size. + * SEE: trace, invert, solve, eigen, REF: MatrixExpressions * @return automatically generated */ public static double determinant(Mat mtx) { @@ -3743,16 +3736,15 @@ public static double determinant(Mat mtx) { // - // C++: double cv::determinant(Mat mtx) + // C++: Scalar cv::trace(Mat mtx) // /** * Returns the trace of a matrix. - *

      + * * The function cv::trace returns the sum of the diagonal elements of the * matrix mtx . * \(\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\) - * * @param mtx input matrix. * @return automatically generated */ @@ -3762,61 +3754,56 @@ public static Scalar trace(Mat mtx) { // - // C++: Scalar cv::trace(Mat mtx) + // C++: double cv::invert(Mat src, Mat& dst, int flags = DECOMP_LU) // /** * Finds the inverse or pseudo-inverse of a matrix. - *

      + * * The function cv::invert inverts the matrix src and stores the result in dst * . When the matrix src is singular or non-square, the function calculates * the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is * minimal, where I is an identity matrix. - *

      + * * In case of the #DECOMP_LU method, the function returns non-zero value if * the inverse has been successfully calculated and 0 if src is singular. - *

      + * * In case of the #DECOMP_SVD method, the function returns the inverse * condition number of src (the ratio of the smallest singular value to the * largest singular value) and 0 if src is singular. The SVD method * calculates a pseudo-inverse matrix if src is singular. - *

      + * * Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with * non-singular square matrices that should also be symmetrical and * positively defined. In this case, the function stores the inverted * matrix in dst and returns non-zero. Otherwise, it returns 0. * - * @param src input floating-point M x N matrix. - * @param dst output matrix of N x M size and the same type as src. + * @param src input floating-point M x N matrix. + * @param dst output matrix of N x M size and the same type as src. * @param flags inversion method (cv::DecompTypes) - * SEE: solve, SVD + * SEE: solve, SVD * @return automatically generated */ public static double invert(Mat src, Mat dst, int flags) { return invert_0(src.nativeObj, dst.nativeObj, flags); } - - // - // C++: double cv::invert(Mat src, Mat& dst, int flags = DECOMP_LU) - // - /** * Finds the inverse or pseudo-inverse of a matrix. - *

      + * * The function cv::invert inverts the matrix src and stores the result in dst * . When the matrix src is singular or non-square, the function calculates * the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is * minimal, where I is an identity matrix. - *

      + * * In case of the #DECOMP_LU method, the function returns non-zero value if * the inverse has been successfully calculated and 0 if src is singular. - *

      + * * In case of the #DECOMP_SVD method, the function returns the inverse * condition number of src (the ratio of the smallest singular value to the * largest singular value) and 0 if src is singular. The SVD method * calculates a pseudo-inverse matrix if src is singular. - *

      + * * Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with * non-singular square matrices that should also be symmetrical and * positively defined. In this case, the function stores the inverted @@ -3824,21 +3811,26 @@ public static double invert(Mat src, Mat dst, int flags) { * * @param src input floating-point M x N matrix. * @param dst output matrix of N x M size and the same type as src. - * SEE: solve, SVD + * SEE: solve, SVD * @return automatically generated */ public static double invert(Mat src, Mat dst) { return invert_1(src.nativeObj, dst.nativeObj); } + + // + // C++: bool cv::solve(Mat src1, Mat src2, Mat& dst, int flags = DECOMP_LU) + // + /** * Solves one or more linear systems or least-squares problems. - *

      + * * The function cv::solve solves a linear system or least-squares problem (the * latter is possible with SVD or QR methods, or by specifying the flag * #DECOMP_NORMAL ): * \(\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\) - *

      + * * If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 1 * if src1 (or \(\texttt{src1}^T\texttt{src1}\) ) is non-singular. Otherwise, * it returns 0. In the latter case, dst is not valid. Other methods find a @@ -3848,30 +3840,25 @@ public static double invert(Mat src, Mat dst) { * singular system \(\texttt{src1}\cdot\texttt{dst}=0\) , the function solve * will not do the work. Use SVD::solveZ instead. * - * @param src1 input matrix on the left-hand side of the system. - * @param src2 input matrix on the right-hand side of the system. - * @param dst output solution. + * @param src1 input matrix on the left-hand side of the system. + * @param src2 input matrix on the right-hand side of the system. + * @param dst output solution. * @param flags solution (matrix inversion) method (#DecompTypes) - * SEE: invert, SVD, eigen + * SEE: invert, SVD, eigen * @return automatically generated */ public static boolean solve(Mat src1, Mat src2, Mat dst, int flags) { return solve_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, flags); } - - // - // C++: bool cv::solve(Mat src1, Mat src2, Mat& dst, int flags = DECOMP_LU) - // - /** * Solves one or more linear systems or least-squares problems. - *

      + * * The function cv::solve solves a linear system or least-squares problem (the * latter is possible with SVD or QR methods, or by specifying the flag * #DECOMP_NORMAL ): * \(\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\) - *

      + * * If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 1 * if src1 (or \(\texttt{src1}^T\texttt{src1}\) ) is non-singular. Otherwise, * it returns 0. In the latter case, dst is not valid. Other methods find a @@ -3883,27 +3870,32 @@ public static boolean solve(Mat src1, Mat src2, Mat dst, int flags) { * * @param src1 input matrix on the left-hand side of the system. * @param src2 input matrix on the right-hand side of the system. - * @param dst output solution. - * SEE: invert, SVD, eigen + * @param dst output solution. + * SEE: invert, SVD, eigen * @return automatically generated */ public static boolean solve(Mat src1, Mat src2, Mat dst) { return solve_1(src1.nativeObj, src2.nativeObj, dst.nativeObj); } + + // + // C++: void cv::sort(Mat src, Mat& dst, int flags) + // + /** * Sorts each row or each column of a matrix. - *

      + * * The function cv::sort sorts each matrix row or each matrix column in * ascending or descending order. So you should pass two operation flags to * get desired behaviour. If you want to sort matrix rows or columns * lexicographically, you can use STL std::sort generic function with the * proper comparison predicate. * - * @param src input single-channel array. - * @param dst output array of the same size and type as src. + * @param src input single-channel array. + * @param dst output array of the same size and type as src. * @param flags operation flags, a combination of #SortFlags - * SEE: sortIdx, randShuffle + * SEE: sortIdx, randShuffle */ public static void sort(Mat src, Mat dst, int flags) { sort_0(src.nativeObj, dst.nativeObj, flags); @@ -3911,28 +3903,27 @@ public static void sort(Mat src, Mat dst, int flags) { // - // C++: void cv::sort(Mat src, Mat& dst, int flags) + // C++: void cv::sortIdx(Mat src, Mat& dst, int flags) // /** * Sorts each row or each column of a matrix. - *

      + * * The function cv::sortIdx sorts each matrix row or each matrix column in the * ascending or descending order. So you should pass two operation flags to * get desired behaviour. Instead of reordering the elements themselves, it * stores the indices of sorted elements in the output array. For example: * - * Mat A = Mat::eye(3,3,CV_32F), B; - * sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING); - * // B will probably contain - * // (because of equal elements in A some permutations are possible): - * // [[1, 2, 0], [0, 2, 1], [0, 1, 2]] + * Mat A = Mat::eye(3,3,CV_32F), B; + * sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING); + * // B will probably contain + * // (because of equal elements in A some permutations are possible): + * // [[1, 2, 0], [0, 2, 1], [0, 1, 2]] * - * - * @param src input single-channel array. - * @param dst output integer array of the same size as src. + * @param src input single-channel array. + * @param dst output integer array of the same size as src. * @param flags operation flags that could be a combination of cv::SortFlags - * SEE: sort, randShuffle + * SEE: sort, randShuffle */ public static void sortIdx(Mat src, Mat dst, int flags) { sortIdx_0(src.nativeObj, dst.nativeObj, flags); @@ -3940,12 +3931,12 @@ public static void sortIdx(Mat src, Mat dst, int flags) { // - // C++: void cv::sortIdx(Mat src, Mat& dst, int flags) + // C++: int cv::solveCubic(Mat coeffs, Mat& roots) // /** * Finds the real roots of a cubic equation. - *

      + * * The function solveCubic finds the real roots of a cubic equation: *

        *
      • @@ -3957,11 +3948,10 @@ public static void sortIdx(Mat src, Mat dst, int flags) { * \(x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\) *
      • *
      - *

      - * The roots are stored in the roots array. * + * The roots are stored in the roots array. * @param coeffs equation coefficients, an array of 3 or 4 elements. - * @param roots output array of real roots that has 1 or 3 elements. + * @param roots output array of real roots that has 1 or 3 elements. * @return number of real roots. It can be 0, 1 or 2. */ public static int solveCubic(Mat coeffs, Mat roots) { @@ -3970,17 +3960,16 @@ public static int solveCubic(Mat coeffs, Mat roots) { // - // C++: int cv::solveCubic(Mat coeffs, Mat& roots) + // C++: double cv::solvePoly(Mat coeffs, Mat& roots, int maxIters = 300) // /** * Finds the real or complex roots of a polynomial equation. - *

      + * * The function cv::solvePoly finds real and complex roots of a polynomial equation: * \(\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\) - * - * @param coeffs array of polynomial coefficients. - * @param roots output (complex) array of roots. + * @param coeffs array of polynomial coefficients. + * @param roots output (complex) array of roots. * @param maxIters maximum number of iterations the algorithm does. * @return automatically generated */ @@ -3988,93 +3977,92 @@ public static double solvePoly(Mat coeffs, Mat roots, int maxIters) { return solvePoly_0(coeffs.nativeObj, roots.nativeObj, maxIters); } - - // - // C++: double cv::solvePoly(Mat coeffs, Mat& roots, int maxIters = 300) - // - /** * Finds the real or complex roots of a polynomial equation. - *

      + * * The function cv::solvePoly finds real and complex roots of a polynomial equation: * \(\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\) - * * @param coeffs array of polynomial coefficients. - * @param roots output (complex) array of roots. + * @param roots output (complex) array of roots. * @return automatically generated */ public static double solvePoly(Mat coeffs, Mat roots) { return solvePoly_1(coeffs.nativeObj, roots.nativeObj); } + + // + // C++: bool cv::eigen(Mat src, Mat& eigenvalues, Mat& eigenvectors = Mat()) + // + /** * Calculates eigenvalues and eigenvectors of a symmetric matrix. - *

      + * * The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric * matrix src: * - * src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t() + * src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t() * * * Note: Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix. * - * @param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical - * (src ^T^ == src). - * @param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored - * in the descending order. + * @param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical + * (src ^T^ == src). + * @param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored + * in the descending order. * @param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the - * eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding - * eigenvalues. - * SEE: eigenNonSymmetric, completeSymm , PCA + * eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding + * eigenvalues. + * SEE: eigenNonSymmetric, completeSymm , PCA * @return automatically generated */ public static boolean eigen(Mat src, Mat eigenvalues, Mat eigenvectors) { return eigen_0(src.nativeObj, eigenvalues.nativeObj, eigenvectors.nativeObj); } - - // - // C++: bool cv::eigen(Mat src, Mat& eigenvalues, Mat& eigenvectors = Mat()) - // - /** * Calculates eigenvalues and eigenvectors of a symmetric matrix. - *

      + * * The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric * matrix src: * - * src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t() + * src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t() * * * Note: Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix. * - * @param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical - * (src ^T^ == src). + * @param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical + * (src ^T^ == src). * @param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored - * in the descending order. - * eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding - * eigenvalues. - * SEE: eigenNonSymmetric, completeSymm , PCA + * in the descending order. + * eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding + * eigenvalues. + * SEE: eigenNonSymmetric, completeSymm , PCA * @return automatically generated */ public static boolean eigen(Mat src, Mat eigenvalues) { return eigen_1(src.nativeObj, eigenvalues.nativeObj); } + + // + // C++: void cv::eigenNonSymmetric(Mat src, Mat& eigenvalues, Mat& eigenvectors) + // + /** * Calculates eigenvalues and eigenvectors of a non-symmetric matrix (real eigenvalues only). * * Note: Assumes real eigenvalues. - *

      + * * The function calculates eigenvalues and eigenvectors (optional) of the square matrix src: * - * src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t() + * src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t() * * - * @param src input matrix (CV_32FC1 or CV_64FC1 type). - * @param eigenvalues output vector of eigenvalues (type is the same type as src). + * @param src input matrix (CV_32FC1 or CV_64FC1 type). + * @param eigenvalues output vector of eigenvalues (type is the same type as src). * @param eigenvectors output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues. - * SEE: eigen + * SEE: eigen */ public static void eigenNonSymmetric(Mat src, Mat eigenvalues, Mat eigenvectors) { eigenNonSymmetric_0(src.nativeObj, eigenvalues.nativeObj, eigenvectors.nativeObj); @@ -4082,103 +4070,98 @@ public static void eigenNonSymmetric(Mat src, Mat eigenvalues, Mat eigenvectors) // - // C++: void cv::eigenNonSymmetric(Mat src, Mat& eigenvalues, Mat& eigenvectors) + // C++: void cv::calcCovarMatrix(Mat samples, Mat& covar, Mat& mean, int flags, int ctype = CV_64F) // /** - * Note: use #COVAR_ROWS or #COVAR_COLS flag * + * Note: use #COVAR_ROWS or #COVAR_COLS flag * @param samples samples stored as rows/columns of a single matrix. - * @param covar output covariance matrix of the type ctype and square size. - * @param mean input or output (depending on the flags) array as the average value of the input vectors. - * @param flags operation flags as a combination of #CovarFlags - * @param ctype type of the matrixl; it equals 'CV_64F' by default. + * @param covar output covariance matrix of the type ctype and square size. + * @param mean input or output (depending on the flags) array as the average value of the input vectors. + * @param flags operation flags as a combination of #CovarFlags + * @param ctype type of the matrixl; it equals 'CV_64F' by default. */ public static void calcCovarMatrix(Mat samples, Mat covar, Mat mean, int flags, int ctype) { calcCovarMatrix_0(samples.nativeObj, covar.nativeObj, mean.nativeObj, flags, ctype); } - - // - // C++: void cv::calcCovarMatrix(Mat samples, Mat& covar, Mat& mean, int flags, int ctype = CV_64F) - // - /** - * Note: use #COVAR_ROWS or #COVAR_COLS flag * + * Note: use #COVAR_ROWS or #COVAR_COLS flag * @param samples samples stored as rows/columns of a single matrix. - * @param covar output covariance matrix of the type ctype and square size. - * @param mean input or output (depending on the flags) array as the average value of the input vectors. - * @param flags operation flags as a combination of #CovarFlags + * @param covar output covariance matrix of the type ctype and square size. + * @param mean input or output (depending on the flags) array as the average value of the input vectors. + * @param flags operation flags as a combination of #CovarFlags */ public static void calcCovarMatrix(Mat samples, Mat covar, Mat mean, int flags) { calcCovarMatrix_1(samples.nativeObj, covar.nativeObj, mean.nativeObj, flags); } + + // + // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, int maxComponents = 0) + // + /** * wrap PCA::operator() - * - * @param data automatically generated - * @param mean automatically generated - * @param eigenvectors automatically generated + * @param data automatically generated + * @param mean automatically generated + * @param eigenvectors automatically generated * @param maxComponents automatically generated */ public static void PCACompute(Mat data, Mat mean, Mat eigenvectors, int maxComponents) { PCACompute_0(data.nativeObj, mean.nativeObj, eigenvectors.nativeObj, maxComponents); } - - // - // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, int maxComponents = 0) - // - /** * wrap PCA::operator() - * - * @param data automatically generated - * @param mean automatically generated + * @param data automatically generated + * @param mean automatically generated * @param eigenvectors automatically generated */ public static void PCACompute(Mat data, Mat mean, Mat eigenvectors) { PCACompute_1(data.nativeObj, mean.nativeObj, eigenvectors.nativeObj); } + + // + // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, Mat& eigenvalues, int maxComponents = 0) + // + /** * wrap PCA::operator() and add eigenvalues output parameter - * - * @param data automatically generated - * @param mean automatically generated - * @param eigenvectors automatically generated - * @param eigenvalues automatically generated + * @param data automatically generated + * @param mean automatically generated + * @param eigenvectors automatically generated + * @param eigenvalues automatically generated * @param maxComponents automatically generated */ public static void PCACompute2(Mat data, Mat mean, Mat eigenvectors, Mat eigenvalues, int maxComponents) { PCACompute2_0(data.nativeObj, mean.nativeObj, eigenvectors.nativeObj, eigenvalues.nativeObj, maxComponents); } - - // - // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, Mat& eigenvalues, int maxComponents = 0) - // - /** * wrap PCA::operator() and add eigenvalues output parameter - * - * @param data automatically generated - * @param mean automatically generated + * @param data automatically generated + * @param mean automatically generated * @param eigenvectors automatically generated - * @param eigenvalues automatically generated + * @param eigenvalues automatically generated */ public static void PCACompute2(Mat data, Mat mean, Mat eigenvectors, Mat eigenvalues) { PCACompute2_1(data.nativeObj, mean.nativeObj, eigenvectors.nativeObj, eigenvalues.nativeObj); } + + // + // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, double retainedVariance) + // + /** * wrap PCA::operator() - * - * @param data automatically generated - * @param mean automatically generated - * @param eigenvectors automatically generated + * @param data automatically generated + * @param mean automatically generated + * @param eigenvectors automatically generated * @param retainedVariance automatically generated */ public static void PCACompute(Mat data, Mat mean, Mat eigenvectors, double retainedVariance) { @@ -4187,16 +4170,15 @@ public static void PCACompute(Mat data, Mat mean, Mat eigenvectors, double retai // - // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, double retainedVariance) + // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, Mat& eigenvalues, double retainedVariance) // /** * wrap PCA::operator() and add eigenvalues output parameter - * - * @param data automatically generated - * @param mean automatically generated - * @param eigenvectors automatically generated - * @param eigenvalues automatically generated + * @param data automatically generated + * @param mean automatically generated + * @param eigenvectors automatically generated + * @param eigenvalues automatically generated * @param retainedVariance automatically generated */ public static void PCACompute2(Mat data, Mat mean, Mat eigenvectors, Mat eigenvalues, double retainedVariance) { @@ -4205,16 +4187,15 @@ public static void PCACompute2(Mat data, Mat mean, Mat eigenvectors, Mat eigenva // - // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, Mat& eigenvalues, double retainedVariance) + // C++: void cv::PCAProject(Mat data, Mat mean, Mat eigenvectors, Mat& result) // /** * wrap PCA::project - * - * @param data automatically generated - * @param mean automatically generated + * @param data automatically generated + * @param mean automatically generated * @param eigenvectors automatically generated - * @param result automatically generated + * @param result automatically generated */ public static void PCAProject(Mat data, Mat mean, Mat eigenvectors, Mat result) { PCAProject_0(data.nativeObj, mean.nativeObj, eigenvectors.nativeObj, result.nativeObj); @@ -4222,16 +4203,15 @@ public static void PCAProject(Mat data, Mat mean, Mat eigenvectors, Mat result) // - // C++: void cv::PCAProject(Mat data, Mat mean, Mat eigenvectors, Mat& result) + // C++: void cv::PCABackProject(Mat data, Mat mean, Mat eigenvectors, Mat& result) // /** * wrap PCA::backProject - * - * @param data automatically generated - * @param mean automatically generated + * @param data automatically generated + * @param mean automatically generated * @param eigenvectors automatically generated - * @param result automatically generated + * @param result automatically generated */ public static void PCABackProject(Mat data, Mat mean, Mat eigenvectors, Mat result) { PCABackProject_0(data.nativeObj, mean.nativeObj, eigenvectors.nativeObj, result.nativeObj); @@ -4239,45 +4219,42 @@ public static void PCABackProject(Mat data, Mat mean, Mat eigenvectors, Mat resu // - // C++: void cv::PCABackProject(Mat data, Mat mean, Mat eigenvectors, Mat& result) + // C++: void cv::SVDecomp(Mat src, Mat& w, Mat& u, Mat& vt, int flags = 0) // /** * wrap SVD::compute - * - * @param src automatically generated - * @param w automatically generated - * @param u automatically generated - * @param vt automatically generated + * @param src automatically generated + * @param w automatically generated + * @param u automatically generated + * @param vt automatically generated * @param flags automatically generated */ public static void SVDecomp(Mat src, Mat w, Mat u, Mat vt, int flags) { SVDecomp_0(src.nativeObj, w.nativeObj, u.nativeObj, vt.nativeObj, flags); } - - // - // C++: void cv::SVDecomp(Mat src, Mat& w, Mat& u, Mat& vt, int flags = 0) - // - /** * wrap SVD::compute - * * @param src automatically generated - * @param w automatically generated - * @param u automatically generated - * @param vt automatically generated + * @param w automatically generated + * @param u automatically generated + * @param vt automatically generated */ public static void SVDecomp(Mat src, Mat w, Mat u, Mat vt) { SVDecomp_1(src.nativeObj, w.nativeObj, u.nativeObj, vt.nativeObj); } + + // + // C++: void cv::SVBackSubst(Mat w, Mat u, Mat vt, Mat rhs, Mat& dst) + // + /** * wrap SVD::backSubst - * - * @param w automatically generated - * @param u automatically generated - * @param vt automatically generated + * @param w automatically generated + * @param u automatically generated + * @param vt automatically generated * @param rhs automatically generated * @param dst automatically generated */ @@ -4287,19 +4264,18 @@ public static void SVBackSubst(Mat w, Mat u, Mat vt, Mat rhs, Mat dst) { // - // C++: void cv::SVBackSubst(Mat w, Mat u, Mat vt, Mat rhs, Mat& dst) + // C++: double cv::Mahalanobis(Mat v1, Mat v2, Mat icovar) // /** * Calculates the Mahalanobis distance between two vectors. - *

      + * * The function cv::Mahalanobis calculates and returns the weighted distance between two vectors: * \(d( \texttt{vec1} , \texttt{vec2} )= \sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})} }\) * The covariance matrix may be calculated using the #calcCovarMatrix function and then inverted using * the invert function (preferably using the #DECOMP_SVD method, as the most accurate). - * - * @param v1 first 1D input vector. - * @param v2 second 1D input vector. + * @param v1 first 1D input vector. + * @param v2 second 1D input vector. * @param icovar inverse covariance matrix. * @return automatically generated */ @@ -4309,12 +4285,12 @@ public static double Mahalanobis(Mat v1, Mat v2, Mat icovar) { // - // C++: double cv::Mahalanobis(Mat v1, Mat v2, Mat icovar) + // C++: void cv::dft(Mat src, Mat& dst, int flags = 0, int nonzeroRows = 0) // /** * Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array. - *

      + * * The function cv::dft performs one of the following: *

        *
      • @@ -4336,15 +4312,15 @@ public static double Mahalanobis(Mat v1, Mat v2, Mat icovar) { * \(\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\) *
      • *
      - *

      + * * In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input * spectrum of the inverse Fourier transform can be represented in a packed format called *CCS* * (complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here * is how 2D *CCS* spectrum looks: * \(\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\) - *

      + * * In case of 1D transform of a real vector, the output looks like the first row of the matrix above. - *

      + * * So, the function chooses an operation mode depending on the flags and size of the input array: *

        *
      • @@ -4381,14 +4357,14 @@ public static double Mahalanobis(Mat v1, Mat v2, Mat icovar) { * #DFT_INVERSE and #DFT_ROWS. *
      • *
      - *

      + * * If #DFT_SCALE is set, the scaling is done after the transformation. - *

      + * * Unlike dct , the function supports arrays of arbitrary size. But only those arrays are processed * efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the * current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize * method. - *

      + * * The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays: * * void convolveDFT(InputArray A, InputArray B, OutputArray C) @@ -4399,35 +4375,35 @@ public static double Mahalanobis(Mat v1, Mat v2, Mat icovar) { * // calculate the size of DFT transform * dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1); * dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1); - *

      + * * // allocate temporary buffers and initialize them with 0's * Mat tempA(dftSize, A.type(), Scalar::all(0)); * Mat tempB(dftSize, B.type(), Scalar::all(0)); - *

      + * * // copy A and B to the top-left corners of tempA and tempB, respectively * Mat roiA(tempA, Rect(0,0,A.cols,A.rows)); * A.copyTo(roiA); * Mat roiB(tempB, Rect(0,0,B.cols,B.rows)); * B.copyTo(roiB); - *

      + * * // now transform the padded A & B in-place; * // use "nonzeroRows" hint for faster processing * dft(tempA, tempA, 0, A.rows); * dft(tempB, tempB, 0, B.rows); - *

      + * * // multiply the spectrums; * // the function handles packed spectrum representations well * mulSpectrums(tempA, tempB, tempA); - *

      + * * // transform the product back from the frequency domain. * // Even though all the result rows will be non-zero, * // you need only the first C.rows of them, and thus you * // pass nonzeroRows == C.rows * dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows); - *

      + * * // now copy the result back to C. * tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C); - *

      + * * // all the temporary buffers will be deallocated automatically * } * @@ -4455,7 +4431,7 @@ public static double Mahalanobis(Mat v1, Mat v2, Mat icovar) { * parts, the loop can be threaded. * *

    - *

    + * * All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by * using them, you can get the performance even better than with the above theoretically optimal * implementation. Though, those two functions actually calculate cross-correlation, not convolution, @@ -4475,30 +4451,24 @@ public static double Mahalanobis(Mat v1, Mat v2, Mat icovar) { * opencv_source/samples/python/dft.py * * - * - * @param src input array that could be real or complex. - * @param dst output array whose size and type depends on the flags . - * @param flags transformation flags, representing a combination of the #DftFlags + * @param src input array that could be real or complex. + * @param dst output array whose size and type depends on the flags . + * @param flags transformation flags, representing a combination of the #DftFlags * @param nonzeroRows when the parameter is not zero, the function assumes that only the first - * nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the - * output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the - * rows more efficiently and save some time; this technique is very useful for calculating array - * cross-correlation or convolution using DFT. - * SEE: dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar , - * magnitude , phase + * nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the + * output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the + * rows more efficiently and save some time; this technique is very useful for calculating array + * cross-correlation or convolution using DFT. + * SEE: dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar , + * magnitude , phase */ public static void dft(Mat src, Mat dst, int flags, int nonzeroRows) { dft_0(src.nativeObj, dst.nativeObj, flags, nonzeroRows); } - - // - // C++: void cv::dft(Mat src, Mat& dst, int flags = 0, int nonzeroRows = 0) - // - /** * Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array. - *

    + * * The function cv::dft performs one of the following: *

      *
    • @@ -4520,15 +4490,15 @@ public static void dft(Mat src, Mat dst, int flags, int nonzeroRows) { * \(\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\) *
    • *
    - *

    + * * In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input * spectrum of the inverse Fourier transform can be represented in a packed format called *CCS* * (complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here * is how 2D *CCS* spectrum looks: * \(\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\) - *

    + * * In case of 1D transform of a real vector, the output looks like the first row of the matrix above. - *

    + * * So, the function chooses an operation mode depending on the flags and size of the input array: *

      *
    • @@ -4565,14 +4535,14 @@ public static void dft(Mat src, Mat dst, int flags, int nonzeroRows) { * #DFT_INVERSE and #DFT_ROWS. *
    • *
    - *

    + * * If #DFT_SCALE is set, the scaling is done after the transformation. - *

    + * * Unlike dct , the function supports arrays of arbitrary size. But only those arrays are processed * efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the * current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize * method. - *

    + * * The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays: * * void convolveDFT(InputArray A, InputArray B, OutputArray C) @@ -4583,35 +4553,35 @@ public static void dft(Mat src, Mat dst, int flags, int nonzeroRows) { * // calculate the size of DFT transform * dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1); * dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1); - *

    + * * // allocate temporary buffers and initialize them with 0's * Mat tempA(dftSize, A.type(), Scalar::all(0)); * Mat tempB(dftSize, B.type(), Scalar::all(0)); - *

    + * * // copy A and B to the top-left corners of tempA and tempB, respectively * Mat roiA(tempA, Rect(0,0,A.cols,A.rows)); * A.copyTo(roiA); * Mat roiB(tempB, Rect(0,0,B.cols,B.rows)); * B.copyTo(roiB); - *

    + * * // now transform the padded A & B in-place; * // use "nonzeroRows" hint for faster processing * dft(tempA, tempA, 0, A.rows); * dft(tempB, tempB, 0, B.rows); - *

    + * * // multiply the spectrums; * // the function handles packed spectrum representations well * mulSpectrums(tempA, tempB, tempA); - *

    + * * // transform the product back from the frequency domain. * // Even though all the result rows will be non-zero, * // you need only the first C.rows of them, and thus you * // pass nonzeroRows == C.rows * dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows); - *

    + * * // now copy the result back to C. * tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C); - *

    + * * // all the temporary buffers will be deallocated automatically * } * @@ -4639,7 +4609,7 @@ public static void dft(Mat src, Mat dst, int flags, int nonzeroRows) { * parts, the loop can be threaded. * * - *

    + * * All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by * using them, you can get the performance even better than with the above theoretically optimal * implementation. Though, those two functions actually calculate cross-correlation, not convolution, @@ -4659,16 +4629,15 @@ public static void dft(Mat src, Mat dst, int flags, int nonzeroRows) { * opencv_source/samples/python/dft.py * * - * - * @param src input array that could be real or complex. - * @param dst output array whose size and type depends on the flags . + * @param src input array that could be real or complex. + * @param dst output array whose size and type depends on the flags . * @param flags transformation flags, representing a combination of the #DftFlags - * nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the - * output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the - * rows more efficiently and save some time; this technique is very useful for calculating array - * cross-correlation or convolution using DFT. - * SEE: dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar , - * magnitude , phase + * nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the + * output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the + * rows more efficiently and save some time; this technique is very useful for calculating array + * cross-correlation or convolution using DFT. + * SEE: dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar , + * magnitude , phase */ public static void dft(Mat src, Mat dst, int flags) { dft_1(src.nativeObj, dst.nativeObj, flags); @@ -4676,7 +4645,7 @@ public static void dft(Mat src, Mat dst, int flags) { /** * Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array. - *

    + * * The function cv::dft performs one of the following: *

      *
    • @@ -4698,15 +4667,15 @@ public static void dft(Mat src, Mat dst, int flags) { * \(\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\) *
    • *
    - *

    + * * In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input * spectrum of the inverse Fourier transform can be represented in a packed format called *CCS* * (complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here * is how 2D *CCS* spectrum looks: * \(\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\) - *

    + * * In case of 1D transform of a real vector, the output looks like the first row of the matrix above. - *

    + * * So, the function chooses an operation mode depending on the flags and size of the input array: *

      *
    • @@ -4743,14 +4712,14 @@ public static void dft(Mat src, Mat dst, int flags) { * #DFT_INVERSE and #DFT_ROWS. *
    • *
    - *

    + * * If #DFT_SCALE is set, the scaling is done after the transformation. - *

    + * * Unlike dct , the function supports arrays of arbitrary size. But only those arrays are processed * efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the * current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize * method. - *

    + * * The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays: * * void convolveDFT(InputArray A, InputArray B, OutputArray C) @@ -4761,35 +4730,35 @@ public static void dft(Mat src, Mat dst, int flags) { * // calculate the size of DFT transform * dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1); * dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1); - *

    + * * // allocate temporary buffers and initialize them with 0's * Mat tempA(dftSize, A.type(), Scalar::all(0)); * Mat tempB(dftSize, B.type(), Scalar::all(0)); - *

    + * * // copy A and B to the top-left corners of tempA and tempB, respectively * Mat roiA(tempA, Rect(0,0,A.cols,A.rows)); * A.copyTo(roiA); * Mat roiB(tempB, Rect(0,0,B.cols,B.rows)); * B.copyTo(roiB); - *

    + * * // now transform the padded A & B in-place; * // use "nonzeroRows" hint for faster processing * dft(tempA, tempA, 0, A.rows); * dft(tempB, tempB, 0, B.rows); - *

    + * * // multiply the spectrums; * // the function handles packed spectrum representations well * mulSpectrums(tempA, tempB, tempA); - *

    + * * // transform the product back from the frequency domain. * // Even though all the result rows will be non-zero, * // you need only the first C.rows of them, and thus you * // pass nonzeroRows == C.rows * dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows); - *

    + * * // now copy the result back to C. * tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C); - *

    + * * // all the temporary buffers will be deallocated automatically * } * @@ -4817,7 +4786,7 @@ public static void dft(Mat src, Mat dst, int flags) { * parts, the loop can be threaded. * * - *

    + * * All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by * using them, you can get the performance even better than with the above theoretically optimal * implementation. Though, those two functions actually calculate cross-correlation, not convolution, @@ -4837,55 +4806,52 @@ public static void dft(Mat src, Mat dst, int flags) { * opencv_source/samples/python/dft.py * * - * * @param src input array that could be real or complex. * @param dst output array whose size and type depends on the flags . - * nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the - * output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the - * rows more efficiently and save some time; this technique is very useful for calculating array - * cross-correlation or convolution using DFT. - * SEE: dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar , - * magnitude , phase + * nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the + * output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the + * rows more efficiently and save some time; this technique is very useful for calculating array + * cross-correlation or convolution using DFT. + * SEE: dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar , + * magnitude , phase */ public static void dft(Mat src, Mat dst) { dft_2(src.nativeObj, dst.nativeObj); } + + // + // C++: void cv::idft(Mat src, Mat& dst, int flags = 0, int nonzeroRows = 0) + // + /** * Calculates the inverse Discrete Fourier Transform of a 1D or 2D array. - *

    + * * idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) . * Note: None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of * dft or idft explicitly to make these transforms mutually inverse. * SEE: dft, dct, idct, mulSpectrums, getOptimalDFTSize - * - * @param src input floating-point real or complex array. - * @param dst output array whose size and type depend on the flags. - * @param flags operation flags (see dft and #DftFlags). + * @param src input floating-point real or complex array. + * @param dst output array whose size and type depend on the flags. + * @param flags operation flags (see dft and #DftFlags). * @param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see - * the convolution sample in dft description. + * the convolution sample in dft description. */ public static void idft(Mat src, Mat dst, int flags, int nonzeroRows) { idft_0(src.nativeObj, dst.nativeObj, flags, nonzeroRows); } - - // - // C++: void cv::idft(Mat src, Mat& dst, int flags = 0, int nonzeroRows = 0) - // - /** * Calculates the inverse Discrete Fourier Transform of a 1D or 2D array. - *

    + * * idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) . * Note: None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of * dft or idft explicitly to make these transforms mutually inverse. * SEE: dft, dct, idct, mulSpectrums, getOptimalDFTSize - * - * @param src input floating-point real or complex array. - * @param dst output array whose size and type depend on the flags. + * @param src input floating-point real or complex array. + * @param dst output array whose size and type depend on the flags. * @param flags operation flags (see dft and #DftFlags). - * the convolution sample in dft description. + * the convolution sample in dft description. */ public static void idft(Mat src, Mat dst, int flags) { idft_1(src.nativeObj, dst.nativeObj, flags); @@ -4893,23 +4859,27 @@ public static void idft(Mat src, Mat dst, int flags) { /** * Calculates the inverse Discrete Fourier Transform of a 1D or 2D array. - *

    + * * idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) . * Note: None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of * dft or idft explicitly to make these transforms mutually inverse. * SEE: dft, dct, idct, mulSpectrums, getOptimalDFTSize - * * @param src input floating-point real or complex array. * @param dst output array whose size and type depend on the flags. - * the convolution sample in dft description. + * the convolution sample in dft description. */ public static void idft(Mat src, Mat dst) { idft_2(src.nativeObj, dst.nativeObj); } + + // + // C++: void cv::dct(Mat src, Mat& dst, int flags = 0) + // + /** * Performs a forward or inverse discrete Cosine transform of 1D or 2D array. - *

    + * * The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D * floating-point array: *

      @@ -4935,7 +4905,7 @@ public static void idft(Mat src, Mat dst) { * \(X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\) * *
    - *

    + * * The function chooses the mode of operation by looking at the flags and size of the input array: *

      *
    • @@ -4962,24 +4932,18 @@ public static void idft(Mat src, Mat dst) { * size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); } * N1 = getOptimalDCTSize(N); * - * - * @param src input floating-point array. - * @param dst output array of the same size and type as src . + * @param src input floating-point array. + * @param dst output array of the same size and type as src . * @param flags transformation flags as a combination of cv::DftFlags (DCT_*) - * SEE: dft , getOptimalDFTSize , idct + * SEE: dft , getOptimalDFTSize , idct */ public static void dct(Mat src, Mat dst, int flags) { dct_0(src.nativeObj, dst.nativeObj, flags); } - - // - // C++: void cv::dct(Mat src, Mat& dst, int flags = 0) - // - /** * Performs a forward or inverse discrete Cosine transform of 1D or 2D array. - *

      + * * The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D * floating-point array: *

        @@ -5005,7 +4969,7 @@ public static void dct(Mat src, Mat dst, int flags) { * \(X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\) * *
      - *

      + * * The function chooses the mode of operation by looking at the flags and size of the input array: *

        *
      • @@ -5032,119 +4996,118 @@ public static void dct(Mat src, Mat dst, int flags) { * size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); } * N1 = getOptimalDCTSize(N); * - * * @param src input floating-point array. * @param dst output array of the same size and type as src . - * SEE: dft , getOptimalDFTSize , idct + * SEE: dft , getOptimalDFTSize , idct */ public static void dct(Mat src, Mat dst) { dct_1(src.nativeObj, dst.nativeObj); } + + // + // C++: void cv::idct(Mat src, Mat& dst, int flags = 0) + // + /** * Calculates the inverse Discrete Cosine Transform of a 1D or 2D array. - *

        - * idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). * - * @param src input floating-point single-channel array. - * @param dst output array of the same size and type as src. + * idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). + * @param src input floating-point single-channel array. + * @param dst output array of the same size and type as src. * @param flags operation flags. - * SEE: dct, dft, idft, getOptimalDFTSize + * SEE: dct, dft, idft, getOptimalDFTSize */ public static void idct(Mat src, Mat dst, int flags) { idct_0(src.nativeObj, dst.nativeObj, flags); } - - // - // C++: void cv::idct(Mat src, Mat& dst, int flags = 0) - // - /** * Calculates the inverse Discrete Cosine Transform of a 1D or 2D array. - *

        - * idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). * + * idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). * @param src input floating-point single-channel array. * @param dst output array of the same size and type as src. - * SEE: dct, dft, idft, getOptimalDFTSize + * SEE: dct, dft, idft, getOptimalDFTSize */ public static void idct(Mat src, Mat dst) { idct_1(src.nativeObj, dst.nativeObj); } + + // + // C++: void cv::mulSpectrums(Mat a, Mat b, Mat& c, int flags, bool conjB = false) + // + /** * Performs the per-element multiplication of two Fourier spectrums. - *

        + * * The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex * matrices that are results of a real or complex Fourier transform. - *

        + * * The function, together with dft and idft , may be used to calculate convolution (pass conjB=false ) * or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are * simply multiplied (per element) with an optional conjugation of the second-array elements. When the * arrays are real, they are assumed to be CCS-packed (see dft for details). - * - * @param a first input array. - * @param b second input array of the same size and type as src1 . - * @param c output array of the same size and type as src1 . + * @param a first input array. + * @param b second input array of the same size and type as src1 . + * @param c output array of the same size and type as src1 . * @param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that - * each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a {@code 0} as value. + * each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a {@code 0} as value. * @param conjB optional flag that conjugates the second input array before the multiplication (true) - * or not (false). + * or not (false). */ public static void mulSpectrums(Mat a, Mat b, Mat c, int flags, boolean conjB) { mulSpectrums_0(a.nativeObj, b.nativeObj, c.nativeObj, flags, conjB); } - - // - // C++: void cv::mulSpectrums(Mat a, Mat b, Mat& c, int flags, bool conjB = false) - // - /** * Performs the per-element multiplication of two Fourier spectrums. - *

        + * * The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex * matrices that are results of a real or complex Fourier transform. - *

        + * * The function, together with dft and idft , may be used to calculate convolution (pass conjB=false ) * or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are * simply multiplied (per element) with an optional conjugation of the second-array elements. When the * arrays are real, they are assumed to be CCS-packed (see dft for details). - * - * @param a first input array. - * @param b second input array of the same size and type as src1 . - * @param c output array of the same size and type as src1 . + * @param a first input array. + * @param b second input array of the same size and type as src1 . + * @param c output array of the same size and type as src1 . * @param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that - * each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a {@code 0} as value. - * or not (false). + * each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a {@code 0} as value. + * or not (false). */ public static void mulSpectrums(Mat a, Mat b, Mat c, int flags) { mulSpectrums_1(a.nativeObj, b.nativeObj, c.nativeObj, flags); } + + // + // C++: int cv::getOptimalDFTSize(int vecsize) + // + /** * Returns the optimal DFT size for a given vector size. - *

        + * * DFT performance is not a monotonic function of a vector size. Therefore, when you calculate * convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to * pad the input data with zeros to get a bit larger array that can be transformed much faster than the * original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process. * Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2) * are also processed quite efficiently. - *

        + * * The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize * so that the DFT of a vector of size N can be processed efficiently. In the current implementation N * = 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r. - *

        + * * The function returns a negative number if vecsize is too large (very close to INT_MAX ). - *

        + * * While the function cannot be used directly to estimate the optimal vector size for DCT transform * (since the current DCT implementation supports only even-size vectors), it can be easily processed * as getOptimalDFTSize((vecsize+1)/2)\*2. - * * @param vecsize vector size. - * SEE: dft , dct , idft , idct , mulSpectrums + * SEE: dft , dct , idft , idct , mulSpectrums * @return automatically generated */ public static int getOptimalDFTSize(int vecsize) { @@ -5153,16 +5116,15 @@ public static int getOptimalDFTSize(int vecsize) { // - // C++: int cv::getOptimalDFTSize(int vecsize) + // C++: void cv::setRNGSeed(int seed) // /** * Sets state of default random number generator. - *

        - * The function cv::setRNGSeed sets state of default random number generator to custom value. * + * The function cv::setRNGSeed sets state of default random number generator to custom value. * @param seed new state for default random number generator - * SEE: RNG, randu, randn + * SEE: RNG, randu, randn */ public static void setRNGSeed(int seed) { setRNGSeed_0(seed); @@ -5170,20 +5132,19 @@ public static void setRNGSeed(int seed) { // - // C++: void cv::setRNGSeed(int seed) + // C++: void cv::randu(Mat& dst, double low, double high) // /** * Generates a single uniformly-distributed random number or an array of random numbers. - *

        + * * Non-template variant of the function fills the matrix dst with uniformly-distributed * random numbers from the specified range: * \(\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\) - * - * @param dst output array of random numbers; the array must be pre-allocated. - * @param low inclusive lower boundary of the generated random numbers. + * @param dst output array of random numbers; the array must be pre-allocated. + * @param low inclusive lower boundary of the generated random numbers. * @param high exclusive upper boundary of the generated random numbers. - * SEE: RNG, randn, theRNG + * SEE: RNG, randn, theRNG */ public static void randu(Mat dst, double low, double high) { randu_0(dst.nativeObj, low, high); @@ -5191,21 +5152,20 @@ public static void randu(Mat dst, double low, double high) { // - // C++: void cv::randu(Mat& dst, double low, double high) + // C++: void cv::randn(Mat& dst, double mean, double stddev) // /** * Fills the array with normally distributed random numbers. - *

        + * * The function cv::randn fills the matrix dst with normally distributed random numbers with the specified * mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the * value range of the output array data type. - * - * @param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels. - * @param mean mean value (expectation) of the generated random numbers. + * @param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels. + * @param mean mean value (expectation) of the generated random numbers. * @param stddev standard deviation of the generated random numbers; it can be either a vector (in - * which case a diagonal standard deviation matrix is assumed) or a square matrix. - * SEE: RNG, randu + * which case a diagonal standard deviation matrix is assumed) or a square matrix. + * SEE: RNG, randu */ public static void randn(Mat dst, double mean, double stddev) { randn_0(dst.nativeObj, mean, stddev); @@ -5213,48 +5173,46 @@ public static void randn(Mat dst, double mean, double stddev) { // - // C++: void cv::randn(Mat& dst, double mean, double stddev) + // C++: void cv::randShuffle(Mat& dst, double iterFactor = 1., RNG* rng = 0) // /** * Shuffles the array elements randomly. - *

        + * * The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and * swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor . - * - * @param dst input/output numerical 1D array. + * @param dst input/output numerical 1D array. * @param iterFactor scale factor that determines the number of random swap operations (see the details - * below). - * instead. - * SEE: RNG, sort + * below). + * instead. + * SEE: RNG, sort */ public static void randShuffle(Mat dst, double iterFactor) { randShuffle_0(dst.nativeObj, iterFactor); } - - // - // C++: void cv::randShuffle(Mat& dst, double iterFactor = 1., RNG* rng = 0) - // - /** * Shuffles the array elements randomly. - *

        + * * The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and * swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor . - * * @param dst input/output numerical 1D array. - * below). - * instead. - * SEE: RNG, sort + * below). + * instead. + * SEE: RNG, sort */ public static void randShuffle(Mat dst) { randShuffle_2(dst.nativeObj); } + + // + // C++: double cv::kmeans(Mat data, int K, Mat& bestLabels, TermCriteria criteria, int attempts, int flags, Mat& centers = Mat()) + // + /** * Finds centers of clusters and groups input samples around the clusters. - *

        + * * The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters * and groups the input samples around the clusters. As an output, \(\texttt{bestLabels}_i\) contains a * 0-based cluster index for the sample stored in the \(i^{th}\) row of the samples matrix. @@ -5266,33 +5224,32 @@ public static void randShuffle(Mat dst) { * opencv_source_code/samples/python/kmeans.py *

      • *
      - * - * @param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. - * Examples of this array can be: - *
        - *
      • - * Mat points(count, 2, CV_32F); - *
      • - *
      • - * Mat points(count, 1, CV_32FC2); - *
      • - *
      • - * Mat points(1, count, CV_32FC2); - *
      • - *
      • - * std::vector<cv::Point2f> points(sampleCount); - *
      • - *
      - * @param K Number of clusters to split the set by. + * @param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. + * Examples of this array can be: + *
        + *
      • + * Mat points(count, 2, CV_32F); + *
      • + *
      • + * Mat points(count, 1, CV_32FC2); + *
      • + *
      • + * Mat points(1, count, CV_32FC2); + *
      • + *
      • + * std::vector<cv::Point2f> points(sampleCount); + *
      • + *
      + * @param K Number of clusters to split the set by. * @param bestLabels Input/output integer array that stores the cluster indices for every sample. - * @param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or - * the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster - * centers moves by less than criteria.epsilon on some iteration, the algorithm stops. - * @param attempts Flag to specify the number of times the algorithm is executed using different - * initial labellings. The algorithm returns the labels that yield the best compactness (see the last - * function parameter). - * @param flags Flag that can take values of cv::KmeansFlags - * @param centers Output matrix of the cluster centers, one row per each cluster center. + * @param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or + * the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster + * centers moves by less than criteria.epsilon on some iteration, the algorithm stops. + * @param attempts Flag to specify the number of times the algorithm is executed using different + * initial labellings. The algorithm returns the labels that yield the best compactness (see the last + * function parameter). + * @param flags Flag that can take values of cv::KmeansFlags + * @param centers Output matrix of the cluster centers, one row per each cluster center. * @return The function returns the compactness measure that is computed as * \(\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\) * after every attempt. The best (minimum) value is chosen and the corresponding labels and the @@ -5305,14 +5262,9 @@ public static double kmeans(Mat data, int K, Mat bestLabels, TermCriteria criter return kmeans_0(data.nativeObj, K, bestLabels.nativeObj, criteria.type, criteria.maxCount, criteria.epsilon, attempts, flags, centers.nativeObj); } - - // - // C++: double cv::kmeans(Mat data, int K, Mat& bestLabels, TermCriteria criteria, int attempts, int flags, Mat& centers = Mat()) - // - /** * Finds centers of clusters and groups input samples around the clusters. - *

      + * * The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters * and groups the input samples around the clusters. As an output, \(\texttt{bestLabels}_i\) contains a * 0-based cluster index for the sample stored in the \(i^{th}\) row of the samples matrix. @@ -5324,32 +5276,31 @@ public static double kmeans(Mat data, int K, Mat bestLabels, TermCriteria criter * opencv_source_code/samples/python/kmeans.py *

    • *
    - * - * @param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. - * Examples of this array can be: - *
      - *
    • - * Mat points(count, 2, CV_32F); - *
    • - *
    • - * Mat points(count, 1, CV_32FC2); - *
    • - *
    • - * Mat points(1, count, CV_32FC2); - *
    • - *
    • - * std::vector<cv::Point2f> points(sampleCount); - *
    • - *
    - * @param K Number of clusters to split the set by. + * @param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. + * Examples of this array can be: + *
      + *
    • + * Mat points(count, 2, CV_32F); + *
    • + *
    • + * Mat points(count, 1, CV_32FC2); + *
    • + *
    • + * Mat points(1, count, CV_32FC2); + *
    • + *
    • + * std::vector<cv::Point2f> points(sampleCount); + *
    • + *
    + * @param K Number of clusters to split the set by. * @param bestLabels Input/output integer array that stores the cluster indices for every sample. - * @param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or - * the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster - * centers moves by less than criteria.epsilon on some iteration, the algorithm stops. - * @param attempts Flag to specify the number of times the algorithm is executed using different - * initial labellings. The algorithm returns the labels that yield the best compactness (see the last - * function parameter). - * @param flags Flag that can take values of cv::KmeansFlags + * @param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or + * the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster + * centers moves by less than criteria.epsilon on some iteration, the algorithm stops. + * @param attempts Flag to specify the number of times the algorithm is executed using different + * initial labellings. The algorithm returns the labels that yield the best compactness (see the last + * function parameter). + * @param flags Flag that can take values of cv::KmeansFlags * @return The function returns the compactness measure that is computed as * \(\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\) * after every attempt. The best (minimum) value is chosen and the corresponding labels and the @@ -5362,94 +5313,96 @@ public static double kmeans(Mat data, int K, Mat bestLabels, TermCriteria criter return kmeans_1(data.nativeObj, K, bestLabels.nativeObj, criteria.type, criteria.maxCount, criteria.epsilon, attempts, flags); } + + // + // C++: void cv::setNumThreads(int nthreads) + // + /** - * Returns the number of threads used by OpenCV for parallel regions. - *

    - * Always returns 1 if OpenCV is built without threading support. - *

    - * The exact meaning of return value depends on the threading framework used by OpenCV library: + * OpenCV will try to set the number of threads for subsequent parallel regions. + * + * If threads == 1, OpenCV will disable threading optimizations and run all it's functions + * sequentially. Passing threads < 0 will reset threads number to system default. + * The function is not thread-safe. It must not be called in parallel region or concurrent threads. + * + * OpenCV will try to run its functions with specified threads number, but some behaviour differs from + * framework: *

      *
    • - * {@code TBB} - The number of threads, that OpenCV will try to use for parallel regions. If there is - * any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns - * default number of threads used by TBB library. + * {@code TBB} - User-defined parallel constructions will run with the same threads number, if + * another is not specified. If later on user creates his own scheduler, OpenCV will use it. *
    • *
    • - * {@code OpenMP} - An upper bound on the number of threads that could be used to form a new team. + * {@code OpenMP} - No special defined behaviour. *
    • *
    • - * {@code Concurrency} - The number of threads, that OpenCV will try to use for parallel regions. + * {@code Concurrency} - If threads == 1, OpenCV will disable threading optimizations and run its + * functions sequentially. *
    • *
    • - * {@code GCD} - Unsupported; returns the GCD thread pool limit (512) for compatibility. + * {@code GCD} - Supports only values <= 0. *
    • *
    • - * {@code C=} - The number of threads, that OpenCV will try to use for parallel regions, if before - * called setNumThreads with threads > 0, otherwise returns the number of logical CPUs, - * available for the process. - * SEE: setNumThreads, getThreadNum + * {@code C=} - No special defined behaviour. *
    • *
    - * - * @return automatically generated + * @param nthreads Number of threads used by OpenCV. + * SEE: getNumThreads, getThreadNum */ - public static int getNumThreads() { - return getNumThreads_0(); + public static void setNumThreads(int nthreads) { + setNumThreads_0(nthreads); } // - // C++: void cv::setNumThreads(int nthreads) + // C++: int cv::getNumThreads() // /** - * OpenCV will try to set the number of threads for subsequent parallel regions. - *

    - * If threads == 1, OpenCV will disable threading optimizations and run all it's functions - * sequentially. Passing threads < 0 will reset threads number to system default. - * The function is not thread-safe. It must not be called in parallel region or concurrent threads. - *

    - * OpenCV will try to run its functions with specified threads number, but some behaviour differs from - * framework: + * Returns the number of threads used by OpenCV for parallel regions. + * + * Always returns 1 if OpenCV is built without threading support. + * + * The exact meaning of return value depends on the threading framework used by OpenCV library: *

      *
    • - * {@code TBB} - User-defined parallel constructions will run with the same threads number, if - * another is not specified. If later on user creates his own scheduler, OpenCV will use it. + * {@code TBB} - The number of threads, that OpenCV will try to use for parallel regions. If there is + * any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns + * default number of threads used by TBB library. *
    • *
    • - * {@code OpenMP} - No special defined behaviour. + * {@code OpenMP} - An upper bound on the number of threads that could be used to form a new team. *
    • *
    • - * {@code Concurrency} - If threads == 1, OpenCV will disable threading optimizations and run its - * functions sequentially. + * {@code Concurrency} - The number of threads, that OpenCV will try to use for parallel regions. *
    • *
    • - * {@code GCD} - Supports only values <= 0. + * {@code GCD} - Unsupported; returns the GCD thread pool limit (512) for compatibility. *
    • *
    • - * {@code C=} - No special defined behaviour. + * {@code C=} - The number of threads, that OpenCV will try to use for parallel regions, if before + * called setNumThreads with threads > 0, otherwise returns the number of logical CPUs, + * available for the process. + * SEE: setNumThreads, getThreadNum *
    • *
    - * - * @param nthreads Number of threads used by OpenCV. - * SEE: getNumThreads, getThreadNum + * @return automatically generated */ - public static void setNumThreads(int nthreads) { - setNumThreads_0(nthreads); + public static int getNumThreads() { + return getNumThreads_0(); } // - // C++: int cv::getNumThreads() + // C++: int cv::getThreadNum() // /** * Returns the index of the currently executed thread within the current parallel region. Always * returns 0 if called outside of parallel region. * - * @return automatically generated * @deprecated Current implementation doesn't corresponding to this documentation. - *

    + * * The exact meaning of the return value depends on the threading framework used by OpenCV library: *

      *
    • @@ -5470,6 +5423,7 @@ public static void setNumThreads(int nthreads) { * SEE: setNumThreads, getNumThreads *
    • *
    + * @return automatically generated */ @Deprecated public static int getThreadNum() { @@ -5478,16 +5432,15 @@ public static int getThreadNum() { // - // C++: int cv::getThreadNum() + // C++: String cv::getBuildInformation() // /** * Returns full configuration time cmake output. - *

    + * * Returned value is raw cmake output including version control system revision, compiler version, * compiler flags, enabled modules and third party libraries, etc. Output format depends on target * architecture. - * * @return automatically generated */ public static String getBuildInformation() { @@ -5496,16 +5449,15 @@ public static String getBuildInformation() { // - // C++: String cv::getBuildInformation() + // C++: String cv::getVersionString() // /** * Returns library version string - *

    + * * For example "3.4.1-dev". - *

    - * SEE: getMajorVersion, getMinorVersion, getRevisionVersion * + * SEE: getMajorVersion, getMinorVersion, getRevisionVersion * @return automatically generated */ public static String getVersionString() { @@ -5514,12 +5466,11 @@ public static String getVersionString() { // - // C++: String cv::getVersionString() + // C++: int cv::getVersionMajor() // /** * Returns major library version - * * @return automatically generated */ public static int getVersionMajor() { @@ -5528,12 +5479,11 @@ public static int getVersionMajor() { // - // C++: int cv::getVersionMajor() + // C++: int cv::getVersionMinor() // /** * Returns minor library version - * * @return automatically generated */ public static int getVersionMinor() { @@ -5542,12 +5492,11 @@ public static int getVersionMinor() { // - // C++: int cv::getVersionMinor() + // C++: int cv::getVersionRevision() // /** * Returns revision field of the library version - * * @return automatically generated */ public static int getVersionRevision() { @@ -5556,17 +5505,16 @@ public static int getVersionRevision() { // - // C++: int cv::getVersionRevision() + // C++: int64 cv::getTickCount() // /** * Returns the number of ticks. - *

    + * * The function returns the number of ticks after the certain event (for example, when the machine was * turned on). It can be used to initialize RNG or to measure a function execution time by reading the * tick count before and after the function call. * SEE: getTickFrequency, TickMeter - * * @return automatically generated */ public static long getTickCount() { @@ -5575,21 +5523,20 @@ public static long getTickCount() { // - // C++: int64 cv::getTickCount() + // C++: double cv::getTickFrequency() // /** * Returns the number of ticks per second. - *

    + * * The function returns the number of ticks per second. That is, the following code computes the * execution time in seconds: * - * double t = (double)getTickCount(); - * // do something ... - * t = ((double)getTickCount() - t)/getTickFrequency(); + * double t = (double)getTickCount(); + * // do something ... + * t = ((double)getTickCount() - t)/getTickFrequency(); * * SEE: getTickCount, TickMeter - * * @return automatically generated */ public static double getTickFrequency() { @@ -5598,12 +5545,12 @@ public static double getTickFrequency() { // - // C++: double cv::getTickFrequency() + // C++: int64 cv::getCPUTickCount() // /** * Returns the number of CPU ticks. - *

    + * * The function returns the current number of CPU ticks on some architectures (such as x86, x64, * PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for * very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU @@ -5613,7 +5560,6 @@ public static double getTickFrequency() { * frequency depending on the load, the number of CPU clocks spent in some code cannot be directly * converted to time units. Therefore, getTickCount is generally a preferable solution for measuring * execution time. - * * @return automatically generated */ public static long getCPUTickCount() { @@ -5622,17 +5568,16 @@ public static long getCPUTickCount() { // - // C++: int64 cv::getCPUTickCount() + // C++: bool cv::checkHardwareSupport(int feature) // /** * Returns true if the specified feature is supported by the host hardware. - *

    + * * The function returns true if the host hardware supports the specified feature. When user calls * setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until * setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code * in OpenCV. - * * @param feature The feature of interest, one of cv::CpuFeatures * @return automatically generated */ @@ -5642,14 +5587,13 @@ public static boolean checkHardwareSupport(int feature) { // - // C++: bool cv::checkHardwareSupport(int feature) + // C++: String cv::getHardwareFeatureName(int feature) // /** * Returns feature name by ID - *

    - * Returns empty string if feature is not defined * + * Returns empty string if feature is not defined * @param feature automatically generated * @return automatically generated */ @@ -5659,12 +5603,12 @@ public static String getHardwareFeatureName(int feature) { // - // C++: String cv::getHardwareFeatureName(int feature) + // C++: string cv::getCPUFeaturesLine() // /** * Returns list of CPU features enabled during compilation. - *

    + * * Returned value is a string containing space separated list of CPU features with following markers: * *

      @@ -5678,9 +5622,8 @@ public static String getHardwareFeatureName(int feature) { * suffix {@code ?} - features enabled but not available in HW * *
    - *

    - * Example: {@code SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *FP16 *AVX *AVX2 *AVX512-SKX?} * + * Example: {@code SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *FP16 *AVX *AVX2 *AVX512-SKX?} * @return automatically generated */ public static String getCPUFeaturesLine() { @@ -5689,12 +5632,11 @@ public static String getCPUFeaturesLine() { // - // C++: string cv::getCPUFeaturesLine() + // C++: int cv::getNumberOfCPUs() // /** * Returns the number of logical CPUs available for the process. - * * @return automatically generated */ public static int getNumberOfCPUs() { @@ -5703,23 +5645,22 @@ public static int getNumberOfCPUs() { // - // C++: int cv::getNumberOfCPUs() + // C++: void cv::setUseOptimized(bool onoff) // /** * Enables or disables the optimized code. - *

    + * * The function can be used to dynamically turn on and off optimized dispatched code (code that uses SSE4.2, AVX/AVX2, * and other instructions on the platforms that support it). It sets a global flag that is further * checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only * safe to call the function on the very top level in your application where you can be sure that no * other OpenCV function is currently executed. - *

    + * * By default, the optimized code is enabled unless you disable it in CMake. The current status can be * retrieved using useOptimized. - * * @param onoff The boolean flag specifying whether the optimized code should be used (onoff=true) - * or not (onoff=false). + * or not (onoff=false). */ public static void setUseOptimized(boolean onoff) { setUseOptimized_0(onoff); @@ -5727,14 +5668,13 @@ public static void setUseOptimized(boolean onoff) { // - // C++: void cv::setUseOptimized(bool onoff) + // C++: bool cv::useOptimized() // /** * Returns the status of optimized code usage. - *

    - * The function returns true if the optimized code is enabled. Otherwise, it returns false. * + * The function returns true if the optimized code is enabled. Otherwise, it returns false. * @return automatically generated */ public static boolean useOptimized() { @@ -5743,63 +5683,58 @@ public static boolean useOptimized() { // - // C++: bool cv::useOptimized() + // C++: String cv::samples::findFile(String relative_path, bool required = true, bool silentMode = false) // /** * Try to find requested data file - *

    + * * Search directories: - *

    + * * 1. Directories passed via {@code addSamplesDataSearchPath()} * 2. OPENCV_SAMPLES_DATA_PATH_HINT environment variable * 3. OPENCV_SAMPLES_DATA_PATH environment variable - * If parameter value is not empty and nothing is found then stop searching. + * If parameter value is not empty and nothing is found then stop searching. * 4. Detects build/install path based on: - * a. current working directory (CWD) - * b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) + * a. current working directory (CWD) + * b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) * 5. Scan {@code <source>/{,data,samples/data}} directories if build directory is detected or the current directory is in source tree. * 6. Scan {@code <install>/share/OpenCV} directory if install directory is detected. - *

    + * * SEE: cv::utils::findDataFile * * @param relative_path Relative path to data file - * @param required Specify "file not found" handling. - * If true, function prints information message and raises cv::Exception. - * If false, function returns empty result - * @param silentMode Disables messages + * @param required Specify "file not found" handling. + * If true, function prints information message and raises cv::Exception. + * If false, function returns empty result + * @param silentMode Disables messages * @return Returns path (absolute or relative to the current directory) or empty string if file is not found */ public static String findFile(String relative_path, boolean required, boolean silentMode) { return findFile_0(relative_path, required, silentMode); } - - // - // C++: String cv::samples::findFile(String relative_path, bool required = true, bool silentMode = false) - // - /** * Try to find requested data file - *

    + * * Search directories: - *

    + * * 1. Directories passed via {@code addSamplesDataSearchPath()} * 2. OPENCV_SAMPLES_DATA_PATH_HINT environment variable * 3. OPENCV_SAMPLES_DATA_PATH environment variable - * If parameter value is not empty and nothing is found then stop searching. + * If parameter value is not empty and nothing is found then stop searching. * 4. Detects build/install path based on: - * a. current working directory (CWD) - * b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) + * a. current working directory (CWD) + * b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) * 5. Scan {@code <source>/{,data,samples/data}} directories if build directory is detected or the current directory is in source tree. * 6. Scan {@code <install>/share/OpenCV} directory if install directory is detected. - *

    + * * SEE: cv::utils::findDataFile * * @param relative_path Relative path to data file - * @param required Specify "file not found" handling. - * If true, function prints information message and raises cv::Exception. - * If false, function returns empty result + * @param required Specify "file not found" handling. + * If true, function prints information message and raises cv::Exception. + * If false, function returns empty result * @return Returns path (absolute or relative to the current directory) or empty string if file is not found */ public static String findFile(String relative_path, boolean required) { @@ -5808,46 +5743,51 @@ public static String findFile(String relative_path, boolean required) { /** * Try to find requested data file - *

    + * * Search directories: - *

    + * * 1. Directories passed via {@code addSamplesDataSearchPath()} * 2. OPENCV_SAMPLES_DATA_PATH_HINT environment variable * 3. OPENCV_SAMPLES_DATA_PATH environment variable - * If parameter value is not empty and nothing is found then stop searching. + * If parameter value is not empty and nothing is found then stop searching. * 4. Detects build/install path based on: - * a. current working directory (CWD) - * b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) + * a. current working directory (CWD) + * b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) * 5. Scan {@code <source>/{,data,samples/data}} directories if build directory is detected or the current directory is in source tree. * 6. Scan {@code <install>/share/OpenCV} directory if install directory is detected. - *

    + * * SEE: cv::utils::findDataFile * * @param relative_path Relative path to data file - * If true, function prints information message and raises cv::Exception. - * If false, function returns empty result + * If true, function prints information message and raises cv::Exception. + * If false, function returns empty result * @return Returns path (absolute or relative to the current directory) or empty string if file is not found */ public static String findFile(String relative_path) { return findFile_2(relative_path); } - public static String findFileOrKeep(String relative_path, boolean silentMode) { - return findFileOrKeep_0(relative_path, silentMode); - } - // // C++: String cv::samples::findFileOrKeep(String relative_path, bool silentMode = false) // + public static String findFileOrKeep(String relative_path, boolean silentMode) { + return findFileOrKeep_0(relative_path, silentMode); + } + public static String findFileOrKeep(String relative_path) { return findFileOrKeep_1(relative_path); } + + // + // C++: void cv::samples::addSamplesDataSearchPath(String path) + // + /** * Override search data path by adding new search location - *

    + * * Use this only to override default behavior * Passed paths are used in LIFO order. * @@ -5859,12 +5799,12 @@ public static void addSamplesDataSearchPath(String path) { // - // C++: void cv::samples::addSamplesDataSearchPath(String path) + // C++: void cv::samples::addSamplesDataSearchSubDirectory(String subdir) // /** * Append samples search data sub directory - *

    + * * General usage is to add OpenCV modules name ({@code <opencv_contrib>/modules/<name>/samples/data} -> {@code <name>/samples/data} + {@code modules/<name>/samples/data}). * Passed subdirectories are used in LIFO order. * @@ -5876,7 +5816,7 @@ public static void addSamplesDataSearchSubDirectory(String subdir) { // - // C++: void cv::samples::addSamplesDataSearchSubDirectory(String subdir) + // C++: void cv::setErrorVerbosity(bool verbose) // public static void setErrorVerbosity(boolean verbose) { @@ -5885,18 +5825,13 @@ public static void setErrorVerbosity(boolean verbose) { // - // C++: void cv::setErrorVerbosity(bool verbose) + // C++: void cv::add(Mat src1, Scalar src2, Mat& dst, Mat mask = Mat(), int dtype = -1) // public static void add(Mat src1, Scalar src2, Mat dst, Mat mask, int dtype) { add_3(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, mask.nativeObj, dtype); } - - // - // C++: void cv::add(Mat src1, Scalar src2, Mat& dst, Mat mask = Mat(), int dtype = -1) - // - public static void add(Mat src1, Scalar src2, Mat dst, Mat mask) { add_4(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, mask.nativeObj); } @@ -5905,15 +5840,15 @@ public static void add(Mat src1, Scalar src2, Mat dst) { add_5(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj); } - public static void subtract(Mat src1, Scalar src2, Mat dst, Mat mask, int dtype) { - subtract_3(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, mask.nativeObj, dtype); - } - // // C++: void cv::subtract(Mat src1, Scalar src2, Mat& dst, Mat mask = Mat(), int dtype = -1) // + public static void subtract(Mat src1, Scalar src2, Mat dst, Mat mask, int dtype) { + subtract_3(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, mask.nativeObj, dtype); + } + public static void subtract(Mat src1, Scalar src2, Mat dst, Mat mask) { subtract_4(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, mask.nativeObj); } @@ -5922,15 +5857,15 @@ public static void subtract(Mat src1, Scalar src2, Mat dst) { subtract_5(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj); } - public static void multiply(Mat src1, Scalar src2, Mat dst, double scale, int dtype) { - multiply_3(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, scale, dtype); - } - // // C++: void cv::multiply(Mat src1, Scalar src2, Mat& dst, double scale = 1, int dtype = -1) // + public static void multiply(Mat src1, Scalar src2, Mat dst, double scale, int dtype) { + multiply_3(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, scale, dtype); + } + public static void multiply(Mat src1, Scalar src2, Mat dst, double scale) { multiply_4(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, scale); } @@ -5939,15 +5874,15 @@ public static void multiply(Mat src1, Scalar src2, Mat dst) { multiply_5(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj); } - public static void divide(Mat src1, Scalar src2, Mat dst, double scale, int dtype) { - divide_5(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, scale, dtype); - } - // // C++: void cv::divide(Mat src1, Scalar src2, Mat& dst, double scale = 1, int dtype = -1) // + public static void divide(Mat src1, Scalar src2, Mat dst, double scale, int dtype) { + divide_5(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, scale, dtype); + } + public static void divide(Mat src1, Scalar src2, Mat dst, double scale) { divide_6(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj, scale); } @@ -5956,13 +5891,18 @@ public static void divide(Mat src1, Scalar src2, Mat dst) { divide_7(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj); } + + // + // C++: void cv::absdiff(Mat src1, Scalar src2, Mat& dst) + // + public static void absdiff(Mat src1, Scalar src2, Mat dst) { absdiff_1(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj); } // - // C++: void cv::absdiff(Mat src1, Scalar src2, Mat& dst) + // C++: void cv::compare(Mat src1, Scalar src2, Mat& dst, int cmpop) // public static void compare(Mat src1, Scalar src2, Mat dst, int cmpop) { @@ -5971,7 +5911,7 @@ public static void compare(Mat src1, Scalar src2, Mat dst, int cmpop) { // - // C++: void cv::compare(Mat src1, Scalar src2, Mat& dst, int cmpop) + // C++: void cv::min(Mat src1, Scalar src2, Mat& dst) // public static void min(Mat src1, Scalar src2, Mat dst) { @@ -5980,43 +5920,56 @@ public static void min(Mat src1, Scalar src2, Mat dst) { // - // C++: void cv::min(Mat src1, Scalar src2, Mat& dst) + // C++: void cv::max(Mat src1, Scalar src2, Mat& dst) // public static void max(Mat src1, Scalar src2, Mat dst) { max_1(src1.nativeObj, src2.val[0], src2.val[1], src2.val[2], src2.val[3], dst.nativeObj); } +// manual port +public static class MinMaxLocResult { + public double minVal; + public double maxVal; + public Point minLoc; + public Point maxLoc; - // - // C++: void cv::max(Mat src1, Scalar src2, Mat& dst) - // - - //javadoc: minMaxLoc(src, mask) - public static MinMaxLocResult minMaxLoc(Mat src, Mat mask) { - MinMaxLocResult res = new MinMaxLocResult(); - long maskNativeObj = 0; - if (mask != null) { - maskNativeObj = mask.nativeObj; - } - double resarr[] = n_minMaxLocManual(src.nativeObj, maskNativeObj); - res.minVal = resarr[0]; - res.maxVal = resarr[1]; - res.minLoc.x = resarr[2]; - res.minLoc.y = resarr[3]; - res.maxLoc.x = resarr[4]; - res.maxLoc.y = resarr[5]; - return res; - } - //javadoc: minMaxLoc(src) - public static MinMaxLocResult minMaxLoc(Mat src) { - return minMaxLoc(src, null); + public MinMaxLocResult() { + minVal=0; maxVal=0; + minLoc=new Point(); + maxLoc=new Point(); } +} // C++: minMaxLoc(Mat src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArray mask=noArray()) + +//javadoc: minMaxLoc(src, mask) +public static MinMaxLocResult minMaxLoc(Mat src, Mat mask) { + MinMaxLocResult res = new MinMaxLocResult(); + long maskNativeObj=0; + if (mask != null) { + maskNativeObj=mask.nativeObj; + } + double resarr[] = n_minMaxLocManual(src.nativeObj, maskNativeObj); + res.minVal=resarr[0]; + res.maxVal=resarr[1]; + res.minLoc.x=resarr[2]; + res.minLoc.y=resarr[3]; + res.maxLoc.x=resarr[4]; + res.maxLoc.y=resarr[5]; + return res; +} + + +//javadoc: minMaxLoc(src) +public static MinMaxLocResult minMaxLoc(Mat src) { + return minMaxLoc(src, null); +} + + // C++: float cv::cubeRoot(float val) private static native float cubeRoot_0(float val); @@ -6043,40 +5996,30 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::copyMakeBorder(Mat src, Mat& dst, int top, int bottom, int left, int right, int borderType, Scalar value = Scalar()) private static native void copyMakeBorder_0(long src_nativeObj, long dst_nativeObj, int top, int bottom, int left, int right, int borderType, double value_val0, double value_val1, double value_val2, double value_val3); - private static native void copyMakeBorder_1(long src_nativeObj, long dst_nativeObj, int top, int bottom, int left, int right, int borderType); // C++: void cv::add(Mat src1, Mat src2, Mat& dst, Mat mask = Mat(), int dtype = -1) private static native void add_0(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, long mask_nativeObj, int dtype); - private static native void add_1(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, long mask_nativeObj); - private static native void add_2(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj); // C++: void cv::subtract(Mat src1, Mat src2, Mat& dst, Mat mask = Mat(), int dtype = -1) private static native void subtract_0(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, long mask_nativeObj, int dtype); - private static native void subtract_1(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, long mask_nativeObj); - private static native void subtract_2(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj); // C++: void cv::multiply(Mat src1, Mat src2, Mat& dst, double scale = 1, int dtype = -1) private static native void multiply_0(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, double scale, int dtype); - private static native void multiply_1(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, double scale); - private static native void multiply_2(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj); // C++: void cv::divide(Mat src1, Mat src2, Mat& dst, double scale = 1, int dtype = -1) private static native void divide_0(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, double scale, int dtype); - private static native void divide_1(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, double scale); - private static native void divide_2(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj); // C++: void cv::divide(double scale, Mat src2, Mat& dst, int dtype = -1) private static native void divide_3(double scale, long src2_nativeObj, long dst_nativeObj, int dtype); - private static native void divide_4(double scale, long src2_nativeObj, long dst_nativeObj); // C++: void cv::scaleAdd(Mat src1, double alpha, Mat src2, Mat& dst) @@ -6084,14 +6027,11 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::addWeighted(Mat src1, double alpha, Mat src2, double beta, double gamma, Mat& dst, int dtype = -1) private static native void addWeighted_0(long src1_nativeObj, double alpha, long src2_nativeObj, double beta, double gamma, long dst_nativeObj, int dtype); - private static native void addWeighted_1(long src1_nativeObj, double alpha, long src2_nativeObj, double beta, double gamma, long dst_nativeObj); // C++: void cv::convertScaleAbs(Mat src, Mat& dst, double alpha = 1, double beta = 0) private static native void convertScaleAbs_0(long src_nativeObj, long dst_nativeObj, double alpha, double beta); - private static native void convertScaleAbs_1(long src_nativeObj, long dst_nativeObj, double alpha); - private static native void convertScaleAbs_2(long src_nativeObj, long dst_nativeObj); // C++: void cv::convertFp16(Mat src, Mat& dst) @@ -6114,72 +6054,52 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: Scalar cv::mean(Mat src, Mat mask = Mat()) private static native double[] mean_0(long src_nativeObj, long mask_nativeObj); - private static native double[] mean_1(long src_nativeObj); // C++: void cv::meanStdDev(Mat src, vector_double& mean, vector_double& stddev, Mat mask = Mat()) private static native void meanStdDev_0(long src_nativeObj, long mean_mat_nativeObj, long stddev_mat_nativeObj, long mask_nativeObj); - private static native void meanStdDev_1(long src_nativeObj, long mean_mat_nativeObj, long stddev_mat_nativeObj); // C++: double cv::norm(Mat src1, int normType = NORM_L2, Mat mask = Mat()) private static native double norm_0(long src1_nativeObj, int normType, long mask_nativeObj); - private static native double norm_1(long src1_nativeObj, int normType); - private static native double norm_2(long src1_nativeObj); // C++: double cv::norm(Mat src1, Mat src2, int normType = NORM_L2, Mat mask = Mat()) private static native double norm_3(long src1_nativeObj, long src2_nativeObj, int normType, long mask_nativeObj); - private static native double norm_4(long src1_nativeObj, long src2_nativeObj, int normType); - private static native double norm_5(long src1_nativeObj, long src2_nativeObj); // C++: double cv::PSNR(Mat src1, Mat src2, double R = 255.) private static native double PSNR_0(long src1_nativeObj, long src2_nativeObj, double R); - private static native double PSNR_1(long src1_nativeObj, long src2_nativeObj); // C++: void cv::batchDistance(Mat src1, Mat src2, Mat& dist, int dtype, Mat& nidx, int normType = NORM_L2, int K = 0, Mat mask = Mat(), int update = 0, bool crosscheck = false) private static native void batchDistance_0(long src1_nativeObj, long src2_nativeObj, long dist_nativeObj, int dtype, long nidx_nativeObj, int normType, int K, long mask_nativeObj, int update, boolean crosscheck); - private static native void batchDistance_1(long src1_nativeObj, long src2_nativeObj, long dist_nativeObj, int dtype, long nidx_nativeObj, int normType, int K, long mask_nativeObj, int update); - private static native void batchDistance_2(long src1_nativeObj, long src2_nativeObj, long dist_nativeObj, int dtype, long nidx_nativeObj, int normType, int K, long mask_nativeObj); - private static native void batchDistance_3(long src1_nativeObj, long src2_nativeObj, long dist_nativeObj, int dtype, long nidx_nativeObj, int normType, int K); - private static native void batchDistance_4(long src1_nativeObj, long src2_nativeObj, long dist_nativeObj, int dtype, long nidx_nativeObj, int normType); - private static native void batchDistance_5(long src1_nativeObj, long src2_nativeObj, long dist_nativeObj, int dtype, long nidx_nativeObj); // C++: void cv::normalize(Mat src, Mat& dst, double alpha = 1, double beta = 0, int norm_type = NORM_L2, int dtype = -1, Mat mask = Mat()) private static native void normalize_0(long src_nativeObj, long dst_nativeObj, double alpha, double beta, int norm_type, int dtype, long mask_nativeObj); - private static native void normalize_1(long src_nativeObj, long dst_nativeObj, double alpha, double beta, int norm_type, int dtype); - private static native void normalize_2(long src_nativeObj, long dst_nativeObj, double alpha, double beta, int norm_type); - private static native void normalize_3(long src_nativeObj, long dst_nativeObj, double alpha, double beta); - private static native void normalize_4(long src_nativeObj, long dst_nativeObj, double alpha); - private static native void normalize_5(long src_nativeObj, long dst_nativeObj); // C++: void cv::reduceArgMin(Mat src, Mat& dst, int axis, bool lastIndex = false) private static native void reduceArgMin_0(long src_nativeObj, long dst_nativeObj, int axis, boolean lastIndex); - private static native void reduceArgMin_1(long src_nativeObj, long dst_nativeObj, int axis); // C++: void cv::reduceArgMax(Mat src, Mat& dst, int axis, bool lastIndex = false) private static native void reduceArgMax_0(long src_nativeObj, long dst_nativeObj, int axis, boolean lastIndex); - private static native void reduceArgMax_1(long src_nativeObj, long dst_nativeObj, int axis); // C++: void cv::reduce(Mat src, Mat& dst, int dim, int rtype, int dtype = -1) private static native void reduce_0(long src_nativeObj, long dst_nativeObj, int dim, int rtype, int dtype); - private static native void reduce_1(long src_nativeObj, long dst_nativeObj, int dim, int rtype); // C++: void cv::merge(vector_Mat mv, Mat& dst) @@ -6203,6 +6123,9 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::flipND(Mat src, Mat& dst, int axis) private static native void flipND_0(long src_nativeObj, long dst_nativeObj, int axis); + // C++: void cv::broadcast(Mat src, Mat shape, Mat& dst) + private static native void broadcast_0(long src_nativeObj, long shape_nativeObj, long dst_nativeObj); + // C++: void cv::rotate(Mat src, Mat& dst, int rotateCode) private static native void rotate_0(long src_nativeObj, long dst_nativeObj, int rotateCode); @@ -6217,22 +6140,18 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::bitwise_and(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) private static native void bitwise_and_0(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, long mask_nativeObj); - private static native void bitwise_and_1(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj); // C++: void cv::bitwise_or(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) private static native void bitwise_or_0(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, long mask_nativeObj); - private static native void bitwise_or_1(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj); // C++: void cv::bitwise_xor(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) private static native void bitwise_xor_0(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, long mask_nativeObj); - private static native void bitwise_xor_1(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj); // C++: void cv::bitwise_not(Mat src, Mat& dst, Mat mask = Mat()) private static native void bitwise_not_0(long src_nativeObj, long dst_nativeObj, long mask_nativeObj); - private static native void bitwise_not_1(long src_nativeObj, long dst_nativeObj); // C++: void cv::absdiff(Mat src1, Mat src2, Mat& dst) @@ -6267,17 +6186,14 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::polarToCart(Mat magnitude, Mat angle, Mat& x, Mat& y, bool angleInDegrees = false) private static native void polarToCart_0(long magnitude_nativeObj, long angle_nativeObj, long x_nativeObj, long y_nativeObj, boolean angleInDegrees); - private static native void polarToCart_1(long magnitude_nativeObj, long angle_nativeObj, long x_nativeObj, long y_nativeObj); // C++: void cv::cartToPolar(Mat x, Mat y, Mat& magnitude, Mat& angle, bool angleInDegrees = false) private static native void cartToPolar_0(long x_nativeObj, long y_nativeObj, long magnitude_nativeObj, long angle_nativeObj, boolean angleInDegrees); - private static native void cartToPolar_1(long x_nativeObj, long y_nativeObj, long magnitude_nativeObj, long angle_nativeObj); // C++: void cv::phase(Mat x, Mat y, Mat& angle, bool angleInDegrees = false) private static native void phase_0(long x_nativeObj, long y_nativeObj, long angle_nativeObj, boolean angleInDegrees); - private static native void phase_1(long x_nativeObj, long y_nativeObj, long angle_nativeObj); // C++: void cv::magnitude(Mat x, Mat y, Mat& magnitude) @@ -6285,30 +6201,22 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: bool cv::checkRange(Mat a, bool quiet = true, _hidden_ * pos = 0, double minVal = -DBL_MAX, double maxVal = DBL_MAX) private static native boolean checkRange_0(long a_nativeObj, boolean quiet, double minVal, double maxVal); - private static native boolean checkRange_1(long a_nativeObj, boolean quiet, double minVal); - private static native boolean checkRange_2(long a_nativeObj, boolean quiet); - private static native boolean checkRange_4(long a_nativeObj); // C++: void cv::patchNaNs(Mat& a, double val = 0) private static native void patchNaNs_0(long a_nativeObj, double val); - private static native void patchNaNs_1(long a_nativeObj); // C++: void cv::gemm(Mat src1, Mat src2, double alpha, Mat src3, double beta, Mat& dst, int flags = 0) private static native void gemm_0(long src1_nativeObj, long src2_nativeObj, double alpha, long src3_nativeObj, double beta, long dst_nativeObj, int flags); - private static native void gemm_1(long src1_nativeObj, long src2_nativeObj, double alpha, long src3_nativeObj, double beta, long dst_nativeObj); // C++: void cv::mulTransposed(Mat src, Mat& dst, bool aTa, Mat delta = Mat(), double scale = 1, int dtype = -1) private static native void mulTransposed_0(long src_nativeObj, long dst_nativeObj, boolean aTa, long delta_nativeObj, double scale, int dtype); - private static native void mulTransposed_1(long src_nativeObj, long dst_nativeObj, boolean aTa, long delta_nativeObj, double scale); - private static native void mulTransposed_2(long src_nativeObj, long dst_nativeObj, boolean aTa, long delta_nativeObj); - private static native void mulTransposed_3(long src_nativeObj, long dst_nativeObj, boolean aTa); // C++: void cv::transpose(Mat src, Mat& dst) @@ -6325,12 +6233,10 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::completeSymm(Mat& m, bool lowerToUpper = false) private static native void completeSymm_0(long m_nativeObj, boolean lowerToUpper); - private static native void completeSymm_1(long m_nativeObj); // C++: void cv::setIdentity(Mat& mtx, Scalar s = Scalar(1)) private static native void setIdentity_0(long mtx_nativeObj, double s_val0, double s_val1, double s_val2, double s_val3); - private static native void setIdentity_1(long mtx_nativeObj); // C++: double cv::determinant(Mat mtx) @@ -6341,12 +6247,10 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: double cv::invert(Mat src, Mat& dst, int flags = DECOMP_LU) private static native double invert_0(long src_nativeObj, long dst_nativeObj, int flags); - private static native double invert_1(long src_nativeObj, long dst_nativeObj); // C++: bool cv::solve(Mat src1, Mat src2, Mat& dst, int flags = DECOMP_LU) private static native boolean solve_0(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, int flags); - private static native boolean solve_1(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj); // C++: void cv::sort(Mat src, Mat& dst, int flags) @@ -6360,12 +6264,10 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: double cv::solvePoly(Mat coeffs, Mat& roots, int maxIters = 300) private static native double solvePoly_0(long coeffs_nativeObj, long roots_nativeObj, int maxIters); - private static native double solvePoly_1(long coeffs_nativeObj, long roots_nativeObj); // C++: bool cv::eigen(Mat src, Mat& eigenvalues, Mat& eigenvectors = Mat()) private static native boolean eigen_0(long src_nativeObj, long eigenvalues_nativeObj, long eigenvectors_nativeObj); - private static native boolean eigen_1(long src_nativeObj, long eigenvalues_nativeObj); // C++: void cv::eigenNonSymmetric(Mat src, Mat& eigenvalues, Mat& eigenvectors) @@ -6373,17 +6275,14 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::calcCovarMatrix(Mat samples, Mat& covar, Mat& mean, int flags, int ctype = CV_64F) private static native void calcCovarMatrix_0(long samples_nativeObj, long covar_nativeObj, long mean_nativeObj, int flags, int ctype); - private static native void calcCovarMatrix_1(long samples_nativeObj, long covar_nativeObj, long mean_nativeObj, int flags); // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, int maxComponents = 0) private static native void PCACompute_0(long data_nativeObj, long mean_nativeObj, long eigenvectors_nativeObj, int maxComponents); - private static native void PCACompute_1(long data_nativeObj, long mean_nativeObj, long eigenvectors_nativeObj); // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, Mat& eigenvalues, int maxComponents = 0) private static native void PCACompute2_0(long data_nativeObj, long mean_nativeObj, long eigenvectors_nativeObj, long eigenvalues_nativeObj, int maxComponents); - private static native void PCACompute2_1(long data_nativeObj, long mean_nativeObj, long eigenvectors_nativeObj, long eigenvalues_nativeObj); // C++: void cv::PCACompute(Mat data, Mat& mean, Mat& eigenvectors, double retainedVariance) @@ -6400,7 +6299,6 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::SVDecomp(Mat src, Mat& w, Mat& u, Mat& vt, int flags = 0) private static native void SVDecomp_0(long src_nativeObj, long w_nativeObj, long u_nativeObj, long vt_nativeObj, int flags); - private static native void SVDecomp_1(long src_nativeObj, long w_nativeObj, long u_nativeObj, long vt_nativeObj); // C++: void cv::SVBackSubst(Mat w, Mat u, Mat vt, Mat rhs, Mat& dst) @@ -6411,31 +6309,24 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::dft(Mat src, Mat& dst, int flags = 0, int nonzeroRows = 0) private static native void dft_0(long src_nativeObj, long dst_nativeObj, int flags, int nonzeroRows); - private static native void dft_1(long src_nativeObj, long dst_nativeObj, int flags); - private static native void dft_2(long src_nativeObj, long dst_nativeObj); // C++: void cv::idft(Mat src, Mat& dst, int flags = 0, int nonzeroRows = 0) private static native void idft_0(long src_nativeObj, long dst_nativeObj, int flags, int nonzeroRows); - private static native void idft_1(long src_nativeObj, long dst_nativeObj, int flags); - private static native void idft_2(long src_nativeObj, long dst_nativeObj); // C++: void cv::dct(Mat src, Mat& dst, int flags = 0) private static native void dct_0(long src_nativeObj, long dst_nativeObj, int flags); - private static native void dct_1(long src_nativeObj, long dst_nativeObj); // C++: void cv::idct(Mat src, Mat& dst, int flags = 0) private static native void idct_0(long src_nativeObj, long dst_nativeObj, int flags); - private static native void idct_1(long src_nativeObj, long dst_nativeObj); // C++: void cv::mulSpectrums(Mat a, Mat b, Mat& c, int flags, bool conjB = false) private static native void mulSpectrums_0(long a_nativeObj, long b_nativeObj, long c_nativeObj, int flags, boolean conjB); - private static native void mulSpectrums_1(long a_nativeObj, long b_nativeObj, long c_nativeObj, int flags); // C++: int cv::getOptimalDFTSize(int vecsize) @@ -6452,20 +6343,18 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::randShuffle(Mat& dst, double iterFactor = 1., RNG* rng = 0) private static native void randShuffle_0(long dst_nativeObj, double iterFactor); - private static native void randShuffle_2(long dst_nativeObj); // C++: double cv::kmeans(Mat data, int K, Mat& bestLabels, TermCriteria criteria, int attempts, int flags, Mat& centers = Mat()) private static native double kmeans_0(long data_nativeObj, int K, long bestLabels_nativeObj, int criteria_type, int criteria_maxCount, double criteria_epsilon, int attempts, int flags, long centers_nativeObj); - private static native double kmeans_1(long data_nativeObj, int K, long bestLabels_nativeObj, int criteria_type, int criteria_maxCount, double criteria_epsilon, int attempts, int flags); - // C++: int cv::getNumThreads() - private static native int getNumThreads_0(); - // C++: void cv::setNumThreads(int nthreads) private static native void setNumThreads_0(int nthreads); + // C++: int cv::getNumThreads() + private static native int getNumThreads_0(); + // C++: int cv::getThreadNum() private static native int getThreadNum_0(); @@ -6513,14 +6402,11 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: String cv::samples::findFile(String relative_path, bool required = true, bool silentMode = false) private static native String findFile_0(String relative_path, boolean required, boolean silentMode); - private static native String findFile_1(String relative_path, boolean required); - private static native String findFile_2(String relative_path); // C++: String cv::samples::findFileOrKeep(String relative_path, bool silentMode = false) private static native String findFileOrKeep_0(String relative_path, boolean silentMode); - private static native String findFileOrKeep_1(String relative_path); // C++: void cv::samples::addSamplesDataSearchPath(String path) @@ -6534,30 +6420,22 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::add(Mat src1, Scalar src2, Mat& dst, Mat mask = Mat(), int dtype = -1) private static native void add_3(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj, long mask_nativeObj, int dtype); - private static native void add_4(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj, long mask_nativeObj); - private static native void add_5(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj); // C++: void cv::subtract(Mat src1, Scalar src2, Mat& dst, Mat mask = Mat(), int dtype = -1) private static native void subtract_3(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj, long mask_nativeObj, int dtype); - private static native void subtract_4(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj, long mask_nativeObj); - private static native void subtract_5(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj); // C++: void cv::multiply(Mat src1, Scalar src2, Mat& dst, double scale = 1, int dtype = -1) private static native void multiply_3(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj, double scale, int dtype); - private static native void multiply_4(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj, double scale); - private static native void multiply_5(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj); // C++: void cv::divide(Mat src1, Scalar src2, Mat& dst, double scale = 1, int dtype = -1) private static native void divide_5(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj, double scale, int dtype); - private static native void divide_6(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj, double scale); - private static native void divide_7(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj); // C++: void cv::absdiff(Mat src1, Scalar src2, Mat& dst) @@ -6571,25 +6449,6 @@ public static MinMaxLocResult minMaxLoc(Mat src) { // C++: void cv::max(Mat src1, Scalar src2, Mat& dst) private static native void max_1(long src1_nativeObj, double src2_val0, double src2_val1, double src2_val2, double src2_val3, long dst_nativeObj); - - private static native double[] n_minMaxLocManual(long src_nativeObj, long mask_nativeObj); - - // manual port - public static class MinMaxLocResult { - public double minVal; - public double maxVal; - public Point minLoc; - public Point maxLoc; - - - public MinMaxLocResult() { - minVal = 0; - maxVal = 0; - minLoc = new Point(); - maxLoc = new Point(); - } - } - - +private static native double[] n_minMaxLocManual(long src_nativeObj, long mask_nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/core/CvType.java b/bus-opencv/src/main/java/org/opencv/core/CvType.java index c415254590..fcf616fe02 100644 --- a/bus-opencv/src/main/java/org/opencv/core/CvType.java +++ b/bus-opencv/src/main/java/org/opencv/core/CvType.java @@ -18,7 +18,7 @@ public final class CvType { */ @Deprecated public static final int CV_USRTYPE1 = CV_16F; - private static final int CV_CN_MAX = 512, CV_CN_SHIFT = 3, CV_DEPTH_MAX = (1 << CV_CN_SHIFT); + // predefined type constants public static final int CV_8UC1 = CV_8UC(1), CV_8UC2 = CV_8UC(2), CV_8UC3 = CV_8UC(3), CV_8UC4 = CV_8UC(4), @@ -30,6 +30,8 @@ public final class CvType { CV_64FC1 = CV_64FC(1), CV_64FC2 = CV_64FC(2), CV_64FC3 = CV_64FC(3), CV_64FC4 = CV_64FC(4), CV_16FC1 = CV_16FC(1), CV_16FC2 = CV_16FC(2), CV_16FC3 = CV_16FC(3), CV_16FC4 = CV_16FC(4); + private static final int CV_CN_MAX = 512, CV_CN_SHIFT = 3, CV_DEPTH_MAX = (1 << CV_CN_SHIFT); + public static final int makeType(int depth, int channels) { if (channels <= 0 || channels >= CV_CN_MAX) { throw new UnsupportedOperationException( @@ -88,54 +90,54 @@ public static final boolean isInteger(int type) { public static final int ELEM_SIZE(int type) { switch (depth(type)) { - case CV_8U: - case CV_8S: - return channels(type); - case CV_16U: - case CV_16S: - case CV_16F: - return 2 * channels(type); - case CV_32S: - case CV_32F: - return 4 * channels(type); - case CV_64F: - return 8 * channels(type); - default: - throw new UnsupportedOperationException( - "Unsupported CvType value: " + type); + case CV_8U: + case CV_8S: + return channels(type); + case CV_16U: + case CV_16S: + case CV_16F: + return 2 * channels(type); + case CV_32S: + case CV_32F: + return 4 * channels(type); + case CV_64F: + return 8 * channels(type); + default: + throw new UnsupportedOperationException( + "Unsupported CvType value: " + type); } } public static final String typeToString(int type) { String s; switch (depth(type)) { - case CV_8U: - s = "CV_8U"; - break; - case CV_8S: - s = "CV_8S"; - break; - case CV_16U: - s = "CV_16U"; - break; - case CV_16S: - s = "CV_16S"; - break; - case CV_32S: - s = "CV_32S"; - break; - case CV_32F: - s = "CV_32F"; - break; - case CV_64F: - s = "CV_64F"; - break; - case CV_16F: - s = "CV_16F"; - break; - default: - throw new UnsupportedOperationException( - "Unsupported CvType value: " + type); + case CV_8U: + s = "CV_8U"; + break; + case CV_8S: + s = "CV_8S"; + break; + case CV_16U: + s = "CV_16U"; + break; + case CV_16S: + s = "CV_16S"; + break; + case CV_32S: + s = "CV_32S"; + break; + case CV_32F: + s = "CV_32F"; + break; + case CV_64F: + s = "CV_64F"; + break; + case CV_16F: + s = "CV_16F"; + break; + default: + throw new UnsupportedOperationException( + "Unsupported CvType value: " + type); } int ch = channels(type); diff --git a/bus-opencv/src/main/java/org/opencv/core/Mat.java b/bus-opencv/src/main/java/org/opencv/core/Mat.java index 157bd15c37..51cda595b5 100644 --- a/bus-opencv/src/main/java/org/opencv/core/Mat.java +++ b/bus-opencv/src/main/java/org/opencv/core/Mat.java @@ -1,10 +1,13 @@ package org.opencv.core; +import java.lang.ref.Cleaner; import java.nio.ByteBuffer; // C++: class Mat //javadoc: Mat public class Mat { + // A native memory cleaner for the OpenCV library + public static final Cleaner cleaner = Cleaner.create(); public final long nativeObj; @@ -12,6 +15,7 @@ public Mat(long addr) { if (addr == 0) throw new UnsupportedOperationException("Native object address is NULL"); nativeObj = addr; + registerCleaner(); } // @@ -20,7 +24,8 @@ public Mat(long addr) { // javadoc: Mat::Mat() public Mat() { - this(n_Mat()); + nativeObj = n_Mat(); + registerCleaner(); } // @@ -29,7 +34,8 @@ public Mat() { // javadoc: Mat::Mat(rows, cols, type) public Mat(int rows, int cols, int type) { - this(n_Mat(rows, cols, type)); + nativeObj = n_Mat(rows, cols, type); + registerCleaner(); } // @@ -38,7 +44,8 @@ public Mat(int rows, int cols, int type) { // javadoc: Mat::Mat(rows, cols, type, data) public Mat(int rows, int cols, int type, ByteBuffer data) { - this(n_Mat(rows, cols, type, data)); + nativeObj = n_Mat(rows, cols, type, data); + registerCleaner(); } // @@ -47,7 +54,8 @@ public Mat(int rows, int cols, int type, ByteBuffer data) { // javadoc: Mat::Mat(rows, cols, type, data, step) public Mat(int rows, int cols, int type, ByteBuffer data, long step) { - this(n_Mat(rows, cols, type, data, step)); + nativeObj = n_Mat(rows, cols, type, data, step); + registerCleaner(); } // @@ -56,7 +64,8 @@ public Mat(int rows, int cols, int type, ByteBuffer data, long step) { // javadoc: Mat::Mat(size, type) public Mat(Size size, int type) { - this(n_Mat(size.width, size.height, type)); + nativeObj = n_Mat(size.width, size.height, type); + registerCleaner(); } // @@ -65,7 +74,8 @@ public Mat(Size size, int type) { // javadoc: Mat::Mat(sizes, type) public Mat(int[] sizes, int type) { - this(n_Mat(sizes.length, sizes, type)); + nativeObj = n_Mat(sizes.length, sizes, type); + registerCleaner(); } // @@ -74,7 +84,8 @@ public Mat(int[] sizes, int type) { // javadoc: Mat::Mat(rows, cols, type, s) public Mat(int rows, int cols, int type, Scalar s) { - this(n_Mat(rows, cols, type, s.val[0], s.val[1], s.val[2], s.val[3])); + nativeObj = n_Mat(rows, cols, type, s.val[0], s.val[1], s.val[2], s.val[3]); + registerCleaner(); } // @@ -83,7 +94,8 @@ public Mat(int rows, int cols, int type, Scalar s) { // javadoc: Mat::Mat(size, type, s) public Mat(Size size, int type, Scalar s) { - this(n_Mat(size.width, size.height, type, s.val[0], s.val[1], s.val[2], s.val[3])); + nativeObj = n_Mat(size.width, size.height, type, s.val[0], s.val[1], s.val[2], s.val[3]); + registerCleaner(); } // @@ -92,7 +104,8 @@ public Mat(Size size, int type, Scalar s) { // javadoc: Mat::Mat(sizes, type, s) public Mat(int[] sizes, int type, Scalar s) { - this(n_Mat(sizes.length, sizes, type, s.val[0], s.val[1], s.val[2], s.val[3])); + nativeObj = n_Mat(sizes.length, sizes, type, s.val[0], s.val[1], s.val[2], s.val[3]); + registerCleaner(); } // @@ -101,12 +114,14 @@ public Mat(int[] sizes, int type, Scalar s) { // javadoc: Mat::Mat(m, rowRange, colRange) public Mat(Mat m, Range rowRange, Range colRange) { - this(n_Mat(m.nativeObj, rowRange.start, rowRange.end, colRange.start, colRange.end)); + nativeObj = n_Mat(m.nativeObj, rowRange.start, rowRange.end, colRange.start, colRange.end); + registerCleaner(); } // javadoc: Mat::Mat(m, rowRange) public Mat(Mat m, Range rowRange) { - this(n_Mat(m.nativeObj, rowRange.start, rowRange.end)); + nativeObj = n_Mat(m.nativeObj, rowRange.start, rowRange.end); + registerCleaner(); } // @@ -115,7 +130,8 @@ public Mat(Mat m, Range rowRange) { // javadoc: Mat::Mat(m, ranges) public Mat(Mat m, Range[] ranges) { - this(n_Mat(m.nativeObj, ranges)); + nativeObj = n_Mat(m.nativeObj, ranges); + registerCleaner(); } // @@ -124,39 +140,46 @@ public Mat(Mat m, Range[] ranges) { // javadoc: Mat::Mat(m, roi) public Mat(Mat m, Rect roi) { - this(n_Mat(m.nativeObj, roi.y, roi.y + roi.height, roi.x, roi.x + roi.width)); + nativeObj = n_Mat(m.nativeObj, roi.y, roi.y + roi.height, roi.x, roi.x + roi.width); + registerCleaner(); + } + + protected void registerCleaner(){ + // The n_delete action must not refer to the object being registered. So, do not use nativeObj directly. + long nativeObjCopy = nativeObj; + cleaner.register(this, () -> n_delete(nativeObjCopy)); } // // C++: Mat Mat::adjustROI(int dtop, int dbottom, int dleft, int dright) // - // javadoc: Mat::diag(d) - public static Mat diag(Mat d) { - return new Mat(n_diag(d.nativeObj)); + // javadoc: Mat::adjustROI(dtop, dbottom, dleft, dright) + public Mat adjustROI(int dtop, int dbottom, int dleft, int dright) { + return new Mat(n_adjustROI(nativeObj, dtop, dbottom, dleft, dright)); } // // C++: void Mat::assignTo(Mat m, int type = -1) // - // javadoc: Mat::eye(rows, cols, type) - public static Mat eye(int rows, int cols, int type) { - return new Mat(n_eye(rows, cols, type)); + // javadoc: Mat::assignTo(m, type) + public void assignTo(Mat m, int type) { + n_assignTo(nativeObj, m.nativeObj, type); } - // javadoc: Mat::eye(size, type) - public static Mat eye(Size size, int type) { - return new Mat(n_eye(size.width, size.height, type)); + // javadoc: Mat::assignTo(m) + public void assignTo(Mat m) { + n_assignTo(nativeObj, m.nativeObj); } // // C++: int Mat::channels() // - // javadoc: Mat::ones(rows, cols, type) - public static Mat ones(int rows, int cols, int type) { - return new Mat(n_ones(rows, cols, type)); + // javadoc: Mat::channels() + public int channels() { + return n_channels(nativeObj); } // @@ -164,947 +187,655 @@ public static Mat ones(int rows, int cols, int type) { // requireContinuous = true) // - // javadoc: Mat::ones(size, type) - public static Mat ones(Size size, int type) { - return new Mat(n_ones(size.width, size.height, type)); + // javadoc: Mat::checkVector(elemChannels, depth, requireContinuous) + public int checkVector(int elemChannels, int depth, boolean requireContinuous) { + return n_checkVector(nativeObj, elemChannels, depth, requireContinuous); } - // javadoc: Mat::ones(sizes, type) - public static Mat ones(int[] sizes, int type) { - return new Mat(n_ones(sizes.length, sizes, type)); + // javadoc: Mat::checkVector(elemChannels, depth) + public int checkVector(int elemChannels, int depth) { + return n_checkVector(nativeObj, elemChannels, depth); } - // javadoc: Mat::zeros(rows, cols, type) - public static Mat zeros(int rows, int cols, int type) { - return new Mat(n_zeros(rows, cols, type)); + // javadoc: Mat::checkVector(elemChannels) + public int checkVector(int elemChannels) { + return n_checkVector(nativeObj, elemChannels); } // // C++: Mat Mat::clone() // - // javadoc: Mat::zeros(size, type) - public static Mat zeros(Size size, int type) { - return new Mat(n_zeros(size.width, size.height, type)); + // javadoc: Mat::clone() + public Mat clone() { + return new Mat(n_clone(nativeObj)); } // // C++: Mat Mat::col(int x) // - // javadoc: Mat::zeros(sizes, type) - public static Mat zeros(int[] sizes, int type) { - return new Mat(n_zeros(sizes.length, sizes, type)); + // javadoc: Mat::col(x) + public Mat col(int x) { + return new Mat(n_col(nativeObj, x)); } // // C++: Mat Mat::colRange(int startcol, int endcol) // - // C++: Mat::Mat() - private static native long n_Mat(); + // javadoc: Mat::colRange(startcol, endcol) + public Mat colRange(int startcol, int endcol) { + return new Mat(n_colRange(nativeObj, startcol, endcol)); + } // // C++: Mat Mat::colRange(Range r) // - // C++: Mat::Mat(int rows, int cols, int type) - private static native long n_Mat(int rows, int cols, int type); + // javadoc: Mat::colRange(r) + public Mat colRange(Range r) { + return new Mat(n_colRange(nativeObj, r.start, r.end)); + } // // C++: int Mat::dims() // - // C++: Mat::Mat(int ndims, const int* sizes, int type) - private static native long n_Mat(int ndims, int[] sizes, int type); + // javadoc: Mat::dims() + public int dims() { + return n_dims(nativeObj); + } // // C++: int Mat::cols() // - // C++: Mat::Mat(int rows, int cols, int type, void* data) - private static native long n_Mat(int rows, int cols, int type, ByteBuffer data); + // javadoc: Mat::cols() + public int cols() { + return n_cols(nativeObj); + } // // C++: void Mat::convertTo(Mat& m, int rtype, double alpha = 1, double beta // = 0) // - // C++: Mat::Mat(int rows, int cols, int type, void* data, size_t step) - private static native long n_Mat(int rows, int cols, int type, ByteBuffer data, long step); + // javadoc: Mat::convertTo(m, rtype, alpha, beta) + public void convertTo(Mat m, int rtype, double alpha, double beta) { + n_convertTo(nativeObj, m.nativeObj, rtype, alpha, beta); + } - // C++: Mat::Mat(Size size, int type) - private static native long n_Mat(double size_width, double size_height, int type); + // javadoc: Mat::convertTo(m, rtype, alpha) + public void convertTo(Mat m, int rtype, double alpha) { + n_convertTo(nativeObj, m.nativeObj, rtype, alpha); + } - // C++: Mat::Mat(int rows, int cols, int type, Scalar s) - private static native long n_Mat(int rows, int cols, int type, double s_val0, double s_val1, double s_val2, double s_val3); + // javadoc: Mat::convertTo(m, rtype) + public void convertTo(Mat m, int rtype) { + n_convertTo(nativeObj, m.nativeObj, rtype); + } // // C++: void Mat::copyTo(Mat& m) // - // C++: Mat::Mat(Size size, int type, Scalar s) - private static native long n_Mat(double size_width, double size_height, int type, double s_val0, double s_val1, double s_val2, double s_val3); + // javadoc: Mat::copyTo(m) + public void copyTo(Mat m) { + n_copyTo(nativeObj, m.nativeObj); + } // // C++: void Mat::copyTo(Mat& m, Mat mask) // - // C++: Mat::Mat(int ndims, const int* sizes, int type, Scalar s) - private static native long n_Mat(int ndims, int[] sizes, int type, double s_val0, double s_val1, double s_val2, double s_val3); + // javadoc: Mat::copyTo(m, mask) + public void copyTo(Mat m, Mat mask) { + n_copyTo(nativeObj, m.nativeObj, mask.nativeObj); + } // // C++: void Mat::create(int rows, int cols, int type) // - // C++: Mat::Mat(Mat m, Range rowRange, Range colRange = Range::all()) - private static native long n_Mat(long m_nativeObj, int rowRange_start, int rowRange_end, int colRange_start, int colRange_end); + // javadoc: Mat::create(rows, cols, type) + public void create(int rows, int cols, int type) { + n_create(nativeObj, rows, cols, type); + } // // C++: void Mat::create(Size size, int type) // - private static native long n_Mat(long m_nativeObj, int rowRange_start, int rowRange_end); + // javadoc: Mat::create(size, type) + public void create(Size size, int type) { + n_create(nativeObj, size.width, size.height, type); + } // // C++: void Mat::create(int ndims, const int* sizes, int type) // - // C++: Mat::Mat(const Mat& m, const std::vector& ranges) - private static native long n_Mat(long m_nativeObj, Range[] ranges); + // javadoc: Mat::create(sizes, type) + public void create(int[] sizes, int type) { + n_create(nativeObj, sizes.length, sizes, type); + } // // C++: void Mat::copySize(const Mat& m); // - // C++: Mat Mat::adjustROI(int dtop, int dbottom, int dleft, int dright) - private static native long n_adjustROI(long nativeObj, int dtop, int dbottom, int dleft, int dright); + // javadoc: Mat::copySize(m) + public void copySize(Mat m) { + n_copySize(nativeObj, m.nativeObj); + } // // C++: Mat Mat::cross(Mat m) // - // C++: void Mat::assignTo(Mat m, int type = -1) - private static native void n_assignTo(long nativeObj, long m_nativeObj, int type); + // javadoc: Mat::cross(m) + public Mat cross(Mat m) { + return new Mat(n_cross(nativeObj, m.nativeObj)); + } // // C++: long Mat::dataAddr() // - private static native void n_assignTo(long nativeObj, long m_nativeObj); + // javadoc: Mat::dataAddr() + public long dataAddr() { + return n_dataAddr(nativeObj); + } // // C++: int Mat::depth() // - // C++: int Mat::channels() - private static native int n_channels(long nativeObj); + // javadoc: Mat::depth() + public int depth() { + return n_depth(nativeObj); + } // // C++: Mat Mat::diag(int d = 0) // - // C++: int Mat::checkVector(int elemChannels, int depth = -1, bool - // requireContinuous = true) - private static native int n_checkVector(long nativeObj, int elemChannels, int depth, boolean requireContinuous); + // javadoc: Mat::diag(d) + public Mat diag(int d) { + return new Mat(n_diag(nativeObj, d)); + } - private static native int n_checkVector(long nativeObj, int elemChannels, int depth); + // javadoc: Mat::diag() + public Mat diag() { + return new Mat(n_diag(nativeObj, 0)); + } // // C++: static Mat Mat::diag(Mat d) // - private static native int n_checkVector(long nativeObj, int elemChannels); + // javadoc: Mat::diag(d) + public static Mat diag(Mat d) { + return new Mat(n_diag(d.nativeObj)); + } // // C++: double Mat::dot(Mat m) // - // C++: Mat Mat::clone() - private static native long n_clone(long nativeObj); + // javadoc: Mat::dot(m) + public double dot(Mat m) { + return n_dot(nativeObj, m.nativeObj); + } // // C++: size_t Mat::elemSize() // - // C++: Mat Mat::col(int x) - private static native long n_col(long nativeObj, int x); + // javadoc: Mat::elemSize() + public long elemSize() { + return n_elemSize(nativeObj); + } // // C++: size_t Mat::elemSize1() // - // C++: Mat Mat::colRange(int startcol, int endcol) - private static native long n_colRange(long nativeObj, int startcol, int endcol); + // javadoc: Mat::elemSize1() + public long elemSize1() { + return n_elemSize1(nativeObj); + } // // C++: bool Mat::empty() // - // C++: int Mat::dims() - private static native int n_dims(long nativeObj); + // javadoc: Mat::empty() + public boolean empty() { + return n_empty(nativeObj); + } // // C++: static Mat Mat::eye(int rows, int cols, int type) // - // C++: int Mat::cols() - private static native int n_cols(long nativeObj); + // javadoc: Mat::eye(rows, cols, type) + public static Mat eye(int rows, int cols, int type) { + return new Mat(n_eye(rows, cols, type)); + } // // C++: static Mat Mat::eye(Size size, int type) // - // C++: void Mat::convertTo(Mat& m, int rtype, double alpha = 1, double beta - // = 0) - private static native void n_convertTo(long nativeObj, long m_nativeObj, int rtype, double alpha, double beta); + // javadoc: Mat::eye(size, type) + public static Mat eye(Size size, int type) { + return new Mat(n_eye(size.width, size.height, type)); + } // // C++: Mat Mat::inv(int method = DECOMP_LU) // - private static native void n_convertTo(long nativeObj, long m_nativeObj, int rtype, double alpha); + // javadoc: Mat::inv(method) + public Mat inv(int method) { + return new Mat(n_inv(nativeObj, method)); + } - private static native void n_convertTo(long nativeObj, long m_nativeObj, int rtype); + // javadoc: Mat::inv() + public Mat inv() { + return new Mat(n_inv(nativeObj)); + } // // C++: bool Mat::isContinuous() // - // C++: void Mat::copyTo(Mat& m) - private static native void n_copyTo(long nativeObj, long m_nativeObj); + // javadoc: Mat::isContinuous() + public boolean isContinuous() { + return n_isContinuous(nativeObj); + } // // C++: bool Mat::isSubmatrix() // - // C++: void Mat::copyTo(Mat& m, Mat mask) - private static native void n_copyTo(long nativeObj, long m_nativeObj, long mask_nativeObj); + // javadoc: Mat::isSubmatrix() + public boolean isSubmatrix() { + return n_isSubmatrix(nativeObj); + } // // C++: void Mat::locateROI(Size wholeSize, Point ofs) // - // C++: void Mat::create(int rows, int cols, int type) - private static native void n_create(long nativeObj, int rows, int cols, int type); + // javadoc: Mat::locateROI(wholeSize, ofs) + public void locateROI(Size wholeSize, Point ofs) { + double[] wholeSize_out = new double[2]; + double[] ofs_out = new double[2]; + locateROI_0(nativeObj, wholeSize_out, ofs_out); + if (wholeSize != null) { + wholeSize.width = wholeSize_out[0]; + wholeSize.height = wholeSize_out[1]; + } + if (ofs != null) { + ofs.x = ofs_out[0]; + ofs.y = ofs_out[1]; + } + } // // C++: Mat Mat::mul(Mat m, double scale = 1) // - // C++: void Mat::create(Size size, int type) - private static native void n_create(long nativeObj, double size_width, double size_height, int type); - - // C++: void Mat::create(int ndims, const int* sizes, int type) - private static native void n_create(long nativeObj, int ndims, int[] sizes, int type); + /** + * Element-wise multiplication with scale factor + * @param m operand with with which to perform element-wise multiplication + * @param scale scale factor + * @return reference to a new Mat object + */ + public Mat mul(Mat m, double scale) { + return new Mat(n_mul(nativeObj, m.nativeObj, scale)); + } - // C++: void Mat::copySize(const Mat& m) - private static native void n_copySize(long nativeObj, long m_nativeObj); + /** + * Element-wise multiplication + * @param m operand with with which to perform element-wise multiplication + * @return reference to a new Mat object + */ + public Mat mul(Mat m) { + return new Mat(n_mul(nativeObj, m.nativeObj)); + } + + /** + * Matrix multiplication + * @param m operand with with which to perform matrix multiplication + * @see Core#gemm(Mat, Mat, double, Mat, double, Mat, int) + * @return reference to a new Mat object + */ + public Mat matMul(Mat m) { + return new Mat(n_matMul(nativeObj, m.nativeObj)); + } // // C++: static Mat Mat::ones(int rows, int cols, int type) // - // C++: Mat Mat::cross(Mat m) - private static native long n_cross(long nativeObj, long m_nativeObj); + // javadoc: Mat::ones(rows, cols, type) + public static Mat ones(int rows, int cols, int type) { + return new Mat(n_ones(rows, cols, type)); + } // // C++: static Mat Mat::ones(Size size, int type) // - // C++: long Mat::dataAddr() - private static native long n_dataAddr(long nativeObj); + // javadoc: Mat::ones(size, type) + public static Mat ones(Size size, int type) { + return new Mat(n_ones(size.width, size.height, type)); + } // // C++: static Mat Mat::ones(int ndims, const int* sizes, int type) // - // C++: int Mat::depth() - private static native int n_depth(long nativeObj); + // javadoc: Mat::ones(sizes, type) + public static Mat ones(int[] sizes, int type) { + return new Mat(n_ones(sizes.length, sizes, type)); + } // // C++: void Mat::push_back(Mat m) // - // C++: Mat Mat::diag(int d = 0) - private static native long n_diag(long nativeObj, int d); + // javadoc: Mat::push_back(m) + public void push_back(Mat m) { + n_push_back(nativeObj, m.nativeObj); + } // // C++: void Mat::release() // - // C++: static Mat Mat::diag(Mat d) - private static native long n_diag(long d_nativeObj); + // javadoc: Mat::release() + public void release() { + n_release(nativeObj); + } // // C++: Mat Mat::reshape(int cn, int rows = 0) // - // C++: double Mat::dot(Mat m) - private static native double n_dot(long nativeObj, long m_nativeObj); + // javadoc: Mat::reshape(cn, rows) + public Mat reshape(int cn, int rows) { + return new Mat(n_reshape(nativeObj, cn, rows)); + } - // C++: size_t Mat::elemSize() - private static native long n_elemSize(long nativeObj); + // javadoc: Mat::reshape(cn) + public Mat reshape(int cn) { + return new Mat(n_reshape(nativeObj, cn)); + } // // C++: Mat Mat::reshape(int cn, int newndims, const int* newsz) // - // C++: size_t Mat::elemSize1() - private static native long n_elemSize1(long nativeObj); + // javadoc: Mat::reshape(cn, newshape) + public Mat reshape(int cn, int[] newshape) { + return new Mat(n_reshape_1(nativeObj, cn, newshape.length, newshape)); + } // // C++: Mat Mat::row(int y) // - // C++: bool Mat::empty() - private static native boolean n_empty(long nativeObj); + // javadoc: Mat::row(y) + public Mat row(int y) { + return new Mat(n_row(nativeObj, y)); + } // // C++: Mat Mat::rowRange(int startrow, int endrow) // - // C++: static Mat Mat::eye(int rows, int cols, int type) - private static native long n_eye(int rows, int cols, int type); + // javadoc: Mat::rowRange(startrow, endrow) + public Mat rowRange(int startrow, int endrow) { + return new Mat(n_rowRange(nativeObj, startrow, endrow)); + } // // C++: Mat Mat::rowRange(Range r) // - // C++: static Mat Mat::eye(Size size, int type) - private static native long n_eye(double size_width, double size_height, int type); + // javadoc: Mat::rowRange(r) + public Mat rowRange(Range r) { + return new Mat(n_rowRange(nativeObj, r.start, r.end)); + } // // C++: int Mat::rows() // - // C++: Mat Mat::inv(int method = DECOMP_LU) - private static native long n_inv(long nativeObj, int method); + // javadoc: Mat::rows() + public int rows() { + return n_rows(nativeObj); + } // // C++: Mat Mat::operator =(Scalar s) // - private static native long n_inv(long nativeObj); + // javadoc: Mat::operator =(s) + public Mat setTo(Scalar s) { + return new Mat(n_setTo(nativeObj, s.val[0], s.val[1], s.val[2], s.val[3])); + } // // C++: Mat Mat::setTo(Scalar value, Mat mask = Mat()) // - // C++: bool Mat::isContinuous() - private static native boolean n_isContinuous(long nativeObj); + // javadoc: Mat::setTo(value, mask) + public Mat setTo(Scalar value, Mat mask) { + return new Mat(n_setTo(nativeObj, value.val[0], value.val[1], value.val[2], value.val[3], mask.nativeObj)); + } // // C++: Mat Mat::setTo(Mat value, Mat mask = Mat()) // - // C++: bool Mat::isSubmatrix() - private static native boolean n_isSubmatrix(long nativeObj); + // javadoc: Mat::setTo(value, mask) + public Mat setTo(Mat value, Mat mask) { + return new Mat(n_setTo(nativeObj, value.nativeObj, mask.nativeObj)); + } - // C++: void Mat::locateROI(Size wholeSize, Point ofs) - private static native void locateROI_0(long nativeObj, double[] wholeSize_out, double[] ofs_out); + // javadoc: Mat::setTo(value) + public Mat setTo(Mat value) { + return new Mat(n_setTo(nativeObj, value.nativeObj)); + } // // C++: Size Mat::size() // - // C++: Mat Mat::mul(Mat m, double scale = 1) - private static native long n_mul(long nativeObj, long m_nativeObj, double scale); + // javadoc: Mat::size() + public Size size() { + return new Size(n_size(nativeObj)); + } // // C++: int Mat::size(int i) // - private static native long n_mul(long nativeObj, long m_nativeObj); + // javadoc: Mat::size(int i) + public int size(int i) { + return n_size_i(nativeObj, i); + } // // C++: size_t Mat::step1(int i = 0) // - private static native long n_matMul(long nativeObj, long m_nativeObj); + // javadoc: Mat::step1(i) + public long step1(int i) { + return n_step1(nativeObj, i); + } - // C++: static Mat Mat::ones(int rows, int cols, int type) - private static native long n_ones(int rows, int cols, int type); + // javadoc: Mat::step1() + public long step1() { + return n_step1(nativeObj); + } // // C++: Mat Mat::operator()(int rowStart, int rowEnd, int colStart, int // colEnd) // - // C++: static Mat Mat::ones(Size size, int type) - private static native long n_ones(double size_width, double size_height, int type); + // javadoc: Mat::operator()(rowStart, rowEnd, colStart, colEnd) + public Mat submat(int rowStart, int rowEnd, int colStart, int colEnd) { + return new Mat(n_submat_rr(nativeObj, rowStart, rowEnd, colStart, colEnd)); + } // // C++: Mat Mat::operator()(Range rowRange, Range colRange) // - // C++: static Mat Mat::ones(int ndims, const int* sizes, int type) - private static native long n_ones(int ndims, int[] sizes, int type); + // javadoc: Mat::operator()(rowRange, colRange) + public Mat submat(Range rowRange, Range colRange) { + return new Mat(n_submat_rr(nativeObj, rowRange.start, rowRange.end, colRange.start, colRange.end)); + } // // C++: Mat Mat::operator()(const std::vector& ranges) // - // C++: void Mat::push_back(Mat m) - private static native void n_push_back(long nativeObj, long m_nativeObj); + // javadoc: Mat::operator()(ranges[]) + public Mat submat(Range[] ranges) { + return new Mat(n_submat_ranges(nativeObj, ranges)); + } // // C++: Mat Mat::operator()(Rect roi) // - // C++: void Mat::release() - private static native void n_release(long nativeObj); + // javadoc: Mat::operator()(roi) + public Mat submat(Rect roi) { + return new Mat(n_submat(nativeObj, roi.x, roi.y, roi.width, roi.height)); + } // // C++: Mat Mat::t() // - // C++: Mat Mat::reshape(int cn, int rows = 0) - private static native long n_reshape(long nativeObj, int cn, int rows); + // javadoc: Mat::t() + public Mat t() { + return new Mat(n_t(nativeObj)); + } // // C++: size_t Mat::total() // - private static native long n_reshape(long nativeObj, int cn); + // javadoc: Mat::total() + public long total() { + return n_total(nativeObj); + } // // C++: int Mat::type() // - // C++: Mat Mat::reshape(int cn, int newndims, const int* newsz) - private static native long n_reshape_1(long nativeObj, int cn, int newndims, int[] newsz); + // javadoc: Mat::type() + public int type() { + return n_type(nativeObj); + } // // C++: static Mat Mat::zeros(int rows, int cols, int type) // - // C++: Mat Mat::row(int y) - private static native long n_row(long nativeObj, int y); + // javadoc: Mat::zeros(rows, cols, type) + public static Mat zeros(int rows, int cols, int type) { + return new Mat(n_zeros(rows, cols, type)); + } // // C++: static Mat Mat::zeros(Size size, int type) // - // C++: Mat Mat::rowRange(int startrow, int endrow) - private static native long n_rowRange(long nativeObj, int startrow, int endrow); + // javadoc: Mat::zeros(size, type) + public static Mat zeros(Size size, int type) { + return new Mat(n_zeros(size.width, size.height, type)); + } // // C++: static Mat Mat::zeros(int ndims, const int* sizes, int type) // - // C++: int Mat::rows() - private static native int n_rows(long nativeObj); - - // C++: Mat Mat::operator =(Scalar s) - private static native long n_setTo(long nativeObj, double s_val0, double s_val1, double s_val2, double s_val3); - - // C++: Mat Mat::setTo(Scalar value, Mat mask = Mat()) - private static native long n_setTo(long nativeObj, double s_val0, double s_val1, double s_val2, double s_val3, long mask_nativeObj); + // javadoc: Mat::zeros(sizes, type) + public static Mat zeros(int[] sizes, int type) { + return new Mat(n_zeros(sizes.length, sizes, type)); + } - // C++: Mat Mat::setTo(Mat value, Mat mask = Mat()) - private static native long n_setTo(long nativeObj, long value_nativeObj, long mask_nativeObj); + // javadoc:Mat::toString() + @Override + public String toString() { + String _dims = (dims() > 0) ? "" : "-1*-1*"; + for (int i=0; i& ranges) - private static native long n_submat_ranges(long nativeObj, Range[] ranges); - - // C++: Mat Mat::operator()(Rect roi) - private static native long n_submat(long nativeObj, int roi_x, int roi_y, int roi_width, int roi_height); - - // C++: Mat Mat::t() - private static native long n_t(long nativeObj); - - // C++: size_t Mat::total() - private static native long n_total(long nativeObj); - - // C++: int Mat::type() - private static native int n_type(long nativeObj); - - // C++: static Mat Mat::zeros(int rows, int cols, int type) - private static native long n_zeros(int rows, int cols, int type); - - // C++: static Mat Mat::zeros(Size size, int type) - private static native long n_zeros(double size_width, double size_height, int type); - - // C++: static Mat Mat::zeros(int ndims, const int* sizes, int type) - private static native long n_zeros(int ndims, int[] sizes, int type); - - // native support for deleting native object - private static native void n_delete(long nativeObj); - - private static native int nPutD(long self, int row, int col, int count, double[] data); - - private static native int nPutDIdx(long self, int[] idx, int count, double[] data); - - private static native int nPutF(long self, int row, int col, int count, float[] data); - - private static native int nPutFIdx(long self, int[] idx, int count, float[] data); - - private static native int nPutI(long self, int row, int col, int count, int[] data); - - private static native int nPutIIdx(long self, int[] idx, int count, int[] data); - - private static native int nPutS(long self, int row, int col, int count, short[] data); - - private static native int nPutSIdx(long self, int[] idx, int count, short[] data); - - private static native int nPutB(long self, int row, int col, int count, byte[] data); - - private static native int nPutBIdx(long self, int[] idx, int count, byte[] data); - - private static native int nPutBwOffset(long self, int row, int col, int count, int offset, byte[] data); - - private static native int nPutBwIdxOffset(long self, int[] idx, int count, int offset, byte[] data); - - private static native int nGetB(long self, int row, int col, int count, byte[] vals); - - private static native int nGetBIdx(long self, int[] idx, int count, byte[] vals); - - private static native int nGetS(long self, int row, int col, int count, short[] vals); - - private static native int nGetSIdx(long self, int[] idx, int count, short[] vals); - - private static native int nGetI(long self, int row, int col, int count, int[] vals); - - private static native int nGetIIdx(long self, int[] idx, int count, int[] vals); - - private static native int nGetF(long self, int row, int col, int count, float[] vals); - - private static native int nGetFIdx(long self, int[] idx, int count, float[] vals); - - private static native int nGetD(long self, int row, int col, int count, double[] vals); - - private static native int nGetDIdx(long self, int[] idx, int count, double[] vals); - - private static native double[] nGet(long self, int row, int col); - - private static native double[] nGetIdx(long self, int[] idx); - - private static native String nDump(long self); - - // javadoc: Mat::adjustROI(dtop, dbottom, dleft, dright) - public Mat adjustROI(int dtop, int dbottom, int dleft, int dright) { - return new Mat(n_adjustROI(nativeObj, dtop, dbottom, dleft, dright)); - } - - // javadoc: Mat::assignTo(m, type) - public void assignTo(Mat m, int type) { - n_assignTo(nativeObj, m.nativeObj, type); - } - - // javadoc: Mat::assignTo(m) - public void assignTo(Mat m) { - n_assignTo(nativeObj, m.nativeObj); - } - - // javadoc: Mat::channels() - public int channels() { - return n_channels(nativeObj); - } - - // javadoc: Mat::checkVector(elemChannels, depth, requireContinuous) - public int checkVector(int elemChannels, int depth, boolean requireContinuous) { - return n_checkVector(nativeObj, elemChannels, depth, requireContinuous); - } - - // javadoc: Mat::checkVector(elemChannels, depth) - public int checkVector(int elemChannels, int depth) { - return n_checkVector(nativeObj, elemChannels, depth); - } - - // javadoc: Mat::checkVector(elemChannels) - public int checkVector(int elemChannels) { - return n_checkVector(nativeObj, elemChannels); - } - - // javadoc: Mat::clone() - public Mat clone() { - return new Mat(n_clone(nativeObj)); - } - - // javadoc: Mat::col(x) - public Mat col(int x) { - return new Mat(n_col(nativeObj, x)); - } - - // javadoc: Mat::colRange(startcol, endcol) - public Mat colRange(int startcol, int endcol) { - return new Mat(n_colRange(nativeObj, startcol, endcol)); - } - - // javadoc: Mat::colRange(r) - public Mat colRange(Range r) { - return new Mat(n_colRange(nativeObj, r.start, r.end)); - } - - // javadoc: Mat::dims() - public int dims() { - return n_dims(nativeObj); - } - - // javadoc: Mat::cols() - public int cols() { - return n_cols(nativeObj); - } - - // javadoc: Mat::convertTo(m, rtype, alpha, beta) - public void convertTo(Mat m, int rtype, double alpha, double beta) { - n_convertTo(nativeObj, m.nativeObj, rtype, alpha, beta); - } - - // javadoc: Mat::convertTo(m, rtype, alpha) - public void convertTo(Mat m, int rtype, double alpha) { - n_convertTo(nativeObj, m.nativeObj, rtype, alpha); - } - - // javadoc: Mat::convertTo(m, rtype) - public void convertTo(Mat m, int rtype) { - n_convertTo(nativeObj, m.nativeObj, rtype); - } - - // javadoc: Mat::copyTo(m) - public void copyTo(Mat m) { - n_copyTo(nativeObj, m.nativeObj); - } - - // javadoc: Mat::copyTo(m, mask) - public void copyTo(Mat m, Mat mask) { - n_copyTo(nativeObj, m.nativeObj, mask.nativeObj); - } - - // javadoc: Mat::create(rows, cols, type) - public void create(int rows, int cols, int type) { - n_create(nativeObj, rows, cols, type); - } - - // javadoc: Mat::create(size, type) - public void create(Size size, int type) { - n_create(nativeObj, size.width, size.height, type); - } - - // javadoc: Mat::create(sizes, type) - public void create(int[] sizes, int type) { - n_create(nativeObj, sizes.length, sizes, type); - } - - // javadoc: Mat::copySize(m) - public void copySize(Mat m) { - n_copySize(nativeObj, m.nativeObj); - } - - // javadoc: Mat::cross(m) - public Mat cross(Mat m) { - return new Mat(n_cross(nativeObj, m.nativeObj)); - } - - // javadoc: Mat::dataAddr() - public long dataAddr() { - return n_dataAddr(nativeObj); - } - - // javadoc: Mat::depth() - public int depth() { - return n_depth(nativeObj); - } - - // javadoc: Mat::diag(d) - public Mat diag(int d) { - return new Mat(n_diag(nativeObj, d)); - } - - // javadoc: Mat::diag() - public Mat diag() { - return new Mat(n_diag(nativeObj, 0)); - } - - // javadoc: Mat::dot(m) - public double dot(Mat m) { - return n_dot(nativeObj, m.nativeObj); - } - - // javadoc: Mat::elemSize() - public long elemSize() { - return n_elemSize(nativeObj); - } - - // javadoc: Mat::elemSize1() - public long elemSize1() { - return n_elemSize1(nativeObj); - } - - // javadoc: Mat::empty() - public boolean empty() { - return n_empty(nativeObj); - } - - // javadoc: Mat::inv(method) - public Mat inv(int method) { - return new Mat(n_inv(nativeObj, method)); - } - - // javadoc: Mat::inv() - public Mat inv() { - return new Mat(n_inv(nativeObj)); - } - - // javadoc: Mat::isContinuous() - public boolean isContinuous() { - return n_isContinuous(nativeObj); - } - - // javadoc: Mat::isSubmatrix() - public boolean isSubmatrix() { - return n_isSubmatrix(nativeObj); - } - - // javadoc: Mat::locateROI(wholeSize, ofs) - public void locateROI(Size wholeSize, Point ofs) { - double[] wholeSize_out = new double[2]; - double[] ofs_out = new double[2]; - locateROI_0(nativeObj, wholeSize_out, ofs_out); - if (wholeSize != null) { - wholeSize.width = wholeSize_out[0]; - wholeSize.height = wholeSize_out[1]; - } - if (ofs != null) { - ofs.x = ofs_out[0]; - ofs.y = ofs_out[1]; - } - } - - /** - * Element-wise multiplication with scale factor - * - * @param m operand with with which to perform element-wise multiplication - * @param scale scale factor - * @return reference to a new Mat object - */ - public Mat mul(Mat m, double scale) { - return new Mat(n_mul(nativeObj, m.nativeObj, scale)); - } - - /** - * Element-wise multiplication - * - * @param m operand with with which to perform element-wise multiplication - * @return reference to a new Mat object - */ - public Mat mul(Mat m) { - return new Mat(n_mul(nativeObj, m.nativeObj)); - } - - /** - * Matrix multiplication - * - * @param m operand with with which to perform matrix multiplication - * @return reference to a new Mat object - * @see Core#gemm(Mat, Mat, double, Mat, double, Mat, int) - */ - public Mat matMul(Mat m) { - return new Mat(n_matMul(nativeObj, m.nativeObj)); - } - - // javadoc: Mat::push_back(m) - public void push_back(Mat m) { - n_push_back(nativeObj, m.nativeObj); - } - - // javadoc: Mat::release() - public void release() { - n_release(nativeObj); - } - - // javadoc: Mat::reshape(cn, rows) - public Mat reshape(int cn, int rows) { - return new Mat(n_reshape(nativeObj, cn, rows)); - } - - // javadoc: Mat::reshape(cn) - public Mat reshape(int cn) { - return new Mat(n_reshape(nativeObj, cn)); - } - - // javadoc: Mat::reshape(cn, newshape) - public Mat reshape(int cn, int[] newshape) { - return new Mat(n_reshape_1(nativeObj, cn, newshape.length, newshape)); - } - - // javadoc: Mat::row(y) - public Mat row(int y) { - return new Mat(n_row(nativeObj, y)); - } - - // javadoc: Mat::rowRange(startrow, endrow) - public Mat rowRange(int startrow, int endrow) { - return new Mat(n_rowRange(nativeObj, startrow, endrow)); - } - - // javadoc: Mat::rowRange(r) - public Mat rowRange(Range r) { - return new Mat(n_rowRange(nativeObj, r.start, r.end)); - } - - // javadoc: Mat::rows() - public int rows() { - return n_rows(nativeObj); - } - - // javadoc: Mat::operator =(s) - public Mat setTo(Scalar s) { - return new Mat(n_setTo(nativeObj, s.val[0], s.val[1], s.val[2], s.val[3])); - } - - // javadoc: Mat::setTo(value, mask) - public Mat setTo(Scalar value, Mat mask) { - return new Mat(n_setTo(nativeObj, value.val[0], value.val[1], value.val[2], value.val[3], mask.nativeObj)); - } - - // javadoc: Mat::setTo(value, mask) - public Mat setTo(Mat value, Mat mask) { - return new Mat(n_setTo(nativeObj, value.nativeObj, mask.nativeObj)); - } - - // javadoc: Mat::setTo(value) - public Mat setTo(Mat value) { - return new Mat(n_setTo(nativeObj, value.nativeObj)); - } - - // javadoc: Mat::size() - public Size size() { - return new Size(n_size(nativeObj)); - } - - // javadoc: Mat::size(int i) - public int size(int i) { - return n_size_i(nativeObj, i); - } - - // javadoc: Mat::step1(i) - public long step1(int i) { - return n_step1(nativeObj, i); - } - - // javadoc: Mat::step1() - public long step1() { - return n_step1(nativeObj); - } - - // javadoc: Mat::operator()(rowStart, rowEnd, colStart, colEnd) - public Mat submat(int rowStart, int rowEnd, int colStart, int colEnd) { - return new Mat(n_submat_rr(nativeObj, rowStart, rowEnd, colStart, colEnd)); - } - - // javadoc: Mat::operator()(rowRange, colRange) - public Mat submat(Range rowRange, Range colRange) { - return new Mat(n_submat_rr(nativeObj, rowRange.start, rowRange.end, colRange.start, colRange.end)); - } - - // javadoc: Mat::operator()(ranges[]) - public Mat submat(Range[] ranges) { - return new Mat(n_submat_ranges(nativeObj, ranges)); - } - - // javadoc: Mat::operator()(roi) - public Mat submat(Rect roi) { - return new Mat(n_submat(nativeObj, roi.x, roi.y, roi.width, roi.height)); - } - - // javadoc: Mat::t() - public Mat t() { - return new Mat(n_t(nativeObj)); - } - - // javadoc: Mat::total() - public long total() { - return n_total(nativeObj); - } - - // javadoc: Mat::type() - public int type() { - return n_type(nativeObj); - } - - @Override - protected void finalize() throws Throwable { - n_delete(nativeObj); - super.finalize(); - } - - // javadoc:Mat::toString() - @Override - public String toString() { - String _dims = (dims() > 0) ? "" : "-1*-1*"; - for (int i = 0; i < dims(); i++) { - _dims += size(i) + "*"; - } - return "Mat [ " + _dims + CvType.typeToString(type()) + - ", isCont=" + isContinuous() + ", isSubmat=" + isSubmatrix() + - ", nativeObj=0x" + Long.toHexString(nativeObj) + - ", dataAddr=0x" + Long.toHexString(dataAddr()) + - " ]"; - } - - // javadoc:Mat::dump() - public String dump() { - return nDump(nativeObj); - } - - // javadoc:Mat::put(row,col,data) - public int put(int row, int col, double... data) { - int t = type(); - if (data == null || data.length % CvType.channels(t) != 0) - throw new UnsupportedOperationException( - "Provided data element number (" + - (data == null ? 0 : data.length) + - ") should be multiple of the Mat channels count (" + - CvType.channels(t) + ")"); - return nPutD(nativeObj, row, col, data.length, data); - } - - // javadoc:Mat::put(idx,data) - public int put(int[] idx, double... data) { - int t = type(); - if (data == null || data.length % CvType.channels(t) != 0) - throw new UnsupportedOperationException( - "Provided data element number (" + - (data == null ? 0 : data.length) + - ") should be multiple of the Mat channels count (" + - CvType.channels(t) + ")"); - if (idx.length != dims()) - throw new IllegalArgumentException("Incorrect number of indices"); - return nPutDIdx(nativeObj, idx, data.length, data); - } - - // javadoc:Mat::put(row,col,data) - public int put(int row, int col, float[] data) { - int t = type(); - if (data == null || data.length % CvType.channels(t) != 0) - throw new UnsupportedOperationException( - "Provided data element number (" + - (data == null ? 0 : data.length) + - ") should be multiple of the Mat channels count (" + - CvType.channels(t) + ")"); - if (CvType.depth(t) == CvType.CV_32F) { - return nPutF(nativeObj, row, col, data.length, data); - } - throw new UnsupportedOperationException("Mat data type is not compatible: " + t); - } + // javadoc:Mat::put(row,col,data) + public int put(int row, int col, float[] data) { + int t = type(); + if (data == null || data.length % CvType.channels(t) != 0) + throw new UnsupportedOperationException( + "Provided data element number (" + + (data == null ? 0 : data.length) + + ") should be multiple of the Mat channels count (" + + CvType.channels(t) + ")"); + if (CvType.depth(t) == CvType.CV_32F) { + return nPutF(nativeObj, row, col, data.length, data); + } + throw new UnsupportedOperationException("Mat data type is not compatible: " + t); + } // javadoc:Mat::put(idx,data) public int put(int[] idx, float[] data) { @@ -1359,538 +1090,817 @@ public int get(int row, int col, float[] data) { if (CvType.depth(t) == CvType.CV_32F) { return nGetF(nativeObj, row, col, data.length, data); } - throw new UnsupportedOperationException("Mat data type is not compatible: " + t); - } + throw new UnsupportedOperationException("Mat data type is not compatible: " + t); + } + + // javadoc:Mat::get(idx,data) + public int get(int[] idx, float[] data) { + int t = type(); + if (data == null || data.length % CvType.channels(t) != 0) + throw new UnsupportedOperationException( + "Provided data element number (" + + (data == null ? 0 : data.length) + + ") should be multiple of the Mat channels count (" + + CvType.channels(t) + ")"); + if (idx.length != dims()) + throw new IllegalArgumentException("Incorrect number of indices"); + if (CvType.depth(t) == CvType.CV_32F) { + return nGetFIdx(nativeObj, idx, data.length, data); + } + throw new UnsupportedOperationException("Mat data type is not compatible: " + t); + } + + // javadoc:Mat::get(row,col,data) + public int get(int row, int col, double[] data) { + int t = type(); + if (data == null || data.length % CvType.channels(t) != 0) + throw new UnsupportedOperationException( + "Provided data element number (" + + (data == null ? 0 : data.length) + + ") should be multiple of the Mat channels count (" + + CvType.channels(t) + ")"); + if (CvType.depth(t) == CvType.CV_64F) { + return nGetD(nativeObj, row, col, data.length, data); + } + throw new UnsupportedOperationException("Mat data type is not compatible: " + t); + } + + // javadoc:Mat::get(idx,data) + public int get(int[] idx, double[] data) { + int t = type(); + if (data == null || data.length % CvType.channels(t) != 0) + throw new UnsupportedOperationException( + "Provided data element number (" + + (data == null ? 0 : data.length) + + ") should be multiple of the Mat channels count (" + + CvType.channels(t) + ")"); + if (idx.length != dims()) + throw new IllegalArgumentException("Incorrect number of indices"); + if (CvType.depth(t) == CvType.CV_64F) { + return nGetDIdx(nativeObj, idx, data.length, data); + } + throw new UnsupportedOperationException("Mat data type is not compatible: " + t); + } + + // javadoc:Mat::get(row,col) + public double[] get(int row, int col) { + return nGet(nativeObj, row, col); + } + + // javadoc:Mat::get(idx) + public double[] get(int[] idx) { + if (idx.length != dims()) + throw new IllegalArgumentException("Incorrect number of indices"); + return nGetIdx(nativeObj, idx); + } + + // javadoc:Mat::height() + public int height() { + return rows(); + } + + // javadoc:Mat::width() + public int width() { + return cols(); + } + + // javadoc:Mat::at(clazz, row, col) + @SuppressWarnings("unchecked") + public Atable at(Class clazz, int row, int col) { + if (clazz == Byte.class || clazz == byte.class) { + return (Atable)new AtableByte(this, row, col); + } else if (clazz == Double.class || clazz == double.class) { + return (Atable)new AtableDouble(this, row, col); + } else if (clazz == Float.class || clazz == float.class) { + return (Atable)new AtableFloat(this, row, col); + } else if (clazz == Integer.class || clazz == int.class) { + return (Atable)new AtableInteger(this, row, col); + } else if (clazz == Short.class || clazz == short.class) { + return (Atable)new AtableShort(this, row, col); + } else { + throw new RuntimeException("Unsupported class type"); + } + } + + // javadoc:Mat::at(clazz, idx) + @SuppressWarnings("unchecked") + public Atable at(Class clazz, int[] idx) { + if (clazz == Byte.class || clazz == byte.class) { + return (Atable)new AtableByte(this, idx); + } else if (clazz == Double.class || clazz == double.class) { + return (Atable)new AtableDouble(this, idx); + } else if (clazz == Float.class || clazz == float.class) { + return (Atable)new AtableFloat(this, idx); + } else if (clazz == Integer.class || clazz == int.class) { + return (Atable)new AtableInteger(this, idx); + } else if (clazz == Short.class || clazz == short.class) { + return (Atable)new AtableShort(this, idx); + } else { + throw new RuntimeException("Unsupported class parameter"); + } + } + + public static class Tuple2 { + public Tuple2(T _0, T _1) { + this._0 = _0; + this._1 = _1; + } + + public T get_0() { + return _0; + } + + public T get_1() { + return _1; + } + + private final T _0; + private final T _1; + } + + public static class Tuple3 { + public Tuple3(T _0, T _1, T _2) { + this._0 = _0; + this._1 = _1; + this._2 = _2; + } + + public T get_0() { + return _0; + } + + public T get_1() { + return _1; + } + + public T get_2() { + return _2; + } + + private final T _0; + private final T _1; + private final T _2; + } + + public static class Tuple4 { + public Tuple4(T _0, T _1, T _2, T _3) { + this._0 = _0; + this._1 = _1; + this._2 = _2; + this._3 = _3; + } + + public T get_0() { + return _0; + } + + public T get_1() { + return _1; + } + + public T get_2() { + return _2; + } + + public T get_3() { + return _3; + } + + private final T _0; + private final T _1; + private final T _2; + private final T _3; + } + + public interface Atable { + T getV(); + void setV(T v); + Tuple2 getV2c(); + void setV2c(Tuple2 v); + Tuple3 getV3c(); + void setV3c(Tuple3 v); + Tuple4 getV4c(); + void setV4c(Tuple4 v); + } + + private static class AtableBase { + + protected AtableBase(Mat mat, int row, int col) { + this.mat = mat; + indices = new int[2]; + indices[0] = row; + indices[1] = col; + } + + protected AtableBase(Mat mat, int[] indices) { + this.mat = mat; + this.indices = indices; + } + + protected final Mat mat; + protected final int[] indices; + } + + private static class AtableByte extends AtableBase implements Atable { + + public AtableByte(Mat mat, int row, int col) { + super(mat, row, col); + } + + public AtableByte(Mat mat, int[] indices) { + super(mat, indices); + } + + @Override + public Byte getV() { + byte[] data = new byte[1]; + mat.get(indices, data); + return data[0]; + } + + @Override + public void setV(Byte v) { + byte[] data = new byte[] { v }; + mat.put(indices, data); + } + + @Override + public Tuple2 getV2c() { + byte[] data = new byte[2]; + mat.get(indices, data); + return new Tuple2(data[0], data[1]); + } + + @Override + public void setV2c(Tuple2 v) { + byte[] data = new byte[] { v._0, v._1 }; + mat.put(indices, data); + } + + @Override + public Tuple3 getV3c() { + byte[] data = new byte[3]; + mat.get(indices, data); + return new Tuple3(data[0], data[1], data[2]); + } - // javadoc:Mat::get(idx,data) - public int get(int[] idx, float[] data) { - int t = type(); - if (data == null || data.length % CvType.channels(t) != 0) - throw new UnsupportedOperationException( - "Provided data element number (" + - (data == null ? 0 : data.length) + - ") should be multiple of the Mat channels count (" + - CvType.channels(t) + ")"); - if (idx.length != dims()) - throw new IllegalArgumentException("Incorrect number of indices"); - if (CvType.depth(t) == CvType.CV_32F) { - return nGetFIdx(nativeObj, idx, data.length, data); + @Override + public void setV3c(Tuple3 v) { + byte[] data = new byte[] { v._0, v._1, v._2 }; + mat.put(indices, data); } - throw new UnsupportedOperationException("Mat data type is not compatible: " + t); - } - // javadoc:Mat::get(row,col,data) - public int get(int row, int col, double[] data) { - int t = type(); - if (data == null || data.length % CvType.channels(t) != 0) - throw new UnsupportedOperationException( - "Provided data element number (" + - (data == null ? 0 : data.length) + - ") should be multiple of the Mat channels count (" + - CvType.channels(t) + ")"); - if (CvType.depth(t) == CvType.CV_64F) { - return nGetD(nativeObj, row, col, data.length, data); + @Override + public Tuple4 getV4c() { + byte[] data = new byte[4]; + mat.get(indices, data); + return new Tuple4(data[0], data[1], data[2], data[3]); } - throw new UnsupportedOperationException("Mat data type is not compatible: " + t); - } - // javadoc:Mat::get(idx,data) - public int get(int[] idx, double[] data) { - int t = type(); - if (data == null || data.length % CvType.channels(t) != 0) - throw new UnsupportedOperationException( - "Provided data element number (" + - (data == null ? 0 : data.length) + - ") should be multiple of the Mat channels count (" + - CvType.channels(t) + ")"); - if (idx.length != dims()) - throw new IllegalArgumentException("Incorrect number of indices"); - if (CvType.depth(t) == CvType.CV_64F) { - return nGetDIdx(nativeObj, idx, data.length, data); + @Override + public void setV4c(Tuple4 v) { + byte[] data = new byte[] { v._0, v._1, v._2, v._3 }; + mat.put(indices, data); } - throw new UnsupportedOperationException("Mat data type is not compatible: " + t); } - // javadoc:Mat::get(row,col) - public double[] get(int row, int col) { - return nGet(nativeObj, row, col); - } + private static class AtableDouble extends AtableBase implements Atable { - // javadoc:Mat::get(idx) - public double[] get(int[] idx) { - if (idx.length != dims()) - throw new IllegalArgumentException("Incorrect number of indices"); - return nGetIdx(nativeObj, idx); - } + public AtableDouble(Mat mat, int row, int col) { + super(mat, row, col); + } - // javadoc:Mat::height() - public int height() { - return rows(); - } + public AtableDouble(Mat mat, int[] indices) { + super(mat, indices); + } - // javadoc:Mat::width() - public int width() { - return cols(); - } + @Override + public Double getV() { + double[] data = new double[1]; + mat.get(indices, data); + return data[0]; + } - // javadoc:Mat::at(clazz, row, col) - public Atable at(Class clazz, int row, int col) { - if (clazz == Byte.class || clazz == byte.class) { - return (Atable) new AtableByte(this, row, col); - } else if (clazz == Double.class || clazz == double.class) { - return (Atable) new AtableDouble(this, row, col); - } else if (clazz == Float.class || clazz == float.class) { - return (Atable) new AtableFloat(this, row, col); - } else if (clazz == Integer.class || clazz == int.class) { - return (Atable) new AtableInteger(this, row, col); - } else if (clazz == Short.class || clazz == short.class) { - return (Atable) new AtableShort(this, row, col); - } else { - throw new RuntimeException("Unsupported class type"); + @Override + public void setV(Double v) { + double[] data = new double[] { v }; + mat.put(indices, data); } - } - // javadoc:Mat::at(clazz, idx) - public Atable at(Class clazz, int[] idx) { - if (clazz == Byte.class || clazz == byte.class) { - return (Atable) new AtableByte(this, idx); - } else if (clazz == Double.class || clazz == double.class) { - return (Atable) new AtableDouble(this, idx); - } else if (clazz == Float.class || clazz == float.class) { - return (Atable) new AtableFloat(this, idx); - } else if (clazz == Integer.class || clazz == int.class) { - return (Atable) new AtableInteger(this, idx); - } else if (clazz == Short.class || clazz == short.class) { - return (Atable) new AtableShort(this, idx); - } else { - throw new RuntimeException("Unsupported class parameter"); + @Override + public Tuple2 getV2c() { + double[] data = new double[2]; + mat.get(indices, data); + return new Tuple2(data[0], data[1]); } - } - // javadoc:Mat::getNativeObjAddr() - public long getNativeObjAddr() { - return nativeObj; - } + @Override + public void setV2c(Tuple2 v) { + double[] data = new double[] { v._0, v._1 }; + mat.put(indices, data); + } - public interface Atable { - T getV(); + @Override + public Tuple3 getV3c() { + double[] data = new double[3]; + mat.get(indices, data); + return new Tuple3(data[0], data[1], data[2]); + } - void setV(T v); + @Override + public void setV3c(Tuple3 v) { + double[] data = new double[] { v._0, v._1, v._2 }; + mat.put(indices, data); + } - Tuple2 getV2c(); + @Override + public Tuple4 getV4c() { + double[] data = new double[4]; + mat.get(indices, data); + return new Tuple4(data[0], data[1], data[2], data[3]); + } - void setV2c(Tuple2 v); + @Override + public void setV4c(Tuple4 v) { + double[] data = new double[] { v._0, v._1, v._2, v._3 }; + mat.put(indices, data); + } + } - Tuple3 getV3c(); + private static class AtableFloat extends AtableBase implements Atable { - void setV3c(Tuple3 v); + public AtableFloat(Mat mat, int row, int col) { + super(mat, row, col); + } - Tuple4 getV4c(); + public AtableFloat(Mat mat, int[] indices) { + super(mat, indices); + } - void setV4c(Tuple4 v); - } + @Override + public Float getV() { + float[] data = new float[1]; + mat.get(indices, data); + return data[0]; + } - public static class Tuple2 { - private final T _0; - private final T _1; + @Override + public void setV(Float v) { + float[] data = new float[] { v }; + mat.put(indices, data); + } - public Tuple2(T _0, T _1) { - this._0 = _0; - this._1 = _1; + @Override + public Tuple2 getV2c() { + float[] data = new float[2]; + mat.get(indices, data); + return new Tuple2(data[0], data[1]); } - public T get_0() { - return _0; + @Override + public void setV2c(Tuple2 v) { + float[] data = new float[] { v._0, v._1 }; + mat.put(indices, data); } - public T get_1() { - return _1; + @Override + public Tuple3 getV3c() { + float[] data = new float[3]; + mat.get(indices, data); + return new Tuple3(data[0], data[1], data[2]); } - } - public static class Tuple3 { - private final T _0; - private final T _1; - private final T _2; + @Override + public void setV3c(Tuple3 v) { + float[] data = new float[] { v._0, v._1, v._2 }; + mat.put(indices, data); + } - public Tuple3(T _0, T _1, T _2) { - this._0 = _0; - this._1 = _1; - this._2 = _2; + @Override + public Tuple4 getV4c() { + float[] data = new float[4]; + mat.get(indices, data); + return new Tuple4(data[0], data[1], data[2], data[3]); } - public T get_0() { - return _0; + @Override + public void setV4c(Tuple4 v) { + double[] data = new double[] { v._0, v._1, v._2, v._3 }; + mat.put(indices, data); } + } - public T get_1() { - return _1; + private static class AtableInteger extends AtableBase implements Atable { + + public AtableInteger(Mat mat, int row, int col) { + super(mat, row, col); } - public T get_2() { - return _2; + public AtableInteger(Mat mat, int[] indices) { + super(mat, indices); } - } - public static class Tuple4 { - private final T _0; - private final T _1; - private final T _2; - private final T _3; + @Override + public Integer getV() { + int[] data = new int[1]; + mat.get(indices, data); + return data[0]; + } - public Tuple4(T _0, T _1, T _2, T _3) { - this._0 = _0; - this._1 = _1; - this._2 = _2; - this._3 = _3; + @Override + public void setV(Integer v) { + int[] data = new int[] { v }; + mat.put(indices, data); } - public T get_0() { - return _0; + @Override + public Tuple2 getV2c() { + int[] data = new int[2]; + mat.get(indices, data); + return new Tuple2(data[0], data[1]); } - public T get_1() { - return _1; + @Override + public void setV2c(Tuple2 v) { + int[] data = new int[] { v._0, v._1 }; + mat.put(indices, data); } - public T get_2() { - return _2; + @Override + public Tuple3 getV3c() { + int[] data = new int[3]; + mat.get(indices, data); + return new Tuple3(data[0], data[1], data[2]); } - public T get_3() { - return _3; + @Override + public void setV3c(Tuple3 v) { + int[] data = new int[] { v._0, v._1, v._2 }; + mat.put(indices, data); } - } - - private static class AtableBase { - protected final Mat mat; - protected final int[] indices; - - protected AtableBase(Mat mat, int row, int col) { - this.mat = mat; - indices = new int[2]; - indices[0] = row; - indices[1] = col; + @Override + public Tuple4 getV4c() { + int[] data = new int[4]; + mat.get(indices, data); + return new Tuple4(data[0], data[1], data[2], data[3]); } - protected AtableBase(Mat mat, int[] indices) { - this.mat = mat; - this.indices = indices; + + @Override + public void setV4c(Tuple4 v) { + int[] data = new int[] { v._0, v._1, v._2, v._3 }; + mat.put(indices, data); } } - private static class AtableByte extends AtableBase implements Atable { + private static class AtableShort extends AtableBase implements Atable { - public AtableByte(Mat mat, int row, int col) { + public AtableShort(Mat mat, int row, int col) { super(mat, row, col); } - public AtableByte(Mat mat, int[] indices) { + public AtableShort(Mat mat, int[] indices) { super(mat, indices); } @Override - public Byte getV() { - byte[] data = new byte[1]; + public Short getV() { + short[] data = new short[1]; mat.get(indices, data); return data[0]; } @Override - public void setV(Byte v) { - byte[] data = new byte[]{v}; + public void setV(Short v) { + short[] data = new short[] { v }; mat.put(indices, data); } @Override - public Tuple2 getV2c() { - byte[] data = new byte[2]; + public Tuple2 getV2c() { + short[] data = new short[2]; mat.get(indices, data); - return new Tuple2(data[0], data[1]); + return new Tuple2(data[0], data[1]); } @Override - public void setV2c(Tuple2 v) { - byte[] data = new byte[]{v._0, v._1}; + public void setV2c(Tuple2 v) { + short[] data = new short[] { v._0, v._1 }; mat.put(indices, data); } @Override - public Tuple3 getV3c() { - byte[] data = new byte[3]; + public Tuple3 getV3c() { + short[] data = new short[3]; mat.get(indices, data); - return new Tuple3(data[0], data[1], data[2]); + return new Tuple3(data[0], data[1], data[2]); } @Override - public void setV3c(Tuple3 v) { - byte[] data = new byte[]{v._0, v._1, v._2}; + public void setV3c(Tuple3 v) { + short[] data = new short[] { v._0, v._1, v._2 }; mat.put(indices, data); } @Override - public Tuple4 getV4c() { - byte[] data = new byte[4]; + public Tuple4 getV4c() { + short[] data = new short[4]; mat.get(indices, data); - return new Tuple4(data[0], data[1], data[2], data[3]); + return new Tuple4(data[0], data[1], data[2], data[3]); } @Override - public void setV4c(Tuple4 v) { - byte[] data = new byte[]{v._0, v._1, v._2, v._3}; + public void setV4c(Tuple4 v) { + short[] data = new short[] { v._0, v._1, v._2, v._3 }; mat.put(indices, data); } } - private static class AtableDouble extends AtableBase implements Atable { + // javadoc:Mat::getNativeObjAddr() + public long getNativeObjAddr() { + return nativeObj; + } + + // C++: Mat::Mat() + private static native long n_Mat(); + + // C++: Mat::Mat(int rows, int cols, int type) + private static native long n_Mat(int rows, int cols, int type); + + // C++: Mat::Mat(int ndims, const int* sizes, int type) + private static native long n_Mat(int ndims, int[] sizes, int type); + + // C++: Mat::Mat(int rows, int cols, int type, void* data) + private static native long n_Mat(int rows, int cols, int type, ByteBuffer data); + + // C++: Mat::Mat(int rows, int cols, int type, void* data, size_t step) + private static native long n_Mat(int rows, int cols, int type, ByteBuffer data, long step); + + // C++: Mat::Mat(Size size, int type) + private static native long n_Mat(double size_width, double size_height, int type); + + // C++: Mat::Mat(int rows, int cols, int type, Scalar s) + private static native long n_Mat(int rows, int cols, int type, double s_val0, double s_val1, double s_val2, double s_val3); + + // C++: Mat::Mat(Size size, int type, Scalar s) + private static native long n_Mat(double size_width, double size_height, int type, double s_val0, double s_val1, double s_val2, double s_val3); + + // C++: Mat::Mat(int ndims, const int* sizes, int type, Scalar s) + private static native long n_Mat(int ndims, int[] sizes, int type, double s_val0, double s_val1, double s_val2, double s_val3); + + // C++: Mat::Mat(Mat m, Range rowRange, Range colRange = Range::all()) + private static native long n_Mat(long m_nativeObj, int rowRange_start, int rowRange_end, int colRange_start, int colRange_end); + + private static native long n_Mat(long m_nativeObj, int rowRange_start, int rowRange_end); + + // C++: Mat::Mat(const Mat& m, const std::vector& ranges) + private static native long n_Mat(long m_nativeObj, Range[] ranges); + + // C++: Mat Mat::adjustROI(int dtop, int dbottom, int dleft, int dright) + private static native long n_adjustROI(long nativeObj, int dtop, int dbottom, int dleft, int dright); + + // C++: void Mat::assignTo(Mat m, int type = -1) + private static native void n_assignTo(long nativeObj, long m_nativeObj, int type); + + private static native void n_assignTo(long nativeObj, long m_nativeObj); + + // C++: int Mat::channels() + private static native int n_channels(long nativeObj); + + // C++: int Mat::checkVector(int elemChannels, int depth = -1, bool + // requireContinuous = true) + private static native int n_checkVector(long nativeObj, int elemChannels, int depth, boolean requireContinuous); + + private static native int n_checkVector(long nativeObj, int elemChannels, int depth); + + private static native int n_checkVector(long nativeObj, int elemChannels); + + // C++: Mat Mat::clone() + private static native long n_clone(long nativeObj); + + // C++: Mat Mat::col(int x) + private static native long n_col(long nativeObj, int x); + + // C++: Mat Mat::colRange(int startcol, int endcol) + private static native long n_colRange(long nativeObj, int startcol, int endcol); + + // C++: int Mat::dims() + private static native int n_dims(long nativeObj); + + // C++: int Mat::cols() + private static native int n_cols(long nativeObj); + + // C++: void Mat::convertTo(Mat& m, int rtype, double alpha = 1, double beta + // = 0) + private static native void n_convertTo(long nativeObj, long m_nativeObj, int rtype, double alpha, double beta); + + private static native void n_convertTo(long nativeObj, long m_nativeObj, int rtype, double alpha); + + private static native void n_convertTo(long nativeObj, long m_nativeObj, int rtype); + + // C++: void Mat::copyTo(Mat& m) + private static native void n_copyTo(long nativeObj, long m_nativeObj); + + // C++: void Mat::copyTo(Mat& m, Mat mask) + private static native void n_copyTo(long nativeObj, long m_nativeObj, long mask_nativeObj); + + // C++: void Mat::create(int rows, int cols, int type) + private static native void n_create(long nativeObj, int rows, int cols, int type); + + // C++: void Mat::create(Size size, int type) + private static native void n_create(long nativeObj, double size_width, double size_height, int type); + + // C++: void Mat::create(int ndims, const int* sizes, int type) + private static native void n_create(long nativeObj, int ndims, int[] sizes, int type); + + // C++: void Mat::copySize(const Mat& m) + private static native void n_copySize(long nativeObj, long m_nativeObj); + + // C++: Mat Mat::cross(Mat m) + private static native long n_cross(long nativeObj, long m_nativeObj); + + // C++: long Mat::dataAddr() + private static native long n_dataAddr(long nativeObj); + + // C++: int Mat::depth() + private static native int n_depth(long nativeObj); + + // C++: Mat Mat::diag(int d = 0) + private static native long n_diag(long nativeObj, int d); + + // C++: static Mat Mat::diag(Mat d) + private static native long n_diag(long d_nativeObj); + + // C++: double Mat::dot(Mat m) + private static native double n_dot(long nativeObj, long m_nativeObj); + + // C++: size_t Mat::elemSize() + private static native long n_elemSize(long nativeObj); + + // C++: size_t Mat::elemSize1() + private static native long n_elemSize1(long nativeObj); + + // C++: bool Mat::empty() + private static native boolean n_empty(long nativeObj); + + // C++: static Mat Mat::eye(int rows, int cols, int type) + private static native long n_eye(int rows, int cols, int type); + + // C++: static Mat Mat::eye(Size size, int type) + private static native long n_eye(double size_width, double size_height, int type); + + // C++: Mat Mat::inv(int method = DECOMP_LU) + private static native long n_inv(long nativeObj, int method); + + private static native long n_inv(long nativeObj); + + // C++: bool Mat::isContinuous() + private static native boolean n_isContinuous(long nativeObj); + + // C++: bool Mat::isSubmatrix() + private static native boolean n_isSubmatrix(long nativeObj); + + // C++: void Mat::locateROI(Size wholeSize, Point ofs) + private static native void locateROI_0(long nativeObj, double[] wholeSize_out, double[] ofs_out); + + // C++: Mat Mat::mul(Mat m, double scale = 1) + private static native long n_mul(long nativeObj, long m_nativeObj, double scale); + + private static native long n_mul(long nativeObj, long m_nativeObj); + + private static native long n_matMul(long nativeObj, long m_nativeObj); + + // C++: static Mat Mat::ones(int rows, int cols, int type) + private static native long n_ones(int rows, int cols, int type); + + // C++: static Mat Mat::ones(Size size, int type) + private static native long n_ones(double size_width, double size_height, int type); + + // C++: static Mat Mat::ones(int ndims, const int* sizes, int type) + private static native long n_ones(int ndims, int[] sizes, int type); + + // C++: void Mat::push_back(Mat m) + private static native void n_push_back(long nativeObj, long m_nativeObj); + + // C++: void Mat::release() + private static native void n_release(long nativeObj); + + // C++: Mat Mat::reshape(int cn, int rows = 0) + private static native long n_reshape(long nativeObj, int cn, int rows); + + private static native long n_reshape(long nativeObj, int cn); + + // C++: Mat Mat::reshape(int cn, int newndims, const int* newsz) + private static native long n_reshape_1(long nativeObj, int cn, int newndims, int[] newsz); + + // C++: Mat Mat::row(int y) + private static native long n_row(long nativeObj, int y); + + // C++: Mat Mat::rowRange(int startrow, int endrow) + private static native long n_rowRange(long nativeObj, int startrow, int endrow); - public AtableDouble(Mat mat, int row, int col) { - super(mat, row, col); - } + // C++: int Mat::rows() + private static native int n_rows(long nativeObj); - public AtableDouble(Mat mat, int[] indices) { - super(mat, indices); - } + // C++: Mat Mat::operator =(Scalar s) + private static native long n_setTo(long nativeObj, double s_val0, double s_val1, double s_val2, double s_val3); - @Override - public Double getV() { - double[] data = new double[1]; - mat.get(indices, data); - return data[0]; - } + // C++: Mat Mat::setTo(Scalar value, Mat mask = Mat()) + private static native long n_setTo(long nativeObj, double s_val0, double s_val1, double s_val2, double s_val3, long mask_nativeObj); - @Override - public void setV(Double v) { - double[] data = new double[]{v}; - mat.put(indices, data); - } + // C++: Mat Mat::setTo(Mat value, Mat mask = Mat()) + private static native long n_setTo(long nativeObj, long value_nativeObj, long mask_nativeObj); - @Override - public Tuple2 getV2c() { - double[] data = new double[2]; - mat.get(indices, data); - return new Tuple2(data[0], data[1]); - } + private static native long n_setTo(long nativeObj, long value_nativeObj); - @Override - public void setV2c(Tuple2 v) { - double[] data = new double[]{v._0, v._1}; - mat.put(indices, data); - } + // C++: Size Mat::size() + private static native double[] n_size(long nativeObj); - @Override - public Tuple3 getV3c() { - double[] data = new double[3]; - mat.get(indices, data); - return new Tuple3(data[0], data[1], data[2]); - } + // C++: int Mat::size(int i) + private static native int n_size_i(long nativeObj, int i); - @Override - public void setV3c(Tuple3 v) { - double[] data = new double[]{v._0, v._1, v._2}; - mat.put(indices, data); - } + // C++: size_t Mat::step1(int i = 0) + private static native long n_step1(long nativeObj, int i); - @Override - public Tuple4 getV4c() { - double[] data = new double[4]; - mat.get(indices, data); - return new Tuple4(data[0], data[1], data[2], data[3]); - } + private static native long n_step1(long nativeObj); - @Override - public void setV4c(Tuple4 v) { - double[] data = new double[]{v._0, v._1, v._2, v._3}; - mat.put(indices, data); - } - } + // C++: Mat Mat::operator()(Range rowRange, Range colRange) + private static native long n_submat_rr(long nativeObj, int rowRange_start, int rowRange_end, int colRange_start, int colRange_end); - private static class AtableFloat extends AtableBase implements Atable { + // C++: Mat Mat::operator()(const std::vector& ranges) + private static native long n_submat_ranges(long nativeObj, Range[] ranges); - public AtableFloat(Mat mat, int row, int col) { - super(mat, row, col); - } + // C++: Mat Mat::operator()(Rect roi) + private static native long n_submat(long nativeObj, int roi_x, int roi_y, int roi_width, int roi_height); - public AtableFloat(Mat mat, int[] indices) { - super(mat, indices); - } + // C++: Mat Mat::t() + private static native long n_t(long nativeObj); - @Override - public Float getV() { - float[] data = new float[1]; - mat.get(indices, data); - return data[0]; - } + // C++: size_t Mat::total() + private static native long n_total(long nativeObj); - @Override - public void setV(Float v) { - float[] data = new float[]{v}; - mat.put(indices, data); - } + // C++: int Mat::type() + private static native int n_type(long nativeObj); - @Override - public Tuple2 getV2c() { - float[] data = new float[2]; - mat.get(indices, data); - return new Tuple2(data[0], data[1]); - } + // C++: static Mat Mat::zeros(int rows, int cols, int type) + private static native long n_zeros(int rows, int cols, int type); - @Override - public void setV2c(Tuple2 v) { - float[] data = new float[]{v._0, v._1}; - mat.put(indices, data); - } + // C++: static Mat Mat::zeros(Size size, int type) + private static native long n_zeros(double size_width, double size_height, int type); - @Override - public Tuple3 getV3c() { - float[] data = new float[3]; - mat.get(indices, data); - return new Tuple3(data[0], data[1], data[2]); - } + // C++: static Mat Mat::zeros(int ndims, const int* sizes, int type) + private static native long n_zeros(int ndims, int[] sizes, int type); - @Override - public void setV3c(Tuple3 v) { - float[] data = new float[]{v._0, v._1, v._2}; - mat.put(indices, data); - } + // native support for deleting native object + private static native void n_delete(long nativeObj); - @Override - public Tuple4 getV4c() { - float[] data = new float[4]; - mat.get(indices, data); - return new Tuple4(data[0], data[1], data[2], data[3]); - } + private static native int nPutD(long self, int row, int col, int count, double[] data); - @Override - public void setV4c(Tuple4 v) { - double[] data = new double[]{v._0, v._1, v._2, v._3}; - mat.put(indices, data); - } - } + private static native int nPutDIdx(long self, int[] idx, int count, double[] data); - private static class AtableInteger extends AtableBase implements Atable { + private static native int nPutF(long self, int row, int col, int count, float[] data); - public AtableInteger(Mat mat, int row, int col) { - super(mat, row, col); - } + private static native int nPutFIdx(long self, int[] idx, int count, float[] data); - public AtableInteger(Mat mat, int[] indices) { - super(mat, indices); - } + private static native int nPutI(long self, int row, int col, int count, int[] data); - @Override - public Integer getV() { - int[] data = new int[1]; - mat.get(indices, data); - return data[0]; - } + private static native int nPutIIdx(long self, int[] idx, int count, int[] data); - @Override - public void setV(Integer v) { - int[] data = new int[]{v}; - mat.put(indices, data); - } + private static native int nPutS(long self, int row, int col, int count, short[] data); - @Override - public Tuple2 getV2c() { - int[] data = new int[2]; - mat.get(indices, data); - return new Tuple2(data[0], data[1]); - } + private static native int nPutSIdx(long self, int[] idx, int count, short[] data); - @Override - public void setV2c(Tuple2 v) { - int[] data = new int[]{v._0, v._1}; - mat.put(indices, data); - } + private static native int nPutB(long self, int row, int col, int count, byte[] data); - @Override - public Tuple3 getV3c() { - int[] data = new int[3]; - mat.get(indices, data); - return new Tuple3(data[0], data[1], data[2]); - } + private static native int nPutBIdx(long self, int[] idx, int count, byte[] data); - @Override - public void setV3c(Tuple3 v) { - int[] data = new int[]{v._0, v._1, v._2}; - mat.put(indices, data); - } + private static native int nPutBwOffset(long self, int row, int col, int count, int offset, byte[] data); - @Override - public Tuple4 getV4c() { - int[] data = new int[4]; - mat.get(indices, data); - return new Tuple4(data[0], data[1], data[2], data[3]); - } + private static native int nPutBwIdxOffset(long self, int[] idx, int count, int offset, byte[] data); - @Override - public void setV4c(Tuple4 v) { - int[] data = new int[]{v._0, v._1, v._2, v._3}; - mat.put(indices, data); - } - } + private static native int nGetB(long self, int row, int col, int count, byte[] vals); - private static class AtableShort extends AtableBase implements Atable { + private static native int nGetBIdx(long self, int[] idx, int count, byte[] vals); - public AtableShort(Mat mat, int row, int col) { - super(mat, row, col); - } + private static native int nGetS(long self, int row, int col, int count, short[] vals); - public AtableShort(Mat mat, int[] indices) { - super(mat, indices); - } + private static native int nGetSIdx(long self, int[] idx, int count, short[] vals); - @Override - public Short getV() { - short[] data = new short[1]; - mat.get(indices, data); - return data[0]; - } + private static native int nGetI(long self, int row, int col, int count, int[] vals); - @Override - public void setV(Short v) { - short[] data = new short[]{v}; - mat.put(indices, data); - } + private static native int nGetIIdx(long self, int[] idx, int count, int[] vals); - @Override - public Tuple2 getV2c() { - short[] data = new short[2]; - mat.get(indices, data); - return new Tuple2(data[0], data[1]); - } + private static native int nGetF(long self, int row, int col, int count, float[] vals); - @Override - public void setV2c(Tuple2 v) { - short[] data = new short[]{v._0, v._1}; - mat.put(indices, data); - } + private static native int nGetFIdx(long self, int[] idx, int count, float[] vals); - @Override - public Tuple3 getV3c() { - short[] data = new short[3]; - mat.get(indices, data); - return new Tuple3(data[0], data[1], data[2]); - } + private static native int nGetD(long self, int row, int col, int count, double[] vals); - @Override - public void setV3c(Tuple3 v) { - short[] data = new short[]{v._0, v._1, v._2}; - mat.put(indices, data); - } + private static native int nGetDIdx(long self, int[] idx, int count, double[] vals); - @Override - public Tuple4 getV4c() { - short[] data = new short[4]; - mat.get(indices, data); - return new Tuple4(data[0], data[1], data[2], data[3]); - } + private static native double[] nGet(long self, int row, int col); - @Override - public void setV4c(Tuple4 v) { - short[] data = new short[]{v._0, v._1, v._2, v._3}; - mat.put(indices, data); - } - } + private static native double[] nGetIdx(long self, int[] idx); + + private static native String nDump(long self); } diff --git a/bus-opencv/src/main/java/org/opencv/core/MatOfByte.java b/bus-opencv/src/main/java/org/opencv/core/MatOfByte.java index c44b8d6ea0..eb928fb0a9 100644 --- a/bus-opencv/src/main/java/org/opencv/core/MatOfByte.java +++ b/bus-opencv/src/main/java/org/opencv/core/MatOfByte.java @@ -14,46 +14,46 @@ public MatOfByte() { protected MatOfByte(long addr) { super(addr); - if (!empty() && checkVector(_channels, _depth) < 0) + if( !empty() && checkVector(_channels, _depth) < 0 ) throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } + public static MatOfByte fromNativeAddr(long addr) { + return new MatOfByte(addr); + } + public MatOfByte(Mat m) { super(m, Range.all()); - if (!empty() && checkVector(_channels, _depth) < 0) + if( !empty() && checkVector(_channels, _depth) < 0 ) throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } - public MatOfByte(byte... a) { + public MatOfByte(byte...a) { super(); fromArray(a); } - public MatOfByte(int offset, int length, byte... a) { + public MatOfByte(int offset, int length, byte...a) { super(); fromArray(offset, length, a); } - public static MatOfByte fromNativeAddr(long addr) { - return new MatOfByte(addr); - } - public void alloc(int elemNumber) { - if (elemNumber > 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(byte... a) { - if (a == null || a.length == 0) + public void fromArray(byte...a) { + if(a==null || a.length==0) return; int num = a.length / _channels; alloc(num); put(0, 0, a); //TODO: check ret val! } - public void fromArray(int offset, int length, byte... a) { + public void fromArray(int offset, int length, byte...a) { if (offset < 0) throw new IllegalArgumentException("offset < 0"); if (a == null) @@ -69,21 +69,21 @@ public void fromArray(int offset, int length, byte... a) { public byte[] toArray() { int num = checkVector(_channels, _depth); - if (num < 0) + if(num < 0) throw new RuntimeException("Native Mat has unexpected type or size: " + toString()); byte[] a = new byte[num * _channels]; - if (num == 0) + if(num == 0) return a; get(0, 0, a); //TODO: check ret val! return a; } public void fromList(List lb) { - if (lb == null || lb.size() == 0) + if(lb==null || lb.size()==0) return; Byte ab[] = lb.toArray(new Byte[0]); byte a[] = new byte[ab.length]; - for (int i = 0; i < ab.length; i++) + for(int i=0; i lb) { public List toList() { byte[] a = toArray(); Byte ab[] = new Byte[a.length]; - for (int i = 0; i < a.length; i++) + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(DMatch... a) { - if (a == null || a.length == 0) + public void fromArray(DMatch...a) { + if(a==null || a.length==0) return; int num = a.length; alloc(num); float buff[] = new float[num * _channels]; - for (int i = 0; i < num; i++) { + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(double... a) { - if (a == null || a.length == 0) + public void fromArray(double...a) { + if(a==null || a.length==0) return; int num = a.length / _channels; alloc(num); @@ -50,21 +50,21 @@ public void fromArray(double... a) { public double[] toArray() { int num = checkVector(_channels, _depth); - if (num < 0) + if(num < 0) throw new RuntimeException("Native Mat has unexpected type or size: " + toString()); double[] a = new double[num * _channels]; - if (num == 0) + if(num == 0) return a; get(0, 0, a); //TODO: check ret val! return a; } public void fromList(List lb) { - if (lb == null || lb.size() == 0) + if(lb==null || lb.size()==0) return; Double ab[] = lb.toArray(new Double[0]); double a[] = new double[ab.length]; - for (int i = 0; i < ab.length; i++) + for(int i=0; i lb) { public List toList() { double[] a = toArray(); Double ab[] = new Double[a.length]; - for (int i = 0; i < a.length; i++) + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(float... a) { - if (a == null || a.length == 0) + public void fromArray(float...a) { + if(a==null || a.length==0) return; int num = a.length / _channels; alloc(num); @@ -50,21 +50,21 @@ public void fromArray(float... a) { public float[] toArray() { int num = checkVector(_channels, _depth); - if (num < 0) + if(num < 0) throw new RuntimeException("Native Mat has unexpected type or size: " + toString()); float[] a = new float[num * _channels]; - if (num == 0) + if(num == 0) return a; get(0, 0, a); //TODO: check ret val! return a; } public void fromList(List lb) { - if (lb == null || lb.size() == 0) + if(lb==null || lb.size()==0) return; Float ab[] = lb.toArray(new Float[0]); float a[] = new float[ab.length]; - for (int i = 0; i < ab.length; i++) + for(int i=0; i lb) { public List toList() { float[] a = toArray(); Float ab[] = new Float[a.length]; - for (int i = 0; i < a.length; i++) + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(float... a) { - if (a == null || a.length == 0) + public void fromArray(float...a) { + if(a==null || a.length==0) return; int num = a.length / _channels; alloc(num); @@ -50,21 +50,21 @@ public void fromArray(float... a) { public float[] toArray() { int num = checkVector(_channels, _depth); - if (num < 0) + if(num < 0) throw new RuntimeException("Native Mat has unexpected type or size: " + toString()); float[] a = new float[num * _channels]; - if (num == 0) + if(num == 0) return a; get(0, 0, a); //TODO: check ret val! return a; } public void fromList(List lb) { - if (lb == null || lb.size() == 0) + if(lb==null || lb.size()==0) return; Float ab[] = lb.toArray(new Float[0]); float a[] = new float[ab.length]; - for (int i = 0; i < ab.length; i++) + for(int i=0; i lb) { public List toList() { float[] a = toArray(); Float ab[] = new Float[a.length]; - for (int i = 0; i < a.length; i++) + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(float... a) { - if (a == null || a.length == 0) + public void fromArray(float...a) { + if(a==null || a.length==0) return; int num = a.length / _channels; alloc(num); @@ -50,21 +50,21 @@ public void fromArray(float... a) { public float[] toArray() { int num = checkVector(_channels, _depth); - if (num < 0) + if(num < 0) throw new RuntimeException("Native Mat has unexpected type or size: " + toString()); float[] a = new float[num * _channels]; - if (num == 0) + if(num == 0) return a; get(0, 0, a); //TODO: check ret val! return a; } public void fromList(List lb) { - if (lb == null || lb.size() == 0) + if(lb==null || lb.size()==0) return; Float ab[] = lb.toArray(new Float[0]); float a[] = new float[ab.length]; - for (int i = 0; i < ab.length; i++) + for(int i=0; i lb) { public List toList() { float[] a = toArray(); Float ab[] = new Float[a.length]; - for (int i = 0; i < a.length; i++) + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(int... a) { - if (a == null || a.length == 0) + public void fromArray(int...a) { + if(a==null || a.length==0) return; int num = a.length / _channels; alloc(num); @@ -51,21 +51,21 @@ public void fromArray(int... a) { public int[] toArray() { int num = checkVector(_channels, _depth); - if (num < 0) + if(num < 0) throw new RuntimeException("Native Mat has unexpected type or size: " + toString()); int[] a = new int[num * _channels]; - if (num == 0) + if(num == 0) return a; get(0, 0, a); //TODO: check ret val! return a; } public void fromList(List lb) { - if (lb == null || lb.size() == 0) + if(lb==null || lb.size()==0) return; Integer ab[] = lb.toArray(new Integer[0]); int a[] = new int[ab.length]; - for (int i = 0; i < ab.length; i++) + for(int i=0; i lb) { public List toList() { int[] a = toArray(); Integer ab[] = new Integer[a.length]; - for (int i = 0; i < a.length; i++) + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(int... a) { - if (a == null || a.length == 0) + public void fromArray(int...a) { + if(a==null || a.length==0) return; int num = a.length / _channels; alloc(num); @@ -51,21 +51,21 @@ public void fromArray(int... a) { public int[] toArray() { int num = checkVector(_channels, _depth); - if (num < 0) + if(num < 0) throw new RuntimeException("Native Mat has unexpected type or size: " + toString()); int[] a = new int[num * _channels]; - if (num == 0) + if(num == 0) return a; get(0, 0, a); //TODO: check ret val! return a; } public void fromList(List lb) { - if (lb == null || lb.size() == 0) + if(lb==null || lb.size()==0) return; Integer ab[] = lb.toArray(new Integer[0]); int a[] = new int[ab.length]; - for (int i = 0; i < ab.length; i++) + for(int i=0; i lb) { public List toList() { int[] a = toArray(); Integer ab[] = new Integer[a.length]; - for (int i = 0; i < a.length; i++) + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(KeyPoint... a) { - if (a == null || a.length == 0) + public void fromArray(KeyPoint...a) { + if(a==null || a.length==0) return; int num = a.length; alloc(num); float buff[] = new float[num * _channels]; - for (int i = 0; i < num; i++) { + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(Point... a) { - if (a == null || a.length == 0) + public void fromArray(Point...a) { + if(a==null || a.length==0) return; int num = a.length; alloc(num); int buff[] = new int[num * _channels]; - for (int i = 0; i < num; i++) { + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(Point... a) { - if (a == null || a.length == 0) + public void fromArray(Point...a) { + if(a==null || a.length==0) return; int num = a.length; alloc(num); float buff[] = new float[num * _channels]; - for (int i = 0; i < num; i++) { + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(Point3... a) { - if (a == null || a.length == 0) + public void fromArray(Point3...a) { + if(a==null || a.length==0) return; int num = a.length; alloc(num); int buff[] = new int[num * _channels]; - for (int i = 0; i < num; i++) { + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(Point3... a) { - if (a == null || a.length == 0) + public void fromArray(Point3...a) { + if(a==null || a.length==0) return; int num = a.length; alloc(num); float buff[] = new float[num * _channels]; - for (int i = 0; i < num; i++) { + for(int i=0; i 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(Rect... a) { - if (a == null || a.length == 0) + public void fromArray(Rect...a) { + if(a==null || a.length==0) return; int num = a.length; alloc(num); int buff[] = new int[num * _channels]; - for (int i = 0; i < num; i++) { + for(int i=0; i lr) { Rect ap[] = lr.toArray(new Rect[0]); fromArray(ap); diff --git a/bus-opencv/src/main/java/org/opencv/core/MatOfRect2d.java b/bus-opencv/src/main/java/org/opencv/core/MatOfRect2d.java index f6110364d1..71c4b1aef6 100644 --- a/bus-opencv/src/main/java/org/opencv/core/MatOfRect2d.java +++ b/bus-opencv/src/main/java/org/opencv/core/MatOfRect2d.java @@ -15,44 +15,44 @@ public MatOfRect2d() { protected MatOfRect2d(long addr) { super(addr); - if (!empty() && checkVector(_channels, _depth) < 0) + if( !empty() && checkVector(_channels, _depth) < 0 ) throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } + public static MatOfRect2d fromNativeAddr(long addr) { + return new MatOfRect2d(addr); + } + public MatOfRect2d(Mat m) { super(m, Range.all()); - if (!empty() && checkVector(_channels, _depth) < 0) + if( !empty() && checkVector(_channels, _depth) < 0 ) throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } - public MatOfRect2d(Rect2d... a) { + public MatOfRect2d(Rect2d...a) { super(); fromArray(a); } - public static MatOfRect2d fromNativeAddr(long addr) { - return new MatOfRect2d(addr); - } - public void alloc(int elemNumber) { - if (elemNumber > 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(Rect2d... a) { - if (a == null || a.length == 0) + public void fromArray(Rect2d...a) { + if(a==null || a.length==0) return; int num = a.length; alloc(num); double buff[] = new double[num * _channels]; - for (int i = 0; i < num; i++) { + for(int i=0; i lr) { Rect2d ap[] = lr.toArray(new Rect2d[0]); fromArray(ap); diff --git a/bus-opencv/src/main/java/org/opencv/core/MatOfRotatedRect.java b/bus-opencv/src/main/java/org/opencv/core/MatOfRotatedRect.java index 57cd5be790..902005ea4e 100644 --- a/bus-opencv/src/main/java/org/opencv/core/MatOfRotatedRect.java +++ b/bus-opencv/src/main/java/org/opencv/core/MatOfRotatedRect.java @@ -4,6 +4,7 @@ import java.util.List; + public class MatOfRotatedRect extends Mat { // 32FC5 private static final int _depth = CvType.CV_32F; @@ -15,45 +16,45 @@ public MatOfRotatedRect() { protected MatOfRotatedRect(long addr) { super(addr); - if (!empty() && checkVector(_channels, _depth) < 0) + if( !empty() && checkVector(_channels, _depth) < 0 ) throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } + public static MatOfRotatedRect fromNativeAddr(long addr) { + return new MatOfRotatedRect(addr); + } + public MatOfRotatedRect(Mat m) { super(m, Range.all()); - if (!empty() && checkVector(_channels, _depth) < 0) + if( !empty() && checkVector(_channels, _depth) < 0 ) throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } - public MatOfRotatedRect(RotatedRect... a) { + public MatOfRotatedRect(RotatedRect...a) { super(); fromArray(a); } - public static MatOfRotatedRect fromNativeAddr(long addr) { - return new MatOfRotatedRect(addr); - } - public void alloc(int elemNumber) { - if (elemNumber > 0) + if(elemNumber>0) super.create(elemNumber, 1, CvType.makeType(_depth, _channels)); } - public void fromArray(RotatedRect... a) { - if (a == null || a.length == 0) + public void fromArray(RotatedRect...a) { + if(a==null || a.length==0) return; int num = a.length; alloc(num); float buff[] = new float[num * _channels]; - for (int i = 0; i < num; i++) { + for(int i=0; i 0 ? (int) vals[0] : 0; @@ -41,6 +37,10 @@ public boolean empty() { return end <= start; } + public static Range all() { + return new Range(Integer.MIN_VALUE, Integer.MAX_VALUE); + } + public Range intersection(Range r1) { Range r = new Range(Math.max(r1.start, this.start), Math.min(r1.end, this.end)); r.end = Math.max(r.end, r.start); diff --git a/bus-opencv/src/main/java/org/opencv/core/RotatedRect.java b/bus-opencv/src/main/java/org/opencv/core/RotatedRect.java index 7762a00c7d..05ee3811fe 100644 --- a/bus-opencv/src/main/java/org/opencv/core/RotatedRect.java +++ b/bus-opencv/src/main/java/org/opencv/core/RotatedRect.java @@ -40,7 +40,8 @@ public void set(double[] vals) { } } - public void points(Point pt[]) { + public void points(Point pt[]) + { double _angle = angle * Math.PI / 180.0; double b = (double) Math.cos(_angle) * 0.5f; double a = (double) Math.sin(_angle) * 0.5f; @@ -62,7 +63,8 @@ public void points(Point pt[]) { 2 * center.y - pt[1].y); } - public Rect boundingRect() { + public Rect boundingRect() + { Point pt[] = new Point[4]; points(pt); Rect r = new Rect((int) Math.floor(Math.min(Math.min(Math.min(pt[0].x, pt[1].x), pt[2].x), pt[3].x)), @@ -108,5 +110,4 @@ public boolean equals(Object obj) { public String toString() { return "{ " + center + " " + size + " * " + angle + " }"; } - } diff --git a/bus-opencv/src/main/java/org/opencv/core/Scalar.java b/bus-opencv/src/main/java/org/opencv/core/Scalar.java index 4b1032b5a2..01676e4cb5 100644 --- a/bus-opencv/src/main/java/org/opencv/core/Scalar.java +++ b/bus-opencv/src/main/java/org/opencv/core/Scalar.java @@ -6,19 +6,19 @@ public class Scalar { public double val[]; public Scalar(double v0, double v1, double v2, double v3) { - val = new double[]{v0, v1, v2, v3}; + val = new double[] { v0, v1, v2, v3 }; } public Scalar(double v0, double v1, double v2) { - val = new double[]{v0, v1, v2, 0}; + val = new double[] { v0, v1, v2, 0 }; } public Scalar(double v0, double v1) { - val = new double[]{v0, v1, 0, 0}; + val = new double[] { v0, v1, 0, 0 }; } public Scalar(double v0) { - val = new double[]{v0, 0, 0, 0}; + val = new double[] { v0, 0, 0, 0 }; } public Scalar(double[] vals) { @@ -30,10 +30,6 @@ public Scalar(double[] vals) { } } - public static Scalar all(double v) { - return new Scalar(v, v, v, v); - } - public void set(double[] vals) { if (vals != null) { val[0] = vals.length > 0 ? vals[0] : 0; @@ -44,6 +40,10 @@ public void set(double[] vals) { val[0] = val[1] = val[2] = val[3] = 0; } + public static Scalar all(double v) { + return new Scalar(v, v, v, v); + } + public Scalar clone() { return new Scalar(val); } diff --git a/bus-opencv/src/main/java/org/opencv/core/Size.java b/bus-opencv/src/main/java/org/opencv/core/Size.java index 68ea973878..f7d69f37cd 100644 --- a/bus-opencv/src/main/java/org/opencv/core/Size.java +++ b/bus-opencv/src/main/java/org/opencv/core/Size.java @@ -67,7 +67,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return (int) width + "x" + (int) height; + return (int)width + "x" + (int)height; } } diff --git a/bus-opencv/src/main/java/org/opencv/core/TermCriteria.java b/bus-opencv/src/main/java/org/opencv/core/TermCriteria.java index 952e0507af..c67e51ea8d 100644 --- a/bus-opencv/src/main/java/org/opencv/core/TermCriteria.java +++ b/bus-opencv/src/main/java/org/opencv/core/TermCriteria.java @@ -23,9 +23,12 @@ public class TermCriteria { /** * Termination criteria for iterative algorithms. * - * @param type the type of termination criteria: COUNT, EPS or COUNT + EPS. - * @param maxCount the maximum number of iterations/elements. - * @param epsilon the desired accuracy. + * @param type + * the type of termination criteria: COUNT, EPS or COUNT + EPS. + * @param maxCount + * the maximum number of iterations/elements. + * @param epsilon + * the desired accuracy. */ public TermCriteria(int type, int maxCount, double epsilon) { this.type = type; diff --git a/bus-opencv/src/main/java/org/opencv/core/TickMeter.java b/bus-opencv/src/main/java/org/opencv/core/TickMeter.java index 9b9e1b0e4d..1d08700d9c 100644 --- a/bus-opencv/src/main/java/org/opencv/core/TickMeter.java +++ b/bus-opencv/src/main/java/org/opencv/core/TickMeter.java @@ -4,187 +4,183 @@ package org.opencv.core; -// C++: class TickMeter +// C++: class TickMeter /** * a Class to measure passing time. - *

    + * * The class computes passing time by counting the number of ticks per second. That is, the following code computes the * execution time in seconds: * SNIPPET: snippets/core_various.cpp TickMeter_total - *

    + * * It is also possible to compute the average time over multiple runs: * SNIPPET: snippets/core_various.cpp TickMeter_average - *

    + * * SEE: getTickCount, getTickFrequency */ public class TickMeter { protected final long nativeObj; - protected TickMeter(long addr) { - nativeObj = addr; - + nativeObj = addr; + long nativeObjCopy = nativeObj; + org.opencv.core.Mat.cleaner.register(this, () -> delete(nativeObjCopy)); } - public TickMeter() { - this(TickMeter_0()); - } + public long getNativeObjAddr() { return nativeObj; } // internal usage only - public static TickMeter __fromPtr__(long addr) { - return new TickMeter(addr); - } + public static TickMeter __fromPtr__(long addr) { return new TickMeter(addr); } // // C++: cv::TickMeter::TickMeter() // - // C++: cv::TickMeter::TickMeter() - private static native long TickMeter_0(); + public TickMeter() { + nativeObj = TickMeter_0(); + long nativeObjCopy = nativeObj; + org.opencv.core.Mat.cleaner.register(this, () -> delete(nativeObjCopy)); + } // // C++: void cv::TickMeter::start() // - // C++: void cv::TickMeter::start() - private static native void start_0(long nativeObj); + public void start() { + start_0(nativeObj); + } // // C++: void cv::TickMeter::stop() // - // C++: void cv::TickMeter::stop() - private static native void stop_0(long nativeObj); + public void stop() { + stop_0(nativeObj); + } // // C++: int64 cv::TickMeter::getTimeTicks() // - // C++: int64 cv::TickMeter::getTimeTicks() - private static native long getTimeTicks_0(long nativeObj); + public long getTimeTicks() { + return getTimeTicks_0(nativeObj); + } // // C++: double cv::TickMeter::getTimeMicro() // - // C++: double cv::TickMeter::getTimeMicro() - private static native double getTimeMicro_0(long nativeObj); + public double getTimeMicro() { + return getTimeMicro_0(nativeObj); + } // // C++: double cv::TickMeter::getTimeMilli() // - // C++: double cv::TickMeter::getTimeMilli() - private static native double getTimeMilli_0(long nativeObj); + public double getTimeMilli() { + return getTimeMilli_0(nativeObj); + } // // C++: double cv::TickMeter::getTimeSec() // - // C++: double cv::TickMeter::getTimeSec() - private static native double getTimeSec_0(long nativeObj); + public double getTimeSec() { + return getTimeSec_0(nativeObj); + } // // C++: int64 cv::TickMeter::getCounter() // - // C++: int64 cv::TickMeter::getCounter() - private static native long getCounter_0(long nativeObj); + public long getCounter() { + return getCounter_0(nativeObj); + } // // C++: double cv::TickMeter::getFPS() // - // C++: double cv::TickMeter::getFPS() - private static native double getFPS_0(long nativeObj); + public double getFPS() { + return getFPS_0(nativeObj); + } // // C++: double cv::TickMeter::getAvgTimeSec() // - // C++: double cv::TickMeter::getAvgTimeSec() - private static native double getAvgTimeSec_0(long nativeObj); + public double getAvgTimeSec() { + return getAvgTimeSec_0(nativeObj); + } // // C++: double cv::TickMeter::getAvgTimeMilli() // - // C++: double cv::TickMeter::getAvgTimeMilli() - private static native double getAvgTimeMilli_0(long nativeObj); + public double getAvgTimeMilli() { + return getAvgTimeMilli_0(nativeObj); + } // // C++: void cv::TickMeter::reset() // - // C++: void cv::TickMeter::reset() - private static native void reset_0(long nativeObj); + public void reset() { + reset_0(nativeObj); + } - // native support for deleting native object - private static native void delete(long nativeObj); - public long getNativeObjAddr() { - return nativeObj; - } - public void start() { - start_0(nativeObj); - } - public void stop() { - stop_0(nativeObj); - } + // C++: cv::TickMeter::TickMeter() + private static native long TickMeter_0(); - public long getTimeTicks() { - return getTimeTicks_0(nativeObj); - } + // C++: void cv::TickMeter::start() + private static native void start_0(long nativeObj); - public double getTimeMicro() { - return getTimeMicro_0(nativeObj); - } + // C++: void cv::TickMeter::stop() + private static native void stop_0(long nativeObj); - public double getTimeMilli() { - return getTimeMilli_0(nativeObj); - } + // C++: int64 cv::TickMeter::getTimeTicks() + private static native long getTimeTicks_0(long nativeObj); - public double getTimeSec() { - return getTimeSec_0(nativeObj); - } + // C++: double cv::TickMeter::getTimeMicro() + private static native double getTimeMicro_0(long nativeObj); - public long getCounter() { - return getCounter_0(nativeObj); - } + // C++: double cv::TickMeter::getTimeMilli() + private static native double getTimeMilli_0(long nativeObj); - public double getFPS() { - return getFPS_0(nativeObj); - } + // C++: double cv::TickMeter::getTimeSec() + private static native double getTimeSec_0(long nativeObj); - public double getAvgTimeSec() { - return getAvgTimeSec_0(nativeObj); - } + // C++: int64 cv::TickMeter::getCounter() + private static native long getCounter_0(long nativeObj); - public double getAvgTimeMilli() { - return getAvgTimeMilli_0(nativeObj); - } + // C++: double cv::TickMeter::getFPS() + private static native double getFPS_0(long nativeObj); - public void reset() { - reset_0(nativeObj); - } + // C++: double cv::TickMeter::getAvgTimeSec() + private static native double getAvgTimeSec_0(long nativeObj); - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } + // C++: double cv::TickMeter::getAvgTimeMilli() + private static native double getAvgTimeMilli_0(long nativeObj); + + // C++: void cv::TickMeter::reset() + private static native void reset_0(long nativeObj); + + // native support for deleting native object + private static native void delete(long nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/img_hash/AverageHash.java b/bus-opencv/src/main/java/org/opencv/img_hash/AverageHash.java index 17d94f42ed..feff464169 100644 --- a/bus-opencv/src/main/java/org/opencv/img_hash/AverageHash.java +++ b/bus-opencv/src/main/java/org/opencv/img_hash/AverageHash.java @@ -4,23 +4,18 @@ package org.opencv.img_hash; // C++: class AverageHash - /** * Computes average hash value of the input image - *

    + * * This is a fast image hashing algorithm, but only work on simple case. For more details, please * refer to CITE: lookslikeit */ public class AverageHash extends ImgHashBase { - protected AverageHash(long addr) { - super(addr); - } + protected AverageHash(long addr) { super(addr); } // internal usage only - public static AverageHash __fromPtr__(long addr) { - return new AverageHash(addr); - } + public static AverageHash __fromPtr__(long addr) { return new AverageHash(addr); } // // C++: static Ptr_AverageHash cv::img_hash::AverageHash::create() @@ -30,15 +25,13 @@ public static AverageHash create() { return AverageHash.__fromPtr__(create_0()); } + + + // C++: static Ptr_AverageHash cv::img_hash::AverageHash::create() private static native long create_0(); // native support for deleting native object private static native void delete(long nativeObj); - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } - } diff --git a/bus-opencv/src/main/java/org/opencv/img_hash/BlockMeanHash.java b/bus-opencv/src/main/java/org/opencv/img_hash/BlockMeanHash.java index ddb6f53e7f..f0078508bf 100644 --- a/bus-opencv/src/main/java/org/opencv/img_hash/BlockMeanHash.java +++ b/bus-opencv/src/main/java/org/opencv/img_hash/BlockMeanHash.java @@ -6,29 +6,28 @@ import org.opencv.core.MatOfDouble; // C++: class BlockMeanHash - /** * Image hash based on block mean. - *

    + * * See CITE: zauner2010implementation for details. */ public class BlockMeanHash extends ImgHashBase { - protected BlockMeanHash(long addr) { - super(addr); - } + protected BlockMeanHash(long addr) { super(addr); } // internal usage only - public static BlockMeanHash __fromPtr__(long addr) { - return new BlockMeanHash(addr); - } + public static BlockMeanHash __fromPtr__(long addr) { return new BlockMeanHash(addr); } // // C++: void cv::img_hash::BlockMeanHash::setMode(int mode) // - public static BlockMeanHash create(int mode) { - return BlockMeanHash.__fromPtr__(create_0(mode)); + /** + * Create BlockMeanHash object + * @param mode the mode + */ + public void setMode(int mode) { + setMode_0(nativeObj, mode); } @@ -36,8 +35,8 @@ public static BlockMeanHash create(int mode) { // C++: vector_double cv::img_hash::BlockMeanHash::getMean() // - public static BlockMeanHash create() { - return BlockMeanHash.__fromPtr__(create_1()); + public MatOfDouble getMean() { + return MatOfDouble.fromNativeAddr(getMean_0(nativeObj)); } @@ -45,6 +44,17 @@ public static BlockMeanHash create() { // C++: static Ptr_BlockMeanHash cv::img_hash::BlockMeanHash::create(int mode = BLOCK_MEAN_HASH_MODE_0) // + public static BlockMeanHash create(int mode) { + return BlockMeanHash.__fromPtr__(create_0(mode)); + } + + public static BlockMeanHash create() { + return BlockMeanHash.__fromPtr__(create_1()); + } + + + + // C++: void cv::img_hash::BlockMeanHash::setMode(int mode) private static native void setMode_0(long nativeObj, int mode); @@ -53,28 +63,9 @@ public static BlockMeanHash create() { // C++: static Ptr_BlockMeanHash cv::img_hash::BlockMeanHash::create(int mode = BLOCK_MEAN_HASH_MODE_0) private static native long create_0(int mode); - private static native long create_1(); // native support for deleting native object private static native void delete(long nativeObj); - /** - * Create BlockMeanHash object - * - * @param mode the mode - */ - public void setMode(int mode) { - setMode_0(nativeObj, mode); - } - - public MatOfDouble getMean() { - return MatOfDouble.fromNativeAddr(getMean_0(nativeObj)); - } - - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } - } diff --git a/bus-opencv/src/main/java/org/opencv/img_hash/ColorMomentHash.java b/bus-opencv/src/main/java/org/opencv/img_hash/ColorMomentHash.java index f17830b2d3..128c49fa0c 100644 --- a/bus-opencv/src/main/java/org/opencv/img_hash/ColorMomentHash.java +++ b/bus-opencv/src/main/java/org/opencv/img_hash/ColorMomentHash.java @@ -4,22 +4,17 @@ package org.opencv.img_hash; // C++: class ColorMomentHash - /** * Image hash based on color moments. - *

    + * * See CITE: tang2012perceptual for details. */ public class ColorMomentHash extends ImgHashBase { - protected ColorMomentHash(long addr) { - super(addr); - } + protected ColorMomentHash(long addr) { super(addr); } // internal usage only - public static ColorMomentHash __fromPtr__(long addr) { - return new ColorMomentHash(addr); - } + public static ColorMomentHash __fromPtr__(long addr) { return new ColorMomentHash(addr); } // // C++: static Ptr_ColorMomentHash cv::img_hash::ColorMomentHash::create() @@ -29,15 +24,13 @@ public static ColorMomentHash create() { return ColorMomentHash.__fromPtr__(create_0()); } + + + // C++: static Ptr_ColorMomentHash cv::img_hash::ColorMomentHash::create() private static native long create_0(); // native support for deleting native object private static native void delete(long nativeObj); - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } - } diff --git a/bus-opencv/src/main/java/org/opencv/img_hash/ImgHashBase.java b/bus-opencv/src/main/java/org/opencv/img_hash/ImgHashBase.java index 4dc644568c..5c2454ad7b 100644 --- a/bus-opencv/src/main/java/org/opencv/img_hash/ImgHashBase.java +++ b/bus-opencv/src/main/java/org/opencv/img_hash/ImgHashBase.java @@ -7,64 +7,55 @@ import org.opencv.core.Mat; // C++: class ImgHashBase - /** * The base class for image hash algorithms */ public class ImgHashBase extends Algorithm { - protected ImgHashBase(long addr) { - super(addr); - } + protected ImgHashBase(long addr) { super(addr); } // internal usage only - public static ImgHashBase __fromPtr__(long addr) { - return new ImgHashBase(addr); - } + public static ImgHashBase __fromPtr__(long addr) { return new ImgHashBase(addr); } // // C++: void cv::img_hash::ImgHashBase::compute(Mat inputArr, Mat& outputArr) // - // C++: void cv::img_hash::ImgHashBase::compute(Mat inputArr, Mat& outputArr) - private static native void compute_0(long nativeObj, long inputArr_nativeObj, long outputArr_nativeObj); - - - // - // C++: double cv::img_hash::ImgHashBase::compare(Mat hashOne, Mat hashTwo) - // - - // C++: double cv::img_hash::ImgHashBase::compare(Mat hashOne, Mat hashTwo) - private static native double compare_0(long nativeObj, long hashOne_nativeObj, long hashTwo_nativeObj); - - // native support for deleting native object - private static native void delete(long nativeObj); - /** * Computes hash of the input image - * - * @param inputArr input image want to compute hash value - * @param outputArr hash of the image + * @param inputArr input image want to compute hash value + * @param outputArr hash of the image */ public void compute(Mat inputArr, Mat outputArr) { compute_0(nativeObj, inputArr.nativeObj, outputArr.nativeObj); } + + // + // C++: double cv::img_hash::ImgHashBase::compare(Mat hashOne, Mat hashTwo) + // + /** * Compare the hash value between inOne and inTwo - * - * @param hashOne Hash value one - * @param hashTwo Hash value two - * @return value indicate similarity between inOne and inTwo, the meaning - * of the value vary from algorithms to algorithms + * @param hashOne Hash value one + * @param hashTwo Hash value two + * @return value indicate similarity between inOne and inTwo, the meaning + * of the value vary from algorithms to algorithms */ public double compare(Mat hashOne, Mat hashTwo) { return compare_0(nativeObj, hashOne.nativeObj, hashTwo.nativeObj); } - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } + + + + // C++: void cv::img_hash::ImgHashBase::compute(Mat inputArr, Mat& outputArr) + private static native void compute_0(long nativeObj, long inputArr_nativeObj, long outputArr_nativeObj); + + // C++: double cv::img_hash::ImgHashBase::compare(Mat hashOne, Mat hashTwo) + private static native double compare_0(long nativeObj, long hashOne_nativeObj, long hashTwo_nativeObj); + + // native support for deleting native object + private static native void delete(long nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/img_hash/Img_hash.java b/bus-opencv/src/main/java/org/opencv/img_hash/Img_hash.java index c22e669f21..732be48bd0 100644 --- a/bus-opencv/src/main/java/org/opencv/img_hash/Img_hash.java +++ b/bus-opencv/src/main/java/org/opencv/img_hash/Img_hash.java @@ -15,14 +15,28 @@ public class Img_hash { BLOCK_MEAN_HASH_MODE_1 = 1; + // + // C++: void cv::img_hash::pHash(Mat inputArr, Mat& outputArr) + // + + /** + * Computes pHash value of the input image + * @param inputArr input image want to compute hash value, + * type should be CV_8UC4, CV_8UC3, CV_8UC1. + * @param outputArr Hash value of input, it will contain 8 uchar value + */ + public static void pHash(Mat inputArr, Mat outputArr) { + pHash_0(inputArr.nativeObj, outputArr.nativeObj); + } + + // // C++: void cv::img_hash::averageHash(Mat inputArr, Mat& outputArr) // /** * Calculates img_hash::AverageHash in one call - * - * @param inputArr input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. + * @param inputArr input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. * @param outputArr Hash value of input, it will contain 16 hex decimal number, return type is CV_8U */ public static void averageHash(Mat inputArr, Mat outputArr) { @@ -36,10 +50,9 @@ public static void averageHash(Mat inputArr, Mat outputArr) { /** * Computes block mean hash of the input image - * - * @param inputArr input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. - * @param outputArr Hash value of input, it will contain 16 hex decimal number, return type is CV_8U - * @param mode the mode + * @param inputArr input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. + * @param outputArr Hash value of input, it will contain 16 hex decimal number, return type is CV_8U + * @param mode the mode */ public static void blockMeanHash(Mat inputArr, Mat outputArr, int mode) { blockMeanHash_0(inputArr.nativeObj, outputArr.nativeObj, mode); @@ -47,9 +60,8 @@ public static void blockMeanHash(Mat inputArr, Mat outputArr, int mode) { /** * Computes block mean hash of the input image - * - * @param inputArr input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. - * @param outputArr Hash value of input, it will contain 16 hex decimal number, return type is CV_8U + * @param inputArr input image want to compute hash value, type should be CV_8UC4, CV_8UC3 or CV_8UC1. + * @param outputArr Hash value of input, it will contain 16 hex decimal number, return type is CV_8U */ public static void blockMeanHash(Mat inputArr, Mat outputArr) { blockMeanHash_1(inputArr.nativeObj, outputArr.nativeObj); @@ -57,20 +69,40 @@ public static void blockMeanHash(Mat inputArr, Mat outputArr) { // - // C++: void cv::img_hash::colorMomentHash(Mat inputArr, Mat& outputArr) + // C++: void cv::img_hash::radialVarianceHash(Mat inputArr, Mat& outputArr, double sigma = 1, int numOfAngleLine = 180) // /** - * Computes color moment hash of the input, the algorithm - * is come from the paper "Perceptual Hashing for Color Images - * Using Invariant Moments" - * - * @param inputArr input image want to compute hash value, - * type should be CV_8UC4, CV_8UC3 or CV_8UC1. - * @param outputArr 42 hash values with type CV_64F(double) + * Computes radial variance hash of the input image + * @param inputArr input image want to compute hash value, + * type should be CV_8UC4, CV_8UC3, CV_8UC1. + * @param outputArr Hash value of input + * @param sigma Gaussian kernel standard deviation + * @param numOfAngleLine The number of angles to consider */ - public static void colorMomentHash(Mat inputArr, Mat outputArr) { - colorMomentHash_0(inputArr.nativeObj, outputArr.nativeObj); + public static void radialVarianceHash(Mat inputArr, Mat outputArr, double sigma, int numOfAngleLine) { + radialVarianceHash_0(inputArr.nativeObj, outputArr.nativeObj, sigma, numOfAngleLine); + } + + /** + * Computes radial variance hash of the input image + * @param inputArr input image want to compute hash value, + * type should be CV_8UC4, CV_8UC3, CV_8UC1. + * @param outputArr Hash value of input + * @param sigma Gaussian kernel standard deviation + */ + public static void radialVarianceHash(Mat inputArr, Mat outputArr, double sigma) { + radialVarianceHash_1(inputArr.nativeObj, outputArr.nativeObj, sigma); + } + + /** + * Computes radial variance hash of the input image + * @param inputArr input image want to compute hash value, + * type should be CV_8UC4, CV_8UC3, CV_8UC1. + * @param outputArr Hash value of input + */ + public static void radialVarianceHash(Mat inputArr, Mat outputArr) { + radialVarianceHash_2(inputArr.nativeObj, outputArr.nativeObj); } @@ -80,13 +112,12 @@ public static void colorMomentHash(Mat inputArr, Mat outputArr) { /** * Computes average hash value of the input image - * - * @param inputArr input image want to compute hash value, - * type should be CV_8UC4, CV_8UC3, CV_8UC1. - * @param outputArr Hash value of input, it will contain 16 hex - * decimal number, return type is CV_8U - * @param alpha int scale factor for marr wavelet (default=2). - * @param scale int level of scale factor (default = 1) + * @param inputArr input image want to compute hash value, + * type should be CV_8UC4, CV_8UC3, CV_8UC1. + * @param outputArr Hash value of input, it will contain 16 hex + * decimal number, return type is CV_8U + * @param alpha int scale factor for marr wavelet (default=2). + * @param scale int level of scale factor (default = 1) */ public static void marrHildrethHash(Mat inputArr, Mat outputArr, float alpha, float scale) { marrHildrethHash_0(inputArr.nativeObj, outputArr.nativeObj, alpha, scale); @@ -94,12 +125,11 @@ public static void marrHildrethHash(Mat inputArr, Mat outputArr, float alpha, fl /** * Computes average hash value of the input image - * - * @param inputArr input image want to compute hash value, - * type should be CV_8UC4, CV_8UC3, CV_8UC1. - * @param outputArr Hash value of input, it will contain 16 hex - * decimal number, return type is CV_8U - * @param alpha int scale factor for marr wavelet (default=2). + * @param inputArr input image want to compute hash value, + * type should be CV_8UC4, CV_8UC3, CV_8UC1. + * @param outputArr Hash value of input, it will contain 16 hex + * decimal number, return type is CV_8U + * @param alpha int scale factor for marr wavelet (default=2). */ public static void marrHildrethHash(Mat inputArr, Mat outputArr, float alpha) { marrHildrethHash_1(inputArr.nativeObj, outputArr.nativeObj, alpha); @@ -107,11 +137,10 @@ public static void marrHildrethHash(Mat inputArr, Mat outputArr, float alpha) { /** * Computes average hash value of the input image - * - * @param inputArr input image want to compute hash value, - * type should be CV_8UC4, CV_8UC3, CV_8UC1. - * @param outputArr Hash value of input, it will contain 16 hex - * decimal number, return type is CV_8U + * @param inputArr input image want to compute hash value, + * type should be CV_8UC4, CV_8UC3, CV_8UC1. + * @param outputArr Hash value of input, it will contain 16 hex + * decimal number, return type is CV_8U */ public static void marrHildrethHash(Mat inputArr, Mat outputArr) { marrHildrethHash_2(inputArr.nativeObj, outputArr.nativeObj); @@ -119,88 +148,45 @@ public static void marrHildrethHash(Mat inputArr, Mat outputArr) { // - // C++: void cv::img_hash::pHash(Mat inputArr, Mat& outputArr) + // C++: void cv::img_hash::colorMomentHash(Mat inputArr, Mat& outputArr) // /** - * Computes pHash value of the input image - * - * @param inputArr input image want to compute hash value, - * type should be CV_8UC4, CV_8UC3, CV_8UC1. - * @param outputArr Hash value of input, it will contain 8 uchar value + * Computes color moment hash of the input, the algorithm + * is come from the paper "Perceptual Hashing for Color Images + * Using Invariant Moments" + * @param inputArr input image want to compute hash value, + * type should be CV_8UC4, CV_8UC3 or CV_8UC1. + * @param outputArr 42 hash values with type CV_64F(double) */ - public static void pHash(Mat inputArr, Mat outputArr) { - pHash_0(inputArr.nativeObj, outputArr.nativeObj); + public static void colorMomentHash(Mat inputArr, Mat outputArr) { + colorMomentHash_0(inputArr.nativeObj, outputArr.nativeObj); } - // - // C++: void cv::img_hash::radialVarianceHash(Mat inputArr, Mat& outputArr, double sigma = 1, int numOfAngleLine = 180) - // - - /** - * Computes radial variance hash of the input image - * - * @param inputArr input image want to compute hash value, - * type should be CV_8UC4, CV_8UC3, CV_8UC1. - * @param outputArr Hash value of input - * @param sigma Gaussian kernel standard deviation - * @param numOfAngleLine The number of angles to consider - */ - public static void radialVarianceHash(Mat inputArr, Mat outputArr, double sigma, int numOfAngleLine) { - radialVarianceHash_0(inputArr.nativeObj, outputArr.nativeObj, sigma, numOfAngleLine); - } - - /** - * Computes radial variance hash of the input image - * - * @param inputArr input image want to compute hash value, - * type should be CV_8UC4, CV_8UC3, CV_8UC1. - * @param outputArr Hash value of input - * @param sigma Gaussian kernel standard deviation - */ - public static void radialVarianceHash(Mat inputArr, Mat outputArr, double sigma) { - radialVarianceHash_1(inputArr.nativeObj, outputArr.nativeObj, sigma); - } - /** - * Computes radial variance hash of the input image - * - * @param inputArr input image want to compute hash value, - * type should be CV_8UC4, CV_8UC3, CV_8UC1. - * @param outputArr Hash value of input - */ - public static void radialVarianceHash(Mat inputArr, Mat outputArr) { - radialVarianceHash_2(inputArr.nativeObj, outputArr.nativeObj); - } + // C++: void cv::img_hash::pHash(Mat inputArr, Mat& outputArr) + private static native void pHash_0(long inputArr_nativeObj, long outputArr_nativeObj); // C++: void cv::img_hash::averageHash(Mat inputArr, Mat& outputArr) private static native void averageHash_0(long inputArr_nativeObj, long outputArr_nativeObj); // C++: void cv::img_hash::blockMeanHash(Mat inputArr, Mat& outputArr, int mode = BLOCK_MEAN_HASH_MODE_0) private static native void blockMeanHash_0(long inputArr_nativeObj, long outputArr_nativeObj, int mode); - private static native void blockMeanHash_1(long inputArr_nativeObj, long outputArr_nativeObj); - // C++: void cv::img_hash::colorMomentHash(Mat inputArr, Mat& outputArr) - private static native void colorMomentHash_0(long inputArr_nativeObj, long outputArr_nativeObj); + // C++: void cv::img_hash::radialVarianceHash(Mat inputArr, Mat& outputArr, double sigma = 1, int numOfAngleLine = 180) + private static native void radialVarianceHash_0(long inputArr_nativeObj, long outputArr_nativeObj, double sigma, int numOfAngleLine); + private static native void radialVarianceHash_1(long inputArr_nativeObj, long outputArr_nativeObj, double sigma); + private static native void radialVarianceHash_2(long inputArr_nativeObj, long outputArr_nativeObj); // C++: void cv::img_hash::marrHildrethHash(Mat inputArr, Mat& outputArr, float alpha = 2.0f, float scale = 1.0f) private static native void marrHildrethHash_0(long inputArr_nativeObj, long outputArr_nativeObj, float alpha, float scale); - private static native void marrHildrethHash_1(long inputArr_nativeObj, long outputArr_nativeObj, float alpha); - private static native void marrHildrethHash_2(long inputArr_nativeObj, long outputArr_nativeObj); - // C++: void cv::img_hash::pHash(Mat inputArr, Mat& outputArr) - private static native void pHash_0(long inputArr_nativeObj, long outputArr_nativeObj); - - // C++: void cv::img_hash::radialVarianceHash(Mat inputArr, Mat& outputArr, double sigma = 1, int numOfAngleLine = 180) - private static native void radialVarianceHash_0(long inputArr_nativeObj, long outputArr_nativeObj, double sigma, int numOfAngleLine); - - private static native void radialVarianceHash_1(long inputArr_nativeObj, long outputArr_nativeObj, double sigma); - - private static native void radialVarianceHash_2(long inputArr_nativeObj, long outputArr_nativeObj); + // C++: void cv::img_hash::colorMomentHash(Mat inputArr, Mat& outputArr) + private static native void colorMomentHash_0(long inputArr_nativeObj, long outputArr_nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/img_hash/MarrHildrethHash.java b/bus-opencv/src/main/java/org/opencv/img_hash/MarrHildrethHash.java index 3dab4efea4..a85e4153d6 100644 --- a/bus-opencv/src/main/java/org/opencv/img_hash/MarrHildrethHash.java +++ b/bus-opencv/src/main/java/org/opencv/img_hash/MarrHildrethHash.java @@ -4,34 +4,28 @@ package org.opencv.img_hash; // C++: class MarrHildrethHash - /** * Marr-Hildreth Operator Based Hash, slowest but more discriminative. - *

    + * * See CITE: zauner2010implementation for details. */ public class MarrHildrethHash extends ImgHashBase { - protected MarrHildrethHash(long addr) { - super(addr); - } + protected MarrHildrethHash(long addr) { super(addr); } // internal usage only - public static MarrHildrethHash __fromPtr__(long addr) { - return new MarrHildrethHash(addr); - } + public static MarrHildrethHash __fromPtr__(long addr) { return new MarrHildrethHash(addr); } // // C++: float cv::img_hash::MarrHildrethHash::getAlpha() // /** - * @param alpha int scale factor for marr wavelet (default=2). - * @param scale int level of scale factor (default = 1) + * self explain * @return automatically generated */ - public static MarrHildrethHash create(float alpha, float scale) { - return MarrHildrethHash.__fromPtr__(create_0(alpha, scale)); + public float getAlpha() { + return getAlpha_0(nativeObj); } @@ -40,11 +34,11 @@ public static MarrHildrethHash create(float alpha, float scale) { // /** - * @param alpha int scale factor for marr wavelet (default=2). + * self explain * @return automatically generated */ - public static MarrHildrethHash create(float alpha) { - return MarrHildrethHash.__fromPtr__(create_1(alpha)); + public float getScale() { + return getScale_0(nativeObj); } @@ -53,10 +47,12 @@ public static MarrHildrethHash create(float alpha) { // /** - * @return automatically generated + * Set Mh kernel parameters + * @param alpha int scale factor for marr wavelet (default=2). + * @param scale int level of scale factor (default = 1) */ - public static MarrHildrethHash create() { - return MarrHildrethHash.__fromPtr__(create_2()); + public void setKernelParam(float alpha, float scale) { + setKernelParam_0(nativeObj, alpha, scale); } @@ -64,6 +60,33 @@ public static MarrHildrethHash create() { // C++: static Ptr_MarrHildrethHash cv::img_hash::MarrHildrethHash::create(float alpha = 2.0f, float scale = 1.0f) // + /** + * @param alpha int scale factor for marr wavelet (default=2). + * @param scale int level of scale factor (default = 1) + * @return automatically generated + */ + public static MarrHildrethHash create(float alpha, float scale) { + return MarrHildrethHash.__fromPtr__(create_0(alpha, scale)); + } + + /** + * @param alpha int scale factor for marr wavelet (default=2). + * @return automatically generated + */ + public static MarrHildrethHash create(float alpha) { + return MarrHildrethHash.__fromPtr__(create_1(alpha)); + } + + /** + * @return automatically generated + */ + public static MarrHildrethHash create() { + return MarrHildrethHash.__fromPtr__(create_2()); + } + + + + // C++: float cv::img_hash::MarrHildrethHash::getAlpha() private static native float getAlpha_0(long nativeObj); @@ -75,45 +98,10 @@ public static MarrHildrethHash create() { // C++: static Ptr_MarrHildrethHash cv::img_hash::MarrHildrethHash::create(float alpha = 2.0f, float scale = 1.0f) private static native long create_0(float alpha, float scale); - private static native long create_1(float alpha); - private static native long create_2(); // native support for deleting native object private static native void delete(long nativeObj); - /** - * self explain - * - * @return automatically generated - */ - public float getAlpha() { - return getAlpha_0(nativeObj); - } - - /** - * self explain - * - * @return automatically generated - */ - public float getScale() { - return getScale_0(nativeObj); - } - - /** - * Set Mh kernel parameters - * - * @param alpha int scale factor for marr wavelet (default=2). - * @param scale int level of scale factor (default = 1) - */ - public void setKernelParam(float alpha, float scale) { - setKernelParam_0(nativeObj, alpha, scale); - } - - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } - } diff --git a/bus-opencv/src/main/java/org/opencv/img_hash/PHash.java b/bus-opencv/src/main/java/org/opencv/img_hash/PHash.java index 9421b240a4..f90d6e712a 100644 --- a/bus-opencv/src/main/java/org/opencv/img_hash/PHash.java +++ b/bus-opencv/src/main/java/org/opencv/img_hash/PHash.java @@ -4,24 +4,19 @@ package org.opencv.img_hash; // C++: class PHash - /** * pHash - *

    + * * Slower than average_hash, but tolerant of minor modifications - *

    + * * This algorithm can combat more variation than averageHash, for more details please refer to CITE: lookslikeit */ public class PHash extends ImgHashBase { - protected PHash(long addr) { - super(addr); - } + protected PHash(long addr) { super(addr); } // internal usage only - public static PHash __fromPtr__(long addr) { - return new PHash(addr); - } + public static PHash __fromPtr__(long addr) { return new PHash(addr); } // // C++: static Ptr_PHash cv::img_hash::PHash::create() @@ -31,15 +26,13 @@ public static PHash create() { return PHash.__fromPtr__(create_0()); } + + + // C++: static Ptr_PHash cv::img_hash::PHash::create() private static native long create_0(); // native support for deleting native object private static native void delete(long nativeObj); - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } - } diff --git a/bus-opencv/src/main/java/org/opencv/img_hash/RadialVarianceHash.java b/bus-opencv/src/main/java/org/opencv/img_hash/RadialVarianceHash.java index 3208830a00..b27c8099b6 100644 --- a/bus-opencv/src/main/java/org/opencv/img_hash/RadialVarianceHash.java +++ b/bus-opencv/src/main/java/org/opencv/img_hash/RadialVarianceHash.java @@ -4,22 +4,17 @@ package org.opencv.img_hash; // C++: class RadialVarianceHash - /** * Image hash based on Radon transform. - *

    + * * See CITE: tang2012perceptual for details. */ public class RadialVarianceHash extends ImgHashBase { - protected RadialVarianceHash(long addr) { - super(addr); - } + protected RadialVarianceHash(long addr) { super(addr); } // internal usage only - public static RadialVarianceHash __fromPtr__(long addr) { - return new RadialVarianceHash(addr); - } + public static RadialVarianceHash __fromPtr__(long addr) { return new RadialVarianceHash(addr); } // // C++: static Ptr_RadialVarianceHash cv::img_hash::RadialVarianceHash::create(double sigma = 1, int numOfAngleLine = 180) @@ -42,28 +37,45 @@ public static RadialVarianceHash create() { // C++: int cv::img_hash::RadialVarianceHash::getNumOfAngleLine() // - // C++: static Ptr_RadialVarianceHash cv::img_hash::RadialVarianceHash::create(double sigma = 1, int numOfAngleLine = 180) - private static native long create_0(double sigma, int numOfAngleLine); + public int getNumOfAngleLine() { + return getNumOfAngleLine_0(nativeObj); + } // // C++: double cv::img_hash::RadialVarianceHash::getSigma() // - private static native long create_1(double sigma); + public double getSigma() { + return getSigma_0(nativeObj); + } // // C++: void cv::img_hash::RadialVarianceHash::setNumOfAngleLine(int value) // - private static native long create_2(); + public void setNumOfAngleLine(int value) { + setNumOfAngleLine_0(nativeObj, value); + } // // C++: void cv::img_hash::RadialVarianceHash::setSigma(double value) // + public void setSigma(double value) { + setSigma_0(nativeObj, value); + } + + + + + // C++: static Ptr_RadialVarianceHash cv::img_hash::RadialVarianceHash::create(double sigma = 1, int numOfAngleLine = 180) + private static native long create_0(double sigma, int numOfAngleLine); + private static native long create_1(double sigma); + private static native long create_2(); + // C++: int cv::img_hash::RadialVarianceHash::getNumOfAngleLine() private static native int getNumOfAngleLine_0(long nativeObj); @@ -79,25 +91,4 @@ public static RadialVarianceHash create() { // native support for deleting native object private static native void delete(long nativeObj); - public int getNumOfAngleLine() { - return getNumOfAngleLine_0(nativeObj); - } - - public void setNumOfAngleLine(int value) { - setNumOfAngleLine_0(nativeObj, value); - } - - public double getSigma() { - return getSigma_0(nativeObj); - } - - public void setSigma(double value) { - setSigma_0(nativeObj, value); - } - - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } - } diff --git a/bus-opencv/src/main/java/org/opencv/imgcodecs/Imgcodecs.java b/bus-opencv/src/main/java/org/opencv/imgcodecs/Imgcodecs.java index ccd9859bc9..957d57f838 100644 --- a/bus-opencv/src/main/java/org/opencv/imgcodecs/Imgcodecs.java +++ b/bus-opencv/src/main/java/org/opencv/imgcodecs/Imgcodecs.java @@ -3,10 +3,7 @@ // package org.opencv.imgcodecs; -import org.opencv.core.Mat; -import org.opencv.core.MatOfByte; -import org.opencv.core.MatOfDouble; -import org.opencv.core.MatOfInt; +import org.opencv.core.*; import org.opencv.utils.Converters; import java.util.List; @@ -207,13 +204,13 @@ public class Imgcodecs { /** * Loads an image from a file. - *

    - * imread - *

    + * + * imread + * * The function imread loads an image from the specified file and returns it. If the image cannot be * read (because of missing file, improper permissions, unsupported or invalid format), the function * returns an empty matrix ( Mat::data==NULL ). - *

    + * * Currently, the following file formats are supported: * *

      @@ -304,8 +301,8 @@ public class Imgcodecs { *
    * * @param filename Name of file to be loaded. - * @param tags Output parameter for returning the list of EXIF tags - * @param flags Flag that can take values of cv::ImreadModes + * @param tags Output parameter for returning the list of EXIF tags + * @param flags Flag that can take values of cv::ImreadModes * @return automatically generated */ public static Mat imread(String filename, List tags, int flags) { @@ -314,13 +311,13 @@ public static Mat imread(String filename, List tags, int flags) { /** * Loads an image from a file. - *

    - * imread - *

    + * + * imread + * * The function imread loads an image from the specified file and returns it. If the image cannot be * read (because of missing file, improper permissions, unsupported or invalid format), the function * returns an empty matrix ( Mat::data==NULL ). - *

    + * * Currently, the following file formats are supported: * *

      @@ -411,7 +408,7 @@ public static Mat imread(String filename, List tags, int flags) { *
    * * @param filename Name of file to be loaded. - * @param tags Output parameter for returning the list of EXIF tags + * @param tags Output parameter for returning the list of EXIF tags * @return automatically generated */ public static Mat imread(String filename, List tags) { @@ -425,14 +422,13 @@ public static Mat imread(String filename, List tags) { /** * Loads a jpeg image (jpeg, jpeg-losseless, jpeg-ls and jpeg-2000) from file segments. - *

    - * The function dicomJpgRead loads a DICOM image from the specified file into Mat. * - * @param filename Name of file to be loaded. + * The function dicomJpgRead loads a DICOM image from the specified file into Mat. + * @param filename Name of file to be loaded. * @param segposition A vector of double holding the position of each fragment to read. - * @param seglength A vector of double holding the length of each fragment to read. - * @param dicomflags specific DICOM Flags (signed, ybr). Default is unsigned data. See DICOM_IMREAD in grfmt_dcm_dicom.hpp. - * @param flags Flag that can take values of cv::ImreadModes. + * @param seglength A vector of double holding the length of each fragment to read. + * @param dicomflags specific DICOM Flags (signed, ybr). Default is unsigned data. See DICOM_IMREAD in grfmt_dcm_dicom.hpp. + * @param flags Flag that can take values of cv::ImreadModes. * @return automatically generated */ public static Mat dicomJpgFileRead(String filename, MatOfDouble segposition, MatOfDouble seglength, int dicomflags, int flags) { @@ -443,13 +439,12 @@ public static Mat dicomJpgFileRead(String filename, MatOfDouble segposition, Mat /** * Loads a jpeg image (jpeg, jpeg-losseless, jpeg-ls and jpeg-2000) from file segments. - *

    - * The function dicomJpgRead loads a DICOM image from the specified file into Mat. * - * @param filename Name of file to be loaded. + * The function dicomJpgRead loads a DICOM image from the specified file into Mat. + * @param filename Name of file to be loaded. * @param segposition A vector of double holding the position of each fragment to read. - * @param seglength A vector of double holding the length of each fragment to read. - * @param dicomflags specific DICOM Flags (signed, ybr). Default is unsigned data. See DICOM_IMREAD in grfmt_dcm_dicom.hpp. + * @param seglength A vector of double holding the length of each fragment to read. + * @param dicomflags specific DICOM Flags (signed, ybr). Default is unsigned data. See DICOM_IMREAD in grfmt_dcm_dicom.hpp. * @return automatically generated */ public static Mat dicomJpgFileRead(String filename, MatOfDouble segposition, MatOfDouble seglength, int dicomflags) { @@ -460,12 +455,11 @@ public static Mat dicomJpgFileRead(String filename, MatOfDouble segposition, Mat /** * Loads a jpeg image (jpeg, jpeg-losseless, jpeg-ls and jpeg-2000) from file segments. - *

    - * The function dicomJpgRead loads a DICOM image from the specified file into Mat. * - * @param filename Name of file to be loaded. + * The function dicomJpgRead loads a DICOM image from the specified file into Mat. + * @param filename Name of file to be loaded. * @param segposition A vector of double holding the position of each fragment to read. - * @param seglength A vector of double holding the length of each fragment to read. + * @param seglength A vector of double holding the length of each fragment to read. * @return automatically generated */ public static Mat dicomJpgFileRead(String filename, MatOfDouble segposition, MatOfDouble seglength) { @@ -481,12 +475,11 @@ public static Mat dicomJpgFileRead(String filename, MatOfDouble segposition, Mat /** * Loads a jpeg image (jpeg, jpeg-losseless, jpeg-ls and jpeg-2000) from Mat. - *

    - * The function dicomJpgRead loads a DICOM image from a specified byte array into Mat. * - * @param buf the raw byte data of jpg image (1 raw, x column). + * The function dicomJpgRead loads a DICOM image from a specified byte array into Mat. + * @param buf the raw byte data of jpg image (1 raw, x column). * @param dicomflags specific DICOM Flags (signed, ybr). Default is unsigned data. See DICOM_IMREAD in grfmt_dcm_dicom.hpp. - * @param flags Flag that can take values of cv::ImreadModes. + * @param flags Flag that can take values of cv::ImreadModes. * @return automatically generated */ public static Mat dicomJpgMatRead(Mat buf, int dicomflags, int flags) { @@ -495,10 +488,9 @@ public static Mat dicomJpgMatRead(Mat buf, int dicomflags, int flags) { /** * Loads a jpeg image (jpeg, jpeg-losseless, jpeg-ls and jpeg-2000) from Mat. - *

    - * The function dicomJpgRead loads a DICOM image from a specified byte array into Mat. * - * @param buf the raw byte data of jpg image (1 raw, x column). + * The function dicomJpgRead loads a DICOM image from a specified byte array into Mat. + * @param buf the raw byte data of jpg image (1 raw, x column). * @param dicomflags specific DICOM Flags (signed, ybr). Default is unsigned data. See DICOM_IMREAD in grfmt_dcm_dicom.hpp. * @return automatically generated */ @@ -508,9 +500,8 @@ public static Mat dicomJpgMatRead(Mat buf, int dicomflags) { /** * Loads a jpeg image (jpeg, jpeg-losseless, jpeg-ls and jpeg-2000) from Mat. - *

    - * The function dicomJpgRead loads a DICOM image from a specified byte array into Mat. * + * The function dicomJpgRead loads a DICOM image from a specified byte array into Mat. * @param buf the raw byte data of jpg image (1 raw, x column). * @return automatically generated */ @@ -525,13 +516,12 @@ public static Mat dicomJpgMatRead(Mat buf) { /** * Loads a raw image (include RLE compressed image) from file segments. - *

    - * The function dicomRawRead loads a DICOM image from the specified file into Mat. * - * @param filename Name of file to be loaded. + * The function dicomRawRead loads a DICOM image from the specified file into Mat. + * @param filename Name of file to be loaded. * @param segposition The position of the image to read. - * @param seglength The length image to read. - * @param colormodel The image color model. + * @param seglength The length image to read. + * @param colormodel The image color model. * @param dicomparams automatically generated * @return automatically generated */ @@ -549,12 +539,11 @@ public static Mat dicomRawFileRead(String filename, MatOfDouble segposition, Mat /** * Loads a raw image (include RLE compressed image) from Mat. - *

    - * The function dicomRawRead loads a DICOM image from a specified byte array into Mat. * - * @param buf the raw byte data of jpg image (1 raw, x column). - * @param dicomParams A vector of int containing the specific DICOM parameters. See DICOM_PARAM in grfmt_dcm_dicom.hpp. - * @param colormodel The image color model. + * The function dicomRawRead loads a DICOM image from a specified byte array into Mat. + * @param buf the raw byte data of jpg image (1 raw, x column). + * @param dicomParams A vector of int containing the specific DICOM parameters. See DICOM_PARAM in grfmt_dcm_dicom.hpp. + * @param colormodel The image color model. * @return automatically generated */ public static Mat dicomRawMatRead(Mat buf, MatOfInt dicomParams, String colormodel) { @@ -570,8 +559,8 @@ public static Mat dicomRawMatRead(Mat buf, MatOfInt dicomParams, String colormod /** * Encodes an DICOM image into a memory buffer. * - * @param colormodel The image color model. - * @param image automatically generated + * @param colormodel The image color model. + * @param image automatically generated * @param dicomParams automatically generated * @return automatically generated */ @@ -587,13 +576,12 @@ public static Mat dicomJpgWrite(Mat image, MatOfInt dicomParams, String colormod /** * Loads a multi-page image from a file. - *

    - * The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. * + * The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. * @param filename Name of file to be loaded. - * @param mats A vector of Mat objects holding each page. - * @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. - * SEE: cv::imread + * @param mats A vector of Mat objects holding each page. + * @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. + * SEE: cv::imread * @return automatically generated */ public static boolean imreadmulti(String filename, List mats, int flags) { @@ -606,12 +594,11 @@ public static boolean imreadmulti(String filename, List mats, int flags) { /** * Loads a multi-page image from a file. - *

    - * The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. * + * The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. * @param filename Name of file to be loaded. - * @param mats A vector of Mat objects holding each page. - * SEE: cv::imread + * @param mats A vector of Mat objects holding each page. + * SEE: cv::imread * @return automatically generated */ public static boolean imreadmulti(String filename, List mats) { @@ -629,15 +616,14 @@ public static boolean imreadmulti(String filename, List mats) { /** * Loads a of images of a multi-page image from a file. - *

    - * The function imreadmulti loads a specified range from a multi-page image from the specified file into a vector of Mat objects. * + * The function imreadmulti loads a specified range from a multi-page image from the specified file into a vector of Mat objects. * @param filename Name of file to be loaded. - * @param mats A vector of Mat objects holding each page. - * @param start Start index of the image to load - * @param count Count number of images to load - * @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. - * SEE: cv::imread + * @param mats A vector of Mat objects holding each page. + * @param start Start index of the image to load + * @param count Count number of images to load + * @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. + * SEE: cv::imread * @return automatically generated */ public static boolean imreadmulti(String filename, List mats, int start, int count, int flags) { @@ -650,14 +636,13 @@ public static boolean imreadmulti(String filename, List mats, int start, in /** * Loads a of images of a multi-page image from a file. - *

    - * The function imreadmulti loads a specified range from a multi-page image from the specified file into a vector of Mat objects. * + * The function imreadmulti loads a specified range from a multi-page image from the specified file into a vector of Mat objects. * @param filename Name of file to be loaded. - * @param mats A vector of Mat objects holding each page. - * @param start Start index of the image to load - * @param count Count number of images to load - * SEE: cv::imread + * @param mats A vector of Mat objects holding each page. + * @param start Start index of the image to load + * @param count Count number of images to load + * SEE: cv::imread * @return automatically generated */ public static boolean imreadmulti(String filename, List mats, int start, int count) { @@ -675,11 +660,10 @@ public static boolean imreadmulti(String filename, List mats, int start, in /** * Returns the number of images inside the give file - *

    - * The function imcount will return the number of pages in a multi-page image, or 1 for single-page images * + * The function imcount will return the number of pages in a multi-page image, or 1 for single-page images * @param filename Name of file to be loaded. - * @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. + * @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. * @return automatically generated */ public static long imcount(String filename, int flags) { @@ -688,9 +672,8 @@ public static long imcount(String filename, int flags) { /** * Returns the number of images inside the give file - *

    - * The function imcount will return the number of pages in a multi-page image, or 1 for single-page images * + * The function imcount will return the number of pages in a multi-page image, or 1 for single-page images * @param filename Name of file to be loaded. * @return automatically generated */ @@ -705,7 +688,7 @@ public static long imcount(String filename) { /** * Saves an image to a specified file. - *

    + * * The function imwrite saves the image to the specified file. The image format is chosen based on the * filename extension (see cv::imread for the list of extensions). In general, only 8-bit unsigned (CV_8U) * single-channel or 3-channel (with 'BGR' channel order) images @@ -756,22 +739,21 @@ public static long imcount(String filename) { * using the LogLuv high dynamic range encoding (4 bytes per pixel) * * - *

    + * * If the image format is not supported, the image will be converted to 8-bit unsigned (CV_8U) and saved that way. * * - *

    + * * If the format, depth or channel order is different, use * Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O * functions to save the image to XML or YAML format. - *

    + * * The sample below shows how to create a BGRA image, how to set custom compression parameters and save it to a PNG file. * It also demonstrates how to save multiple images in a TIFF file: * INCLUDE: snippets/imgcodecs_imwrite.cpp - * * @param filename Name of the file. - * @param img (Mat or vector of Mat) Image or Images to be saved. - * @param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags + * @param img (Mat or vector of Mat) Image or Images to be saved. + * @param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags * @return automatically generated */ public static boolean imwrite(String filename, Mat img, MatOfInt params) { @@ -781,7 +763,7 @@ public static boolean imwrite(String filename, Mat img, MatOfInt params) { /** * Saves an image to a specified file. - *

    + * * The function imwrite saves the image to the specified file. The image format is chosen based on the * filename extension (see cv::imread for the list of extensions). In general, only 8-bit unsigned (CV_8U) * single-channel or 3-channel (with 'BGR' channel order) images @@ -832,21 +814,20 @@ public static boolean imwrite(String filename, Mat img, MatOfInt params) { * using the LogLuv high dynamic range encoding (4 bytes per pixel) * * - *

    + * * If the image format is not supported, the image will be converted to 8-bit unsigned (CV_8U) and saved that way. * * - *

    + * * If the format, depth or channel order is different, use * Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O * functions to save the image to XML or YAML format. - *

    + * * The sample below shows how to create a BGRA image, how to set custom compression parameters and save it to a PNG file. * It also demonstrates how to save multiple images in a TIFF file: * INCLUDE: snippets/imgcodecs_imwrite.cpp - * * @param filename Name of the file. - * @param img (Mat or vector of Mat) Image or Images to be saved. + * @param img (Mat or vector of Mat) Image or Images to be saved. * @return automatically generated */ public static boolean imwrite(String filename, Mat img) { @@ -876,15 +857,14 @@ public static boolean imwritemulti(String filename, List img) { /** * Reads an image from a buffer in memory. - *

    + * * The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or * contains invalid data, the function returns an empty matrix ( Mat::data==NULL ). - *

    + * * See cv::imread for the list of supported formats and flags description. * * Note: In the case of color images, the decoded images will have the channels stored in B G R order. - * - * @param buf Input array or vector of bytes. + * @param buf Input array or vector of bytes. * @param flags The same flags as in cv::imread, see cv::ImreadModes. * @return automatically generated */ @@ -894,27 +874,49 @@ public static Mat imdecode(Mat buf, int flags) { // - // C++: bool cv::imdecodemulti(Mat buf, int flags, vector_Mat& mats) + // C++: bool cv::imdecodemulti(Mat buf, int flags, vector_Mat& mats, Range range = Range::all()) // /** * Reads a multi-page image from a buffer in memory. - *

    + * * The function imdecodemulti reads a multi-page image from the specified buffer in the memory. If the buffer is too short or * contains invalid data, the function returns false. - *

    + * * See cv::imreadmulti for the list of supported formats and flags description. * * Note: In the case of color images, the decoded images will have the channels stored in B G R order. + * @param buf Input array or vector of bytes. + * @param flags The same flags as in cv::imread, see cv::ImreadModes. + * @param mats A vector of Mat objects holding each page, if more than one. + * @param range A continuous selection of pages. + * @return automatically generated + */ + public static boolean imdecodemulti(Mat buf, int flags, List mats, Range range) { + Mat mats_mat = new Mat(); + boolean retVal = imdecodemulti_0(buf.nativeObj, flags, mats_mat.nativeObj, range.start, range.end); + Converters.Mat_to_vector_Mat(mats_mat, mats); + mats_mat.release(); + return retVal; + } + + /** + * Reads a multi-page image from a buffer in memory. * - * @param buf Input array or vector of bytes. + * The function imdecodemulti reads a multi-page image from the specified buffer in the memory. If the buffer is too short or + * contains invalid data, the function returns false. + * + * See cv::imreadmulti for the list of supported formats and flags description. + * + * Note: In the case of color images, the decoded images will have the channels stored in B G R order. + * @param buf Input array or vector of bytes. * @param flags The same flags as in cv::imread, see cv::ImreadModes. - * @param mats A vector of Mat objects holding each page, if more than one. + * @param mats A vector of Mat objects holding each page, if more than one. * @return automatically generated */ public static boolean imdecodemulti(Mat buf, int flags, List mats) { Mat mats_mat = new Mat(); - boolean retVal = imdecodemulti_0(buf.nativeObj, flags, mats_mat.nativeObj); + boolean retVal = imdecodemulti_1(buf.nativeObj, flags, mats_mat.nativeObj); Converters.Mat_to_vector_Mat(mats_mat, mats); mats_mat.release(); return retVal; @@ -927,13 +929,13 @@ public static boolean imdecodemulti(Mat buf, int flags, List mats) { /** * Encodes an image into a memory buffer. - *

    + * * The function imencode compresses the image and stores it in the memory buffer that is resized to fit the * result. See cv::imwrite for the list of supported formats and flags description. * - * @param ext File extension that defines the output format. Must include a leading period. - * @param img Image to be written. - * @param buf Output buffer resized to fit the compressed image. + * @param ext File extension that defines the output format. Must include a leading period. + * @param img Image to be written. + * @param buf Output buffer resized to fit the compressed image. * @param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. * @return automatically generated */ @@ -945,7 +947,7 @@ public static boolean imencode(String ext, Mat img, MatOfByte buf, MatOfInt para /** * Encodes an image into a memory buffer. - *

    + * * The function imencode compresses the image and stores it in the memory buffer that is resized to fit the * result. See cv::imwrite for the list of supported formats and flags description. * @@ -982,7 +984,7 @@ public static boolean haveImageReader(String filename) { /** * Returns true if an image with the specified filename can be encoded by OpenCV * - * @param filename File name of the image + * @param filename File name of the image * @return automatically generated */ public static boolean haveImageWriter(String filename) { @@ -990,23 +992,20 @@ public static boolean haveImageWriter(String filename) { } + + // C++: Mat cv::imread(String filename, vector_String& tags, int flags = IMREAD_UNCHANGED) private static native long imread_0(String filename, List tags, int flags); - private static native long imread_1(String filename, List tags); // C++: Mat cv::dicomJpgFileRead(String filename, vector_double segposition, vector_double seglength, int dicomflags = 0, int flags = IMREAD_UNCHANGED) private static native long dicomJpgFileRead_0(String filename, long segposition_mat_nativeObj, long seglength_mat_nativeObj, int dicomflags, int flags); - private static native long dicomJpgFileRead_1(String filename, long segposition_mat_nativeObj, long seglength_mat_nativeObj, int dicomflags); - private static native long dicomJpgFileRead_2(String filename, long segposition_mat_nativeObj, long seglength_mat_nativeObj); // C++: Mat cv::dicomJpgMatRead(Mat buf, int dicomflags = 0, int flags = IMREAD_UNCHANGED) private static native long dicomJpgMatRead_0(long buf_nativeObj, int dicomflags, int flags); - private static native long dicomJpgMatRead_1(long buf_nativeObj, int dicomflags); - private static native long dicomJpgMatRead_2(long buf_nativeObj); // C++: Mat cv::dicomRawFileRead(String filename, vector_double segposition, vector_double seglength, vector_int dicomparams, String colormodel) @@ -1020,38 +1019,33 @@ public static boolean haveImageWriter(String filename) { // C++: bool cv::imreadmulti(String filename, vector_Mat& mats, int flags = IMREAD_COLOR) private static native boolean imreadmulti_0(String filename, long mats_mat_nativeObj, int flags); - private static native boolean imreadmulti_1(String filename, long mats_mat_nativeObj); // C++: bool cv::imreadmulti(String filename, vector_Mat& mats, int start, int count, int flags = IMREAD_ANYCOLOR) private static native boolean imreadmulti_2(String filename, long mats_mat_nativeObj, int start, int count, int flags); - private static native boolean imreadmulti_3(String filename, long mats_mat_nativeObj, int start, int count); // C++: size_t cv::imcount(String filename, int flags = IMREAD_ANYCOLOR) private static native long imcount_0(String filename, int flags); - private static native long imcount_1(String filename); // C++: bool cv::imwrite(String filename, Mat img, vector_int params = std::vector()) private static native boolean imwrite_0(String filename, long img_nativeObj, long params_mat_nativeObj); - private static native boolean imwrite_1(String filename, long img_nativeObj); // C++: bool cv::imwritemulti(String filename, vector_Mat img, vector_int params = std::vector()) private static native boolean imwritemulti_0(String filename, long img_mat_nativeObj, long params_mat_nativeObj); - private static native boolean imwritemulti_1(String filename, long img_mat_nativeObj); // C++: Mat cv::imdecode(Mat buf, int flags) private static native long imdecode_0(long buf_nativeObj, int flags); - // C++: bool cv::imdecodemulti(Mat buf, int flags, vector_Mat& mats) - private static native boolean imdecodemulti_0(long buf_nativeObj, int flags, long mats_mat_nativeObj); + // C++: bool cv::imdecodemulti(Mat buf, int flags, vector_Mat& mats, Range range = Range::all()) + private static native boolean imdecodemulti_0(long buf_nativeObj, int flags, long mats_mat_nativeObj, int range_start, int range_end); + private static native boolean imdecodemulti_1(long buf_nativeObj, int flags, long mats_mat_nativeObj); // C++: bool cv::imencode(String ext, Mat img, vector_uchar& buf, vector_int params = std::vector()) private static native boolean imencode_0(String ext, long img_nativeObj, long buf_mat_nativeObj, long params_mat_nativeObj); - private static native boolean imencode_1(String ext, long img_nativeObj, long buf_mat_nativeObj); // C++: bool cv::haveImageReader(String filename) diff --git a/bus-opencv/src/main/java/org/opencv/imgproc/CLAHE.java b/bus-opencv/src/main/java/org/opencv/imgproc/CLAHE.java index 009b49bf95..ebecfbaaa7 100644 --- a/bus-opencv/src/main/java/org/opencv/imgproc/CLAHE.java +++ b/bus-opencv/src/main/java/org/opencv/imgproc/CLAHE.java @@ -8,115 +8,108 @@ import org.opencv.core.Size; // C++: class CLAHE - /** * Base class for Contrast Limited Adaptive Histogram Equalization. */ public class CLAHE extends Algorithm { - protected CLAHE(long addr) { - super(addr); - } + protected CLAHE(long addr) { super(addr); } // internal usage only - public static CLAHE __fromPtr__(long addr) { - return new CLAHE(addr); - } + public static CLAHE __fromPtr__(long addr) { return new CLAHE(addr); } // // C++: void cv::CLAHE::apply(Mat src, Mat& dst) // - // C++: void cv::CLAHE::apply(Mat src, Mat& dst) - private static native void apply_0(long nativeObj, long src_nativeObj, long dst_nativeObj); + /** + * Equalizes the histogram of a grayscale image using Contrast Limited Adaptive Histogram Equalization. + * + * @param src Source image of type CV_8UC1 or CV_16UC1. + * @param dst Destination image. + */ + public void apply(Mat src, Mat dst) { + apply_0(nativeObj, src.nativeObj, dst.nativeObj); + } // // C++: void cv::CLAHE::setClipLimit(double clipLimit) // - // C++: void cv::CLAHE::setClipLimit(double clipLimit) - private static native void setClipLimit_0(long nativeObj, double clipLimit); + /** + * Sets threshold for contrast limiting. + * + * @param clipLimit threshold value. + */ + public void setClipLimit(double clipLimit) { + setClipLimit_0(nativeObj, clipLimit); + } // // C++: double cv::CLAHE::getClipLimit() // - // C++: double cv::CLAHE::getClipLimit() - private static native double getClipLimit_0(long nativeObj); + public double getClipLimit() { + return getClipLimit_0(nativeObj); + } // // C++: void cv::CLAHE::setTilesGridSize(Size tileGridSize) // - // C++: void cv::CLAHE::setTilesGridSize(Size tileGridSize) - private static native void setTilesGridSize_0(long nativeObj, double tileGridSize_width, double tileGridSize_height); + /** + * Sets size of grid for histogram equalization. Input image will be divided into + * equally sized rectangular tiles. + * + * @param tileGridSize defines the number of tiles in row and column. + */ + public void setTilesGridSize(Size tileGridSize) { + setTilesGridSize_0(nativeObj, tileGridSize.width, tileGridSize.height); + } // // C++: Size cv::CLAHE::getTilesGridSize() // - // C++: Size cv::CLAHE::getTilesGridSize() - private static native double[] getTilesGridSize_0(long nativeObj); + public Size getTilesGridSize() { + return new Size(getTilesGridSize_0(nativeObj)); + } // // C++: void cv::CLAHE::collectGarbage() // - // C++: void cv::CLAHE::collectGarbage() - private static native void collectGarbage_0(long nativeObj); + public void collectGarbage() { + collectGarbage_0(nativeObj); + } - // native support for deleting native object - private static native void delete(long nativeObj); - /** - * Equalizes the histogram of a grayscale image using Contrast Limited Adaptive Histogram Equalization. - * - * @param src Source image of type CV_8UC1 or CV_16UC1. - * @param dst Destination image. - */ - public void apply(Mat src, Mat dst) { - apply_0(nativeObj, src.nativeObj, dst.nativeObj); - } - public double getClipLimit() { - return getClipLimit_0(nativeObj); - } - /** - * Sets threshold for contrast limiting. - * - * @param clipLimit threshold value. - */ - public void setClipLimit(double clipLimit) { - setClipLimit_0(nativeObj, clipLimit); - } + // C++: void cv::CLAHE::apply(Mat src, Mat& dst) + private static native void apply_0(long nativeObj, long src_nativeObj, long dst_nativeObj); - public Size getTilesGridSize() { - return new Size(getTilesGridSize_0(nativeObj)); - } + // C++: void cv::CLAHE::setClipLimit(double clipLimit) + private static native void setClipLimit_0(long nativeObj, double clipLimit); - /** - * Sets size of grid for histogram equalization. Input image will be divided into - * equally sized rectangular tiles. - * - * @param tileGridSize defines the number of tiles in row and column. - */ - public void setTilesGridSize(Size tileGridSize) { - setTilesGridSize_0(nativeObj, tileGridSize.width, tileGridSize.height); - } + // C++: double cv::CLAHE::getClipLimit() + private static native double getClipLimit_0(long nativeObj); - public void collectGarbage() { - collectGarbage_0(nativeObj); - } + // C++: void cv::CLAHE::setTilesGridSize(Size tileGridSize) + private static native void setTilesGridSize_0(long nativeObj, double tileGridSize_width, double tileGridSize_height); - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } + // C++: Size cv::CLAHE::getTilesGridSize() + private static native double[] getTilesGridSize_0(long nativeObj); + + // C++: void cv::CLAHE::collectGarbage() + private static native void collectGarbage_0(long nativeObj); + + // native support for deleting native object + private static native void delete(long nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHough.java b/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHough.java index f969fa9cfc..36b64d992b 100644 --- a/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHough.java +++ b/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHough.java @@ -8,218 +8,207 @@ import org.opencv.core.Point; // C++: class GeneralizedHough - /** * finds arbitrary template in the grayscale image using Generalized Hough Transform */ public class GeneralizedHough extends Algorithm { - protected GeneralizedHough(long addr) { - super(addr); - } + protected GeneralizedHough(long addr) { super(addr); } // internal usage only - public static GeneralizedHough __fromPtr__(long addr) { - return new GeneralizedHough(addr); - } + public static GeneralizedHough __fromPtr__(long addr) { return new GeneralizedHough(addr); } // // C++: void cv::GeneralizedHough::setTemplate(Mat templ, Point templCenter = Point(-1, -1)) // - // C++: void cv::GeneralizedHough::setTemplate(Mat templ, Point templCenter = Point(-1, -1)) - private static native void setTemplate_0(long nativeObj, long templ_nativeObj, double templCenter_x, double templCenter_y); + public void setTemplate(Mat templ, Point templCenter) { + setTemplate_0(nativeObj, templ.nativeObj, templCenter.x, templCenter.y); + } - private static native void setTemplate_1(long nativeObj, long templ_nativeObj); + public void setTemplate(Mat templ) { + setTemplate_1(nativeObj, templ.nativeObj); + } // // C++: void cv::GeneralizedHough::setTemplate(Mat edges, Mat dx, Mat dy, Point templCenter = Point(-1, -1)) // - // C++: void cv::GeneralizedHough::setTemplate(Mat edges, Mat dx, Mat dy, Point templCenter = Point(-1, -1)) - private static native void setTemplate_2(long nativeObj, long edges_nativeObj, long dx_nativeObj, long dy_nativeObj, double templCenter_x, double templCenter_y); + public void setTemplate(Mat edges, Mat dx, Mat dy, Point templCenter) { + setTemplate_2(nativeObj, edges.nativeObj, dx.nativeObj, dy.nativeObj, templCenter.x, templCenter.y); + } - private static native void setTemplate_3(long nativeObj, long edges_nativeObj, long dx_nativeObj, long dy_nativeObj); + public void setTemplate(Mat edges, Mat dx, Mat dy) { + setTemplate_3(nativeObj, edges.nativeObj, dx.nativeObj, dy.nativeObj); + } // // C++: void cv::GeneralizedHough::detect(Mat image, Mat& positions, Mat& votes = Mat()) // - // C++: void cv::GeneralizedHough::detect(Mat image, Mat& positions, Mat& votes = Mat()) - private static native void detect_0(long nativeObj, long image_nativeObj, long positions_nativeObj, long votes_nativeObj); + public void detect(Mat image, Mat positions, Mat votes) { + detect_0(nativeObj, image.nativeObj, positions.nativeObj, votes.nativeObj); + } - private static native void detect_1(long nativeObj, long image_nativeObj, long positions_nativeObj); + public void detect(Mat image, Mat positions) { + detect_1(nativeObj, image.nativeObj, positions.nativeObj); + } // // C++: void cv::GeneralizedHough::detect(Mat edges, Mat dx, Mat dy, Mat& positions, Mat& votes = Mat()) // - // C++: void cv::GeneralizedHough::detect(Mat edges, Mat dx, Mat dy, Mat& positions, Mat& votes = Mat()) - private static native void detect_2(long nativeObj, long edges_nativeObj, long dx_nativeObj, long dy_nativeObj, long positions_nativeObj, long votes_nativeObj); + public void detect(Mat edges, Mat dx, Mat dy, Mat positions, Mat votes) { + detect_2(nativeObj, edges.nativeObj, dx.nativeObj, dy.nativeObj, positions.nativeObj, votes.nativeObj); + } - private static native void detect_3(long nativeObj, long edges_nativeObj, long dx_nativeObj, long dy_nativeObj, long positions_nativeObj); + public void detect(Mat edges, Mat dx, Mat dy, Mat positions) { + detect_3(nativeObj, edges.nativeObj, dx.nativeObj, dy.nativeObj, positions.nativeObj); + } // // C++: void cv::GeneralizedHough::setCannyLowThresh(int cannyLowThresh) // - // C++: void cv::GeneralizedHough::setCannyLowThresh(int cannyLowThresh) - private static native void setCannyLowThresh_0(long nativeObj, int cannyLowThresh); + public void setCannyLowThresh(int cannyLowThresh) { + setCannyLowThresh_0(nativeObj, cannyLowThresh); + } // // C++: int cv::GeneralizedHough::getCannyLowThresh() // - // C++: int cv::GeneralizedHough::getCannyLowThresh() - private static native int getCannyLowThresh_0(long nativeObj); + public int getCannyLowThresh() { + return getCannyLowThresh_0(nativeObj); + } // // C++: void cv::GeneralizedHough::setCannyHighThresh(int cannyHighThresh) // - // C++: void cv::GeneralizedHough::setCannyHighThresh(int cannyHighThresh) - private static native void setCannyHighThresh_0(long nativeObj, int cannyHighThresh); + public void setCannyHighThresh(int cannyHighThresh) { + setCannyHighThresh_0(nativeObj, cannyHighThresh); + } // // C++: int cv::GeneralizedHough::getCannyHighThresh() // - // C++: int cv::GeneralizedHough::getCannyHighThresh() - private static native int getCannyHighThresh_0(long nativeObj); + public int getCannyHighThresh() { + return getCannyHighThresh_0(nativeObj); + } // // C++: void cv::GeneralizedHough::setMinDist(double minDist) // - // C++: void cv::GeneralizedHough::setMinDist(double minDist) - private static native void setMinDist_0(long nativeObj, double minDist); + public void setMinDist(double minDist) { + setMinDist_0(nativeObj, minDist); + } // // C++: double cv::GeneralizedHough::getMinDist() // - // C++: double cv::GeneralizedHough::getMinDist() - private static native double getMinDist_0(long nativeObj); + public double getMinDist() { + return getMinDist_0(nativeObj); + } // // C++: void cv::GeneralizedHough::setDp(double dp) // - // C++: void cv::GeneralizedHough::setDp(double dp) - private static native void setDp_0(long nativeObj, double dp); + public void setDp(double dp) { + setDp_0(nativeObj, dp); + } // // C++: double cv::GeneralizedHough::getDp() // - // C++: double cv::GeneralizedHough::getDp() - private static native double getDp_0(long nativeObj); + public double getDp() { + return getDp_0(nativeObj); + } // // C++: void cv::GeneralizedHough::setMaxBufferSize(int maxBufferSize) // - // C++: void cv::GeneralizedHough::setMaxBufferSize(int maxBufferSize) - private static native void setMaxBufferSize_0(long nativeObj, int maxBufferSize); + public void setMaxBufferSize(int maxBufferSize) { + setMaxBufferSize_0(nativeObj, maxBufferSize); + } // // C++: int cv::GeneralizedHough::getMaxBufferSize() // - // C++: int cv::GeneralizedHough::getMaxBufferSize() - private static native int getMaxBufferSize_0(long nativeObj); - - // native support for deleting native object - private static native void delete(long nativeObj); - - public void setTemplate(Mat templ, Point templCenter) { - setTemplate_0(nativeObj, templ.nativeObj, templCenter.x, templCenter.y); + public int getMaxBufferSize() { + return getMaxBufferSize_0(nativeObj); } - public void setTemplate(Mat templ) { - setTemplate_1(nativeObj, templ.nativeObj); - } - public void setTemplate(Mat edges, Mat dx, Mat dy, Point templCenter) { - setTemplate_2(nativeObj, edges.nativeObj, dx.nativeObj, dy.nativeObj, templCenter.x, templCenter.y); - } - public void setTemplate(Mat edges, Mat dx, Mat dy) { - setTemplate_3(nativeObj, edges.nativeObj, dx.nativeObj, dy.nativeObj); - } - public void detect(Mat image, Mat positions, Mat votes) { - detect_0(nativeObj, image.nativeObj, positions.nativeObj, votes.nativeObj); - } + // C++: void cv::GeneralizedHough::setTemplate(Mat templ, Point templCenter = Point(-1, -1)) + private static native void setTemplate_0(long nativeObj, long templ_nativeObj, double templCenter_x, double templCenter_y); + private static native void setTemplate_1(long nativeObj, long templ_nativeObj); - public void detect(Mat image, Mat positions) { - detect_1(nativeObj, image.nativeObj, positions.nativeObj); - } + // C++: void cv::GeneralizedHough::setTemplate(Mat edges, Mat dx, Mat dy, Point templCenter = Point(-1, -1)) + private static native void setTemplate_2(long nativeObj, long edges_nativeObj, long dx_nativeObj, long dy_nativeObj, double templCenter_x, double templCenter_y); + private static native void setTemplate_3(long nativeObj, long edges_nativeObj, long dx_nativeObj, long dy_nativeObj); - public void detect(Mat edges, Mat dx, Mat dy, Mat positions, Mat votes) { - detect_2(nativeObj, edges.nativeObj, dx.nativeObj, dy.nativeObj, positions.nativeObj, votes.nativeObj); - } + // C++: void cv::GeneralizedHough::detect(Mat image, Mat& positions, Mat& votes = Mat()) + private static native void detect_0(long nativeObj, long image_nativeObj, long positions_nativeObj, long votes_nativeObj); + private static native void detect_1(long nativeObj, long image_nativeObj, long positions_nativeObj); - public void detect(Mat edges, Mat dx, Mat dy, Mat positions) { - detect_3(nativeObj, edges.nativeObj, dx.nativeObj, dy.nativeObj, positions.nativeObj); - } + // C++: void cv::GeneralizedHough::detect(Mat edges, Mat dx, Mat dy, Mat& positions, Mat& votes = Mat()) + private static native void detect_2(long nativeObj, long edges_nativeObj, long dx_nativeObj, long dy_nativeObj, long positions_nativeObj, long votes_nativeObj); + private static native void detect_3(long nativeObj, long edges_nativeObj, long dx_nativeObj, long dy_nativeObj, long positions_nativeObj); - public int getCannyLowThresh() { - return getCannyLowThresh_0(nativeObj); - } + // C++: void cv::GeneralizedHough::setCannyLowThresh(int cannyLowThresh) + private static native void setCannyLowThresh_0(long nativeObj, int cannyLowThresh); - public void setCannyLowThresh(int cannyLowThresh) { - setCannyLowThresh_0(nativeObj, cannyLowThresh); - } + // C++: int cv::GeneralizedHough::getCannyLowThresh() + private static native int getCannyLowThresh_0(long nativeObj); - public int getCannyHighThresh() { - return getCannyHighThresh_0(nativeObj); - } + // C++: void cv::GeneralizedHough::setCannyHighThresh(int cannyHighThresh) + private static native void setCannyHighThresh_0(long nativeObj, int cannyHighThresh); - public void setCannyHighThresh(int cannyHighThresh) { - setCannyHighThresh_0(nativeObj, cannyHighThresh); - } + // C++: int cv::GeneralizedHough::getCannyHighThresh() + private static native int getCannyHighThresh_0(long nativeObj); - public double getMinDist() { - return getMinDist_0(nativeObj); - } + // C++: void cv::GeneralizedHough::setMinDist(double minDist) + private static native void setMinDist_0(long nativeObj, double minDist); - public void setMinDist(double minDist) { - setMinDist_0(nativeObj, minDist); - } + // C++: double cv::GeneralizedHough::getMinDist() + private static native double getMinDist_0(long nativeObj); - public double getDp() { - return getDp_0(nativeObj); - } + // C++: void cv::GeneralizedHough::setDp(double dp) + private static native void setDp_0(long nativeObj, double dp); - public void setDp(double dp) { - setDp_0(nativeObj, dp); - } + // C++: double cv::GeneralizedHough::getDp() + private static native double getDp_0(long nativeObj); - public int getMaxBufferSize() { - return getMaxBufferSize_0(nativeObj); - } + // C++: void cv::GeneralizedHough::setMaxBufferSize(int maxBufferSize) + private static native void setMaxBufferSize_0(long nativeObj, int maxBufferSize); - public void setMaxBufferSize(int maxBufferSize) { - setMaxBufferSize_0(nativeObj, maxBufferSize); - } + // C++: int cv::GeneralizedHough::getMaxBufferSize() + private static native int getMaxBufferSize_0(long nativeObj); - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } + // native support for deleting native object + private static native void delete(long nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHoughBallard.java b/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHoughBallard.java index 2738334305..eee1f9e16e 100644 --- a/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHoughBallard.java +++ b/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHoughBallard.java @@ -4,76 +4,69 @@ package org.opencv.imgproc; // C++: class GeneralizedHoughBallard - /** * finds arbitrary template in the grayscale image using Generalized Hough Transform - *

    + * * Detects position only without translation and rotation CITE: Ballard1981 . */ public class GeneralizedHoughBallard extends GeneralizedHough { - protected GeneralizedHoughBallard(long addr) { - super(addr); - } + protected GeneralizedHoughBallard(long addr) { super(addr); } // internal usage only - public static GeneralizedHoughBallard __fromPtr__(long addr) { - return new GeneralizedHoughBallard(addr); - } + public static GeneralizedHoughBallard __fromPtr__(long addr) { return new GeneralizedHoughBallard(addr); } // // C++: void cv::GeneralizedHoughBallard::setLevels(int levels) // - // C++: void cv::GeneralizedHoughBallard::setLevels(int levels) - private static native void setLevels_0(long nativeObj, int levels); + public void setLevels(int levels) { + setLevels_0(nativeObj, levels); + } // // C++: int cv::GeneralizedHoughBallard::getLevels() // - // C++: int cv::GeneralizedHoughBallard::getLevels() - private static native int getLevels_0(long nativeObj); + public int getLevels() { + return getLevels_0(nativeObj); + } // // C++: void cv::GeneralizedHoughBallard::setVotesThreshold(int votesThreshold) // - // C++: void cv::GeneralizedHoughBallard::setVotesThreshold(int votesThreshold) - private static native void setVotesThreshold_0(long nativeObj, int votesThreshold); + public void setVotesThreshold(int votesThreshold) { + setVotesThreshold_0(nativeObj, votesThreshold); + } // // C++: int cv::GeneralizedHoughBallard::getVotesThreshold() // - // C++: int cv::GeneralizedHoughBallard::getVotesThreshold() - private static native int getVotesThreshold_0(long nativeObj); + public int getVotesThreshold() { + return getVotesThreshold_0(nativeObj); + } - // native support for deleting native object - private static native void delete(long nativeObj); - public int getLevels() { - return getLevels_0(nativeObj); - } - public void setLevels(int levels) { - setLevels_0(nativeObj, levels); - } - public int getVotesThreshold() { - return getVotesThreshold_0(nativeObj); - } + // C++: void cv::GeneralizedHoughBallard::setLevels(int levels) + private static native void setLevels_0(long nativeObj, int levels); - public void setVotesThreshold(int votesThreshold) { - setVotesThreshold_0(nativeObj, votesThreshold); - } + // C++: int cv::GeneralizedHoughBallard::getLevels() + private static native int getLevels_0(long nativeObj); - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } + // C++: void cv::GeneralizedHoughBallard::setVotesThreshold(int votesThreshold) + private static native void setVotesThreshold_0(long nativeObj, int votesThreshold); + + // C++: int cv::GeneralizedHoughBallard::getVotesThreshold() + private static native int getVotesThreshold_0(long nativeObj); + + // native support for deleting native object + private static native void delete(long nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHoughGuil.java b/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHoughGuil.java index af422d81eb..110ae55047 100644 --- a/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHoughGuil.java +++ b/bus-opencv/src/main/java/org/opencv/imgproc/GeneralizedHoughGuil.java @@ -4,316 +4,309 @@ package org.opencv.imgproc; // C++: class GeneralizedHoughGuil - /** * finds arbitrary template in the grayscale image using Generalized Hough Transform - *

    + * * Detects position, translation and rotation CITE: Guil1999 . */ public class GeneralizedHoughGuil extends GeneralizedHough { - protected GeneralizedHoughGuil(long addr) { - super(addr); - } + protected GeneralizedHoughGuil(long addr) { super(addr); } // internal usage only - public static GeneralizedHoughGuil __fromPtr__(long addr) { - return new GeneralizedHoughGuil(addr); - } + public static GeneralizedHoughGuil __fromPtr__(long addr) { return new GeneralizedHoughGuil(addr); } // // C++: void cv::GeneralizedHoughGuil::setXi(double xi) // - // C++: void cv::GeneralizedHoughGuil::setXi(double xi) - private static native void setXi_0(long nativeObj, double xi); + public void setXi(double xi) { + setXi_0(nativeObj, xi); + } // // C++: double cv::GeneralizedHoughGuil::getXi() // - // C++: double cv::GeneralizedHoughGuil::getXi() - private static native double getXi_0(long nativeObj); + public double getXi() { + return getXi_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setLevels(int levels) // - // C++: void cv::GeneralizedHoughGuil::setLevels(int levels) - private static native void setLevels_0(long nativeObj, int levels); + public void setLevels(int levels) { + setLevels_0(nativeObj, levels); + } // // C++: int cv::GeneralizedHoughGuil::getLevels() // - // C++: int cv::GeneralizedHoughGuil::getLevels() - private static native int getLevels_0(long nativeObj); + public int getLevels() { + return getLevels_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setAngleEpsilon(double angleEpsilon) // - // C++: void cv::GeneralizedHoughGuil::setAngleEpsilon(double angleEpsilon) - private static native void setAngleEpsilon_0(long nativeObj, double angleEpsilon); + public void setAngleEpsilon(double angleEpsilon) { + setAngleEpsilon_0(nativeObj, angleEpsilon); + } // // C++: double cv::GeneralizedHoughGuil::getAngleEpsilon() // - // C++: double cv::GeneralizedHoughGuil::getAngleEpsilon() - private static native double getAngleEpsilon_0(long nativeObj); + public double getAngleEpsilon() { + return getAngleEpsilon_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setMinAngle(double minAngle) // - // C++: void cv::GeneralizedHoughGuil::setMinAngle(double minAngle) - private static native void setMinAngle_0(long nativeObj, double minAngle); + public void setMinAngle(double minAngle) { + setMinAngle_0(nativeObj, minAngle); + } // // C++: double cv::GeneralizedHoughGuil::getMinAngle() // - // C++: double cv::GeneralizedHoughGuil::getMinAngle() - private static native double getMinAngle_0(long nativeObj); + public double getMinAngle() { + return getMinAngle_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setMaxAngle(double maxAngle) // - // C++: void cv::GeneralizedHoughGuil::setMaxAngle(double maxAngle) - private static native void setMaxAngle_0(long nativeObj, double maxAngle); + public void setMaxAngle(double maxAngle) { + setMaxAngle_0(nativeObj, maxAngle); + } // // C++: double cv::GeneralizedHoughGuil::getMaxAngle() // - // C++: double cv::GeneralizedHoughGuil::getMaxAngle() - private static native double getMaxAngle_0(long nativeObj); + public double getMaxAngle() { + return getMaxAngle_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setAngleStep(double angleStep) // - // C++: void cv::GeneralizedHoughGuil::setAngleStep(double angleStep) - private static native void setAngleStep_0(long nativeObj, double angleStep); + public void setAngleStep(double angleStep) { + setAngleStep_0(nativeObj, angleStep); + } // // C++: double cv::GeneralizedHoughGuil::getAngleStep() // - // C++: double cv::GeneralizedHoughGuil::getAngleStep() - private static native double getAngleStep_0(long nativeObj); + public double getAngleStep() { + return getAngleStep_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setAngleThresh(int angleThresh) // - // C++: void cv::GeneralizedHoughGuil::setAngleThresh(int angleThresh) - private static native void setAngleThresh_0(long nativeObj, int angleThresh); + public void setAngleThresh(int angleThresh) { + setAngleThresh_0(nativeObj, angleThresh); + } // // C++: int cv::GeneralizedHoughGuil::getAngleThresh() // - // C++: int cv::GeneralizedHoughGuil::getAngleThresh() - private static native int getAngleThresh_0(long nativeObj); + public int getAngleThresh() { + return getAngleThresh_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setMinScale(double minScale) // - // C++: void cv::GeneralizedHoughGuil::setMinScale(double minScale) - private static native void setMinScale_0(long nativeObj, double minScale); + public void setMinScale(double minScale) { + setMinScale_0(nativeObj, minScale); + } // // C++: double cv::GeneralizedHoughGuil::getMinScale() // - // C++: double cv::GeneralizedHoughGuil::getMinScale() - private static native double getMinScale_0(long nativeObj); + public double getMinScale() { + return getMinScale_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setMaxScale(double maxScale) // - // C++: void cv::GeneralizedHoughGuil::setMaxScale(double maxScale) - private static native void setMaxScale_0(long nativeObj, double maxScale); + public void setMaxScale(double maxScale) { + setMaxScale_0(nativeObj, maxScale); + } // // C++: double cv::GeneralizedHoughGuil::getMaxScale() // - // C++: double cv::GeneralizedHoughGuil::getMaxScale() - private static native double getMaxScale_0(long nativeObj); + public double getMaxScale() { + return getMaxScale_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setScaleStep(double scaleStep) // - // C++: void cv::GeneralizedHoughGuil::setScaleStep(double scaleStep) - private static native void setScaleStep_0(long nativeObj, double scaleStep); + public void setScaleStep(double scaleStep) { + setScaleStep_0(nativeObj, scaleStep); + } // // C++: double cv::GeneralizedHoughGuil::getScaleStep() // - // C++: double cv::GeneralizedHoughGuil::getScaleStep() - private static native double getScaleStep_0(long nativeObj); + public double getScaleStep() { + return getScaleStep_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setScaleThresh(int scaleThresh) // - // C++: void cv::GeneralizedHoughGuil::setScaleThresh(int scaleThresh) - private static native void setScaleThresh_0(long nativeObj, int scaleThresh); + public void setScaleThresh(int scaleThresh) { + setScaleThresh_0(nativeObj, scaleThresh); + } // // C++: int cv::GeneralizedHoughGuil::getScaleThresh() // - // C++: int cv::GeneralizedHoughGuil::getScaleThresh() - private static native int getScaleThresh_0(long nativeObj); + public int getScaleThresh() { + return getScaleThresh_0(nativeObj); + } // // C++: void cv::GeneralizedHoughGuil::setPosThresh(int posThresh) // - // C++: void cv::GeneralizedHoughGuil::setPosThresh(int posThresh) - private static native void setPosThresh_0(long nativeObj, int posThresh); + public void setPosThresh(int posThresh) { + setPosThresh_0(nativeObj, posThresh); + } // // C++: int cv::GeneralizedHoughGuil::getPosThresh() // - // C++: int cv::GeneralizedHoughGuil::getPosThresh() - private static native int getPosThresh_0(long nativeObj); + public int getPosThresh() { + return getPosThresh_0(nativeObj); + } - // native support for deleting native object - private static native void delete(long nativeObj); - public double getXi() { - return getXi_0(nativeObj); - } - public void setXi(double xi) { - setXi_0(nativeObj, xi); - } - public int getLevels() { - return getLevels_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setXi(double xi) + private static native void setXi_0(long nativeObj, double xi); - public void setLevels(int levels) { - setLevels_0(nativeObj, levels); - } + // C++: double cv::GeneralizedHoughGuil::getXi() + private static native double getXi_0(long nativeObj); - public double getAngleEpsilon() { - return getAngleEpsilon_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setLevels(int levels) + private static native void setLevels_0(long nativeObj, int levels); - public void setAngleEpsilon(double angleEpsilon) { - setAngleEpsilon_0(nativeObj, angleEpsilon); - } + // C++: int cv::GeneralizedHoughGuil::getLevels() + private static native int getLevels_0(long nativeObj); - public double getMinAngle() { - return getMinAngle_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setAngleEpsilon(double angleEpsilon) + private static native void setAngleEpsilon_0(long nativeObj, double angleEpsilon); - public void setMinAngle(double minAngle) { - setMinAngle_0(nativeObj, minAngle); - } + // C++: double cv::GeneralizedHoughGuil::getAngleEpsilon() + private static native double getAngleEpsilon_0(long nativeObj); - public double getMaxAngle() { - return getMaxAngle_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setMinAngle(double minAngle) + private static native void setMinAngle_0(long nativeObj, double minAngle); - public void setMaxAngle(double maxAngle) { - setMaxAngle_0(nativeObj, maxAngle); - } + // C++: double cv::GeneralizedHoughGuil::getMinAngle() + private static native double getMinAngle_0(long nativeObj); - public double getAngleStep() { - return getAngleStep_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setMaxAngle(double maxAngle) + private static native void setMaxAngle_0(long nativeObj, double maxAngle); - public void setAngleStep(double angleStep) { - setAngleStep_0(nativeObj, angleStep); - } + // C++: double cv::GeneralizedHoughGuil::getMaxAngle() + private static native double getMaxAngle_0(long nativeObj); - public int getAngleThresh() { - return getAngleThresh_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setAngleStep(double angleStep) + private static native void setAngleStep_0(long nativeObj, double angleStep); - public void setAngleThresh(int angleThresh) { - setAngleThresh_0(nativeObj, angleThresh); - } + // C++: double cv::GeneralizedHoughGuil::getAngleStep() + private static native double getAngleStep_0(long nativeObj); - public double getMinScale() { - return getMinScale_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setAngleThresh(int angleThresh) + private static native void setAngleThresh_0(long nativeObj, int angleThresh); - public void setMinScale(double minScale) { - setMinScale_0(nativeObj, minScale); - } + // C++: int cv::GeneralizedHoughGuil::getAngleThresh() + private static native int getAngleThresh_0(long nativeObj); - public double getMaxScale() { - return getMaxScale_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setMinScale(double minScale) + private static native void setMinScale_0(long nativeObj, double minScale); - public void setMaxScale(double maxScale) { - setMaxScale_0(nativeObj, maxScale); - } + // C++: double cv::GeneralizedHoughGuil::getMinScale() + private static native double getMinScale_0(long nativeObj); - public double getScaleStep() { - return getScaleStep_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setMaxScale(double maxScale) + private static native void setMaxScale_0(long nativeObj, double maxScale); - public void setScaleStep(double scaleStep) { - setScaleStep_0(nativeObj, scaleStep); - } + // C++: double cv::GeneralizedHoughGuil::getMaxScale() + private static native double getMaxScale_0(long nativeObj); - public int getScaleThresh() { - return getScaleThresh_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setScaleStep(double scaleStep) + private static native void setScaleStep_0(long nativeObj, double scaleStep); - public void setScaleThresh(int scaleThresh) { - setScaleThresh_0(nativeObj, scaleThresh); - } + // C++: double cv::GeneralizedHoughGuil::getScaleStep() + private static native double getScaleStep_0(long nativeObj); - public int getPosThresh() { - return getPosThresh_0(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setScaleThresh(int scaleThresh) + private static native void setScaleThresh_0(long nativeObj, int scaleThresh); - public void setPosThresh(int posThresh) { - setPosThresh_0(nativeObj, posThresh); - } + // C++: int cv::GeneralizedHoughGuil::getScaleThresh() + private static native int getScaleThresh_0(long nativeObj); - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } + // C++: void cv::GeneralizedHoughGuil::setPosThresh(int posThresh) + private static native void setPosThresh_0(long nativeObj, int posThresh); + + // C++: int cv::GeneralizedHoughGuil::getPosThresh() + private static native int getPosThresh_0(long nativeObj); + + // native support for deleting native object + private static native void delete(long nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/imgproc/Imgproc.java b/bus-opencv/src/main/java/org/opencv/imgproc/Imgproc.java index 621b39d2bc..802cc04d1c 100644 --- a/bus-opencv/src/main/java/org/opencv/imgproc/Imgproc.java +++ b/bus-opencv/src/main/java/org/opencv/imgproc/Imgproc.java @@ -13,6 +13,44 @@ public class Imgproc { + private static final int + IPL_BORDER_CONSTANT = 0, + IPL_BORDER_REPLICATE = 1, + IPL_BORDER_REFLECT = 2, + IPL_BORDER_WRAP = 3, + IPL_BORDER_REFLECT_101 = 4, + IPL_BORDER_TRANSPARENT = 5, + CV_INTER_NN = 0, + CV_INTER_LINEAR = 1, + CV_INTER_CUBIC = 2, + CV_INTER_AREA = 3, + CV_INTER_LANCZOS4 = 4, + CV_MOP_ERODE = 0, + CV_MOP_DILATE = 1, + CV_MOP_OPEN = 2, + CV_MOP_CLOSE = 3, + CV_MOP_GRADIENT = 4, + CV_MOP_TOPHAT = 5, + CV_MOP_BLACKHAT = 6, + CV_RETR_EXTERNAL = 0, + CV_RETR_LIST = 1, + CV_RETR_CCOMP = 2, + CV_RETR_TREE = 3, + CV_RETR_FLOODFILL = 4, + CV_CHAIN_APPROX_NONE = 1, + CV_CHAIN_APPROX_SIMPLE = 2, + CV_CHAIN_APPROX_TC89_L1 = 3, + CV_CHAIN_APPROX_TC89_KCOS = 4, + CV_THRESH_BINARY = 0, + CV_THRESH_BINARY_INV = 1, + CV_THRESH_TRUNC = 2, + CV_THRESH_TOZERO = 3, + CV_THRESH_TOZERO_INV = 4, + CV_THRESH_MASK = 7, + CV_THRESH_OTSU = 8, + CV_THRESH_TRIANGLE = 16; + + // C++: enum public static final int CV_GAUSSIAN_5x5 = 7, @@ -55,12 +93,16 @@ public class Imgproc { CV_HOUGH_PROBABILISTIC = 1, CV_HOUGH_MULTI_SCALE = 2, CV_HOUGH_GRADIENT = 3; + + // C++: enum MorphShapes_c (MorphShapes_c) public static final int CV_SHAPE_RECT = 0, CV_SHAPE_CROSS = 1, CV_SHAPE_ELLIPSE = 2, CV_SHAPE_CUSTOM = 100; + + // C++: enum SmoothMethod_c (SmoothMethod_c) public static final int CV_BLUR_NO_SCALE = 0, @@ -68,43 +110,15 @@ public class Imgproc { CV_GAUSSIAN = 2, CV_MEDIAN = 3, CV_BILATERAL = 4; + + // C++: enum AdaptiveThresholdTypes (cv.AdaptiveThresholdTypes) public static final int ADAPTIVE_THRESH_MEAN_C = 0, ADAPTIVE_THRESH_GAUSSIAN_C = 1; - // C++: enum ColormapTypes (cv.ColormapTypes) - public static final int - COLORMAP_AUTUMN = 0, - COLORMAP_BONE = 1, - COLORMAP_JET = 2, - COLORMAP_WINTER = 3, - COLORMAP_RAINBOW = 4, - COLORMAP_OCEAN = 5, - COLORMAP_SUMMER = 6, - COLORMAP_SPRING = 7, - COLORMAP_COOL = 8, - COLORMAP_HSV = 9, - COLORMAP_PINK = 10, - COLORMAP_HOT = 11, - COLORMAP_PARULA = 12, - COLORMAP_MAGMA = 13, - COLORMAP_INFERNO = 14, - COLORMAP_PLASMA = 15, - COLORMAP_VIRIDIS = 16, - COLORMAP_CIVIDIS = 17, - COLORMAP_TWILIGHT = 18, - COLORMAP_TWILIGHT_SHIFTED = 19, - COLORMAP_TURBO = 20, - COLORMAP_DEEPGREEN = 21; - // C++: enum ConnectedComponentsAlgorithmsTypes (cv.ConnectedComponentsAlgorithmsTypes) - public static final int - CCL_DEFAULT = -1, - CCL_WU = 0, - CCL_GRANA = 1, - CCL_BOLELLI = 2, - CCL_SAUF = 3, - CCL_BBDT = 4, - CCL_SPAGHETTI = 5; // C++: enum ColorConversionCodes (cv.ColorConversionCodes) + + + // C++: enum ColorConversionCodes (cv.ColorConversionCodes) public static final int COLOR_BGR2BGRA = 0, COLOR_RGB2RGBA = COLOR_BGR2BGRA, @@ -347,7 +361,74 @@ public class Imgproc { COLOR_BayerGB2RGBA = COLOR_BayerGR2BGRA, COLOR_BayerRG2RGBA = COLOR_BayerBG2BGRA, COLOR_BayerGR2RGBA = COLOR_BayerGB2BGRA, - COLOR_COLORCVT_MAX = 143; + COLOR_RGB2YUV_UYVY = 143, + COLOR_BGR2YUV_UYVY = 144, + COLOR_RGB2YUV_Y422 = COLOR_RGB2YUV_UYVY, + COLOR_BGR2YUV_Y422 = COLOR_BGR2YUV_UYVY, + COLOR_RGB2YUV_UYNV = COLOR_RGB2YUV_UYVY, + COLOR_BGR2YUV_UYNV = COLOR_BGR2YUV_UYVY, + COLOR_RGBA2YUV_UYVY = 145, + COLOR_BGRA2YUV_UYVY = 146, + COLOR_RGBA2YUV_Y422 = COLOR_RGBA2YUV_UYVY, + COLOR_BGRA2YUV_Y422 = COLOR_BGRA2YUV_UYVY, + COLOR_RGBA2YUV_UYNV = COLOR_RGBA2YUV_UYVY, + COLOR_BGRA2YUV_UYNV = COLOR_BGRA2YUV_UYVY, + COLOR_RGB2YUV_YUY2 = 147, + COLOR_BGR2YUV_YUY2 = 148, + COLOR_RGB2YUV_YVYU = 149, + COLOR_BGR2YUV_YVYU = 150, + COLOR_RGB2YUV_YUYV = COLOR_RGB2YUV_YUY2, + COLOR_BGR2YUV_YUYV = COLOR_BGR2YUV_YUY2, + COLOR_RGB2YUV_YUNV = COLOR_RGB2YUV_YUY2, + COLOR_BGR2YUV_YUNV = COLOR_BGR2YUV_YUY2, + COLOR_RGBA2YUV_YUY2 = 151, + COLOR_BGRA2YUV_YUY2 = 152, + COLOR_RGBA2YUV_YVYU = 153, + COLOR_BGRA2YUV_YVYU = 154, + COLOR_RGBA2YUV_YUYV = COLOR_RGBA2YUV_YUY2, + COLOR_BGRA2YUV_YUYV = COLOR_BGRA2YUV_YUY2, + COLOR_RGBA2YUV_YUNV = COLOR_RGBA2YUV_YUY2, + COLOR_BGRA2YUV_YUNV = COLOR_BGRA2YUV_YUY2, + COLOR_COLORCVT_MAX = 155; + + + // C++: enum ColormapTypes (cv.ColormapTypes) + public static final int + COLORMAP_AUTUMN = 0, + COLORMAP_BONE = 1, + COLORMAP_JET = 2, + COLORMAP_WINTER = 3, + COLORMAP_RAINBOW = 4, + COLORMAP_OCEAN = 5, + COLORMAP_SUMMER = 6, + COLORMAP_SPRING = 7, + COLORMAP_COOL = 8, + COLORMAP_HSV = 9, + COLORMAP_PINK = 10, + COLORMAP_HOT = 11, + COLORMAP_PARULA = 12, + COLORMAP_MAGMA = 13, + COLORMAP_INFERNO = 14, + COLORMAP_PLASMA = 15, + COLORMAP_VIRIDIS = 16, + COLORMAP_CIVIDIS = 17, + COLORMAP_TWILIGHT = 18, + COLORMAP_TWILIGHT_SHIFTED = 19, + COLORMAP_TURBO = 20, + COLORMAP_DEEPGREEN = 21; + + + // C++: enum ConnectedComponentsAlgorithmsTypes (cv.ConnectedComponentsAlgorithmsTypes) + public static final int + CCL_DEFAULT = -1, + CCL_WU = 0, + CCL_GRANA = 1, + CCL_BOLELLI = 2, + CCL_SAUF = 3, + CCL_BBDT = 4, + CCL_SPAGHETTI = 5; + + // C++: enum ConnectedComponentsTypes (cv.ConnectedComponentsTypes) public static final int CC_STAT_LEFT = 0, @@ -356,21 +437,29 @@ public class Imgproc { CC_STAT_HEIGHT = 3, CC_STAT_AREA = 4, CC_STAT_MAX = 5; + + // C++: enum ContourApproximationModes (cv.ContourApproximationModes) public static final int CHAIN_APPROX_NONE = 1, CHAIN_APPROX_SIMPLE = 2, CHAIN_APPROX_TC89_L1 = 3, CHAIN_APPROX_TC89_KCOS = 4; + + // C++: enum DistanceTransformLabelTypes (cv.DistanceTransformLabelTypes) public static final int DIST_LABEL_CCOMP = 0, DIST_LABEL_PIXEL = 1; + + // C++: enum DistanceTransformMasks (cv.DistanceTransformMasks) public static final int DIST_MASK_3 = 3, DIST_MASK_5 = 5, DIST_MASK_PRECISE = 0; + + // C++: enum DistanceTypes (cv.DistanceTypes) public static final int DIST_USER = -1, @@ -381,22 +470,30 @@ public class Imgproc { DIST_FAIR = 5, DIST_WELSCH = 6, DIST_HUBER = 7; + + // C++: enum FloodFillFlags (cv.FloodFillFlags) public static final int FLOODFILL_FIXED_RANGE = 1 << 16, FLOODFILL_MASK_ONLY = 1 << 17; + + // C++: enum GrabCutClasses (cv.GrabCutClasses) public static final int GC_BGD = 0, GC_FGD = 1, GC_PR_BGD = 2, GC_PR_FGD = 3; + + // C++: enum GrabCutModes (cv.GrabCutModes) public static final int GC_INIT_WITH_RECT = 0, GC_INIT_WITH_MASK = 1, GC_EVAL = 2, GC_EVAL_FREEZE_MODEL = 3; + + // C++: enum HersheyFonts (cv.HersheyFonts) public static final int FONT_HERSHEY_SIMPLEX = 0, @@ -408,6 +505,8 @@ public class Imgproc { FONT_HERSHEY_SCRIPT_SIMPLEX = 6, FONT_HERSHEY_SCRIPT_COMPLEX = 7, FONT_ITALIC = 16; + + // C++: enum HistCompMethods (cv.HistCompMethods) public static final int HISTCMP_CORREL = 0, @@ -417,6 +516,8 @@ public class Imgproc { HISTCMP_HELLINGER = HISTCMP_BHATTACHARYYA, HISTCMP_CHISQR_ALT = 4, HISTCMP_KL_DIV = 5; + + // C++: enum HoughModes (cv.HoughModes) public static final int HOUGH_STANDARD = 0, @@ -424,6 +525,8 @@ public class Imgproc { HOUGH_MULTI_SCALE = 2, HOUGH_GRADIENT = 3, HOUGH_GRADIENT_ALT = 4; + + // C++: enum InterpolationFlags (cv.InterpolationFlags) public static final int INTER_NEAREST = 0, @@ -436,17 +539,31 @@ public class Imgproc { INTER_MAX = 7, WARP_FILL_OUTLIERS = 8, WARP_INVERSE_MAP = 16; + + + // C++: enum InterpolationMasks (cv.InterpolationMasks) + public static final int + INTER_BITS = 5, + INTER_BITS2 = INTER_BITS * 2, + INTER_TAB_SIZE = 1 << INTER_BITS, + INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE; + + // C++: enum LineSegmentDetectorModes (cv.LineSegmentDetectorModes) public static final int LSD_REFINE_NONE = 0, LSD_REFINE_STD = 1, LSD_REFINE_ADV = 2; + + // C++: enum LineTypes (cv.LineTypes) public static final int FILLED = -1, LINE_4 = 4, LINE_8 = 8, LINE_AA = 16; + + // C++: enum MarkerTypes (cv.MarkerTypes) public static final int MARKER_CROSS = 0, @@ -455,17 +572,16 @@ public class Imgproc { MARKER_DIAMOND = 3, MARKER_SQUARE = 4, MARKER_TRIANGLE_UP = 5, - MARKER_TRIANGLE_DOWN = 6; // C++: enum InterpolationMasks (cv.InterpolationMasks) - public static final int - INTER_BITS = 5, - INTER_BITS2 = INTER_BITS * 2, - INTER_TAB_SIZE = 1 << INTER_BITS, - INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE; + MARKER_TRIANGLE_DOWN = 6; + + // C++: enum MorphShapes (cv.MorphShapes) public static final int MORPH_RECT = 0, MORPH_CROSS = 1, MORPH_ELLIPSE = 2; + + // C++: enum MorphTypes (cv.MorphTypes) public static final int MORPH_ERODE = 0, @@ -476,11 +592,15 @@ public class Imgproc { MORPH_TOPHAT = 5, MORPH_BLACKHAT = 6, MORPH_HITMISS = 7; + + // C++: enum RectanglesIntersectTypes (cv.RectanglesIntersectTypes) public static final int INTERSECT_NONE = 0, INTERSECT_PARTIAL = 1, INTERSECT_FULL = 2; + + // C++: enum RetrievalModes (cv.RetrievalModes) public static final int RETR_EXTERNAL = 0, @@ -488,14 +608,20 @@ public class Imgproc { RETR_CCOMP = 2, RETR_TREE = 3, RETR_FLOODFILL = 4; + + // C++: enum ShapeMatchModes (cv.ShapeMatchModes) public static final int CONTOURS_MATCH_I1 = 1, CONTOURS_MATCH_I2 = 2, CONTOURS_MATCH_I3 = 3; + + // C++: enum SpecialFilter (cv.SpecialFilter) public static final int FILTER_SCHARR = -1; + + // C++: enum TemplateMatchModes (cv.TemplateMatchModes) public static final int TM_SQDIFF = 0, @@ -504,6 +630,8 @@ public class Imgproc { TM_CCORR_NORMED = 3, TM_CCOEFF = 4, TM_CCOEFF_NORMED = 5; + + // C++: enum ThresholdTypes (cv.ThresholdTypes) public static final int THRESH_BINARY = 0, @@ -514,61 +642,32 @@ public class Imgproc { THRESH_MASK = 7, THRESH_OTSU = 8, THRESH_TRIANGLE = 16; + + // C++: enum WarpPolarMode (cv.WarpPolarMode) public static final int WARP_POLAR_LINEAR = 0, WARP_POLAR_LOG = 256; - private static final int - IPL_BORDER_CONSTANT = 0, - IPL_BORDER_REPLICATE = 1, - IPL_BORDER_REFLECT = 2, - IPL_BORDER_WRAP = 3, - IPL_BORDER_REFLECT_101 = 4, - IPL_BORDER_TRANSPARENT = 5, - CV_INTER_NN = 0, - CV_INTER_LINEAR = 1, - CV_INTER_CUBIC = 2, - CV_INTER_AREA = 3, - CV_INTER_LANCZOS4 = 4, - CV_MOP_ERODE = 0, - CV_MOP_DILATE = 1, - CV_MOP_OPEN = 2, - CV_MOP_CLOSE = 3, - CV_MOP_GRADIENT = 4, - CV_MOP_TOPHAT = 5, - CV_MOP_BLACKHAT = 6, - CV_RETR_EXTERNAL = 0, - CV_RETR_LIST = 1, - CV_RETR_CCOMP = 2, - CV_RETR_TREE = 3, - CV_RETR_FLOODFILL = 4, - CV_CHAIN_APPROX_NONE = 1, - CV_CHAIN_APPROX_SIMPLE = 2, - CV_CHAIN_APPROX_TC89_L1 = 3, - CV_CHAIN_APPROX_TC89_KCOS = 4, - CV_THRESH_BINARY = 0, - CV_THRESH_BINARY_INV = 1, - CV_THRESH_TRUNC = 2, - CV_THRESH_TOZERO = 3, - CV_THRESH_TOZERO_INV = 4, - CV_THRESH_MASK = 7, - CV_THRESH_OTSU = 8, - CV_THRESH_TRIANGLE = 16; + + + // + // C++: Ptr_LineSegmentDetector cv::createLineSegmentDetector(int refine = LSD_REFINE_STD, double scale = 0.8, double sigma_scale = 0.6, double quant = 2.0, double ang_th = 22.5, double log_eps = 0, double density_th = 0.7, int n_bins = 1024) + // /** * Creates a smart pointer to a LineSegmentDetector object and initializes it. - *

    + * * The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want * to edit those, as to tailor it for their own application. * - * @param refine The way found lines will be refined, see #LineSegmentDetectorModes - * @param scale The scale of the image that will be used to find the lines. Range (0..1]. + * @param refine The way found lines will be refined, see #LineSegmentDetectorModes + * @param scale The scale of the image that will be used to find the lines. Range (0..1]. * @param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. - * @param quant Bound to the quantization error on the gradient norm. - * @param ang_th Gradient angle tolerance in degrees. - * @param log_eps Detection threshold: -log10(NFA) > log_eps. Used only when advance refinement is chosen. - * @param density_th Minimal density of aligned region points in the enclosing rectangle. - * @param n_bins Number of bins in pseudo-ordering of gradient modulus. + * @param quant Bound to the quantization error on the gradient norm. + * @param ang_th Gradient angle tolerance in degrees. + * @param log_eps Detection threshold: -log10(NFA) > log_eps. Used only when advance refinement is chosen. + * @param density_th Minimal density of aligned region points in the enclosing rectangle. + * @param n_bins Number of bins in pseudo-ordering of gradient modulus. * @return automatically generated */ public static LineSegmentDetector createLineSegmentDetector(int refine, double scale, double sigma_scale, double quant, double ang_th, double log_eps, double density_th, int n_bins) { @@ -577,40 +676,35 @@ public static LineSegmentDetector createLineSegmentDetector(int refine, double s /** * Creates a smart pointer to a LineSegmentDetector object and initializes it. - *

    + * * The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want * to edit those, as to tailor it for their own application. * - * @param refine The way found lines will be refined, see #LineSegmentDetectorModes - * @param scale The scale of the image that will be used to find the lines. Range (0..1]. + * @param refine The way found lines will be refined, see #LineSegmentDetectorModes + * @param scale The scale of the image that will be used to find the lines. Range (0..1]. * @param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. - * @param quant Bound to the quantization error on the gradient norm. - * @param ang_th Gradient angle tolerance in degrees. - * @param log_eps Detection threshold: -log10(NFA) > log_eps. Used only when advance refinement is chosen. - * @param density_th Minimal density of aligned region points in the enclosing rectangle. + * @param quant Bound to the quantization error on the gradient norm. + * @param ang_th Gradient angle tolerance in degrees. + * @param log_eps Detection threshold: -log10(NFA) > log_eps. Used only when advance refinement is chosen. + * @param density_th Minimal density of aligned region points in the enclosing rectangle. * @return automatically generated */ public static LineSegmentDetector createLineSegmentDetector(int refine, double scale, double sigma_scale, double quant, double ang_th, double log_eps, double density_th) { return LineSegmentDetector.__fromPtr__(createLineSegmentDetector_1(refine, scale, sigma_scale, quant, ang_th, log_eps, density_th)); } - - // - // C++: Ptr_LineSegmentDetector cv::createLineSegmentDetector(int refine = LSD_REFINE_STD, double scale = 0.8, double sigma_scale = 0.6, double quant = 2.0, double ang_th = 22.5, double log_eps = 0, double density_th = 0.7, int n_bins = 1024) - // - /** * Creates a smart pointer to a LineSegmentDetector object and initializes it. - *

    + * * The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want * to edit those, as to tailor it for their own application. * - * @param refine The way found lines will be refined, see #LineSegmentDetectorModes - * @param scale The scale of the image that will be used to find the lines. Range (0..1]. + * @param refine The way found lines will be refined, see #LineSegmentDetectorModes + * @param scale The scale of the image that will be used to find the lines. Range (0..1]. * @param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. - * @param quant Bound to the quantization error on the gradient norm. - * @param ang_th Gradient angle tolerance in degrees. - * @param log_eps Detection threshold: -log10(NFA) > log_eps. Used only when advance refinement is chosen. + * @param quant Bound to the quantization error on the gradient norm. + * @param ang_th Gradient angle tolerance in degrees. + * @param log_eps Detection threshold: -log10(NFA) > log_eps. Used only when advance refinement is chosen. * @return automatically generated */ public static LineSegmentDetector createLineSegmentDetector(int refine, double scale, double sigma_scale, double quant, double ang_th, double log_eps) { @@ -619,15 +713,15 @@ public static LineSegmentDetector createLineSegmentDetector(int refine, double s /** * Creates a smart pointer to a LineSegmentDetector object and initializes it. - *

    + * * The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want * to edit those, as to tailor it for their own application. * - * @param refine The way found lines will be refined, see #LineSegmentDetectorModes - * @param scale The scale of the image that will be used to find the lines. Range (0..1]. + * @param refine The way found lines will be refined, see #LineSegmentDetectorModes + * @param scale The scale of the image that will be used to find the lines. Range (0..1]. * @param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. - * @param quant Bound to the quantization error on the gradient norm. - * @param ang_th Gradient angle tolerance in degrees. + * @param quant Bound to the quantization error on the gradient norm. + * @param ang_th Gradient angle tolerance in degrees. * @return automatically generated */ public static LineSegmentDetector createLineSegmentDetector(int refine, double scale, double sigma_scale, double quant, double ang_th) { @@ -636,14 +730,14 @@ public static LineSegmentDetector createLineSegmentDetector(int refine, double s /** * Creates a smart pointer to a LineSegmentDetector object and initializes it. - *

    + * * The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want * to edit those, as to tailor it for their own application. * - * @param refine The way found lines will be refined, see #LineSegmentDetectorModes - * @param scale The scale of the image that will be used to find the lines. Range (0..1]. + * @param refine The way found lines will be refined, see #LineSegmentDetectorModes + * @param scale The scale of the image that will be used to find the lines. Range (0..1]. * @param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. - * @param quant Bound to the quantization error on the gradient norm. + * @param quant Bound to the quantization error on the gradient norm. * @return automatically generated */ public static LineSegmentDetector createLineSegmentDetector(int refine, double scale, double sigma_scale, double quant) { @@ -652,12 +746,12 @@ public static LineSegmentDetector createLineSegmentDetector(int refine, double s /** * Creates a smart pointer to a LineSegmentDetector object and initializes it. - *

    + * * The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want * to edit those, as to tailor it for their own application. * - * @param refine The way found lines will be refined, see #LineSegmentDetectorModes - * @param scale The scale of the image that will be used to find the lines. Range (0..1]. + * @param refine The way found lines will be refined, see #LineSegmentDetectorModes + * @param scale The scale of the image that will be used to find the lines. Range (0..1]. * @param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. * @return automatically generated */ @@ -667,12 +761,12 @@ public static LineSegmentDetector createLineSegmentDetector(int refine, double s /** * Creates a smart pointer to a LineSegmentDetector object and initializes it. - *

    + * * The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want * to edit those, as to tailor it for their own application. * * @param refine The way found lines will be refined, see #LineSegmentDetectorModes - * @param scale The scale of the image that will be used to find the lines. Range (0..1]. + * @param scale The scale of the image that will be used to find the lines. Range (0..1]. * @return automatically generated */ public static LineSegmentDetector createLineSegmentDetector(int refine, double scale) { @@ -681,7 +775,7 @@ public static LineSegmentDetector createLineSegmentDetector(int refine, double s /** * Creates a smart pointer to a LineSegmentDetector object and initializes it. - *

    + * * The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want * to edit those, as to tailor it for their own application. * @@ -694,7 +788,7 @@ public static LineSegmentDetector createLineSegmentDetector(int refine) { /** * Creates a smart pointer to a LineSegmentDetector object and initializes it. - *

    + * * The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want * to edit those, as to tailor it for their own application. * @@ -704,25 +798,29 @@ public static LineSegmentDetector createLineSegmentDetector() { return LineSegmentDetector.__fromPtr__(createLineSegmentDetector_8()); } + + // + // C++: Mat cv::getGaussianKernel(int ksize, double sigma, int ktype = CV_64F) + // + /** * Returns Gaussian filter coefficients. - *

    + * * The function computes and returns the \(\texttt{ksize} \times 1\) matrix of Gaussian filter * coefficients: - *

    + * * \(G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\) - *

    + * * where \(i=0..\texttt{ksize}-1\) and \(\alpha\) is the scale factor chosen so that \(\sum_i G_i=1\). - *

    + * * Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize * smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. * You may also use the higher-level GaussianBlur. - * * @param ksize Aperture size. It should be odd ( \(\texttt{ksize} \mod 2 = 1\) ) and positive. * @param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as - * {@code sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8}. + * {@code sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8}. * @param ktype Type of filter coefficients. It can be CV_32F or CV_64F . - * SEE: sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur + * SEE: sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur * @return automatically generated */ public static Mat getGaussianKernel(int ksize, double sigma, int ktype) { @@ -731,22 +829,21 @@ public static Mat getGaussianKernel(int ksize, double sigma, int ktype) { /** * Returns Gaussian filter coefficients. - *

    + * * The function computes and returns the \(\texttt{ksize} \times 1\) matrix of Gaussian filter * coefficients: - *

    + * * \(G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\) - *

    + * * where \(i=0..\texttt{ksize}-1\) and \(\alpha\) is the scale factor chosen so that \(\sum_i G_i=1\). - *

    + * * Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize * smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. * You may also use the higher-level GaussianBlur. - * * @param ksize Aperture size. It should be odd ( \(\texttt{ksize} \mod 2 = 1\) ) and positive. * @param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as - * {@code sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8}. - * SEE: sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur + * {@code sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8}. + * SEE: sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur * @return automatically generated */ public static Mat getGaussianKernel(int ksize, double sigma) { @@ -755,27 +852,27 @@ public static Mat getGaussianKernel(int ksize, double sigma) { // - // C++: Mat cv::getGaussianKernel(int ksize, double sigma, int ktype = CV_64F) + // C++: void cv::getDerivKernels(Mat& kx, Mat& ky, int dx, int dy, int ksize, bool normalize = false, int ktype = CV_32F) // /** * Returns filter coefficients for computing spatial image derivatives. - *

    + * * The function computes and returns the filter coefficients for spatial image derivatives. When * {@code ksize=FILTER_SCHARR}, the Scharr \(3 \times 3\) kernels are generated (see #Scharr). Otherwise, Sobel * kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to * - * @param kx Output matrix of row filter coefficients. It has the type ktype . - * @param ky Output matrix of column filter coefficients. It has the type ktype . - * @param dx Derivative order in respect of x. - * @param dy Derivative order in respect of y. - * @param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7. + * @param kx Output matrix of row filter coefficients. It has the type ktype . + * @param ky Output matrix of column filter coefficients. It has the type ktype . + * @param dx Derivative order in respect of x. + * @param dy Derivative order in respect of y. + * @param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7. * @param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not. - * Theoretically, the coefficients should have the denominator \(=2^{ksize*2-dx-dy-2}\). If you are - * going to filter floating-point images, you are likely to use the normalized kernels. But if you - * compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve - * all the fractional bits, you may want to set normalize=false . - * @param ktype Type of filter coefficients. It can be CV_32f or CV_64F . + * Theoretically, the coefficients should have the denominator \(=2^{ksize*2-dx-dy-2}\). If you are + * going to filter floating-point images, you are likely to use the normalized kernels. But if you + * compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve + * all the fractional bits, you may want to set normalize=false . + * @param ktype Type of filter coefficients. It can be CV_32f or CV_64F . */ public static void getDerivKernels(Mat kx, Mat ky, int dx, int dy, int ksize, boolean normalize, int ktype) { getDerivKernels_0(kx.nativeObj, ky.nativeObj, dx, dy, ksize, normalize, ktype); @@ -783,55 +880,55 @@ public static void getDerivKernels(Mat kx, Mat ky, int dx, int dy, int ksize, bo /** * Returns filter coefficients for computing spatial image derivatives. - *

    + * * The function computes and returns the filter coefficients for spatial image derivatives. When * {@code ksize=FILTER_SCHARR}, the Scharr \(3 \times 3\) kernels are generated (see #Scharr). Otherwise, Sobel * kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to * - * @param kx Output matrix of row filter coefficients. It has the type ktype . - * @param ky Output matrix of column filter coefficients. It has the type ktype . - * @param dx Derivative order in respect of x. - * @param dy Derivative order in respect of y. - * @param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7. + * @param kx Output matrix of row filter coefficients. It has the type ktype . + * @param ky Output matrix of column filter coefficients. It has the type ktype . + * @param dx Derivative order in respect of x. + * @param dy Derivative order in respect of y. + * @param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7. * @param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not. - * Theoretically, the coefficients should have the denominator \(=2^{ksize*2-dx-dy-2}\). If you are - * going to filter floating-point images, you are likely to use the normalized kernels. But if you - * compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve - * all the fractional bits, you may want to set normalize=false . + * Theoretically, the coefficients should have the denominator \(=2^{ksize*2-dx-dy-2}\). If you are + * going to filter floating-point images, you are likely to use the normalized kernels. But if you + * compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve + * all the fractional bits, you may want to set normalize=false . */ public static void getDerivKernels(Mat kx, Mat ky, int dx, int dy, int ksize, boolean normalize) { getDerivKernels_1(kx.nativeObj, ky.nativeObj, dx, dy, ksize, normalize); } - - // - // C++: void cv::getDerivKernels(Mat& kx, Mat& ky, int dx, int dy, int ksize, bool normalize = false, int ktype = CV_32F) - // - /** * Returns filter coefficients for computing spatial image derivatives. - *

    + * * The function computes and returns the filter coefficients for spatial image derivatives. When * {@code ksize=FILTER_SCHARR}, the Scharr \(3 \times 3\) kernels are generated (see #Scharr). Otherwise, Sobel * kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to * - * @param kx Output matrix of row filter coefficients. It has the type ktype . - * @param ky Output matrix of column filter coefficients. It has the type ktype . - * @param dx Derivative order in respect of x. - * @param dy Derivative order in respect of y. + * @param kx Output matrix of row filter coefficients. It has the type ktype . + * @param ky Output matrix of column filter coefficients. It has the type ktype . + * @param dx Derivative order in respect of x. + * @param dy Derivative order in respect of y. * @param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7. - * Theoretically, the coefficients should have the denominator \(=2^{ksize*2-dx-dy-2}\). If you are - * going to filter floating-point images, you are likely to use the normalized kernels. But if you - * compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve - * all the fractional bits, you may want to set normalize=false . + * Theoretically, the coefficients should have the denominator \(=2^{ksize*2-dx-dy-2}\). If you are + * going to filter floating-point images, you are likely to use the normalized kernels. But if you + * compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve + * all the fractional bits, you may want to set normalize=false . */ public static void getDerivKernels(Mat kx, Mat ky, int dx, int dy, int ksize) { getDerivKernels_2(kx.nativeObj, ky.nativeObj, dx, dy, ksize); } + + // + // C++: Mat cv::getGaborKernel(Size ksize, double sigma, double theta, double lambd, double gamma, double psi = CV_PI*0.5, int ktype = CV_64F) + // + /** * Returns Gabor filter coefficients. - *

    + * * For more details about gabor filter equations and parameters, see: [Gabor * Filter](http://en.wikipedia.org/wiki/Gabor_filter). * @@ -840,7 +937,7 @@ public static void getDerivKernels(Mat kx, Mat ky, int dx, int dy, int ksize) { * @param theta Orientation of the normal to the parallel stripes of a Gabor function. * @param lambd Wavelength of the sinusoidal factor. * @param gamma Spatial aspect ratio. - * @param psi Phase offset. + * @param psi Phase offset. * @param ktype Type of filter coefficients. It can be CV_32F or CV_64F . * @return automatically generated */ @@ -850,7 +947,7 @@ public static Mat getGaborKernel(Size ksize, double sigma, double theta, double /** * Returns Gabor filter coefficients. - *

    + * * For more details about gabor filter equations and parameters, see: [Gabor * Filter](http://en.wikipedia.org/wiki/Gabor_filter). * @@ -859,21 +956,16 @@ public static Mat getGaborKernel(Size ksize, double sigma, double theta, double * @param theta Orientation of the normal to the parallel stripes of a Gabor function. * @param lambd Wavelength of the sinusoidal factor. * @param gamma Spatial aspect ratio. - * @param psi Phase offset. + * @param psi Phase offset. * @return automatically generated */ public static Mat getGaborKernel(Size ksize, double sigma, double theta, double lambd, double gamma, double psi) { return new Mat(getGaborKernel_1(ksize.width, ksize.height, sigma, theta, lambd, gamma, psi)); } - - // - // C++: Mat cv::getGaborKernel(Size ksize, double sigma, double theta, double lambd, double gamma, double psi = CV_PI*0.5, int ktype = CV_64F) - // - /** * Returns Gabor filter coefficients. - *

    + * * For more details about gabor filter equations and parameters, see: [Gabor * Filter](http://en.wikipedia.org/wiki/Gabor_filter). * @@ -888,19 +980,24 @@ public static Mat getGaborKernel(Size ksize, double sigma, double theta, double return new Mat(getGaborKernel_2(ksize.width, ksize.height, sigma, theta, lambd, gamma)); } + + // + // C++: Mat cv::getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)) + // + /** * Returns a structuring element of the specified size and shape for morphological operations. - *

    + * * The function constructs and returns the structuring element that can be further passed to #erode, * #dilate or #morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as * the structuring element. * - * @param shape Element shape that could be one of #MorphShapes - * @param ksize Size of the structuring element. + * @param shape Element shape that could be one of #MorphShapes + * @param ksize Size of the structuring element. * @param anchor Anchor position within the element. The default value \((-1, -1)\) means that the - * anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor - * position. In other cases the anchor just regulates how much the result of the morphological - * operation is shifted. + * anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor + * position. In other cases the anchor just regulates how much the result of the morphological + * operation is shifted. * @return automatically generated */ public static Mat getStructuringElement(int shape, Size ksize, Point anchor) { @@ -909,16 +1006,16 @@ public static Mat getStructuringElement(int shape, Size ksize, Point anchor) { /** * Returns a structuring element of the specified size and shape for morphological operations. - *

    + * * The function constructs and returns the structuring element that can be further passed to #erode, * #dilate or #morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as * the structuring element. * * @param shape Element shape that could be one of #MorphShapes * @param ksize Size of the structuring element. - * anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor - * position. In other cases the anchor just regulates how much the result of the morphological - * operation is shifted. + * anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor + * position. In other cases the anchor just regulates how much the result of the morphological + * operation is shifted. * @return automatically generated */ public static Mat getStructuringElement(int shape, Size ksize) { @@ -927,138 +1024,137 @@ public static Mat getStructuringElement(int shape, Size ksize) { // - // C++: Mat cv::getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)) + // C++: void cv::medianBlur(Mat src, Mat& dst, int ksize) // /** * Blurs an image using the median filter. - *

    + * * The function smoothes an image using the median filter with the \(\texttt{ksize} \times * \texttt{ksize}\) aperture. Each channel of a multi-channel image is processed independently. * In-place operation is supported. * * Note: The median filter uses #BORDER_REPLICATE internally to cope with border pixels, see #BorderTypes * - * @param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be - * CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U. - * @param dst destination array of the same size and type as src. + * @param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be + * CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U. + * @param dst destination array of the same size and type as src. * @param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... - * SEE: bilateralFilter, blur, boxFilter, GaussianBlur + * SEE: bilateralFilter, blur, boxFilter, GaussianBlur */ public static void medianBlur(Mat src, Mat dst, int ksize) { medianBlur_0(src.nativeObj, dst.nativeObj, ksize); } + + // + // C++: void cv::GaussianBlur(Mat src, Mat& dst, Size ksize, double sigmaX, double sigmaY = 0, int borderType = BORDER_DEFAULT) + // + /** * Blurs an image using a Gaussian filter. - *

    + * * The function convolves the source image with the specified Gaussian kernel. In-place filtering is * supported. * - * @param src input image; the image can have any number of channels, which are processed - * independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be - * positive and odd. Or, they can be zero's and then they are computed from sigma. - * @param sigmaX Gaussian kernel standard deviation in X direction. - * @param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be - * equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, - * respectively (see #getGaussianKernel for details); to fully control the result regardless of - * possible future modifications of all this semantics, it is recommended to specify all of ksize, - * sigmaX, and sigmaY. + * @param src input image; the image can have any number of channels, which are processed + * independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be + * positive and odd. Or, they can be zero's and then they are computed from sigma. + * @param sigmaX Gaussian kernel standard deviation in X direction. + * @param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be + * equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, + * respectively (see #getGaussianKernel for details); to fully control the result regardless of + * possible future modifications of all this semantics, it is recommended to specify all of ksize, + * sigmaX, and sigmaY. * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. - *

    - * SEE: sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur + * + * SEE: sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur */ public static void GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX, double sigmaY, int borderType) { GaussianBlur_0(src.nativeObj, dst.nativeObj, ksize.width, ksize.height, sigmaX, sigmaY, borderType); } - - // - // C++: void cv::medianBlur(Mat src, Mat& dst, int ksize) - // - /** * Blurs an image using a Gaussian filter. - *

    + * * The function convolves the source image with the specified Gaussian kernel. In-place filtering is * supported. * - * @param src input image; the image can have any number of channels, which are processed - * independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be - * positive and odd. Or, they can be zero's and then they are computed from sigma. + * @param src input image; the image can have any number of channels, which are processed + * independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be + * positive and odd. Or, they can be zero's and then they are computed from sigma. * @param sigmaX Gaussian kernel standard deviation in X direction. * @param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be - * equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, - * respectively (see #getGaussianKernel for details); to fully control the result regardless of - * possible future modifications of all this semantics, it is recommended to specify all of ksize, - * sigmaX, and sigmaY. - *

    - * SEE: sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur + * equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, + * respectively (see #getGaussianKernel for details); to fully control the result regardless of + * possible future modifications of all this semantics, it is recommended to specify all of ksize, + * sigmaX, and sigmaY. + * + * SEE: sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur */ public static void GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX, double sigmaY) { GaussianBlur_1(src.nativeObj, dst.nativeObj, ksize.width, ksize.height, sigmaX, sigmaY); } - - // - // C++: void cv::GaussianBlur(Mat src, Mat& dst, Size ksize, double sigmaX, double sigmaY = 0, int borderType = BORDER_DEFAULT) - // - /** * Blurs an image using a Gaussian filter. - *

    + * * The function convolves the source image with the specified Gaussian kernel. In-place filtering is * supported. * - * @param src input image; the image can have any number of channels, which are processed - * independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be - * positive and odd. Or, they can be zero's and then they are computed from sigma. + * @param src input image; the image can have any number of channels, which are processed + * independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be + * positive and odd. Or, they can be zero's and then they are computed from sigma. * @param sigmaX Gaussian kernel standard deviation in X direction. - * equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, - * respectively (see #getGaussianKernel for details); to fully control the result regardless of - * possible future modifications of all this semantics, it is recommended to specify all of ksize, - * sigmaX, and sigmaY. - *

    - * SEE: sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur + * equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, + * respectively (see #getGaussianKernel for details); to fully control the result regardless of + * possible future modifications of all this semantics, it is recommended to specify all of ksize, + * sigmaX, and sigmaY. + * + * SEE: sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur */ public static void GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX) { GaussianBlur_2(src.nativeObj, dst.nativeObj, ksize.width, ksize.height, sigmaX); } + + // + // C++: void cv::bilateralFilter(Mat src, Mat& dst, int d, double sigmaColor, double sigmaSpace, int borderType = BORDER_DEFAULT) + // + /** * Applies the bilateral filter to an image. - *

    + * * The function applies bilateral filtering to the input image, as described in * http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html * bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is * very slow compared to most filters. - *

    + * * _Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (< * 10), the filter will not have much effect, whereas if they are large (> 150), they will have a very * strong effect, making the image look "cartoonish". - *

    + * * _Filter size_: Large filters (d > 5) are very slow, so it is recommended to use d=5 for real-time * applications, and perhaps d=9 for offline applications that need heavy noise filtering. - *

    - * This filter does not work inplace. * - * @param src Source 8-bit or floating-point, 1-channel or 3-channel image. - * @param dst Destination image of the same size and type as src . - * @param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, - * it is computed from sigmaSpace. + * This filter does not work inplace. + * @param src Source 8-bit or floating-point, 1-channel or 3-channel image. + * @param dst Destination image of the same size and type as src . + * @param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, + * it is computed from sigmaSpace. * @param sigmaColor Filter sigma in the color space. A larger value of the parameter means that - * farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting - * in larger areas of semi-equal color. + * farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting + * in larger areas of semi-equal color. * @param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that - * farther pixels will influence each other as long as their colors are close enough (see sigmaColor - * ). When d>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is - * proportional to sigmaSpace. + * farther pixels will influence each other as long as their colors are close enough (see sigmaColor + * ). When d>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is + * proportional to sigmaSpace. * @param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes */ public static void bilateralFilter(Mat src, Mat dst, int d, double sigmaColor, double sigmaSpace, int borderType) { @@ -1067,32 +1163,31 @@ public static void bilateralFilter(Mat src, Mat dst, int d, double sigmaColor, d /** * Applies the bilateral filter to an image. - *

    + * * The function applies bilateral filtering to the input image, as described in * http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html * bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is * very slow compared to most filters. - *

    + * * _Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (< * 10), the filter will not have much effect, whereas if they are large (> 150), they will have a very * strong effect, making the image look "cartoonish". - *

    + * * _Filter size_: Large filters (d > 5) are very slow, so it is recommended to use d=5 for real-time * applications, and perhaps d=9 for offline applications that need heavy noise filtering. - *

    - * This filter does not work inplace. * - * @param src Source 8-bit or floating-point, 1-channel or 3-channel image. - * @param dst Destination image of the same size and type as src . - * @param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, - * it is computed from sigmaSpace. + * This filter does not work inplace. + * @param src Source 8-bit or floating-point, 1-channel or 3-channel image. + * @param dst Destination image of the same size and type as src . + * @param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, + * it is computed from sigmaSpace. * @param sigmaColor Filter sigma in the color space. A larger value of the parameter means that - * farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting - * in larger areas of semi-equal color. + * farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting + * in larger areas of semi-equal color. * @param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that - * farther pixels will influence each other as long as their colors are close enough (see sigmaColor - * ). When d>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is - * proportional to sigmaSpace. + * farther pixels will influence each other as long as their colors are close enough (see sigmaColor + * ). When d>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is + * proportional to sigmaSpace. */ public static void bilateralFilter(Mat src, Mat dst, int d, double sigmaColor, double sigmaSpace) { bilateralFilter_1(src.nativeObj, dst.nativeObj, d, sigmaColor, sigmaSpace); @@ -1100,33 +1195,33 @@ public static void bilateralFilter(Mat src, Mat dst, int d, double sigmaColor, d // - // C++: void cv::bilateralFilter(Mat src, Mat& dst, int d, double sigmaColor, double sigmaSpace, int borderType = BORDER_DEFAULT) + // C++: void cv::boxFilter(Mat src, Mat& dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), bool normalize = true, int borderType = BORDER_DEFAULT) // /** * Blurs an image using the box filter. - *

    + * * The function smooths an image using the kernel: - *

    + * * \(\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\) - *

    + * * where - *

    + * * \(\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\) - *

    + * * Unnormalized box filter is useful for computing various integral characteristics over each pixel * neighborhood, such as covariance matrices of image derivatives (used in dense optical flow * algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral. * - * @param src input image. - * @param dst output image of the same size and type as src. - * @param ddepth the output image depth (-1 to use src.depth()). - * @param ksize blurring kernel size. - * @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel - * center. - * @param normalize flag, specifying whether the kernel is normalized by its area or not. + * @param src input image. + * @param dst output image of the same size and type as src. + * @param ddepth the output image depth (-1 to use src.depth()). + * @param ksize blurring kernel size. + * @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel + * center. + * @param normalize flag, specifying whether the kernel is normalized by its area or not. * @param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. - * SEE: blur, bilateralFilter, GaussianBlur, medianBlur, integral + * SEE: blur, bilateralFilter, GaussianBlur, medianBlur, integral */ public static void boxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anchor, boolean normalize, int borderType) { boxFilter_0(src.nativeObj, dst.nativeObj, ddepth, ksize.width, ksize.height, anchor.x, anchor.y, normalize, borderType); @@ -1134,59 +1229,54 @@ public static void boxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anc /** * Blurs an image using the box filter. - *

    + * * The function smooths an image using the kernel: - *

    + * * \(\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\) - *

    + * * where - *

    + * * \(\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\) - *

    + * * Unnormalized box filter is useful for computing various integral characteristics over each pixel * neighborhood, such as covariance matrices of image derivatives (used in dense optical flow * algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral. * - * @param src input image. - * @param dst output image of the same size and type as src. - * @param ddepth the output image depth (-1 to use src.depth()). - * @param ksize blurring kernel size. - * @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel - * center. + * @param src input image. + * @param dst output image of the same size and type as src. + * @param ddepth the output image depth (-1 to use src.depth()). + * @param ksize blurring kernel size. + * @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel + * center. * @param normalize flag, specifying whether the kernel is normalized by its area or not. - * SEE: blur, bilateralFilter, GaussianBlur, medianBlur, integral + * SEE: blur, bilateralFilter, GaussianBlur, medianBlur, integral */ public static void boxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anchor, boolean normalize) { boxFilter_1(src.nativeObj, dst.nativeObj, ddepth, ksize.width, ksize.height, anchor.x, anchor.y, normalize); } - - // - // C++: void cv::boxFilter(Mat src, Mat& dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), bool normalize = true, int borderType = BORDER_DEFAULT) - // - /** * Blurs an image using the box filter. - *

    + * * The function smooths an image using the kernel: - *

    + * * \(\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\) - *

    + * * where - *

    + * * \(\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\) - *

    + * * Unnormalized box filter is useful for computing various integral characteristics over each pixel * neighborhood, such as covariance matrices of image derivatives (used in dense optical flow * algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral. * - * @param src input image. - * @param dst output image of the same size and type as src. + * @param src input image. + * @param dst output image of the same size and type as src. * @param ddepth the output image depth (-1 to use src.depth()). - * @param ksize blurring kernel size. + * @param ksize blurring kernel size. * @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel - * center. - * SEE: blur, bilateralFilter, GaussianBlur, medianBlur, integral + * center. + * SEE: blur, bilateralFilter, GaussianBlur, medianBlur, integral */ public static void boxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anchor) { boxFilter_2(src.nativeObj, dst.nativeObj, ddepth, ksize.width, ksize.height, anchor.x, anchor.y); @@ -1194,48 +1284,53 @@ public static void boxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anc /** * Blurs an image using the box filter. - *

    + * * The function smooths an image using the kernel: - *

    + * * \(\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\) - *

    + * * where - *

    + * * \(\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\) - *

    + * * Unnormalized box filter is useful for computing various integral characteristics over each pixel * neighborhood, such as covariance matrices of image derivatives (used in dense optical flow * algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral. * - * @param src input image. - * @param dst output image of the same size and type as src. + * @param src input image. + * @param dst output image of the same size and type as src. * @param ddepth the output image depth (-1 to use src.depth()). - * @param ksize blurring kernel size. - * center. - * SEE: blur, bilateralFilter, GaussianBlur, medianBlur, integral + * @param ksize blurring kernel size. + * center. + * SEE: blur, bilateralFilter, GaussianBlur, medianBlur, integral */ public static void boxFilter(Mat src, Mat dst, int ddepth, Size ksize) { boxFilter_3(src.nativeObj, dst.nativeObj, ddepth, ksize.width, ksize.height); } + + // + // C++: void cv::sqrBoxFilter(Mat src, Mat& dst, int ddepth, Size ksize, Point anchor = Point(-1, -1), bool normalize = true, int borderType = BORDER_DEFAULT) + // + /** * Calculates the normalized sum of squares of the pixel values overlapping the filter. - *

    + * * For every pixel \( (x, y) \) in the source image, the function calculates the sum of squares of those neighboring * pixel values which overlap the filter placed over the pixel \( (x, y) \). - *

    + * * The unnormalized square box filter can be useful in computing local image statistics such as the local * variance and standard deviation around the neighborhood of a pixel. * - * @param src input image - * @param dst output image of the same size and type as src - * @param ddepth the output image depth (-1 to use src.depth()) - * @param ksize kernel size - * @param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel - * center. - * @param normalize flag, specifying whether the kernel is to be normalized by it's area or not. + * @param src input image + * @param dst output image of the same size and type as src + * @param ddepth the output image depth (-1 to use src.depth()) + * @param ksize kernel size + * @param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel + * center. + * @param normalize flag, specifying whether the kernel is to be normalized by it's area or not. * @param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. - * SEE: boxFilter + * SEE: boxFilter */ public static void sqrBoxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anchor, boolean normalize, int borderType) { sqrBoxFilter_0(src.nativeObj, dst.nativeObj, ddepth, ksize.width, ksize.height, anchor.x, anchor.y, normalize, borderType); @@ -1243,47 +1338,42 @@ public static void sqrBoxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point /** * Calculates the normalized sum of squares of the pixel values overlapping the filter. - *

    + * * For every pixel \( (x, y) \) in the source image, the function calculates the sum of squares of those neighboring * pixel values which overlap the filter placed over the pixel \( (x, y) \). - *

    + * * The unnormalized square box filter can be useful in computing local image statistics such as the local * variance and standard deviation around the neighborhood of a pixel. * - * @param src input image - * @param dst output image of the same size and type as src - * @param ddepth the output image depth (-1 to use src.depth()) - * @param ksize kernel size - * @param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel - * center. + * @param src input image + * @param dst output image of the same size and type as src + * @param ddepth the output image depth (-1 to use src.depth()) + * @param ksize kernel size + * @param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel + * center. * @param normalize flag, specifying whether the kernel is to be normalized by it's area or not. - * SEE: boxFilter + * SEE: boxFilter */ public static void sqrBoxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anchor, boolean normalize) { sqrBoxFilter_1(src.nativeObj, dst.nativeObj, ddepth, ksize.width, ksize.height, anchor.x, anchor.y, normalize); } - - // - // C++: void cv::sqrBoxFilter(Mat src, Mat& dst, int ddepth, Size ksize, Point anchor = Point(-1, -1), bool normalize = true, int borderType = BORDER_DEFAULT) - // - /** * Calculates the normalized sum of squares of the pixel values overlapping the filter. - *

    + * * For every pixel \( (x, y) \) in the source image, the function calculates the sum of squares of those neighboring * pixel values which overlap the filter placed over the pixel \( (x, y) \). - *

    + * * The unnormalized square box filter can be useful in computing local image statistics such as the local * variance and standard deviation around the neighborhood of a pixel. * - * @param src input image - * @param dst output image of the same size and type as src + * @param src input image + * @param dst output image of the same size and type as src * @param ddepth the output image depth (-1 to use src.depth()) - * @param ksize kernel size + * @param ksize kernel size * @param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel - * center. - * SEE: boxFilter + * center. + * SEE: boxFilter */ public static void sqrBoxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point anchor) { sqrBoxFilter_2(src.nativeObj, dst.nativeObj, ddepth, ksize.width, ksize.height, anchor.x, anchor.y); @@ -1291,42 +1381,47 @@ public static void sqrBoxFilter(Mat src, Mat dst, int ddepth, Size ksize, Point /** * Calculates the normalized sum of squares of the pixel values overlapping the filter. - *

    + * * For every pixel \( (x, y) \) in the source image, the function calculates the sum of squares of those neighboring * pixel values which overlap the filter placed over the pixel \( (x, y) \). - *

    + * * The unnormalized square box filter can be useful in computing local image statistics such as the local * variance and standard deviation around the neighborhood of a pixel. * - * @param src input image - * @param dst output image of the same size and type as src + * @param src input image + * @param dst output image of the same size and type as src * @param ddepth the output image depth (-1 to use src.depth()) - * @param ksize kernel size - * center. - * SEE: boxFilter + * @param ksize kernel size + * center. + * SEE: boxFilter */ public static void sqrBoxFilter(Mat src, Mat dst, int ddepth, Size ksize) { sqrBoxFilter_3(src.nativeObj, dst.nativeObj, ddepth, ksize.width, ksize.height); } + + // + // C++: void cv::blur(Mat src, Mat& dst, Size ksize, Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT) + // + /** * Blurs an image using the normalized box filter. - *

    + * * The function smooths an image using the kernel: - *

    + * * \(\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\) - *

    + * * The call {@code blur(src, dst, ksize, anchor, borderType)} is equivalent to `boxFilter(src, dst, src.type(), ksize, * anchor, true, borderType)`. * - * @param src input image; it can have any number of channels, which are processed independently, but - * the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param ksize blurring kernel size. - * @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel - * center. + * @param src input image; it can have any number of channels, which are processed independently, but + * the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param ksize blurring kernel size. + * @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel + * center. * @param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. - * SEE: boxFilter, bilateralFilter, GaussianBlur, medianBlur + * SEE: boxFilter, bilateralFilter, GaussianBlur, medianBlur */ public static void blur(Mat src, Mat dst, Size ksize, Point anchor, int borderType) { blur_0(src.nativeObj, dst.nativeObj, ksize.width, ksize.height, anchor.x, anchor.y, borderType); @@ -1334,55 +1429,55 @@ public static void blur(Mat src, Mat dst, Size ksize, Point anchor, int borderTy /** * Blurs an image using the normalized box filter. - *

    + * * The function smooths an image using the kernel: - *

    + * * \(\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\) - *

    + * * The call {@code blur(src, dst, ksize, anchor, borderType)} is equivalent to `boxFilter(src, dst, src.type(), ksize, * anchor, true, borderType)`. * - * @param src input image; it can have any number of channels, which are processed independently, but - * the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param ksize blurring kernel size. + * @param src input image; it can have any number of channels, which are processed independently, but + * the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param ksize blurring kernel size. * @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel - * center. - * SEE: boxFilter, bilateralFilter, GaussianBlur, medianBlur + * center. + * SEE: boxFilter, bilateralFilter, GaussianBlur, medianBlur */ public static void blur(Mat src, Mat dst, Size ksize, Point anchor) { blur_1(src.nativeObj, dst.nativeObj, ksize.width, ksize.height, anchor.x, anchor.y); } - - // - // C++: void cv::blur(Mat src, Mat& dst, Size ksize, Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT) - // - /** * Blurs an image using the normalized box filter. - *

    + * * The function smooths an image using the kernel: - *

    + * * \(\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\) - *

    + * * The call {@code blur(src, dst, ksize, anchor, borderType)} is equivalent to `boxFilter(src, dst, src.type(), ksize, * anchor, true, borderType)`. * - * @param src input image; it can have any number of channels, which are processed independently, but - * the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. + * @param src input image; it can have any number of channels, which are processed independently, but + * the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. * @param ksize blurring kernel size. - * center. - * SEE: boxFilter, bilateralFilter, GaussianBlur, medianBlur + * center. + * SEE: boxFilter, bilateralFilter, GaussianBlur, medianBlur */ public static void blur(Mat src, Mat dst, Size ksize) { blur_2(src.nativeObj, dst.nativeObj, ksize.width, ksize.height); } + + // + // C++: void cv::stackBlur(Mat src, Mat& dst, Size ksize) + // + /** * Blurs an image using the stackBlur. - *

    + * * The function applies and stackBlur to an image. * stackBlur can generate similar results as Gaussian blur, and the time consumption does not increase with the increase of kernel size. * It creates a kind of moving stack of colors whilst scanning through the image. Thereby it just has to add one new block of color to the right side @@ -1390,123 +1485,118 @@ public static void blur(Mat src, Mat dst, Size ksize) { * depending on if they are on the right or on the left side of the stack. The only supported borderType is BORDER_REPLICATE. * Original paper was proposed by Mario Klingemann, which can be found http://underdestruction.com/2004/02/25/stackblur-2004. * - * @param src input image. The number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S or CV_32F. - * @param dst output image of the same size and type as src. + * @param src input image. The number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S or CV_32F. + * @param dst output image of the same size and type as src. * @param ksize stack-blurring kernel size. The ksize.width and ksize.height can differ but they both must be - * positive and odd. + * positive and odd. */ public static void stackBlur(Mat src, Mat dst, Size ksize) { stackBlur_0(src.nativeObj, dst.nativeObj, ksize.width, ksize.height); } + + // + // C++: void cv::filter2D(Mat src, Mat& dst, int ddepth, Mat kernel, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT) + // + /** * Convolves an image with the kernel. - *

    + * * The function applies an arbitrary linear filter to an image. In-place operation is supported. When * the aperture is partially outside the image, the function interpolates outlier pixel values * according to the specified border mode. - *

    + * * The function does actually compute correlation, not the convolution: - *

    + * * \(\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\) - *

    + * * That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip * the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - * anchor.y - 1)`. - *

    + * * The function uses the DFT-based algorithm in case of sufficiently large kernels (~{@code 11 x 11} or * larger) and the direct algorithm for small kernels. * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src. - * @param ddepth desired depth of the destination image, see REF: filter_depths "combinations" - * @param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point - * matrix; if you want to apply different kernels to different channels, split the image into - * separate color planes using split and process them individually. - * @param anchor anchor of the kernel that indicates the relative position of a filtered point within - * the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor - * is at the kernel center. - * @param delta optional value added to the filtered pixels before storing them in dst. + * @param src input image. + * @param dst output image of the same size and the same number of channels as src. + * @param ddepth desired depth of the destination image, see REF: filter_depths "combinations" + * @param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point + * matrix; if you want to apply different kernels to different channels, split the image into + * separate color planes using split and process them individually. + * @param anchor anchor of the kernel that indicates the relative position of a filtered point within + * the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor + * is at the kernel center. + * @param delta optional value added to the filtered pixels before storing them in dst. * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. - * SEE: sepFilter2D, dft, matchTemplate + * SEE: sepFilter2D, dft, matchTemplate */ public static void filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta, int borderType) { filter2D_0(src.nativeObj, dst.nativeObj, ddepth, kernel.nativeObj, anchor.x, anchor.y, delta, borderType); } - - // - // C++: void cv::stackBlur(Mat src, Mat& dst, Size ksize) - // - /** * Convolves an image with the kernel. - *

    + * * The function applies an arbitrary linear filter to an image. In-place operation is supported. When * the aperture is partially outside the image, the function interpolates outlier pixel values * according to the specified border mode. - *

    + * * The function does actually compute correlation, not the convolution: - *

    + * * \(\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\) - *

    + * * That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip * the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - * anchor.y - 1)`. - *

    + * * The function uses the DFT-based algorithm in case of sufficiently large kernels (~{@code 11 x 11} or * larger) and the direct algorithm for small kernels. * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src. + * @param src input image. + * @param dst output image of the same size and the same number of channels as src. * @param ddepth desired depth of the destination image, see REF: filter_depths "combinations" * @param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point - * matrix; if you want to apply different kernels to different channels, split the image into - * separate color planes using split and process them individually. + * matrix; if you want to apply different kernels to different channels, split the image into + * separate color planes using split and process them individually. * @param anchor anchor of the kernel that indicates the relative position of a filtered point within - * the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor - * is at the kernel center. - * @param delta optional value added to the filtered pixels before storing them in dst. - * SEE: sepFilter2D, dft, matchTemplate + * the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor + * is at the kernel center. + * @param delta optional value added to the filtered pixels before storing them in dst. + * SEE: sepFilter2D, dft, matchTemplate */ public static void filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta) { filter2D_1(src.nativeObj, dst.nativeObj, ddepth, kernel.nativeObj, anchor.x, anchor.y, delta); } - - // - // C++: void cv::filter2D(Mat src, Mat& dst, int ddepth, Mat kernel, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT) - // - /** * Convolves an image with the kernel. - *

    + * * The function applies an arbitrary linear filter to an image. In-place operation is supported. When * the aperture is partially outside the image, the function interpolates outlier pixel values * according to the specified border mode. - *

    + * * The function does actually compute correlation, not the convolution: - *

    + * * \(\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\) - *

    + * * That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip * the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - * anchor.y - 1)`. - *

    + * * The function uses the DFT-based algorithm in case of sufficiently large kernels (~{@code 11 x 11} or * larger) and the direct algorithm for small kernels. * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src. + * @param src input image. + * @param dst output image of the same size and the same number of channels as src. * @param ddepth desired depth of the destination image, see REF: filter_depths "combinations" * @param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point - * matrix; if you want to apply different kernels to different channels, split the image into - * separate color planes using split and process them individually. + * matrix; if you want to apply different kernels to different channels, split the image into + * separate color planes using split and process them individually. * @param anchor anchor of the kernel that indicates the relative position of a filtered point within - * the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor - * is at the kernel center. - * SEE: sepFilter2D, dft, matchTemplate + * the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor + * is at the kernel center. + * SEE: sepFilter2D, dft, matchTemplate */ public static void filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor) { filter2D_2(src.nativeObj, dst.nativeObj, ddepth, kernel.nativeObj, anchor.x, anchor.y); @@ -1514,53 +1604,58 @@ public static void filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anch /** * Convolves an image with the kernel. - *

    + * * The function applies an arbitrary linear filter to an image. In-place operation is supported. When * the aperture is partially outside the image, the function interpolates outlier pixel values * according to the specified border mode. - *

    + * * The function does actually compute correlation, not the convolution: - *

    + * * \(\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\) - *

    + * * That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip * the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - * anchor.y - 1)`. - *

    + * * The function uses the DFT-based algorithm in case of sufficiently large kernels (~{@code 11 x 11} or * larger) and the direct algorithm for small kernels. * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src. + * @param src input image. + * @param dst output image of the same size and the same number of channels as src. * @param ddepth desired depth of the destination image, see REF: filter_depths "combinations" * @param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point - * matrix; if you want to apply different kernels to different channels, split the image into - * separate color planes using split and process them individually. - * the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor - * is at the kernel center. - * SEE: sepFilter2D, dft, matchTemplate + * matrix; if you want to apply different kernels to different channels, split the image into + * separate color planes using split and process them individually. + * the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor + * is at the kernel center. + * SEE: sepFilter2D, dft, matchTemplate */ public static void filter2D(Mat src, Mat dst, int ddepth, Mat kernel) { filter2D_3(src.nativeObj, dst.nativeObj, ddepth, kernel.nativeObj); } + + // + // C++: void cv::sepFilter2D(Mat src, Mat& dst, int ddepth, Mat kernelX, Mat kernelY, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT) + // + /** * Applies a separable linear filter to an image. - *

    + * * The function applies a separable linear filter to the image. That is, first, every row of src is * filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D * kernel kernelY. The final result shifted by delta is stored in dst . * - * @param src Source image. - * @param dst Destination image of the same size and the same number of channels as src . - * @param ddepth Destination image depth, see REF: filter_depths "combinations" - * @param kernelX Coefficients for filtering each row. - * @param kernelY Coefficients for filtering each column. - * @param anchor Anchor position within the kernel. The default value \((-1,-1)\) means that the anchor - * is at the kernel center. - * @param delta Value added to the filtered results before storing them. + * @param src Source image. + * @param dst Destination image of the same size and the same number of channels as src . + * @param ddepth Destination image depth, see REF: filter_depths "combinations" + * @param kernelX Coefficients for filtering each row. + * @param kernelY Coefficients for filtering each column. + * @param anchor Anchor position within the kernel. The default value \((-1,-1)\) means that the anchor + * is at the kernel center. + * @param delta Value added to the filtered results before storing them. * @param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. - * SEE: filter2D, Sobel, GaussianBlur, boxFilter, blur + * SEE: filter2D, Sobel, GaussianBlur, boxFilter, blur */ public static void sepFilter2D(Mat src, Mat dst, int ddepth, Mat kernelX, Mat kernelY, Point anchor, double delta, int borderType) { sepFilter2D_0(src.nativeObj, dst.nativeObj, ddepth, kernelX.nativeObj, kernelY.nativeObj, anchor.x, anchor.y, delta, borderType); @@ -1568,45 +1663,40 @@ public static void sepFilter2D(Mat src, Mat dst, int ddepth, Mat kernelX, Mat ke /** * Applies a separable linear filter to an image. - *

    + * * The function applies a separable linear filter to the image. That is, first, every row of src is * filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D * kernel kernelY. The final result shifted by delta is stored in dst . * - * @param src Source image. - * @param dst Destination image of the same size and the same number of channels as src . - * @param ddepth Destination image depth, see REF: filter_depths "combinations" + * @param src Source image. + * @param dst Destination image of the same size and the same number of channels as src . + * @param ddepth Destination image depth, see REF: filter_depths "combinations" * @param kernelX Coefficients for filtering each row. * @param kernelY Coefficients for filtering each column. - * @param anchor Anchor position within the kernel. The default value \((-1,-1)\) means that the anchor - * is at the kernel center. - * @param delta Value added to the filtered results before storing them. - * SEE: filter2D, Sobel, GaussianBlur, boxFilter, blur + * @param anchor Anchor position within the kernel. The default value \((-1,-1)\) means that the anchor + * is at the kernel center. + * @param delta Value added to the filtered results before storing them. + * SEE: filter2D, Sobel, GaussianBlur, boxFilter, blur */ public static void sepFilter2D(Mat src, Mat dst, int ddepth, Mat kernelX, Mat kernelY, Point anchor, double delta) { sepFilter2D_1(src.nativeObj, dst.nativeObj, ddepth, kernelX.nativeObj, kernelY.nativeObj, anchor.x, anchor.y, delta); } - - // - // C++: void cv::sepFilter2D(Mat src, Mat& dst, int ddepth, Mat kernelX, Mat kernelY, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT) - // - /** * Applies a separable linear filter to an image. - *

    + * * The function applies a separable linear filter to the image. That is, first, every row of src is * filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D * kernel kernelY. The final result shifted by delta is stored in dst . * - * @param src Source image. - * @param dst Destination image of the same size and the same number of channels as src . - * @param ddepth Destination image depth, see REF: filter_depths "combinations" + * @param src Source image. + * @param dst Destination image of the same size and the same number of channels as src . + * @param ddepth Destination image depth, see REF: filter_depths "combinations" * @param kernelX Coefficients for filtering each row. * @param kernelY Coefficients for filtering each column. - * @param anchor Anchor position within the kernel. The default value \((-1,-1)\) means that the anchor - * is at the kernel center. - * SEE: filter2D, Sobel, GaussianBlur, boxFilter, blur + * @param anchor Anchor position within the kernel. The default value \((-1,-1)\) means that the anchor + * is at the kernel center. + * SEE: filter2D, Sobel, GaussianBlur, boxFilter, blur */ public static void sepFilter2D(Mat src, Mat dst, int ddepth, Mat kernelX, Mat kernelY, Point anchor) { sepFilter2D_2(src.nativeObj, dst.nativeObj, ddepth, kernelX.nativeObj, kernelY.nativeObj, anchor.x, anchor.y); @@ -1614,65 +1704,70 @@ public static void sepFilter2D(Mat src, Mat dst, int ddepth, Mat kernelX, Mat ke /** * Applies a separable linear filter to an image. - *

    + * * The function applies a separable linear filter to the image. That is, first, every row of src is * filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D * kernel kernelY. The final result shifted by delta is stored in dst . * - * @param src Source image. - * @param dst Destination image of the same size and the same number of channels as src . - * @param ddepth Destination image depth, see REF: filter_depths "combinations" + * @param src Source image. + * @param dst Destination image of the same size and the same number of channels as src . + * @param ddepth Destination image depth, see REF: filter_depths "combinations" * @param kernelX Coefficients for filtering each row. * @param kernelY Coefficients for filtering each column. - * is at the kernel center. - * SEE: filter2D, Sobel, GaussianBlur, boxFilter, blur + * is at the kernel center. + * SEE: filter2D, Sobel, GaussianBlur, boxFilter, blur */ public static void sepFilter2D(Mat src, Mat dst, int ddepth, Mat kernelX, Mat kernelY) { sepFilter2D_3(src.nativeObj, dst.nativeObj, ddepth, kernelX.nativeObj, kernelY.nativeObj); } + + // + // C++: void cv::Sobel(Mat src, Mat& dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT) + // + /** * Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - *

    + * * In all cases except one, the \(\texttt{ksize} \times \texttt{ksize}\) separable kernel is used to * calculate the derivative. When \(\texttt{ksize = 1}\), the \(3 \times 1\) or \(1 \times 3\) * kernel is used (that is, no Gaussian smoothing is done). {@code ksize = 1} can only be used for the first * or the second x- or y- derivatives. - *

    + * * There is also the special value {@code ksize = #FILTER_SCHARR (-1)} that corresponds to the \(3\times3\) Scharr * filter that may give more accurate results than the \(3\times3\) Sobel. The Scharr aperture is - *

    + * * \(\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\) - *

    + * * for the x-derivative, or transposed for the y-derivative. - *

    + * * The function calculates an image derivative by convolving the image with the appropriate kernel: - *

    + * * \(\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\) - *

    + * * The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less * resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) * or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first * case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\) - *

    + * * The second case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\) * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src . - * @param ddepth output image depth, see REF: filter_depths "combinations"; in the case of - * 8-bit input images it will result in truncated derivatives. - * @param dx order of the derivative x. - * @param dy order of the derivative y. - * @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. - * @param scale optional scale factor for the computed derivative values; by default, no scaling is - * applied (see #getDerivKernels for details). - * @param delta optional delta value that is added to the results prior to storing them in dst. + * @param src input image. + * @param dst output image of the same size and the same number of channels as src . + * @param ddepth output image depth, see REF: filter_depths "combinations"; in the case of + * 8-bit input images it will result in truncated derivatives. + * @param dx order of the derivative x. + * @param dy order of the derivative y. + * @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. + * @param scale optional scale factor for the computed derivative values; by default, no scaling is + * applied (see #getDerivKernels for details). + * @param delta optional delta value that is added to the results prior to storing them in dst. * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. - * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar + * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar */ public static void Sobel(Mat src, Mat dst, int ddepth, int dx, int dy, int ksize, double scale, double delta, int borderType) { Sobel_0(src.nativeObj, dst.nativeObj, ddepth, dx, dy, ksize, scale, delta, borderType); @@ -1680,95 +1775,90 @@ public static void Sobel(Mat src, Mat dst, int ddepth, int dx, int dy, int ksize /** * Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - *

    + * * In all cases except one, the \(\texttt{ksize} \times \texttt{ksize}\) separable kernel is used to * calculate the derivative. When \(\texttt{ksize = 1}\), the \(3 \times 1\) or \(1 \times 3\) * kernel is used (that is, no Gaussian smoothing is done). {@code ksize = 1} can only be used for the first * or the second x- or y- derivatives. - *

    + * * There is also the special value {@code ksize = #FILTER_SCHARR (-1)} that corresponds to the \(3\times3\) Scharr * filter that may give more accurate results than the \(3\times3\) Sobel. The Scharr aperture is - *

    + * * \(\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\) - *

    + * * for the x-derivative, or transposed for the y-derivative. - *

    + * * The function calculates an image derivative by convolving the image with the appropriate kernel: - *

    + * * \(\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\) - *

    + * * The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less * resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) * or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first * case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\) - *

    + * * The second case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\) * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src . + * @param src input image. + * @param dst output image of the same size and the same number of channels as src . * @param ddepth output image depth, see REF: filter_depths "combinations"; in the case of - * 8-bit input images it will result in truncated derivatives. - * @param dx order of the derivative x. - * @param dy order of the derivative y. - * @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. - * @param scale optional scale factor for the computed derivative values; by default, no scaling is - * applied (see #getDerivKernels for details). - * @param delta optional delta value that is added to the results prior to storing them in dst. - * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar + * 8-bit input images it will result in truncated derivatives. + * @param dx order of the derivative x. + * @param dy order of the derivative y. + * @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. + * @param scale optional scale factor for the computed derivative values; by default, no scaling is + * applied (see #getDerivKernels for details). + * @param delta optional delta value that is added to the results prior to storing them in dst. + * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar */ public static void Sobel(Mat src, Mat dst, int ddepth, int dx, int dy, int ksize, double scale, double delta) { Sobel_1(src.nativeObj, dst.nativeObj, ddepth, dx, dy, ksize, scale, delta); } - - // - // C++: void cv::Sobel(Mat src, Mat& dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT) - // - /** * Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - *

    + * * In all cases except one, the \(\texttt{ksize} \times \texttt{ksize}\) separable kernel is used to * calculate the derivative. When \(\texttt{ksize = 1}\), the \(3 \times 1\) or \(1 \times 3\) * kernel is used (that is, no Gaussian smoothing is done). {@code ksize = 1} can only be used for the first * or the second x- or y- derivatives. - *

    + * * There is also the special value {@code ksize = #FILTER_SCHARR (-1)} that corresponds to the \(3\times3\) Scharr * filter that may give more accurate results than the \(3\times3\) Sobel. The Scharr aperture is - *

    + * * \(\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\) - *

    + * * for the x-derivative, or transposed for the y-derivative. - *

    + * * The function calculates an image derivative by convolving the image with the appropriate kernel: - *

    + * * \(\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\) - *

    + * * The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less * resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) * or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first * case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\) - *

    + * * The second case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\) * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src . + * @param src input image. + * @param dst output image of the same size and the same number of channels as src . * @param ddepth output image depth, see REF: filter_depths "combinations"; in the case of - * 8-bit input images it will result in truncated derivatives. - * @param dx order of the derivative x. - * @param dy order of the derivative y. - * @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. - * @param scale optional scale factor for the computed derivative values; by default, no scaling is - * applied (see #getDerivKernels for details). - * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar + * 8-bit input images it will result in truncated derivatives. + * @param dx order of the derivative x. + * @param dy order of the derivative y. + * @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. + * @param scale optional scale factor for the computed derivative values; by default, no scaling is + * applied (see #getDerivKernels for details). + * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar */ public static void Sobel(Mat src, Mat dst, int ddepth, int dx, int dy, int ksize, double scale) { Sobel_2(src.nativeObj, dst.nativeObj, ddepth, dx, dy, ksize, scale); @@ -1776,43 +1866,43 @@ public static void Sobel(Mat src, Mat dst, int ddepth, int dx, int dy, int ksize /** * Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - *

    + * * In all cases except one, the \(\texttt{ksize} \times \texttt{ksize}\) separable kernel is used to * calculate the derivative. When \(\texttt{ksize = 1}\), the \(3 \times 1\) or \(1 \times 3\) * kernel is used (that is, no Gaussian smoothing is done). {@code ksize = 1} can only be used for the first * or the second x- or y- derivatives. - *

    + * * There is also the special value {@code ksize = #FILTER_SCHARR (-1)} that corresponds to the \(3\times3\) Scharr * filter that may give more accurate results than the \(3\times3\) Sobel. The Scharr aperture is - *

    + * * \(\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\) - *

    + * * for the x-derivative, or transposed for the y-derivative. - *

    + * * The function calculates an image derivative by convolving the image with the appropriate kernel: - *

    + * * \(\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\) - *

    + * * The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less * resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) * or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first * case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\) - *

    + * * The second case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\) * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src . + * @param src input image. + * @param dst output image of the same size and the same number of channels as src . * @param ddepth output image depth, see REF: filter_depths "combinations"; in the case of - * 8-bit input images it will result in truncated derivatives. - * @param dx order of the derivative x. - * @param dy order of the derivative y. - * @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. - * applied (see #getDerivKernels for details). - * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar + * 8-bit input images it will result in truncated derivatives. + * @param dx order of the derivative x. + * @param dy order of the derivative y. + * @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. + * applied (see #getDerivKernels for details). + * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar */ public static void Sobel(Mat src, Mat dst, int ddepth, int dx, int dy, int ksize) { Sobel_3(src.nativeObj, dst.nativeObj, ddepth, dx, dy, ksize); @@ -1820,50 +1910,55 @@ public static void Sobel(Mat src, Mat dst, int ddepth, int dx, int dy, int ksize /** * Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - *

    + * * In all cases except one, the \(\texttt{ksize} \times \texttt{ksize}\) separable kernel is used to * calculate the derivative. When \(\texttt{ksize = 1}\), the \(3 \times 1\) or \(1 \times 3\) * kernel is used (that is, no Gaussian smoothing is done). {@code ksize = 1} can only be used for the first * or the second x- or y- derivatives. - *

    + * * There is also the special value {@code ksize = #FILTER_SCHARR (-1)} that corresponds to the \(3\times3\) Scharr * filter that may give more accurate results than the \(3\times3\) Sobel. The Scharr aperture is - *

    + * * \(\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\) - *

    + * * for the x-derivative, or transposed for the y-derivative. - *

    + * * The function calculates an image derivative by convolving the image with the appropriate kernel: - *

    + * * \(\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\) - *

    + * * The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less * resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) * or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first * case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\) - *

    + * * The second case corresponds to a kernel of: - *

    + * * \(\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\) * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src . + * @param src input image. + * @param dst output image of the same size and the same number of channels as src . * @param ddepth output image depth, see REF: filter_depths "combinations"; in the case of - * 8-bit input images it will result in truncated derivatives. - * @param dx order of the derivative x. - * @param dy order of the derivative y. - * applied (see #getDerivKernels for details). - * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar + * 8-bit input images it will result in truncated derivatives. + * @param dx order of the derivative x. + * @param dy order of the derivative y. + * applied (see #getDerivKernels for details). + * SEE: Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar */ public static void Sobel(Mat src, Mat dst, int ddepth, int dx, int dy) { Sobel_4(src.nativeObj, dst.nativeObj, ddepth, dx, dy); } + + // + // C++: void cv::spatialGradient(Mat src, Mat& dx, Mat& dy, int ksize = 3, int borderType = BORDER_DEFAULT) + // + /** * Calculates the first order image derivative in both x and y using a Sobel operator - *

    + * * Equivalent to calling: * * @@ -1871,14 +1966,14 @@ public static void Sobel(Mat src, Mat dst, int ddepth, int dx, int dy) { * Sobel( src, dy, CV_16SC1, 0, 1, 3 ); * * - * @param src input image. - * @param dx output image with first-order derivative in x. - * @param dy output image with first-order derivative in y. - * @param ksize size of Sobel kernel. It must be 3. + * @param src input image. + * @param dx output image with first-order derivative in x. + * @param dy output image with first-order derivative in y. + * @param ksize size of Sobel kernel. It must be 3. * @param borderType pixel extrapolation method, see #BorderTypes. * Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported. - *

    - * SEE: Sobel + * + * SEE: Sobel */ public static void spatialGradient(Mat src, Mat dx, Mat dy, int ksize, int borderType) { spatialGradient_0(src.nativeObj, dx.nativeObj, dy.nativeObj, ksize, borderType); @@ -1886,7 +1981,7 @@ public static void spatialGradient(Mat src, Mat dx, Mat dy, int ksize, int borde /** * Calculates the first order image derivative in both x and y using a Sobel operator - *

    + * * Equivalent to calling: * * @@ -1894,26 +1989,21 @@ public static void spatialGradient(Mat src, Mat dx, Mat dy, int ksize, int borde * Sobel( src, dy, CV_16SC1, 0, 1, 3 ); * * - * @param src input image. - * @param dx output image with first-order derivative in x. - * @param dy output image with first-order derivative in y. + * @param src input image. + * @param dx output image with first-order derivative in x. + * @param dy output image with first-order derivative in y. * @param ksize size of Sobel kernel. It must be 3. - * Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported. - *

    - * SEE: Sobel + * Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported. + * + * SEE: Sobel */ public static void spatialGradient(Mat src, Mat dx, Mat dy, int ksize) { spatialGradient_1(src.nativeObj, dx.nativeObj, dy.nativeObj, ksize); } - - // - // C++: void cv::spatialGradient(Mat src, Mat& dx, Mat& dy, int ksize = 3, int borderType = BORDER_DEFAULT) - // - /** * Calculates the first order image derivative in both x and y using a Sobel operator - *

    + * * Equivalent to calling: * * @@ -1922,38 +2012,43 @@ public static void spatialGradient(Mat src, Mat dx, Mat dy, int ksize) { * * * @param src input image. - * @param dx output image with first-order derivative in x. - * @param dy output image with first-order derivative in y. - * Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported. - *

    - * SEE: Sobel + * @param dx output image with first-order derivative in x. + * @param dy output image with first-order derivative in y. + * Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported. + * + * SEE: Sobel */ public static void spatialGradient(Mat src, Mat dx, Mat dy) { spatialGradient_2(src.nativeObj, dx.nativeObj, dy.nativeObj); } + + // + // C++: void cv::Scharr(Mat src, Mat& dst, int ddepth, int dx, int dy, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT) + // + /** * Calculates the first x- or y- image derivative using Scharr operator. - *

    + * * The function computes the first x- or y- spatial image derivative using the Scharr operator. The * call - *

    + * * \(\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\) - *

    + * * is equivalent to - *

    + * * \(\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\) * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src. - * @param ddepth output image depth, see REF: filter_depths "combinations" - * @param dx order of the derivative x. - * @param dy order of the derivative y. - * @param scale optional scale factor for the computed derivative values; by default, no scaling is - * applied (see #getDerivKernels for details). - * @param delta optional delta value that is added to the results prior to storing them in dst. + * @param src input image. + * @param dst output image of the same size and the same number of channels as src. + * @param ddepth output image depth, see REF: filter_depths "combinations" + * @param dx order of the derivative x. + * @param dy order of the derivative y. + * @param scale optional scale factor for the computed derivative values; by default, no scaling is + * applied (see #getDerivKernels for details). + * @param delta optional delta value that is added to the results prior to storing them in dst. * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. - * SEE: cartToPolar + * SEE: cartToPolar */ public static void Scharr(Mat src, Mat dst, int ddepth, int dx, int dy, double scale, double delta, int borderType) { Scharr_0(src.nativeObj, dst.nativeObj, ddepth, dx, dy, scale, delta, borderType); @@ -1961,55 +2056,50 @@ public static void Scharr(Mat src, Mat dst, int ddepth, int dx, int dy, double s /** * Calculates the first x- or y- image derivative using Scharr operator. - *

    + * * The function computes the first x- or y- spatial image derivative using the Scharr operator. The * call - *

    + * * \(\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\) - *

    + * * is equivalent to - *

    + * * \(\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\) * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src. + * @param src input image. + * @param dst output image of the same size and the same number of channels as src. * @param ddepth output image depth, see REF: filter_depths "combinations" - * @param dx order of the derivative x. - * @param dy order of the derivative y. - * @param scale optional scale factor for the computed derivative values; by default, no scaling is - * applied (see #getDerivKernels for details). - * @param delta optional delta value that is added to the results prior to storing them in dst. - * SEE: cartToPolar + * @param dx order of the derivative x. + * @param dy order of the derivative y. + * @param scale optional scale factor for the computed derivative values; by default, no scaling is + * applied (see #getDerivKernels for details). + * @param delta optional delta value that is added to the results prior to storing them in dst. + * SEE: cartToPolar */ public static void Scharr(Mat src, Mat dst, int ddepth, int dx, int dy, double scale, double delta) { Scharr_1(src.nativeObj, dst.nativeObj, ddepth, dx, dy, scale, delta); } - - // - // C++: void cv::Scharr(Mat src, Mat& dst, int ddepth, int dx, int dy, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT) - // - /** * Calculates the first x- or y- image derivative using Scharr operator. - *

    + * * The function computes the first x- or y- spatial image derivative using the Scharr operator. The * call - *

    + * * \(\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\) - *

    + * * is equivalent to - *

    + * * \(\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\) * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src. + * @param src input image. + * @param dst output image of the same size and the same number of channels as src. * @param ddepth output image depth, see REF: filter_depths "combinations" - * @param dx order of the derivative x. - * @param dy order of the derivative y. - * @param scale optional scale factor for the computed derivative values; by default, no scaling is - * applied (see #getDerivKernels for details). - * SEE: cartToPolar + * @param dx order of the derivative x. + * @param dy order of the derivative y. + * @param scale optional scale factor for the computed derivative values; by default, no scaling is + * applied (see #getDerivKernels for details). + * SEE: cartToPolar */ public static void Scharr(Mat src, Mat dst, int ddepth, int dx, int dy, double scale) { Scharr_2(src.nativeObj, dst.nativeObj, ddepth, dx, dy, scale); @@ -2017,51 +2107,56 @@ public static void Scharr(Mat src, Mat dst, int ddepth, int dx, int dy, double s /** * Calculates the first x- or y- image derivative using Scharr operator. - *

    + * * The function computes the first x- or y- spatial image derivative using the Scharr operator. The * call - *

    + * * \(\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\) - *

    + * * is equivalent to - *

    + * * \(\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\) * - * @param src input image. - * @param dst output image of the same size and the same number of channels as src. + * @param src input image. + * @param dst output image of the same size and the same number of channels as src. * @param ddepth output image depth, see REF: filter_depths "combinations" - * @param dx order of the derivative x. - * @param dy order of the derivative y. - * applied (see #getDerivKernels for details). - * SEE: cartToPolar + * @param dx order of the derivative x. + * @param dy order of the derivative y. + * applied (see #getDerivKernels for details). + * SEE: cartToPolar */ public static void Scharr(Mat src, Mat dst, int ddepth, int dx, int dy) { Scharr_3(src.nativeObj, dst.nativeObj, ddepth, dx, dy); } + + // + // C++: void cv::Laplacian(Mat src, Mat& dst, int ddepth, int ksize = 1, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT) + // + /** * Calculates the Laplacian of an image. - *

    + * * The function calculates the Laplacian of the source image by adding up the second x and y * derivatives calculated using the Sobel operator: - *

    + * * \(\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\) - *

    + * * This is done when {@code ksize > 1}. When {@code ksize == 1}, the Laplacian is computed by filtering the image * with the following \(3 \times 3\) aperture: - *

    + * * \(\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\) * - * @param src Source image. - * @param dst Destination image of the same size and the same number of channels as src . - * @param ddepth Desired depth of the destination image, see REF: filter_depths "combinations". - * @param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for - * details. The size must be positive and odd. - * @param scale Optional scale factor for the computed Laplacian values. By default, no scaling is - * applied. See #getDerivKernels for details. - * @param delta Optional delta value that is added to the results prior to storing them in dst . + * @param src Source image. + * @param dst Destination image of the same size and the same number of channels as src . + * @param ddepth Desired depth of the destination image, see REF: filter_depths "combinations". + * @param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for + * details. The size must be positive and odd. + * @param scale Optional scale factor for the computed Laplacian values. By default, no scaling is + * applied. See #getDerivKernels for details. + * @param delta Optional delta value that is added to the results prior to storing them in dst . * @param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. - * SEE: Sobel, Scharr + * SEE: Sobel, Scharr */ public static void Laplacian(Mat src, Mat dst, int ddepth, int ksize, double scale, double delta, int borderType) { Laplacian_0(src.nativeObj, dst.nativeObj, ddepth, ksize, scale, delta, borderType); @@ -2069,57 +2164,52 @@ public static void Laplacian(Mat src, Mat dst, int ddepth, int ksize, double sca /** * Calculates the Laplacian of an image. - *

    + * * The function calculates the Laplacian of the source image by adding up the second x and y * derivatives calculated using the Sobel operator: - *

    + * * \(\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\) - *

    + * * This is done when {@code ksize > 1}. When {@code ksize == 1}, the Laplacian is computed by filtering the image * with the following \(3 \times 3\) aperture: - *

    + * * \(\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\) * - * @param src Source image. - * @param dst Destination image of the same size and the same number of channels as src . + * @param src Source image. + * @param dst Destination image of the same size and the same number of channels as src . * @param ddepth Desired depth of the destination image, see REF: filter_depths "combinations". - * @param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for - * details. The size must be positive and odd. - * @param scale Optional scale factor for the computed Laplacian values. By default, no scaling is - * applied. See #getDerivKernels for details. - * @param delta Optional delta value that is added to the results prior to storing them in dst . - * SEE: Sobel, Scharr + * @param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for + * details. The size must be positive and odd. + * @param scale Optional scale factor for the computed Laplacian values. By default, no scaling is + * applied. See #getDerivKernels for details. + * @param delta Optional delta value that is added to the results prior to storing them in dst . + * SEE: Sobel, Scharr */ public static void Laplacian(Mat src, Mat dst, int ddepth, int ksize, double scale, double delta) { Laplacian_1(src.nativeObj, dst.nativeObj, ddepth, ksize, scale, delta); - } - - - // - // C++: void cv::Laplacian(Mat src, Mat& dst, int ddepth, int ksize = 1, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT) - // + } /** * Calculates the Laplacian of an image. - *

    + * * The function calculates the Laplacian of the source image by adding up the second x and y * derivatives calculated using the Sobel operator: - *

    + * * \(\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\) - *

    + * * This is done when {@code ksize > 1}. When {@code ksize == 1}, the Laplacian is computed by filtering the image * with the following \(3 \times 3\) aperture: - *

    + * * \(\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\) * - * @param src Source image. - * @param dst Destination image of the same size and the same number of channels as src . + * @param src Source image. + * @param dst Destination image of the same size and the same number of channels as src . * @param ddepth Desired depth of the destination image, see REF: filter_depths "combinations". - * @param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for - * details. The size must be positive and odd. - * @param scale Optional scale factor for the computed Laplacian values. By default, no scaling is - * applied. See #getDerivKernels for details. - * SEE: Sobel, Scharr + * @param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for + * details. The size must be positive and odd. + * @param scale Optional scale factor for the computed Laplacian values. By default, no scaling is + * applied. See #getDerivKernels for details. + * SEE: Sobel, Scharr */ public static void Laplacian(Mat src, Mat dst, int ddepth, int ksize, double scale) { Laplacian_2(src.nativeObj, dst.nativeObj, ddepth, ksize, scale); @@ -2127,24 +2217,24 @@ public static void Laplacian(Mat src, Mat dst, int ddepth, int ksize, double sca /** * Calculates the Laplacian of an image. - *

    + * * The function calculates the Laplacian of the source image by adding up the second x and y * derivatives calculated using the Sobel operator: - *

    + * * \(\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\) - *

    + * * This is done when {@code ksize > 1}. When {@code ksize == 1}, the Laplacian is computed by filtering the image * with the following \(3 \times 3\) aperture: - *

    + * * \(\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\) * - * @param src Source image. - * @param dst Destination image of the same size and the same number of channels as src . + * @param src Source image. + * @param dst Destination image of the same size and the same number of channels as src . * @param ddepth Desired depth of the destination image, see REF: filter_depths "combinations". - * @param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for - * details. The size must be positive and odd. - * applied. See #getDerivKernels for details. - * SEE: Sobel, Scharr + * @param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for + * details. The size must be positive and odd. + * applied. See #getDerivKernels for details. + * SEE: Sobel, Scharr */ public static void Laplacian(Mat src, Mat dst, int ddepth, int ksize) { Laplacian_3(src.nativeObj, dst.nativeObj, ddepth, ksize); @@ -2152,45 +2242,50 @@ public static void Laplacian(Mat src, Mat dst, int ddepth, int ksize) { /** * Calculates the Laplacian of an image. - *

    + * * The function calculates the Laplacian of the source image by adding up the second x and y * derivatives calculated using the Sobel operator: - *

    + * * \(\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\) - *

    + * * This is done when {@code ksize > 1}. When {@code ksize == 1}, the Laplacian is computed by filtering the image * with the following \(3 \times 3\) aperture: - *

    + * * \(\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\) * - * @param src Source image. - * @param dst Destination image of the same size and the same number of channels as src . + * @param src Source image. + * @param dst Destination image of the same size and the same number of channels as src . * @param ddepth Desired depth of the destination image, see REF: filter_depths "combinations". - * details. The size must be positive and odd. - * applied. See #getDerivKernels for details. - * SEE: Sobel, Scharr + * details. The size must be positive and odd. + * applied. See #getDerivKernels for details. + * SEE: Sobel, Scharr */ public static void Laplacian(Mat src, Mat dst, int ddepth) { Laplacian_4(src.nativeObj, dst.nativeObj, ddepth); } + + // + // C++: void cv::Canny(Mat image, Mat& edges, double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) + // + /** * Finds edges in an image using the Canny algorithm CITE: Canny86 . - *

    + * * The function finds edges in the input image and marks them in the output map edges using the * Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The * largest value is used to find initial segments of strong edges. See * <http://en.wikipedia.org/wiki/Canny_edge_detector> * - * @param image 8-bit input image. - * @param edges output edge map; single channels 8-bit image, which has the same size as image . - * @param threshold1 first threshold for the hysteresis procedure. - * @param threshold2 second threshold for the hysteresis procedure. + * @param image 8-bit input image. + * @param edges output edge map; single channels 8-bit image, which has the same size as image . + * @param threshold1 first threshold for the hysteresis procedure. + * @param threshold2 second threshold for the hysteresis procedure. * @param apertureSize aperture size for the Sobel operator. - * @param L2gradient a flag, indicating whether a more accurate \(L_2\) norm - * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( - * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( - * L2gradient=false ). + * @param L2gradient a flag, indicating whether a more accurate \(L_2\) norm + * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( + * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( + * L2gradient=false ). */ public static void Canny(Mat image, Mat edges, double threshold1, double threshold2, int apertureSize, boolean L2gradient) { Canny_0(image.nativeObj, edges.nativeObj, threshold1, threshold2, apertureSize, L2gradient); @@ -2198,64 +2293,64 @@ public static void Canny(Mat image, Mat edges, double threshold1, double thresho /** * Finds edges in an image using the Canny algorithm CITE: Canny86 . - *

    + * * The function finds edges in the input image and marks them in the output map edges using the * Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The * largest value is used to find initial segments of strong edges. See * <http://en.wikipedia.org/wiki/Canny_edge_detector> * - * @param image 8-bit input image. - * @param edges output edge map; single channels 8-bit image, which has the same size as image . - * @param threshold1 first threshold for the hysteresis procedure. - * @param threshold2 second threshold for the hysteresis procedure. + * @param image 8-bit input image. + * @param edges output edge map; single channels 8-bit image, which has the same size as image . + * @param threshold1 first threshold for the hysteresis procedure. + * @param threshold2 second threshold for the hysteresis procedure. * @param apertureSize aperture size for the Sobel operator. - * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( - * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( - * L2gradient=false ). + * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( + * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( + * L2gradient=false ). */ public static void Canny(Mat image, Mat edges, double threshold1, double threshold2, int apertureSize) { Canny_1(image.nativeObj, edges.nativeObj, threshold1, threshold2, apertureSize); } - - // - // C++: void cv::Canny(Mat image, Mat& edges, double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) - // - /** * Finds edges in an image using the Canny algorithm CITE: Canny86 . - *

    + * * The function finds edges in the input image and marks them in the output map edges using the * Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The * largest value is used to find initial segments of strong edges. See * <http://en.wikipedia.org/wiki/Canny_edge_detector> * - * @param image 8-bit input image. - * @param edges output edge map; single channels 8-bit image, which has the same size as image . + * @param image 8-bit input image. + * @param edges output edge map; single channels 8-bit image, which has the same size as image . * @param threshold1 first threshold for the hysteresis procedure. * @param threshold2 second threshold for the hysteresis procedure. - * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( - * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( - * L2gradient=false ). + * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( + * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( + * L2gradient=false ). */ public static void Canny(Mat image, Mat edges, double threshold1, double threshold2) { Canny_2(image.nativeObj, edges.nativeObj, threshold1, threshold2); } + + // + // C++: void cv::Canny(Mat dx, Mat dy, Mat& edges, double threshold1, double threshold2, bool L2gradient = false) + // + /** * \overload - *

    + * * Finds edges in an image using the Canny algorithm with custom image gradient. * - * @param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3). - * @param dy 16-bit y derivative of input image (same type as dx). - * @param edges output edge map; single channels 8-bit image, which has the same size as image . + * @param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3). + * @param dy 16-bit y derivative of input image (same type as dx). + * @param edges output edge map; single channels 8-bit image, which has the same size as image . * @param threshold1 first threshold for the hysteresis procedure. * @param threshold2 second threshold for the hysteresis procedure. * @param L2gradient a flag, indicating whether a more accurate \(L_2\) norm - * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( - * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( - * L2gradient=false ). + * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( + * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( + * L2gradient=false ). */ public static void Canny(Mat dx, Mat dy, Mat edges, double threshold1, double threshold2, boolean L2gradient) { Canny_3(dx.nativeObj, dy.nativeObj, edges.nativeObj, threshold1, threshold2, L2gradient); @@ -2263,17 +2358,17 @@ public static void Canny(Mat dx, Mat dy, Mat edges, double threshold1, double th /** * \overload - *

    + * * Finds edges in an image using the Canny algorithm with custom image gradient. * - * @param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3). - * @param dy 16-bit y derivative of input image (same type as dx). - * @param edges output edge map; single channels 8-bit image, which has the same size as image . + * @param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3). + * @param dy 16-bit y derivative of input image (same type as dx). + * @param edges output edge map; single channels 8-bit image, which has the same size as image . * @param threshold1 first threshold for the hysteresis procedure. * @param threshold2 second threshold for the hysteresis procedure. - * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( - * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( - * L2gradient=false ). + * \(=\sqrt{(dI/dx)^2 + (dI/dy)^2}\) should be used to calculate the image gradient magnitude ( + * L2gradient=true ), or whether the default \(L_1\) norm \(=|dI/dx|+|dI/dy|\) is enough ( + * L2gradient=false ). */ public static void Canny(Mat dx, Mat dy, Mat edges, double threshold1, double threshold2) { Canny_4(dx.nativeObj, dy.nativeObj, edges.nativeObj, threshold1, threshold2); @@ -2281,21 +2376,21 @@ public static void Canny(Mat dx, Mat dy, Mat edges, double threshold1, double th // - // C++: void cv::Canny(Mat dx, Mat dy, Mat& edges, double threshold1, double threshold2, bool L2gradient = false) + // C++: void cv::cornerMinEigenVal(Mat src, Mat& dst, int blockSize, int ksize = 3, int borderType = BORDER_DEFAULT) // /** * Calculates the minimal eigenvalue of gradient matrices for corner detection. - *

    + * * The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal * eigenvalue of the covariance matrix of derivatives, that is, \(\min(\lambda_1, \lambda_2)\) in terms * of the formulae in the cornerEigenValsAndVecs description. * - * @param src Input single-channel 8-bit or floating-point image. - * @param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as - * src . - * @param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). - * @param ksize Aperture parameter for the Sobel operator. + * @param src Input single-channel 8-bit or floating-point image. + * @param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as + * src . + * @param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). + * @param ksize Aperture parameter for the Sobel operator. * @param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. */ public static void cornerMinEigenVal(Mat src, Mat dst, int blockSize, int ksize, int borderType) { @@ -2304,60 +2399,60 @@ public static void cornerMinEigenVal(Mat src, Mat dst, int blockSize, int ksize, /** * Calculates the minimal eigenvalue of gradient matrices for corner detection. - *

    + * * The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal * eigenvalue of the covariance matrix of derivatives, that is, \(\min(\lambda_1, \lambda_2)\) in terms * of the formulae in the cornerEigenValsAndVecs description. * - * @param src Input single-channel 8-bit or floating-point image. - * @param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as - * src . + * @param src Input single-channel 8-bit or floating-point image. + * @param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as + * src . * @param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). - * @param ksize Aperture parameter for the Sobel operator. + * @param ksize Aperture parameter for the Sobel operator. */ public static void cornerMinEigenVal(Mat src, Mat dst, int blockSize, int ksize) { cornerMinEigenVal_1(src.nativeObj, dst.nativeObj, blockSize, ksize); } - - // - // C++: void cv::cornerMinEigenVal(Mat src, Mat& dst, int blockSize, int ksize = 3, int borderType = BORDER_DEFAULT) - // - /** * Calculates the minimal eigenvalue of gradient matrices for corner detection. - *

    + * * The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal * eigenvalue of the covariance matrix of derivatives, that is, \(\min(\lambda_1, \lambda_2)\) in terms * of the formulae in the cornerEigenValsAndVecs description. * - * @param src Input single-channel 8-bit or floating-point image. - * @param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as - * src . + * @param src Input single-channel 8-bit or floating-point image. + * @param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as + * src . * @param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). */ public static void cornerMinEigenVal(Mat src, Mat dst, int blockSize) { cornerMinEigenVal_2(src.nativeObj, dst.nativeObj, blockSize); } + + // + // C++: void cv::cornerHarris(Mat src, Mat& dst, int blockSize, int ksize, double k, int borderType = BORDER_DEFAULT) + // + /** * Harris corner detector. - *

    + * * The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and * cornerEigenValsAndVecs , for each pixel \((x, y)\) it calculates a \(2\times2\) gradient covariance * matrix \(M^{(x,y)}\) over a \(\texttt{blockSize} \times \texttt{blockSize}\) neighborhood. Then, it * computes the following characteristic: - *

    + * * \(\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\) - *

    + * * Corners in the image can be found as the local maxima of this response map. * - * @param src Input single-channel 8-bit or floating-point image. - * @param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same - * size as src . - * @param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). - * @param ksize Aperture parameter for the Sobel operator. - * @param k Harris detector free parameter. See the formula above. + * @param src Input single-channel 8-bit or floating-point image. + * @param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same + * size as src . + * @param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). + * @param ksize Aperture parameter for the Sobel operator. + * @param k Harris detector free parameter. See the formula above. * @param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. */ public static void cornerHarris(Mat src, Mat dst, int blockSize, int ksize, double k, int borderType) { @@ -2366,22 +2461,22 @@ public static void cornerHarris(Mat src, Mat dst, int blockSize, int ksize, doub /** * Harris corner detector. - *

    + * * The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and * cornerEigenValsAndVecs , for each pixel \((x, y)\) it calculates a \(2\times2\) gradient covariance * matrix \(M^{(x,y)}\) over a \(\texttt{blockSize} \times \texttt{blockSize}\) neighborhood. Then, it * computes the following characteristic: - *

    + * * \(\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\) - *

    + * * Corners in the image can be found as the local maxima of this response map. * - * @param src Input single-channel 8-bit or floating-point image. - * @param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same - * size as src . + * @param src Input single-channel 8-bit or floating-point image. + * @param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same + * size as src . * @param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). - * @param ksize Aperture parameter for the Sobel operator. - * @param k Harris detector free parameter. See the formula above. + * @param ksize Aperture parameter for the Sobel operator. + * @param k Harris detector free parameter. See the formula above. */ public static void cornerHarris(Mat src, Mat dst, int blockSize, int ksize, double k) { cornerHarris_1(src.nativeObj, dst.nativeObj, blockSize, ksize, k); @@ -2389,19 +2484,19 @@ public static void cornerHarris(Mat src, Mat dst, int blockSize, int ksize, doub // - // C++: void cv::cornerHarris(Mat src, Mat& dst, int blockSize, int ksize, double k, int borderType = BORDER_DEFAULT) + // C++: void cv::cornerEigenValsAndVecs(Mat src, Mat& dst, int blockSize, int ksize, int borderType = BORDER_DEFAULT) // /** * Calculates eigenvalues and eigenvectors of image blocks for corner detection. - *

    + * * For every pixel \(p\) , the function cornerEigenValsAndVecs considers a blockSize \(\times\) blockSize * neighborhood \(S(p)\) . It calculates the covariation matrix of derivatives over the neighborhood as: - *

    + * * \(M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\) - *

    + * * where the derivatives are computed using the Sobel operator. - *

    + * * After that, it finds eigenvectors and eigenvalues of \(M\) and stores them in the destination image as * \((\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\) where * @@ -2416,16 +2511,16 @@ public static void cornerHarris(Mat src, Mat dst, int blockSize, int ksize, doub * \(x_2, y_2\) are the eigenvectors corresponding to \(\lambda_2\) * * - *

    + * * The output of the function can be used for robust edge or corner detection. * - * @param src Input single-channel 8-bit or floating-point image. - * @param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . - * @param blockSize Neighborhood size (see details below). - * @param ksize Aperture parameter for the Sobel operator. + * @param src Input single-channel 8-bit or floating-point image. + * @param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . + * @param blockSize Neighborhood size (see details below). + * @param ksize Aperture parameter for the Sobel operator. * @param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. - *

    - * SEE: cornerMinEigenVal, cornerHarris, preCornerDetect + * + * SEE: cornerMinEigenVal, cornerHarris, preCornerDetect */ public static void cornerEigenValsAndVecs(Mat src, Mat dst, int blockSize, int ksize, int borderType) { cornerEigenValsAndVecs_0(src.nativeObj, dst.nativeObj, blockSize, ksize, borderType); @@ -2433,14 +2528,14 @@ public static void cornerEigenValsAndVecs(Mat src, Mat dst, int blockSize, int k /** * Calculates eigenvalues and eigenvectors of image blocks for corner detection. - *

    + * * For every pixel \(p\) , the function cornerEigenValsAndVecs considers a blockSize \(\times\) blockSize * neighborhood \(S(p)\) . It calculates the covariation matrix of derivatives over the neighborhood as: - *

    + * * \(M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\) - *

    + * * where the derivatives are computed using the Sobel operator. - *

    + * * After that, it finds eigenvectors and eigenvalues of \(M\) and stores them in the destination image as * \((\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\) where * @@ -2455,15 +2550,15 @@ public static void cornerEigenValsAndVecs(Mat src, Mat dst, int blockSize, int k * \(x_2, y_2\) are the eigenvectors corresponding to \(\lambda_2\) * * - *

    + * * The output of the function can be used for robust edge or corner detection. * - * @param src Input single-channel 8-bit or floating-point image. - * @param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . + * @param src Input single-channel 8-bit or floating-point image. + * @param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . * @param blockSize Neighborhood size (see details below). - * @param ksize Aperture parameter for the Sobel operator. - *

    - * SEE: cornerMinEigenVal, cornerHarris, preCornerDetect + * @param ksize Aperture parameter for the Sobel operator. + * + * SEE: cornerMinEigenVal, cornerHarris, preCornerDetect */ public static void cornerEigenValsAndVecs(Mat src, Mat dst, int blockSize, int ksize) { cornerEigenValsAndVecs_1(src.nativeObj, dst.nativeObj, blockSize, ksize); @@ -2471,31 +2566,31 @@ public static void cornerEigenValsAndVecs(Mat src, Mat dst, int blockSize, int k // - // C++: void cv::cornerEigenValsAndVecs(Mat src, Mat& dst, int blockSize, int ksize, int borderType = BORDER_DEFAULT) + // C++: void cv::preCornerDetect(Mat src, Mat& dst, int ksize, int borderType = BORDER_DEFAULT) // /** * Calculates a feature map for corner detection. - *

    + * * The function calculates the complex spatial derivative-based function of the source image - *

    + * * \(\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}\) - *

    + * * where \(D_x\),\(D_y\) are the first image derivatives, \(D_{xx}\),\(D_{yy}\) are the second image * derivatives, and \(D_{xy}\) is the mixed derivative. - *

    + * * The corners can be found as local maximums of the functions, as shown below: * - * Mat corners, dilated_corners; - * preCornerDetect(image, corners, 3); - * // dilation with 3x3 rectangular structuring element - * dilate(corners, dilated_corners, Mat(), 1); - * Mat corner_mask = corners == dilated_corners; + * Mat corners, dilated_corners; + * preCornerDetect(image, corners, 3); + * // dilation with 3x3 rectangular structuring element + * dilate(corners, dilated_corners, Mat(), 1); + * Mat corner_mask = corners == dilated_corners; * * - * @param src Source single-channel 8-bit of floating-point image. - * @param dst Output image that has the type CV_32F and the same size as src . - * @param ksize %Aperture size of the Sobel . + * @param src Source single-channel 8-bit of floating-point image. + * @param dst Output image that has the type CV_32F and the same size as src . + * @param ksize %Aperture size of the Sobel . * @param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. */ public static void preCornerDetect(Mat src, Mat dst, int ksize, int borderType) { @@ -2504,25 +2599,25 @@ public static void preCornerDetect(Mat src, Mat dst, int ksize, int borderType) /** * Calculates a feature map for corner detection. - *

    + * * The function calculates the complex spatial derivative-based function of the source image - *

    + * * \(\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}\) - *

    + * * where \(D_x\),\(D_y\) are the first image derivatives, \(D_{xx}\),\(D_{yy}\) are the second image * derivatives, and \(D_{xy}\) is the mixed derivative. - *

    + * * The corners can be found as local maximums of the functions, as shown below: * - * Mat corners, dilated_corners; - * preCornerDetect(image, corners, 3); - * // dilation with 3x3 rectangular structuring element - * dilate(corners, dilated_corners, Mat(), 1); - * Mat corner_mask = corners == dilated_corners; + * Mat corners, dilated_corners; + * preCornerDetect(image, corners, 3); + * // dilation with 3x3 rectangular structuring element + * dilate(corners, dilated_corners, Mat(), 1); + * Mat corner_mask = corners == dilated_corners; * * - * @param src Source single-channel 8-bit of floating-point image. - * @param dst Output image that has the type CV_32F and the same size as src . + * @param src Source single-channel 8-bit of floating-point image. + * @param dst Output image that has the type CV_32F and the same size as src . * @param ksize %Aperture size of the Sobel . */ public static void preCornerDetect(Mat src, Mat dst, int ksize) { @@ -2531,57 +2626,62 @@ public static void preCornerDetect(Mat src, Mat dst, int ksize) { // - // C++: void cv::preCornerDetect(Mat src, Mat& dst, int ksize, int borderType = BORDER_DEFAULT) + // C++: void cv::cornerSubPix(Mat image, Mat& corners, Size winSize, Size zeroZone, TermCriteria criteria) // /** * Refines the corner locations. - *

    + * * The function iterates to find the sub-pixel accurate location of corners or radial saddle * points as described in CITE: forstner1987fast, and as shown on the figure below. - *

    + * * ![image](pics/cornersubpix.png) - *

    + * * Sub-pixel accurate corner locator is based on the observation that every vector from the center \(q\) * to a point \(p\) located within a neighborhood of \(q\) is orthogonal to the image gradient at \(p\) * subject to image and measurement noise. Consider the expression: - *

    + * * \(\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)\) - *

    + * * where \({DI_{p_i}}\) is an image gradient at one of the points \(p_i\) in a neighborhood of \(q\) . The * value of \(q\) is to be found so that \(\epsilon_i\) is minimized. A system of equations may be set up * with \(\epsilon_i\) set to zero: - *

    + * * \(\sum _i(DI_{p_i} \cdot {DI_{p_i}}^T) \cdot q - \sum _i(DI_{p_i} \cdot {DI_{p_i}}^T \cdot p_i)\) - *

    + * * where the gradients are summed within a neighborhood ("search window") of \(q\) . Calling the first * gradient term \(G\) and the second gradient term \(b\) gives: - *

    + * * \(q = G^{-1} \cdot b\) - *

    + * * The algorithm sets the center of the neighborhood window at this new center \(q\) and then iterates * until the center stays within a set threshold. * - * @param image Input single-channel, 8-bit or float image. - * @param corners Initial coordinates of the input corners and refined coordinates provided for - * output. - * @param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) , - * then a \((5*2+1) \times (5*2+1) = 11 \times 11\) search window is used. + * @param image Input single-channel, 8-bit or float image. + * @param corners Initial coordinates of the input corners and refined coordinates provided for + * output. + * @param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) , + * then a \((5*2+1) \times (5*2+1) = 11 \times 11\) search window is used. * @param zeroZone Half of the size of the dead region in the middle of the search zone over which - * the summation in the formula below is not done. It is used sometimes to avoid possible - * singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such - * a size. + * the summation in the formula below is not done. It is used sometimes to avoid possible + * singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such + * a size. * @param criteria Criteria for termination of the iterative process of corner refinement. That is, - * the process of corner position refinement stops either after criteria.maxCount iterations or when - * the corner position moves by less than criteria.epsilon on some iteration. + * the process of corner position refinement stops either after criteria.maxCount iterations or when + * the corner position moves by less than criteria.epsilon on some iteration. */ public static void cornerSubPix(Mat image, Mat corners, Size winSize, Size zeroZone, TermCriteria criteria) { cornerSubPix_0(image.nativeObj, corners.nativeObj, winSize.width, winSize.height, zeroZone.width, zeroZone.height, criteria.type, criteria.maxCount, criteria.epsilon); } + + // + // C++: void cv::goodFeaturesToTrack(Mat image, vector_Point& corners, int maxCorners, double qualityLevel, double minDistance, Mat mask = Mat(), int blockSize = 3, bool useHarrisDetector = false, double k = 0.04) + // + /** * Determines strong corners on an image. - *

    + * * The function finds the most prominent corners in the image or in the specified image region, as * described in CITE: Shi94 * @@ -2606,48 +2706,43 @@ public static void cornerSubPix(Mat image, Mat corners, Size winSize, Size zeroZ * maxDistance. * * - *

    + * * The function can be used to initialize a point-based tracker of an object. * * Note: If the function is called with different values A and B of the parameter qualityLevel , and * A > B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector * with qualityLevel=B . * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. - * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * @param mask Optional region of interest. If the image is not empty (it needs to have the type - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. - * @param blockSize Size of an average block for computing a derivative covariation matrix over each - * pixel neighborhood. See cornerEigenValsAndVecs . + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. + * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * @param mask Optional region of interest. If the image is not empty (it needs to have the type + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * @param blockSize Size of an average block for computing a derivative covariation matrix over each + * pixel neighborhood. See cornerEigenValsAndVecs . * @param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) - * or #cornerMinEigenVal. - * @param k Free parameter of the Harris detector. - *

    - * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, + * or #cornerMinEigenVal. + * @param k Free parameter of the Harris detector. + * + * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, */ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, int blockSize, boolean useHarrisDetector, double k) { Mat corners_mat = corners; goodFeaturesToTrack_0(image.nativeObj, corners_mat.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, blockSize, useHarrisDetector, k); } - - // - // C++: void cv::cornerSubPix(Mat image, Mat& corners, Size winSize, Size zeroZone, TermCriteria criteria) - // - /** * Determines strong corners on an image. - *

    + * * The function finds the most prominent corners in the image or in the specified image region, as * described in CITE: Shi94 * @@ -2672,47 +2767,42 @@ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCor * maxDistance. * * - *

    + * * The function can be used to initialize a point-based tracker of an object. * * Note: If the function is called with different values A and B of the parameter qualityLevel , and * A > B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector * with qualityLevel=B . * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. - * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * @param mask Optional region of interest. If the image is not empty (it needs to have the type - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. - * @param blockSize Size of an average block for computing a derivative covariation matrix over each - * pixel neighborhood. See cornerEigenValsAndVecs . + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. + * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * @param mask Optional region of interest. If the image is not empty (it needs to have the type + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * @param blockSize Size of an average block for computing a derivative covariation matrix over each + * pixel neighborhood. See cornerEigenValsAndVecs . * @param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) - * or #cornerMinEigenVal. - *

    - * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, + * or #cornerMinEigenVal. + * + * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, */ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, int blockSize, boolean useHarrisDetector) { Mat corners_mat = corners; goodFeaturesToTrack_1(image.nativeObj, corners_mat.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, blockSize, useHarrisDetector); } - - // - // C++: void cv::goodFeaturesToTrack(Mat image, vector_Point& corners, int maxCorners, double qualityLevel, double minDistance, Mat mask = Mat(), int blockSize = 3, bool useHarrisDetector = false, double k = 0.04) - // - /** * Determines strong corners on an image. - *

    + * * The function finds the most prominent corners in the image or in the specified image region, as * described in CITE: Shi94 * @@ -2737,32 +2827,32 @@ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCor * maxDistance. * * - *

    + * * The function can be used to initialize a point-based tracker of an object. * * Note: If the function is called with different values A and B of the parameter qualityLevel , and * A > B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector * with qualityLevel=B . * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * @param mask Optional region of interest. If the image is not empty (it needs to have the type - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. - * @param blockSize Size of an average block for computing a derivative covariation matrix over each - * pixel neighborhood. See cornerEigenValsAndVecs . - * or #cornerMinEigenVal. - *

    - * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * @param mask Optional region of interest. If the image is not empty (it needs to have the type + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * @param blockSize Size of an average block for computing a derivative covariation matrix over each + * pixel neighborhood. See cornerEigenValsAndVecs . + * or #cornerMinEigenVal. + * + * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, */ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, int blockSize) { Mat corners_mat = corners; @@ -2771,7 +2861,7 @@ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCor /** * Determines strong corners on an image. - *

    + * * The function finds the most prominent corners in the image or in the specified image region, as * described in CITE: Shi94 * @@ -2796,31 +2886,31 @@ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCor * maxDistance. * * - *

    + * * The function can be used to initialize a point-based tracker of an object. * * Note: If the function is called with different values A and B of the parameter qualityLevel , and * A > B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector * with qualityLevel=B . * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * @param mask Optional region of interest. If the image is not empty (it needs to have the type - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. - * pixel neighborhood. See cornerEigenValsAndVecs . - * or #cornerMinEigenVal. - *

    - * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * @param mask Optional region of interest. If the image is not empty (it needs to have the type + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * pixel neighborhood. See cornerEigenValsAndVecs . + * or #cornerMinEigenVal. + * + * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, */ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCorners, double qualityLevel, double minDistance, Mat mask) { Mat corners_mat = corners; @@ -2829,7 +2919,7 @@ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCor /** * Determines strong corners on an image. - *

    + * * The function finds the most prominent corners in the image or in the specified image region, as * described in CITE: Shi94 * @@ -2854,36 +2944,41 @@ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCor * maxDistance. * * - *

    + * * The function can be used to initialize a point-based tracker of an object. * * Note: If the function is called with different values A and B of the parameter qualityLevel , and * A > B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector * with qualityLevel=B . * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. - * pixel neighborhood. See cornerEigenValsAndVecs . - * or #cornerMinEigenVal. - *

    - * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * pixel neighborhood. See cornerEigenValsAndVecs . + * or #cornerMinEigenVal. + * + * SEE: cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, */ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCorners, double qualityLevel, double minDistance) { Mat corners_mat = corners; goodFeaturesToTrack_4(image.nativeObj, corners_mat.nativeObj, maxCorners, qualityLevel, minDistance); } + + // + // C++: void cv::goodFeaturesToTrack(Mat image, vector_Point& corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, int blockSize, int gradientSize, bool useHarrisDetector = false, double k = 0.04) + // + public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, int blockSize, int gradientSize, boolean useHarrisDetector, double k) { Mat corners_mat = corners; goodFeaturesToTrack_5(image.nativeObj, corners_mat.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, blockSize, gradientSize, useHarrisDetector, k); @@ -2894,41 +2989,41 @@ public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCor goodFeaturesToTrack_6(image.nativeObj, corners_mat.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, blockSize, gradientSize, useHarrisDetector); } - - // - // C++: void cv::goodFeaturesToTrack(Mat image, vector_Point& corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, int blockSize, int gradientSize, bool useHarrisDetector = false, double k = 0.04) - // - public static void goodFeaturesToTrack(Mat image, MatOfPoint corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, int blockSize, int gradientSize) { Mat corners_mat = corners; goodFeaturesToTrack_7(image.nativeObj, corners_mat.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, blockSize, gradientSize); } + + // + // C++: void cv::goodFeaturesToTrack(Mat image, Mat& corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, Mat& cornersQuality, int blockSize = 3, int gradientSize = 3, bool useHarrisDetector = false, double k = 0.04) + // + /** * Same as above, but returns also quality measure of the detected corners. * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. - * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * @param mask Region of interest. If the image is not empty (it needs to have the type - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. - * @param cornersQuality Output vector of quality measure of the detected corners. - * @param blockSize Size of an average block for computing a derivative covariation matrix over each - * pixel neighborhood. See cornerEigenValsAndVecs . - * @param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. - * See cornerEigenValsAndVecs . + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. + * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * @param mask Region of interest. If the image is not empty (it needs to have the type + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * @param cornersQuality Output vector of quality measure of the detected corners. + * @param blockSize Size of an average block for computing a derivative covariation matrix over each + * pixel neighborhood. See cornerEigenValsAndVecs . + * @param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. + * See cornerEigenValsAndVecs . * @param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) - * or #cornerMinEigenVal. - * @param k Free parameter of the Harris detector. + * or #cornerMinEigenVal. + * @param k Free parameter of the Harris detector. */ public static void goodFeaturesToTrackWithQuality(Mat image, Mat corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, Mat cornersQuality, int blockSize, int gradientSize, boolean useHarrisDetector, double k) { goodFeaturesToTrackWithQuality_0(image.nativeObj, corners.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, cornersQuality.nativeObj, blockSize, gradientSize, useHarrisDetector, k); @@ -2937,60 +3032,55 @@ public static void goodFeaturesToTrackWithQuality(Mat image, Mat corners, int ma /** * Same as above, but returns also quality measure of the detected corners. * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. - * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * @param mask Region of interest. If the image is not empty (it needs to have the type - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. - * @param cornersQuality Output vector of quality measure of the detected corners. - * @param blockSize Size of an average block for computing a derivative covariation matrix over each - * pixel neighborhood. See cornerEigenValsAndVecs . - * @param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. - * See cornerEigenValsAndVecs . + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. + * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * @param mask Region of interest. If the image is not empty (it needs to have the type + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * @param cornersQuality Output vector of quality measure of the detected corners. + * @param blockSize Size of an average block for computing a derivative covariation matrix over each + * pixel neighborhood. See cornerEigenValsAndVecs . + * @param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. + * See cornerEigenValsAndVecs . * @param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) - * or #cornerMinEigenVal. + * or #cornerMinEigenVal. */ public static void goodFeaturesToTrackWithQuality(Mat image, Mat corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, Mat cornersQuality, int blockSize, int gradientSize, boolean useHarrisDetector) { goodFeaturesToTrackWithQuality_1(image.nativeObj, corners.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, cornersQuality.nativeObj, blockSize, gradientSize, useHarrisDetector); } - - // - // C++: void cv::goodFeaturesToTrack(Mat image, Mat& corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, Mat& cornersQuality, int blockSize = 3, int gradientSize = 3, bool useHarrisDetector = false, double k = 0.04) - // - /** * Same as above, but returns also quality measure of the detected corners. * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. - * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * @param mask Region of interest. If the image is not empty (it needs to have the type - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. + * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * @param mask Region of interest. If the image is not empty (it needs to have the type + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. * @param cornersQuality Output vector of quality measure of the detected corners. - * @param blockSize Size of an average block for computing a derivative covariation matrix over each - * pixel neighborhood. See cornerEigenValsAndVecs . - * @param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. - * See cornerEigenValsAndVecs . - * or #cornerMinEigenVal. + * @param blockSize Size of an average block for computing a derivative covariation matrix over each + * pixel neighborhood. See cornerEigenValsAndVecs . + * @param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. + * See cornerEigenValsAndVecs . + * or #cornerMinEigenVal. */ public static void goodFeaturesToTrackWithQuality(Mat image, Mat corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, Mat cornersQuality, int blockSize, int gradientSize) { goodFeaturesToTrackWithQuality_2(image.nativeObj, corners.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, cornersQuality.nativeObj, blockSize, gradientSize); @@ -2999,25 +3089,25 @@ public static void goodFeaturesToTrackWithQuality(Mat image, Mat corners, int ma /** * Same as above, but returns also quality measure of the detected corners. * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. - * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * @param mask Region of interest. If the image is not empty (it needs to have the type - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. + * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * @param mask Region of interest. If the image is not empty (it needs to have the type + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. * @param cornersQuality Output vector of quality measure of the detected corners. - * @param blockSize Size of an average block for computing a derivative covariation matrix over each - * pixel neighborhood. See cornerEigenValsAndVecs . - * See cornerEigenValsAndVecs . - * or #cornerMinEigenVal. + * @param blockSize Size of an average block for computing a derivative covariation matrix over each + * pixel neighborhood. See cornerEigenValsAndVecs . + * See cornerEigenValsAndVecs . + * or #cornerMinEigenVal. */ public static void goodFeaturesToTrackWithQuality(Mat image, Mat corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, Mat cornersQuality, int blockSize) { goodFeaturesToTrackWithQuality_3(image.nativeObj, corners.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, cornersQuality.nativeObj, blockSize); @@ -3026,56 +3116,61 @@ public static void goodFeaturesToTrackWithQuality(Mat image, Mat corners, int ma /** * Same as above, but returns also quality measure of the detected corners. * - * @param image Input 8-bit or floating-point 32-bit, single-channel image. - * @param corners Output vector of detected corners. - * @param maxCorners Maximum number of corners to return. If there are more corners than are found, - * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set - * and all detected corners are returned. - * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The - * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue - * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the - * quality measure less than the product are rejected. For example, if the best corner has the - * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure - * less than 15 are rejected. - * @param minDistance Minimum possible Euclidean distance between the returned corners. - * @param mask Region of interest. If the image is not empty (it needs to have the type - * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. + * @param image Input 8-bit or floating-point 32-bit, single-channel image. + * @param corners Output vector of detected corners. + * @param maxCorners Maximum number of corners to return. If there are more corners than are found, + * the strongest of them is returned. {@code maxCorners <= 0} implies that no limit on the maximum is set + * and all detected corners are returned. + * @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The + * parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue + * (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the + * quality measure less than the product are rejected. For example, if the best corner has the + * quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure + * less than 15 are rejected. + * @param minDistance Minimum possible Euclidean distance between the returned corners. + * @param mask Region of interest. If the image is not empty (it needs to have the type + * CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. * @param cornersQuality Output vector of quality measure of the detected corners. - * pixel neighborhood. See cornerEigenValsAndVecs . - * See cornerEigenValsAndVecs . - * or #cornerMinEigenVal. + * pixel neighborhood. See cornerEigenValsAndVecs . + * See cornerEigenValsAndVecs . + * or #cornerMinEigenVal. */ public static void goodFeaturesToTrackWithQuality(Mat image, Mat corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, Mat cornersQuality) { goodFeaturesToTrackWithQuality_4(image.nativeObj, corners.nativeObj, maxCorners, qualityLevel, minDistance, mask.nativeObj, cornersQuality.nativeObj); } + + // + // C++: void cv::HoughLines(Mat image, Mat& lines, double rho, double theta, int threshold, double srn = 0, double stn = 0, double min_theta = 0, double max_theta = CV_PI) + // + /** * Finds lines in a binary image using the standard Hough transform. - *

    + * * The function implements the standard or standard multi-scale Hough transform algorithm for line * detection. See <http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm> for a good explanation of Hough * transform. * - * @param image 8-bit, single-channel binary source image. The image may be modified by the function. - * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector - * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from - * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation - * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and - * \(\textrm{votes}\) is the value of accumulator. - * @param rho Distance resolution of the accumulator in pixels. - * @param theta Angle resolution of the accumulator in radians. + * @param image 8-bit, single-channel binary source image. The image may be modified by the function. + * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector + * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from + * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation + * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and + * \(\textrm{votes}\) is the value of accumulator. + * @param rho Distance resolution of the accumulator in pixels. + * @param theta Angle resolution of the accumulator in radians. * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough - * votes ( \(>\texttt{threshold}\) ). - * @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. - * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is - * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these - * parameters should be positive. - * @param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. + * votes ( \(>\texttt{threshold}\) ). + * @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. + * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is + * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these + * parameters should be positive. + * @param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. * @param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines. - * Must fall between 0 and max_theta. + * Must fall between 0 and max_theta. * @param max_theta For standard and multi-scale Hough transform, an upper bound for the angle. - * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly - * less than max_theta, depending on the parameters min_theta and theta. + * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly + * less than max_theta, depending on the parameters min_theta and theta. */ public static void HoughLines(Mat image, Mat lines, double rho, double theta, int threshold, double srn, double stn, double min_theta, double max_theta) { HoughLines_0(image.nativeObj, lines.nativeObj, rho, theta, threshold, srn, stn, min_theta, max_theta); @@ -3083,65 +3178,60 @@ public static void HoughLines(Mat image, Mat lines, double rho, double theta, in /** * Finds lines in a binary image using the standard Hough transform. - *

    + * * The function implements the standard or standard multi-scale Hough transform algorithm for line * detection. See <http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm> for a good explanation of Hough * transform. * - * @param image 8-bit, single-channel binary source image. The image may be modified by the function. - * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector - * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from - * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation - * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and - * \(\textrm{votes}\) is the value of accumulator. - * @param rho Distance resolution of the accumulator in pixels. - * @param theta Angle resolution of the accumulator in radians. + * @param image 8-bit, single-channel binary source image. The image may be modified by the function. + * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector + * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from + * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation + * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and + * \(\textrm{votes}\) is the value of accumulator. + * @param rho Distance resolution of the accumulator in pixels. + * @param theta Angle resolution of the accumulator in radians. * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough - * votes ( \(>\texttt{threshold}\) ). - * @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. - * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is - * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these - * parameters should be positive. - * @param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. + * votes ( \(>\texttt{threshold}\) ). + * @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. + * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is + * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these + * parameters should be positive. + * @param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. * @param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines. - * Must fall between 0 and max_theta. - * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly - * less than max_theta, depending on the parameters min_theta and theta. + * Must fall between 0 and max_theta. + * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly + * less than max_theta, depending on the parameters min_theta and theta. */ public static void HoughLines(Mat image, Mat lines, double rho, double theta, int threshold, double srn, double stn, double min_theta) { HoughLines_1(image.nativeObj, lines.nativeObj, rho, theta, threshold, srn, stn, min_theta); } - - // - // C++: void cv::HoughLines(Mat image, Mat& lines, double rho, double theta, int threshold, double srn = 0, double stn = 0, double min_theta = 0, double max_theta = CV_PI) - // - /** * Finds lines in a binary image using the standard Hough transform. - *

    + * * The function implements the standard or standard multi-scale Hough transform algorithm for line * detection. See <http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm> for a good explanation of Hough * transform. * - * @param image 8-bit, single-channel binary source image. The image may be modified by the function. - * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector - * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from - * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation - * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and - * \(\textrm{votes}\) is the value of accumulator. - * @param rho Distance resolution of the accumulator in pixels. - * @param theta Angle resolution of the accumulator in radians. + * @param image 8-bit, single-channel binary source image. The image may be modified by the function. + * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector + * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from + * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation + * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and + * \(\textrm{votes}\) is the value of accumulator. + * @param rho Distance resolution of the accumulator in pixels. + * @param theta Angle resolution of the accumulator in radians. * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough - * votes ( \(>\texttt{threshold}\) ). - * @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. - * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is - * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these - * parameters should be positive. - * @param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. - * Must fall between 0 and max_theta. - * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly - * less than max_theta, depending on the parameters min_theta and theta. + * votes ( \(>\texttt{threshold}\) ). + * @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. + * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is + * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these + * parameters should be positive. + * @param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. + * Must fall between 0 and max_theta. + * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly + * less than max_theta, depending on the parameters min_theta and theta. */ public static void HoughLines(Mat image, Mat lines, double rho, double theta, int threshold, double srn, double stn) { HoughLines_2(image.nativeObj, lines.nativeObj, rho, theta, threshold, srn, stn); @@ -3149,28 +3239,28 @@ public static void HoughLines(Mat image, Mat lines, double rho, double theta, in /** * Finds lines in a binary image using the standard Hough transform. - *

    + * * The function implements the standard or standard multi-scale Hough transform algorithm for line * detection. See <http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm> for a good explanation of Hough * transform. * - * @param image 8-bit, single-channel binary source image. The image may be modified by the function. - * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector - * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from - * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation - * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and - * \(\textrm{votes}\) is the value of accumulator. - * @param rho Distance resolution of the accumulator in pixels. - * @param theta Angle resolution of the accumulator in radians. + * @param image 8-bit, single-channel binary source image. The image may be modified by the function. + * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector + * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from + * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation + * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and + * \(\textrm{votes}\) is the value of accumulator. + * @param rho Distance resolution of the accumulator in pixels. + * @param theta Angle resolution of the accumulator in radians. * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough - * votes ( \(>\texttt{threshold}\) ). - * @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. - * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is - * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these - * parameters should be positive. - * Must fall between 0 and max_theta. - * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly - * less than max_theta, depending on the parameters min_theta and theta. + * votes ( \(>\texttt{threshold}\) ). + * @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. + * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is + * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these + * parameters should be positive. + * Must fall between 0 and max_theta. + * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly + * less than max_theta, depending on the parameters min_theta and theta. */ public static void HoughLines(Mat image, Mat lines, double rho, double theta, int threshold, double srn) { HoughLines_3(image.nativeObj, lines.nativeObj, rho, theta, threshold, srn); @@ -3178,60 +3268,65 @@ public static void HoughLines(Mat image, Mat lines, double rho, double theta, in /** * Finds lines in a binary image using the standard Hough transform. - *

    + * * The function implements the standard or standard multi-scale Hough transform algorithm for line * detection. See <http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm> for a good explanation of Hough * transform. * - * @param image 8-bit, single-channel binary source image. The image may be modified by the function. - * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector - * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from - * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation - * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and - * \(\textrm{votes}\) is the value of accumulator. - * @param rho Distance resolution of the accumulator in pixels. - * @param theta Angle resolution of the accumulator in radians. + * @param image 8-bit, single-channel binary source image. The image may be modified by the function. + * @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector + * \((\rho, \theta)\) or \((\rho, \theta, \textrm{votes})\), where \(\rho\) is the distance from + * the coordinate origin \((0,0)\) (top-left corner of the image), \(\theta\) is the line rotation + * angle in radians ( \(0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\) ), and + * \(\textrm{votes}\) is the value of accumulator. + * @param rho Distance resolution of the accumulator in pixels. + * @param theta Angle resolution of the accumulator in radians. * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough - * votes ( \(>\texttt{threshold}\) ). - * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is - * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these - * parameters should be positive. - * Must fall between 0 and max_theta. - * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly - * less than max_theta, depending on the parameters min_theta and theta. + * votes ( \(>\texttt{threshold}\) ). + * The coarse accumulator distance resolution is rho and the accurate accumulator resolution is + * rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these + * parameters should be positive. + * Must fall between 0 and max_theta. + * Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly + * less than max_theta, depending on the parameters min_theta and theta. */ public static void HoughLines(Mat image, Mat lines, double rho, double theta, int threshold) { HoughLines_4(image.nativeObj, lines.nativeObj, rho, theta, threshold); } + + // + // C++: void cv::HoughLinesP(Mat image, Mat& lines, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0) + // + /** * Finds line segments in a binary image using the probabilistic Hough transform. - *

    + * * The function implements the probabilistic Hough transform algorithm for line detection, described * in CITE: Matas00 - *

    + * * See the line detection example below: * INCLUDE: snippets/imgproc_HoughLinesP.cpp * This is a sample picture the function parameters have been tuned for: - *

    + * * ![image](pics/building.jpg) - *

    + * * And this is the output of the above program in case of the probabilistic Hough transform: - *

    + * * ![image](pics/houghp.png) * - * @param image 8-bit, single-channel binary source image. The image may be modified by the function. - * @param lines Output vector of lines. Each line is represented by a 4-element vector - * \((x_1, y_1, x_2, y_2)\) , where \((x_1,y_1)\) and \((x_2, y_2)\) are the ending points of each detected - * line segment. - * @param rho Distance resolution of the accumulator in pixels. - * @param theta Angle resolution of the accumulator in radians. - * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough - * votes ( \(>\texttt{threshold}\) ). + * @param image 8-bit, single-channel binary source image. The image may be modified by the function. + * @param lines Output vector of lines. Each line is represented by a 4-element vector + * \((x_1, y_1, x_2, y_2)\) , where \((x_1,y_1)\) and \((x_2, y_2)\) are the ending points of each detected + * line segment. + * @param rho Distance resolution of the accumulator in pixels. + * @param theta Angle resolution of the accumulator in radians. + * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough + * votes ( \(>\texttt{threshold}\) ). * @param minLineLength Minimum line length. Line segments shorter than that are rejected. - * @param maxLineGap Maximum allowed gap between points on the same line to link them. - *

    - * SEE: LineSegmentDetector + * @param maxLineGap Maximum allowed gap between points on the same line to link them. + * + * SEE: LineSegmentDetector */ public static void HoughLinesP(Mat image, Mat lines, double rho, double theta, int threshold, double minLineLength, double maxLineGap) { HoughLinesP_0(image.nativeObj, lines.nativeObj, rho, theta, threshold, minLineLength, maxLineGap); @@ -3239,101 +3334,105 @@ public static void HoughLinesP(Mat image, Mat lines, double rho, double theta, i /** * Finds line segments in a binary image using the probabilistic Hough transform. - *

    + * * The function implements the probabilistic Hough transform algorithm for line detection, described * in CITE: Matas00 - *

    + * * See the line detection example below: * INCLUDE: snippets/imgproc_HoughLinesP.cpp * This is a sample picture the function parameters have been tuned for: - *

    + * * ![image](pics/building.jpg) - *

    + * * And this is the output of the above program in case of the probabilistic Hough transform: - *

    + * * ![image](pics/houghp.png) * - * @param image 8-bit, single-channel binary source image. The image may be modified by the function. - * @param lines Output vector of lines. Each line is represented by a 4-element vector - * \((x_1, y_1, x_2, y_2)\) , where \((x_1,y_1)\) and \((x_2, y_2)\) are the ending points of each detected - * line segment. - * @param rho Distance resolution of the accumulator in pixels. - * @param theta Angle resolution of the accumulator in radians. - * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough - * votes ( \(>\texttt{threshold}\) ). + * @param image 8-bit, single-channel binary source image. The image may be modified by the function. + * @param lines Output vector of lines. Each line is represented by a 4-element vector + * \((x_1, y_1, x_2, y_2)\) , where \((x_1,y_1)\) and \((x_2, y_2)\) are the ending points of each detected + * line segment. + * @param rho Distance resolution of the accumulator in pixels. + * @param theta Angle resolution of the accumulator in radians. + * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough + * votes ( \(>\texttt{threshold}\) ). * @param minLineLength Minimum line length. Line segments shorter than that are rejected. - *

    - * SEE: LineSegmentDetector + * + * SEE: LineSegmentDetector */ public static void HoughLinesP(Mat image, Mat lines, double rho, double theta, int threshold, double minLineLength) { HoughLinesP_1(image.nativeObj, lines.nativeObj, rho, theta, threshold, minLineLength); } - - // - // C++: void cv::HoughLinesP(Mat image, Mat& lines, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0) - // - /** * Finds line segments in a binary image using the probabilistic Hough transform. - *

    + * * The function implements the probabilistic Hough transform algorithm for line detection, described * in CITE: Matas00 - *

    + * * See the line detection example below: * INCLUDE: snippets/imgproc_HoughLinesP.cpp * This is a sample picture the function parameters have been tuned for: - *

    + * * ![image](pics/building.jpg) - *

    + * * And this is the output of the above program in case of the probabilistic Hough transform: - *

    + * * ![image](pics/houghp.png) * - * @param image 8-bit, single-channel binary source image. The image may be modified by the function. - * @param lines Output vector of lines. Each line is represented by a 4-element vector - * \((x_1, y_1, x_2, y_2)\) , where \((x_1,y_1)\) and \((x_2, y_2)\) are the ending points of each detected - * line segment. - * @param rho Distance resolution of the accumulator in pixels. - * @param theta Angle resolution of the accumulator in radians. + * @param image 8-bit, single-channel binary source image. The image may be modified by the function. + * @param lines Output vector of lines. Each line is represented by a 4-element vector + * \((x_1, y_1, x_2, y_2)\) , where \((x_1,y_1)\) and \((x_2, y_2)\) are the ending points of each detected + * line segment. + * @param rho Distance resolution of the accumulator in pixels. + * @param theta Angle resolution of the accumulator in radians. * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough - * votes ( \(>\texttt{threshold}\) ). - *

    - * SEE: LineSegmentDetector + * votes ( \(>\texttt{threshold}\) ). + * + * SEE: LineSegmentDetector */ public static void HoughLinesP(Mat image, Mat lines, double rho, double theta, int threshold) { HoughLinesP_2(image.nativeObj, lines.nativeObj, rho, theta, threshold); } + + // + // C++: void cv::HoughLinesPointSet(Mat point, Mat& lines, int lines_max, int threshold, double min_rho, double max_rho, double rho_step, double min_theta, double max_theta, double theta_step) + // + /** * Finds lines in a set of points using the standard Hough transform. - *

    + * * The function finds lines in a set of points using a modification of the Hough transform. * INCLUDE: snippets/imgproc_HoughLinesPointSet.cpp - * - * @param point Input vector of points. Each vector must be encoded as a Point vector \((x,y)\). Type must be CV_32FC2 or CV_32SC2. - * @param lines Output vector of found lines. Each vector is encoded as a vector<Vec3d> \((votes, rho, theta)\). - * The larger the value of 'votes', the higher the reliability of the Hough line. - * @param lines_max Max count of Hough lines. - * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough - * votes ( \(>\texttt{threshold}\) ). - * @param min_rho Minimum value for \(\rho\) for the accumulator (Note: \(\rho\) can be negative. The absolute value \(|\rho|\) is the distance of a line to the origin.). - * @param max_rho Maximum value for \(\rho\) for the accumulator. - * @param rho_step Distance resolution of the accumulator. - * @param min_theta Minimum angle value of the accumulator in radians. - * @param max_theta Upper bound for the angle value of the accumulator in radians. The actual maximum - * angle may be slightly less than max_theta, depending on the parameters min_theta and theta_step. + * @param point Input vector of points. Each vector must be encoded as a Point vector \((x,y)\). Type must be CV_32FC2 or CV_32SC2. + * @param lines Output vector of found lines. Each vector is encoded as a vector<Vec3d> \((votes, rho, theta)\). + * The larger the value of 'votes', the higher the reliability of the Hough line. + * @param lines_max Max count of Hough lines. + * @param threshold %Accumulator threshold parameter. Only those lines are returned that get enough + * votes ( \(>\texttt{threshold}\) ). + * @param min_rho Minimum value for \(\rho\) for the accumulator (Note: \(\rho\) can be negative. The absolute value \(|\rho|\) is the distance of a line to the origin.). + * @param max_rho Maximum value for \(\rho\) for the accumulator. + * @param rho_step Distance resolution of the accumulator. + * @param min_theta Minimum angle value of the accumulator in radians. + * @param max_theta Upper bound for the angle value of the accumulator in radians. The actual maximum + * angle may be slightly less than max_theta, depending on the parameters min_theta and theta_step. * @param theta_step Angle resolution of the accumulator in radians. */ public static void HoughLinesPointSet(Mat point, Mat lines, int lines_max, int threshold, double min_rho, double max_rho, double rho_step, double min_theta, double max_theta, double theta_step) { HoughLinesPointSet_0(point.nativeObj, lines.nativeObj, lines_max, threshold, min_rho, max_rho, rho_step, min_theta, max_theta, theta_step); } + + // + // C++: void cv::HoughCircles(Mat image, Mat& circles, int method, double dp, double minDist, double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0) + // + /** * Finds circles in a grayscale image using the Hough transform. - *

    + * * The function finds circles in a grayscale image using a modification of the Hough transform. - *

    + * * Example: : * INCLUDE: snippets/imgproc_HoughLinesCircles.cpp * @@ -3341,52 +3440,47 @@ public static void HoughLinesPointSet(Mat point, Mat lines, int lines_max, int t * radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if * you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number * to return centers only without radius search, and find the correct radius using an additional procedure. - *

    + * * It also helps to smooth image a bit unless it's already soft. For example, * GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help. * - * @param image 8-bit, single-channel, grayscale input image. - * @param circles Output vector of found circles. Each vector is encoded as 3 or 4 element - * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . - * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. - * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if - * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has - * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, - * unless some small very circles need to be detected. - * @param minDist Minimum distance between the centers of the detected circles. If the parameter is - * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is - * too large, some circles may be missed. - * @param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, - * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). - * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value - * shough normally be higher, such as 300 or normally exposed and contrasty images. - * @param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the - * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more - * false circles may be detected. Circles, corresponding to the larger accumulator values, will be - * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. - * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. - * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. - * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. + * @param image 8-bit, single-channel, grayscale input image. + * @param circles Output vector of found circles. Each vector is encoded as 3 or 4 element + * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . + * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. + * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if + * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has + * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, + * unless some small very circles need to be detected. + * @param minDist Minimum distance between the centers of the detected circles. If the parameter is + * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is + * too large, some circles may be missed. + * @param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, + * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). + * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value + * should normally be higher, such as 300 or normally exposed and contrasty images. + * @param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the + * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more + * false circles may be detected. Circles, corresponding to the larger accumulator values, will be + * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. + * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. + * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. + * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. * @param minRadius Minimum circle radius. * @param maxRadius Maximum circle radius. If <= 0, uses the maximum image dimension. If < 0, #HOUGH_GRADIENT returns - * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. - *

    - * SEE: fitEllipse, minEnclosingCircle + * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. + * + * SEE: fitEllipse, minEnclosingCircle */ public static void HoughCircles(Mat image, Mat circles, int method, double dp, double minDist, double param1, double param2, int minRadius, int maxRadius) { HoughCircles_0(image.nativeObj, circles.nativeObj, method, dp, minDist, param1, param2, minRadius, maxRadius); } - - // - // C++: void cv::HoughLinesPointSet(Mat point, Mat& lines, int lines_max, int threshold, double min_rho, double max_rho, double rho_step, double min_theta, double max_theta, double theta_step) - // - /** * Finds circles in a grayscale image using the Hough transform. - *

    + * * The function finds circles in a grayscale image using a modification of the Hough transform. - *

    + * * Example: : * INCLUDE: snippets/imgproc_HoughLinesCircles.cpp * @@ -3394,51 +3488,46 @@ public static void HoughCircles(Mat image, Mat circles, int method, double dp, d * radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if * you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number * to return centers only without radius search, and find the correct radius using an additional procedure. - *

    + * * It also helps to smooth image a bit unless it's already soft. For example, * GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help. * - * @param image 8-bit, single-channel, grayscale input image. - * @param circles Output vector of found circles. Each vector is encoded as 3 or 4 element - * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . - * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. - * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if - * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has - * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, - * unless some small very circles need to be detected. - * @param minDist Minimum distance between the centers of the detected circles. If the parameter is - * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is - * too large, some circles may be missed. - * @param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, - * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). - * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value - * shough normally be higher, such as 300 or normally exposed and contrasty images. - * @param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the - * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more - * false circles may be detected. Circles, corresponding to the larger accumulator values, will be - * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. - * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. - * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. - * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. + * @param image 8-bit, single-channel, grayscale input image. + * @param circles Output vector of found circles. Each vector is encoded as 3 or 4 element + * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . + * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. + * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if + * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has + * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, + * unless some small very circles need to be detected. + * @param minDist Minimum distance between the centers of the detected circles. If the parameter is + * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is + * too large, some circles may be missed. + * @param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, + * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). + * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value + * should normally be higher, such as 300 or normally exposed and contrasty images. + * @param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the + * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more + * false circles may be detected. Circles, corresponding to the larger accumulator values, will be + * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. + * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. + * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. + * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. * @param minRadius Minimum circle radius. - * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. - *

    - * SEE: fitEllipse, minEnclosingCircle + * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. + * + * SEE: fitEllipse, minEnclosingCircle */ public static void HoughCircles(Mat image, Mat circles, int method, double dp, double minDist, double param1, double param2, int minRadius) { HoughCircles_1(image.nativeObj, circles.nativeObj, method, dp, minDist, param1, param2, minRadius); } - - // - // C++: void cv::HoughCircles(Mat image, Mat& circles, int method, double dp, double minDist, double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0) - // - /** * Finds circles in a grayscale image using the Hough transform. - *

    + * * The function finds circles in a grayscale image using a modification of the Hough transform. - *

    + * * Example: : * INCLUDE: snippets/imgproc_HoughLinesCircles.cpp * @@ -3446,35 +3535,35 @@ public static void HoughCircles(Mat image, Mat circles, int method, double dp, d * radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if * you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number * to return centers only without radius search, and find the correct radius using an additional procedure. - *

    + * * It also helps to smooth image a bit unless it's already soft. For example, * GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help. * - * @param image 8-bit, single-channel, grayscale input image. + * @param image 8-bit, single-channel, grayscale input image. * @param circles Output vector of found circles. Each vector is encoded as 3 or 4 element - * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . - * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. - * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if - * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has - * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, - * unless some small very circles need to be detected. + * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . + * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. + * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if + * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has + * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, + * unless some small very circles need to be detected. * @param minDist Minimum distance between the centers of the detected circles. If the parameter is - * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is - * too large, some circles may be missed. - * @param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, - * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). - * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value - * shough normally be higher, such as 300 or normally exposed and contrasty images. - * @param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the - * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more - * false circles may be detected. Circles, corresponding to the larger accumulator values, will be - * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. - * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. - * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. - * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. - * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. - *

    - * SEE: fitEllipse, minEnclosingCircle + * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is + * too large, some circles may be missed. + * @param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, + * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). + * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value + * should normally be higher, such as 300 or normally exposed and contrasty images. + * @param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the + * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more + * false circles may be detected. Circles, corresponding to the larger accumulator values, will be + * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. + * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. + * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. + * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. + * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. + * + * SEE: fitEllipse, minEnclosingCircle */ public static void HoughCircles(Mat image, Mat circles, int method, double dp, double minDist, double param1, double param2) { HoughCircles_2(image.nativeObj, circles.nativeObj, method, dp, minDist, param1, param2); @@ -3482,9 +3571,9 @@ public static void HoughCircles(Mat image, Mat circles, int method, double dp, d /** * Finds circles in a grayscale image using the Hough transform. - *

    + * * The function finds circles in a grayscale image using a modification of the Hough transform. - *

    + * * Example: : * INCLUDE: snippets/imgproc_HoughLinesCircles.cpp * @@ -3492,34 +3581,34 @@ public static void HoughCircles(Mat image, Mat circles, int method, double dp, d * radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if * you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number * to return centers only without radius search, and find the correct radius using an additional procedure. - *

    + * * It also helps to smooth image a bit unless it's already soft. For example, * GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help. * - * @param image 8-bit, single-channel, grayscale input image. + * @param image 8-bit, single-channel, grayscale input image. * @param circles Output vector of found circles. Each vector is encoded as 3 or 4 element - * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . - * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. - * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if - * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has - * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, - * unless some small very circles need to be detected. + * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . + * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. + * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if + * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has + * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, + * unless some small very circles need to be detected. * @param minDist Minimum distance between the centers of the detected circles. If the parameter is - * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is - * too large, some circles may be missed. - * @param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, - * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). - * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value - * shough normally be higher, such as 300 or normally exposed and contrasty images. - * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more - * false circles may be detected. Circles, corresponding to the larger accumulator values, will be - * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. - * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. - * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. - * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. - * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. - *

    - * SEE: fitEllipse, minEnclosingCircle + * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is + * too large, some circles may be missed. + * @param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, + * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). + * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value + * should normally be higher, such as 300 or normally exposed and contrasty images. + * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more + * false circles may be detected. Circles, corresponding to the larger accumulator values, will be + * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. + * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. + * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. + * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. + * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. + * + * SEE: fitEllipse, minEnclosingCircle */ public static void HoughCircles(Mat image, Mat circles, int method, double dp, double minDist, double param1) { HoughCircles_3(image.nativeObj, circles.nativeObj, method, dp, minDist, param1); @@ -3527,9 +3616,9 @@ public static void HoughCircles(Mat image, Mat circles, int method, double dp, d /** * Finds circles in a grayscale image using the Hough transform. - *

    + * * The function finds circles in a grayscale image using a modification of the Hough transform. - *

    + * * Example: : * INCLUDE: snippets/imgproc_HoughLinesCircles.cpp * @@ -3537,60 +3626,65 @@ public static void HoughCircles(Mat image, Mat circles, int method, double dp, d * radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if * you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number * to return centers only without radius search, and find the correct radius using an additional procedure. - *

    + * * It also helps to smooth image a bit unless it's already soft. For example, * GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help. * - * @param image 8-bit, single-channel, grayscale input image. + * @param image 8-bit, single-channel, grayscale input image. * @param circles Output vector of found circles. Each vector is encoded as 3 or 4 element - * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . - * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. - * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if - * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has - * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, - * unless some small very circles need to be detected. + * floating-point vector \((x, y, radius)\) or \((x, y, radius, votes)\) . + * @param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. + * @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if + * dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has + * half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, + * unless some small very circles need to be detected. * @param minDist Minimum distance between the centers of the detected circles. If the parameter is - * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is - * too large, some circles may be missed. - * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). - * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value - * shough normally be higher, such as 300 or normally exposed and contrasty images. - * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more - * false circles may be detected. Circles, corresponding to the larger accumulator values, will be - * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. - * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. - * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. - * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. - * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. - *

    - * SEE: fitEllipse, minEnclosingCircle + * too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is + * too large, some circles may be missed. + * it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). + * Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value + * should normally be higher, such as 300 or normally exposed and contrasty images. + * accumulator threshold for the circle centers at the detection stage. The smaller it is, the more + * false circles may be detected. Circles, corresponding to the larger accumulator values, will be + * returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. + * The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. + * If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. + * But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. + * centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. + * + * SEE: fitEllipse, minEnclosingCircle */ public static void HoughCircles(Mat image, Mat circles, int method, double dp, double minDist) { HoughCircles_4(image.nativeObj, circles.nativeObj, method, dp, minDist); } + + // + // C++: void cv::erode(Mat src, Mat& dst, Mat kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, Scalar borderValue = morphologyDefaultBorderValue()) + // + /** * Erodes an image by using a specific structuring element. - *

    + * * The function erodes the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the minimum is taken: - *

    + * * \(\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param kernel structuring element used for erosion; if {@code element=Mat()}, a {@code 3 x 3} rectangular - * structuring element is used. Kernel can be created using #getStructuringElement. - * @param anchor position of the anchor within the element; default value (-1, -1) means that the - * anchor is at the element center. - * @param iterations number of times erosion is applied. - * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param kernel structuring element used for erosion; if {@code element=Mat()}, a {@code 3 x 3} rectangular + * structuring element is used. Kernel can be created using #getStructuringElement. + * @param anchor position of the anchor within the element; default value (-1, -1) means that the + * anchor is at the element center. + * @param iterations number of times erosion is applied. + * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. * @param borderValue border value in case of a constant border - * SEE: dilate, morphologyEx, getStructuringElement + * SEE: dilate, morphologyEx, getStructuringElement */ public static void erode(Mat src, Mat dst, Mat kernel, Point anchor, int iterations, int borderType, Scalar borderValue) { erode_0(src.nativeObj, dst.nativeObj, kernel.nativeObj, anchor.x, anchor.y, iterations, borderType, borderValue.val[0], borderValue.val[1], borderValue.val[2], borderValue.val[3]); @@ -3598,55 +3692,50 @@ public static void erode(Mat src, Mat dst, Mat kernel, Point anchor, int iterati /** * Erodes an image by using a specific structuring element. - *

    + * * The function erodes the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the minimum is taken: - *

    + * * \(\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param kernel structuring element used for erosion; if {@code element=Mat()}, a {@code 3 x 3} rectangular - * structuring element is used. Kernel can be created using #getStructuringElement. - * @param anchor position of the anchor within the element; default value (-1, -1) means that the - * anchor is at the element center. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param kernel structuring element used for erosion; if {@code element=Mat()}, a {@code 3 x 3} rectangular + * structuring element is used. Kernel can be created using #getStructuringElement. + * @param anchor position of the anchor within the element; default value (-1, -1) means that the + * anchor is at the element center. * @param iterations number of times erosion is applied. * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. - * SEE: dilate, morphologyEx, getStructuringElement + * SEE: dilate, morphologyEx, getStructuringElement */ public static void erode(Mat src, Mat dst, Mat kernel, Point anchor, int iterations, int borderType) { erode_1(src.nativeObj, dst.nativeObj, kernel.nativeObj, anchor.x, anchor.y, iterations, borderType); } - - // - // C++: void cv::erode(Mat src, Mat& dst, Mat kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, Scalar borderValue = morphologyDefaultBorderValue()) - // - /** * Erodes an image by using a specific structuring element. - *

    + * * The function erodes the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the minimum is taken: - *

    + * * \(\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param kernel structuring element used for erosion; if {@code element=Mat()}, a {@code 3 x 3} rectangular - * structuring element is used. Kernel can be created using #getStructuringElement. - * @param anchor position of the anchor within the element; default value (-1, -1) means that the - * anchor is at the element center. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param kernel structuring element used for erosion; if {@code element=Mat()}, a {@code 3 x 3} rectangular + * structuring element is used. Kernel can be created using #getStructuringElement. + * @param anchor position of the anchor within the element; default value (-1, -1) means that the + * anchor is at the element center. * @param iterations number of times erosion is applied. - * SEE: dilate, morphologyEx, getStructuringElement + * SEE: dilate, morphologyEx, getStructuringElement */ public static void erode(Mat src, Mat dst, Mat kernel, Point anchor, int iterations) { erode_2(src.nativeObj, dst.nativeObj, kernel.nativeObj, anchor.x, anchor.y, iterations); @@ -3654,23 +3743,23 @@ public static void erode(Mat src, Mat dst, Mat kernel, Point anchor, int iterati /** * Erodes an image by using a specific structuring element. - *

    + * * The function erodes the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the minimum is taken: - *

    + * * \(\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. * @param kernel structuring element used for erosion; if {@code element=Mat()}, a {@code 3 x 3} rectangular - * structuring element is used. Kernel can be created using #getStructuringElement. + * structuring element is used. Kernel can be created using #getStructuringElement. * @param anchor position of the anchor within the element; default value (-1, -1) means that the - * anchor is at the element center. - * SEE: dilate, morphologyEx, getStructuringElement + * anchor is at the element center. + * SEE: dilate, morphologyEx, getStructuringElement */ public static void erode(Mat src, Mat dst, Mat kernel, Point anchor) { erode_3(src.nativeObj, dst.nativeObj, kernel.nativeObj, anchor.x, anchor.y); @@ -3678,48 +3767,53 @@ public static void erode(Mat src, Mat dst, Mat kernel, Point anchor) { /** * Erodes an image by using a specific structuring element. - *

    + * * The function erodes the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the minimum is taken: - *

    + * * \(\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. * @param kernel structuring element used for erosion; if {@code element=Mat()}, a {@code 3 x 3} rectangular - * structuring element is used. Kernel can be created using #getStructuringElement. - * anchor is at the element center. - * SEE: dilate, morphologyEx, getStructuringElement + * structuring element is used. Kernel can be created using #getStructuringElement. + * anchor is at the element center. + * SEE: dilate, morphologyEx, getStructuringElement */ public static void erode(Mat src, Mat dst, Mat kernel) { erode_4(src.nativeObj, dst.nativeObj, kernel.nativeObj); } + + // + // C++: void cv::dilate(Mat src, Mat& dst, Mat kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, Scalar borderValue = morphologyDefaultBorderValue()) + // + /** * Dilates an image by using a specific structuring element. - *

    + * * The function dilates the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the maximum is taken: * \(\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular - * structuring element is used. Kernel can be created using #getStructuringElement - * @param anchor position of the anchor within the element; default value (-1, -1) means that the - * anchor is at the element center. - * @param iterations number of times dilation is applied. - * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not suported. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular + * structuring element is used. Kernel can be created using #getStructuringElement + * @param anchor position of the anchor within the element; default value (-1, -1) means that the + * anchor is at the element center. + * @param iterations number of times dilation is applied. + * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not suported. * @param borderValue border value in case of a constant border - * SEE: erode, morphologyEx, getStructuringElement + * SEE: erode, morphologyEx, getStructuringElement */ public static void dilate(Mat src, Mat dst, Mat kernel, Point anchor, int iterations, int borderType, Scalar borderValue) { dilate_0(src.nativeObj, dst.nativeObj, kernel.nativeObj, anchor.x, anchor.y, iterations, borderType, borderValue.val[0], borderValue.val[1], borderValue.val[2], borderValue.val[3]); @@ -3727,53 +3821,48 @@ public static void dilate(Mat src, Mat dst, Mat kernel, Point anchor, int iterat /** * Dilates an image by using a specific structuring element. - *

    + * * The function dilates the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the maximum is taken: * \(\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular - * structuring element is used. Kernel can be created using #getStructuringElement - * @param anchor position of the anchor within the element; default value (-1, -1) means that the - * anchor is at the element center. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular + * structuring element is used. Kernel can be created using #getStructuringElement + * @param anchor position of the anchor within the element; default value (-1, -1) means that the + * anchor is at the element center. * @param iterations number of times dilation is applied. * @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not suported. - * SEE: erode, morphologyEx, getStructuringElement + * SEE: erode, morphologyEx, getStructuringElement */ public static void dilate(Mat src, Mat dst, Mat kernel, Point anchor, int iterations, int borderType) { dilate_1(src.nativeObj, dst.nativeObj, kernel.nativeObj, anchor.x, anchor.y, iterations, borderType); } - - // - // C++: void cv::dilate(Mat src, Mat& dst, Mat kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, Scalar borderValue = morphologyDefaultBorderValue()) - // - /** * Dilates an image by using a specific structuring element. - *

    + * * The function dilates the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the maximum is taken: * \(\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. - * @param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular - * structuring element is used. Kernel can be created using #getStructuringElement - * @param anchor position of the anchor within the element; default value (-1, -1) means that the - * anchor is at the element center. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. + * @param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular + * structuring element is used. Kernel can be created using #getStructuringElement + * @param anchor position of the anchor within the element; default value (-1, -1) means that the + * anchor is at the element center. * @param iterations number of times dilation is applied. - * SEE: erode, morphologyEx, getStructuringElement + * SEE: erode, morphologyEx, getStructuringElement */ public static void dilate(Mat src, Mat dst, Mat kernel, Point anchor, int iterations) { dilate_2(src.nativeObj, dst.nativeObj, kernel.nativeObj, anchor.x, anchor.y, iterations); @@ -3781,22 +3870,22 @@ public static void dilate(Mat src, Mat dst, Mat kernel, Point anchor, int iterat /** * Dilates an image by using a specific structuring element. - *

    + * * The function dilates the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the maximum is taken: * \(\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. * @param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular - * structuring element is used. Kernel can be created using #getStructuringElement + * structuring element is used. Kernel can be created using #getStructuringElement * @param anchor position of the anchor within the element; default value (-1, -1) means that the - * anchor is at the element center. - * SEE: erode, morphologyEx, getStructuringElement + * anchor is at the element center. + * SEE: erode, morphologyEx, getStructuringElement */ public static void dilate(Mat src, Mat dst, Mat kernel, Point anchor) { dilate_3(src.nativeObj, dst.nativeObj, kernel.nativeObj, anchor.x, anchor.y); @@ -3804,50 +3893,55 @@ public static void dilate(Mat src, Mat dst, Mat kernel, Point anchor) { /** * Dilates an image by using a specific structuring element. - *

    + * * The function dilates the source image using the specified structuring element that determines the * shape of a pixel neighborhood over which the maximum is taken: * \(\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\) - *

    + * * The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In * case of multi-channel images, each channel is processed independently. * - * @param src input image; the number of channels can be arbitrary, but the depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst output image of the same size and type as src. + * @param src input image; the number of channels can be arbitrary, but the depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst output image of the same size and type as src. * @param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular - * structuring element is used. Kernel can be created using #getStructuringElement - * anchor is at the element center. - * SEE: erode, morphologyEx, getStructuringElement + * structuring element is used. Kernel can be created using #getStructuringElement + * anchor is at the element center. + * SEE: erode, morphologyEx, getStructuringElement */ public static void dilate(Mat src, Mat dst, Mat kernel) { dilate_4(src.nativeObj, dst.nativeObj, kernel.nativeObj); } + + // + // C++: void cv::morphologyEx(Mat src, Mat& dst, int op, Mat kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, Scalar borderValue = morphologyDefaultBorderValue()) + // + /** * Performs advanced morphological transformations. - *

    + * * The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as * basic operations. - *

    + * * Any of the operations can be done in-place. In case of multi-channel images, each channel is * processed independently. * - * @param src Source image. The number of channels can be arbitrary. The depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst Destination image of the same size and type as source image. - * @param op Type of a morphological operation, see #MorphTypes - * @param kernel Structuring element. It can be created using #getStructuringElement. - * @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the - * kernel center. - * @param iterations Number of times erosion and dilation are applied. - * @param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. + * @param src Source image. The number of channels can be arbitrary. The depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst Destination image of the same size and type as source image. + * @param op Type of a morphological operation, see #MorphTypes + * @param kernel Structuring element. It can be created using #getStructuringElement. + * @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the + * kernel center. + * @param iterations Number of times erosion and dilation are applied. + * @param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. * @param borderValue Border value in case of a constant border. The default value has a special - * meaning. - * SEE: dilate, erode, getStructuringElement - * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. - * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply - * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). + * meaning. + * SEE: dilate, erode, getStructuringElement + * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. + * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply + * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). */ public static void morphologyEx(Mat src, Mat dst, int op, Mat kernel, Point anchor, int iterations, int borderType, Scalar borderValue) { morphologyEx_0(src.nativeObj, dst.nativeObj, op, kernel.nativeObj, anchor.x, anchor.y, iterations, borderType, borderValue.val[0], borderValue.val[1], borderValue.val[2], borderValue.val[3]); @@ -3855,59 +3949,54 @@ public static void morphologyEx(Mat src, Mat dst, int op, Mat kernel, Point anch /** * Performs advanced morphological transformations. - *

    + * * The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as * basic operations. - *

    + * * Any of the operations can be done in-place. In case of multi-channel images, each channel is * processed independently. * - * @param src Source image. The number of channels can be arbitrary. The depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst Destination image of the same size and type as source image. - * @param op Type of a morphological operation, see #MorphTypes - * @param kernel Structuring element. It can be created using #getStructuringElement. - * @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the - * kernel center. + * @param src Source image. The number of channels can be arbitrary. The depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst Destination image of the same size and type as source image. + * @param op Type of a morphological operation, see #MorphTypes + * @param kernel Structuring element. It can be created using #getStructuringElement. + * @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the + * kernel center. * @param iterations Number of times erosion and dilation are applied. * @param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. - * meaning. - * SEE: dilate, erode, getStructuringElement - * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. - * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply - * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). + * meaning. + * SEE: dilate, erode, getStructuringElement + * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. + * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply + * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). */ public static void morphologyEx(Mat src, Mat dst, int op, Mat kernel, Point anchor, int iterations, int borderType) { morphologyEx_1(src.nativeObj, dst.nativeObj, op, kernel.nativeObj, anchor.x, anchor.y, iterations, borderType); } - - // - // C++: void cv::morphologyEx(Mat src, Mat& dst, int op, Mat kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, Scalar borderValue = morphologyDefaultBorderValue()) - // - /** * Performs advanced morphological transformations. - *

    + * * The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as * basic operations. - *

    + * * Any of the operations can be done in-place. In case of multi-channel images, each channel is * processed independently. * - * @param src Source image. The number of channels can be arbitrary. The depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst Destination image of the same size and type as source image. - * @param op Type of a morphological operation, see #MorphTypes - * @param kernel Structuring element. It can be created using #getStructuringElement. - * @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the - * kernel center. + * @param src Source image. The number of channels can be arbitrary. The depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst Destination image of the same size and type as source image. + * @param op Type of a morphological operation, see #MorphTypes + * @param kernel Structuring element. It can be created using #getStructuringElement. + * @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the + * kernel center. * @param iterations Number of times erosion and dilation are applied. - * meaning. - * SEE: dilate, erode, getStructuringElement - * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. - * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply - * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). + * meaning. + * SEE: dilate, erode, getStructuringElement + * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. + * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply + * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). */ public static void morphologyEx(Mat src, Mat dst, int op, Mat kernel, Point anchor, int iterations) { morphologyEx_2(src.nativeObj, dst.nativeObj, op, kernel.nativeObj, anchor.x, anchor.y, iterations); @@ -3915,25 +4004,25 @@ public static void morphologyEx(Mat src, Mat dst, int op, Mat kernel, Point anch /** * Performs advanced morphological transformations. - *

    + * * The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as * basic operations. - *

    + * * Any of the operations can be done in-place. In case of multi-channel images, each channel is * processed independently. * - * @param src Source image. The number of channels can be arbitrary. The depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst Destination image of the same size and type as source image. - * @param op Type of a morphological operation, see #MorphTypes + * @param src Source image. The number of channels can be arbitrary. The depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst Destination image of the same size and type as source image. + * @param op Type of a morphological operation, see #MorphTypes * @param kernel Structuring element. It can be created using #getStructuringElement. * @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the - * kernel center. - * meaning. - * SEE: dilate, erode, getStructuringElement - * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. - * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply - * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). + * kernel center. + * meaning. + * SEE: dilate, erode, getStructuringElement + * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. + * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply + * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). */ public static void morphologyEx(Mat src, Mat dst, int op, Mat kernel, Point anchor) { morphologyEx_3(src.nativeObj, dst.nativeObj, op, kernel.nativeObj, anchor.x, anchor.y); @@ -3941,63 +4030,68 @@ public static void morphologyEx(Mat src, Mat dst, int op, Mat kernel, Point anch /** * Performs advanced morphological transformations. - *

    + * * The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as * basic operations. - *

    + * * Any of the operations can be done in-place. In case of multi-channel images, each channel is * processed independently. * - * @param src Source image. The number of channels can be arbitrary. The depth should be one of - * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. - * @param dst Destination image of the same size and type as source image. - * @param op Type of a morphological operation, see #MorphTypes + * @param src Source image. The number of channels can be arbitrary. The depth should be one of + * CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. + * @param dst Destination image of the same size and type as source image. + * @param op Type of a morphological operation, see #MorphTypes * @param kernel Structuring element. It can be created using #getStructuringElement. - * kernel center. - * meaning. - * SEE: dilate, erode, getStructuringElement - * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. - * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply - * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). + * kernel center. + * meaning. + * SEE: dilate, erode, getStructuringElement + * Note: The number of iterations is the number of times erosion or dilatation operation will be applied. + * For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply + * successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). */ public static void morphologyEx(Mat src, Mat dst, int op, Mat kernel) { morphologyEx_4(src.nativeObj, dst.nativeObj, op, kernel.nativeObj); } + + // + // C++: void cv::resize(Mat src, Mat& dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR) + // + /** * Resizes an image. - *

    + * * The function resize resizes the image src down to or up to the specified size. Note that the * initial dst type or size are not taken into account. Instead, the size and type are derived from * the {@code src},{@code dsize},{@code fx}, and {@code fy}. If you want to resize src so that it fits the pre-created dst, * you may call the function as follows: * - * // explicitly specify dsize=dst.size(); fx and fy will be computed from that. - * resize(src, dst, dst.size(), 0, 0, interpolation); + * // explicitly specify dsize=dst.size(); fx and fy will be computed from that. + * resize(src, dst, dst.size(), 0, 0, interpolation); * * If you want to decimate the image by factor of 2 in each direction, you can call the function this * way: * - * // specify fx and fy and let the function compute the destination image size. - * resize(src, dst, Size(), 0.5, 0.5, interpolation); + * // specify fx and fy and let the function compute the destination image size. + * resize(src, dst, Size(), 0.5, 0.5, interpolation); * * To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to * enlarge an image, it will generally look best with #INTER_CUBIC (slow) or #INTER_LINEAR * (faster but still looks OK). * - * @param src input image. - * @param dst output image; it has the size dsize (when it is non-zero) or the size computed from - * src.size(), fx, and fy; the type of dst is the same as of src. - * @param dsize output image size; if it equals zero ({@code None} in Python), it is computed as: - * \(\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\) - * Either dsize or both fx and fy must be non-zero. - * @param fx scale factor along the horizontal axis; when it equals 0, it is computed as - * \(\texttt{(double)dsize.width/src.cols}\) - * @param fy scale factor along the vertical axis; when it equals 0, it is computed as - * \(\texttt{(double)dsize.height/src.rows}\) + * @param src input image. + * @param dst output image; it has the size dsize (when it is non-zero) or the size computed from + * src.size(), fx, and fy; the type of dst is the same as of src. + * @param dsize output image size; if it equals zero ({@code None} in Python), it is computed as: + * \(\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\) + * Either dsize or both fx and fy must be non-zero. + * @param fx scale factor along the horizontal axis; when it equals 0, it is computed as + * \(\texttt{(double)dsize.width/src.cols}\) + * @param fy scale factor along the vertical axis; when it equals 0, it is computed as + * \(\texttt{(double)dsize.height/src.rows}\) * @param interpolation interpolation method, see #InterpolationFlags - *

    - * SEE: warpAffine, warpPerspective, remap + * + * SEE: warpAffine, warpPerspective, remap */ public static void resize(Mat src, Mat dst, Size dsize, double fx, double fy, int interpolation) { resize_0(src.nativeObj, dst.nativeObj, dsize.width, dsize.height, fx, fy, interpolation); @@ -4005,79 +4099,74 @@ public static void resize(Mat src, Mat dst, Size dsize, double fx, double fy, in /** * Resizes an image. - *

    + * * The function resize resizes the image src down to or up to the specified size. Note that the * initial dst type or size are not taken into account. Instead, the size and type are derived from * the {@code src},{@code dsize},{@code fx}, and {@code fy}. If you want to resize src so that it fits the pre-created dst, * you may call the function as follows: * - * // explicitly specify dsize=dst.size(); fx and fy will be computed from that. - * resize(src, dst, dst.size(), 0, 0, interpolation); + * // explicitly specify dsize=dst.size(); fx and fy will be computed from that. + * resize(src, dst, dst.size(), 0, 0, interpolation); * * If you want to decimate the image by factor of 2 in each direction, you can call the function this * way: * - * // specify fx and fy and let the function compute the destination image size. - * resize(src, dst, Size(), 0.5, 0.5, interpolation); + * // specify fx and fy and let the function compute the destination image size. + * resize(src, dst, Size(), 0.5, 0.5, interpolation); * * To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to * enlarge an image, it will generally look best with #INTER_CUBIC (slow) or #INTER_LINEAR * (faster but still looks OK). * - * @param src input image. - * @param dst output image; it has the size dsize (when it is non-zero) or the size computed from - * src.size(), fx, and fy; the type of dst is the same as of src. + * @param src input image. + * @param dst output image; it has the size dsize (when it is non-zero) or the size computed from + * src.size(), fx, and fy; the type of dst is the same as of src. * @param dsize output image size; if it equals zero ({@code None} in Python), it is computed as: - * \(\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\) - * Either dsize or both fx and fy must be non-zero. - * @param fx scale factor along the horizontal axis; when it equals 0, it is computed as - * \(\texttt{(double)dsize.width/src.cols}\) - * @param fy scale factor along the vertical axis; when it equals 0, it is computed as - * \(\texttt{(double)dsize.height/src.rows}\) - *

    - * SEE: warpAffine, warpPerspective, remap + * \(\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\) + * Either dsize or both fx and fy must be non-zero. + * @param fx scale factor along the horizontal axis; when it equals 0, it is computed as + * \(\texttt{(double)dsize.width/src.cols}\) + * @param fy scale factor along the vertical axis; when it equals 0, it is computed as + * \(\texttt{(double)dsize.height/src.rows}\) + * + * SEE: warpAffine, warpPerspective, remap */ public static void resize(Mat src, Mat dst, Size dsize, double fx, double fy) { resize_1(src.nativeObj, dst.nativeObj, dsize.width, dsize.height, fx, fy); } - - // - // C++: void cv::resize(Mat src, Mat& dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR) - // - /** * Resizes an image. - *

    + * * The function resize resizes the image src down to or up to the specified size. Note that the * initial dst type or size are not taken into account. Instead, the size and type are derived from * the {@code src},{@code dsize},{@code fx}, and {@code fy}. If you want to resize src so that it fits the pre-created dst, * you may call the function as follows: * - * // explicitly specify dsize=dst.size(); fx and fy will be computed from that. - * resize(src, dst, dst.size(), 0, 0, interpolation); + * // explicitly specify dsize=dst.size(); fx and fy will be computed from that. + * resize(src, dst, dst.size(), 0, 0, interpolation); * * If you want to decimate the image by factor of 2 in each direction, you can call the function this * way: * - * // specify fx and fy and let the function compute the destination image size. - * resize(src, dst, Size(), 0.5, 0.5, interpolation); + * // specify fx and fy and let the function compute the destination image size. + * resize(src, dst, Size(), 0.5, 0.5, interpolation); * * To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to * enlarge an image, it will generally look best with #INTER_CUBIC (slow) or #INTER_LINEAR * (faster but still looks OK). * - * @param src input image. - * @param dst output image; it has the size dsize (when it is non-zero) or the size computed from - * src.size(), fx, and fy; the type of dst is the same as of src. + * @param src input image. + * @param dst output image; it has the size dsize (when it is non-zero) or the size computed from + * src.size(), fx, and fy; the type of dst is the same as of src. * @param dsize output image size; if it equals zero ({@code None} in Python), it is computed as: - * \(\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\) - * Either dsize or both fx and fy must be non-zero. - * @param fx scale factor along the horizontal axis; when it equals 0, it is computed as - * \(\texttt{(double)dsize.width/src.cols}\) - * \(\texttt{(double)dsize.height/src.rows}\) - *

    - * SEE: warpAffine, warpPerspective, remap + * \(\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\) + * Either dsize or both fx and fy must be non-zero. + * @param fx scale factor along the horizontal axis; when it equals 0, it is computed as + * \(\texttt{(double)dsize.width/src.cols}\) + * \(\texttt{(double)dsize.height/src.rows}\) + * + * SEE: warpAffine, warpPerspective, remap */ public static void resize(Mat src, Mat dst, Size dsize, double fx) { resize_2(src.nativeObj, dst.nativeObj, dsize.width, dsize.height, fx); @@ -4085,64 +4174,69 @@ public static void resize(Mat src, Mat dst, Size dsize, double fx) { /** * Resizes an image. - *

    + * * The function resize resizes the image src down to or up to the specified size. Note that the * initial dst type or size are not taken into account. Instead, the size and type are derived from * the {@code src},{@code dsize},{@code fx}, and {@code fy}. If you want to resize src so that it fits the pre-created dst, * you may call the function as follows: * - * // explicitly specify dsize=dst.size(); fx and fy will be computed from that. - * resize(src, dst, dst.size(), 0, 0, interpolation); + * // explicitly specify dsize=dst.size(); fx and fy will be computed from that. + * resize(src, dst, dst.size(), 0, 0, interpolation); * * If you want to decimate the image by factor of 2 in each direction, you can call the function this * way: * - * // specify fx and fy and let the function compute the destination image size. - * resize(src, dst, Size(), 0.5, 0.5, interpolation); + * // specify fx and fy and let the function compute the destination image size. + * resize(src, dst, Size(), 0.5, 0.5, interpolation); * * To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to * enlarge an image, it will generally look best with #INTER_CUBIC (slow) or #INTER_LINEAR * (faster but still looks OK). * - * @param src input image. - * @param dst output image; it has the size dsize (when it is non-zero) or the size computed from - * src.size(), fx, and fy; the type of dst is the same as of src. + * @param src input image. + * @param dst output image; it has the size dsize (when it is non-zero) or the size computed from + * src.size(), fx, and fy; the type of dst is the same as of src. * @param dsize output image size; if it equals zero ({@code None} in Python), it is computed as: - * \(\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\) - * Either dsize or both fx and fy must be non-zero. - * \(\texttt{(double)dsize.width/src.cols}\) - * \(\texttt{(double)dsize.height/src.rows}\) - *

    - * SEE: warpAffine, warpPerspective, remap + * \(\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\) + * Either dsize or both fx and fy must be non-zero. + * \(\texttt{(double)dsize.width/src.cols}\) + * \(\texttt{(double)dsize.height/src.rows}\) + * + * SEE: warpAffine, warpPerspective, remap */ public static void resize(Mat src, Mat dst, Size dsize) { resize_3(src.nativeObj, dst.nativeObj, dsize.width, dsize.height); } + + // + // C++: void cv::warpAffine(Mat src, Mat& dst, Mat M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar()) + // + /** * Applies an affine transformation to an image. - *

    + * * The function warpAffine transforms the source image using the specified matrix: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\) - *

    + * * when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted * with #invertAffineTransform and then put in the formula above instead of M. The function cannot * operate in-place. * - * @param src input image. - * @param dst output image that has the size dsize and the same type as src . - * @param M \(2\times 3\) transformation matrix. - * @param dsize size of the output image. - * @param flags combination of interpolation methods (see #InterpolationFlags) and the optional - * flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( - * \(\texttt{dst}\rightarrow\texttt{src}\) ). - * @param borderMode pixel extrapolation method (see #BorderTypes); when - * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to - * the "outliers" in the source image are not modified by the function. + * @param src input image. + * @param dst output image that has the size dsize and the same type as src . + * @param M \(2\times 3\) transformation matrix. + * @param dsize size of the output image. + * @param flags combination of interpolation methods (see #InterpolationFlags) and the optional + * flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( + * \(\texttt{dst}\rightarrow\texttt{src}\) ). + * @param borderMode pixel extrapolation method (see #BorderTypes); when + * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to + * the "outliers" in the source image are not modified by the function. * @param borderValue value used in case of a constant border; by default, it is 0. - *

    - * SEE: warpPerspective, resize, remap, getRectSubPix, transform + * + * SEE: warpPerspective, resize, remap, getRectSubPix, transform */ public static void warpAffine(Mat src, Mat dst, Mat M, Size dsize, int flags, int borderMode, Scalar borderValue) { warpAffine_0(src.nativeObj, dst.nativeObj, M.nativeObj, dsize.width, dsize.height, flags, borderMode, borderValue.val[0], borderValue.val[1], borderValue.val[2], borderValue.val[3]); @@ -4150,59 +4244,54 @@ public static void warpAffine(Mat src, Mat dst, Mat M, Size dsize, int flags, in /** * Applies an affine transformation to an image. - *

    + * * The function warpAffine transforms the source image using the specified matrix: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\) - *

    + * * when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted * with #invertAffineTransform and then put in the formula above instead of M. The function cannot * operate in-place. * - * @param src input image. - * @param dst output image that has the size dsize and the same type as src . - * @param M \(2\times 3\) transformation matrix. - * @param dsize size of the output image. - * @param flags combination of interpolation methods (see #InterpolationFlags) and the optional - * flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( - * \(\texttt{dst}\rightarrow\texttt{src}\) ). + * @param src input image. + * @param dst output image that has the size dsize and the same type as src . + * @param M \(2\times 3\) transformation matrix. + * @param dsize size of the output image. + * @param flags combination of interpolation methods (see #InterpolationFlags) and the optional + * flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( + * \(\texttt{dst}\rightarrow\texttt{src}\) ). * @param borderMode pixel extrapolation method (see #BorderTypes); when - * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to - * the "outliers" in the source image are not modified by the function. - *

    - * SEE: warpPerspective, resize, remap, getRectSubPix, transform + * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to + * the "outliers" in the source image are not modified by the function. + * + * SEE: warpPerspective, resize, remap, getRectSubPix, transform */ public static void warpAffine(Mat src, Mat dst, Mat M, Size dsize, int flags, int borderMode) { warpAffine_1(src.nativeObj, dst.nativeObj, M.nativeObj, dsize.width, dsize.height, flags, borderMode); } - - // - // C++: void cv::warpAffine(Mat src, Mat& dst, Mat M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar()) - // - /** * Applies an affine transformation to an image. - *

    + * * The function warpAffine transforms the source image using the specified matrix: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\) - *

    + * * when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted * with #invertAffineTransform and then put in the formula above instead of M. The function cannot * operate in-place. * - * @param src input image. - * @param dst output image that has the size dsize and the same type as src . - * @param M \(2\times 3\) transformation matrix. + * @param src input image. + * @param dst output image that has the size dsize and the same type as src . + * @param M \(2\times 3\) transformation matrix. * @param dsize size of the output image. * @param flags combination of interpolation methods (see #InterpolationFlags) and the optional - * flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( - * \(\texttt{dst}\rightarrow\texttt{src}\) ). - * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to - * the "outliers" in the source image are not modified by the function. - *

    - * SEE: warpPerspective, resize, remap, getRectSubPix, transform + * flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( + * \(\texttt{dst}\rightarrow\texttt{src}\) ). + * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to + * the "outliers" in the source image are not modified by the function. + * + * SEE: warpPerspective, resize, remap, getRectSubPix, transform */ public static void warpAffine(Mat src, Mat dst, Mat M, Size dsize, int flags) { warpAffine_2(src.nativeObj, dst.nativeObj, M.nativeObj, dsize.width, dsize.height, flags); @@ -4210,52 +4299,57 @@ public static void warpAffine(Mat src, Mat dst, Mat M, Size dsize, int flags) { /** * Applies an affine transformation to an image. - *

    + * * The function warpAffine transforms the source image using the specified matrix: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\) - *

    + * * when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted * with #invertAffineTransform and then put in the formula above instead of M. The function cannot * operate in-place. * - * @param src input image. - * @param dst output image that has the size dsize and the same type as src . - * @param M \(2\times 3\) transformation matrix. + * @param src input image. + * @param dst output image that has the size dsize and the same type as src . + * @param M \(2\times 3\) transformation matrix. * @param dsize size of the output image. - * flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( - * \(\texttt{dst}\rightarrow\texttt{src}\) ). - * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to - * the "outliers" in the source image are not modified by the function. - *

    - * SEE: warpPerspective, resize, remap, getRectSubPix, transform + * flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( + * \(\texttt{dst}\rightarrow\texttt{src}\) ). + * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to + * the "outliers" in the source image are not modified by the function. + * + * SEE: warpPerspective, resize, remap, getRectSubPix, transform */ public static void warpAffine(Mat src, Mat dst, Mat M, Size dsize) { warpAffine_3(src.nativeObj, dst.nativeObj, M.nativeObj, dsize.width, dsize.height); } + + // + // C++: void cv::warpPerspective(Mat src, Mat& dst, Mat M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar()) + // + /** * Applies a perspective transformation to an image. - *

    + * * The function warpPerspective transforms the source image using the specified matrix: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , - * \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\) - *

    + * \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\) + * * when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert * and then put in the formula above instead of M. The function cannot operate in-place. * - * @param src input image. - * @param dst output image that has the size dsize and the same type as src . - * @param M \(3\times 3\) transformation matrix. - * @param dsize size of the output image. - * @param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the - * optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( - * \(\texttt{dst}\rightarrow\texttt{src}\) ). - * @param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). + * @param src input image. + * @param dst output image that has the size dsize and the same type as src . + * @param M \(3\times 3\) transformation matrix. + * @param dsize size of the output image. + * @param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the + * optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( + * \(\texttt{dst}\rightarrow\texttt{src}\) ). + * @param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). * @param borderValue value used in case of a constant border; by default, it equals 0. - *

    - * SEE: warpAffine, resize, remap, getRectSubPix, perspectiveTransform + * + * SEE: warpAffine, resize, remap, getRectSubPix, perspectiveTransform */ public static void warpPerspective(Mat src, Mat dst, Mat M, Size dsize, int flags, int borderMode, Scalar borderValue) { warpPerspective_0(src.nativeObj, dst.nativeObj, M.nativeObj, dsize.width, dsize.height, flags, borderMode, borderValue.val[0], borderValue.val[1], borderValue.val[2], borderValue.val[3]); @@ -4263,55 +4357,50 @@ public static void warpPerspective(Mat src, Mat dst, Mat M, Size dsize, int flag /** * Applies a perspective transformation to an image. - *

    + * * The function warpPerspective transforms the source image using the specified matrix: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , - * \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\) - *

    + * \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\) + * * when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert * and then put in the formula above instead of M. The function cannot operate in-place. * - * @param src input image. - * @param dst output image that has the size dsize and the same type as src . - * @param M \(3\times 3\) transformation matrix. - * @param dsize size of the output image. - * @param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the - * optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( - * \(\texttt{dst}\rightarrow\texttt{src}\) ). + * @param src input image. + * @param dst output image that has the size dsize and the same type as src . + * @param M \(3\times 3\) transformation matrix. + * @param dsize size of the output image. + * @param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the + * optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( + * \(\texttt{dst}\rightarrow\texttt{src}\) ). * @param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). - *

    - * SEE: warpAffine, resize, remap, getRectSubPix, perspectiveTransform + * + * SEE: warpAffine, resize, remap, getRectSubPix, perspectiveTransform */ public static void warpPerspective(Mat src, Mat dst, Mat M, Size dsize, int flags, int borderMode) { warpPerspective_1(src.nativeObj, dst.nativeObj, M.nativeObj, dsize.width, dsize.height, flags, borderMode); } - - // - // C++: void cv::warpPerspective(Mat src, Mat& dst, Mat M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar()) - // - /** * Applies a perspective transformation to an image. - *

    + * * The function warpPerspective transforms the source image using the specified matrix: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , - * \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\) - *

    + * \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\) + * * when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert * and then put in the formula above instead of M. The function cannot operate in-place. * - * @param src input image. - * @param dst output image that has the size dsize and the same type as src . - * @param M \(3\times 3\) transformation matrix. + * @param src input image. + * @param dst output image that has the size dsize and the same type as src . + * @param M \(3\times 3\) transformation matrix. * @param dsize size of the output image. * @param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the - * optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( - * \(\texttt{dst}\rightarrow\texttt{src}\) ). - *

    - * SEE: warpAffine, resize, remap, getRectSubPix, perspectiveTransform + * optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( + * \(\texttt{dst}\rightarrow\texttt{src}\) ). + * + * SEE: warpAffine, resize, remap, getRectSubPix, perspectiveTransform */ public static void warpPerspective(Mat src, Mat dst, Mat M, Size dsize, int flags) { warpPerspective_2(src.nativeObj, dst.nativeObj, M.nativeObj, dsize.width, dsize.height, flags); @@ -4319,35 +4408,40 @@ public static void warpPerspective(Mat src, Mat dst, Mat M, Size dsize, int flag /** * Applies a perspective transformation to an image. - *

    + * * The function warpPerspective transforms the source image using the specified matrix: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , - * \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\) - *

    + * \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\) + * * when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert * and then put in the formula above instead of M. The function cannot operate in-place. * - * @param src input image. - * @param dst output image that has the size dsize and the same type as src . - * @param M \(3\times 3\) transformation matrix. + * @param src input image. + * @param dst output image that has the size dsize and the same type as src . + * @param M \(3\times 3\) transformation matrix. * @param dsize size of the output image. - * optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( - * \(\texttt{dst}\rightarrow\texttt{src}\) ). - *

    - * SEE: warpAffine, resize, remap, getRectSubPix, perspectiveTransform + * optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( + * \(\texttt{dst}\rightarrow\texttt{src}\) ). + * + * SEE: warpAffine, resize, remap, getRectSubPix, perspectiveTransform */ public static void warpPerspective(Mat src, Mat dst, Mat M, Size dsize) { warpPerspective_3(src.nativeObj, dst.nativeObj, M.nativeObj, dsize.width, dsize.height); } + + // + // C++: void cv::remap(Mat src, Mat& dst, Mat map1, Mat map2, int interpolation, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar()) + // + /** * Applies a generic geometrical transformation to an image. - *

    + * * The function remap transforms the source image using the specified map: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\) - *

    + * * where values of pixels with non-integer coordinates are computed using one of available * interpolation methods. \(map_x\) and \(map_y\) can be encoded as separate floating-point maps * in \(map_1\) and \(map_2\) respectively, or interleaved floating-point maps of \((x,y)\) in @@ -4355,24 +4449,24 @@ public static void warpPerspective(Mat src, Mat dst, Mat M, Size dsize) { * convert from floating to fixed-point representations of a map is that they can yield much faster * (\~2x) remapping operations. In the converted case, \(map_1\) contains pairs (cvFloor(x), * cvFloor(y)) and \(map_2\) contains indices in a table of interpolation coefficients. - *

    + * * This function cannot operate in-place. * - * @param src Source image. - * @param dst Destination image. It has the same size as map1 and the same type as src . - * @param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , - * CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point - * representation to fixed-point for speed. - * @param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map - * if map1 is (x,y) points), respectively. + * @param src Source image. + * @param dst Destination image. It has the same size as map1 and the same type as src . + * @param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , + * CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point + * representation to fixed-point for speed. + * @param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map + * if map1 is (x,y) points), respectively. * @param interpolation Interpolation method (see #InterpolationFlags). The methods #INTER_AREA - * and #INTER_LINEAR_EXACT are not supported by this function. - * @param borderMode Pixel extrapolation method (see #BorderTypes). When - * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that - * corresponds to the "outliers" in the source image are not modified by the function. - * @param borderValue Value used in case of a constant border. By default, it is 0. - * Note: - * Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + * and #INTER_LINEAR_EXACT are not supported by this function. + * @param borderMode Pixel extrapolation method (see #BorderTypes). When + * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that + * corresponds to the "outliers" in the source image are not modified by the function. + * @param borderValue Value used in case of a constant border. By default, it is 0. + * Note: + * Due to current implementation limitations the size of an input and output images should be less than 32767x32767. */ public static void remap(Mat src, Mat dst, Mat map1, Mat map2, int interpolation, int borderMode, Scalar borderValue) { remap_0(src.nativeObj, dst.nativeObj, map1.nativeObj, map2.nativeObj, interpolation, borderMode, borderValue.val[0], borderValue.val[1], borderValue.val[2], borderValue.val[3]); @@ -4380,11 +4474,11 @@ public static void remap(Mat src, Mat dst, Mat map1, Mat map2, int interpolation /** * Applies a generic geometrical transformation to an image. - *

    + * * The function remap transforms the source image using the specified map: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\) - *

    + * * where values of pixels with non-integer coordinates are computed using one of available * interpolation methods. \(map_x\) and \(map_y\) can be encoded as separate floating-point maps * in \(map_1\) and \(map_2\) respectively, or interleaved floating-point maps of \((x,y)\) in @@ -4392,40 +4486,35 @@ public static void remap(Mat src, Mat dst, Mat map1, Mat map2, int interpolation * convert from floating to fixed-point representations of a map is that they can yield much faster * (\~2x) remapping operations. In the converted case, \(map_1\) contains pairs (cvFloor(x), * cvFloor(y)) and \(map_2\) contains indices in a table of interpolation coefficients. - *

    + * * This function cannot operate in-place. * - * @param src Source image. - * @param dst Destination image. It has the same size as map1 and the same type as src . - * @param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , - * CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point - * representation to fixed-point for speed. - * @param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map - * if map1 is (x,y) points), respectively. + * @param src Source image. + * @param dst Destination image. It has the same size as map1 and the same type as src . + * @param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , + * CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point + * representation to fixed-point for speed. + * @param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map + * if map1 is (x,y) points), respectively. * @param interpolation Interpolation method (see #InterpolationFlags). The methods #INTER_AREA - * and #INTER_LINEAR_EXACT are not supported by this function. - * @param borderMode Pixel extrapolation method (see #BorderTypes). When - * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that - * corresponds to the "outliers" in the source image are not modified by the function. - * Note: - * Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + * and #INTER_LINEAR_EXACT are not supported by this function. + * @param borderMode Pixel extrapolation method (see #BorderTypes). When + * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that + * corresponds to the "outliers" in the source image are not modified by the function. + * Note: + * Due to current implementation limitations the size of an input and output images should be less than 32767x32767. */ public static void remap(Mat src, Mat dst, Mat map1, Mat map2, int interpolation, int borderMode) { remap_1(src.nativeObj, dst.nativeObj, map1.nativeObj, map2.nativeObj, interpolation, borderMode); } - - // - // C++: void cv::remap(Mat src, Mat& dst, Mat map1, Mat map2, int interpolation, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar()) - // - /** * Applies a generic geometrical transformation to an image. - *

    + * * The function remap transforms the source image using the specified map: - *

    + * * \(\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\) - *

    + * * where values of pixels with non-integer coordinates are computed using one of available * interpolation methods. \(map_x\) and \(map_y\) can be encoded as separate floating-point maps * in \(map_1\) and \(map_2\) respectively, or interleaved floating-point maps of \((x,y)\) in @@ -4433,30 +4522,35 @@ public static void remap(Mat src, Mat dst, Mat map1, Mat map2, int interpolation * convert from floating to fixed-point representations of a map is that they can yield much faster * (\~2x) remapping operations. In the converted case, \(map_1\) contains pairs (cvFloor(x), * cvFloor(y)) and \(map_2\) contains indices in a table of interpolation coefficients. - *

    + * * This function cannot operate in-place. * - * @param src Source image. - * @param dst Destination image. It has the same size as map1 and the same type as src . - * @param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , - * CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point - * representation to fixed-point for speed. - * @param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map - * if map1 is (x,y) points), respectively. + * @param src Source image. + * @param dst Destination image. It has the same size as map1 and the same type as src . + * @param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , + * CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point + * representation to fixed-point for speed. + * @param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map + * if map1 is (x,y) points), respectively. * @param interpolation Interpolation method (see #InterpolationFlags). The methods #INTER_AREA - * and #INTER_LINEAR_EXACT are not supported by this function. - * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that - * corresponds to the "outliers" in the source image are not modified by the function. - * Note: - * Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + * and #INTER_LINEAR_EXACT are not supported by this function. + * borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that + * corresponds to the "outliers" in the source image are not modified by the function. + * Note: + * Due to current implementation limitations the size of an input and output images should be less than 32767x32767. */ public static void remap(Mat src, Mat dst, Mat map1, Mat map2, int interpolation) { remap_2(src.nativeObj, dst.nativeObj, map1.nativeObj, map2.nativeObj, interpolation); } + + // + // C++: void cv::convertMaps(Mat map1, Mat map2, Mat& dstmap1, Mat& dstmap2, int dstmap1type, bool nninterpolation = false) + // + /** * Converts image transformation maps from one representation to another. - *

    + * * The function converts a pair of maps for remap from one representation to another. The following * options ( (map1.type(), map2.type()) \(\rightarrow\) (dstmap1.type(), dstmap2.type()) ) are * supported: @@ -4485,17 +4579,17 @@ public static void remap(Mat src, Mat dst, Mat map1, Mat map2, int interpolation * * * - * @param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . - * @param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), - * respectively. - * @param dstmap1 The first output map that has the type dstmap1type and the same size as src . - * @param dstmap2 The second output map. - * @param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or - * CV_32FC2 . + * @param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . + * @param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), + * respectively. + * @param dstmap1 The first output map that has the type dstmap1type and the same size as src . + * @param dstmap2 The second output map. + * @param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or + * CV_32FC2 . * @param nninterpolation Flag indicating whether the fixed-point maps are used for the - * nearest-neighbor or for a more complex interpolation. - *

    - * SEE: remap, undistort, initUndistortRectifyMap + * nearest-neighbor or for a more complex interpolation. + * + * SEE: remap, undistort, initUndistortRectifyMap */ public static void convertMaps(Mat map1, Mat map2, Mat dstmap1, Mat dstmap2, int dstmap1type, boolean nninterpolation) { convertMaps_0(map1.nativeObj, map2.nativeObj, dstmap1.nativeObj, dstmap2.nativeObj, dstmap1type, nninterpolation); @@ -4503,7 +4597,7 @@ public static void convertMaps(Mat map1, Mat map2, Mat dstmap1, Mat dstmap2, int /** * Converts image transformation maps from one representation to another. - *

    + * * The function converts a pair of maps for remap from one representation to another. The following * options ( (map1.type(), map2.type()) \(\rightarrow\) (dstmap1.type(), dstmap2.type()) ) are * supported: @@ -4532,16 +4626,16 @@ public static void convertMaps(Mat map1, Mat map2, Mat dstmap1, Mat dstmap2, int * * * - * @param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . - * @param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), - * respectively. - * @param dstmap1 The first output map that has the type dstmap1type and the same size as src . - * @param dstmap2 The second output map. + * @param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . + * @param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), + * respectively. + * @param dstmap1 The first output map that has the type dstmap1type and the same size as src . + * @param dstmap2 The second output map. * @param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or - * CV_32FC2 . - * nearest-neighbor or for a more complex interpolation. - *

    - * SEE: remap, undistort, initUndistortRectifyMap + * CV_32FC2 . + * nearest-neighbor or for a more complex interpolation. + * + * SEE: remap, undistort, initUndistortRectifyMap */ public static void convertMaps(Mat map1, Mat map2, Mat dstmap1, Mat dstmap2, int dstmap1type) { convertMaps_1(map1.nativeObj, map2.nativeObj, dstmap1.nativeObj, dstmap2.nativeObj, dstmap1type); @@ -4549,44 +4643,49 @@ public static void convertMaps(Mat map1, Mat map2, Mat dstmap1, Mat dstmap2, int // - // C++: void cv::convertMaps(Mat map1, Mat map2, Mat& dstmap1, Mat& dstmap2, int dstmap1type, bool nninterpolation = false) + // C++: Mat cv::getRotationMatrix2D(Point2f center, double angle, double scale) // /** * Calculates an affine matrix of 2D rotation. - *

    + * * The function calculates the following matrix: - *

    + * * \(\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}\) - *

    + * * where - *

    + * * \(\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}\) - *

    + * * The transformation maps the rotation center to itself. If this is not the target, adjust the shift. * * @param center Center of the rotation in the source image. - * @param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the - * coordinate origin is assumed to be the top-left corner). - * @param scale Isotropic scale factor. - *

    - * SEE: getAffineTransform, warpAffine, transform + * @param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the + * coordinate origin is assumed to be the top-left corner). + * @param scale Isotropic scale factor. + * + * SEE: getAffineTransform, warpAffine, transform * @return automatically generated */ public static Mat getRotationMatrix2D(Point center, double angle, double scale) { return new Mat(getRotationMatrix2D_0(center.x, center.y, angle, scale)); } + + // + // C++: void cv::invertAffineTransform(Mat M, Mat& iM) + // + /** * Inverts an affine transformation. - *

    + * * The function computes an inverse affine transformation represented by \(2 \times 3\) matrix M: - *

    + * * \(\begin{bmatrix} a_{11} & a_{12} & b_1 \\ a_{21} & a_{22} & b_2 \end{bmatrix}\) - *

    + * * The result is also a \(2 \times 3\) matrix of the same type as M. * - * @param M Original affine transformation. + * @param M Original affine transformation. * @param iM Output reverse affine transformation. */ public static void invertAffineTransform(Mat M, Mat iM) { @@ -4595,51 +4694,46 @@ public static void invertAffineTransform(Mat M, Mat iM) { // - // C++: Mat cv::getRotationMatrix2D(Point2f center, double angle, double scale) + // C++: Mat cv::getPerspectiveTransform(Mat src, Mat dst, int solveMethod = DECOMP_LU) // /** * Calculates a perspective transform from four pairs of the corresponding points. - *

    + * * The function calculates the \(3 \times 3\) matrix of a perspective transform so that: - *

    + * * \(\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\) - *

    + * * where - *

    + * * \(dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\) * - * @param src Coordinates of quadrangle vertices in the source image. - * @param dst Coordinates of the corresponding quadrangle vertices in the destination image. + * @param src Coordinates of quadrangle vertices in the source image. + * @param dst Coordinates of the corresponding quadrangle vertices in the destination image. * @param solveMethod method passed to cv::solve (#DecompTypes) - *

    - * SEE: findHomography, warpPerspective, perspectiveTransform + * + * SEE: findHomography, warpPerspective, perspectiveTransform * @return automatically generated */ public static Mat getPerspectiveTransform(Mat src, Mat dst, int solveMethod) { return new Mat(getPerspectiveTransform_0(src.nativeObj, dst.nativeObj, solveMethod)); } - - // - // C++: void cv::invertAffineTransform(Mat M, Mat& iM) - // - /** * Calculates a perspective transform from four pairs of the corresponding points. - *

    + * * The function calculates the \(3 \times 3\) matrix of a perspective transform so that: - *

    + * * \(\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\) - *

    + * * where - *

    + * * \(dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\) * * @param src Coordinates of quadrangle vertices in the source image. * @param dst Coordinates of the corresponding quadrangle vertices in the destination image. - *

    - * SEE: findHomography, warpPerspective, perspectiveTransform + * + * SEE: findHomography, warpPerspective, perspectiveTransform * @return automatically generated */ public static Mat getPerspectiveTransform(Mat src, Mat dst) { @@ -4648,7 +4742,7 @@ public static Mat getPerspectiveTransform(Mat src, Mat dst) { // - // C++: Mat cv::getPerspectiveTransform(Mat src, Mat dst, int solveMethod = DECOMP_LU) + // C++: Mat cv::getAffineTransform(vector_Point2f src, vector_Point2f dst) // public static Mat getAffineTransform(MatOfPoint2f src, MatOfPoint2f dst) { @@ -4657,55 +4751,55 @@ public static Mat getAffineTransform(MatOfPoint2f src, MatOfPoint2f dst) { return new Mat(getAffineTransform_0(src_mat.nativeObj, dst_mat.nativeObj)); } + + // + // C++: void cv::getRectSubPix(Mat image, Size patchSize, Point2f center, Mat& patch, int patchType = -1) + // + /** * Retrieves a pixel rectangle from an image with sub-pixel accuracy. - *

    + * * The function getRectSubPix extracts pixels from src: - *

    + * * \(patch(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\) - *

    + * * where the values of the pixels at non-integer coordinates are retrieved using bilinear * interpolation. Every channel of multi-channel images is processed independently. Also * the image should be a single channel or three channel image. While the center of the * rectangle must be inside the image, parts of the rectangle may be outside. * - * @param image Source image. + * @param image Source image. * @param patchSize Size of the extracted patch. - * @param center Floating point coordinates of the center of the extracted rectangle within the - * source image. The center must be inside the image. - * @param patch Extracted patch that has the size patchSize and the same number of channels as src . + * @param center Floating point coordinates of the center of the extracted rectangle within the + * source image. The center must be inside the image. + * @param patch Extracted patch that has the size patchSize and the same number of channels as src . * @param patchType Depth of the extracted pixels. By default, they have the same depth as src . - *

    - * SEE: warpAffine, warpPerspective + * + * SEE: warpAffine, warpPerspective */ public static void getRectSubPix(Mat image, Size patchSize, Point center, Mat patch, int patchType) { getRectSubPix_0(image.nativeObj, patchSize.width, patchSize.height, center.x, center.y, patch.nativeObj, patchType); } - - // - // C++: Mat cv::getAffineTransform(vector_Point2f src, vector_Point2f dst) - // - /** * Retrieves a pixel rectangle from an image with sub-pixel accuracy. - *

    + * * The function getRectSubPix extracts pixels from src: - *

    + * * \(patch(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\) - *

    + * * where the values of the pixels at non-integer coordinates are retrieved using bilinear * interpolation. Every channel of multi-channel images is processed independently. Also * the image should be a single channel or three channel image. While the center of the * rectangle must be inside the image, parts of the rectangle may be outside. * - * @param image Source image. + * @param image Source image. * @param patchSize Size of the extracted patch. - * @param center Floating point coordinates of the center of the extracted rectangle within the - * source image. The center must be inside the image. - * @param patch Extracted patch that has the size patchSize and the same number of channels as src . - *

    - * SEE: warpAffine, warpPerspective + * @param center Floating point coordinates of the center of the extracted rectangle within the + * source image. The center must be inside the image. + * @param patch Extracted patch that has the size patchSize and the same number of channels as src . + * + * SEE: warpAffine, warpPerspective */ public static void getRectSubPix(Mat image, Size patchSize, Point center, Mat patch) { getRectSubPix_1(image.nativeObj, patchSize.width, patchSize.height, center.x, center.y, patch.nativeObj); @@ -4713,100 +4807,107 @@ public static void getRectSubPix(Mat image, Size patchSize, Point center, Mat pa // - // C++: void cv::getRectSubPix(Mat image, Size patchSize, Point2f center, Mat& patch, int patchType = -1) + // C++: void cv::logPolar(Mat src, Mat& dst, Point2f center, double M, int flags) // /** * Remaps an image to semilog-polar coordinates space. * - * @param src Source image - * @param dst Destination image. It will have same size and type as src. - * @param center The transformation center; where the output precision is maximal - * @param M Magnitude scale parameter. It determines the radius of the bounding circle to transform too. - * @param flags A combination of interpolation methods, see #InterpolationFlags - * - * Note: - *

      - *
    • - * The function can not operate in-place. - *
    • - *
    • - * To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. - *
    • - *
    - *

    - * SEE: cv::linearPolar * @deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags+WARP_POLAR_LOG); - *

    - *

    + * + * * Transform the source image using the following transformation (See REF: polar_remaps_reference_image "Polar remaps reference image d)"): * \(\begin{array}{l} - * dst( \rho , \phi ) = src(x,y) \\ - * dst.size() \leftarrow src.size() + * dst( \rho , \phi ) = src(x,y) \\ + * dst.size() \leftarrow src.size() * \end{array}\) - *

    + * * where * \(\begin{array}{l} - * I = (dx,dy) = (x - center.x,y - center.y) \\ - * \rho = M \cdot log_e(\texttt{magnitude} (I)) ,\\ - * \phi = Kangle \cdot \texttt{angle} (I) \\ + * I = (dx,dy) = (x - center.x,y - center.y) \\ + * \rho = M \cdot log_e(\texttt{magnitude} (I)) ,\\ + * \phi = Kangle \cdot \texttt{angle} (I) \\ * \end{array}\) - *

    + * * and * \(\begin{array}{l} - * M = src.cols / log_e(maxRadius) \\ - * Kangle = src.rows / 2\Pi \\ + * M = src.cols / log_e(maxRadius) \\ + * Kangle = src.rows / 2\Pi \\ * \end{array}\) - *

    + * * The function emulates the human "foveal" vision and can be used for fast scale and * rotation-invariant template matching, for object tracking and so forth. + * @param src Source image + * @param dst Destination image. It will have same size and type as src. + * @param center The transformation center; where the output precision is maximal + * @param M Magnitude scale parameter. It determines the radius of the bounding circle to transform too. + * @param flags A combination of interpolation methods, see #InterpolationFlags + * + * Note: + *

      + *
    • + * The function can not operate in-place. + *
    • + *
    • + * To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. + *
    • + *
    + * + * SEE: cv::linearPolar */ @Deprecated public static void logPolar(Mat src, Mat dst, Point center, double M, int flags) { logPolar_0(src.nativeObj, dst.nativeObj, center.x, center.y, M, flags); } + + // + // C++: void cv::linearPolar(Mat src, Mat& dst, Point2f center, double maxRadius, int flags) + // + /** * Remaps an image to polar coordinates space. * - * @param src Source image - * @param dst Destination image. It will have same size and type as src. - * @param center The transformation center; - * @param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. - * @param flags A combination of interpolation methods, see #InterpolationFlags - * - * Note: - *
      - *
    • - * The function can not operate in-place. - *
    • - *
    • - * To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. - *
    • - *
    - *

    - * SEE: cv::logPolar * @deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags) - *

    - *

    + * + * * Transform the source image using the following transformation (See REF: polar_remaps_reference_image "Polar remaps reference image c)"): * \(\begin{array}{l} - * dst( \rho , \phi ) = src(x,y) \\ - * dst.size() \leftarrow src.size() + * dst( \rho , \phi ) = src(x,y) \\ + * dst.size() \leftarrow src.size() * \end{array}\) - *

    + * * where * \(\begin{array}{l} - * I = (dx,dy) = (x - center.x,y - center.y) \\ - * \rho = Kmag \cdot \texttt{magnitude} (I) ,\\ - * \phi = angle \cdot \texttt{angle} (I) + * I = (dx,dy) = (x - center.x,y - center.y) \\ + * \rho = Kmag \cdot \texttt{magnitude} (I) ,\\ + * \phi = angle \cdot \texttt{angle} (I) * \end{array}\) - *

    + * * and * \(\begin{array}{l} - * Kx = src.cols / maxRadius \\ - * Ky = src.rows / 2\Pi + * Kx = src.cols / maxRadius \\ + * Ky = src.rows / 2\Pi * \end{array}\) + * + * + * @param src Source image + * @param dst Destination image. It will have same size and type as src. + * @param center The transformation center; + * @param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. + * @param flags A combination of interpolation methods, see #InterpolationFlags + * + * Note: + *

      + *
    • + * The function can not operate in-place. + *
    • + *
    • + * To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. + *
    • + *
    + * + * SEE: cv::logPolar */ @Deprecated public static void linearPolar(Mat src, Mat dst, Point center, double maxRadius, int flags) { @@ -4815,20 +4916,20 @@ public static void linearPolar(Mat src, Mat dst, Point center, double maxRadius, // - // C++: void cv::logPolar(Mat src, Mat& dst, Point2f center, double M, int flags) + // C++: void cv::warpPolar(Mat src, Mat& dst, Size dsize, Point2f center, double maxRadius, int flags) // /** * Remaps an image to polar or semilog-polar coordinates space - *

    - * polar_remaps_reference_image + * + * polar_remaps_reference_image * ![Polar remaps reference](pics/polar_remap_doc.png) - *

    + * * Transform the source image using the following transformation: * \( * dst(\rho , \phi ) = src(x,y) * \) - *

    + * * where * \( * \begin{array}{l} @@ -4840,7 +4941,7 @@ public static void linearPolar(Mat src, Mat dst, Point center, double maxRadius, * \end{matrix}\right. * \end{array} * \) - *

    + * * and * \( * \begin{array}{l} @@ -4849,17 +4950,17 @@ public static void linearPolar(Mat src, Mat dst, Point center, double maxRadius, * Klog = dsize.width / log_e(maxRadius) \\ * \end{array} * \) - *

    - *

    + * + * * \par Linear vs semilog mapping - *

    + * * Polar mapping can be linear or semi-log. Add one of #WarpPolarMode to {@code flags} to specify the polar mapping mode. - *

    + * * Linear is the default mode. - *

    + * * The semilog mapping emulates the human "foveal" vision that permit very high acuity on the line of sight (central vision) * in contrast to peripheral vision where acuity is minor. - *

    + * * \par Option on {@code dsize}: * *

      @@ -4892,47 +4993,47 @@ public static void linearPolar(Mat src, Mat dst, Point center, double maxRadius, * the destination image will have the given size therefore the area of the bounding circle will be scaled to {@code dsize}. * *
    - *

    - *

    + * + * * \par Reverse mapping - *

    + * * You can get reverse mapping adding #WARP_INVERSE_MAP to {@code flags} * \snippet polar_transforms.cpp InverseMap - *

    + * * In addiction, to calculate the original coordinate from a polar mapped coordinate \((rho, phi)->(x, y)\): * \snippet polar_transforms.cpp InverseCoordinate * - * @param src Source image. - * @param dst Destination image. It will have same type as src. - * @param dsize The destination image size (see description for valid options). - * @param center The transformation center. + * @param src Source image. + * @param dst Destination image. It will have same type as src. + * @param dsize The destination image size (see description for valid options). + * @param center The transformation center. * @param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. - * @param flags A combination of interpolation methods, #InterpolationFlags + #WarpPolarMode. - *

      - *
    • - * Add #WARP_POLAR_LINEAR to select linear polar mapping (default) - *
    • - *
    • - * Add #WARP_POLAR_LOG to select semilog polar mapping - *
    • - *
    • - * Add #WARP_INVERSE_MAP for reverse mapping. - *
    • - *
    - * Note: - *
      - *
    • - * The function can not operate in-place. - *
    • - *
    • - * To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. - *
    • - *
    • - * This function uses #remap. Due to current implementation limitations the size of an input and output images should be less than 32767x32767. - *
    • - *
    - *

    - * SEE: cv::remap + * @param flags A combination of interpolation methods, #InterpolationFlags + #WarpPolarMode. + *

      + *
    • + * Add #WARP_POLAR_LINEAR to select linear polar mapping (default) + *
    • + *
    • + * Add #WARP_POLAR_LOG to select semilog polar mapping + *
    • + *
    • + * Add #WARP_INVERSE_MAP for reverse mapping. + *
    • + *
    + * Note: + *
      + *
    • + * The function can not operate in-place. + *
    • + *
    • + * To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. + *
    • + *
    • + * This function uses #remap. Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + *
    • + *
    + * + * SEE: cv::remap */ public static void warpPolar(Mat src, Mat dst, Size dsize, Point center, double maxRadius, int flags) { warpPolar_0(src.nativeObj, dst.nativeObj, dsize.width, dsize.height, center.x, center.y, maxRadius, flags); @@ -4940,133 +5041,128 @@ public static void warpPolar(Mat src, Mat dst, Size dsize, Point center, double // - // C++: void cv::linearPolar(Mat src, Mat& dst, Point2f center, double maxRadius, int flags) + // C++: void cv::integral(Mat src, Mat& sum, Mat& sqsum, Mat& tilted, int sdepth = -1, int sqdepth = -1) // /** * Calculates the integral of an image. - *

    + * * The function calculates one or more integral images for the source image as follows: - *

    + * * \(\texttt{sum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)\) - *

    + * * \(\texttt{sqsum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)^2\) - *

    + * * \(\texttt{tilted} (X,Y) = \sum _{y<Y,abs(x-X+1) \leq Y-y-1} \texttt{image} (x,y)\) - *

    + * * Using these integral images, you can calculate sum, mean, and standard deviation over a specific * up-right or rotated rectangular region of the image in a constant time, for example: - *

    + * * \(\sum _{x_1 \leq x < x_2, \, y_1 \leq y < y_2} \texttt{image} (x,y) = \texttt{sum} (x_2,y_2)- \texttt{sum} (x_1,y_2)- \texttt{sum} (x_2,y_1)+ \texttt{sum} (x_1,y_1)\) - *

    + * * It makes possible to do a fast blurring or fast block correlation with a variable window size, for * example. In case of multi-channel images, sums for each channel are accumulated independently. - *

    + * * As a practical example, the next figure shows the calculation of the integral of a straight * rectangle Rect(4,4,3,2) and of a tilted rectangle Rect(5,1,2,3) . The selected pixels in the * original image are shown, as well as the relative pixels in the integral images sum and tilted . - *

    + * * ![integral calculation example](pics/integral.png) * - * @param src input image as \(W \times H\), 8-bit or floating-point (32f or 64f). - * @param sum integral image as \((W+1)\times (H+1)\) , 32-bit integer or floating-point (32f or 64f). - * @param sqsum integral image for squared pixel values; it is \((W+1)\times (H+1)\), double-precision - * floating-point (64f) array. - * @param tilted integral for the image rotated by 45 degrees; it is \((W+1)\times (H+1)\) array with - * the same data type as sum. - * @param sdepth desired depth of the integral and the tilted integral images, CV_32S, CV_32F, or - * CV_64F. + * @param src input image as \(W \times H\), 8-bit or floating-point (32f or 64f). + * @param sum integral image as \((W+1)\times (H+1)\) , 32-bit integer or floating-point (32f or 64f). + * @param sqsum integral image for squared pixel values; it is \((W+1)\times (H+1)\), double-precision + * floating-point (64f) array. + * @param tilted integral for the image rotated by 45 degrees; it is \((W+1)\times (H+1)\) array with + * the same data type as sum. + * @param sdepth desired depth of the integral and the tilted integral images, CV_32S, CV_32F, or + * CV_64F. * @param sqdepth desired depth of the integral image of squared pixel values, CV_32F or CV_64F. */ public static void integral3(Mat src, Mat sum, Mat sqsum, Mat tilted, int sdepth, int sqdepth) { integral3_0(src.nativeObj, sum.nativeObj, sqsum.nativeObj, tilted.nativeObj, sdepth, sqdepth); } - - // - // C++: void cv::warpPolar(Mat src, Mat& dst, Size dsize, Point2f center, double maxRadius, int flags) - // - /** * Calculates the integral of an image. - *

    + * * The function calculates one or more integral images for the source image as follows: - *

    + * * \(\texttt{sum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)\) - *

    + * * \(\texttt{sqsum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)^2\) - *

    + * * \(\texttt{tilted} (X,Y) = \sum _{y<Y,abs(x-X+1) \leq Y-y-1} \texttt{image} (x,y)\) - *

    + * * Using these integral images, you can calculate sum, mean, and standard deviation over a specific * up-right or rotated rectangular region of the image in a constant time, for example: - *

    + * * \(\sum _{x_1 \leq x < x_2, \, y_1 \leq y < y_2} \texttt{image} (x,y) = \texttt{sum} (x_2,y_2)- \texttt{sum} (x_1,y_2)- \texttt{sum} (x_2,y_1)+ \texttt{sum} (x_1,y_1)\) - *

    + * * It makes possible to do a fast blurring or fast block correlation with a variable window size, for * example. In case of multi-channel images, sums for each channel are accumulated independently. - *

    + * * As a practical example, the next figure shows the calculation of the integral of a straight * rectangle Rect(4,4,3,2) and of a tilted rectangle Rect(5,1,2,3) . The selected pixels in the * original image are shown, as well as the relative pixels in the integral images sum and tilted . - *

    + * * ![integral calculation example](pics/integral.png) * - * @param src input image as \(W \times H\), 8-bit or floating-point (32f or 64f). - * @param sum integral image as \((W+1)\times (H+1)\) , 32-bit integer or floating-point (32f or 64f). - * @param sqsum integral image for squared pixel values; it is \((W+1)\times (H+1)\), double-precision - * floating-point (64f) array. + * @param src input image as \(W \times H\), 8-bit or floating-point (32f or 64f). + * @param sum integral image as \((W+1)\times (H+1)\) , 32-bit integer or floating-point (32f or 64f). + * @param sqsum integral image for squared pixel values; it is \((W+1)\times (H+1)\), double-precision + * floating-point (64f) array. * @param tilted integral for the image rotated by 45 degrees; it is \((W+1)\times (H+1)\) array with - * the same data type as sum. + * the same data type as sum. * @param sdepth desired depth of the integral and the tilted integral images, CV_32S, CV_32F, or - * CV_64F. + * CV_64F. */ public static void integral3(Mat src, Mat sum, Mat sqsum, Mat tilted, int sdepth) { integral3_1(src.nativeObj, sum.nativeObj, sqsum.nativeObj, tilted.nativeObj, sdepth); } - - // - // C++: void cv::integral(Mat src, Mat& sum, Mat& sqsum, Mat& tilted, int sdepth = -1, int sqdepth = -1) - // - /** * Calculates the integral of an image. - *

    + * * The function calculates one or more integral images for the source image as follows: - *

    + * * \(\texttt{sum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)\) - *

    + * * \(\texttt{sqsum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)^2\) - *

    + * * \(\texttt{tilted} (X,Y) = \sum _{y<Y,abs(x-X+1) \leq Y-y-1} \texttt{image} (x,y)\) - *

    + * * Using these integral images, you can calculate sum, mean, and standard deviation over a specific * up-right or rotated rectangular region of the image in a constant time, for example: - *

    + * * \(\sum _{x_1 \leq x < x_2, \, y_1 \leq y < y_2} \texttt{image} (x,y) = \texttt{sum} (x_2,y_2)- \texttt{sum} (x_1,y_2)- \texttt{sum} (x_2,y_1)+ \texttt{sum} (x_1,y_1)\) - *

    + * * It makes possible to do a fast blurring or fast block correlation with a variable window size, for * example. In case of multi-channel images, sums for each channel are accumulated independently. - *

    + * * As a practical example, the next figure shows the calculation of the integral of a straight * rectangle Rect(4,4,3,2) and of a tilted rectangle Rect(5,1,2,3) . The selected pixels in the * original image are shown, as well as the relative pixels in the integral images sum and tilted . - *

    + * * ![integral calculation example](pics/integral.png) * - * @param src input image as \(W \times H\), 8-bit or floating-point (32f or 64f). - * @param sum integral image as \((W+1)\times (H+1)\) , 32-bit integer or floating-point (32f or 64f). - * @param sqsum integral image for squared pixel values; it is \((W+1)\times (H+1)\), double-precision - * floating-point (64f) array. + * @param src input image as \(W \times H\), 8-bit or floating-point (32f or 64f). + * @param sum integral image as \((W+1)\times (H+1)\) , 32-bit integer or floating-point (32f or 64f). + * @param sqsum integral image for squared pixel values; it is \((W+1)\times (H+1)\), double-precision + * floating-point (64f) array. * @param tilted integral for the image rotated by 45 degrees; it is \((W+1)\times (H+1)\) array with - * the same data type as sum. - * CV_64F. + * the same data type as sum. + * CV_64F. */ public static void integral3(Mat src, Mat sum, Mat sqsum, Mat tilted) { integral3_2(src.nativeObj, sum.nativeObj, sqsum.nativeObj, tilted.nativeObj); } + + // + // C++: void cv::integral(Mat src, Mat& sum, int sdepth = -1) + // + public static void integral(Mat src, Mat sum, int sdepth) { integral_0(src.nativeObj, sum.nativeObj, sdepth); } @@ -5077,7 +5173,7 @@ public static void integral(Mat src, Mat sum) { // - // C++: void cv::integral(Mat src, Mat& sum, int sdepth = -1) + // C++: void cv::integral(Mat src, Mat& sum, Mat& sqsum, int sdepth = -1, int sqdepth = -1) // public static void integral2(Mat src, Mat sum, Mat sqsum, int sdepth, int sqdepth) { @@ -5088,32 +5184,32 @@ public static void integral2(Mat src, Mat sum, Mat sqsum, int sdepth) { integral2_1(src.nativeObj, sum.nativeObj, sqsum.nativeObj, sdepth); } - - // - // C++: void cv::integral(Mat src, Mat& sum, Mat& sqsum, int sdepth = -1, int sqdepth = -1) - // - public static void integral2(Mat src, Mat sum, Mat sqsum) { integral2_2(src.nativeObj, sum.nativeObj, sqsum.nativeObj); } + + // + // C++: void cv::accumulate(Mat src, Mat& dst, Mat mask = Mat()) + // + /** * Adds an image to the accumulator image. - *

    + * * The function adds src or some of its elements to dst : - *

    + * * \(\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\) - *

    + * * The function supports multi-channel images. Each channel is processed independently. - *

    + * * The function cv::accumulate can be used, for example, to collect statistics of a scene background * viewed by a still camera and for the further foreground-background segmentation. * - * @param src Input image of type CV_8UC(n), CV_16UC(n), CV_32FC(n) or CV_64FC(n), where n is a positive integer. - * @param dst %Accumulator image with the same number of channels as input image, and a depth of CV_32F or CV_64F. + * @param src Input image of type CV_8UC(n), CV_16UC(n), CV_32FC(n) or CV_64FC(n), where n is a positive integer. + * @param dst %Accumulator image with the same number of channels as input image, and a depth of CV_32F or CV_64F. * @param mask Optional operation mask. - *

    - * SEE: accumulateSquare, accumulateProduct, accumulateWeighted + * + * SEE: accumulateSquare, accumulateProduct, accumulateWeighted */ public static void accumulate(Mat src, Mat dst, Mat mask) { accumulate_0(src.nativeObj, dst.nativeObj, mask.nativeObj); @@ -5121,20 +5217,20 @@ public static void accumulate(Mat src, Mat dst, Mat mask) { /** * Adds an image to the accumulator image. - *

    + * * The function adds src or some of its elements to dst : - *

    + * * \(\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\) - *

    + * * The function supports multi-channel images. Each channel is processed independently. - *

    + * * The function cv::accumulate can be used, for example, to collect statistics of a scene background * viewed by a still camera and for the further foreground-background segmentation. * * @param src Input image of type CV_8UC(n), CV_16UC(n), CV_32FC(n) or CV_64FC(n), where n is a positive integer. * @param dst %Accumulator image with the same number of channels as input image, and a depth of CV_32F or CV_64F. - *

    - * SEE: accumulateSquare, accumulateProduct, accumulateWeighted + * + * SEE: accumulateSquare, accumulateProduct, accumulateWeighted */ public static void accumulate(Mat src, Mat dst) { accumulate_1(src.nativeObj, dst.nativeObj); @@ -5142,25 +5238,25 @@ public static void accumulate(Mat src, Mat dst) { // - // C++: void cv::accumulate(Mat src, Mat& dst, Mat mask = Mat()) + // C++: void cv::accumulateSquare(Mat src, Mat& dst, Mat mask = Mat()) // /** * Adds the square of a source image to the accumulator image. - *

    + * * The function adds the input image src or its selected region, raised to a power of 2, to the * accumulator dst : - *

    + * * \(\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y)^2 \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\) - *

    + * * The function supports multi-channel images. Each channel is processed independently. * - * @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. - * @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit - * floating-point. + * @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. + * @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit + * floating-point. * @param mask Optional operation mask. - *

    - * SEE: accumulateSquare, accumulateProduct, accumulateWeighted + * + * SEE: accumulateSquare, accumulateProduct, accumulateWeighted */ public static void accumulateSquare(Mat src, Mat dst, Mat mask) { accumulateSquare_0(src.nativeObj, dst.nativeObj, mask.nativeObj); @@ -5168,19 +5264,19 @@ public static void accumulateSquare(Mat src, Mat dst, Mat mask) { /** * Adds the square of a source image to the accumulator image. - *

    + * * The function adds the input image src or its selected region, raised to a power of 2, to the * accumulator dst : - *

    + * * \(\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y)^2 \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\) - *

    + * * The function supports multi-channel images. Each channel is processed independently. * * @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. * @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit - * floating-point. - *

    - * SEE: accumulateSquare, accumulateProduct, accumulateWeighted + * floating-point. + * + * SEE: accumulateSquare, accumulateProduct, accumulateWeighted */ public static void accumulateSquare(Mat src, Mat dst) { accumulateSquare_1(src.nativeObj, dst.nativeObj); @@ -5188,25 +5284,25 @@ public static void accumulateSquare(Mat src, Mat dst) { // - // C++: void cv::accumulateSquare(Mat src, Mat& dst, Mat mask = Mat()) + // C++: void cv::accumulateProduct(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) // /** * Adds the per-element product of two input images to the accumulator image. - *

    + * * The function adds the product of two images or their selected regions to the accumulator dst : - *

    + * * \(\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src1} (x,y) \cdot \texttt{src2} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\) - *

    + * * The function supports multi-channel images. Each channel is processed independently. * * @param src1 First input image, 1- or 3-channel, 8-bit or 32-bit floating point. * @param src2 Second input image of the same type and the same size as src1 . - * @param dst %Accumulator image with the same number of channels as input images, 32-bit or 64-bit - * floating-point. + * @param dst %Accumulator image with the same number of channels as input images, 32-bit or 64-bit + * floating-point. * @param mask Optional operation mask. - *

    - * SEE: accumulate, accumulateSquare, accumulateWeighted + * + * SEE: accumulate, accumulateSquare, accumulateWeighted */ public static void accumulateProduct(Mat src1, Mat src2, Mat dst, Mat mask) { accumulateProduct_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj); @@ -5214,19 +5310,19 @@ public static void accumulateProduct(Mat src1, Mat src2, Mat dst, Mat mask) { /** * Adds the per-element product of two input images to the accumulator image. - *

    + * * The function adds the product of two images or their selected regions to the accumulator dst : - *

    + * * \(\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src1} (x,y) \cdot \texttt{src2} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\) - *

    + * * The function supports multi-channel images. Each channel is processed independently. * * @param src1 First input image, 1- or 3-channel, 8-bit or 32-bit floating point. * @param src2 Second input image of the same type and the same size as src1 . - * @param dst %Accumulator image with the same number of channels as input images, 32-bit or 64-bit - * floating-point. - *

    - * SEE: accumulate, accumulateSquare, accumulateWeighted + * @param dst %Accumulator image with the same number of channels as input images, 32-bit or 64-bit + * floating-point. + * + * SEE: accumulate, accumulateSquare, accumulateWeighted */ public static void accumulateProduct(Mat src1, Mat src2, Mat dst) { accumulateProduct_1(src1.nativeObj, src2.nativeObj, dst.nativeObj); @@ -5234,27 +5330,27 @@ public static void accumulateProduct(Mat src1, Mat src2, Mat dst) { // - // C++: void cv::accumulateProduct(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) + // C++: void cv::accumulateWeighted(Mat src, Mat& dst, double alpha, Mat mask = Mat()) // /** * Updates a running average. - *

    + * * The function calculates the weighted sum of the input image src and the accumulator dst so that dst * becomes a running average of a frame sequence: - *

    + * * \(\texttt{dst} (x,y) \leftarrow (1- \texttt{alpha} ) \cdot \texttt{dst} (x,y) + \texttt{alpha} \cdot \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\) - *

    + * * That is, alpha regulates the update speed (how fast the accumulator "forgets" about earlier images). * The function supports multi-channel images. Each channel is processed independently. * - * @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. - * @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit - * floating-point. + * @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. + * @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit + * floating-point. * @param alpha Weight of the input image. - * @param mask Optional operation mask. - *

    - * SEE: accumulate, accumulateSquare, accumulateProduct + * @param mask Optional operation mask. + * + * SEE: accumulate, accumulateSquare, accumulateProduct */ public static void accumulateWeighted(Mat src, Mat dst, double alpha, Mat mask) { accumulateWeighted_0(src.nativeObj, dst.nativeObj, alpha, mask.nativeObj); @@ -5262,21 +5358,21 @@ public static void accumulateWeighted(Mat src, Mat dst, double alpha, Mat mask) /** * Updates a running average. - *

    + * * The function calculates the weighted sum of the input image src and the accumulator dst so that dst * becomes a running average of a frame sequence: - *

    + * * \(\texttt{dst} (x,y) \leftarrow (1- \texttt{alpha} ) \cdot \texttt{dst} (x,y) + \texttt{alpha} \cdot \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\) - *

    + * * That is, alpha regulates the update speed (how fast the accumulator "forgets" about earlier images). * The function supports multi-channel images. Each channel is processed independently. * - * @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. - * @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit - * floating-point. + * @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. + * @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit + * floating-point. * @param alpha Weight of the input image. - *

    - * SEE: accumulate, accumulateSquare, accumulateProduct + * + * SEE: accumulate, accumulateSquare, accumulateProduct */ public static void accumulateWeighted(Mat src, Mat dst, double alpha) { accumulateWeighted_1(src.nativeObj, dst.nativeObj, alpha); @@ -5284,19 +5380,19 @@ public static void accumulateWeighted(Mat src, Mat dst, double alpha) { // - // C++: void cv::accumulateWeighted(Mat src, Mat& dst, double alpha, Mat mask = Mat()) + // C++: Point2d cv::phaseCorrelate(Mat src1, Mat src2, Mat window = Mat(), double* response = 0) // /** * The function is used to detect translational shifts that occur between two images. - *

    + * * The operation takes advantage of the Fourier shift theorem for detecting the translational shift in * the frequency domain. It can be used for fast image registration as well as motion estimation. For * more information please see <http://en.wikipedia.org/wiki/Phase_correlation> - *

    + * * Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed * with getOptimalDFTSize. - *

    + * * The function performs the following equations: *

      *
    • @@ -5329,31 +5425,31 @@ public static void accumulateWeighted(Mat src, Mat dst, double alpha) { *
    • *
    * - * @param src1 Source floating point array (CV_32FC1 or CV_64FC1) - * @param src2 Source floating point array (CV_32FC1 or CV_64FC1) - * @param window Floating point array with windowing coefficients to reduce edge effects (optional). + * @param src1 Source floating point array (CV_32FC1 or CV_64FC1) + * @param src2 Source floating point array (CV_32FC1 or CV_64FC1) + * @param window Floating point array with windowing coefficients to reduce edge effects (optional). * @param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional). * @return detected phase shift (sub-pixel) between the two arrays. - *

    + * * SEE: dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow */ public static Point phaseCorrelate(Mat src1, Mat src2, Mat window, double[] response) { double[] response_out = new double[1]; Point retVal = new Point(phaseCorrelate_0(src1.nativeObj, src2.nativeObj, window.nativeObj, response_out)); - if (response != null) response[0] = (double) response_out[0]; + if(response!=null) response[0] = (double)response_out[0]; return retVal; } /** * The function is used to detect translational shifts that occur between two images. - *

    + * * The operation takes advantage of the Fourier shift theorem for detecting the translational shift in * the frequency domain. It can be used for fast image registration as well as motion estimation. For * more information please see <http://en.wikipedia.org/wiki/Phase_correlation> - *

    + * * Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed * with getOptimalDFTSize. - *

    + * * The function performs the following equations: *

      *
    • @@ -5386,32 +5482,27 @@ public static Point phaseCorrelate(Mat src1, Mat src2, Mat window, double[] resp *
    • *
    * - * @param src1 Source floating point array (CV_32FC1 or CV_64FC1) - * @param src2 Source floating point array (CV_32FC1 or CV_64FC1) + * @param src1 Source floating point array (CV_32FC1 or CV_64FC1) + * @param src2 Source floating point array (CV_32FC1 or CV_64FC1) * @param window Floating point array with windowing coefficients to reduce edge effects (optional). * @return detected phase shift (sub-pixel) between the two arrays. - *

    + * * SEE: dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow */ public static Point phaseCorrelate(Mat src1, Mat src2, Mat window) { return new Point(phaseCorrelate_1(src1.nativeObj, src2.nativeObj, window.nativeObj)); } - - // - // C++: Point2d cv::phaseCorrelate(Mat src1, Mat src2, Mat window = Mat(), double* response = 0) - // - /** * The function is used to detect translational shifts that occur between two images. - *

    + * * The operation takes advantage of the Fourier shift theorem for detecting the translational shift in * the frequency domain. It can be used for fast image registration as well as motion estimation. For * more information please see <http://en.wikipedia.org/wiki/Phase_correlation> - *

    + * * Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed * with getOptimalDFTSize. - *

    + * * The function performs the following equations: *

      *
    • @@ -5447,69 +5538,73 @@ public static Point phaseCorrelate(Mat src1, Mat src2, Mat window) { * @param src1 Source floating point array (CV_32FC1 or CV_64FC1) * @param src2 Source floating point array (CV_32FC1 or CV_64FC1) * @return detected phase shift (sub-pixel) between the two arrays. - *

      + * * SEE: dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow */ public static Point phaseCorrelate(Mat src1, Mat src2) { return new Point(phaseCorrelate_2(src1.nativeObj, src2.nativeObj)); } + + // + // C++: void cv::createHanningWindow(Mat& dst, Size winSize, int type) + // + /** * This function computes a Hanning window coefficients in two dimensions. - *

      + * * See (http://en.wikipedia.org/wiki/Hann_function) and (http://en.wikipedia.org/wiki/Window_function) * for more information. - *

      + * * An example is shown below: * - * // create hanning window of size 100x100 and type CV_32F - * Mat hann; - * createHanningWindow(hann, Size(100, 100), CV_32F); + * // create hanning window of size 100x100 and type CV_32F + * Mat hann; + * createHanningWindow(hann, Size(100, 100), CV_32F); * - * - * @param dst Destination array to place Hann coefficients in + * @param dst Destination array to place Hann coefficients in * @param winSize The window size specifications (both width and height must be > 1) - * @param type Created array type + * @param type Created array type */ public static void createHanningWindow(Mat dst, Size winSize, int type) { createHanningWindow_0(dst.nativeObj, winSize.width, winSize.height, type); } + + // + // C++: void cv::divSpectrums(Mat a, Mat b, Mat& c, int flags, bool conjB = false) + // + /** * Performs the per-element division of the first Fourier spectrum by the second Fourier spectrum. - *

      + * * The function cv::divSpectrums performs the per-element division of the first array by the second array. * The arrays are CCS-packed or complex matrices that are results of a real or complex Fourier transform. * - * @param a first input array. - * @param b second input array of the same size and type as src1 . - * @param c output array of the same size and type as src1 . + * @param a first input array. + * @param b second input array of the same size and type as src1 . + * @param c output array of the same size and type as src1 . * @param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that - * each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a {@code 0} as value. + * each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a {@code 0} as value. * @param conjB optional flag that conjugates the second input array before the multiplication (true) - * or not (false). + * or not (false). */ public static void divSpectrums(Mat a, Mat b, Mat c, int flags, boolean conjB) { divSpectrums_0(a.nativeObj, b.nativeObj, c.nativeObj, flags, conjB); } - - // - // C++: void cv::createHanningWindow(Mat& dst, Size winSize, int type) - // - /** * Performs the per-element division of the first Fourier spectrum by the second Fourier spectrum. - *

      + * * The function cv::divSpectrums performs the per-element division of the first array by the second array. * The arrays are CCS-packed or complex matrices that are results of a real or complex Fourier transform. * - * @param a first input array. - * @param b second input array of the same size and type as src1 . - * @param c output array of the same size and type as src1 . + * @param a first input array. + * @param b second input array of the same size and type as src1 . + * @param c output array of the same size and type as src1 . * @param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that - * each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a {@code 0} as value. - * or not (false). + * each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a {@code 0} as value. + * or not (false). */ public static void divSpectrums(Mat a, Mat b, Mat c, int flags) { divSpectrums_1(a.nativeObj, b.nativeObj, c.nativeObj, flags); @@ -5517,41 +5612,46 @@ public static void divSpectrums(Mat a, Mat b, Mat c, int flags) { // - // C++: void cv::divSpectrums(Mat a, Mat b, Mat& c, int flags, bool conjB = false) + // C++: double cv::threshold(Mat src, Mat& dst, double thresh, double maxval, int type) // /** * Applies a fixed-level threshold to each array element. - *

      + * * The function applies fixed-level thresholding to a multiple-channel array. The function is typically * used to get a bi-level (binary) image out of a grayscale image ( #compare could be also used for * this purpose) or for removing a noise, that is, filtering out pixels with too small or too large * values. There are several types of thresholding supported by the function. They are determined by * type parameter. - *

      + * * Also, the special values #THRESH_OTSU or #THRESH_TRIANGLE may be combined with one of the * above values. In these cases, the function determines the optimal threshold value using the Otsu's * or Triangle algorithm and uses it instead of the specified thresh. * * Note: Currently, the Otsu's and Triangle methods are implemented only for 8-bit single-channel images. * - * @param src input array (multiple-channel, 8-bit or 32-bit floating point). - * @param dst output array of the same size and type and the same number of channels as src. + * @param src input array (multiple-channel, 8-bit or 32-bit floating point). + * @param dst output array of the same size and type and the same number of channels as src. * @param thresh threshold value. * @param maxval maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding - * types. - * @param type thresholding type (see #ThresholdTypes). + * types. + * @param type thresholding type (see #ThresholdTypes). * @return the computed threshold value if Otsu's or Triangle methods used. - *

      + * * SEE: adaptiveThreshold, findContours, compare, min, max */ public static double threshold(Mat src, Mat dst, double thresh, double maxval, int type) { return threshold_0(src.nativeObj, dst.nativeObj, thresh, maxval, type); } + + // + // C++: void cv::adaptiveThreshold(Mat src, Mat& dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C) + // + /** * Applies an adaptive threshold to an array. - *

      + * * The function transforms a grayscale image to a binary image according to the formulae: *

        *
      • @@ -5564,22 +5664,22 @@ public static double threshold(Mat src, Mat dst, double thresh, double maxval, i * where \(T(x,y)\) is a threshold calculated individually for each pixel (see adaptiveMethod parameter). *
      • *
      - *

      + * * The function can process the image in-place. * - * @param src Source 8-bit single-channel image. - * @param dst Destination image of the same size and the same type as src. - * @param maxValue Non-zero value assigned to the pixels for which the condition is satisfied + * @param src Source 8-bit single-channel image. + * @param dst Destination image of the same size and the same type as src. + * @param maxValue Non-zero value assigned to the pixels for which the condition is satisfied * @param adaptiveMethod Adaptive thresholding algorithm to use, see #AdaptiveThresholdTypes. - * The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries. - * @param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV, - * see #ThresholdTypes. - * @param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the - * pixel: 3, 5, 7, and so on. - * @param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it - * is positive but may be zero or negative as well. - *

      - * SEE: threshold, blur, GaussianBlur + * The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries. + * @param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV, + * see #ThresholdTypes. + * @param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the + * pixel: 3, 5, 7, and so on. + * @param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it + * is positive but may be zero or negative as well. + * + * SEE: threshold, blur, GaussianBlur */ public static void adaptiveThreshold(Mat src, Mat dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C) { adaptiveThreshold_0(src.nativeObj, dst.nativeObj, maxValue, adaptiveMethod, thresholdType, blockSize, C); @@ -5587,79 +5687,69 @@ public static void adaptiveThreshold(Mat src, Mat dst, double maxValue, int adap // - // C++: double cv::threshold(Mat src, Mat& dst, double thresh, double maxval, int type) + // C++: void cv::pyrDown(Mat src, Mat& dst, Size dstsize = Size(), int borderType = BORDER_DEFAULT) // /** * Blurs an image and downsamples it. - *

      + * * By default, size of the output image is computed as {@code Size((src.cols+1)/2, (src.rows+1)/2)}, but in * any case, the following conditions should be satisfied: - *

      + * * \(\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\) - *

      + * * The function performs the downsampling step of the Gaussian pyramid construction. First, it * convolves the source image with the kernel: - *

      + * * \(\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\) - *

      + * * Then, it downsamples the image by rejecting even rows and columns. * - * @param src input image. - * @param dst output image; it has the specified size and the same type as src. - * @param dstsize size of the output image. + * @param src input image. + * @param dst output image; it has the specified size and the same type as src. + * @param dstsize size of the output image. * @param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported) */ public static void pyrDown(Mat src, Mat dst, Size dstsize, int borderType) { pyrDown_0(src.nativeObj, dst.nativeObj, dstsize.width, dstsize.height, borderType); } - - // - // C++: void cv::adaptiveThreshold(Mat src, Mat& dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C) - // - /** * Blurs an image and downsamples it. - *

      + * * By default, size of the output image is computed as {@code Size((src.cols+1)/2, (src.rows+1)/2)}, but in * any case, the following conditions should be satisfied: - *

      + * * \(\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\) - *

      + * * The function performs the downsampling step of the Gaussian pyramid construction. First, it * convolves the source image with the kernel: - *

      + * * \(\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\) - *

      + * * Then, it downsamples the image by rejecting even rows and columns. * - * @param src input image. - * @param dst output image; it has the specified size and the same type as src. + * @param src input image. + * @param dst output image; it has the specified size and the same type as src. * @param dstsize size of the output image. */ public static void pyrDown(Mat src, Mat dst, Size dstsize) { pyrDown_1(src.nativeObj, dst.nativeObj, dstsize.width, dstsize.height); } - - // - // C++: void cv::pyrDown(Mat src, Mat& dst, Size dstsize = Size(), int borderType = BORDER_DEFAULT) - // - /** * Blurs an image and downsamples it. - *

      + * * By default, size of the output image is computed as {@code Size((src.cols+1)/2, (src.rows+1)/2)}, but in * any case, the following conditions should be satisfied: - *

      + * * \(\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\) - *

      + * * The function performs the downsampling step of the Gaussian pyramid construction. First, it * convolves the source image with the kernel: - *

      + * * \(\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\) - *

      + * * Then, it downsamples the image by rejecting even rows and columns. * * @param src input image. @@ -5669,22 +5759,27 @@ public static void pyrDown(Mat src, Mat dst) { pyrDown_2(src.nativeObj, dst.nativeObj); } + + // + // C++: void cv::pyrUp(Mat src, Mat& dst, Size dstsize = Size(), int borderType = BORDER_DEFAULT) + // + /** * Upsamples an image and then blurs it. - *

      + * * By default, size of the output image is computed as {@code Size(src.cols\*2, (src.rows\*2)}, but in any * case, the following conditions should be satisfied: - *

      + * * \(\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\) - *

      + * * The function performs the upsampling step of the Gaussian pyramid construction, though it can * actually be used to construct the Laplacian pyramid. First, it upsamples the source image by * injecting even zero rows and columns and then convolves the result with the same kernel as in * pyrDown multiplied by 4. * - * @param src input image. - * @param dst output image. It has the specified size and the same type as src . - * @param dstsize size of the output image. + * @param src input image. + * @param dst output image. It has the specified size and the same type as src . + * @param dstsize size of the output image. * @param borderType Pixel extrapolation method, see #BorderTypes (only #BORDER_DEFAULT is supported) */ public static void pyrUp(Mat src, Mat dst, Size dstsize, int borderType) { @@ -5693,38 +5788,33 @@ public static void pyrUp(Mat src, Mat dst, Size dstsize, int borderType) { /** * Upsamples an image and then blurs it. - *

      + * * By default, size of the output image is computed as {@code Size(src.cols\*2, (src.rows\*2)}, but in any * case, the following conditions should be satisfied: - *

      + * * \(\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\) - *

      + * * The function performs the upsampling step of the Gaussian pyramid construction, though it can * actually be used to construct the Laplacian pyramid. First, it upsamples the source image by * injecting even zero rows and columns and then convolves the result with the same kernel as in * pyrDown multiplied by 4. * - * @param src input image. - * @param dst output image. It has the specified size and the same type as src . + * @param src input image. + * @param dst output image. It has the specified size and the same type as src . * @param dstsize size of the output image. */ public static void pyrUp(Mat src, Mat dst, Size dstsize) { pyrUp_1(src.nativeObj, dst.nativeObj, dstsize.width, dstsize.height); } - - // - // C++: void cv::pyrUp(Mat src, Mat& dst, Size dstsize = Size(), int borderType = BORDER_DEFAULT) - // - /** * Upsamples an image and then blurs it. - *

      + * * By default, size of the output image is computed as {@code Size(src.cols\*2, (src.rows\*2)}, but in any * case, the following conditions should be satisfied: - *

      + * * \(\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\) - *

      + * * The function performs the upsampling step of the Gaussian pyramid construction, though it can * actually be used to construct the Laplacian pyramid. First, it upsamples the source image by * injecting even zero rows and columns and then convolves the result with the same kernel as in @@ -5737,19 +5827,25 @@ public static void pyrUp(Mat src, Mat dst) { pyrUp_2(src.nativeObj, dst.nativeObj); } + + // + // C++: void cv::calcHist(vector_Mat images, vector_int channels, Mat mask, Mat& hist, vector_int histSize, vector_float ranges, bool accumulate = false) + // + /** + * + * * this variant supports only uniform histograms. - *

      + * * ranges argument is either empty vector or a flattened vector of histSize.size()*2 elements * (histSize.size() element pairs). The first and second elements of each pair specify the lower and * upper boundaries. - * - * @param images automatically generated - * @param channels automatically generated - * @param mask automatically generated - * @param hist automatically generated - * @param histSize automatically generated - * @param ranges automatically generated + * @param images automatically generated + * @param channels automatically generated + * @param mask automatically generated + * @param hist automatically generated + * @param histSize automatically generated + * @param ranges automatically generated * @param accumulate automatically generated */ public static void calcHist(List images, MatOfInt channels, Mat mask, Mat hist, MatOfInt histSize, MatOfFloat ranges, boolean accumulate) { @@ -5761,18 +5857,19 @@ public static void calcHist(List images, MatOfInt channels, Mat mask, Mat h } /** + * + * * this variant supports only uniform histograms. - *

      + * * ranges argument is either empty vector or a flattened vector of histSize.size()*2 elements * (histSize.size() element pairs). The first and second elements of each pair specify the lower and * upper boundaries. - * - * @param images automatically generated + * @param images automatically generated * @param channels automatically generated - * @param mask automatically generated - * @param hist automatically generated + * @param mask automatically generated + * @param hist automatically generated * @param histSize automatically generated - * @param ranges automatically generated + * @param ranges automatically generated */ public static void calcHist(List images, MatOfInt channels, Mat mask, Mat hist, MatOfInt histSize, MatOfFloat ranges) { Mat images_mat = Converters.vector_Mat_to_Mat(images); @@ -5784,7 +5881,7 @@ public static void calcHist(List images, MatOfInt channels, Mat mask, Mat h // - // C++: void cv::calcHist(vector_Mat images, vector_int channels, Mat mask, Mat& hist, vector_int histSize, vector_float ranges, bool accumulate = false) + // C++: void cv::calcBackProject(vector_Mat images, vector_int channels, Mat hist, Mat& dst, vector_float ranges, double scale) // public static void calcBackProject(List images, MatOfInt channels, Mat hist, Mat dst, MatOfFloat ranges, double scale) { @@ -5794,20 +5891,25 @@ public static void calcBackProject(List images, MatOfInt channels, Mat hist calcBackProject_0(images_mat.nativeObj, channels_mat.nativeObj, hist.nativeObj, dst.nativeObj, ranges_mat.nativeObj, scale); } + + // + // C++: double cv::compareHist(Mat H1, Mat H2, int method) + // + /** * Compares two histograms. - *

      + * * The function cv::compareHist compares two dense or two sparse histograms using the specified method. - *

      + * * The function returns \(d(H_1, H_2)\) . - *

      + * * While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable * for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling * problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms * or more general sparse configurations of weighted points, consider using the #EMD function. * - * @param H1 First compared histogram. - * @param H2 Second compared histogram of the same size as H1 . + * @param H1 First compared histogram. + * @param H2 Second compared histogram of the same size as H1 . * @param method Comparison method, see #HistCompMethods * @return automatically generated */ @@ -5817,12 +5919,12 @@ public static double compareHist(Mat H1, Mat H2, int method) { // - // C++: void cv::calcBackProject(vector_Mat images, vector_int channels, Mat hist, Mat& dst, vector_float ranges, double scale) + // C++: void cv::equalizeHist(Mat src, Mat& dst) // /** * Equalizes the histogram of a grayscale image. - *

      + * * The function equalizes the histogram of the input image using the following algorithm: * *

        @@ -5840,7 +5942,7 @@ public static double compareHist(Mat H1, Mat H2, int method) { * Transform the image using \(H'\) as a look-up table: \(\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\) * *
      - *

      + * * The algorithm normalizes the brightness and increases the contrast of the image. * * @param src Source 8-bit single channel image. @@ -5852,56 +5954,50 @@ public static void equalizeHist(Mat src, Mat dst) { // - // C++: double cv::compareHist(Mat H1, Mat H2, int method) + // C++: Ptr_CLAHE cv::createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)) // /** * Creates a smart pointer to a cv::CLAHE class and initializes it. * - * @param clipLimit Threshold for contrast limiting. + * @param clipLimit Threshold for contrast limiting. * @param tileGridSize Size of grid for histogram equalization. Input image will be divided into - * equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. + * equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. * @return automatically generated */ public static CLAHE createCLAHE(double clipLimit, Size tileGridSize) { return CLAHE.__fromPtr__(createCLAHE_0(clipLimit, tileGridSize.width, tileGridSize.height)); } - - // - // C++: void cv::equalizeHist(Mat src, Mat& dst) - // - /** * Creates a smart pointer to a cv::CLAHE class and initializes it. * * @param clipLimit Threshold for contrast limiting. - * equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. + * equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. * @return automatically generated */ public static CLAHE createCLAHE(double clipLimit) { return CLAHE.__fromPtr__(createCLAHE_1(clipLimit)); } - - // - // C++: Ptr_CLAHE cv::createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)) - // - /** * Creates a smart pointer to a cv::CLAHE class and initializes it. - *

      - * equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. * + * equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. * @return automatically generated */ public static CLAHE createCLAHE() { return CLAHE.__fromPtr__(createCLAHE_2()); } + + // + // C++: float cv::wrapperEMD(Mat signature1, Mat signature2, int distType, Mat cost = Mat(), Ptr_float& lowerBound = Ptr(), Mat& flow = Mat()) + // + /** * Computes the "minimal work" distance between two weighted point configurations. - *

      + * * The function computes the earth mover distance and/or a lower boundary of the distance between the * two weighted point configurations. One of the applications described in CITE: RubnerSept98, * CITE: Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation @@ -5912,26 +6008,26 @@ public static CLAHE createCLAHE() { * same object. * * @param signature1 First signature, a \(\texttt{size1}\times \texttt{dims}+1\) floating-point matrix. - * Each row stores the point weight followed by the point coordinates. The matrix is allowed to have - * a single column (weights only) if the user-defined cost matrix is used. The weights must be - * non-negative and have at least one non-zero value. + * Each row stores the point weight followed by the point coordinates. The matrix is allowed to have + * a single column (weights only) if the user-defined cost matrix is used. The weights must be + * non-negative and have at least one non-zero value. * @param signature2 Second signature of the same format as signature1 , though the number of rows - * may be different. The total weights may be different. In this case an extra "dummy" point is added - * to either signature1 or signature2. The weights must be non-negative and have at least one non-zero - * value. - * @param distType Used metric. See #DistanceTypes. - * @param cost User-defined \(\texttt{size1}\times \texttt{size2}\) cost matrix. Also, if a cost matrix - * is used, lower boundary lowerBound cannot be calculated because it needs a metric function. - * signatures that is a distance between mass centers. The lower boundary may not be calculated if - * the user-defined cost matrix is used, the total weights of point configurations are not equal, or - * if the signatures consist of weights only (the signature matrices have a single column). You - * must initialize \*lowerBound . If the calculated distance between mass centers is greater or - * equal to \*lowerBound (it means that the signatures are far enough), the function does not - * calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on - * return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound - * should be set to 0. - * @param flow Resultant \(\texttt{size1} \times \texttt{size2}\) flow matrix: \(\texttt{flow}_{i,j}\) is - * a flow from \(i\) -th point of signature1 to \(j\) -th point of signature2 . + * may be different. The total weights may be different. In this case an extra "dummy" point is added + * to either signature1 or signature2. The weights must be non-negative and have at least one non-zero + * value. + * @param distType Used metric. See #DistanceTypes. + * @param cost User-defined \(\texttt{size1}\times \texttt{size2}\) cost matrix. Also, if a cost matrix + * is used, lower boundary lowerBound cannot be calculated because it needs a metric function. + * signatures that is a distance between mass centers. The lower boundary may not be calculated if + * the user-defined cost matrix is used, the total weights of point configurations are not equal, or + * if the signatures consist of weights only (the signature matrices have a single column). You + * must initialize \*lowerBound . If the calculated distance between mass centers is greater or + * equal to \*lowerBound (it means that the signatures are far enough), the function does not + * calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on + * return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound + * should be set to 0. + * @param flow Resultant \(\texttt{size1} \times \texttt{size2}\) flow matrix: \(\texttt{flow}_{i,j}\) is + * a flow from \(i\) -th point of signature1 to \(j\) -th point of signature2 . * @return automatically generated */ public static float EMD(Mat signature1, Mat signature2, int distType, Mat cost, Mat flow) { @@ -5940,7 +6036,7 @@ public static float EMD(Mat signature1, Mat signature2, int distType, Mat cost, /** * Computes the "minimal work" distance between two weighted point configurations. - *

      + * * The function computes the earth mover distance and/or a lower boundary of the distance between the * two weighted point configurations. One of the applications described in CITE: RubnerSept98, * CITE: Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation @@ -5951,39 +6047,34 @@ public static float EMD(Mat signature1, Mat signature2, int distType, Mat cost, * same object. * * @param signature1 First signature, a \(\texttt{size1}\times \texttt{dims}+1\) floating-point matrix. - * Each row stores the point weight followed by the point coordinates. The matrix is allowed to have - * a single column (weights only) if the user-defined cost matrix is used. The weights must be - * non-negative and have at least one non-zero value. + * Each row stores the point weight followed by the point coordinates. The matrix is allowed to have + * a single column (weights only) if the user-defined cost matrix is used. The weights must be + * non-negative and have at least one non-zero value. * @param signature2 Second signature of the same format as signature1 , though the number of rows - * may be different. The total weights may be different. In this case an extra "dummy" point is added - * to either signature1 or signature2. The weights must be non-negative and have at least one non-zero - * value. - * @param distType Used metric. See #DistanceTypes. - * @param cost User-defined \(\texttt{size1}\times \texttt{size2}\) cost matrix. Also, if a cost matrix - * is used, lower boundary lowerBound cannot be calculated because it needs a metric function. - * signatures that is a distance between mass centers. The lower boundary may not be calculated if - * the user-defined cost matrix is used, the total weights of point configurations are not equal, or - * if the signatures consist of weights only (the signature matrices have a single column). You - * must initialize \*lowerBound . If the calculated distance between mass centers is greater or - * equal to \*lowerBound (it means that the signatures are far enough), the function does not - * calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on - * return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound - * should be set to 0. - * a flow from \(i\) -th point of signature1 to \(j\) -th point of signature2 . + * may be different. The total weights may be different. In this case an extra "dummy" point is added + * to either signature1 or signature2. The weights must be non-negative and have at least one non-zero + * value. + * @param distType Used metric. See #DistanceTypes. + * @param cost User-defined \(\texttt{size1}\times \texttt{size2}\) cost matrix. Also, if a cost matrix + * is used, lower boundary lowerBound cannot be calculated because it needs a metric function. + * signatures that is a distance between mass centers. The lower boundary may not be calculated if + * the user-defined cost matrix is used, the total weights of point configurations are not equal, or + * if the signatures consist of weights only (the signature matrices have a single column). You + * must initialize \*lowerBound . If the calculated distance between mass centers is greater or + * equal to \*lowerBound (it means that the signatures are far enough), the function does not + * calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on + * return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound + * should be set to 0. + * a flow from \(i\) -th point of signature1 to \(j\) -th point of signature2 . * @return automatically generated */ public static float EMD(Mat signature1, Mat signature2, int distType, Mat cost) { return EMD_1(signature1.nativeObj, signature2.nativeObj, distType, cost.nativeObj); } - - // - // C++: float cv::wrapperEMD(Mat signature1, Mat signature2, int distType, Mat cost = Mat(), Ptr_float& lowerBound = Ptr(), Mat& flow = Mat()) - // - /** * Computes the "minimal work" distance between two weighted point configurations. - *

      + * * The function computes the earth mover distance and/or a lower boundary of the distance between the * two weighted point configurations. One of the applications described in CITE: RubnerSept98, * CITE: Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation @@ -5994,36 +6085,41 @@ public static float EMD(Mat signature1, Mat signature2, int distType, Mat cost) * same object. * * @param signature1 First signature, a \(\texttt{size1}\times \texttt{dims}+1\) floating-point matrix. - * Each row stores the point weight followed by the point coordinates. The matrix is allowed to have - * a single column (weights only) if the user-defined cost matrix is used. The weights must be - * non-negative and have at least one non-zero value. + * Each row stores the point weight followed by the point coordinates. The matrix is allowed to have + * a single column (weights only) if the user-defined cost matrix is used. The weights must be + * non-negative and have at least one non-zero value. * @param signature2 Second signature of the same format as signature1 , though the number of rows - * may be different. The total weights may be different. In this case an extra "dummy" point is added - * to either signature1 or signature2. The weights must be non-negative and have at least one non-zero - * value. - * @param distType Used metric. See #DistanceTypes. - * is used, lower boundary lowerBound cannot be calculated because it needs a metric function. - * signatures that is a distance between mass centers. The lower boundary may not be calculated if - * the user-defined cost matrix is used, the total weights of point configurations are not equal, or - * if the signatures consist of weights only (the signature matrices have a single column). You - * must initialize \*lowerBound . If the calculated distance between mass centers is greater or - * equal to \*lowerBound (it means that the signatures are far enough), the function does not - * calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on - * return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound - * should be set to 0. - * a flow from \(i\) -th point of signature1 to \(j\) -th point of signature2 . + * may be different. The total weights may be different. In this case an extra "dummy" point is added + * to either signature1 or signature2. The weights must be non-negative and have at least one non-zero + * value. + * @param distType Used metric. See #DistanceTypes. + * is used, lower boundary lowerBound cannot be calculated because it needs a metric function. + * signatures that is a distance between mass centers. The lower boundary may not be calculated if + * the user-defined cost matrix is used, the total weights of point configurations are not equal, or + * if the signatures consist of weights only (the signature matrices have a single column). You + * must initialize \*lowerBound . If the calculated distance between mass centers is greater or + * equal to \*lowerBound (it means that the signatures are far enough), the function does not + * calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on + * return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound + * should be set to 0. + * a flow from \(i\) -th point of signature1 to \(j\) -th point of signature2 . * @return automatically generated */ public static float EMD(Mat signature1, Mat signature2, int distType) { return EMD_3(signature1.nativeObj, signature2.nativeObj, distType); } + + // + // C++: void cv::watershed(Mat image, Mat& markers) + // + /** * Performs a marker-based image segmentation using the watershed algorithm. - *

      + * * The function implements one of the variants of watershed, non-parametric marker-based segmentation * algorithm, described in CITE: Meyer92 . - *

      + * * Before passing the image to the function, you have to roughly outline the desired regions in the * image markers with positive (>0) indices. So, every region is represented as one or more connected * components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary @@ -6037,39 +6133,44 @@ public static float EMD(Mat signature1, Mat signature2, int distType) { * (-1's pixels); for example, they can touch each other in the initial marker image passed to the * function. * - * @param image Input 8-bit 3-channel image. + * @param image Input 8-bit 3-channel image. * @param markers Input/output 32-bit single-channel image (map) of markers. It should have the same - * size as image . - *

      - * SEE: findContours + * size as image . + * + * SEE: findContours */ public static void watershed(Mat image, Mat markers) { watershed_0(image.nativeObj, markers.nativeObj); } + + // + // C++: void cv::pyrMeanShiftFiltering(Mat src, Mat& dst, double sp, double sr, int maxLevel = 1, TermCriteria termcrit = TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1)) + // + /** * Performs initial step of meanshift segmentation of an image. - *

      + * * The function implements the filtering stage of meanshift segmentation, that is, the output of the * function is the filtered "posterized" image with color gradients and fine-grain texture flattened. * At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes * meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is * considered: - *

      + * * \((x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\) - *

      + * * where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively * (though, the algorithm does not depend on the color space used, so any 3-component color space can * be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector * (R',G',B') are found and they act as the neighborhood center on the next iteration: - *

      + * * \((X,Y)~(X',Y'), (R,G,B)~(R',G',B').\) - *

      + * * After the iterations over, the color components of the initial pixel (that is, the pixel from where * the iterations started) are set to the final value (average color at the last iteration): - *

      + * * \(I(X,Y) <- (R*,G*,B*)\) - *

      + * * When maxLevel > 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is * run on the smallest layer first. After that, the results are propagated to the larger layer and the * iterations are run again only on those pixels where the layer colors differ by more than sr from the @@ -6077,10 +6178,10 @@ public static void watershed(Mat image, Mat markers) { * results will be actually different from the ones obtained by running the meanshift procedure on the * whole original image (i.e. when maxLevel==0). * - * @param src The source 8-bit, 3-channel image. - * @param dst The destination image of the same format and the same size as the source. - * @param sp The spatial window radius. - * @param sr The color window radius. + * @param src The source 8-bit, 3-channel image. + * @param dst The destination image of the same format and the same size as the source. + * @param sp The spatial window radius. + * @param sr The color window radius. * @param maxLevel Maximum level of the pyramid for the segmentation. * @param termcrit Termination criteria: when to stop meanshift iterations. */ @@ -6088,34 +6189,29 @@ public static void pyrMeanShiftFiltering(Mat src, Mat dst, double sp, double sr, pyrMeanShiftFiltering_0(src.nativeObj, dst.nativeObj, sp, sr, maxLevel, termcrit.type, termcrit.maxCount, termcrit.epsilon); } - - // - // C++: void cv::watershed(Mat image, Mat& markers) - // - /** * Performs initial step of meanshift segmentation of an image. - *

      + * * The function implements the filtering stage of meanshift segmentation, that is, the output of the * function is the filtered "posterized" image with color gradients and fine-grain texture flattened. * At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes * meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is * considered: - *

      + * * \((x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\) - *

      + * * where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively * (though, the algorithm does not depend on the color space used, so any 3-component color space can * be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector * (R',G',B') are found and they act as the neighborhood center on the next iteration: - *

      + * * \((X,Y)~(X',Y'), (R,G,B)~(R',G',B').\) - *

      + * * After the iterations over, the color components of the initial pixel (that is, the pixel from where * the iterations started) are set to the final value (average color at the last iteration): - *

      + * * \(I(X,Y) <- (R*,G*,B*)\) - *

      + * * When maxLevel > 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is * run on the smallest layer first. After that, the results are propagated to the larger layer and the * iterations are run again only on those pixels where the layer colors differ by more than sr from the @@ -6123,44 +6219,39 @@ public static void pyrMeanShiftFiltering(Mat src, Mat dst, double sp, double sr, * results will be actually different from the ones obtained by running the meanshift procedure on the * whole original image (i.e. when maxLevel==0). * - * @param src The source 8-bit, 3-channel image. - * @param dst The destination image of the same format and the same size as the source. - * @param sp The spatial window radius. - * @param sr The color window radius. + * @param src The source 8-bit, 3-channel image. + * @param dst The destination image of the same format and the same size as the source. + * @param sp The spatial window radius. + * @param sr The color window radius. * @param maxLevel Maximum level of the pyramid for the segmentation. */ public static void pyrMeanShiftFiltering(Mat src, Mat dst, double sp, double sr, int maxLevel) { pyrMeanShiftFiltering_1(src.nativeObj, dst.nativeObj, sp, sr, maxLevel); } - - // - // C++: void cv::pyrMeanShiftFiltering(Mat src, Mat& dst, double sp, double sr, int maxLevel = 1, TermCriteria termcrit = TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1)) - // - /** * Performs initial step of meanshift segmentation of an image. - *

      + * * The function implements the filtering stage of meanshift segmentation, that is, the output of the * function is the filtered "posterized" image with color gradients and fine-grain texture flattened. * At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes * meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is * considered: - *

      + * * \((x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\) - *

      + * * where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively * (though, the algorithm does not depend on the color space used, so any 3-component color space can * be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector * (R',G',B') are found and they act as the neighborhood center on the next iteration: - *

      + * * \((X,Y)~(X',Y'), (R,G,B)~(R',G',B').\) - *

      + * * After the iterations over, the color components of the initial pixel (that is, the pixel from where * the iterations started) are set to the final value (average color at the last iteration): - *

      + * * \(I(X,Y) <- (R*,G*,B*)\) - *

      + * * When maxLevel > 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is * run on the smallest layer first. After that, the results are propagated to the larger layer and the * iterations are run again only on those pixels where the layer colors differ by more than sr from the @@ -6170,31 +6261,36 @@ public static void pyrMeanShiftFiltering(Mat src, Mat dst, double sp, double sr, * * @param src The source 8-bit, 3-channel image. * @param dst The destination image of the same format and the same size as the source. - * @param sp The spatial window radius. - * @param sr The color window radius. + * @param sp The spatial window radius. + * @param sr The color window radius. */ public static void pyrMeanShiftFiltering(Mat src, Mat dst, double sp, double sr) { pyrMeanShiftFiltering_2(src.nativeObj, dst.nativeObj, sp, sr); } + + // + // C++: void cv::grabCut(Mat img, Mat& mask, Rect rect, Mat& bgdModel, Mat& fgdModel, int iterCount, int mode = GC_EVAL) + // + /** * Runs the GrabCut algorithm. - *

      + * * The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut). * - * @param img Input 8-bit 3-channel image. - * @param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when - * mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses. - * @param rect ROI containing a segmented object. The pixels outside of the ROI are marked as - * "obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT . - * @param bgdModel Temporary array for the background model. Do not modify it while you are - * processing the same image. - * @param fgdModel Temporary arrays for the foreground model. Do not modify it while you are - * processing the same image. + * @param img Input 8-bit 3-channel image. + * @param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when + * mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses. + * @param rect ROI containing a segmented object. The pixels outside of the ROI are marked as + * "obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT . + * @param bgdModel Temporary array for the background model. Do not modify it while you are + * processing the same image. + * @param fgdModel Temporary arrays for the foreground model. Do not modify it while you are + * processing the same image. * @param iterCount Number of iterations the algorithm should make before returning the result. Note - * that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or - * mode==GC_EVAL . - * @param mode Operation mode that could be one of the #GrabCutModes + * that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or + * mode==GC_EVAL . + * @param mode Operation mode that could be one of the #GrabCutModes */ public static void grabCut(Mat img, Mat mask, Rect rect, Mat bgdModel, Mat fgdModel, int iterCount, int mode) { grabCut_0(img.nativeObj, mask.nativeObj, rect.x, rect.y, rect.width, rect.height, bgdModel.nativeObj, fgdModel.nativeObj, iterCount, mode); @@ -6202,21 +6298,21 @@ public static void grabCut(Mat img, Mat mask, Rect rect, Mat bgdModel, Mat fgdMo /** * Runs the GrabCut algorithm. - *

      + * * The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut). * - * @param img Input 8-bit 3-channel image. - * @param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when - * mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses. - * @param rect ROI containing a segmented object. The pixels outside of the ROI are marked as - * "obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT . - * @param bgdModel Temporary array for the background model. Do not modify it while you are - * processing the same image. - * @param fgdModel Temporary arrays for the foreground model. Do not modify it while you are - * processing the same image. + * @param img Input 8-bit 3-channel image. + * @param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when + * mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses. + * @param rect ROI containing a segmented object. The pixels outside of the ROI are marked as + * "obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT . + * @param bgdModel Temporary array for the background model. Do not modify it while you are + * processing the same image. + * @param fgdModel Temporary arrays for the foreground model. Do not modify it while you are + * processing the same image. * @param iterCount Number of iterations the algorithm should make before returning the result. Note - * that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or - * mode==GC_EVAL . + * that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or + * mode==GC_EVAL . */ public static void grabCut(Mat img, Mat mask, Rect rect, Mat bgdModel, Mat fgdModel, int iterCount) { grabCut_1(img.nativeObj, mask.nativeObj, rect.x, rect.y, rect.width, rect.height, bgdModel.nativeObj, fgdModel.nativeObj, iterCount); @@ -6224,18 +6320,18 @@ public static void grabCut(Mat img, Mat mask, Rect rect, Mat bgdModel, Mat fgdMo // - // C++: void cv::grabCut(Mat img, Mat& mask, Rect rect, Mat& bgdModel, Mat& fgdModel, int iterCount, int mode = GC_EVAL) + // C++: void cv::distanceTransform(Mat src, Mat& dst, Mat& labels, int distanceType, int maskSize, int labelType = DIST_LABEL_CCOMP) // /** * Calculates the distance to the closest zero pixel for each pixel of the source image. - *

      + * * The function cv::distanceTransform calculates the approximate or precise distance from every binary * image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero. - *

      + * * When maskSize == #DIST_MASK_PRECISE and distanceType == #DIST_L2 , the function runs the * algorithm described in CITE: Felzenszwalb04 . This algorithm is parallelized with the TBB library. - *

      + * * In other cases, the algorithm CITE: Borgefors86 is used. This means that for a pixel the function * finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical, * diagonal, or knight's move (the latest is available for a \(5\times 5\) mask). The overall @@ -6264,11 +6360,11 @@ public static void grabCut(Mat img, Mat mask, Rect rect, Mat bgdModel, Mat fgdMo * DIST_C: {@code a = 1, b = 1} *

    • *
    - *

    + * * Typically, for a fast, coarse distance estimation #DIST_L2, a \(3\times 3\) mask is used. For a * more accurate distance estimation #DIST_L2, a \(5\times 5\) mask or the precise algorithm is used. * Note that both the precise and the approximate algorithms are linear on the number of pixels. - *

    + * * This variant of the function does not only compute the minimum distance for each pixel \((x, y)\) * but also identifies the nearest connected component consisting of zero pixels * (labelType==#DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==#DIST_LABEL_PIXEL). Index of the @@ -6276,23 +6372,23 @@ public static void grabCut(Mat img, Mat mask, Rect rect, Mat bgdModel, Mat fgdMo * automatically finds connected components of zero pixels in the input image and marks them with * distinct labels. When labelType==#DIST_LABEL_PIXEL, the function scans through the input image and * marks all the zero pixels with distinct labels. - *

    + * * In this mode, the complexity is still linear. That is, the function provides a very fast way to * compute the Voronoi diagram for a binary image. Currently, the second variant can use only the * approximate distance transform algorithm, i.e. maskSize=#DIST_MASK_PRECISE is not supported * yet. * - * @param src 8-bit, single-channel (binary) source image. - * @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, - * single-channel image of the same size as src. - * @param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type - * CV_32SC1 and the same size as src. + * @param src 8-bit, single-channel (binary) source image. + * @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, + * single-channel image of the same size as src. + * @param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type + * CV_32SC1 and the same size as src. * @param distanceType Type of distance, see #DistanceTypes - * @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. - * #DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, - * the parameter is forced to 3 because a \(3\times 3\) mask gives the same result as \(5\times - * 5\) or any larger aperture. - * @param labelType Type of the label array to build, see #DistanceTransformLabelTypes. + * @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. + * #DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, + * the parameter is forced to 3 because a \(3\times 3\) mask gives the same result as \(5\times + * 5\) or any larger aperture. + * @param labelType Type of the label array to build, see #DistanceTransformLabelTypes. */ public static void distanceTransformWithLabels(Mat src, Mat dst, Mat labels, int distanceType, int maskSize, int labelType) { distanceTransformWithLabels_0(src.nativeObj, dst.nativeObj, labels.nativeObj, distanceType, maskSize, labelType); @@ -6300,13 +6396,13 @@ public static void distanceTransformWithLabels(Mat src, Mat dst, Mat labels, int /** * Calculates the distance to the closest zero pixel for each pixel of the source image. - *

    + * * The function cv::distanceTransform calculates the approximate or precise distance from every binary * image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero. - *

    + * * When maskSize == #DIST_MASK_PRECISE and distanceType == #DIST_L2 , the function runs the * algorithm described in CITE: Felzenszwalb04 . This algorithm is parallelized with the TBB library. - *

    + * * In other cases, the algorithm CITE: Borgefors86 is used. This means that for a pixel the function * finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical, * diagonal, or knight's move (the latest is available for a \(5\times 5\) mask). The overall @@ -6335,11 +6431,11 @@ public static void distanceTransformWithLabels(Mat src, Mat dst, Mat labels, int * DIST_C: {@code a = 1, b = 1} * * - *

    + * * Typically, for a fast, coarse distance estimation #DIST_L2, a \(3\times 3\) mask is used. For a * more accurate distance estimation #DIST_L2, a \(5\times 5\) mask or the precise algorithm is used. * Note that both the precise and the approximate algorithms are linear on the number of pixels. - *

    + * * This variant of the function does not only compute the minimum distance for each pixel \((x, y)\) * but also identifies the nearest connected component consisting of zero pixels * (labelType==#DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==#DIST_LABEL_PIXEL). Index of the @@ -6347,22 +6443,22 @@ public static void distanceTransformWithLabels(Mat src, Mat dst, Mat labels, int * automatically finds connected components of zero pixels in the input image and marks them with * distinct labels. When labelType==#DIST_LABEL_PIXEL, the function scans through the input image and * marks all the zero pixels with distinct labels. - *

    + * * In this mode, the complexity is still linear. That is, the function provides a very fast way to * compute the Voronoi diagram for a binary image. Currently, the second variant can use only the * approximate distance transform algorithm, i.e. maskSize=#DIST_MASK_PRECISE is not supported * yet. * - * @param src 8-bit, single-channel (binary) source image. - * @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, - * single-channel image of the same size as src. - * @param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type - * CV_32SC1 and the same size as src. + * @param src 8-bit, single-channel (binary) source image. + * @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, + * single-channel image of the same size as src. + * @param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type + * CV_32SC1 and the same size as src. * @param distanceType Type of distance, see #DistanceTypes - * @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. - * #DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, - * the parameter is forced to 3 because a \(3\times 3\) mask gives the same result as \(5\times - * 5\) or any larger aperture. + * @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. + * #DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, + * the parameter is forced to 3 because a \(3\times 3\) mask gives the same result as \(5\times + * 5\) or any larger aperture. */ public static void distanceTransformWithLabels(Mat src, Mat dst, Mat labels, int distanceType, int maskSize) { distanceTransformWithLabels_1(src.nativeObj, dst.nativeObj, labels.nativeObj, distanceType, maskSize); @@ -6370,33 +6466,35 @@ public static void distanceTransformWithLabels(Mat src, Mat dst, Mat labels, int // - // C++: void cv::distanceTransform(Mat src, Mat& dst, Mat& labels, int distanceType, int maskSize, int labelType = DIST_LABEL_CCOMP) + // C++: void cv::distanceTransform(Mat src, Mat& dst, int distanceType, int maskSize, int dstType = CV_32F) // /** - * @param src 8-bit, single-channel (binary) source image. - * @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, - * single-channel image of the same size as src . + * + * @param src 8-bit, single-channel (binary) source image. + * @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, + * single-channel image of the same size as src . * @param distanceType Type of distance, see #DistanceTypes - * @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the - * #DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \(3\times 3\) mask gives - * the same result as \(5\times 5\) or any larger aperture. - * @param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for - * the first variant of the function and distanceType == #DIST_L1. + * @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the + * #DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \(3\times 3\) mask gives + * the same result as \(5\times 5\) or any larger aperture. + * @param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for + * the first variant of the function and distanceType == #DIST_L1. */ public static void distanceTransform(Mat src, Mat dst, int distanceType, int maskSize, int dstType) { distanceTransform_0(src.nativeObj, dst.nativeObj, distanceType, maskSize, dstType); } /** - * @param src 8-bit, single-channel (binary) source image. - * @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, - * single-channel image of the same size as src . + * + * @param src 8-bit, single-channel (binary) source image. + * @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, + * single-channel image of the same size as src . * @param distanceType Type of distance, see #DistanceTypes - * @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the - * #DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \(3\times 3\) mask gives - * the same result as \(5\times 5\) or any larger aperture. - * the first variant of the function and distanceType == #DIST_L1. + * @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the + * #DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \(3\times 3\) mask gives + * the same result as \(5\times 5\) or any larger aperture. + * the first variant of the function and distanceType == #DIST_L1. */ public static void distanceTransform(Mat src, Mat dst, int distanceType, int maskSize) { distanceTransform_1(src.nativeObj, dst.nativeObj, distanceType, maskSize); @@ -6404,12 +6502,12 @@ public static void distanceTransform(Mat src, Mat dst, int distanceType, int mas // - // C++: void cv::distanceTransform(Mat src, Mat& dst, int distanceType, int maskSize, int dstType = CV_32F) + // C++: int cv::floodFill(Mat& image, Mat& mask, Point seedPoint, Scalar newVal, Rect* rect = 0, Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), int flags = 4) // /** * Fills a connected component with the given color. - *

    + * * The function cv::floodFill fills a connected component starting from the seed point with the specified * color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The * pixel at \((x,y)\) is considered to belong to the repainted domain if: @@ -6450,8 +6548,8 @@ public static void distanceTransform(Mat src, Mat dst, int distanceType, int mas * \(\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\) * * - *

    - *

    + * + * * where \(src(x',y')\) is the value of one of pixel neighbors that is already known to belong to the * component. That is, to be added to the connected component, a color/brightness of the pixel should * be close enough to: @@ -6464,60 +6562,55 @@ public static void distanceTransform(Mat src, Mat dst, int distanceType, int mas * Color/brightness of the seed point in case of a fixed range. * * - *

    + * * Use these functions to either mark a connected component with the specified color in-place, or build * a mask and then extract the contour, or copy the region to another image, and so on. * - * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the - * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See - * the details below. - * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels - * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an - * input and output parameter, you must take responsibility of initializing it. - * Flood-filling cannot go across non-zero pixels in the input mask. For example, - * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the - * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags - * as described below. Additionally, the function fills the border of the mask with ones to simplify - * internal processing. It is therefore possible to use the same mask in multiple calls to the function - * to make sure the filled areas do not overlap. + * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the + * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See + * the details below. + * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels + * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an + * input and output parameter, you must take responsibility of initializing it. + * Flood-filling cannot go across non-zero pixels in the input mask. For example, + * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the + * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags + * as described below. Additionally, the function fills the border of the mask with ones to simplify + * internal processing. It is therefore possible to use the same mask in multiple calls to the function + * to make sure the filled areas do not overlap. * @param seedPoint Starting point. - * @param newVal New value of the repainted domain pixels. - * @param loDiff Maximal lower brightness/color difference between the currently observed pixel and - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * @param upDiff Maximal upper brightness/color difference between the currently observed pixel and - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * @param rect Optional output parameter set by the function to the minimum bounding rectangle of the - * repainted domain. - * @param flags Operation flags. The first 8 bits contain a connectivity value. The default value of - * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A - * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) - * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill - * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest - * neighbours and fill the mask with a value of 255. The following additional options occupy higher - * bits and therefore may be further combined with the connectivity and mask fill values using - * bit-wise or (|), see #FloodFillFlags. - * - * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the - * pixel \((x+1, y+1)\) in the mask . - *

    - * SEE: findContours + * @param newVal New value of the repainted domain pixels. + * @param loDiff Maximal lower brightness/color difference between the currently observed pixel and + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * @param upDiff Maximal upper brightness/color difference between the currently observed pixel and + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * @param rect Optional output parameter set by the function to the minimum bounding rectangle of the + * repainted domain. + * @param flags Operation flags. The first 8 bits contain a connectivity value. The default value of + * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A + * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) + * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill + * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest + * neighbours and fill the mask with a value of 255. The following additional options occupy higher + * bits and therefore may be further combined with the connectivity and mask fill values using + * bit-wise or (|), see #FloodFillFlags. + * + * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the + * pixel \((x+1, y+1)\) in the mask . + * + * SEE: findContours * @return automatically generated */ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, Rect rect, Scalar loDiff, Scalar upDiff, int flags) { double[] rect_out = new double[4]; int retVal = floodFill_0(image.nativeObj, mask.nativeObj, seedPoint.x, seedPoint.y, newVal.val[0], newVal.val[1], newVal.val[2], newVal.val[3], rect_out, loDiff.val[0], loDiff.val[1], loDiff.val[2], loDiff.val[3], upDiff.val[0], upDiff.val[1], upDiff.val[2], upDiff.val[3], flags); - if (rect != null) { - rect.x = (int) rect_out[0]; - rect.y = (int) rect_out[1]; - rect.width = (int) rect_out[2]; - rect.height = (int) rect_out[3]; - } + if(rect!=null){ rect.x = (int)rect_out[0]; rect.y = (int)rect_out[1]; rect.width = (int)rect_out[2]; rect.height = (int)rect_out[3]; } return retVal; } /** * Fills a connected component with the given color. - *

    + * * The function cv::floodFill fills a connected component starting from the seed point with the specified * color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The * pixel at \((x,y)\) is considered to belong to the repainted domain if: @@ -6558,8 +6651,8 @@ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, * \(\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\) * * - *

    - *

    + * + * * where \(src(x',y')\) is the value of one of pixel neighbors that is already known to belong to the * component. That is, to be added to the connected component, a color/brightness of the pixel should * be close enough to: @@ -6572,64 +6665,54 @@ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, * Color/brightness of the seed point in case of a fixed range. * * - *

    + * * Use these functions to either mark a connected component with the specified color in-place, or build * a mask and then extract the contour, or copy the region to another image, and so on. * - * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the - * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See - * the details below. - * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels - * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an - * input and output parameter, you must take responsibility of initializing it. - * Flood-filling cannot go across non-zero pixels in the input mask. For example, - * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the - * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags - * as described below. Additionally, the function fills the border of the mask with ones to simplify - * internal processing. It is therefore possible to use the same mask in multiple calls to the function - * to make sure the filled areas do not overlap. + * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the + * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See + * the details below. + * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels + * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an + * input and output parameter, you must take responsibility of initializing it. + * Flood-filling cannot go across non-zero pixels in the input mask. For example, + * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the + * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags + * as described below. Additionally, the function fills the border of the mask with ones to simplify + * internal processing. It is therefore possible to use the same mask in multiple calls to the function + * to make sure the filled areas do not overlap. * @param seedPoint Starting point. - * @param newVal New value of the repainted domain pixels. - * @param loDiff Maximal lower brightness/color difference between the currently observed pixel and - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * @param upDiff Maximal upper brightness/color difference between the currently observed pixel and - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * @param rect Optional output parameter set by the function to the minimum bounding rectangle of the - * repainted domain. - * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A - * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) - * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill - * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest - * neighbours and fill the mask with a value of 255. The following additional options occupy higher - * bits and therefore may be further combined with the connectivity and mask fill values using - * bit-wise or (|), see #FloodFillFlags. - * - * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the - * pixel \((x+1, y+1)\) in the mask . - *

    - * SEE: findContours + * @param newVal New value of the repainted domain pixels. + * @param loDiff Maximal lower brightness/color difference between the currently observed pixel and + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * @param upDiff Maximal upper brightness/color difference between the currently observed pixel and + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * @param rect Optional output parameter set by the function to the minimum bounding rectangle of the + * repainted domain. + * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A + * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) + * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill + * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest + * neighbours and fill the mask with a value of 255. The following additional options occupy higher + * bits and therefore may be further combined with the connectivity and mask fill values using + * bit-wise or (|), see #FloodFillFlags. + * + * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the + * pixel \((x+1, y+1)\) in the mask . + * + * SEE: findContours * @return automatically generated */ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, Rect rect, Scalar loDiff, Scalar upDiff) { double[] rect_out = new double[4]; int retVal = floodFill_1(image.nativeObj, mask.nativeObj, seedPoint.x, seedPoint.y, newVal.val[0], newVal.val[1], newVal.val[2], newVal.val[3], rect_out, loDiff.val[0], loDiff.val[1], loDiff.val[2], loDiff.val[3], upDiff.val[0], upDiff.val[1], upDiff.val[2], upDiff.val[3]); - if (rect != null) { - rect.x = (int) rect_out[0]; - rect.y = (int) rect_out[1]; - rect.width = (int) rect_out[2]; - rect.height = (int) rect_out[3]; - } + if(rect!=null){ rect.x = (int)rect_out[0]; rect.y = (int)rect_out[1]; rect.width = (int)rect_out[2]; rect.height = (int)rect_out[3]; } return retVal; } - - // - // C++: int cv::floodFill(Mat& image, Mat& mask, Point seedPoint, Scalar newVal, Rect* rect = 0, Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), int flags = 4) - // - /** * Fills a connected component with the given color. - *

    + * * The function cv::floodFill fills a connected component starting from the seed point with the specified * color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The * pixel at \((x,y)\) is considered to belong to the repainted domain if: @@ -6670,8 +6753,8 @@ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, * \(\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\) * * - *

    - *

    + * + * * where \(src(x',y')\) is the value of one of pixel neighbors that is already known to belong to the * component. That is, to be added to the connected component, a color/brightness of the pixel should * be close enough to: @@ -6684,58 +6767,53 @@ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, * Color/brightness of the seed point in case of a fixed range. * * - *

    + * * Use these functions to either mark a connected component with the specified color in-place, or build * a mask and then extract the contour, or copy the region to another image, and so on. * - * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the - * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See - * the details below. - * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels - * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an - * input and output parameter, you must take responsibility of initializing it. - * Flood-filling cannot go across non-zero pixels in the input mask. For example, - * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the - * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags - * as described below. Additionally, the function fills the border of the mask with ones to simplify - * internal processing. It is therefore possible to use the same mask in multiple calls to the function - * to make sure the filled areas do not overlap. + * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the + * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See + * the details below. + * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels + * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an + * input and output parameter, you must take responsibility of initializing it. + * Flood-filling cannot go across non-zero pixels in the input mask. For example, + * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the + * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags + * as described below. Additionally, the function fills the border of the mask with ones to simplify + * internal processing. It is therefore possible to use the same mask in multiple calls to the function + * to make sure the filled areas do not overlap. * @param seedPoint Starting point. - * @param newVal New value of the repainted domain pixels. - * @param loDiff Maximal lower brightness/color difference between the currently observed pixel and - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * @param rect Optional output parameter set by the function to the minimum bounding rectangle of the - * repainted domain. - * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A - * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) - * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill - * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest - * neighbours and fill the mask with a value of 255. The following additional options occupy higher - * bits and therefore may be further combined with the connectivity and mask fill values using - * bit-wise or (|), see #FloodFillFlags. - * - * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the - * pixel \((x+1, y+1)\) in the mask . - *

    - * SEE: findContours + * @param newVal New value of the repainted domain pixels. + * @param loDiff Maximal lower brightness/color difference between the currently observed pixel and + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * @param rect Optional output parameter set by the function to the minimum bounding rectangle of the + * repainted domain. + * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A + * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) + * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill + * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest + * neighbours and fill the mask with a value of 255. The following additional options occupy higher + * bits and therefore may be further combined with the connectivity and mask fill values using + * bit-wise or (|), see #FloodFillFlags. + * + * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the + * pixel \((x+1, y+1)\) in the mask . + * + * SEE: findContours * @return automatically generated */ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, Rect rect, Scalar loDiff) { double[] rect_out = new double[4]; int retVal = floodFill_2(image.nativeObj, mask.nativeObj, seedPoint.x, seedPoint.y, newVal.val[0], newVal.val[1], newVal.val[2], newVal.val[3], rect_out, loDiff.val[0], loDiff.val[1], loDiff.val[2], loDiff.val[3]); - if (rect != null) { - rect.x = (int) rect_out[0]; - rect.y = (int) rect_out[1]; - rect.width = (int) rect_out[2]; - rect.height = (int) rect_out[3]; - } + if(rect!=null){ rect.x = (int)rect_out[0]; rect.y = (int)rect_out[1]; rect.width = (int)rect_out[2]; rect.height = (int)rect_out[3]; } return retVal; } /** * Fills a connected component with the given color. - *

    + * * The function cv::floodFill fills a connected component starting from the seed point with the specified * color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The * pixel at \((x,y)\) is considered to belong to the repainted domain if: @@ -6776,8 +6854,8 @@ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, * \(\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\) * * - *

    - *

    + * + * * where \(src(x',y')\) is the value of one of pixel neighbors that is already known to belong to the * component. That is, to be added to the connected component, a color/brightness of the pixel should * be close enough to: @@ -6790,57 +6868,52 @@ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, * Color/brightness of the seed point in case of a fixed range. * * - *

    + * * Use these functions to either mark a connected component with the specified color in-place, or build * a mask and then extract the contour, or copy the region to another image, and so on. * - * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the - * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See - * the details below. - * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels - * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an - * input and output parameter, you must take responsibility of initializing it. - * Flood-filling cannot go across non-zero pixels in the input mask. For example, - * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the - * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags - * as described below. Additionally, the function fills the border of the mask with ones to simplify - * internal processing. It is therefore possible to use the same mask in multiple calls to the function - * to make sure the filled areas do not overlap. + * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the + * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See + * the details below. + * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels + * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an + * input and output parameter, you must take responsibility of initializing it. + * Flood-filling cannot go across non-zero pixels in the input mask. For example, + * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the + * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags + * as described below. Additionally, the function fills the border of the mask with ones to simplify + * internal processing. It is therefore possible to use the same mask in multiple calls to the function + * to make sure the filled areas do not overlap. * @param seedPoint Starting point. - * @param newVal New value of the repainted domain pixels. - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * @param rect Optional output parameter set by the function to the minimum bounding rectangle of the - * repainted domain. - * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A - * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) - * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill - * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest - * neighbours and fill the mask with a value of 255. The following additional options occupy higher - * bits and therefore may be further combined with the connectivity and mask fill values using - * bit-wise or (|), see #FloodFillFlags. - * - * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the - * pixel \((x+1, y+1)\) in the mask . - *

    - * SEE: findContours + * @param newVal New value of the repainted domain pixels. + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * @param rect Optional output parameter set by the function to the minimum bounding rectangle of the + * repainted domain. + * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A + * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) + * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill + * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest + * neighbours and fill the mask with a value of 255. The following additional options occupy higher + * bits and therefore may be further combined with the connectivity and mask fill values using + * bit-wise or (|), see #FloodFillFlags. + * + * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the + * pixel \((x+1, y+1)\) in the mask . + * + * SEE: findContours * @return automatically generated */ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, Rect rect) { double[] rect_out = new double[4]; int retVal = floodFill_3(image.nativeObj, mask.nativeObj, seedPoint.x, seedPoint.y, newVal.val[0], newVal.val[1], newVal.val[2], newVal.val[3], rect_out); - if (rect != null) { - rect.x = (int) rect_out[0]; - rect.y = (int) rect_out[1]; - rect.width = (int) rect_out[2]; - rect.height = (int) rect_out[3]; - } + if(rect!=null){ rect.x = (int)rect_out[0]; rect.y = (int)rect_out[1]; rect.width = (int)rect_out[2]; rect.height = (int)rect_out[3]; } return retVal; } /** * Fills a connected component with the given color. - *

    + * * The function cv::floodFill fills a connected component starting from the seed point with the specified * color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The * pixel at \((x,y)\) is considered to belong to the repainted domain if: @@ -6881,8 +6954,8 @@ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, * \(\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\) * * - *

    - *

    + * + * * where \(src(x',y')\) is the value of one of pixel neighbors that is already known to belong to the * component. That is, to be added to the connected component, a color/brightness of the pixel should * be close enough to: @@ -6895,68 +6968,79 @@ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, * Color/brightness of the seed point in case of a fixed range. * * - *

    + * * Use these functions to either mark a connected component with the specified color in-place, or build * a mask and then extract the contour, or copy the region to another image, and so on. * - * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the - * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See - * the details below. - * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels - * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an - * input and output parameter, you must take responsibility of initializing it. - * Flood-filling cannot go across non-zero pixels in the input mask. For example, - * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the - * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags - * as described below. Additionally, the function fills the border of the mask with ones to simplify - * internal processing. It is therefore possible to use the same mask in multiple calls to the function - * to make sure the filled areas do not overlap. + * @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the + * function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See + * the details below. + * @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels + * taller than image. If an empty Mat is passed it will be created automatically. Since this is both an + * input and output parameter, you must take responsibility of initializing it. + * Flood-filling cannot go across non-zero pixels in the input mask. For example, + * an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the + * mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags + * as described below. Additionally, the function fills the border of the mask with ones to simplify + * internal processing. It is therefore possible to use the same mask in multiple calls to the function + * to make sure the filled areas do not overlap. * @param seedPoint Starting point. - * @param newVal New value of the repainted domain pixels. - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * one of its neighbors belonging to the component, or a seed pixel being added to the component. - * repainted domain. - * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A - * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) - * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill - * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest - * neighbours and fill the mask with a value of 255. The following additional options occupy higher - * bits and therefore may be further combined with the connectivity and mask fill values using - * bit-wise or (|), see #FloodFillFlags. - * - * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the - * pixel \((x+1, y+1)\) in the mask . - *

    - * SEE: findContours + * @param newVal New value of the repainted domain pixels. + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * one of its neighbors belonging to the component, or a seed pixel being added to the component. + * repainted domain. + * 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A + * connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) + * will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill + * the mask (the default value is 1). For example, 4 | ( 255 << 8 ) will consider 4 nearest + * neighbours and fill the mask with a value of 255. The following additional options occupy higher + * bits and therefore may be further combined with the connectivity and mask fill values using + * bit-wise or (|), see #FloodFillFlags. + * + * Note: Since the mask is larger than the filled image, a pixel \((x, y)\) in image corresponds to the + * pixel \((x+1, y+1)\) in the mask . + * + * SEE: findContours * @return automatically generated */ public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal) { return floodFill_4(image.nativeObj, mask.nativeObj, seedPoint.x, seedPoint.y, newVal.val[0], newVal.val[1], newVal.val[2], newVal.val[3]); } + + // + // C++: void cv::blendLinear(Mat src1, Mat src2, Mat weights1, Mat weights2, Mat& dst) + // + /** - * variant without {@code mask} parameter * - * @param src1 automatically generated - * @param src2 automatically generated + * + * variant without {@code mask} parameter + * @param src1 automatically generated + * @param src2 automatically generated * @param weights1 automatically generated * @param weights2 automatically generated - * @param dst automatically generated + * @param dst automatically generated */ public static void blendLinear(Mat src1, Mat src2, Mat weights1, Mat weights2, Mat dst) { blendLinear_0(src1.nativeObj, src2.nativeObj, weights1.nativeObj, weights2.nativeObj, dst.nativeObj); } + + // + // C++: void cv::cvtColor(Mat src, Mat& dst, int code, int dstCn = 0) + // + /** * Converts an image from one color space to another. - *

    + * * The function converts an input image from one color space to another. In case of a transformation * to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note * that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the * bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue * component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and * sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on. - *

    + * * The conventional ranges for R, G, and B channel values are: *

      *
    • @@ -6969,7 +7053,7 @@ public static void blendLinear(Mat src1, Mat src2, Mat weights1, Mat weights2, M * 0 to 1 for CV_32F images *
    • *
    - *

    + * * In case of linear transformations, the range does not matter. But in case of a non-linear * transformation, an input RGB image should be normalized to the proper value range to get the correct * results, for example, for RGB \(\rightarrow\) L\*u\*v\* transformation. For example, if you have a @@ -6984,38 +7068,33 @@ public static void blendLinear(Mat src1, Mat src2, Mat weights1, Mat weights2, M * applications, this will not be noticeable but it is recommended to use 32-bit images in applications * that need the full range of colors or that convert an image before an operation and then convert * back. - *

    + * * If conversion adds the alpha channel, its value will set to the maximum of corresponding channel * range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F. * - * @param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision - * floating-point. - * @param dst output image of the same size and depth as src. - * @param code color space conversion code (see #ColorConversionCodes). + * @param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision + * floating-point. + * @param dst output image of the same size and depth as src. + * @param code color space conversion code (see #ColorConversionCodes). * @param dstCn number of channels in the destination image; if the parameter is 0, the number of the - * channels is derived automatically from src and code. - *

    - * SEE: REF: imgproc_color_conversions + * channels is derived automatically from src and code. + * + * SEE: REF: imgproc_color_conversions */ public static void cvtColor(Mat src, Mat dst, int code, int dstCn) { cvtColor_0(src.nativeObj, dst.nativeObj, code, dstCn); } - - // - // C++: void cv::blendLinear(Mat src1, Mat src2, Mat weights1, Mat weights2, Mat& dst) - // - /** * Converts an image from one color space to another. - *

    + * * The function converts an input image from one color space to another. In case of a transformation * to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note * that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the * bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue * component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and * sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on. - *

    + * * The conventional ranges for R, G, and B channel values are: *

      *
    • @@ -7028,7 +7107,7 @@ public static void cvtColor(Mat src, Mat dst, int code, int dstCn) { * 0 to 1 for CV_32F images *
    • *
    - *

    + * * In case of linear transformations, the range does not matter. But in case of a non-linear * transformation, an input RGB image should be normalized to the proper value range to get the correct * results, for example, for RGB \(\rightarrow\) L\*u\*v\* transformation. For example, if you have a @@ -7043,17 +7122,17 @@ public static void cvtColor(Mat src, Mat dst, int code, int dstCn) { * applications, this will not be noticeable but it is recommended to use 32-bit images in applications * that need the full range of colors or that convert an image before an operation and then convert * back. - *

    + * * If conversion adds the alpha channel, its value will set to the maximum of corresponding channel * range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F. * - * @param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision - * floating-point. - * @param dst output image of the same size and depth as src. + * @param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision + * floating-point. + * @param dst output image of the same size and depth as src. * @param code color space conversion code (see #ColorConversionCodes). - * channels is derived automatically from src and code. - *

    - * SEE: REF: imgproc_color_conversions + * channels is derived automatically from src and code. + * + * SEE: REF: imgproc_color_conversions */ public static void cvtColor(Mat src, Mat dst, int code) { cvtColor_1(src.nativeObj, dst.nativeObj, code); @@ -7061,15 +7140,19 @@ public static void cvtColor(Mat src, Mat dst, int code) { // - // C++: void cv::cvtColor(Mat src, Mat& dst, int code, int dstCn = 0) + // C++: void cv::cvtColorTwoPlane(Mat src1, Mat src2, Mat& dst, int code) // /** * Converts an image from one color space to another where the source image is * stored in two planes. - *

    + * * This function only supports YUV420 to RGB conversion as of now. * + * @param src1 8-bit image (#CV_8U) of the Y plane. + * @param src2 image containing interleaved U/V plane. + * @param dst output image. + * @param code Specifies the type of conversion. It can take any of the following values: *

      *
    • * #COLOR_YUV2BGR_NV12 @@ -7084,129 +7167,124 @@ public static void cvtColor(Mat src, Mat dst, int code) { * #COLOR_YUV2RGBA_NV12 *
    • *
    • - * #COLOR_YUV2BGR_NV21 + * #COLOR_YUV2BGR_NV21 + *
    • + *
    • + * #COLOR_YUV2RGB_NV21 + *
    • + *
    • + * #COLOR_YUV2BGRA_NV21 + *
    • + *
    • + * #COLOR_YUV2RGBA_NV21 + *
    • + *
    + */ + public static void cvtColorTwoPlane(Mat src1, Mat src2, Mat dst, int code) { + cvtColorTwoPlane_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, code); + } + + + // + // C++: void cv::demosaicing(Mat src, Mat& dst, int code, int dstCn = 0) + // + + /** + * main function for all demosaicing processes + * + * @param src input image: 8-bit unsigned or 16-bit unsigned. + * @param dst output image of the same size and depth as src. + * @param code Color space conversion code (see the description below). + * @param dstCn number of channels in the destination image; if the parameter is 0, the number of the + * channels is derived automatically from src and code. + * + * The function can do the following transformations: + * + *
      + *
    • + * Demosaicing using bilinear interpolation *
    • + *
    + * + * #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR + * + * #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY + * + *
      *
    • - * #COLOR_YUV2RGB_NV21 + * Demosaicing using Variable Number of Gradients. *
    • + *
    + * + * #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG + * + *
      *
    • - * #COLOR_YUV2BGRA_NV21 + * Edge-Aware Demosaicing. *
    • + *
    + * + * #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA + * + *
      *
    • - * #COLOR_YUV2RGBA_NV21 + * Demosaicing with alpha channel *
    • *
    * - * @param src1 automatically generated - * @param src2 automatically generated - * @param dst automatically generated - * @param code automatically generated - */ - public static void cvtColorTwoPlane(Mat src1, Mat src2, Mat dst, int code) { - cvtColorTwoPlane_0(src1.nativeObj, src2.nativeObj, dst.nativeObj, code); - } - - /** - * main function for all demosaicing processes + * #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA * - * @param src input image: 8-bit unsigned or 16-bit unsigned. - * @param dst output image of the same size and depth as src. - * @param code Color space conversion code (see the description below). - * @param dstCn number of channels in the destination image; if the parameter is 0, the number of the - * channels is derived automatically from src and code. - *

    - * The function can do the following transformations: - * - *

      - *
    • - * Demosaicing using bilinear interpolation - *
    • - *
    - *

    - * #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR - *

    - * #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY - * - *

      - *
    • - * Demosaicing using Variable Number of Gradients. - *
    • - *
    - *

    - * #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG - * - *

      - *
    • - * Edge-Aware Demosaicing. - *
    • - *
    - *

    - * #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA - * - *

      - *
    • - * Demosaicing with alpha channel - *
    • - *
    - *

    - * #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA - *

    - * SEE: cvtColor + * SEE: cvtColor */ public static void demosaicing(Mat src, Mat dst, int code, int dstCn) { demosaicing_0(src.nativeObj, dst.nativeObj, code, dstCn); } - - // - // C++: void cv::cvtColorTwoPlane(Mat src1, Mat src2, Mat& dst, int code) - // - /** * main function for all demosaicing processes * - * @param src input image: 8-bit unsigned or 16-bit unsigned. - * @param dst output image of the same size and depth as src. + * @param src input image: 8-bit unsigned or 16-bit unsigned. + * @param dst output image of the same size and depth as src. * @param code Color space conversion code (see the description below). - * channels is derived automatically from src and code. - *

    - * The function can do the following transformations: - * - *

      - *
    • - * Demosaicing using bilinear interpolation - *
    • - *
    - *

    - * #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR - *

    - * #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY - * - *

      - *
    • - * Demosaicing using Variable Number of Gradients. - *
    • - *
    - *

    - * #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG - * - *

      - *
    • - * Edge-Aware Demosaicing. - *
    • - *
    - *

    - * #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA - * - *

      - *
    • - * Demosaicing with alpha channel - *
    • - *
    - *

    - * #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA - *

    - * SEE: cvtColor + * channels is derived automatically from src and code. + * + * The function can do the following transformations: + * + *

      + *
    • + * Demosaicing using bilinear interpolation + *
    • + *
    + * + * #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR + * + * #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY + * + *
      + *
    • + * Demosaicing using Variable Number of Gradients. + *
    • + *
    + * + * #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG + * + *
      + *
    • + * Edge-Aware Demosaicing. + *
    • + *
    + * + * #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA + * + *
      + *
    • + * Demosaicing with alpha channel + *
    • + *
    + * + * #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA + * + * SEE: cvtColor */ public static void demosaicing(Mat src, Mat dst, int code) { demosaicing_1(src.nativeObj, dst.nativeObj, code); @@ -7214,24 +7292,24 @@ public static void demosaicing(Mat src, Mat dst, int code) { // - // C++: void cv::demosaicing(Mat src, Mat& dst, int code, int dstCn = 0) + // C++: Moments cv::moments(Mat array, bool binaryImage = false) // /** * Calculates all of the moments up to the third order of a polygon or rasterized shape. - *

    + * * The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The * results are returned in the structure cv::Moments. * - * @param array Raster image (single-channel, 8-bit or floating-point 2D array) or an array ( - * \(1 \times N\) or \(N \times 1\) ) of 2D points (Point or Point2f ). + * @param array Raster image (single-channel, 8-bit or floating-point 2D array) or an array ( + * \(1 \times N\) or \(N \times 1\) ) of 2D points (Point or Point2f ). * @param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is - * used for images only. + * used for images only. * @return moments. * * Note: Only applicable to contour moments calculations from Python bindings: Note that the numpy * type for the input array should be either np.int32 or np.float32. - *

    + * * SEE: contourArea, arcLength */ public static Moments moments(Mat array, boolean binaryImage) { @@ -7240,18 +7318,18 @@ public static Moments moments(Mat array, boolean binaryImage) { /** * Calculates all of the moments up to the third order of a polygon or rasterized shape. - *

    + * * The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The * results are returned in the structure cv::Moments. * * @param array Raster image (single-channel, 8-bit or floating-point 2D array) or an array ( - * \(1 \times N\) or \(N \times 1\) ) of 2D points (Point or Point2f ). - * used for images only. + * \(1 \times N\) or \(N \times 1\) ) of 2D points (Point or Point2f ). + * used for images only. * @return moments. * * Note: Only applicable to contour moments calculations from Python bindings: Note that the numpy * type for the input array should be either np.int32 or np.float32. - *

    + * * SEE: contourArea, arcLength */ public static Moments moments(Mat array) { @@ -7260,22 +7338,27 @@ public static Moments moments(Mat array) { // - // C++: Moments cv::moments(Mat array, bool binaryImage = false) + // C++: void cv::HuMoments(Moments m, Mat& hu) // public static void HuMoments(Moments m, Mat hu) { HuMoments_0(m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03, hu.nativeObj); } + + // + // C++: void cv::matchTemplate(Mat image, Mat templ, Mat& result, int method, Mat mask = Mat()) + // + /** * Compares a template against overlapped image regions. - *

    + * * The function slides through image , compares the overlapped patches of size \(w \times h\) against * templ using the specified method and stores the comparison results in result . #TemplateMatchModes * describes the formulae for the available comparison methods ( \(I\) denotes image, \(T\) * template, \(R\) result, \(M\) the optional mask ). The summation is done over template and/or * the image patch: \(x' = 0...w-1, y' = 0...h-1\) - *

    + * * After the function finishes the comparison, the best matches can be found as global minimums (when * #TM_SQDIFF was used) or maximums (when #TM_CCORR or #TM_CCOEFF was used) using the * #minMaxLoc function. In case of a color image, template summation in the numerator and each sum in @@ -7283,37 +7366,32 @@ public static void HuMoments(Moments m, Mat hu) { * That is, the function can take a color template and a color image. The result will still be a * single-channel image, which is easier to analyze. * - * @param image Image where the search is running. It must be 8-bit or 32-bit floating-point. - * @param templ Searched template. It must be not greater than the source image and have the same - * data type. + * @param image Image where the search is running. It must be 8-bit or 32-bit floating-point. + * @param templ Searched template. It must be not greater than the source image and have the same + * data type. * @param result Map of comparison results. It must be single-channel 32-bit floating-point. If image - * is \(W \times H\) and templ is \(w \times h\) , then result is \((W-w+1) \times (H-h+1)\) . + * is \(W \times H\) and templ is \(w \times h\) , then result is \((W-w+1) \times (H-h+1)\) . * @param method Parameter specifying the comparison method, see #TemplateMatchModes - * @param mask Optional mask. It must have the same size as templ. It must either have the same number - * of channels as template or only one channel, which is then used for all template and - * image channels. If the data type is #CV_8U, the mask is interpreted as a binary mask, - * meaning only elements where mask is nonzero are used and are kept unchanged independent - * of the actual mask value (weight equals 1). For data tpye #CV_32F, the mask values are - * used as weights. The exact formulas are documented in #TemplateMatchModes. + * @param mask Optional mask. It must have the same size as templ. It must either have the same number + * of channels as template or only one channel, which is then used for all template and + * image channels. If the data type is #CV_8U, the mask is interpreted as a binary mask, + * meaning only elements where mask is nonzero are used and are kept unchanged independent + * of the actual mask value (weight equals 1). For data tpye #CV_32F, the mask values are + * used as weights. The exact formulas are documented in #TemplateMatchModes. */ public static void matchTemplate(Mat image, Mat templ, Mat result, int method, Mat mask) { matchTemplate_0(image.nativeObj, templ.nativeObj, result.nativeObj, method, mask.nativeObj); } - - // - // C++: void cv::HuMoments(Moments m, Mat& hu) - // - /** * Compares a template against overlapped image regions. - *

    + * * The function slides through image , compares the overlapped patches of size \(w \times h\) against * templ using the specified method and stores the comparison results in result . #TemplateMatchModes * describes the formulae for the available comparison methods ( \(I\) denotes image, \(T\) * template, \(R\) result, \(M\) the optional mask ). The summation is done over template and/or * the image patch: \(x' = 0...w-1, y' = 0...h-1\) - *

    + * * After the function finishes the comparison, the best matches can be found as global minimums (when * #TM_SQDIFF was used) or maximums (when #TM_CCORR or #TM_CCOEFF was used) using the * #minMaxLoc function. In case of a color image, template summation in the numerator and each sum in @@ -7321,17 +7399,17 @@ public static void matchTemplate(Mat image, Mat templ, Mat result, int method, M * That is, the function can take a color template and a color image. The result will still be a * single-channel image, which is easier to analyze. * - * @param image Image where the search is running. It must be 8-bit or 32-bit floating-point. - * @param templ Searched template. It must be not greater than the source image and have the same - * data type. + * @param image Image where the search is running. It must be 8-bit or 32-bit floating-point. + * @param templ Searched template. It must be not greater than the source image and have the same + * data type. * @param result Map of comparison results. It must be single-channel 32-bit floating-point. If image - * is \(W \times H\) and templ is \(w \times h\) , then result is \((W-w+1) \times (H-h+1)\) . + * is \(W \times H\) and templ is \(w \times h\) , then result is \((W-w+1) \times (H-h+1)\) . * @param method Parameter specifying the comparison method, see #TemplateMatchModes - * of channels as template or only one channel, which is then used for all template and - * image channels. If the data type is #CV_8U, the mask is interpreted as a binary mask, - * meaning only elements where mask is nonzero are used and are kept unchanged independent - * of the actual mask value (weight equals 1). For data tpye #CV_32F, the mask values are - * used as weights. The exact formulas are documented in #TemplateMatchModes. + * of channels as template or only one channel, which is then used for all template and + * image channels. If the data type is #CV_8U, the mask is interpreted as a binary mask, + * meaning only elements where mask is nonzero are used and are kept unchanged independent + * of the actual mask value (weight equals 1). For data tpye #CV_32F, the mask values are + * used as weights. The exact formulas are documented in #TemplateMatchModes. */ public static void matchTemplate(Mat image, Mat templ, Mat result, int method) { matchTemplate_1(image.nativeObj, templ.nativeObj, result.nativeObj, method); @@ -7339,12 +7417,12 @@ public static void matchTemplate(Mat image, Mat templ, Mat result, int method) { // - // C++: void cv::matchTemplate(Mat image, Mat templ, Mat& result, int method, Mat mask = Mat()) + // C++: int cv::connectedComponents(Mat image, Mat& labels, int connectivity, int ltype, int ccltype) // /** * computes the connected components labeled image of boolean image - *

    + * * image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 * represents the background label. ltype specifies the output label image type, an important * consideration based on the total number of labels or alternatively the total number of pixels in @@ -7355,36 +7433,40 @@ public static void matchTemplate(Mat image, Mat templ, Mat result, int method) { * This function uses parallel version of the algorithms if at least one allowed * parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. * - * @param image the 8-bit single-channel image to be labeled - * @param labels destination labeled image + * @param image the 8-bit single-channel image to be labeled + * @param labels destination labeled image * @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively - * @param ltype output image label type. Currently CV_32S and CV_16U are supported. - * @param ccltype connected components algorithm type (see the #ConnectedComponentsAlgorithmsTypes). + * @param ltype output image label type. Currently CV_32S and CV_16U are supported. + * @param ccltype connected components algorithm type (see the #ConnectedComponentsAlgorithmsTypes). * @return automatically generated */ public static int connectedComponentsWithAlgorithm(Mat image, Mat labels, int connectivity, int ltype, int ccltype) { return connectedComponentsWithAlgorithm_0(image.nativeObj, labels.nativeObj, connectivity, ltype, ccltype); } + + // + // C++: int cv::connectedComponents(Mat image, Mat& labels, int connectivity = 8, int ltype = CV_32S) + // + /** - * @param image the 8-bit single-channel image to be labeled - * @param labels destination labeled image + * + * + * @param image the 8-bit single-channel image to be labeled + * @param labels destination labeled image * @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively - * @param ltype output image label type. Currently CV_32S and CV_16U are supported. + * @param ltype output image label type. Currently CV_32S and CV_16U are supported. * @return automatically generated */ public static int connectedComponents(Mat image, Mat labels, int connectivity, int ltype) { return connectedComponents_0(image.nativeObj, labels.nativeObj, connectivity, ltype); } - - // - // C++: int cv::connectedComponents(Mat image, Mat& labels, int connectivity, int ltype, int ccltype) - // - /** - * @param image the 8-bit single-channel image to be labeled - * @param labels destination labeled image + * + * + * @param image the 8-bit single-channel image to be labeled + * @param labels destination labeled image * @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively * @return automatically generated */ @@ -7392,13 +7474,10 @@ public static int connectedComponents(Mat image, Mat labels, int connectivity) { return connectedComponents_1(image.nativeObj, labels.nativeObj, connectivity); } - - // - // C++: int cv::connectedComponents(Mat image, Mat& labels, int connectivity = 8, int ltype = CV_32S) - // - /** - * @param image the 8-bit single-channel image to be labeled + * + * + * @param image the 8-bit single-channel image to be labeled * @param labels destination labeled image * @return automatically generated */ @@ -7406,9 +7485,14 @@ public static int connectedComponents(Mat image, Mat labels) { return connectedComponents_2(image.nativeObj, labels.nativeObj); } + + // + // C++: int cv::connectedComponentsWithStats(Mat image, Mat& labels, Mat& stats, Mat& centroids, int connectivity, int ltype, int ccltype) + // + /** * computes the connected components labeled image of boolean image and also produces a statistics output for each label - *

    + * * image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 * represents the background label. ltype specifies the output label image type, an important * consideration based on the total number of labels or alternatively the total number of pixels in @@ -7419,51 +7503,53 @@ public static int connectedComponents(Mat image, Mat labels) { * This function uses parallel version of the algorithms (statistics included) if at least one allowed * parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. * - * @param image the 8-bit single-channel image to be labeled - * @param labels destination labeled image - * @param stats statistics output for each label, including the background label. - * Statistics are accessed via stats(label, COLUMN) where COLUMN is one of - * #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. - * @param centroids centroid output for each label, including the background label. Centroids are - * accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. + * @param image the 8-bit single-channel image to be labeled + * @param labels destination labeled image + * @param stats statistics output for each label, including the background label. + * Statistics are accessed via stats(label, COLUMN) where COLUMN is one of + * #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. + * @param centroids centroid output for each label, including the background label. Centroids are + * accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. * @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively - * @param ltype output image label type. Currently CV_32S and CV_16U are supported. - * @param ccltype connected components algorithm type (see #ConnectedComponentsAlgorithmsTypes). + * @param ltype output image label type. Currently CV_32S and CV_16U are supported. + * @param ccltype connected components algorithm type (see #ConnectedComponentsAlgorithmsTypes). * @return automatically generated */ public static int connectedComponentsWithStatsWithAlgorithm(Mat image, Mat labels, Mat stats, Mat centroids, int connectivity, int ltype, int ccltype) { return connectedComponentsWithStatsWithAlgorithm_0(image.nativeObj, labels.nativeObj, stats.nativeObj, centroids.nativeObj, connectivity, ltype, ccltype); } + + // + // C++: int cv::connectedComponentsWithStats(Mat image, Mat& labels, Mat& stats, Mat& centroids, int connectivity = 8, int ltype = CV_32S) + // + /** - * @param image the 8-bit single-channel image to be labeled - * @param labels destination labeled image - * @param stats statistics output for each label, including the background label. - * Statistics are accessed via stats(label, COLUMN) where COLUMN is one of - * #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. - * @param centroids centroid output for each label, including the background label. Centroids are - * accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. + * + * @param image the 8-bit single-channel image to be labeled + * @param labels destination labeled image + * @param stats statistics output for each label, including the background label. + * Statistics are accessed via stats(label, COLUMN) where COLUMN is one of + * #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. + * @param centroids centroid output for each label, including the background label. Centroids are + * accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. * @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively - * @param ltype output image label type. Currently CV_32S and CV_16U are supported. + * @param ltype output image label type. Currently CV_32S and CV_16U are supported. * @return automatically generated */ public static int connectedComponentsWithStats(Mat image, Mat labels, Mat stats, Mat centroids, int connectivity, int ltype) { return connectedComponentsWithStats_0(image.nativeObj, labels.nativeObj, stats.nativeObj, centroids.nativeObj, connectivity, ltype); } - - // - // C++: int cv::connectedComponentsWithStats(Mat image, Mat& labels, Mat& stats, Mat& centroids, int connectivity, int ltype, int ccltype) - // - /** - * @param image the 8-bit single-channel image to be labeled - * @param labels destination labeled image - * @param stats statistics output for each label, including the background label. - * Statistics are accessed via stats(label, COLUMN) where COLUMN is one of - * #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. - * @param centroids centroid output for each label, including the background label. Centroids are - * accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. + * + * @param image the 8-bit single-channel image to be labeled + * @param labels destination labeled image + * @param stats statistics output for each label, including the background label. + * Statistics are accessed via stats(label, COLUMN) where COLUMN is one of + * #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. + * @param centroids centroid output for each label, including the background label. Centroids are + * accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. * @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively * @return automatically generated */ @@ -7471,51 +7557,52 @@ public static int connectedComponentsWithStats(Mat image, Mat labels, Mat stats, return connectedComponentsWithStats_1(image.nativeObj, labels.nativeObj, stats.nativeObj, centroids.nativeObj, connectivity); } - - // - // C++: int cv::connectedComponentsWithStats(Mat image, Mat& labels, Mat& stats, Mat& centroids, int connectivity = 8, int ltype = CV_32S) - // - /** - * @param image the 8-bit single-channel image to be labeled - * @param labels destination labeled image - * @param stats statistics output for each label, including the background label. - * Statistics are accessed via stats(label, COLUMN) where COLUMN is one of - * #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. + * + * @param image the 8-bit single-channel image to be labeled + * @param labels destination labeled image + * @param stats statistics output for each label, including the background label. + * Statistics are accessed via stats(label, COLUMN) where COLUMN is one of + * #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. * @param centroids centroid output for each label, including the background label. Centroids are - * accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. + * accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. * @return automatically generated */ public static int connectedComponentsWithStats(Mat image, Mat labels, Mat stats, Mat centroids) { return connectedComponentsWithStats_2(image.nativeObj, labels.nativeObj, stats.nativeObj, centroids.nativeObj); } + + // + // C++: void cv::findContours(Mat image, vector_vector_Point& contours, Mat& hierarchy, int mode, int method, Point offset = Point()) + // + /** * Finds contours in a binary image. - *

    + * * The function retrieves contours from the binary image using the algorithm CITE: Suzuki85 . The contours * are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the * OpenCV sample directory. * Note: Since opencv 3.2 source image is not modified by this function. * - * @param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero - * pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , - * #adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. - * If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). - * @param contours Detected contours. Each contour is stored as a vector of points (e.g. - * std::vector<std::vector<cv::Point> >). + * @param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero + * pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , + * #adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. + * If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). + * @param contours Detected contours. Each contour is stored as a vector of points (e.g. + * std::vector<std::vector<cv::Point> >). * @param hierarchy Optional output vector (e.g. std::vector<cv::Vec4i>), containing information about the image topology. It has - * as many elements as the number of contours. For each i-th contour contours[i], the elements - * hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices - * in contours of the next and previous contours at the same hierarchical level, the first child - * contour and the parent contour, respectively. If for the contour i there are no next, previous, - * parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. - * Note: In Python, hierarchy is nested inside a top level array. Use hierarchy[0][i] to access hierarchical elements of i-th contour. - * @param mode Contour retrieval mode, see #RetrievalModes - * @param method Contour approximation method, see #ContourApproximationModes - * @param offset Optional offset by which every contour point is shifted. This is useful if the - * contours are extracted from the image ROI and then they should be analyzed in the whole image - * context. + * as many elements as the number of contours. For each i-th contour contours[i], the elements + * hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices + * in contours of the next and previous contours at the same hierarchical level, the first child + * contour and the parent contour, respectively. If for the contour i there are no next, previous, + * parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. + * Note: In Python, hierarchy is nested inside a top level array. Use hierarchy[0][i] to access hierarchical elements of i-th contour. + * @param mode Contour retrieval mode, see #RetrievalModes + * @param method Contour approximation method, see #ContourApproximationModes + * @param offset Optional offset by which every contour point is shifted. This is useful if the + * contours are extracted from the image ROI and then they should be analyzed in the whole image + * context. */ public static void findContours(Mat image, List contours, Mat hierarchy, int mode, int method, Point offset) { Mat contours_mat = new Mat(); @@ -7526,29 +7613,29 @@ public static void findContours(Mat image, List contours, Mat hierar /** * Finds contours in a binary image. - *

    + * * The function retrieves contours from the binary image using the algorithm CITE: Suzuki85 . The contours * are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the * OpenCV sample directory. * Note: Since opencv 3.2 source image is not modified by this function. * - * @param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero - * pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , - * #adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. - * If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). - * @param contours Detected contours. Each contour is stored as a vector of points (e.g. - * std::vector<std::vector<cv::Point> >). + * @param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero + * pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , + * #adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. + * If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). + * @param contours Detected contours. Each contour is stored as a vector of points (e.g. + * std::vector<std::vector<cv::Point> >). * @param hierarchy Optional output vector (e.g. std::vector<cv::Vec4i>), containing information about the image topology. It has - * as many elements as the number of contours. For each i-th contour contours[i], the elements - * hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices - * in contours of the next and previous contours at the same hierarchical level, the first child - * contour and the parent contour, respectively. If for the contour i there are no next, previous, - * parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. - * Note: In Python, hierarchy is nested inside a top level array. Use hierarchy[0][i] to access hierarchical elements of i-th contour. - * @param mode Contour retrieval mode, see #RetrievalModes - * @param method Contour approximation method, see #ContourApproximationModes - * contours are extracted from the image ROI and then they should be analyzed in the whole image - * context. + * as many elements as the number of contours. For each i-th contour contours[i], the elements + * hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices + * in contours of the next and previous contours at the same hierarchical level, the first child + * contour and the parent contour, respectively. If for the contour i there are no next, previous, + * parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. + * Note: In Python, hierarchy is nested inside a top level array. Use hierarchy[0][i] to access hierarchical elements of i-th contour. + * @param mode Contour retrieval mode, see #RetrievalModes + * @param method Contour approximation method, see #ContourApproximationModes + * contours are extracted from the image ROI and then they should be analyzed in the whole image + * context. */ public static void findContours(Mat image, List contours, Mat hierarchy, int mode, int method) { Mat contours_mat = new Mat(); @@ -7559,22 +7646,22 @@ public static void findContours(Mat image, List contours, Mat hierar // - // C++: void cv::findContours(Mat image, vector_vector_Point& contours, Mat& hierarchy, int mode, int method, Point offset = Point()) + // C++: void cv::approxPolyDP(vector_Point2f curve, vector_Point2f& approxCurve, double epsilon, bool closed) // /** * Approximates a polygonal curve(s) with the specified precision. - *

    + * * The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less * vertices so that the distance between them is less or equal to the specified precision. It uses the * Douglas-Peucker algorithm <http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm> * - * @param curve Input vector of a 2D point stored in std::vector or Mat + * @param curve Input vector of a 2D point stored in std::vector or Mat * @param approxCurve Result of the approximation. The type should match the type of the input curve. - * @param epsilon Parameter specifying the approximation accuracy. This is the maximum distance - * between the original curve and its approximation. - * @param closed If true, the approximated curve is closed (its first and last vertices are - * connected). Otherwise, it is not closed. + * @param epsilon Parameter specifying the approximation accuracy. This is the maximum distance + * between the original curve and its approximation. + * @param closed If true, the approximated curve is closed (its first and last vertices are + * connected). Otherwise, it is not closed. */ public static void approxPolyDP(MatOfPoint2f curve, MatOfPoint2f approxCurve, double epsilon, boolean closed) { Mat curve_mat = curve; @@ -7582,12 +7669,17 @@ public static void approxPolyDP(MatOfPoint2f curve, MatOfPoint2f approxCurve, do approxPolyDP_0(curve_mat.nativeObj, approxCurve_mat.nativeObj, epsilon, closed); } + + // + // C++: double cv::arcLength(vector_Point2f curve, bool closed) + // + /** * Calculates a contour perimeter or a curve length. - *

    + * * The function computes a curve length or a closed contour perimeter. * - * @param curve Input vector of 2D points, stored in std::vector or Mat. + * @param curve Input vector of 2D points, stored in std::vector or Mat. * @param closed Flag indicating whether the curve is closed or not. * @return automatically generated */ @@ -7598,12 +7690,12 @@ public static double arcLength(MatOfPoint2f curve, boolean closed) { // - // C++: void cv::approxPolyDP(vector_Point2f curve, vector_Point2f& approxCurve, double epsilon, bool closed) + // C++: Rect cv::boundingRect(Mat array) // /** * Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image. - *

    + * * The function calculates and returns the minimal up-right bounding rectangle for the specified point set or * non-zero pixels of gray-scale image. * @@ -7616,81 +7708,74 @@ public static Rect boundingRect(Mat array) { // - // C++: double cv::arcLength(vector_Point2f curve, bool closed) + // C++: double cv::contourArea(Mat contour, bool oriented = false) // /** * Calculates a contour area. - *

    + * * The function computes a contour area. Similarly to moments , the area is computed using the Green * formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using * #drawContours or #fillPoly , can be different. Also, the function will most certainly give a wrong * results for contours with self-intersections. - *

    + * * Example: * - * vector<Point> contour; - * contour.push_back(Point2f(0, 0)); - * contour.push_back(Point2f(10, 0)); - * contour.push_back(Point2f(10, 10)); - * contour.push_back(Point2f(5, 4)); - *

    - * double area0 = contourArea(contour); - * vector<Point> approx; - * approxPolyDP(contour, approx, 5, true); - * double area1 = contourArea(approx); - *

    - * cout << "area0 =" << area0 << endl << - * "area1 =" << area1 << endl << - * "approx poly vertices" << approx.size() << endl; + * vector<Point> contour; + * contour.push_back(Point2f(0, 0)); + * contour.push_back(Point2f(10, 0)); + * contour.push_back(Point2f(10, 10)); + * contour.push_back(Point2f(5, 4)); + * + * double area0 = contourArea(contour); + * vector<Point> approx; + * approxPolyDP(contour, approx, 5, true); + * double area1 = contourArea(approx); + * + * cout << "area0 =" << area0 << endl << + * "area1 =" << area1 << endl << + * "approx poly vertices" << approx.size() << endl; * - * - * @param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat. + * @param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat. * @param oriented Oriented area flag. If it is true, the function returns a signed area value, - * depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can - * determine orientation of a contour by taking the sign of an area. By default, the parameter is - * false, which means that the absolute value is returned. + * depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can + * determine orientation of a contour by taking the sign of an area. By default, the parameter is + * false, which means that the absolute value is returned. * @return automatically generated */ public static double contourArea(Mat contour, boolean oriented) { return contourArea_0(contour.nativeObj, oriented); } - - // - // C++: Rect cv::boundingRect(Mat array) - // - /** * Calculates a contour area. - *

    + * * The function computes a contour area. Similarly to moments , the area is computed using the Green * formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using * #drawContours or #fillPoly , can be different. Also, the function will most certainly give a wrong * results for contours with self-intersections. - *

    + * * Example: * - * vector<Point> contour; - * contour.push_back(Point2f(0, 0)); - * contour.push_back(Point2f(10, 0)); - * contour.push_back(Point2f(10, 10)); - * contour.push_back(Point2f(5, 4)); - *

    - * double area0 = contourArea(contour); - * vector<Point> approx; - * approxPolyDP(contour, approx, 5, true); - * double area1 = contourArea(approx); - *

    - * cout << "area0 =" << area0 << endl << - * "area1 =" << area1 << endl << - * "approx poly vertices" << approx.size() << endl; + * vector<Point> contour; + * contour.push_back(Point2f(0, 0)); + * contour.push_back(Point2f(10, 0)); + * contour.push_back(Point2f(10, 10)); + * contour.push_back(Point2f(5, 4)); + * + * double area0 = contourArea(contour); + * vector<Point> approx; + * approxPolyDP(contour, approx, 5, true); + * double area1 = contourArea(approx); + * + * cout << "area0 =" << area0 << endl << + * "area1 =" << area1 << endl << + * "approx poly vertices" << approx.size() << endl; * - * * @param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat. - * depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can - * determine orientation of a contour by taking the sign of an area. By default, the parameter is - * false, which means that the absolute value is returned. + * depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can + * determine orientation of a contour by taking the sign of an area. By default, the parameter is + * false, which means that the absolute value is returned. * @return automatically generated */ public static double contourArea(Mat contour) { @@ -7699,12 +7784,12 @@ public static double contourArea(Mat contour) { // - // C++: double cv::contourArea(Mat contour, bool oriented = false) + // C++: RotatedRect cv::minAreaRect(vector_Point2f points) // /** * Finds a rotated rectangle of the minimum area enclosing the input 2D point set. - *

    + * * The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a * specified point set. Developer should keep in mind that the returned RotatedRect can contain negative * indices when data is close to the containing Mat element boundary. @@ -7717,14 +7802,19 @@ public static RotatedRect minAreaRect(MatOfPoint2f points) { return new RotatedRect(minAreaRect_0(points_mat.nativeObj)); } + + // + // C++: void cv::boxPoints(RotatedRect box, Mat& points) + // + /** * Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle. - *

    + * * The function finds the four vertices of a rotated rectangle. This function is useful to draw the * rectangle. In C++, instead of using this function, you can directly use RotatedRect::points method. Please * visit the REF: tutorial_bounding_rotated_ellipses "tutorial on Creating Bounding rotated boxes and ellipses for contours" for more information. * - * @param box The input rotated rectangle. It may be the output of REF: minAreaRect. + * @param box The input rotated rectangle. It may be the output of REF: minAreaRect. * @param points The output array of four vertices of rectangles. */ public static void boxPoints(RotatedRect box, Mat points) { @@ -7733,12 +7823,12 @@ public static void boxPoints(RotatedRect box, Mat points) { // - // C++: RotatedRect cv::minAreaRect(vector_Point2f points) + // C++: void cv::minEnclosingCircle(vector_Point2f points, Point2f& center, float& radius) // /** * Finds a circle of the minimum area enclosing a 2D point set. - *

    + * * The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. * * @param points Input vector of 2D points, stored in std::vector<> or Mat @@ -7750,27 +7840,24 @@ public static void minEnclosingCircle(MatOfPoint2f points, Point center, float[] double[] center_out = new double[2]; double[] radius_out = new double[1]; minEnclosingCircle_0(points_mat.nativeObj, center_out, radius_out); - if (center != null) { - center.x = center_out[0]; - center.y = center_out[1]; - } - if (radius != null) radius[0] = (float) radius_out[0]; + if(center!=null){ center.x = center_out[0]; center.y = center_out[1]; } + if(radius!=null) radius[0] = (float)radius_out[0]; } // - // C++: void cv::boxPoints(RotatedRect box, Mat& points) + // C++: double cv::minEnclosingTriangle(Mat points, Mat& triangle) // /** * Finds a triangle of minimum area enclosing a 2D point set and returns its area. - *

    + * * The function finds a triangle of minimum area enclosing the given set of 2D points and returns its * area. The output for a given 2D point set is shown in the image below. 2D points are depicted in * red* and the enclosing triangle in *yellow*. - *

    + * * ![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png) - *

    + * * The implementation of the algorithm is based on O'Rourke's CITE: ORourke86 and Klee and Laskowski's * CITE: KleeLaskowski85 papers. O'Rourke provides a \(\theta(n)\) algorithm for finding the minimal * enclosing triangle of a 2D convex polygon with n vertices. Since the #minEnclosingTriangle function @@ -7778,9 +7865,9 @@ public static void minEnclosingCircle(MatOfPoint2f points, Point center, float[] * 2D point set is required. The complexity of the #convexHull function is \(O(n log(n))\) which is higher * than \(\theta(n)\). Thus the overall complexity of the function is \(O(n log(n))\). * - * @param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector<> or Mat + * @param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector<> or Mat * @param triangle Output vector of three 2D points defining the vertices of the triangle. The depth - * of the OutputArray must be CV_32F. + * of the OutputArray must be CV_32F. * @return automatically generated */ public static double minEnclosingTriangle(Mat points, Mat triangle) { @@ -7789,17 +7876,17 @@ public static double minEnclosingTriangle(Mat points, Mat triangle) { // - // C++: void cv::minEnclosingCircle(vector_Point2f points, Point2f& center, float& radius) + // C++: double cv::matchShapes(Mat contour1, Mat contour2, int method, double parameter) // /** * Compares two shapes. - *

    + * * The function compares two shapes. All three implemented methods use the Hu invariants (see #HuMoments) * - * @param contour1 First contour or grayscale image. - * @param contour2 Second contour or grayscale image. - * @param method Comparison method, see #ShapeMatchModes + * @param contour1 First contour or grayscale image. + * @param contour2 Second contour or grayscale image. + * @param method Comparison method, see #ShapeMatchModes * @param parameter Method-specific parameter (not supported now). * @return automatically generated */ @@ -7809,35 +7896,35 @@ public static double matchShapes(Mat contour1, Mat contour2, int method, double // - // C++: double cv::minEnclosingTriangle(Mat points, Mat& triangle) + // C++: void cv::convexHull(vector_Point points, vector_int& hull, bool clockwise = false, _hidden_ returnPoints = true) // /** * Finds the convex hull of a point set. - *

    + * * The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm CITE: Sklansky82 * that has *O(N logN)* complexity in the current implementation. * - * @param points Input 2D point set, stored in std::vector or Mat. - * @param hull Output convex hull. It is either an integer vector of indices or vector of points. In - * the first case, the hull elements are 0-based indices of the convex hull points in the original - * array (since the set of convex hull points is a subset of the original point set). In the second - * case, hull elements are the convex hull points themselves. + * @param points Input 2D point set, stored in std::vector or Mat. + * @param hull Output convex hull. It is either an integer vector of indices or vector of points. In + * the first case, the hull elements are 0-based indices of the convex hull points in the original + * array (since the set of convex hull points is a subset of the original point set). In the second + * case, hull elements are the convex hull points themselves. * @param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise. - * Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing - * to the right, and its Y axis pointing upwards. - * returns convex hull points. Otherwise, it returns indices of the convex hull points. When the - * output array is std::vector, the flag is ignored, and the output depends on the type of the - * vector: std::vector<int> implies returnPoints=false, std::vector<Point> implies - * returnPoints=true. - * - * Note: {@code points} and {@code hull} should be different arrays, inplace processing isn't supported. - *

    - * Check REF: tutorial_hull "the corresponding tutorial" for more details. - *

    - * useful links: - *

    - * https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/ + * Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing + * to the right, and its Y axis pointing upwards. + * returns convex hull points. Otherwise, it returns indices of the convex hull points. When the + * output array is std::vector, the flag is ignored, and the output depends on the type of the + * vector: std::vector<int> implies returnPoints=false, std::vector<Point> implies + * returnPoints=true. + * + * Note: {@code points} and {@code hull} should be different arrays, inplace processing isn't supported. + * + * Check REF: tutorial_hull "the corresponding tutorial" for more details. + * + * useful links: + * + * https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/ */ public static void convexHull(MatOfPoint points, MatOfInt hull, boolean clockwise) { Mat points_mat = points; @@ -7845,36 +7932,31 @@ public static void convexHull(MatOfPoint points, MatOfInt hull, boolean clockwis convexHull_0(points_mat.nativeObj, hull_mat.nativeObj, clockwise); } - - // - // C++: double cv::matchShapes(Mat contour1, Mat contour2, int method, double parameter) - // - /** * Finds the convex hull of a point set. - *

    + * * The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm CITE: Sklansky82 * that has *O(N logN)* complexity in the current implementation. * * @param points Input 2D point set, stored in std::vector or Mat. - * @param hull Output convex hull. It is either an integer vector of indices or vector of points. In - * the first case, the hull elements are 0-based indices of the convex hull points in the original - * array (since the set of convex hull points is a subset of the original point set). In the second - * case, hull elements are the convex hull points themselves. - * Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing - * to the right, and its Y axis pointing upwards. - * returns convex hull points. Otherwise, it returns indices of the convex hull points. When the - * output array is std::vector, the flag is ignored, and the output depends on the type of the - * vector: std::vector<int> implies returnPoints=false, std::vector<Point> implies - * returnPoints=true. - * - * Note: {@code points} and {@code hull} should be different arrays, inplace processing isn't supported. - *

    - * Check REF: tutorial_hull "the corresponding tutorial" for more details. - *

    - * useful links: - *

    - * https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/ + * @param hull Output convex hull. It is either an integer vector of indices or vector of points. In + * the first case, the hull elements are 0-based indices of the convex hull points in the original + * array (since the set of convex hull points is a subset of the original point set). In the second + * case, hull elements are the convex hull points themselves. + * Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing + * to the right, and its Y axis pointing upwards. + * returns convex hull points. Otherwise, it returns indices of the convex hull points. When the + * output array is std::vector, the flag is ignored, and the output depends on the type of the + * vector: std::vector<int> implies returnPoints=false, std::vector<Point> implies + * returnPoints=true. + * + * Note: {@code points} and {@code hull} should be different arrays, inplace processing isn't supported. + * + * Check REF: tutorial_hull "the corresponding tutorial" for more details. + * + * useful links: + * + * https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/ */ public static void convexHull(MatOfPoint points, MatOfInt hull) { Mat points_mat = points; @@ -7884,26 +7966,26 @@ public static void convexHull(MatOfPoint points, MatOfInt hull) { // - // C++: void cv::convexHull(vector_Point points, vector_int& hull, bool clockwise = false, _hidden_ returnPoints = true) + // C++: void cv::convexityDefects(vector_Point contour, vector_int convexhull, vector_Vec4i& convexityDefects) // /** * Finds the convexity defects of a contour. - *

    + * * The figure below displays convexity defects of a hand contour: - *

    + * * ![image](pics/defects.png) * - * @param contour Input contour. - * @param convexhull Convex hull obtained using convexHull that should contain indices of the contour - * points that make the hull. + * @param contour Input contour. + * @param convexhull Convex hull obtained using convexHull that should contain indices of the contour + * points that make the hull. * @param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java - * interface each convexity defect is represented as 4-element integer vector (a.k.a. #Vec4i): - * (start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices - * in the original contour of the convexity defect beginning, end and the farthest point, and - * fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the - * farthest contour point and the hull. That is, to get the floating-point value of the depth will be - * fixpt_depth/256.0. + * interface each convexity defect is represented as 4-element integer vector (a.k.a. #Vec4i): + * (start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices + * in the original contour of the convexity defect beginning, end and the farthest point, and + * fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the + * farthest contour point and the hull. That is, to get the floating-point value of the depth will be + * fixpt_depth/256.0. */ public static void convexityDefects(MatOfPoint contour, MatOfInt convexhull, MatOfInt4 convexityDefects) { Mat contour_mat = contour; @@ -7912,9 +7994,14 @@ public static void convexityDefects(MatOfPoint contour, MatOfInt convexhull, Mat convexityDefects_0(contour_mat.nativeObj, convexhull_mat.nativeObj, convexityDefects_mat.nativeObj); } + + // + // C++: bool cv::isContourConvex(vector_Point contour) + // + /** * Tests a contour convexity. - *

    + * * The function tests whether the input contour is convex or not. The contour must be simple, that is, * without self-intersections. Otherwise, the function output is undefined. * @@ -7928,18 +8015,19 @@ public static boolean isContourConvex(MatOfPoint contour) { // - // C++: void cv::convexityDefects(vector_Point contour, vector_int convexhull, vector_Vec4i& convexityDefects) + // C++: float cv::intersectConvexConvex(Mat p1, Mat p2, Mat& p12, bool handleNested = true) // /** * Finds intersection of two convex polygons * - * @param p1 First polygon - * @param p2 Second polygon - * @param p12 Output polygon describing the intersecting area + * @param p1 First polygon + * @param p2 Second polygon + * @param p12 Output polygon describing the intersecting area * @param handleNested When true, an intersection is found if one of the polygons is fully enclosed in the other. - * When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge - * of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested. + * When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge + * of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested. + * * @return Absolute value of area of intersecting polygon * * Note: intersectConvexConvex doesn't confirm that both polygons are convex and will return invalid results if they aren't. @@ -7948,19 +8036,15 @@ public static float intersectConvexConvex(Mat p1, Mat p2, Mat p12, boolean handl return intersectConvexConvex_0(p1.nativeObj, p2.nativeObj, p12.nativeObj, handleNested); } - - // - // C++: bool cv::isContourConvex(vector_Point contour) - // - /** * Finds intersection of two convex polygons * - * @param p1 First polygon - * @param p2 Second polygon + * @param p1 First polygon + * @param p2 Second polygon * @param p12 Output polygon describing the intersecting area - * When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge - * of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested. + * When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge + * of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested. + * * @return Absolute value of area of intersecting polygon * * Note: intersectConvexConvex doesn't confirm that both polygons are convex and will return invalid results if they aren't. @@ -7971,12 +8055,12 @@ public static float intersectConvexConvex(Mat p1, Mat p2, Mat p12) { // - // C++: float cv::intersectConvexConvex(Mat p1, Mat p2, Mat& p12, bool handleNested = true) + // C++: RotatedRect cv::fitEllipse(vector_Point2f points) // /** * Fits an ellipse around a set of 2D points. - *

    + * * The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of * all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by CITE: Fitzgibbon95 * is used. Developer should keep in mind that it is possible that the returned @@ -7991,41 +8075,46 @@ public static RotatedRect fitEllipse(MatOfPoint2f points) { return new RotatedRect(fitEllipse_0(points_mat.nativeObj)); } + + // + // C++: RotatedRect cv::fitEllipseAMS(Mat points) + // + /** * Fits an ellipse around a set of 2D points. - *

    - * The function calculates the ellipse that fits a set of 2D points. - * It returns the rotated rectangle in which the ellipse is inscribed. - * The Approximate Mean Square (AMS) proposed by CITE: Taubin1991 is used. - *

    - * For an ellipse, this basis set is \( \chi= \left(x^2, x y, y^2, x, y, 1\right) \), - * which is a set of six free coefficients \( A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \). - * However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \( (a,b) \), - * the position \( (x_0,y_0) \), and the orientation \( \theta \). This is because the basis set includes lines, - * quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. - * If the fit is found to be a parabolic or hyperbolic function then the standard #fitEllipse method is used. - * The AMS method restricts the fit to parabolic, hyperbolic and elliptical curves - * by imposing the condition that \( A^T ( D_x^T D_x + D_y^T D_y) A = 1 \) where - * the matrices \( Dx \) and \( Dy \) are the partial derivatives of the design matrix \( D \) with - * respect to x and y. The matrices are formed row by row applying the following to - * each of the points in the set: - * \(align*}{ - * D(i,:)&=\left\{x_i^2, x_i y_i, y_i^2, x_i, y_i, 1\right\} & - * D_x(i,:)&=\left\{2 x_i,y_i,0,1,0,0\right\} & - * D_y(i,:)&=\left\{0,x_i,2 y_i,0,1,0\right\} - * \) - * The AMS method minimizes the cost function - * \(equation*}{ - * \epsilon ^2=\frac{ A^T D^T D A }{ A^T (D_x^T D_x + D_y^T D_y) A^T } - * \) - *

    - * The minimum cost is found by solving the generalized eigenvalue problem. - *

    - * \(equation*}{ - * D^T D A = \lambda \left( D_x^T D_x + D_y^T D_y\right) A - * \) * - * @param points Input 2D point set, stored in std::vector<> or Mat + * The function calculates the ellipse that fits a set of 2D points. + * It returns the rotated rectangle in which the ellipse is inscribed. + * The Approximate Mean Square (AMS) proposed by CITE: Taubin1991 is used. + * + * For an ellipse, this basis set is \( \chi= \left(x^2, x y, y^2, x, y, 1\right) \), + * which is a set of six free coefficients \( A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \). + * However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \( (a,b) \), + * the position \( (x_0,y_0) \), and the orientation \( \theta \). This is because the basis set includes lines, + * quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. + * If the fit is found to be a parabolic or hyperbolic function then the standard #fitEllipse method is used. + * The AMS method restricts the fit to parabolic, hyperbolic and elliptical curves + * by imposing the condition that \( A^T ( D_x^T D_x + D_y^T D_y) A = 1 \) where + * the matrices \( Dx \) and \( Dy \) are the partial derivatives of the design matrix \( D \) with + * respect to x and y. The matrices are formed row by row applying the following to + * each of the points in the set: + * \(align*}{ + * D(i,:)&=\left\{x_i^2, x_i y_i, y_i^2, x_i, y_i, 1\right\} & + * D_x(i,:)&=\left\{2 x_i,y_i,0,1,0,0\right\} & + * D_y(i,:)&=\left\{0,x_i,2 y_i,0,1,0\right\} + * \) + * The AMS method minimizes the cost function + * \(equation*}{ + * \epsilon ^2=\frac{ A^T D^T D A }{ A^T (D_x^T D_x + D_y^T D_y) A^T } + * \) + * + * The minimum cost is found by solving the generalized eigenvalue problem. + * + * \(equation*}{ + * D^T D A = \lambda \left( D_x^T D_x + D_y^T D_y\right) A + * \) + * + * @param points Input 2D point set, stored in std::vector<> or Mat * @return automatically generated */ public static RotatedRect fitEllipseAMS(Mat points) { @@ -8034,51 +8123,51 @@ public static RotatedRect fitEllipseAMS(Mat points) { // - // C++: RotatedRect cv::fitEllipse(vector_Point2f points) + // C++: RotatedRect cv::fitEllipseDirect(Mat points) // /** * Fits an ellipse around a set of 2D points. - *

    - * The function calculates the ellipse that fits a set of 2D points. - * It returns the rotated rectangle in which the ellipse is inscribed. - * The Direct least square (Direct) method by CITE: Fitzgibbon1999 is used. - *

    - * For an ellipse, this basis set is \( \chi= \left(x^2, x y, y^2, x, y, 1\right) \), - * which is a set of six free coefficients \( A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \). - * However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \( (a,b) \), - * the position \( (x_0,y_0) \), and the orientation \( \theta \). This is because the basis set includes lines, - * quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. - * The Direct method confines the fit to ellipses by ensuring that \( 4 A_{xx} A_{yy}- A_{xy}^2 > 0 \). - * The condition imposed is that \( 4 A_{xx} A_{yy}- A_{xy}^2=1 \) which satisfies the inequality - * and as the coefficients can be arbitrarily scaled is not overly restrictive. - *

    - * \(equation*}{ - * \epsilon ^2= A^T D^T D A \quad \text{with} \quad A^T C A =1 \quad \text{and} \quad C=\left(\begin{matrix} - * 0 & 0 & 2 & 0 & 0 & 0 \\ - * 0 & -1 & 0 & 0 & 0 & 0 \\ - * 2 & 0 & 0 & 0 & 0 & 0 \\ - * 0 & 0 & 0 & 0 & 0 & 0 \\ - * 0 & 0 & 0 & 0 & 0 & 0 \\ - * 0 & 0 & 0 & 0 & 0 & 0 - * \end{matrix} \right) - * \) - *

    - * The minimum cost is found by solving the generalized eigenvalue problem. - *

    - * \(equation*}{ - * D^T D A = \lambda \left( C\right) A - * \) - *

    - * The system produces only one positive eigenvalue \( \lambda\) which is chosen as the solution - * with its eigenvector \(\mathbf{u}\). These are used to find the coefficients - *

    - * \(equation*}{ - * A = \sqrt{\frac{1}{\mathbf{u}^T C \mathbf{u}}} \mathbf{u} - * \) - * The scaling factor guarantees that \(A^T C A =1\). * - * @param points Input 2D point set, stored in std::vector<> or Mat + * The function calculates the ellipse that fits a set of 2D points. + * It returns the rotated rectangle in which the ellipse is inscribed. + * The Direct least square (Direct) method by CITE: Fitzgibbon1999 is used. + * + * For an ellipse, this basis set is \( \chi= \left(x^2, x y, y^2, x, y, 1\right) \), + * which is a set of six free coefficients \( A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \). + * However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \( (a,b) \), + * the position \( (x_0,y_0) \), and the orientation \( \theta \). This is because the basis set includes lines, + * quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. + * The Direct method confines the fit to ellipses by ensuring that \( 4 A_{xx} A_{yy}- A_{xy}^2 > 0 \). + * The condition imposed is that \( 4 A_{xx} A_{yy}- A_{xy}^2=1 \) which satisfies the inequality + * and as the coefficients can be arbitrarily scaled is not overly restrictive. + * + * \(equation*}{ + * \epsilon ^2= A^T D^T D A \quad \text{with} \quad A^T C A =1 \quad \text{and} \quad C=\left(\begin{matrix} + * 0 & 0 & 2 & 0 & 0 & 0 \\ + * 0 & -1 & 0 & 0 & 0 & 0 \\ + * 2 & 0 & 0 & 0 & 0 & 0 \\ + * 0 & 0 & 0 & 0 & 0 & 0 \\ + * 0 & 0 & 0 & 0 & 0 & 0 \\ + * 0 & 0 & 0 & 0 & 0 & 0 + * \end{matrix} \right) + * \) + * + * The minimum cost is found by solving the generalized eigenvalue problem. + * + * \(equation*}{ + * D^T D A = \lambda \left( C\right) A + * \) + * + * The system produces only one positive eigenvalue \( \lambda\) which is chosen as the solution + * with its eigenvector \(\mathbf{u}\). These are used to find the coefficients + * + * \(equation*}{ + * A = \sqrt{\frac{1}{\mathbf{u}^T C \mathbf{u}}} \mathbf{u} + * \) + * The scaling factor guarantees that \(A^T C A =1\). + * + * @param points Input 2D point set, stored in std::vector<> or Mat * @return automatically generated */ public static RotatedRect fitEllipseDirect(Mat points) { @@ -8087,12 +8176,12 @@ public static RotatedRect fitEllipseDirect(Mat points) { // - // C++: RotatedRect cv::fitEllipseAMS(Mat points) + // C++: void cv::fitLine(Mat points, Mat& line, int distType, double param, double reps, double aeps) // /** * Fits a line to a 2D or 3D point set. - *

    + * * The function fitLine fits a line to a 2D or 3D point set by minimizing \(\sum_i \rho(r_i)\) where * \(r_i\) is a distance between the \(i^{th}\) point, the line and \(\rho(r)\) is a distance function, one * of the following: @@ -8122,22 +8211,22 @@ public static RotatedRect fitEllipseDirect(Mat points) { * \(\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\) * * - *

    + * * The algorithm is based on the M-estimator ( <http://en.wikipedia.org/wiki/M-estimator> ) technique * that iteratively fits the line using the weighted least-squares algorithm. After each iteration the * weights \(w_i\) are adjusted to be inversely proportional to \(\rho(r_i)\) . * - * @param points Input vector of 2D or 3D points, stored in std::vector<> or Mat. - * @param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements - * (like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and - * (x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like - * Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line - * and (x0, y0, z0) is a point on the line. + * @param points Input vector of 2D or 3D points, stored in std::vector<> or Mat. + * @param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements + * (like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and + * (x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like + * Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line + * and (x0, y0, z0) is a point on the line. * @param distType Distance used by the M-estimator, see #DistanceTypes - * @param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value - * is chosen. - * @param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line). - * @param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps. + * @param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value + * is chosen. + * @param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line). + * @param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps. */ public static void fitLine(Mat points, Mat line, int distType, double param, double reps, double aeps) { fitLine_0(points.nativeObj, line.nativeObj, distType, param, reps, aeps); @@ -8145,25 +8234,25 @@ public static void fitLine(Mat points, Mat line, int distType, double param, dou // - // C++: RotatedRect cv::fitEllipseDirect(Mat points) + // C++: double cv::pointPolygonTest(vector_Point2f contour, Point2f pt, bool measureDist) // /** * Performs a point-in-contour test. - *

    + * * The function determines whether the point is inside a contour, outside, or lies on an edge (or * coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) * value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively. * Otherwise, the return value is a signed distance between the point and the nearest contour edge. - *

    + * * See below a sample output of the function where each image pixel is tested against the contour: - *

    + * * ![sample output](pics/pointpolygon.png) * - * @param contour Input contour. - * @param pt Point tested against the contour. + * @param contour Input contour. + * @param pt Point tested against the contour. * @param measureDist If true, the function estimates the signed distance from the point to the - * nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not. + * nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not. * @return automatically generated */ public static double pointPolygonTest(MatOfPoint2f contour, Point pt, boolean measureDist) { @@ -8173,23 +8262,23 @@ public static double pointPolygonTest(MatOfPoint2f contour, Point pt, boolean me // - // C++: void cv::fitLine(Mat points, Mat& line, int distType, double param, double reps, double aeps) + // C++: int cv::rotatedRectangleIntersection(RotatedRect rect1, RotatedRect rect2, Mat& intersectingRegion) // /** * Finds out if there is any intersection between two rotated rectangles. - *

    + * * If there is then the vertices of the intersecting region are returned as well. - *

    + * * Below are some examples of intersection configurations. The hatched pattern indicates the * intersecting region and the red vertices are returned by the function. - *

    + * * ![intersection examples](pics/intersection.png) * - * @param rect1 First rectangle - * @param rect2 Second rectangle + * @param rect1 First rectangle + * @param rect2 Second rectangle * @param intersectingRegion The output array of the vertices of the intersecting region. It returns - * at most 8 vertices. Stored as std::vector<cv::Point2f> or cv::Mat as Mx1 of type CV_32FC2. + * at most 8 vertices. Stored as std::vector<cv::Point2f> or cv::Mat as Mx1 of type CV_32FC2. * @return One of #RectanglesIntersectTypes */ public static int rotatedRectangleIntersection(RotatedRect rect1, RotatedRect rect2, Mat intersectingRegion) { @@ -8198,12 +8287,11 @@ public static int rotatedRectangleIntersection(RotatedRect rect1, RotatedRect re // - // C++: double cv::pointPolygonTest(vector_Point2f contour, Point2f pt, bool measureDist) + // C++: Ptr_GeneralizedHoughBallard cv::createGeneralizedHoughBallard() // /** * Creates a smart pointer to a cv::GeneralizedHoughBallard class and initializes it. - * * @return automatically generated */ public static GeneralizedHoughBallard createGeneralizedHoughBallard() { @@ -8212,12 +8300,11 @@ public static GeneralizedHoughBallard createGeneralizedHoughBallard() { // - // C++: int cv::rotatedRectangleIntersection(RotatedRect rect1, RotatedRect rect2, Mat& intersectingRegion) + // C++: Ptr_GeneralizedHoughGuil cv::createGeneralizedHoughGuil() // /** * Creates a smart pointer to a cv::GeneralizedHoughGuil class and initializes it. - * * @return automatically generated */ public static GeneralizedHoughGuil createGeneralizedHoughGuil() { @@ -8226,14 +8313,14 @@ public static GeneralizedHoughGuil createGeneralizedHoughGuil() { // - // C++: Ptr_GeneralizedHoughBallard cv::createGeneralizedHoughBallard() + // C++: void cv::applyColorMap(Mat src, Mat& dst, int colormap) // /** * Applies a GNU Octave/MATLAB equivalent colormap on a given image. * - * @param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. - * @param dst The result is the colormapped source image. Note: Mat::create is called on dst. + * @param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. + * @param dst The result is the colormapped source image. Note: Mat::create is called on dst. * @param colormap The colormap to apply, see #ColormapTypes */ public static void applyColorMap(Mat src, Mat dst, int colormap) { @@ -8242,14 +8329,14 @@ public static void applyColorMap(Mat src, Mat dst, int colormap) { // - // C++: Ptr_GeneralizedHoughGuil cv::createGeneralizedHoughGuil() + // C++: void cv::applyColorMap(Mat src, Mat& dst, Mat userColor) // /** * Applies a user colormap on a given image. * - * @param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. - * @param dst The result is the colormapped source image. Note: Mat::create is called on dst. + * @param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. + * @param dst The result is the colormapped source image. Note: Mat::create is called on dst. * @param userColor The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256 */ public static void applyColorMap(Mat src, Mat dst, Mat userColor) { @@ -8258,70 +8345,60 @@ public static void applyColorMap(Mat src, Mat dst, Mat userColor) { // - // C++: void cv::applyColorMap(Mat src, Mat& dst, int colormap) + // C++: void cv::line(Mat& img, Point pt1, Point pt2, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) // /** * Draws a line segment connecting two points. - *

    + * * The function line draws the line segment between pt1 and pt2 points in the image. The line is * clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected * or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased * lines are drawn using Gaussian filtering. * - * @param img Image. - * @param pt1 First point of the line segment. - * @param pt2 Second point of the line segment. - * @param color Line color. + * @param img Image. + * @param pt1 First point of the line segment. + * @param pt2 Second point of the line segment. + * @param color Line color. * @param thickness Line thickness. - * @param lineType Type of the line. See #LineTypes. - * @param shift Number of fractional bits in the point coordinates. + * @param lineType Type of the line. See #LineTypes. + * @param shift Number of fractional bits in the point coordinates. */ public static void line(Mat img, Point pt1, Point pt2, Scalar color, int thickness, int lineType, int shift) { line_0(img.nativeObj, pt1.x, pt1.y, pt2.x, pt2.y, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType, shift); } - - // - // C++: void cv::applyColorMap(Mat src, Mat& dst, Mat userColor) - // - /** * Draws a line segment connecting two points. - *

    + * * The function line draws the line segment between pt1 and pt2 points in the image. The line is * clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected * or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased * lines are drawn using Gaussian filtering. * - * @param img Image. - * @param pt1 First point of the line segment. - * @param pt2 Second point of the line segment. - * @param color Line color. + * @param img Image. + * @param pt1 First point of the line segment. + * @param pt2 Second point of the line segment. + * @param color Line color. * @param thickness Line thickness. - * @param lineType Type of the line. See #LineTypes. + * @param lineType Type of the line. See #LineTypes. */ public static void line(Mat img, Point pt1, Point pt2, Scalar color, int thickness, int lineType) { line_1(img.nativeObj, pt1.x, pt1.y, pt2.x, pt2.y, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType); } - - // - // C++: void cv::line(Mat& img, Point pt1, Point pt2, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) - // - /** * Draws a line segment connecting two points. - *

    + * * The function line draws the line segment between pt1 and pt2 points in the image. The line is * clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected * or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased * lines are drawn using Gaussian filtering. * - * @param img Image. - * @param pt1 First point of the line segment. - * @param pt2 Second point of the line segment. - * @param color Line color. + * @param img Image. + * @param pt1 First point of the line segment. + * @param pt2 Second point of the line segment. + * @param color Line color. * @param thickness Line thickness. */ public static void line(Mat img, Point pt1, Point pt2, Scalar color, int thickness) { @@ -8330,33 +8407,38 @@ public static void line(Mat img, Point pt1, Point pt2, Scalar color, int thickne /** * Draws a line segment connecting two points. - *

    + * * The function line draws the line segment between pt1 and pt2 points in the image. The line is * clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected * or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased * lines are drawn using Gaussian filtering. * - * @param img Image. - * @param pt1 First point of the line segment. - * @param pt2 Second point of the line segment. + * @param img Image. + * @param pt1 First point of the line segment. + * @param pt2 Second point of the line segment. * @param color Line color. */ public static void line(Mat img, Point pt1, Point pt2, Scalar color) { line_3(img.nativeObj, pt1.x, pt1.y, pt2.x, pt2.y, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::arrowedLine(Mat& img, Point pt1, Point pt2, Scalar color, int thickness = 1, int line_type = 8, int shift = 0, double tipLength = 0.1) + // + /** * Draws an arrow segment pointing from the first point to the second one. - *

    + * * The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line. * - * @param img Image. - * @param pt1 The point the arrow starts from. - * @param pt2 The point the arrow points to. - * @param color Line color. + * @param img Image. + * @param pt1 The point the arrow starts from. + * @param pt2 The point the arrow points to. + * @param color Line color. * @param thickness Line thickness. * @param line_type Type of the line. See #LineTypes - * @param shift Number of fractional bits in the point coordinates. + * @param shift Number of fractional bits in the point coordinates. * @param tipLength The length of the arrow tip in relation to the arrow length */ public static void arrowedLine(Mat img, Point pt1, Point pt2, Scalar color, int thickness, int line_type, int shift, double tipLength) { @@ -8365,35 +8447,30 @@ public static void arrowedLine(Mat img, Point pt1, Point pt2, Scalar color, int /** * Draws an arrow segment pointing from the first point to the second one. - *

    + * * The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line. * - * @param img Image. - * @param pt1 The point the arrow starts from. - * @param pt2 The point the arrow points to. - * @param color Line color. + * @param img Image. + * @param pt1 The point the arrow starts from. + * @param pt2 The point the arrow points to. + * @param color Line color. * @param thickness Line thickness. * @param line_type Type of the line. See #LineTypes - * @param shift Number of fractional bits in the point coordinates. + * @param shift Number of fractional bits in the point coordinates. */ public static void arrowedLine(Mat img, Point pt1, Point pt2, Scalar color, int thickness, int line_type, int shift) { arrowedLine_1(img.nativeObj, pt1.x, pt1.y, pt2.x, pt2.y, color.val[0], color.val[1], color.val[2], color.val[3], thickness, line_type, shift); } - - // - // C++: void cv::arrowedLine(Mat& img, Point pt1, Point pt2, Scalar color, int thickness = 1, int line_type = 8, int shift = 0, double tipLength = 0.1) - // - /** * Draws an arrow segment pointing from the first point to the second one. - *

    + * * The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line. * - * @param img Image. - * @param pt1 The point the arrow starts from. - * @param pt2 The point the arrow points to. - * @param color Line color. + * @param img Image. + * @param pt1 The point the arrow starts from. + * @param pt2 The point the arrow points to. + * @param color Line color. * @param thickness Line thickness. * @param line_type Type of the line. See #LineTypes */ @@ -8403,13 +8480,13 @@ public static void arrowedLine(Mat img, Point pt1, Point pt2, Scalar color, int /** * Draws an arrow segment pointing from the first point to the second one. - *

    + * * The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line. * - * @param img Image. - * @param pt1 The point the arrow starts from. - * @param pt2 The point the arrow points to. - * @param color Line color. + * @param img Image. + * @param pt1 The point the arrow starts from. + * @param pt2 The point the arrow points to. + * @param color Line color. * @param thickness Line thickness. */ public static void arrowedLine(Mat img, Point pt1, Point pt2, Scalar color, int thickness) { @@ -8418,32 +8495,37 @@ public static void arrowedLine(Mat img, Point pt1, Point pt2, Scalar color, int /** * Draws an arrow segment pointing from the first point to the second one. - *

    + * * The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line. * - * @param img Image. - * @param pt1 The point the arrow starts from. - * @param pt2 The point the arrow points to. + * @param img Image. + * @param pt1 The point the arrow starts from. + * @param pt2 The point the arrow points to. * @param color Line color. */ public static void arrowedLine(Mat img, Point pt1, Point pt2, Scalar color) { arrowedLine_4(img.nativeObj, pt1.x, pt1.y, pt2.x, pt2.y, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::rectangle(Mat& img, Point pt1, Point pt2, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) + // + /** * Draws a simple, thick, or filled up-right rectangle. - *

    + * * The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners * are pt1 and pt2. * - * @param img Image. - * @param pt1 Vertex of the rectangle. - * @param pt2 Vertex of the rectangle opposite to pt1 . - * @param color Rectangle color or brightness (grayscale image). + * @param img Image. + * @param pt1 Vertex of the rectangle. + * @param pt2 Vertex of the rectangle opposite to pt1 . + * @param color Rectangle color or brightness (grayscale image). * @param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED, - * mean that the function has to draw a filled rectangle. - * @param lineType Type of the line. See #LineTypes - * @param shift Number of fractional bits in the point coordinates. + * mean that the function has to draw a filled rectangle. + * @param lineType Type of the line. See #LineTypes + * @param shift Number of fractional bits in the point coordinates. */ public static void rectangle(Mat img, Point pt1, Point pt2, Scalar color, int thickness, int lineType, int shift) { rectangle_0(img.nativeObj, pt1.x, pt1.y, pt2.x, pt2.y, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType, shift); @@ -8451,39 +8533,34 @@ public static void rectangle(Mat img, Point pt1, Point pt2, Scalar color, int th /** * Draws a simple, thick, or filled up-right rectangle. - *

    + * * The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners * are pt1 and pt2. * - * @param img Image. - * @param pt1 Vertex of the rectangle. - * @param pt2 Vertex of the rectangle opposite to pt1 . - * @param color Rectangle color or brightness (grayscale image). + * @param img Image. + * @param pt1 Vertex of the rectangle. + * @param pt2 Vertex of the rectangle opposite to pt1 . + * @param color Rectangle color or brightness (grayscale image). * @param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED, - * mean that the function has to draw a filled rectangle. - * @param lineType Type of the line. See #LineTypes + * mean that the function has to draw a filled rectangle. + * @param lineType Type of the line. See #LineTypes */ public static void rectangle(Mat img, Point pt1, Point pt2, Scalar color, int thickness, int lineType) { rectangle_1(img.nativeObj, pt1.x, pt1.y, pt2.x, pt2.y, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType); } - - // - // C++: void cv::rectangle(Mat& img, Point pt1, Point pt2, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) - // - /** * Draws a simple, thick, or filled up-right rectangle. - *

    + * * The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners * are pt1 and pt2. * - * @param img Image. - * @param pt1 Vertex of the rectangle. - * @param pt2 Vertex of the rectangle opposite to pt1 . - * @param color Rectangle color or brightness (grayscale image). + * @param img Image. + * @param pt1 Vertex of the rectangle. + * @param pt2 Vertex of the rectangle opposite to pt1 . + * @param color Rectangle color or brightness (grayscale image). * @param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED, - * mean that the function has to draw a filled rectangle. + * mean that the function has to draw a filled rectangle. */ public static void rectangle(Mat img, Point pt1, Point pt2, Scalar color, int thickness) { rectangle_2(img.nativeObj, pt1.x, pt1.y, pt2.x, pt2.y, color.val[0], color.val[1], color.val[2], color.val[3], thickness); @@ -8491,61 +8568,64 @@ public static void rectangle(Mat img, Point pt1, Point pt2, Scalar color, int th /** * Draws a simple, thick, or filled up-right rectangle. - *

    + * * The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners * are pt1 and pt2. * - * @param img Image. - * @param pt1 Vertex of the rectangle. - * @param pt2 Vertex of the rectangle opposite to pt1 . + * @param img Image. + * @param pt1 Vertex of the rectangle. + * @param pt2 Vertex of the rectangle opposite to pt1 . * @param color Rectangle color or brightness (grayscale image). - * mean that the function has to draw a filled rectangle. + * mean that the function has to draw a filled rectangle. */ public static void rectangle(Mat img, Point pt1, Point pt2, Scalar color) { rectangle_3(img.nativeObj, pt1.x, pt1.y, pt2.x, pt2.y, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::rectangle(Mat& img, Rect rec, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) + // + /** + * + * * use {@code rec} parameter as alternative specification of the drawn rectangle: `r.tl() and * r.br()-Point(1,1)` are opposite corners - * - * @param img automatically generated - * @param rec automatically generated - * @param color automatically generated + * @param img automatically generated + * @param rec automatically generated + * @param color automatically generated * @param thickness automatically generated - * @param lineType automatically generated - * @param shift automatically generated + * @param lineType automatically generated + * @param shift automatically generated */ public static void rectangle(Mat img, Rect rec, Scalar color, int thickness, int lineType, int shift) { rectangle_4(img.nativeObj, rec.x, rec.y, rec.width, rec.height, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType, shift); } /** + * + * * use {@code rec} parameter as alternative specification of the drawn rectangle: `r.tl() and * r.br()-Point(1,1)` are opposite corners - * - * @param img automatically generated - * @param rec automatically generated - * @param color automatically generated + * @param img automatically generated + * @param rec automatically generated + * @param color automatically generated * @param thickness automatically generated - * @param lineType automatically generated + * @param lineType automatically generated */ public static void rectangle(Mat img, Rect rec, Scalar color, int thickness, int lineType) { rectangle_5(img.nativeObj, rec.x, rec.y, rec.width, rec.height, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType); } - - // - // C++: void cv::rectangle(Mat& img, Rect rec, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) - // - /** + * + * * use {@code rec} parameter as alternative specification of the drawn rectangle: `r.tl() and * r.br()-Point(1,1)` are opposite corners - * - * @param img automatically generated - * @param rec automatically generated - * @param color automatically generated + * @param img automatically generated + * @param rec automatically generated + * @param color automatically generated * @param thickness automatically generated */ public static void rectangle(Mat img, Rect rec, Scalar color, int thickness) { @@ -8553,30 +8633,35 @@ public static void rectangle(Mat img, Rect rec, Scalar color, int thickness) { } /** + * + * * use {@code rec} parameter as alternative specification of the drawn rectangle: `r.tl() and * r.br()-Point(1,1)` are opposite corners - * - * @param img automatically generated - * @param rec automatically generated + * @param img automatically generated + * @param rec automatically generated * @param color automatically generated */ public static void rectangle(Mat img, Rect rec, Scalar color) { rectangle_7(img.nativeObj, rec.x, rec.y, rec.width, rec.height, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::circle(Mat& img, Point center, int radius, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) + // + /** * Draws a circle. - *

    - * The function cv::circle draws a simple or filled circle with a given center and radius. * - * @param img Image where the circle is drawn. - * @param center Center of the circle. - * @param radius Radius of the circle. - * @param color Circle color. + * The function cv::circle draws a simple or filled circle with a given center and radius. + * @param img Image where the circle is drawn. + * @param center Center of the circle. + * @param radius Radius of the circle. + * @param color Circle color. * @param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED, - * mean that a filled circle is to be drawn. - * @param lineType Type of the circle boundary. See #LineTypes - * @param shift Number of fractional bits in the coordinates of the center and in the radius value. + * mean that a filled circle is to be drawn. + * @param lineType Type of the circle boundary. See #LineTypes + * @param shift Number of fractional bits in the coordinates of the center and in the radius value. */ public static void circle(Mat img, Point center, int radius, Scalar color, int thickness, int lineType, int shift) { circle_0(img.nativeObj, center.x, center.y, radius, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType, shift); @@ -8584,37 +8669,30 @@ public static void circle(Mat img, Point center, int radius, Scalar color, int t /** * Draws a circle. - *

    - * The function cv::circle draws a simple or filled circle with a given center and radius. * - * @param img Image where the circle is drawn. - * @param center Center of the circle. - * @param radius Radius of the circle. - * @param color Circle color. + * The function cv::circle draws a simple or filled circle with a given center and radius. + * @param img Image where the circle is drawn. + * @param center Center of the circle. + * @param radius Radius of the circle. + * @param color Circle color. * @param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED, - * mean that a filled circle is to be drawn. - * @param lineType Type of the circle boundary. See #LineTypes + * mean that a filled circle is to be drawn. + * @param lineType Type of the circle boundary. See #LineTypes */ public static void circle(Mat img, Point center, int radius, Scalar color, int thickness, int lineType) { circle_1(img.nativeObj, center.x, center.y, radius, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType); } - - // - // C++: void cv::circle(Mat& img, Point center, int radius, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) - // - /** * Draws a circle. - *

    - * The function cv::circle draws a simple or filled circle with a given center and radius. * - * @param img Image where the circle is drawn. - * @param center Center of the circle. - * @param radius Radius of the circle. - * @param color Circle color. + * The function cv::circle draws a simple or filled circle with a given center and radius. + * @param img Image where the circle is drawn. + * @param center Center of the circle. + * @param radius Radius of the circle. + * @param color Circle color. * @param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED, - * mean that a filled circle is to be drawn. + * mean that a filled circle is to be drawn. */ public static void circle(Mat img, Point center, int radius, Scalar color, int thickness) { circle_2(img.nativeObj, center.x, center.y, radius, color.val[0], color.val[1], color.val[2], color.val[3], thickness); @@ -8622,22 +8700,26 @@ public static void circle(Mat img, Point center, int radius, Scalar color, int t /** * Draws a circle. - *

    - * The function cv::circle draws a simple or filled circle with a given center and radius. * - * @param img Image where the circle is drawn. + * The function cv::circle draws a simple or filled circle with a given center and radius. + * @param img Image where the circle is drawn. * @param center Center of the circle. * @param radius Radius of the circle. - * @param color Circle color. - * mean that a filled circle is to be drawn. + * @param color Circle color. + * mean that a filled circle is to be drawn. */ public static void circle(Mat img, Point center, int radius, Scalar color) { circle_3(img.nativeObj, center.x, center.y, radius, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) + // + /** * Draws a simple or thick elliptic arc or fills an ellipse sector. - *

    + * * The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic * arc, or a filled ellipse sector. The drawing code uses general parametric form. * A piecewise-linear curve is used to approximate the elliptic arc @@ -8646,20 +8728,20 @@ public static void circle(Mat img, Point center, int radius, Scalar color) { * variant of the function and want to draw the whole ellipse, not an arc, pass {@code startAngle=0} and * {@code endAngle=360}. If {@code startAngle} is greater than {@code endAngle}, they are swapped. The figure below explains * the meaning of the parameters to draw the blue arc. - *

    + * * ![Parameters of Elliptic Arc](pics/ellipse.svg) * - * @param img Image. - * @param center Center of the ellipse. - * @param axes Half of the size of the ellipse main axes. - * @param angle Ellipse rotation angle in degrees. + * @param img Image. + * @param center Center of the ellipse. + * @param axes Half of the size of the ellipse main axes. + * @param angle Ellipse rotation angle in degrees. * @param startAngle Starting angle of the elliptic arc in degrees. - * @param endAngle Ending angle of the elliptic arc in degrees. - * @param color Ellipse color. - * @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that - * a filled ellipse sector is to be drawn. - * @param lineType Type of the ellipse boundary. See #LineTypes - * @param shift Number of fractional bits in the coordinates of the center and values of axes. + * @param endAngle Ending angle of the elliptic arc in degrees. + * @param color Ellipse color. + * @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that + * a filled ellipse sector is to be drawn. + * @param lineType Type of the ellipse boundary. See #LineTypes + * @param shift Number of fractional bits in the coordinates of the center and values of axes. */ public static void ellipse(Mat img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, int thickness, int lineType, int shift) { ellipse_0(img.nativeObj, center.x, center.y, axes.width, axes.height, angle, startAngle, endAngle, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType, shift); @@ -8667,7 +8749,7 @@ public static void ellipse(Mat img, Point center, Size axes, double angle, doubl /** * Draws a simple or thick elliptic arc or fills an ellipse sector. - *

    + * * The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic * arc, or a filled ellipse sector. The drawing code uses general parametric form. * A piecewise-linear curve is used to approximate the elliptic arc @@ -8676,32 +8758,27 @@ public static void ellipse(Mat img, Point center, Size axes, double angle, doubl * variant of the function and want to draw the whole ellipse, not an arc, pass {@code startAngle=0} and * {@code endAngle=360}. If {@code startAngle} is greater than {@code endAngle}, they are swapped. The figure below explains * the meaning of the parameters to draw the blue arc. - *

    + * * ![Parameters of Elliptic Arc](pics/ellipse.svg) * - * @param img Image. - * @param center Center of the ellipse. - * @param axes Half of the size of the ellipse main axes. - * @param angle Ellipse rotation angle in degrees. + * @param img Image. + * @param center Center of the ellipse. + * @param axes Half of the size of the ellipse main axes. + * @param angle Ellipse rotation angle in degrees. * @param startAngle Starting angle of the elliptic arc in degrees. - * @param endAngle Ending angle of the elliptic arc in degrees. - * @param color Ellipse color. - * @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that - * a filled ellipse sector is to be drawn. - * @param lineType Type of the ellipse boundary. See #LineTypes + * @param endAngle Ending angle of the elliptic arc in degrees. + * @param color Ellipse color. + * @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that + * a filled ellipse sector is to be drawn. + * @param lineType Type of the ellipse boundary. See #LineTypes */ public static void ellipse(Mat img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, int thickness, int lineType) { ellipse_1(img.nativeObj, center.x, center.y, axes.width, axes.height, angle, startAngle, endAngle, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType); } - - // - // C++: void cv::ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) - // - /** * Draws a simple or thick elliptic arc or fills an ellipse sector. - *

    + * * The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic * arc, or a filled ellipse sector. The drawing code uses general parametric form. * A piecewise-linear curve is used to approximate the elliptic arc @@ -8710,18 +8787,18 @@ public static void ellipse(Mat img, Point center, Size axes, double angle, doubl * variant of the function and want to draw the whole ellipse, not an arc, pass {@code startAngle=0} and * {@code endAngle=360}. If {@code startAngle} is greater than {@code endAngle}, they are swapped. The figure below explains * the meaning of the parameters to draw the blue arc. - *

    + * * ![Parameters of Elliptic Arc](pics/ellipse.svg) * - * @param img Image. - * @param center Center of the ellipse. - * @param axes Half of the size of the ellipse main axes. - * @param angle Ellipse rotation angle in degrees. + * @param img Image. + * @param center Center of the ellipse. + * @param axes Half of the size of the ellipse main axes. + * @param angle Ellipse rotation angle in degrees. * @param startAngle Starting angle of the elliptic arc in degrees. - * @param endAngle Ending angle of the elliptic arc in degrees. - * @param color Ellipse color. - * @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that - * a filled ellipse sector is to be drawn. + * @param endAngle Ending angle of the elliptic arc in degrees. + * @param color Ellipse color. + * @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that + * a filled ellipse sector is to be drawn. */ public static void ellipse(Mat img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, int thickness) { ellipse_2(img.nativeObj, center.x, center.y, axes.width, axes.height, angle, startAngle, endAngle, color.val[0], color.val[1], color.val[2], color.val[3], thickness); @@ -8729,7 +8806,7 @@ public static void ellipse(Mat img, Point center, Size axes, double angle, doubl /** * Draws a simple or thick elliptic arc or fills an ellipse sector. - *

    + * * The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic * arc, or a filled ellipse sector. The drawing code uses general parametric form. * A piecewise-linear curve is used to approximate the elliptic arc @@ -8738,75 +8815,83 @@ public static void ellipse(Mat img, Point center, Size axes, double angle, doubl * variant of the function and want to draw the whole ellipse, not an arc, pass {@code startAngle=0} and * {@code endAngle=360}. If {@code startAngle} is greater than {@code endAngle}, they are swapped. The figure below explains * the meaning of the parameters to draw the blue arc. - *

    + * * ![Parameters of Elliptic Arc](pics/ellipse.svg) * - * @param img Image. - * @param center Center of the ellipse. - * @param axes Half of the size of the ellipse main axes. - * @param angle Ellipse rotation angle in degrees. + * @param img Image. + * @param center Center of the ellipse. + * @param axes Half of the size of the ellipse main axes. + * @param angle Ellipse rotation angle in degrees. * @param startAngle Starting angle of the elliptic arc in degrees. - * @param endAngle Ending angle of the elliptic arc in degrees. - * @param color Ellipse color. - * a filled ellipse sector is to be drawn. + * @param endAngle Ending angle of the elliptic arc in degrees. + * @param color Ellipse color. + * a filled ellipse sector is to be drawn. */ public static void ellipse(Mat img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color) { ellipse_3(img.nativeObj, center.x, center.y, axes.width, axes.height, angle, startAngle, endAngle, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::ellipse(Mat& img, RotatedRect box, Scalar color, int thickness = 1, int lineType = LINE_8) + // + /** - * @param img Image. - * @param box Alternative ellipse representation via RotatedRect. This means that the function draws - * an ellipse inscribed in the rotated rectangle. - * @param color Ellipse color. + * + * @param img Image. + * @param box Alternative ellipse representation via RotatedRect. This means that the function draws + * an ellipse inscribed in the rotated rectangle. + * @param color Ellipse color. * @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that - * a filled ellipse sector is to be drawn. - * @param lineType Type of the ellipse boundary. See #LineTypes + * a filled ellipse sector is to be drawn. + * @param lineType Type of the ellipse boundary. See #LineTypes */ public static void ellipse(Mat img, RotatedRect box, Scalar color, int thickness, int lineType) { ellipse_4(img.nativeObj, box.center.x, box.center.y, box.size.width, box.size.height, box.angle, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType); } /** - * @param img Image. - * @param box Alternative ellipse representation via RotatedRect. This means that the function draws - * an ellipse inscribed in the rotated rectangle. - * @param color Ellipse color. + * + * @param img Image. + * @param box Alternative ellipse representation via RotatedRect. This means that the function draws + * an ellipse inscribed in the rotated rectangle. + * @param color Ellipse color. * @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that - * a filled ellipse sector is to be drawn. + * a filled ellipse sector is to be drawn. */ public static void ellipse(Mat img, RotatedRect box, Scalar color, int thickness) { ellipse_5(img.nativeObj, box.center.x, box.center.y, box.size.width, box.size.height, box.angle, color.val[0], color.val[1], color.val[2], color.val[3], thickness); } - - // - // C++: void cv::ellipse(Mat& img, RotatedRect box, Scalar color, int thickness = 1, int lineType = LINE_8) - // - /** - * @param img Image. - * @param box Alternative ellipse representation via RotatedRect. This means that the function draws - * an ellipse inscribed in the rotated rectangle. + * + * @param img Image. + * @param box Alternative ellipse representation via RotatedRect. This means that the function draws + * an ellipse inscribed in the rotated rectangle. * @param color Ellipse color. - * a filled ellipse sector is to be drawn. + * a filled ellipse sector is to be drawn. */ public static void ellipse(Mat img, RotatedRect box, Scalar color) { ellipse_6(img.nativeObj, box.center.x, box.center.y, box.size.width, box.size.height, box.angle, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::drawMarker(Mat& img, Point position, Scalar color, int markerType = MARKER_CROSS, int markerSize = 20, int thickness = 1, int line_type = 8) + // + /** * Draws a marker on a predefined position in an image. - *

    + * * The function cv::drawMarker draws a marker on a given position in the image. For the moment several * marker types are supported, see #MarkerTypes for more information. * - * @param img Image. - * @param position The point where the crosshair is positioned. - * @param color Line color. + * @param img Image. + * @param position The point where the crosshair is positioned. + * @param color Line color. * @param markerType The specific type of marker you want to use, see #MarkerTypes - * @param thickness Line thickness. - * @param line_type Type of the line, See #LineTypes + * @param thickness Line thickness. + * @param line_type Type of the line, See #LineTypes * @param markerSize The length of the marker axis [default = 20 pixels] */ public static void drawMarker(Mat img, Point position, Scalar color, int markerType, int markerSize, int thickness, int line_type) { @@ -8815,35 +8900,30 @@ public static void drawMarker(Mat img, Point position, Scalar color, int markerT /** * Draws a marker on a predefined position in an image. - *

    + * * The function cv::drawMarker draws a marker on a given position in the image. For the moment several * marker types are supported, see #MarkerTypes for more information. * - * @param img Image. - * @param position The point where the crosshair is positioned. - * @param color Line color. + * @param img Image. + * @param position The point where the crosshair is positioned. + * @param color Line color. * @param markerType The specific type of marker you want to use, see #MarkerTypes - * @param thickness Line thickness. + * @param thickness Line thickness. * @param markerSize The length of the marker axis [default = 20 pixels] */ public static void drawMarker(Mat img, Point position, Scalar color, int markerType, int markerSize, int thickness) { drawMarker_1(img.nativeObj, position.x, position.y, color.val[0], color.val[1], color.val[2], color.val[3], markerType, markerSize, thickness); } - - // - // C++: void cv::drawMarker(Mat& img, Point position, Scalar color, int markerType = MARKER_CROSS, int markerSize = 20, int thickness = 1, int line_type = 8) - // - /** * Draws a marker on a predefined position in an image. - *

    + * * The function cv::drawMarker draws a marker on a given position in the image. For the moment several * marker types are supported, see #MarkerTypes for more information. * - * @param img Image. - * @param position The point where the crosshair is positioned. - * @param color Line color. + * @param img Image. + * @param position The point where the crosshair is positioned. + * @param color Line color. * @param markerType The specific type of marker you want to use, see #MarkerTypes * @param markerSize The length of the marker axis [default = 20 pixels] */ @@ -8853,13 +8933,13 @@ public static void drawMarker(Mat img, Point position, Scalar color, int markerT /** * Draws a marker on a predefined position in an image. - *

    + * * The function cv::drawMarker draws a marker on a given position in the image. For the moment several * marker types are supported, see #MarkerTypes for more information. * - * @param img Image. - * @param position The point where the crosshair is positioned. - * @param color Line color. + * @param img Image. + * @param position The point where the crosshair is positioned. + * @param color Line color. * @param markerType The specific type of marker you want to use, see #MarkerTypes */ public static void drawMarker(Mat img, Point position, Scalar color, int markerType) { @@ -8868,31 +8948,36 @@ public static void drawMarker(Mat img, Point position, Scalar color, int markerT /** * Draws a marker on a predefined position in an image. - *

    + * * The function cv::drawMarker draws a marker on a given position in the image. For the moment several * marker types are supported, see #MarkerTypes for more information. * - * @param img Image. + * @param img Image. * @param position The point where the crosshair is positioned. - * @param color Line color. + * @param color Line color. */ public static void drawMarker(Mat img, Point position, Scalar color) { drawMarker_4(img.nativeObj, position.x, position.y, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::fillConvexPoly(Mat& img, vector_Point points, Scalar color, int lineType = LINE_8, int shift = 0) + // + /** * Fills a convex polygon. - *

    + * * The function cv::fillConvexPoly draws a filled convex polygon. This function is much faster than the * function #fillPoly . It can fill not only convex polygons but any monotonic polygon without * self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line) * twice at the most (though, its top-most and/or the bottom edge could be horizontal). * - * @param img Image. - * @param points Polygon vertices. - * @param color Polygon color. + * @param img Image. + * @param points Polygon vertices. + * @param color Polygon color. * @param lineType Type of the polygon boundaries. See #LineTypes - * @param shift Number of fractional bits in the vertex coordinates. + * @param shift Number of fractional bits in the vertex coordinates. */ public static void fillConvexPoly(Mat img, MatOfPoint points, Scalar color, int lineType, int shift) { Mat points_mat = points; @@ -8901,15 +8986,15 @@ public static void fillConvexPoly(Mat img, MatOfPoint points, Scalar color, int /** * Fills a convex polygon. - *

    + * * The function cv::fillConvexPoly draws a filled convex polygon. This function is much faster than the * function #fillPoly . It can fill not only convex polygons but any monotonic polygon without * self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line) * twice at the most (though, its top-most and/or the bottom edge could be horizontal). * - * @param img Image. - * @param points Polygon vertices. - * @param color Polygon color. + * @param img Image. + * @param points Polygon vertices. + * @param color Polygon color. * @param lineType Type of the polygon boundaries. See #LineTypes */ public static void fillConvexPoly(Mat img, MatOfPoint points, Scalar color, int lineType) { @@ -8917,41 +9002,41 @@ public static void fillConvexPoly(Mat img, MatOfPoint points, Scalar color, int fillConvexPoly_1(img.nativeObj, points_mat.nativeObj, color.val[0], color.val[1], color.val[2], color.val[3], lineType); } - - // - // C++: void cv::fillConvexPoly(Mat& img, vector_Point points, Scalar color, int lineType = LINE_8, int shift = 0) - // - /** * Fills a convex polygon. - *

    + * * The function cv::fillConvexPoly draws a filled convex polygon. This function is much faster than the * function #fillPoly . It can fill not only convex polygons but any monotonic polygon without * self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line) * twice at the most (though, its top-most and/or the bottom edge could be horizontal). * - * @param img Image. + * @param img Image. * @param points Polygon vertices. - * @param color Polygon color. + * @param color Polygon color. */ public static void fillConvexPoly(Mat img, MatOfPoint points, Scalar color) { Mat points_mat = points; fillConvexPoly_2(img.nativeObj, points_mat.nativeObj, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::fillPoly(Mat& img, vector_vector_Point pts, Scalar color, int lineType = LINE_8, int shift = 0, Point offset = Point()) + // + /** * Fills the area bounded by one or more polygons. - *

    + * * The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill * complex areas, for example, areas with holes, contours with self-intersections (some of their * parts), and so forth. * - * @param img Image. - * @param pts Array of polygons where each polygon is represented as an array of points. - * @param color Polygon color. + * @param img Image. + * @param pts Array of polygons where each polygon is represented as an array of points. + * @param color Polygon color. * @param lineType Type of the polygon boundaries. See #LineTypes - * @param shift Number of fractional bits in the vertex coordinates. - * @param offset Optional offset of all points of the contours. + * @param shift Number of fractional bits in the vertex coordinates. + * @param offset Optional offset of all points of the contours. */ public static void fillPoly(Mat img, List pts, Scalar color, int lineType, int shift, Point offset) { List pts_tmplm = new ArrayList((pts != null) ? pts.size() : 0); @@ -8961,16 +9046,16 @@ public static void fillPoly(Mat img, List pts, Scalar color, int lin /** * Fills the area bounded by one or more polygons. - *

    + * * The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill * complex areas, for example, areas with holes, contours with self-intersections (some of their * parts), and so forth. * - * @param img Image. - * @param pts Array of polygons where each polygon is represented as an array of points. - * @param color Polygon color. + * @param img Image. + * @param pts Array of polygons where each polygon is represented as an array of points. + * @param color Polygon color. * @param lineType Type of the polygon boundaries. See #LineTypes - * @param shift Number of fractional bits in the vertex coordinates. + * @param shift Number of fractional bits in the vertex coordinates. */ public static void fillPoly(Mat img, List pts, Scalar color, int lineType, int shift) { List pts_tmplm = new ArrayList((pts != null) ? pts.size() : 0); @@ -8978,21 +9063,16 @@ public static void fillPoly(Mat img, List pts, Scalar color, int lin fillPoly_1(img.nativeObj, pts_mat.nativeObj, color.val[0], color.val[1], color.val[2], color.val[3], lineType, shift); } - - // - // C++: void cv::fillPoly(Mat& img, vector_vector_Point pts, Scalar color, int lineType = LINE_8, int shift = 0, Point offset = Point()) - // - /** * Fills the area bounded by one or more polygons. - *

    + * * The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill * complex areas, for example, areas with holes, contours with self-intersections (some of their * parts), and so forth. * - * @param img Image. - * @param pts Array of polygons where each polygon is represented as an array of points. - * @param color Polygon color. + * @param img Image. + * @param pts Array of polygons where each polygon is represented as an array of points. + * @param color Polygon color. * @param lineType Type of the polygon boundaries. See #LineTypes */ public static void fillPoly(Mat img, List pts, Scalar color, int lineType) { @@ -9003,13 +9083,13 @@ public static void fillPoly(Mat img, List pts, Scalar color, int lin /** * Fills the area bounded by one or more polygons. - *

    + * * The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill * complex areas, for example, areas with holes, contours with self-intersections (some of their * parts), and so forth. * - * @param img Image. - * @param pts Array of polygons where each polygon is represented as an array of points. + * @param img Image. + * @param pts Array of polygons where each polygon is represented as an array of points. * @param color Polygon color. */ public static void fillPoly(Mat img, List pts, Scalar color) { @@ -9018,19 +9098,24 @@ public static void fillPoly(Mat img, List pts, Scalar color) { fillPoly_3(img.nativeObj, pts_mat.nativeObj, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::polylines(Mat& img, vector_vector_Point pts, bool isClosed, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) + // + /** * Draws several polygonal curves. * - * @param img Image. - * @param pts Array of polygonal curves. - * @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, - * the function draws a line from the last vertex of each curve to its first vertex. - * @param color Polyline color. + * @param img Image. + * @param pts Array of polygonal curves. + * @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, + * the function draws a line from the last vertex of each curve to its first vertex. + * @param color Polyline color. * @param thickness Thickness of the polyline edges. - * @param lineType Type of the line segments. See #LineTypes - * @param shift Number of fractional bits in the vertex coordinates. - *

    - * The function cv::polylines draws one or more polygonal curves. + * @param lineType Type of the line segments. See #LineTypes + * @param shift Number of fractional bits in the vertex coordinates. + * + * The function cv::polylines draws one or more polygonal curves. */ public static void polylines(Mat img, List pts, boolean isClosed, Scalar color, int thickness, int lineType, int shift) { List pts_tmplm = new ArrayList((pts != null) ? pts.size() : 0); @@ -9041,15 +9126,15 @@ public static void polylines(Mat img, List pts, boolean isClosed, Sc /** * Draws several polygonal curves. * - * @param img Image. - * @param pts Array of polygonal curves. - * @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, - * the function draws a line from the last vertex of each curve to its first vertex. - * @param color Polyline color. + * @param img Image. + * @param pts Array of polygonal curves. + * @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, + * the function draws a line from the last vertex of each curve to its first vertex. + * @param color Polyline color. * @param thickness Thickness of the polyline edges. - * @param lineType Type of the line segments. See #LineTypes - *

    - * The function cv::polylines draws one or more polygonal curves. + * @param lineType Type of the line segments. See #LineTypes + * + * The function cv::polylines draws one or more polygonal curves. */ public static void polylines(Mat img, List pts, boolean isClosed, Scalar color, int thickness, int lineType) { List pts_tmplm = new ArrayList((pts != null) ? pts.size() : 0); @@ -9057,22 +9142,17 @@ public static void polylines(Mat img, List pts, boolean isClosed, Sc polylines_1(img.nativeObj, pts_mat.nativeObj, isClosed, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType); } - - // - // C++: void cv::polylines(Mat& img, vector_vector_Point pts, bool isClosed, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) - // - /** * Draws several polygonal curves. * - * @param img Image. - * @param pts Array of polygonal curves. - * @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, - * the function draws a line from the last vertex of each curve to its first vertex. - * @param color Polyline color. + * @param img Image. + * @param pts Array of polygonal curves. + * @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, + * the function draws a line from the last vertex of each curve to its first vertex. + * @param color Polyline color. * @param thickness Thickness of the polyline edges. - *

    - * The function cv::polylines draws one or more polygonal curves. + * + * The function cv::polylines draws one or more polygonal curves. */ public static void polylines(Mat img, List pts, boolean isClosed, Scalar color, int thickness) { List pts_tmplm = new ArrayList((pts != null) ? pts.size() : 0); @@ -9083,13 +9163,13 @@ public static void polylines(Mat img, List pts, boolean isClosed, Sc /** * Draws several polygonal curves. * - * @param img Image. - * @param pts Array of polygonal curves. + * @param img Image. + * @param pts Array of polygonal curves. * @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, - * the function draws a line from the last vertex of each curve to its first vertex. - * @param color Polyline color. - *

    - * The function cv::polylines draws one or more polygonal curves. + * the function draws a line from the last vertex of each curve to its first vertex. + * @param color Polyline color. + * + * The function cv::polylines draws one or more polygonal curves. */ public static void polylines(Mat img, List pts, boolean isClosed, Scalar color) { List pts_tmplm = new ArrayList((pts != null) ? pts.size() : 0); @@ -9097,34 +9177,39 @@ public static void polylines(Mat img, List pts, boolean isClosed, Sc polylines_3(img.nativeObj, pts_mat.nativeObj, isClosed, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: void cv::drawContours(Mat& image, vector_vector_Point contours, int contourIdx, Scalar color, int thickness = 1, int lineType = LINE_8, Mat hierarchy = Mat(), int maxLevel = INT_MAX, Point offset = Point()) + // + /** * Draws contours outlines or filled contours. - *

    + * * The function draws contour outlines in the image if \(\texttt{thickness} \ge 0\) or fills the area * bounded by the contours if \(\texttt{thickness}<0\) . The example below shows how to retrieve * connected components from the binary image and label them: : * INCLUDE: snippets/imgproc_drawContours.cpp * - * @param image Destination image. - * @param contours All the input contours. Each contour is stored as a point vector. + * @param image Destination image. + * @param contours All the input contours. Each contour is stored as a point vector. * @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. - * @param color Color of the contours. - * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, - * thickness=#FILLED ), the contour interiors are drawn. - * @param lineType Line connectivity. See #LineTypes - * @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only - * some of the contours (see maxLevel ). - * @param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. - * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function - * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This - * parameter is only taken into account when there is hierarchy available. - * @param offset Optional contour shift parameter. Shift all the drawn contours by the specified - * \(\texttt{offset}=(dx,dy)\) . - * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly - * even when no hierarchy data is provided. This is done by analyzing all the outlines together - * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved - * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group - * of contours, or iterate over the collection using contourIdx parameter. + * @param color Color of the contours. + * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, + * thickness=#FILLED ), the contour interiors are drawn. + * @param lineType Line connectivity. See #LineTypes + * @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only + * some of the contours (see maxLevel ). + * @param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. + * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function + * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This + * parameter is only taken into account when there is hierarchy available. + * @param offset Optional contour shift parameter. Shift all the drawn contours by the specified + * \(\texttt{offset}=(dx,dy)\) . + * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly + * even when no hierarchy data is provided. This is done by analyzing all the outlines together + * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved + * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group + * of contours, or iterate over the collection using contourIdx parameter. */ public static void drawContours(Mat image, List contours, int contourIdx, Scalar color, int thickness, int lineType, Mat hierarchy, int maxLevel, Point offset) { List contours_tmplm = new ArrayList((contours != null) ? contours.size() : 0); @@ -9134,69 +9219,64 @@ public static void drawContours(Mat image, List contours, int contou /** * Draws contours outlines or filled contours. - *

    + * * The function draws contour outlines in the image if \(\texttt{thickness} \ge 0\) or fills the area * bounded by the contours if \(\texttt{thickness}<0\) . The example below shows how to retrieve * connected components from the binary image and label them: : * INCLUDE: snippets/imgproc_drawContours.cpp * - * @param image Destination image. - * @param contours All the input contours. Each contour is stored as a point vector. + * @param image Destination image. + * @param contours All the input contours. Each contour is stored as a point vector. * @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. - * @param color Color of the contours. - * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, - * thickness=#FILLED ), the contour interiors are drawn. - * @param lineType Line connectivity. See #LineTypes - * @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only - * some of the contours (see maxLevel ). - * @param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. - * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function - * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This - * parameter is only taken into account when there is hierarchy available. - * \(\texttt{offset}=(dx,dy)\) . - * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly - * even when no hierarchy data is provided. This is done by analyzing all the outlines together - * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved - * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group - * of contours, or iterate over the collection using contourIdx parameter. + * @param color Color of the contours. + * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, + * thickness=#FILLED ), the contour interiors are drawn. + * @param lineType Line connectivity. See #LineTypes + * @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only + * some of the contours (see maxLevel ). + * @param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. + * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function + * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This + * parameter is only taken into account when there is hierarchy available. + * \(\texttt{offset}=(dx,dy)\) . + * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly + * even when no hierarchy data is provided. This is done by analyzing all the outlines together + * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved + * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group + * of contours, or iterate over the collection using contourIdx parameter. */ public static void drawContours(Mat image, List contours, int contourIdx, Scalar color, int thickness, int lineType, Mat hierarchy, int maxLevel) { List contours_tmplm = new ArrayList((contours != null) ? contours.size() : 0); Mat contours_mat = Converters.vector_vector_Point_to_Mat(contours, contours_tmplm); - drawContours_1(image.nativeObj, contours_mat.nativeObj, contourIdx, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType, hierarchy.nativeObj, maxLevel); - } - - - // - // C++: void cv::drawContours(Mat& image, vector_vector_Point contours, int contourIdx, Scalar color, int thickness = 1, int lineType = LINE_8, Mat hierarchy = Mat(), int maxLevel = INT_MAX, Point offset = Point()) - // + drawContours_1(image.nativeObj, contours_mat.nativeObj, contourIdx, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType, hierarchy.nativeObj, maxLevel); + } /** * Draws contours outlines or filled contours. - *

    + * * The function draws contour outlines in the image if \(\texttt{thickness} \ge 0\) or fills the area * bounded by the contours if \(\texttt{thickness}<0\) . The example below shows how to retrieve * connected components from the binary image and label them: : * INCLUDE: snippets/imgproc_drawContours.cpp * - * @param image Destination image. - * @param contours All the input contours. Each contour is stored as a point vector. + * @param image Destination image. + * @param contours All the input contours. Each contour is stored as a point vector. * @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. - * @param color Color of the contours. - * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, - * thickness=#FILLED ), the contour interiors are drawn. - * @param lineType Line connectivity. See #LineTypes - * @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only - * some of the contours (see maxLevel ). - * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function - * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This - * parameter is only taken into account when there is hierarchy available. - * \(\texttt{offset}=(dx,dy)\) . - * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly - * even when no hierarchy data is provided. This is done by analyzing all the outlines together - * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved - * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group - * of contours, or iterate over the collection using contourIdx parameter. + * @param color Color of the contours. + * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, + * thickness=#FILLED ), the contour interiors are drawn. + * @param lineType Line connectivity. See #LineTypes + * @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only + * some of the contours (see maxLevel ). + * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function + * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This + * parameter is only taken into account when there is hierarchy available. + * \(\texttt{offset}=(dx,dy)\) . + * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly + * even when no hierarchy data is provided. This is done by analyzing all the outlines together + * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved + * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group + * of contours, or iterate over the collection using contourIdx parameter. */ public static void drawContours(Mat image, List contours, int contourIdx, Scalar color, int thickness, int lineType, Mat hierarchy) { List contours_tmplm = new ArrayList((contours != null) ? contours.size() : 0); @@ -9206,29 +9286,29 @@ public static void drawContours(Mat image, List contours, int contou /** * Draws contours outlines or filled contours. - *

    + * * The function draws contour outlines in the image if \(\texttt{thickness} \ge 0\) or fills the area * bounded by the contours if \(\texttt{thickness}<0\) . The example below shows how to retrieve * connected components from the binary image and label them: : * INCLUDE: snippets/imgproc_drawContours.cpp * - * @param image Destination image. - * @param contours All the input contours. Each contour is stored as a point vector. + * @param image Destination image. + * @param contours All the input contours. Each contour is stored as a point vector. * @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. - * @param color Color of the contours. - * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, - * thickness=#FILLED ), the contour interiors are drawn. - * @param lineType Line connectivity. See #LineTypes - * some of the contours (see maxLevel ). - * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function - * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This - * parameter is only taken into account when there is hierarchy available. - * \(\texttt{offset}=(dx,dy)\) . - * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly - * even when no hierarchy data is provided. This is done by analyzing all the outlines together - * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved - * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group - * of contours, or iterate over the collection using contourIdx parameter. + * @param color Color of the contours. + * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, + * thickness=#FILLED ), the contour interiors are drawn. + * @param lineType Line connectivity. See #LineTypes + * some of the contours (see maxLevel ). + * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function + * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This + * parameter is only taken into account when there is hierarchy available. + * \(\texttt{offset}=(dx,dy)\) . + * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly + * even when no hierarchy data is provided. This is done by analyzing all the outlines together + * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved + * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group + * of contours, or iterate over the collection using contourIdx parameter. */ public static void drawContours(Mat image, List contours, int contourIdx, Scalar color, int thickness, int lineType) { List contours_tmplm = new ArrayList((contours != null) ? contours.size() : 0); @@ -9238,28 +9318,28 @@ public static void drawContours(Mat image, List contours, int contou /** * Draws contours outlines or filled contours. - *

    + * * The function draws contour outlines in the image if \(\texttt{thickness} \ge 0\) or fills the area * bounded by the contours if \(\texttt{thickness}<0\) . The example below shows how to retrieve * connected components from the binary image and label them: : * INCLUDE: snippets/imgproc_drawContours.cpp * - * @param image Destination image. - * @param contours All the input contours. Each contour is stored as a point vector. + * @param image Destination image. + * @param contours All the input contours. Each contour is stored as a point vector. * @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. - * @param color Color of the contours. - * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, - * thickness=#FILLED ), the contour interiors are drawn. - * some of the contours (see maxLevel ). - * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function - * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This - * parameter is only taken into account when there is hierarchy available. - * \(\texttt{offset}=(dx,dy)\) . - * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly - * even when no hierarchy data is provided. This is done by analyzing all the outlines together - * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved - * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group - * of contours, or iterate over the collection using contourIdx parameter. + * @param color Color of the contours. + * @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, + * thickness=#FILLED ), the contour interiors are drawn. + * some of the contours (see maxLevel ). + * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function + * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This + * parameter is only taken into account when there is hierarchy available. + * \(\texttt{offset}=(dx,dy)\) . + * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly + * even when no hierarchy data is provided. This is done by analyzing all the outlines together + * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved + * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group + * of contours, or iterate over the collection using contourIdx parameter. */ public static void drawContours(Mat image, List contours, int contourIdx, Scalar color, int thickness) { List contours_tmplm = new ArrayList((contours != null) ? contours.size() : 0); @@ -9269,27 +9349,27 @@ public static void drawContours(Mat image, List contours, int contou /** * Draws contours outlines or filled contours. - *

    + * * The function draws contour outlines in the image if \(\texttt{thickness} \ge 0\) or fills the area * bounded by the contours if \(\texttt{thickness}<0\) . The example below shows how to retrieve * connected components from the binary image and label them: : * INCLUDE: snippets/imgproc_drawContours.cpp * - * @param image Destination image. - * @param contours All the input contours. Each contour is stored as a point vector. + * @param image Destination image. + * @param contours All the input contours. Each contour is stored as a point vector. * @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. - * @param color Color of the contours. - * thickness=#FILLED ), the contour interiors are drawn. - * some of the contours (see maxLevel ). - * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function - * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This - * parameter is only taken into account when there is hierarchy available. - * \(\texttt{offset}=(dx,dy)\) . - * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly - * even when no hierarchy data is provided. This is done by analyzing all the outlines together - * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved - * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group - * of contours, or iterate over the collection using contourIdx parameter. + * @param color Color of the contours. + * thickness=#FILLED ), the contour interiors are drawn. + * some of the contours (see maxLevel ). + * If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function + * draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This + * parameter is only taken into account when there is hierarchy available. + * \(\texttt{offset}=(dx,dy)\) . + * Note: When thickness=#FILLED, the function is designed to handle connected components with holes correctly + * even when no hierarchy data is provided. This is done by analyzing all the outlines together + * using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved + * contours. In order to solve this problem, you need to call #drawContours separately for each sub-group + * of contours, or iterate over the collection using contourIdx parameter. */ public static void drawContours(Mat image, List contours, int contourIdx, Scalar color) { List contours_tmplm = new ArrayList((contours != null) ? contours.size() : 0); @@ -9297,41 +9377,46 @@ public static void drawContours(Mat image, List contours, int contou drawContours_5(image.nativeObj, contours_mat.nativeObj, contourIdx, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: bool cv::clipLine(Rect imgRect, Point& pt1, Point& pt2) + // + /** + * * @param imgRect Image rectangle. - * @param pt1 First line point. - * @param pt2 Second line point. + * @param pt1 First line point. + * @param pt2 Second line point. * @return automatically generated */ public static boolean clipLine(Rect imgRect, Point pt1, Point pt2) { double[] pt1_out = new double[2]; double[] pt2_out = new double[2]; boolean retVal = clipLine_0(imgRect.x, imgRect.y, imgRect.width, imgRect.height, pt1.x, pt1.y, pt1_out, pt2.x, pt2.y, pt2_out); - if (pt1 != null) { - pt1.x = pt1_out[0]; - pt1.y = pt1_out[1]; - } - if (pt2 != null) { - pt2.x = pt2_out[0]; - pt2.y = pt2_out[1]; - } + if(pt1!=null){ pt1.x = pt1_out[0]; pt1.y = pt1_out[1]; } + if(pt2!=null){ pt2.x = pt2_out[0]; pt2.y = pt2_out[1]; } return retVal; } + + // + // C++: void cv::ellipse2Poly(Point center, Size axes, int angle, int arcStart, int arcEnd, int delta, vector_Point& pts) + // + /** * Approximates an elliptic arc with a polyline. - *

    + * * The function ellipse2Poly computes the vertices of a polyline that approximates the specified * elliptic arc. It is used by #ellipse. If {@code arcStart} is greater than {@code arcEnd}, they are swapped. * - * @param center Center of the arc. - * @param axes Half of the size of the ellipse main axes. See #ellipse for details. - * @param angle Rotation angle of the ellipse in degrees. See #ellipse for details. + * @param center Center of the arc. + * @param axes Half of the size of the ellipse main axes. See #ellipse for details. + * @param angle Rotation angle of the ellipse in degrees. See #ellipse for details. * @param arcStart Starting angle of the elliptic arc in degrees. - * @param arcEnd Ending angle of the elliptic arc in degrees. - * @param delta Angle between the subsequent polyline vertices. It defines the approximation - * accuracy. - * @param pts Output vector of polyline vertices. + * @param arcEnd Ending angle of the elliptic arc in degrees. + * @param delta Angle between the subsequent polyline vertices. It defines the approximation + * accuracy. + * @param pts Output vector of polyline vertices. */ public static void ellipse2Poly(Point center, Size axes, int angle, int arcStart, int arcEnd, int delta, MatOfPoint pts) { Mat pts_mat = pts; @@ -9340,77 +9425,67 @@ public static void ellipse2Poly(Point center, Size axes, int angle, int arcStart // - // C++: bool cv::clipLine(Rect imgRect, Point& pt1, Point& pt2) + // C++: void cv::putText(Mat& img, String text, Point org, int fontFace, double fontScale, Scalar color, int thickness = 1, int lineType = LINE_8, bool bottomLeftOrigin = false) // /** * Draws a text string. - *

    + * * The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered * using the specified font are replaced by question marks. See #getTextSize for a text rendering code * example. * - * @param img Image. - * @param text Text string to be drawn. - * @param org Bottom-left corner of the text string in the image. - * @param fontFace Font type, see #HersheyFonts. - * @param fontScale Font scale factor that is multiplied by the font-specific base size. - * @param color Text color. - * @param thickness Thickness of the lines used to draw a text. - * @param lineType Line type. See #LineTypes + * @param img Image. + * @param text Text string to be drawn. + * @param org Bottom-left corner of the text string in the image. + * @param fontFace Font type, see #HersheyFonts. + * @param fontScale Font scale factor that is multiplied by the font-specific base size. + * @param color Text color. + * @param thickness Thickness of the lines used to draw a text. + * @param lineType Line type. See #LineTypes * @param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, - * it is at the top-left corner. + * it is at the top-left corner. */ public static void putText(Mat img, String text, Point org, int fontFace, double fontScale, Scalar color, int thickness, int lineType, boolean bottomLeftOrigin) { putText_0(img.nativeObj, text, org.x, org.y, fontFace, fontScale, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType, bottomLeftOrigin); } - - // - // C++: void cv::ellipse2Poly(Point center, Size axes, int angle, int arcStart, int arcEnd, int delta, vector_Point& pts) - // - /** * Draws a text string. - *

    + * * The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered * using the specified font are replaced by question marks. See #getTextSize for a text rendering code * example. * - * @param img Image. - * @param text Text string to be drawn. - * @param org Bottom-left corner of the text string in the image. - * @param fontFace Font type, see #HersheyFonts. + * @param img Image. + * @param text Text string to be drawn. + * @param org Bottom-left corner of the text string in the image. + * @param fontFace Font type, see #HersheyFonts. * @param fontScale Font scale factor that is multiplied by the font-specific base size. - * @param color Text color. + * @param color Text color. * @param thickness Thickness of the lines used to draw a text. - * @param lineType Line type. See #LineTypes - * it is at the top-left corner. + * @param lineType Line type. See #LineTypes + * it is at the top-left corner. */ public static void putText(Mat img, String text, Point org, int fontFace, double fontScale, Scalar color, int thickness, int lineType) { putText_1(img.nativeObj, text, org.x, org.y, fontFace, fontScale, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType); } - - // - // C++: void cv::putText(Mat& img, String text, Point org, int fontFace, double fontScale, Scalar color, int thickness = 1, int lineType = LINE_8, bool bottomLeftOrigin = false) - // - /** * Draws a text string. - *

    + * * The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered * using the specified font are replaced by question marks. See #getTextSize for a text rendering code * example. * - * @param img Image. - * @param text Text string to be drawn. - * @param org Bottom-left corner of the text string in the image. - * @param fontFace Font type, see #HersheyFonts. + * @param img Image. + * @param text Text string to be drawn. + * @param org Bottom-left corner of the text string in the image. + * @param fontFace Font type, see #HersheyFonts. * @param fontScale Font scale factor that is multiplied by the font-specific base size. - * @param color Text color. + * @param color Text color. * @param thickness Thickness of the lines used to draw a text. - * it is at the top-left corner. + * it is at the top-left corner. */ public static void putText(Mat img, String text, Point org, int fontFace, double fontScale, Scalar color, int thickness) { putText_2(img.nativeObj, text, org.x, org.y, fontFace, fontScale, color.val[0], color.val[1], color.val[2], color.val[3], thickness); @@ -9418,31 +9493,36 @@ public static void putText(Mat img, String text, Point org, int fontFace, double /** * Draws a text string. - *

    + * * The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered * using the specified font are replaced by question marks. See #getTextSize for a text rendering code * example. * - * @param img Image. - * @param text Text string to be drawn. - * @param org Bottom-left corner of the text string in the image. - * @param fontFace Font type, see #HersheyFonts. + * @param img Image. + * @param text Text string to be drawn. + * @param org Bottom-left corner of the text string in the image. + * @param fontFace Font type, see #HersheyFonts. * @param fontScale Font scale factor that is multiplied by the font-specific base size. - * @param color Text color. - * it is at the top-left corner. + * @param color Text color. + * it is at the top-left corner. */ public static void putText(Mat img, String text, Point org, int fontFace, double fontScale, Scalar color) { putText_3(img.nativeObj, text, org.x, org.y, fontFace, fontScale, color.val[0], color.val[1], color.val[2], color.val[3]); } + + // + // C++: double cv::getFontScaleFromHeight(int fontFace, int pixelHeight, int thickness = 1) + // + /** * Calculates the font-specific size to use to achieve a given height in pixels. * - * @param fontFace Font to use, see cv::HersheyFonts. + * @param fontFace Font to use, see cv::HersheyFonts. * @param pixelHeight Pixel height to compute the fontScale for - * @param thickness Thickness of lines used to render the text.See putText for details. + * @param thickness Thickness of lines used to render the text.See putText for details. * @return The fontSize to use for cv::putText - *

    + * * SEE: cv::putText */ public static double getFontScaleFromHeight(int fontFace, int pixelHeight, int thickness) { @@ -9452,10 +9532,10 @@ public static double getFontScaleFromHeight(int fontFace, int pixelHeight, int t /** * Calculates the font-specific size to use to achieve a given height in pixels. * - * @param fontFace Font to use, see cv::HersheyFonts. + * @param fontFace Font to use, see cv::HersheyFonts. * @param pixelHeight Pixel height to compute the fontScale for * @return The fontSize to use for cv::putText - *

    + * * SEE: cv::putText */ public static double getFontScaleFromHeight(int fontFace, int pixelHeight) { @@ -9464,23 +9544,22 @@ public static double getFontScaleFromHeight(int fontFace, int pixelHeight) { // - // C++: double cv::getFontScaleFromHeight(int fontFace, int pixelHeight, int thickness = 1) + // C++: void cv::HoughLinesWithAccumulator(Mat image, Mat& lines, double rho, double theta, int threshold, double srn = 0, double stn = 0, double min_theta = 0, double max_theta = CV_PI) // /** * Finds lines in a binary image using the standard Hough transform and get accumulator. * * Note: This function is for bindings use only. Use original function in C++ code - *

    - * SEE: HoughLines * - * @param image automatically generated - * @param lines automatically generated - * @param rho automatically generated - * @param theta automatically generated + * SEE: HoughLines + * @param image automatically generated + * @param lines automatically generated + * @param rho automatically generated + * @param theta automatically generated * @param threshold automatically generated - * @param srn automatically generated - * @param stn automatically generated + * @param srn automatically generated + * @param stn automatically generated * @param min_theta automatically generated * @param max_theta automatically generated */ @@ -9492,41 +9571,34 @@ public static void HoughLinesWithAccumulator(Mat image, Mat lines, double rho, d * Finds lines in a binary image using the standard Hough transform and get accumulator. * * Note: This function is for bindings use only. Use original function in C++ code - *

    - * SEE: HoughLines * - * @param image automatically generated - * @param lines automatically generated - * @param rho automatically generated - * @param theta automatically generated + * SEE: HoughLines + * @param image automatically generated + * @param lines automatically generated + * @param rho automatically generated + * @param theta automatically generated * @param threshold automatically generated - * @param srn automatically generated - * @param stn automatically generated + * @param srn automatically generated + * @param stn automatically generated * @param min_theta automatically generated */ public static void HoughLinesWithAccumulator(Mat image, Mat lines, double rho, double theta, int threshold, double srn, double stn, double min_theta) { HoughLinesWithAccumulator_1(image.nativeObj, lines.nativeObj, rho, theta, threshold, srn, stn, min_theta); } - - // - // C++: void cv::HoughLinesWithAccumulator(Mat image, Mat& lines, double rho, double theta, int threshold, double srn = 0, double stn = 0, double min_theta = 0, double max_theta = CV_PI) - // - /** * Finds lines in a binary image using the standard Hough transform and get accumulator. * * Note: This function is for bindings use only. Use original function in C++ code - *

    - * SEE: HoughLines * - * @param image automatically generated - * @param lines automatically generated - * @param rho automatically generated - * @param theta automatically generated + * SEE: HoughLines + * @param image automatically generated + * @param lines automatically generated + * @param rho automatically generated + * @param theta automatically generated * @param threshold automatically generated - * @param srn automatically generated - * @param stn automatically generated + * @param srn automatically generated + * @param stn automatically generated */ public static void HoughLinesWithAccumulator(Mat image, Mat lines, double rho, double theta, int threshold, double srn, double stn) { HoughLinesWithAccumulator_2(image.nativeObj, lines.nativeObj, rho, theta, threshold, srn, stn); @@ -9536,15 +9608,14 @@ public static void HoughLinesWithAccumulator(Mat image, Mat lines, double rho, d * Finds lines in a binary image using the standard Hough transform and get accumulator. * * Note: This function is for bindings use only. Use original function in C++ code - *

    - * SEE: HoughLines * - * @param image automatically generated - * @param lines automatically generated - * @param rho automatically generated - * @param theta automatically generated + * SEE: HoughLines + * @param image automatically generated + * @param lines automatically generated + * @param rho automatically generated + * @param theta automatically generated * @param threshold automatically generated - * @param srn automatically generated + * @param srn automatically generated */ public static void HoughLinesWithAccumulator(Mat image, Mat lines, double rho, double theta, int threshold, double srn) { HoughLinesWithAccumulator_3(image.nativeObj, lines.nativeObj, rho, theta, threshold, srn); @@ -9554,69 +9625,59 @@ public static void HoughLinesWithAccumulator(Mat image, Mat lines, double rho, d * Finds lines in a binary image using the standard Hough transform and get accumulator. * * Note: This function is for bindings use only. Use original function in C++ code - *

    - * SEE: HoughLines * - * @param image automatically generated - * @param lines automatically generated - * @param rho automatically generated - * @param theta automatically generated + * SEE: HoughLines + * @param image automatically generated + * @param lines automatically generated + * @param rho automatically generated + * @param theta automatically generated * @param threshold automatically generated */ public static void HoughLinesWithAccumulator(Mat image, Mat lines, double rho, double theta, int threshold) { HoughLinesWithAccumulator_4(image.nativeObj, lines.nativeObj, rho, theta, threshold); } - // C++: Size getTextSize(const String& text, int fontFace, double fontScale, int thickness, int* baseLine); + + +// C++: Size getTextSize(const String& text, int fontFace, double fontScale, int thickness, int* baseLine); //javadoc:getTextSize(text, fontFace, fontScale, thickness, baseLine) - public static Size getTextSize(String text, int fontFace, double fontScale, int thickness, int[] baseLine) { - if (baseLine != null && baseLine.length != 1) - throw new IllegalArgumentException("'baseLine' must be 'int[1]' or 'null'."); - Size retVal = new Size(n_getTextSize(text, fontFace, fontScale, thickness, baseLine)); - return retVal; - } +public static Size getTextSize(String text, int fontFace, double fontScale, int thickness, int[] baseLine) { + if(baseLine != null && baseLine.length != 1) + throw new java.lang.IllegalArgumentException("'baseLine' must be 'int[1]' or 'null'."); + Size retVal = new Size(n_getTextSize(text, fontFace, fontScale, thickness, baseLine)); + return retVal; +} + + + // C++: Ptr_LineSegmentDetector cv::createLineSegmentDetector(int refine = LSD_REFINE_STD, double scale = 0.8, double sigma_scale = 0.6, double quant = 2.0, double ang_th = 22.5, double log_eps = 0, double density_th = 0.7, int n_bins = 1024) private static native long createLineSegmentDetector_0(int refine, double scale, double sigma_scale, double quant, double ang_th, double log_eps, double density_th, int n_bins); - private static native long createLineSegmentDetector_1(int refine, double scale, double sigma_scale, double quant, double ang_th, double log_eps, double density_th); - private static native long createLineSegmentDetector_2(int refine, double scale, double sigma_scale, double quant, double ang_th, double log_eps); - private static native long createLineSegmentDetector_3(int refine, double scale, double sigma_scale, double quant, double ang_th); - private static native long createLineSegmentDetector_4(int refine, double scale, double sigma_scale, double quant); - private static native long createLineSegmentDetector_5(int refine, double scale, double sigma_scale); - private static native long createLineSegmentDetector_6(int refine, double scale); - private static native long createLineSegmentDetector_7(int refine); - private static native long createLineSegmentDetector_8(); // C++: Mat cv::getGaussianKernel(int ksize, double sigma, int ktype = CV_64F) private static native long getGaussianKernel_0(int ksize, double sigma, int ktype); - private static native long getGaussianKernel_1(int ksize, double sigma); // C++: void cv::getDerivKernels(Mat& kx, Mat& ky, int dx, int dy, int ksize, bool normalize = false, int ktype = CV_32F) private static native void getDerivKernels_0(long kx_nativeObj, long ky_nativeObj, int dx, int dy, int ksize, boolean normalize, int ktype); - private static native void getDerivKernels_1(long kx_nativeObj, long ky_nativeObj, int dx, int dy, int ksize, boolean normalize); - private static native void getDerivKernels_2(long kx_nativeObj, long ky_nativeObj, int dx, int dy, int ksize); // C++: Mat cv::getGaborKernel(Size ksize, double sigma, double theta, double lambd, double gamma, double psi = CV_PI*0.5, int ktype = CV_64F) private static native long getGaborKernel_0(double ksize_width, double ksize_height, double sigma, double theta, double lambd, double gamma, double psi, int ktype); - private static native long getGaborKernel_1(double ksize_width, double ksize_height, double sigma, double theta, double lambd, double gamma, double psi); - private static native long getGaborKernel_2(double ksize_width, double ksize_height, double sigma, double theta, double lambd, double gamma); // C++: Mat cv::getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)) private static native long getStructuringElement_0(int shape, double ksize_width, double ksize_height, double anchor_x, double anchor_y); - private static native long getStructuringElement_1(int shape, double ksize_width, double ksize_height); // C++: void cv::medianBlur(Mat src, Mat& dst, int ksize) @@ -9624,39 +9685,28 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::GaussianBlur(Mat src, Mat& dst, Size ksize, double sigmaX, double sigmaY = 0, int borderType = BORDER_DEFAULT) private static native void GaussianBlur_0(long src_nativeObj, long dst_nativeObj, double ksize_width, double ksize_height, double sigmaX, double sigmaY, int borderType); - private static native void GaussianBlur_1(long src_nativeObj, long dst_nativeObj, double ksize_width, double ksize_height, double sigmaX, double sigmaY); - private static native void GaussianBlur_2(long src_nativeObj, long dst_nativeObj, double ksize_width, double ksize_height, double sigmaX); // C++: void cv::bilateralFilter(Mat src, Mat& dst, int d, double sigmaColor, double sigmaSpace, int borderType = BORDER_DEFAULT) private static native void bilateralFilter_0(long src_nativeObj, long dst_nativeObj, int d, double sigmaColor, double sigmaSpace, int borderType); - private static native void bilateralFilter_1(long src_nativeObj, long dst_nativeObj, int d, double sigmaColor, double sigmaSpace); // C++: void cv::boxFilter(Mat src, Mat& dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), bool normalize = true, int borderType = BORDER_DEFAULT) private static native void boxFilter_0(long src_nativeObj, long dst_nativeObj, int ddepth, double ksize_width, double ksize_height, double anchor_x, double anchor_y, boolean normalize, int borderType); - private static native void boxFilter_1(long src_nativeObj, long dst_nativeObj, int ddepth, double ksize_width, double ksize_height, double anchor_x, double anchor_y, boolean normalize); - private static native void boxFilter_2(long src_nativeObj, long dst_nativeObj, int ddepth, double ksize_width, double ksize_height, double anchor_x, double anchor_y); - private static native void boxFilter_3(long src_nativeObj, long dst_nativeObj, int ddepth, double ksize_width, double ksize_height); // C++: void cv::sqrBoxFilter(Mat src, Mat& dst, int ddepth, Size ksize, Point anchor = Point(-1, -1), bool normalize = true, int borderType = BORDER_DEFAULT) private static native void sqrBoxFilter_0(long src_nativeObj, long dst_nativeObj, int ddepth, double ksize_width, double ksize_height, double anchor_x, double anchor_y, boolean normalize, int borderType); - private static native void sqrBoxFilter_1(long src_nativeObj, long dst_nativeObj, int ddepth, double ksize_width, double ksize_height, double anchor_x, double anchor_y, boolean normalize); - private static native void sqrBoxFilter_2(long src_nativeObj, long dst_nativeObj, int ddepth, double ksize_width, double ksize_height, double anchor_x, double anchor_y); - private static native void sqrBoxFilter_3(long src_nativeObj, long dst_nativeObj, int ddepth, double ksize_width, double ksize_height); // C++: void cv::blur(Mat src, Mat& dst, Size ksize, Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT) private static native void blur_0(long src_nativeObj, long dst_nativeObj, double ksize_width, double ksize_height, double anchor_x, double anchor_y, int borderType); - private static native void blur_1(long src_nativeObj, long dst_nativeObj, double ksize_width, double ksize_height, double anchor_x, double anchor_y); - private static native void blur_2(long src_nativeObj, long dst_nativeObj, double ksize_width, double ksize_height); // C++: void cv::stackBlur(Mat src, Mat& dst, Size ksize) @@ -9664,92 +9714,65 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::filter2D(Mat src, Mat& dst, int ddepth, Mat kernel, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT) private static native void filter2D_0(long src_nativeObj, long dst_nativeObj, int ddepth, long kernel_nativeObj, double anchor_x, double anchor_y, double delta, int borderType); - private static native void filter2D_1(long src_nativeObj, long dst_nativeObj, int ddepth, long kernel_nativeObj, double anchor_x, double anchor_y, double delta); - private static native void filter2D_2(long src_nativeObj, long dst_nativeObj, int ddepth, long kernel_nativeObj, double anchor_x, double anchor_y); - private static native void filter2D_3(long src_nativeObj, long dst_nativeObj, int ddepth, long kernel_nativeObj); // C++: void cv::sepFilter2D(Mat src, Mat& dst, int ddepth, Mat kernelX, Mat kernelY, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT) private static native void sepFilter2D_0(long src_nativeObj, long dst_nativeObj, int ddepth, long kernelX_nativeObj, long kernelY_nativeObj, double anchor_x, double anchor_y, double delta, int borderType); - private static native void sepFilter2D_1(long src_nativeObj, long dst_nativeObj, int ddepth, long kernelX_nativeObj, long kernelY_nativeObj, double anchor_x, double anchor_y, double delta); - private static native void sepFilter2D_2(long src_nativeObj, long dst_nativeObj, int ddepth, long kernelX_nativeObj, long kernelY_nativeObj, double anchor_x, double anchor_y); - private static native void sepFilter2D_3(long src_nativeObj, long dst_nativeObj, int ddepth, long kernelX_nativeObj, long kernelY_nativeObj); // C++: void cv::Sobel(Mat src, Mat& dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT) private static native void Sobel_0(long src_nativeObj, long dst_nativeObj, int ddepth, int dx, int dy, int ksize, double scale, double delta, int borderType); - private static native void Sobel_1(long src_nativeObj, long dst_nativeObj, int ddepth, int dx, int dy, int ksize, double scale, double delta); - private static native void Sobel_2(long src_nativeObj, long dst_nativeObj, int ddepth, int dx, int dy, int ksize, double scale); - private static native void Sobel_3(long src_nativeObj, long dst_nativeObj, int ddepth, int dx, int dy, int ksize); - private static native void Sobel_4(long src_nativeObj, long dst_nativeObj, int ddepth, int dx, int dy); // C++: void cv::spatialGradient(Mat src, Mat& dx, Mat& dy, int ksize = 3, int borderType = BORDER_DEFAULT) private static native void spatialGradient_0(long src_nativeObj, long dx_nativeObj, long dy_nativeObj, int ksize, int borderType); - private static native void spatialGradient_1(long src_nativeObj, long dx_nativeObj, long dy_nativeObj, int ksize); - private static native void spatialGradient_2(long src_nativeObj, long dx_nativeObj, long dy_nativeObj); // C++: void cv::Scharr(Mat src, Mat& dst, int ddepth, int dx, int dy, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT) private static native void Scharr_0(long src_nativeObj, long dst_nativeObj, int ddepth, int dx, int dy, double scale, double delta, int borderType); - private static native void Scharr_1(long src_nativeObj, long dst_nativeObj, int ddepth, int dx, int dy, double scale, double delta); - private static native void Scharr_2(long src_nativeObj, long dst_nativeObj, int ddepth, int dx, int dy, double scale); - private static native void Scharr_3(long src_nativeObj, long dst_nativeObj, int ddepth, int dx, int dy); // C++: void cv::Laplacian(Mat src, Mat& dst, int ddepth, int ksize = 1, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT) private static native void Laplacian_0(long src_nativeObj, long dst_nativeObj, int ddepth, int ksize, double scale, double delta, int borderType); - private static native void Laplacian_1(long src_nativeObj, long dst_nativeObj, int ddepth, int ksize, double scale, double delta); - private static native void Laplacian_2(long src_nativeObj, long dst_nativeObj, int ddepth, int ksize, double scale); - private static native void Laplacian_3(long src_nativeObj, long dst_nativeObj, int ddepth, int ksize); - private static native void Laplacian_4(long src_nativeObj, long dst_nativeObj, int ddepth); // C++: void cv::Canny(Mat image, Mat& edges, double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) private static native void Canny_0(long image_nativeObj, long edges_nativeObj, double threshold1, double threshold2, int apertureSize, boolean L2gradient); - private static native void Canny_1(long image_nativeObj, long edges_nativeObj, double threshold1, double threshold2, int apertureSize); - private static native void Canny_2(long image_nativeObj, long edges_nativeObj, double threshold1, double threshold2); // C++: void cv::Canny(Mat dx, Mat dy, Mat& edges, double threshold1, double threshold2, bool L2gradient = false) private static native void Canny_3(long dx_nativeObj, long dy_nativeObj, long edges_nativeObj, double threshold1, double threshold2, boolean L2gradient); - private static native void Canny_4(long dx_nativeObj, long dy_nativeObj, long edges_nativeObj, double threshold1, double threshold2); // C++: void cv::cornerMinEigenVal(Mat src, Mat& dst, int blockSize, int ksize = 3, int borderType = BORDER_DEFAULT) private static native void cornerMinEigenVal_0(long src_nativeObj, long dst_nativeObj, int blockSize, int ksize, int borderType); - private static native void cornerMinEigenVal_1(long src_nativeObj, long dst_nativeObj, int blockSize, int ksize); - private static native void cornerMinEigenVal_2(long src_nativeObj, long dst_nativeObj, int blockSize); // C++: void cv::cornerHarris(Mat src, Mat& dst, int blockSize, int ksize, double k, int borderType = BORDER_DEFAULT) private static native void cornerHarris_0(long src_nativeObj, long dst_nativeObj, int blockSize, int ksize, double k, int borderType); - private static native void cornerHarris_1(long src_nativeObj, long dst_nativeObj, int blockSize, int ksize, double k); // C++: void cv::cornerEigenValsAndVecs(Mat src, Mat& dst, int blockSize, int ksize, int borderType = BORDER_DEFAULT) private static native void cornerEigenValsAndVecs_0(long src_nativeObj, long dst_nativeObj, int blockSize, int ksize, int borderType); - private static native void cornerEigenValsAndVecs_1(long src_nativeObj, long dst_nativeObj, int blockSize, int ksize); // C++: void cv::preCornerDetect(Mat src, Mat& dst, int ksize, int borderType = BORDER_DEFAULT) private static native void preCornerDetect_0(long src_nativeObj, long dst_nativeObj, int ksize, int borderType); - private static native void preCornerDetect_1(long src_nativeObj, long dst_nativeObj, int ksize); // C++: void cv::cornerSubPix(Mat image, Mat& corners, Size winSize, Size zeroZone, TermCriteria criteria) @@ -9757,49 +9780,33 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::goodFeaturesToTrack(Mat image, vector_Point& corners, int maxCorners, double qualityLevel, double minDistance, Mat mask = Mat(), int blockSize = 3, bool useHarrisDetector = false, double k = 0.04) private static native void goodFeaturesToTrack_0(long image_nativeObj, long corners_mat_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, int blockSize, boolean useHarrisDetector, double k); - private static native void goodFeaturesToTrack_1(long image_nativeObj, long corners_mat_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, int blockSize, boolean useHarrisDetector); - private static native void goodFeaturesToTrack_2(long image_nativeObj, long corners_mat_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, int blockSize); - private static native void goodFeaturesToTrack_3(long image_nativeObj, long corners_mat_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj); - private static native void goodFeaturesToTrack_4(long image_nativeObj, long corners_mat_nativeObj, int maxCorners, double qualityLevel, double minDistance); // C++: void cv::goodFeaturesToTrack(Mat image, vector_Point& corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, int blockSize, int gradientSize, bool useHarrisDetector = false, double k = 0.04) private static native void goodFeaturesToTrack_5(long image_nativeObj, long corners_mat_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, int blockSize, int gradientSize, boolean useHarrisDetector, double k); - private static native void goodFeaturesToTrack_6(long image_nativeObj, long corners_mat_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, int blockSize, int gradientSize, boolean useHarrisDetector); - private static native void goodFeaturesToTrack_7(long image_nativeObj, long corners_mat_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, int blockSize, int gradientSize); // C++: void cv::goodFeaturesToTrack(Mat image, Mat& corners, int maxCorners, double qualityLevel, double minDistance, Mat mask, Mat& cornersQuality, int blockSize = 3, int gradientSize = 3, bool useHarrisDetector = false, double k = 0.04) private static native void goodFeaturesToTrackWithQuality_0(long image_nativeObj, long corners_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, long cornersQuality_nativeObj, int blockSize, int gradientSize, boolean useHarrisDetector, double k); - private static native void goodFeaturesToTrackWithQuality_1(long image_nativeObj, long corners_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, long cornersQuality_nativeObj, int blockSize, int gradientSize, boolean useHarrisDetector); - private static native void goodFeaturesToTrackWithQuality_2(long image_nativeObj, long corners_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, long cornersQuality_nativeObj, int blockSize, int gradientSize); - private static native void goodFeaturesToTrackWithQuality_3(long image_nativeObj, long corners_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, long cornersQuality_nativeObj, int blockSize); - private static native void goodFeaturesToTrackWithQuality_4(long image_nativeObj, long corners_nativeObj, int maxCorners, double qualityLevel, double minDistance, long mask_nativeObj, long cornersQuality_nativeObj); // C++: void cv::HoughLines(Mat image, Mat& lines, double rho, double theta, int threshold, double srn = 0, double stn = 0, double min_theta = 0, double max_theta = CV_PI) private static native void HoughLines_0(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double srn, double stn, double min_theta, double max_theta); - private static native void HoughLines_1(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double srn, double stn, double min_theta); - private static native void HoughLines_2(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double srn, double stn); - private static native void HoughLines_3(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double srn); - private static native void HoughLines_4(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold); // C++: void cv::HoughLinesP(Mat image, Mat& lines, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0) private static native void HoughLinesP_0(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double minLineLength, double maxLineGap); - private static native void HoughLinesP_1(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double minLineLength); - private static native void HoughLinesP_2(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold); // C++: void cv::HoughLinesPointSet(Mat point, Mat& lines, int lines_max, int threshold, double min_rho, double max_rho, double rho_step, double min_theta, double max_theta, double theta_step) @@ -9807,85 +9814,57 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::HoughCircles(Mat image, Mat& circles, int method, double dp, double minDist, double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0) private static native void HoughCircles_0(long image_nativeObj, long circles_nativeObj, int method, double dp, double minDist, double param1, double param2, int minRadius, int maxRadius); - private static native void HoughCircles_1(long image_nativeObj, long circles_nativeObj, int method, double dp, double minDist, double param1, double param2, int minRadius); - private static native void HoughCircles_2(long image_nativeObj, long circles_nativeObj, int method, double dp, double minDist, double param1, double param2); - private static native void HoughCircles_3(long image_nativeObj, long circles_nativeObj, int method, double dp, double minDist, double param1); - private static native void HoughCircles_4(long image_nativeObj, long circles_nativeObj, int method, double dp, double minDist); // C++: void cv::erode(Mat src, Mat& dst, Mat kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, Scalar borderValue = morphologyDefaultBorderValue()) private static native void erode_0(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj, double anchor_x, double anchor_y, int iterations, int borderType, double borderValue_val0, double borderValue_val1, double borderValue_val2, double borderValue_val3); - private static native void erode_1(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj, double anchor_x, double anchor_y, int iterations, int borderType); - private static native void erode_2(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj, double anchor_x, double anchor_y, int iterations); - private static native void erode_3(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj, double anchor_x, double anchor_y); - private static native void erode_4(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj); // C++: void cv::dilate(Mat src, Mat& dst, Mat kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, Scalar borderValue = morphologyDefaultBorderValue()) private static native void dilate_0(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj, double anchor_x, double anchor_y, int iterations, int borderType, double borderValue_val0, double borderValue_val1, double borderValue_val2, double borderValue_val3); - private static native void dilate_1(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj, double anchor_x, double anchor_y, int iterations, int borderType); - private static native void dilate_2(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj, double anchor_x, double anchor_y, int iterations); - private static native void dilate_3(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj, double anchor_x, double anchor_y); - private static native void dilate_4(long src_nativeObj, long dst_nativeObj, long kernel_nativeObj); // C++: void cv::morphologyEx(Mat src, Mat& dst, int op, Mat kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, Scalar borderValue = morphologyDefaultBorderValue()) private static native void morphologyEx_0(long src_nativeObj, long dst_nativeObj, int op, long kernel_nativeObj, double anchor_x, double anchor_y, int iterations, int borderType, double borderValue_val0, double borderValue_val1, double borderValue_val2, double borderValue_val3); - private static native void morphologyEx_1(long src_nativeObj, long dst_nativeObj, int op, long kernel_nativeObj, double anchor_x, double anchor_y, int iterations, int borderType); - private static native void morphologyEx_2(long src_nativeObj, long dst_nativeObj, int op, long kernel_nativeObj, double anchor_x, double anchor_y, int iterations); - private static native void morphologyEx_3(long src_nativeObj, long dst_nativeObj, int op, long kernel_nativeObj, double anchor_x, double anchor_y); - private static native void morphologyEx_4(long src_nativeObj, long dst_nativeObj, int op, long kernel_nativeObj); // C++: void cv::resize(Mat src, Mat& dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR) private static native void resize_0(long src_nativeObj, long dst_nativeObj, double dsize_width, double dsize_height, double fx, double fy, int interpolation); - private static native void resize_1(long src_nativeObj, long dst_nativeObj, double dsize_width, double dsize_height, double fx, double fy); - private static native void resize_2(long src_nativeObj, long dst_nativeObj, double dsize_width, double dsize_height, double fx); - private static native void resize_3(long src_nativeObj, long dst_nativeObj, double dsize_width, double dsize_height); // C++: void cv::warpAffine(Mat src, Mat& dst, Mat M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar()) private static native void warpAffine_0(long src_nativeObj, long dst_nativeObj, long M_nativeObj, double dsize_width, double dsize_height, int flags, int borderMode, double borderValue_val0, double borderValue_val1, double borderValue_val2, double borderValue_val3); - private static native void warpAffine_1(long src_nativeObj, long dst_nativeObj, long M_nativeObj, double dsize_width, double dsize_height, int flags, int borderMode); - private static native void warpAffine_2(long src_nativeObj, long dst_nativeObj, long M_nativeObj, double dsize_width, double dsize_height, int flags); - private static native void warpAffine_3(long src_nativeObj, long dst_nativeObj, long M_nativeObj, double dsize_width, double dsize_height); // C++: void cv::warpPerspective(Mat src, Mat& dst, Mat M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar()) private static native void warpPerspective_0(long src_nativeObj, long dst_nativeObj, long M_nativeObj, double dsize_width, double dsize_height, int flags, int borderMode, double borderValue_val0, double borderValue_val1, double borderValue_val2, double borderValue_val3); - private static native void warpPerspective_1(long src_nativeObj, long dst_nativeObj, long M_nativeObj, double dsize_width, double dsize_height, int flags, int borderMode); - private static native void warpPerspective_2(long src_nativeObj, long dst_nativeObj, long M_nativeObj, double dsize_width, double dsize_height, int flags); - private static native void warpPerspective_3(long src_nativeObj, long dst_nativeObj, long M_nativeObj, double dsize_width, double dsize_height); // C++: void cv::remap(Mat src, Mat& dst, Mat map1, Mat map2, int interpolation, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar()) private static native void remap_0(long src_nativeObj, long dst_nativeObj, long map1_nativeObj, long map2_nativeObj, int interpolation, int borderMode, double borderValue_val0, double borderValue_val1, double borderValue_val2, double borderValue_val3); - private static native void remap_1(long src_nativeObj, long dst_nativeObj, long map1_nativeObj, long map2_nativeObj, int interpolation, int borderMode); - private static native void remap_2(long src_nativeObj, long dst_nativeObj, long map1_nativeObj, long map2_nativeObj, int interpolation); // C++: void cv::convertMaps(Mat map1, Mat map2, Mat& dstmap1, Mat& dstmap2, int dstmap1type, bool nninterpolation = false) private static native void convertMaps_0(long map1_nativeObj, long map2_nativeObj, long dstmap1_nativeObj, long dstmap2_nativeObj, int dstmap1type, boolean nninterpolation); - private static native void convertMaps_1(long map1_nativeObj, long map2_nativeObj, long dstmap1_nativeObj, long dstmap2_nativeObj, int dstmap1type); // C++: Mat cv::getRotationMatrix2D(Point2f center, double angle, double scale) @@ -9896,7 +9875,6 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: Mat cv::getPerspectiveTransform(Mat src, Mat dst, int solveMethod = DECOMP_LU) private static native long getPerspectiveTransform_0(long src_nativeObj, long dst_nativeObj, int solveMethod); - private static native long getPerspectiveTransform_1(long src_nativeObj, long dst_nativeObj); // C++: Mat cv::getAffineTransform(vector_Point2f src, vector_Point2f dst) @@ -9904,7 +9882,6 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::getRectSubPix(Mat image, Size patchSize, Point2f center, Mat& patch, int patchType = -1) private static native void getRectSubPix_0(long image_nativeObj, double patchSize_width, double patchSize_height, double center_x, double center_y, long patch_nativeObj, int patchType); - private static native void getRectSubPix_1(long image_nativeObj, double patchSize_width, double patchSize_height, double center_x, double center_y, long patch_nativeObj); // C++: void cv::logPolar(Mat src, Mat& dst, Point2f center, double M, int flags) @@ -9918,48 +9895,37 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::integral(Mat src, Mat& sum, Mat& sqsum, Mat& tilted, int sdepth = -1, int sqdepth = -1) private static native void integral3_0(long src_nativeObj, long sum_nativeObj, long sqsum_nativeObj, long tilted_nativeObj, int sdepth, int sqdepth); - private static native void integral3_1(long src_nativeObj, long sum_nativeObj, long sqsum_nativeObj, long tilted_nativeObj, int sdepth); - private static native void integral3_2(long src_nativeObj, long sum_nativeObj, long sqsum_nativeObj, long tilted_nativeObj); // C++: void cv::integral(Mat src, Mat& sum, int sdepth = -1) private static native void integral_0(long src_nativeObj, long sum_nativeObj, int sdepth); - private static native void integral_1(long src_nativeObj, long sum_nativeObj); // C++: void cv::integral(Mat src, Mat& sum, Mat& sqsum, int sdepth = -1, int sqdepth = -1) private static native void integral2_0(long src_nativeObj, long sum_nativeObj, long sqsum_nativeObj, int sdepth, int sqdepth); - private static native void integral2_1(long src_nativeObj, long sum_nativeObj, long sqsum_nativeObj, int sdepth); - private static native void integral2_2(long src_nativeObj, long sum_nativeObj, long sqsum_nativeObj); // C++: void cv::accumulate(Mat src, Mat& dst, Mat mask = Mat()) private static native void accumulate_0(long src_nativeObj, long dst_nativeObj, long mask_nativeObj); - private static native void accumulate_1(long src_nativeObj, long dst_nativeObj); // C++: void cv::accumulateSquare(Mat src, Mat& dst, Mat mask = Mat()) private static native void accumulateSquare_0(long src_nativeObj, long dst_nativeObj, long mask_nativeObj); - private static native void accumulateSquare_1(long src_nativeObj, long dst_nativeObj); // C++: void cv::accumulateProduct(Mat src1, Mat src2, Mat& dst, Mat mask = Mat()) private static native void accumulateProduct_0(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj, long mask_nativeObj); - private static native void accumulateProduct_1(long src1_nativeObj, long src2_nativeObj, long dst_nativeObj); // C++: void cv::accumulateWeighted(Mat src, Mat& dst, double alpha, Mat mask = Mat()) private static native void accumulateWeighted_0(long src_nativeObj, long dst_nativeObj, double alpha, long mask_nativeObj); - private static native void accumulateWeighted_1(long src_nativeObj, long dst_nativeObj, double alpha); // C++: Point2d cv::phaseCorrelate(Mat src1, Mat src2, Mat window = Mat(), double* response = 0) private static native double[] phaseCorrelate_0(long src1_nativeObj, long src2_nativeObj, long window_nativeObj, double[] response_out); - private static native double[] phaseCorrelate_1(long src1_nativeObj, long src2_nativeObj, long window_nativeObj); - private static native double[] phaseCorrelate_2(long src1_nativeObj, long src2_nativeObj); // C++: void cv::createHanningWindow(Mat& dst, Size winSize, int type) @@ -9967,7 +9933,6 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::divSpectrums(Mat a, Mat b, Mat& c, int flags, bool conjB = false) private static native void divSpectrums_0(long a_nativeObj, long b_nativeObj, long c_nativeObj, int flags, boolean conjB); - private static native void divSpectrums_1(long a_nativeObj, long b_nativeObj, long c_nativeObj, int flags); // C++: double cv::threshold(Mat src, Mat& dst, double thresh, double maxval, int type) @@ -9978,21 +9943,16 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::pyrDown(Mat src, Mat& dst, Size dstsize = Size(), int borderType = BORDER_DEFAULT) private static native void pyrDown_0(long src_nativeObj, long dst_nativeObj, double dstsize_width, double dstsize_height, int borderType); - private static native void pyrDown_1(long src_nativeObj, long dst_nativeObj, double dstsize_width, double dstsize_height); - private static native void pyrDown_2(long src_nativeObj, long dst_nativeObj); // C++: void cv::pyrUp(Mat src, Mat& dst, Size dstsize = Size(), int borderType = BORDER_DEFAULT) private static native void pyrUp_0(long src_nativeObj, long dst_nativeObj, double dstsize_width, double dstsize_height, int borderType); - private static native void pyrUp_1(long src_nativeObj, long dst_nativeObj, double dstsize_width, double dstsize_height); - private static native void pyrUp_2(long src_nativeObj, long dst_nativeObj); // C++: void cv::calcHist(vector_Mat images, vector_int channels, Mat mask, Mat& hist, vector_int histSize, vector_float ranges, bool accumulate = false) private static native void calcHist_0(long images_mat_nativeObj, long channels_mat_nativeObj, long mask_nativeObj, long hist_nativeObj, long histSize_mat_nativeObj, long ranges_mat_nativeObj, boolean accumulate); - private static native void calcHist_1(long images_mat_nativeObj, long channels_mat_nativeObj, long mask_nativeObj, long hist_nativeObj, long histSize_mat_nativeObj, long ranges_mat_nativeObj); // C++: void cv::calcBackProject(vector_Mat images, vector_int channels, Mat hist, Mat& dst, vector_float ranges, double scale) @@ -10006,16 +9966,12 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: Ptr_CLAHE cv::createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)) private static native long createCLAHE_0(double clipLimit, double tileGridSize_width, double tileGridSize_height); - private static native long createCLAHE_1(double clipLimit); - private static native long createCLAHE_2(); // C++: float cv::wrapperEMD(Mat signature1, Mat signature2, int distType, Mat cost = Mat(), Ptr_float& lowerBound = Ptr(), Mat& flow = Mat()) private static native float EMD_0(long signature1_nativeObj, long signature2_nativeObj, int distType, long cost_nativeObj, long flow_nativeObj); - private static native float EMD_1(long signature1_nativeObj, long signature2_nativeObj, int distType, long cost_nativeObj); - private static native float EMD_3(long signature1_nativeObj, long signature2_nativeObj, int distType); // C++: void cv::watershed(Mat image, Mat& markers) @@ -10023,35 +9979,26 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::pyrMeanShiftFiltering(Mat src, Mat& dst, double sp, double sr, int maxLevel = 1, TermCriteria termcrit = TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1)) private static native void pyrMeanShiftFiltering_0(long src_nativeObj, long dst_nativeObj, double sp, double sr, int maxLevel, int termcrit_type, int termcrit_maxCount, double termcrit_epsilon); - private static native void pyrMeanShiftFiltering_1(long src_nativeObj, long dst_nativeObj, double sp, double sr, int maxLevel); - private static native void pyrMeanShiftFiltering_2(long src_nativeObj, long dst_nativeObj, double sp, double sr); // C++: void cv::grabCut(Mat img, Mat& mask, Rect rect, Mat& bgdModel, Mat& fgdModel, int iterCount, int mode = GC_EVAL) private static native void grabCut_0(long img_nativeObj, long mask_nativeObj, int rect_x, int rect_y, int rect_width, int rect_height, long bgdModel_nativeObj, long fgdModel_nativeObj, int iterCount, int mode); - private static native void grabCut_1(long img_nativeObj, long mask_nativeObj, int rect_x, int rect_y, int rect_width, int rect_height, long bgdModel_nativeObj, long fgdModel_nativeObj, int iterCount); // C++: void cv::distanceTransform(Mat src, Mat& dst, Mat& labels, int distanceType, int maskSize, int labelType = DIST_LABEL_CCOMP) private static native void distanceTransformWithLabels_0(long src_nativeObj, long dst_nativeObj, long labels_nativeObj, int distanceType, int maskSize, int labelType); - private static native void distanceTransformWithLabels_1(long src_nativeObj, long dst_nativeObj, long labels_nativeObj, int distanceType, int maskSize); // C++: void cv::distanceTransform(Mat src, Mat& dst, int distanceType, int maskSize, int dstType = CV_32F) private static native void distanceTransform_0(long src_nativeObj, long dst_nativeObj, int distanceType, int maskSize, int dstType); - private static native void distanceTransform_1(long src_nativeObj, long dst_nativeObj, int distanceType, int maskSize); // C++: int cv::floodFill(Mat& image, Mat& mask, Point seedPoint, Scalar newVal, Rect* rect = 0, Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), int flags = 4) private static native int floodFill_0(long image_nativeObj, long mask_nativeObj, double seedPoint_x, double seedPoint_y, double newVal_val0, double newVal_val1, double newVal_val2, double newVal_val3, double[] rect_out, double loDiff_val0, double loDiff_val1, double loDiff_val2, double loDiff_val3, double upDiff_val0, double upDiff_val1, double upDiff_val2, double upDiff_val3, int flags); - private static native int floodFill_1(long image_nativeObj, long mask_nativeObj, double seedPoint_x, double seedPoint_y, double newVal_val0, double newVal_val1, double newVal_val2, double newVal_val3, double[] rect_out, double loDiff_val0, double loDiff_val1, double loDiff_val2, double loDiff_val3, double upDiff_val0, double upDiff_val1, double upDiff_val2, double upDiff_val3); - private static native int floodFill_2(long image_nativeObj, long mask_nativeObj, double seedPoint_x, double seedPoint_y, double newVal_val0, double newVal_val1, double newVal_val2, double newVal_val3, double[] rect_out, double loDiff_val0, double loDiff_val1, double loDiff_val2, double loDiff_val3); - private static native int floodFill_3(long image_nativeObj, long mask_nativeObj, double seedPoint_x, double seedPoint_y, double newVal_val0, double newVal_val1, double newVal_val2, double newVal_val3, double[] rect_out); - private static native int floodFill_4(long image_nativeObj, long mask_nativeObj, double seedPoint_x, double seedPoint_y, double newVal_val0, double newVal_val1, double newVal_val2, double newVal_val3); // C++: void cv::blendLinear(Mat src1, Mat src2, Mat weights1, Mat weights2, Mat& dst) @@ -10059,7 +10006,6 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::cvtColor(Mat src, Mat& dst, int code, int dstCn = 0) private static native void cvtColor_0(long src_nativeObj, long dst_nativeObj, int code, int dstCn); - private static native void cvtColor_1(long src_nativeObj, long dst_nativeObj, int code); // C++: void cv::cvtColorTwoPlane(Mat src1, Mat src2, Mat& dst, int code) @@ -10067,12 +10013,10 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::demosaicing(Mat src, Mat& dst, int code, int dstCn = 0) private static native void demosaicing_0(long src_nativeObj, long dst_nativeObj, int code, int dstCn); - private static native void demosaicing_1(long src_nativeObj, long dst_nativeObj, int code); // C++: Moments cv::moments(Mat array, bool binaryImage = false) private static native double[] moments_0(long array_nativeObj, boolean binaryImage); - private static native double[] moments_1(long array_nativeObj); // C++: void cv::HuMoments(Moments m, Mat& hu) @@ -10080,7 +10024,6 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::matchTemplate(Mat image, Mat templ, Mat& result, int method, Mat mask = Mat()) private static native void matchTemplate_0(long image_nativeObj, long templ_nativeObj, long result_nativeObj, int method, long mask_nativeObj); - private static native void matchTemplate_1(long image_nativeObj, long templ_nativeObj, long result_nativeObj, int method); // C++: int cv::connectedComponents(Mat image, Mat& labels, int connectivity, int ltype, int ccltype) @@ -10088,9 +10031,7 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: int cv::connectedComponents(Mat image, Mat& labels, int connectivity = 8, int ltype = CV_32S) private static native int connectedComponents_0(long image_nativeObj, long labels_nativeObj, int connectivity, int ltype); - private static native int connectedComponents_1(long image_nativeObj, long labels_nativeObj, int connectivity); - private static native int connectedComponents_2(long image_nativeObj, long labels_nativeObj); // C++: int cv::connectedComponentsWithStats(Mat image, Mat& labels, Mat& stats, Mat& centroids, int connectivity, int ltype, int ccltype) @@ -10098,14 +10039,11 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: int cv::connectedComponentsWithStats(Mat image, Mat& labels, Mat& stats, Mat& centroids, int connectivity = 8, int ltype = CV_32S) private static native int connectedComponentsWithStats_0(long image_nativeObj, long labels_nativeObj, long stats_nativeObj, long centroids_nativeObj, int connectivity, int ltype); - private static native int connectedComponentsWithStats_1(long image_nativeObj, long labels_nativeObj, long stats_nativeObj, long centroids_nativeObj, int connectivity); - private static native int connectedComponentsWithStats_2(long image_nativeObj, long labels_nativeObj, long stats_nativeObj, long centroids_nativeObj); // C++: void cv::findContours(Mat image, vector_vector_Point& contours, Mat& hierarchy, int mode, int method, Point offset = Point()) private static native void findContours_0(long image_nativeObj, long contours_mat_nativeObj, long hierarchy_nativeObj, int mode, int method, double offset_x, double offset_y); - private static native void findContours_1(long image_nativeObj, long contours_mat_nativeObj, long hierarchy_nativeObj, int mode, int method); // C++: void cv::approxPolyDP(vector_Point2f curve, vector_Point2f& approxCurve, double epsilon, bool closed) @@ -10119,7 +10057,6 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: double cv::contourArea(Mat contour, bool oriented = false) private static native double contourArea_0(long contour_nativeObj, boolean oriented); - private static native double contourArea_1(long contour_nativeObj); // C++: RotatedRect cv::minAreaRect(vector_Point2f points) @@ -10139,7 +10076,6 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::convexHull(vector_Point points, vector_int& hull, bool clockwise = false, _hidden_ returnPoints = true) private static native void convexHull_0(long points_mat_nativeObj, long hull_mat_nativeObj, boolean clockwise); - private static native void convexHull_2(long points_mat_nativeObj, long hull_mat_nativeObj); // C++: void cv::convexityDefects(vector_Point contour, vector_int convexhull, vector_Vec4i& convexityDefects) @@ -10150,7 +10086,6 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: float cv::intersectConvexConvex(Mat p1, Mat p2, Mat& p12, bool handleNested = true) private static native float intersectConvexConvex_0(long p1_nativeObj, long p2_nativeObj, long p12_nativeObj, boolean handleNested); - private static native float intersectConvexConvex_1(long p1_nativeObj, long p2_nativeObj, long p12_nativeObj); // C++: RotatedRect cv::fitEllipse(vector_Point2f points) @@ -10185,114 +10120,76 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::line(Mat& img, Point pt1, Point pt2, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) private static native void line_0(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, int shift); - private static native void line_1(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType); - private static native void line_2(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void line_3(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::arrowedLine(Mat& img, Point pt1, Point pt2, Scalar color, int thickness = 1, int line_type = 8, int shift = 0, double tipLength = 0.1) private static native void arrowedLine_0(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int line_type, int shift, double tipLength); - private static native void arrowedLine_1(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int line_type, int shift); - private static native void arrowedLine_2(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int line_type); - private static native void arrowedLine_3(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void arrowedLine_4(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::rectangle(Mat& img, Point pt1, Point pt2, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) private static native void rectangle_0(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, int shift); - private static native void rectangle_1(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType); - private static native void rectangle_2(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void rectangle_3(long img_nativeObj, double pt1_x, double pt1_y, double pt2_x, double pt2_y, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::rectangle(Mat& img, Rect rec, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) private static native void rectangle_4(long img_nativeObj, int rec_x, int rec_y, int rec_width, int rec_height, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, int shift); - private static native void rectangle_5(long img_nativeObj, int rec_x, int rec_y, int rec_width, int rec_height, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType); - private static native void rectangle_6(long img_nativeObj, int rec_x, int rec_y, int rec_width, int rec_height, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void rectangle_7(long img_nativeObj, int rec_x, int rec_y, int rec_width, int rec_height, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::circle(Mat& img, Point center, int radius, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) private static native void circle_0(long img_nativeObj, double center_x, double center_y, int radius, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, int shift); - private static native void circle_1(long img_nativeObj, double center_x, double center_y, int radius, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType); - private static native void circle_2(long img_nativeObj, double center_x, double center_y, int radius, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void circle_3(long img_nativeObj, double center_x, double center_y, int radius, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) private static native void ellipse_0(long img_nativeObj, double center_x, double center_y, double axes_width, double axes_height, double angle, double startAngle, double endAngle, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, int shift); - private static native void ellipse_1(long img_nativeObj, double center_x, double center_y, double axes_width, double axes_height, double angle, double startAngle, double endAngle, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType); - private static native void ellipse_2(long img_nativeObj, double center_x, double center_y, double axes_width, double axes_height, double angle, double startAngle, double endAngle, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void ellipse_3(long img_nativeObj, double center_x, double center_y, double axes_width, double axes_height, double angle, double startAngle, double endAngle, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::ellipse(Mat& img, RotatedRect box, Scalar color, int thickness = 1, int lineType = LINE_8) private static native void ellipse_4(long img_nativeObj, double box_center_x, double box_center_y, double box_size_width, double box_size_height, double box_angle, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType); - private static native void ellipse_5(long img_nativeObj, double box_center_x, double box_center_y, double box_size_width, double box_size_height, double box_angle, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void ellipse_6(long img_nativeObj, double box_center_x, double box_center_y, double box_size_width, double box_size_height, double box_angle, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::drawMarker(Mat& img, Point position, Scalar color, int markerType = MARKER_CROSS, int markerSize = 20, int thickness = 1, int line_type = 8) private static native void drawMarker_0(long img_nativeObj, double position_x, double position_y, double color_val0, double color_val1, double color_val2, double color_val3, int markerType, int markerSize, int thickness, int line_type); - private static native void drawMarker_1(long img_nativeObj, double position_x, double position_y, double color_val0, double color_val1, double color_val2, double color_val3, int markerType, int markerSize, int thickness); - private static native void drawMarker_2(long img_nativeObj, double position_x, double position_y, double color_val0, double color_val1, double color_val2, double color_val3, int markerType, int markerSize); - private static native void drawMarker_3(long img_nativeObj, double position_x, double position_y, double color_val0, double color_val1, double color_val2, double color_val3, int markerType); - private static native void drawMarker_4(long img_nativeObj, double position_x, double position_y, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::fillConvexPoly(Mat& img, vector_Point points, Scalar color, int lineType = LINE_8, int shift = 0) private static native void fillConvexPoly_0(long img_nativeObj, long points_mat_nativeObj, double color_val0, double color_val1, double color_val2, double color_val3, int lineType, int shift); - private static native void fillConvexPoly_1(long img_nativeObj, long points_mat_nativeObj, double color_val0, double color_val1, double color_val2, double color_val3, int lineType); - private static native void fillConvexPoly_2(long img_nativeObj, long points_mat_nativeObj, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::fillPoly(Mat& img, vector_vector_Point pts, Scalar color, int lineType = LINE_8, int shift = 0, Point offset = Point()) private static native void fillPoly_0(long img_nativeObj, long pts_mat_nativeObj, double color_val0, double color_val1, double color_val2, double color_val3, int lineType, int shift, double offset_x, double offset_y); - private static native void fillPoly_1(long img_nativeObj, long pts_mat_nativeObj, double color_val0, double color_val1, double color_val2, double color_val3, int lineType, int shift); - private static native void fillPoly_2(long img_nativeObj, long pts_mat_nativeObj, double color_val0, double color_val1, double color_val2, double color_val3, int lineType); - private static native void fillPoly_3(long img_nativeObj, long pts_mat_nativeObj, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::polylines(Mat& img, vector_vector_Point pts, bool isClosed, Scalar color, int thickness = 1, int lineType = LINE_8, int shift = 0) private static native void polylines_0(long img_nativeObj, long pts_mat_nativeObj, boolean isClosed, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, int shift); - private static native void polylines_1(long img_nativeObj, long pts_mat_nativeObj, boolean isClosed, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType); - private static native void polylines_2(long img_nativeObj, long pts_mat_nativeObj, boolean isClosed, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void polylines_3(long img_nativeObj, long pts_mat_nativeObj, boolean isClosed, double color_val0, double color_val1, double color_val2, double color_val3); // C++: void cv::drawContours(Mat& image, vector_vector_Point contours, int contourIdx, Scalar color, int thickness = 1, int lineType = LINE_8, Mat hierarchy = Mat(), int maxLevel = INT_MAX, Point offset = Point()) private static native void drawContours_0(long image_nativeObj, long contours_mat_nativeObj, int contourIdx, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, long hierarchy_nativeObj, int maxLevel, double offset_x, double offset_y); - private static native void drawContours_1(long image_nativeObj, long contours_mat_nativeObj, int contourIdx, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, long hierarchy_nativeObj, int maxLevel); - private static native void drawContours_2(long image_nativeObj, long contours_mat_nativeObj, int contourIdx, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, long hierarchy_nativeObj); - private static native void drawContours_3(long image_nativeObj, long contours_mat_nativeObj, int contourIdx, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType); - private static native void drawContours_4(long image_nativeObj, long contours_mat_nativeObj, int contourIdx, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void drawContours_5(long image_nativeObj, long contours_mat_nativeObj, int contourIdx, double color_val0, double color_val1, double color_val2, double color_val3); // C++: bool cv::clipLine(Rect imgRect, Point& pt1, Point& pt2) @@ -10303,30 +10200,20 @@ public static Size getTextSize(String text, int fontFace, double fontScale, int // C++: void cv::putText(Mat& img, String text, Point org, int fontFace, double fontScale, Scalar color, int thickness = 1, int lineType = LINE_8, bool bottomLeftOrigin = false) private static native void putText_0(long img_nativeObj, String text, double org_x, double org_y, int fontFace, double fontScale, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType, boolean bottomLeftOrigin); - private static native void putText_1(long img_nativeObj, String text, double org_x, double org_y, int fontFace, double fontScale, double color_val0, double color_val1, double color_val2, double color_val3, int thickness, int lineType); - private static native void putText_2(long img_nativeObj, String text, double org_x, double org_y, int fontFace, double fontScale, double color_val0, double color_val1, double color_val2, double color_val3, int thickness); - private static native void putText_3(long img_nativeObj, String text, double org_x, double org_y, int fontFace, double fontScale, double color_val0, double color_val1, double color_val2, double color_val3); // C++: double cv::getFontScaleFromHeight(int fontFace, int pixelHeight, int thickness = 1) private static native double getFontScaleFromHeight_0(int fontFace, int pixelHeight, int thickness); - private static native double getFontScaleFromHeight_1(int fontFace, int pixelHeight); // C++: void cv::HoughLinesWithAccumulator(Mat image, Mat& lines, double rho, double theta, int threshold, double srn = 0, double stn = 0, double min_theta = 0, double max_theta = CV_PI) private static native void HoughLinesWithAccumulator_0(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double srn, double stn, double min_theta, double max_theta); - private static native void HoughLinesWithAccumulator_1(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double srn, double stn, double min_theta); - private static native void HoughLinesWithAccumulator_2(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double srn, double stn); - private static native void HoughLinesWithAccumulator_3(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold, double srn); - private static native void HoughLinesWithAccumulator_4(long image_nativeObj, long lines_nativeObj, double rho, double theta, int threshold); - - private static native double[] n_getTextSize(String text, int fontFace, double fontScale, int thickness, int[] baseLine); - +private static native double[] n_getTextSize(String text, int fontFace, double fontScale, int thickness, int[] baseLine); } diff --git a/bus-opencv/src/main/java/org/opencv/imgproc/IntelligentScissorsMB.java b/bus-opencv/src/main/java/org/opencv/imgproc/IntelligentScissorsMB.java index 211743746d..fc3a3b6e55 100644 --- a/bus-opencv/src/main/java/org/opencv/imgproc/IntelligentScissorsMB.java +++ b/bus-opencv/src/main/java/org/opencv/imgproc/IntelligentScissorsMB.java @@ -7,16 +7,15 @@ import org.opencv.core.Point; // C++: class IntelligentScissorsMB - /** * Intelligent Scissors image segmentation - *

    + * * This class is used to find the path (contour) between two points * which can be used for image segmentation. - *

    + * * Usage example: * SNIPPET: snippets/imgproc_segmentation.cpp usage_example_intelligent_scissors - *

    + * * Reference: <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.138.3811&rep=rep1&type=pdf">"Intelligent Scissors for Image Composition"</a> * algorithm designed by Eric N. Mortensen and William A. Barrett, Brigham Young University * CITE: Mortensen95intelligentscissors @@ -24,118 +23,39 @@ public class IntelligentScissorsMB { protected final long nativeObj; - protected IntelligentScissorsMB(long addr) { - nativeObj = addr; - + nativeObj = addr; + long nativeObjCopy = nativeObj; + org.opencv.core.Mat.cleaner.register(this, () -> delete(nativeObjCopy)); } - public IntelligentScissorsMB() { - this(IntelligentScissorsMB_0()); - } + public long getNativeObjAddr() { return nativeObj; } // internal usage only - public static IntelligentScissorsMB __fromPtr__(long addr) { - return new IntelligentScissorsMB(addr); - } + public static IntelligentScissorsMB __fromPtr__(long addr) { return new IntelligentScissorsMB(addr); } // // C++: cv::segmentation::IntelligentScissorsMB::IntelligentScissorsMB() // - // C++: cv::segmentation::IntelligentScissorsMB::IntelligentScissorsMB() - private static native long IntelligentScissorsMB_0(); + public IntelligentScissorsMB() { + nativeObj = IntelligentScissorsMB_0(); + long nativeObjCopy = nativeObj; + org.opencv.core.Mat.cleaner.register(this, () -> delete(nativeObjCopy)); + } // // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setWeights(float weight_non_edge, float weight_gradient_direction, float weight_gradient_magnitude) // - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setWeights(float weight_non_edge, float weight_gradient_direction, float weight_gradient_magnitude) - private static native long setWeights_0(long nativeObj, float weight_non_edge, float weight_gradient_direction, float weight_gradient_magnitude); - - - // - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setGradientMagnitudeMaxLimit(float gradient_magnitude_threshold_max = 0.0f) - // - - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setGradientMagnitudeMaxLimit(float gradient_magnitude_threshold_max = 0.0f) - private static native long setGradientMagnitudeMaxLimit_0(long nativeObj, float gradient_magnitude_threshold_max); - - private static native long setGradientMagnitudeMaxLimit_1(long nativeObj); - - - // - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setEdgeFeatureZeroCrossingParameters(float gradient_magnitude_min_value = 0.0f) - // - - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setEdgeFeatureZeroCrossingParameters(float gradient_magnitude_min_value = 0.0f) - private static native long setEdgeFeatureZeroCrossingParameters_0(long nativeObj, float gradient_magnitude_min_value); - - private static native long setEdgeFeatureZeroCrossingParameters_1(long nativeObj); - - - // - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setEdgeFeatureCannyParameters(double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) - // - - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setEdgeFeatureCannyParameters(double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) - private static native long setEdgeFeatureCannyParameters_0(long nativeObj, double threshold1, double threshold2, int apertureSize, boolean L2gradient); - - private static native long setEdgeFeatureCannyParameters_1(long nativeObj, double threshold1, double threshold2, int apertureSize); - - private static native long setEdgeFeatureCannyParameters_2(long nativeObj, double threshold1, double threshold2); - - - // - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::applyImage(Mat image) - // - - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::applyImage(Mat image) - private static native long applyImage_0(long nativeObj, long image_nativeObj); - - - // - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::applyImageFeatures(Mat non_edge, Mat gradient_direction, Mat gradient_magnitude, Mat image = Mat()) - // - - // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::applyImageFeatures(Mat non_edge, Mat gradient_direction, Mat gradient_magnitude, Mat image = Mat()) - private static native long applyImageFeatures_0(long nativeObj, long non_edge_nativeObj, long gradient_direction_nativeObj, long gradient_magnitude_nativeObj, long image_nativeObj); - - private static native long applyImageFeatures_1(long nativeObj, long non_edge_nativeObj, long gradient_direction_nativeObj, long gradient_magnitude_nativeObj); - - - // - // C++: void cv::segmentation::IntelligentScissorsMB::buildMap(Point sourcePt) - // - - // C++: void cv::segmentation::IntelligentScissorsMB::buildMap(Point sourcePt) - private static native void buildMap_0(long nativeObj, double sourcePt_x, double sourcePt_y); - - - // - // C++: void cv::segmentation::IntelligentScissorsMB::getContour(Point targetPt, Mat& contour, bool backward = false) - // - - // C++: void cv::segmentation::IntelligentScissorsMB::getContour(Point targetPt, Mat& contour, bool backward = false) - private static native void getContour_0(long nativeObj, double targetPt_x, double targetPt_y, long contour_nativeObj, boolean backward); - - private static native void getContour_1(long nativeObj, double targetPt_x, double targetPt_y, long contour_nativeObj); - - // native support for deleting native object - private static native void delete(long nativeObj); - - public long getNativeObjAddr() { - return nativeObj; - } - /** * Specify weights of feature functions - *

    + * * Consider keeping weights normalized (sum of weights equals to 1.0) * Discrete dynamic programming (DP) goal is minimization of costs between pixels. * - * @param weight_non_edge Specify cost of non-edge pixels (default: 0.43f) + * @param weight_non_edge Specify cost of non-edge pixels (default: 0.43f) * @param weight_gradient_direction Specify cost of gradient direction function (default: 0.43f) * @param weight_gradient_magnitude Specify cost of gradient magnitude function (default: 0.14f) * @return automatically generated @@ -144,9 +64,14 @@ public IntelligentScissorsMB setWeights(float weight_non_edge, float weight_grad return new IntelligentScissorsMB(setWeights_0(nativeObj, weight_non_edge, weight_gradient_direction, weight_gradient_magnitude)); } + + // + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setGradientMagnitudeMaxLimit(float gradient_magnitude_threshold_max = 0.0f) + // + /** * Specify gradient magnitude max value threshold - *

    + * * Zero limit value is used to disable gradient magnitude thresholding (default behavior, as described in original article). * Otherwize pixels with {@code gradient magnitude >= threshold} have zero cost. * @@ -161,7 +86,7 @@ public IntelligentScissorsMB setGradientMagnitudeMaxLimit(float gradient_magnitu /** * Specify gradient magnitude max value threshold - *

    + * * Zero limit value is used to disable gradient magnitude thresholding (default behavior, as described in original article). * Otherwize pixels with {@code gradient magnitude >= threshold} have zero cost. * @@ -173,11 +98,16 @@ public IntelligentScissorsMB setGradientMagnitudeMaxLimit() { return new IntelligentScissorsMB(setGradientMagnitudeMaxLimit_1(nativeObj)); } + + // + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setEdgeFeatureZeroCrossingParameters(float gradient_magnitude_min_value = 0.0f) + // + /** * Switch to "Laplacian Zero-Crossing" edge feature extractor and specify its parameters - *

    + * * This feature extractor is used by default according to article. - *

    + * * Implementation has additional filtering for regions with low-amplitude noise. * This filtering is enabled through parameter of minimal gradient amplitude (use some small value 4, 8, 16). * @@ -194,9 +124,9 @@ public IntelligentScissorsMB setEdgeFeatureZeroCrossingParameters(float gradient /** * Switch to "Laplacian Zero-Crossing" edge feature extractor and specify its parameters - *

    + * * This feature extractor is used by default according to article. - *

    + * * Implementation has additional filtering for regions with low-amplitude noise. * This filtering is enabled through parameter of minimal gradient amplitude (use some small value 4, 8, 16). * @@ -210,17 +140,21 @@ public IntelligentScissorsMB setEdgeFeatureZeroCrossingParameters() { return new IntelligentScissorsMB(setEdgeFeatureZeroCrossingParameters_1(nativeObj)); } + + // + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setEdgeFeatureCannyParameters(double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) + // + /** * Switch edge feature extractor to use Canny edge detector * * Note: "Laplacian Zero-Crossing" feature extractor is used by default (following to original article) - *

    - * SEE: Canny * - * @param threshold1 automatically generated - * @param threshold2 automatically generated + * SEE: Canny + * @param threshold1 automatically generated + * @param threshold2 automatically generated * @param apertureSize automatically generated - * @param L2gradient automatically generated + * @param L2gradient automatically generated * @return automatically generated */ public IntelligentScissorsMB setEdgeFeatureCannyParameters(double threshold1, double threshold2, int apertureSize, boolean L2gradient) { @@ -231,11 +165,10 @@ public IntelligentScissorsMB setEdgeFeatureCannyParameters(double threshold1, do * Switch edge feature extractor to use Canny edge detector * * Note: "Laplacian Zero-Crossing" feature extractor is used by default (following to original article) - *

    - * SEE: Canny * - * @param threshold1 automatically generated - * @param threshold2 automatically generated + * SEE: Canny + * @param threshold1 automatically generated + * @param threshold2 automatically generated * @param apertureSize automatically generated * @return automatically generated */ @@ -247,9 +180,8 @@ public IntelligentScissorsMB setEdgeFeatureCannyParameters(double threshold1, do * Switch edge feature extractor to use Canny edge detector * * Note: "Laplacian Zero-Crossing" feature extractor is used by default (following to original article) - *

    - * SEE: Canny * + * SEE: Canny * @param threshold1 automatically generated * @param threshold2 automatically generated * @return automatically generated @@ -258,6 +190,11 @@ public IntelligentScissorsMB setEdgeFeatureCannyParameters(double threshold1, do return new IntelligentScissorsMB(setEdgeFeatureCannyParameters_2(nativeObj, threshold1, threshold2)); } + + // + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::applyImage(Mat image) + // + /** * Specify input image and extract image features * @@ -268,15 +205,20 @@ public IntelligentScissorsMB applyImage(Mat image) { return new IntelligentScissorsMB(applyImage_0(nativeObj, image.nativeObj)); } + + // + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::applyImageFeatures(Mat non_edge, Mat gradient_direction, Mat gradient_magnitude, Mat image = Mat()) + // + /** * Specify custom features of input image - *

    + * * Customized advanced variant of applyImage() call. * - * @param non_edge Specify cost of non-edge pixels. Type is CV_8UC1. Expected values are {@code {0, 1}}. + * @param non_edge Specify cost of non-edge pixels. Type is CV_8UC1. Expected values are {@code {0, 1}}. * @param gradient_direction Specify gradient direction feature. Type is CV_32FC2. Values are expected to be normalized: {@code x^2 + y^2 == 1} * @param gradient_magnitude Specify cost of gradient magnitude function: Type is CV_32FC1. Values should be in range {@code [0, 1]}. - * @param image Optional parameter. Must be specified if subset of features is specified (non-specified features are calculated internally) + * @param image Optional parameter. Must be specified if subset of features is specified (non-specified features are calculated internally) * @return automatically generated */ public IntelligentScissorsMB applyImageFeatures(Mat non_edge, Mat gradient_direction, Mat gradient_magnitude, Mat image) { @@ -285,10 +227,10 @@ public IntelligentScissorsMB applyImageFeatures(Mat non_edge, Mat gradient_direc /** * Specify custom features of input image - *

    + * * Customized advanced variant of applyImage() call. * - * @param non_edge Specify cost of non-edge pixels. Type is CV_8UC1. Expected values are {@code {0, 1}}. + * @param non_edge Specify cost of non-edge pixels. Type is CV_8UC1. Expected values are {@code {0, 1}}. * @param gradient_direction Specify gradient direction feature. Type is CV_32FC2. Values are expected to be normalized: {@code x^2 + y^2 == 1} * @param gradient_magnitude Specify cost of gradient magnitude function: Type is CV_32FC1. Values should be in range {@code [0, 1]}. * @return automatically generated @@ -297,6 +239,11 @@ public IntelligentScissorsMB applyImageFeatures(Mat non_edge, Mat gradient_direc return new IntelligentScissorsMB(applyImageFeatures_1(nativeObj, non_edge.nativeObj, gradient_direction.nativeObj, gradient_magnitude.nativeObj)); } + + // + // C++: void cv::segmentation::IntelligentScissorsMB::buildMap(Point sourcePt) + // + /** * Prepares a map of optimal paths for the given source point on the image * @@ -308,13 +255,18 @@ public void buildMap(Point sourcePt) { buildMap_0(nativeObj, sourcePt.x, sourcePt.y); } + + // + // C++: void cv::segmentation::IntelligentScissorsMB::getContour(Point targetPt, Mat& contour, bool backward = false) + // + /** * Extracts optimal contour for the given target point on the image * * Note: buildMap() must be called before this call * * @param targetPt The target point - * @param contour The list of pixels which contains optimal path between the source and the target points of the image. Type is CV_32SC2 (compatible with {@code std::vector<Point>}) + * @param contour The list of pixels which contains optimal path between the source and the target points of the image. Type is CV_32SC2 (compatible with {@code std::vector<Point>}) * @param backward Flag to indicate reverse order of retrived pixels (use "true" value to fetch points from the target to the source point) */ public void getContour(Point targetPt, Mat contour, boolean backward) { @@ -327,15 +279,49 @@ public void getContour(Point targetPt, Mat contour, boolean backward) { * Note: buildMap() must be called before this call * * @param targetPt The target point - * @param contour The list of pixels which contains optimal path between the source and the target points of the image. Type is CV_32SC2 (compatible with {@code std::vector<Point>}) + * @param contour The list of pixels which contains optimal path between the source and the target points of the image. Type is CV_32SC2 (compatible with {@code std::vector<Point>}) */ public void getContour(Point targetPt, Mat contour) { getContour_1(nativeObj, targetPt.x, targetPt.y, contour.nativeObj); } - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } + + + + // C++: cv::segmentation::IntelligentScissorsMB::IntelligentScissorsMB() + private static native long IntelligentScissorsMB_0(); + + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setWeights(float weight_non_edge, float weight_gradient_direction, float weight_gradient_magnitude) + private static native long setWeights_0(long nativeObj, float weight_non_edge, float weight_gradient_direction, float weight_gradient_magnitude); + + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setGradientMagnitudeMaxLimit(float gradient_magnitude_threshold_max = 0.0f) + private static native long setGradientMagnitudeMaxLimit_0(long nativeObj, float gradient_magnitude_threshold_max); + private static native long setGradientMagnitudeMaxLimit_1(long nativeObj); + + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setEdgeFeatureZeroCrossingParameters(float gradient_magnitude_min_value = 0.0f) + private static native long setEdgeFeatureZeroCrossingParameters_0(long nativeObj, float gradient_magnitude_min_value); + private static native long setEdgeFeatureZeroCrossingParameters_1(long nativeObj); + + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::setEdgeFeatureCannyParameters(double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false) + private static native long setEdgeFeatureCannyParameters_0(long nativeObj, double threshold1, double threshold2, int apertureSize, boolean L2gradient); + private static native long setEdgeFeatureCannyParameters_1(long nativeObj, double threshold1, double threshold2, int apertureSize); + private static native long setEdgeFeatureCannyParameters_2(long nativeObj, double threshold1, double threshold2); + + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::applyImage(Mat image) + private static native long applyImage_0(long nativeObj, long image_nativeObj); + + // C++: IntelligentScissorsMB cv::segmentation::IntelligentScissorsMB::applyImageFeatures(Mat non_edge, Mat gradient_direction, Mat gradient_magnitude, Mat image = Mat()) + private static native long applyImageFeatures_0(long nativeObj, long non_edge_nativeObj, long gradient_direction_nativeObj, long gradient_magnitude_nativeObj, long image_nativeObj); + private static native long applyImageFeatures_1(long nativeObj, long non_edge_nativeObj, long gradient_direction_nativeObj, long gradient_magnitude_nativeObj); + + // C++: void cv::segmentation::IntelligentScissorsMB::buildMap(Point sourcePt) + private static native void buildMap_0(long nativeObj, double sourcePt_x, double sourcePt_y); + + // C++: void cv::segmentation::IntelligentScissorsMB::getContour(Point targetPt, Mat& contour, bool backward = false) + private static native void getContour_0(long nativeObj, double targetPt_x, double targetPt_y, long contour_nativeObj, boolean backward); + private static native void getContour_1(long nativeObj, double targetPt_x, double targetPt_y, long contour_nativeObj); + + // native support for deleting native object + private static native void delete(long nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/imgproc/LineSegmentDetector.java b/bus-opencv/src/main/java/org/opencv/imgproc/LineSegmentDetector.java index 0bf9ba82ad..aa89133ae4 100644 --- a/bus-opencv/src/main/java/org/opencv/imgproc/LineSegmentDetector.java +++ b/bus-opencv/src/main/java/org/opencv/imgproc/LineSegmentDetector.java @@ -8,10 +8,9 @@ import org.opencv.core.Size; // C++: class LineSegmentDetector - /** * Line segment detector class - *

    + * * following the algorithm described at CITE: Rafael12 . * * Note: Implementation has been removed from OpenCV version 3.4.6 to 3.4.15 and version 4.1.0 to 4.5.3 due original code license conflict. @@ -19,77 +18,43 @@ */ public class LineSegmentDetector extends Algorithm { - protected LineSegmentDetector(long addr) { - super(addr); - } + protected LineSegmentDetector(long addr) { super(addr); } // internal usage only - public static LineSegmentDetector __fromPtr__(long addr) { - return new LineSegmentDetector(addr); - } + public static LineSegmentDetector __fromPtr__(long addr) { return new LineSegmentDetector(addr); } // // C++: void cv::LineSegmentDetector::detect(Mat image, Mat& lines, Mat& width = Mat(), Mat& prec = Mat(), Mat& nfa = Mat()) // - // C++: void cv::LineSegmentDetector::detect(Mat image, Mat& lines, Mat& width = Mat(), Mat& prec = Mat(), Mat& nfa = Mat()) - private static native void detect_0(long nativeObj, long image_nativeObj, long lines_nativeObj, long width_nativeObj, long prec_nativeObj, long nfa_nativeObj); - - private static native void detect_1(long nativeObj, long image_nativeObj, long lines_nativeObj, long width_nativeObj, long prec_nativeObj); - - private static native void detect_2(long nativeObj, long image_nativeObj, long lines_nativeObj, long width_nativeObj); - - private static native void detect_3(long nativeObj, long image_nativeObj, long lines_nativeObj); - - - // - // C++: void cv::LineSegmentDetector::drawSegments(Mat& image, Mat lines) - // - - // C++: void cv::LineSegmentDetector::drawSegments(Mat& image, Mat lines) - private static native void drawSegments_0(long nativeObj, long image_nativeObj, long lines_nativeObj); - - - // - // C++: int cv::LineSegmentDetector::compareSegments(Size size, Mat lines1, Mat lines2, Mat& image = Mat()) - // - - // C++: int cv::LineSegmentDetector::compareSegments(Size size, Mat lines1, Mat lines2, Mat& image = Mat()) - private static native int compareSegments_0(long nativeObj, double size_width, double size_height, long lines1_nativeObj, long lines2_nativeObj, long image_nativeObj); - - private static native int compareSegments_1(long nativeObj, double size_width, double size_height, long lines1_nativeObj, long lines2_nativeObj); - - // native support for deleting native object - private static native void delete(long nativeObj); - /** * Finds lines in the input image. - *

    - * This is the output of the default parameters of the algorithm on the above shown image. - *

    - * ![image](pics/building_lsd.png) * - * @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: - * {@code lsd_ptr->detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);} - * @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where - * Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly - * oriented depending on the gradient. - * @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. - * @param prec Vector of precisions with which the lines are found. - * @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The - * bigger the value, logarithmically better the detection. - *

      - *
    • - * -1 corresponds to 10 mean false alarms - *
    • - *
    • - * 0 corresponds to 1 mean false alarm - *
    • - *
    • - * 1 corresponds to 0.1 mean false alarms - * This vector will be calculated only when the objects type is #LSD_REFINE_ADV. - *
    • - *
    + * This is the output of the default parameters of the algorithm on the above shown image. + * + * ![image](pics/building_lsd.png) + * + * @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: + * {@code lsd_ptr->detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);} + * @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where + * Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly + * oriented depending on the gradient. + * @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. + * @param prec Vector of precisions with which the lines are found. + * @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The + * bigger the value, logarithmically better the detection. + *
      + *
    • + * -1 corresponds to 10 mean false alarms + *
    • + *
    • + * 0 corresponds to 1 mean false alarm + *
    • + *
    • + * 1 corresponds to 0.1 mean false alarms + * This vector will be calculated only when the objects type is #LSD_REFINE_ADV. + *
    • + *
    */ public void detect(Mat image, Mat lines, Mat width, Mat prec, Mat nfa) { detect_0(nativeObj, image.nativeObj, lines.nativeObj, width.nativeObj, prec.nativeObj, nfa.nativeObj); @@ -97,31 +62,31 @@ public void detect(Mat image, Mat lines, Mat width, Mat prec, Mat nfa) { /** * Finds lines in the input image. - *

    - * This is the output of the default parameters of the algorithm on the above shown image. - *

    - * ![image](pics/building_lsd.png) * - * @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: - * {@code lsd_ptr->detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);} - * @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where - * Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly - * oriented depending on the gradient. - * @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. - * @param prec Vector of precisions with which the lines are found. - * bigger the value, logarithmically better the detection. - *

      - *
    • - * -1 corresponds to 10 mean false alarms - *
    • - *
    • - * 0 corresponds to 1 mean false alarm - *
    • - *
    • - * 1 corresponds to 0.1 mean false alarms - * This vector will be calculated only when the objects type is #LSD_REFINE_ADV. - *
    • - *
    + * This is the output of the default parameters of the algorithm on the above shown image. + * + * ![image](pics/building_lsd.png) + * + * @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: + * {@code lsd_ptr->detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);} + * @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where + * Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly + * oriented depending on the gradient. + * @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. + * @param prec Vector of precisions with which the lines are found. + * bigger the value, logarithmically better the detection. + *
      + *
    • + * -1 corresponds to 10 mean false alarms + *
    • + *
    • + * 0 corresponds to 1 mean false alarm + *
    • + *
    • + * 1 corresponds to 0.1 mean false alarms + * This vector will be calculated only when the objects type is #LSD_REFINE_ADV. + *
    • + *
    */ public void detect(Mat image, Mat lines, Mat width, Mat prec) { detect_1(nativeObj, image.nativeObj, lines.nativeObj, width.nativeObj, prec.nativeObj); @@ -129,30 +94,30 @@ public void detect(Mat image, Mat lines, Mat width, Mat prec) { /** * Finds lines in the input image. - *

    - * This is the output of the default parameters of the algorithm on the above shown image. - *

    - * ![image](pics/building_lsd.png) * - * @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: - * {@code lsd_ptr->detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);} - * @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where - * Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly - * oriented depending on the gradient. - * @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. - * bigger the value, logarithmically better the detection. - *

      - *
    • - * -1 corresponds to 10 mean false alarms - *
    • - *
    • - * 0 corresponds to 1 mean false alarm - *
    • - *
    • - * 1 corresponds to 0.1 mean false alarms - * This vector will be calculated only when the objects type is #LSD_REFINE_ADV. - *
    • - *
    + * This is the output of the default parameters of the algorithm on the above shown image. + * + * ![image](pics/building_lsd.png) + * + * @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: + * {@code lsd_ptr->detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);} + * @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where + * Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly + * oriented depending on the gradient. + * @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. + * bigger the value, logarithmically better the detection. + *
      + *
    • + * -1 corresponds to 10 mean false alarms + *
    • + *
    • + * 0 corresponds to 1 mean false alarm + *
    • + *
    • + * 1 corresponds to 0.1 mean false alarms + * This vector will be calculated only when the objects type is #LSD_REFINE_ADV. + *
    • + *
    */ public void detect(Mat image, Mat lines, Mat width) { detect_2(nativeObj, image.nativeObj, lines.nativeObj, width.nativeObj); @@ -160,53 +125,62 @@ public void detect(Mat image, Mat lines, Mat width) { /** * Finds lines in the input image. - *

    - * This is the output of the default parameters of the algorithm on the above shown image. - *

    - * ![image](pics/building_lsd.png) * - * @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: - * {@code lsd_ptr->detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);} - * @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where - * Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly - * oriented depending on the gradient. - * bigger the value, logarithmically better the detection. - *

      - *
    • - * -1 corresponds to 10 mean false alarms - *
    • - *
    • - * 0 corresponds to 1 mean false alarm - *
    • - *
    • - * 1 corresponds to 0.1 mean false alarms - * This vector will be calculated only when the objects type is #LSD_REFINE_ADV. - *
    • - *
    + * This is the output of the default parameters of the algorithm on the above shown image. + * + * ![image](pics/building_lsd.png) + * + * @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: + * {@code lsd_ptr->detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);} + * @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where + * Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly + * oriented depending on the gradient. + * bigger the value, logarithmically better the detection. + *
      + *
    • + * -1 corresponds to 10 mean false alarms + *
    • + *
    • + * 0 corresponds to 1 mean false alarm + *
    • + *
    • + * 1 corresponds to 0.1 mean false alarms + * This vector will be calculated only when the objects type is #LSD_REFINE_ADV. + *
    • + *
    */ public void detect(Mat image, Mat lines) { detect_3(nativeObj, image.nativeObj, lines.nativeObj); } + + // + // C++: void cv::LineSegmentDetector::drawSegments(Mat& image, Mat lines) + // + /** * Draws the line segments on a given image. - * - * @param image The image, where the lines will be drawn. Should be bigger or equal to the image, - * where the lines were found. - * @param lines A vector of the lines that needed to be drawn. + * @param image The image, where the lines will be drawn. Should be bigger or equal to the image, + * where the lines were found. + * @param lines A vector of the lines that needed to be drawn. */ public void drawSegments(Mat image, Mat lines) { drawSegments_0(nativeObj, image.nativeObj, lines.nativeObj); } + + // + // C++: int cv::LineSegmentDetector::compareSegments(Size size, Mat lines1, Mat lines2, Mat& image = Mat()) + // + /** * Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels. * - * @param size The size of the image, where lines1 and lines2 were found. - * @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. - * @param lines2 The second group of lines. They visualized in red color. - * @param image Optional image, where the lines will be drawn. The image should be color(3-channel) - * in order for lines1 and lines2 to be drawn in the above mentioned colors. + * @param size The size of the image, where lines1 and lines2 were found. + * @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. + * @param lines2 The second group of lines. They visualized in red color. + * @param image Optional image, where the lines will be drawn. The image should be color(3-channel) + * in order for lines1 and lines2 to be drawn in the above mentioned colors. * @return automatically generated */ public int compareSegments(Size size, Mat lines1, Mat lines2, Mat image) { @@ -216,19 +190,33 @@ public int compareSegments(Size size, Mat lines1, Mat lines2, Mat image) { /** * Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels. * - * @param size The size of the image, where lines1 and lines2 were found. - * @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. - * @param lines2 The second group of lines. They visualized in red color. - * in order for lines1 and lines2 to be drawn in the above mentioned colors. + * @param size The size of the image, where lines1 and lines2 were found. + * @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. + * @param lines2 The second group of lines. They visualized in red color. + * in order for lines1 and lines2 to be drawn in the above mentioned colors. * @return automatically generated */ public int compareSegments(Size size, Mat lines1, Mat lines2) { return compareSegments_1(nativeObj, size.width, size.height, lines1.nativeObj, lines2.nativeObj); } - @Override - protected void finalize() throws Throwable { - delete(nativeObj); - } + + + + // C++: void cv::LineSegmentDetector::detect(Mat image, Mat& lines, Mat& width = Mat(), Mat& prec = Mat(), Mat& nfa = Mat()) + private static native void detect_0(long nativeObj, long image_nativeObj, long lines_nativeObj, long width_nativeObj, long prec_nativeObj, long nfa_nativeObj); + private static native void detect_1(long nativeObj, long image_nativeObj, long lines_nativeObj, long width_nativeObj, long prec_nativeObj); + private static native void detect_2(long nativeObj, long image_nativeObj, long lines_nativeObj, long width_nativeObj); + private static native void detect_3(long nativeObj, long image_nativeObj, long lines_nativeObj); + + // C++: void cv::LineSegmentDetector::drawSegments(Mat& image, Mat lines) + private static native void drawSegments_0(long nativeObj, long image_nativeObj, long lines_nativeObj); + + // C++: int cv::LineSegmentDetector::compareSegments(Size size, Mat lines1, Mat lines2, Mat& image = Mat()) + private static native int compareSegments_0(long nativeObj, double size_width, double size_height, long lines1_nativeObj, long lines2_nativeObj, long image_nativeObj); + private static native int compareSegments_1(long nativeObj, double size_width, double size_height, long lines1_nativeObj, long lines2_nativeObj); + + // native support for deleting native object + private static native void delete(long nativeObj); } diff --git a/bus-opencv/src/main/java/org/opencv/imgproc/Moments.java b/bus-opencv/src/main/java/org/opencv/imgproc/Moments.java index 337a9ce9ab..5c3d94c78c 100644 --- a/bus-opencv/src/main/java/org/opencv/imgproc/Moments.java +++ b/bus-opencv/src/main/java/org/opencv/imgproc/Moments.java @@ -31,16 +31,17 @@ public class Moments { public double nu03; public Moments( - double m00, - double m10, - double m01, - double m20, - double m11, - double m02, - double m30, - double m21, - double m12, - double m03) { + double m00, + double m10, + double m01, + double m20, + double m11, + double m02, + double m30, + double m21, + double m12, + double m03) + { this.m00 = m00; this.m10 = m10; this.m01 = m01; @@ -106,47 +107,49 @@ public void set(double[] vals) { @Override public String toString() { return "Moments [ " + - "\n" + - "m00=" + m00 + ", " + - "\n" + - "m10=" + m10 + ", " + - "m01=" + m01 + ", " + - "\n" + - "m20=" + m20 + ", " + - "m11=" + m11 + ", " + - "m02=" + m02 + ", " + - "\n" + - "m30=" + m30 + ", " + - "m21=" + m21 + ", " + - "m12=" + m12 + ", " + - "m03=" + m03 + ", " + - "\n" + - "mu20=" + mu20 + ", " + - "mu11=" + mu11 + ", " + - "mu02=" + mu02 + ", " + - "\n" + - "mu30=" + mu30 + ", " + - "mu21=" + mu21 + ", " + - "mu12=" + mu12 + ", " + - "mu03=" + mu03 + ", " + - "\n" + - "nu20=" + nu20 + ", " + - "nu11=" + nu11 + ", " + - "nu02=" + nu02 + ", " + - "\n" + - "nu30=" + nu30 + ", " + - "nu21=" + nu21 + ", " + - "nu12=" + nu12 + ", " + - "nu03=" + nu03 + ", " + - "\n]"; - } - - protected void completeState() { + "\n" + + "m00=" + m00 + ", " + + "\n" + + "m10=" + m10 + ", " + + "m01=" + m01 + ", " + + "\n" + + "m20=" + m20 + ", " + + "m11=" + m11 + ", " + + "m02=" + m02 + ", " + + "\n" + + "m30=" + m30 + ", " + + "m21=" + m21 + ", " + + "m12=" + m12 + ", " + + "m03=" + m03 + ", " + + "\n" + + "mu20=" + mu20 + ", " + + "mu11=" + mu11 + ", " + + "mu02=" + mu02 + ", " + + "\n" + + "mu30=" + mu30 + ", " + + "mu21=" + mu21 + ", " + + "mu12=" + mu12 + ", " + + "mu03=" + mu03 + ", " + + "\n" + + "nu20=" + nu20 + ", " + + "nu11=" + nu11 + ", " + + "nu02=" + nu02 + ", " + + "\n" + + "nu30=" + nu30 + ", " + + "nu21=" + nu21 + ", " + + "nu12=" + nu12 + ", " + + "nu03=" + nu03 + ", " + + "\n]"; + } + + protected void completeState() + { double cx = 0, cy = 0; double mu20, mu11, mu02; double inv_m00 = 0.0; - if (Math.abs(this.m00) > 0.00000001) { + if( Math.abs(this.m00) > 0.00000001 ) + { inv_m00 = 1. / this.m00; cx = this.m10 * inv_m00; cy = this.m01 * inv_m00; @@ -175,207 +178,65 @@ protected void completeState() { double inv_sqrt_m00 = Math.sqrt(Math.abs(inv_m00)); - double s2 = inv_m00 * inv_m00, s3 = s2 * inv_sqrt_m00; - - this.nu20 = this.mu20 * s2; - this.nu11 = this.mu11 * s2; - this.nu02 = this.mu02 * s2; - this.nu30 = this.mu30 * s3; - this.nu21 = this.mu21 * s3; - this.nu12 = this.mu12 * s3; - this.nu03 = this.mu03 * s3; - - } - - public double get_m00() { - return this.m00; - } - - public void set_m00(double m00) { - this.m00 = m00; - } - - public double get_m10() { - return this.m10; - } - - public void set_m10(double m10) { - this.m10 = m10; - } - - public double get_m01() { - return this.m01; - } - - public void set_m01(double m01) { - this.m01 = m01; - } - - public double get_m20() { - return this.m20; - } - - public void set_m20(double m20) { - this.m20 = m20; - } - - public double get_m11() { - return this.m11; - } - - public void set_m11(double m11) { - this.m11 = m11; - } - - public double get_m02() { - return this.m02; - } - - public void set_m02(double m02) { - this.m02 = m02; - } - - public double get_m30() { - return this.m30; - } - - public void set_m30(double m30) { - this.m30 = m30; - } - - public double get_m21() { - return this.m21; - } - - public void set_m21(double m21) { - this.m21 = m21; - } - - public double get_m12() { - return this.m12; - } - - public void set_m12(double m12) { - this.m12 = m12; - } - - public double get_m03() { - return this.m03; - } - - public void set_m03(double m03) { - this.m03 = m03; - } - - public double get_mu20() { - return this.mu20; - } - - public void set_mu20(double mu20) { - this.mu20 = mu20; - } - - public double get_mu11() { - return this.mu11; - } - - public void set_mu11(double mu11) { - this.mu11 = mu11; - } - - public double get_mu02() { - return this.mu02; - } - - public void set_mu02(double mu02) { - this.mu02 = mu02; - } - - public double get_mu30() { - return this.mu30; - } - - public void set_mu30(double mu30) { - this.mu30 = mu30; - } - - public double get_mu21() { - return this.mu21; - } - - public void set_mu21(double mu21) { - this.mu21 = mu21; - } - - public double get_mu12() { - return this.mu12; - } - - public void set_mu12(double mu12) { - this.mu12 = mu12; - } - - public double get_mu03() { - return this.mu03; - } - - public void set_mu03(double mu03) { - this.mu03 = mu03; - } - - public double get_nu20() { - return this.nu20; - } - - public void set_nu20(double nu20) { - this.nu20 = nu20; - } - - public double get_nu11() { - return this.nu11; - } - - public void set_nu11(double nu11) { - this.nu11 = nu11; - } - - public double get_nu02() { - return this.nu02; - } - - public void set_nu02(double nu02) { - this.nu02 = nu02; - } - - public double get_nu30() { - return this.nu30; - } - - public void set_nu30(double nu30) { - this.nu30 = nu30; - } - - public double get_nu21() { - return this.nu21; - } - - public void set_nu21(double nu21) { - this.nu21 = nu21; - } - - public double get_nu12() { - return this.nu12; - } - - public void set_nu12(double nu12) { - this.nu12 = nu12; - } - - public double get_nu03() { - return this.nu03; - } - - public void set_nu03(double nu03) { - this.nu03 = nu03; - } + double s2 = inv_m00*inv_m00, s3 = s2*inv_sqrt_m00; + + this.nu20 = this.mu20*s2; + this.nu11 = this.mu11*s2; + this.nu02 = this.mu02*s2; + this.nu30 = this.mu30*s3; + this.nu21 = this.mu21*s3; + this.nu12 = this.mu12*s3; + this.nu03 = this.mu03*s3; + + } + + public double get_m00() { return this.m00; } + public double get_m10() { return this.m10; } + public double get_m01() { return this.m01; } + public double get_m20() { return this.m20; } + public double get_m11() { return this.m11; } + public double get_m02() { return this.m02; } + public double get_m30() { return this.m30; } + public double get_m21() { return this.m21; } + public double get_m12() { return this.m12; } + public double get_m03() { return this.m03; } + public double get_mu20() { return this.mu20; } + public double get_mu11() { return this.mu11; } + public double get_mu02() { return this.mu02; } + public double get_mu30() { return this.mu30; } + public double get_mu21() { return this.mu21; } + public double get_mu12() { return this.mu12; } + public double get_mu03() { return this.mu03; } + public double get_nu20() { return this.nu20; } + public double get_nu11() { return this.nu11; } + public double get_nu02() { return this.nu02; } + public double get_nu30() { return this.nu30; } + public double get_nu21() { return this.nu21; } + public double get_nu12() { return this.nu12; } + public double get_nu03() { return this.nu03; } + + public void set_m00(double m00) { this.m00 = m00; } + public void set_m10(double m10) { this.m10 = m10; } + public void set_m01(double m01) { this.m01 = m01; } + public void set_m20(double m20) { this.m20 = m20; } + public void set_m11(double m11) { this.m11 = m11; } + public void set_m02(double m02) { this.m02 = m02; } + public void set_m30(double m30) { this.m30 = m30; } + public void set_m21(double m21) { this.m21 = m21; } + public void set_m12(double m12) { this.m12 = m12; } + public void set_m03(double m03) { this.m03 = m03; } + public void set_mu20(double mu20) { this.mu20 = mu20; } + public void set_mu11(double mu11) { this.mu11 = mu11; } + public void set_mu02(double mu02) { this.mu02 = mu02; } + public void set_mu30(double mu30) { this.mu30 = mu30; } + public void set_mu21(double mu21) { this.mu21 = mu21; } + public void set_mu12(double mu12) { this.mu12 = mu12; } + public void set_mu03(double mu03) { this.mu03 = mu03; } + public void set_nu20(double nu20) { this.nu20 = nu20; } + public void set_nu11(double nu11) { this.nu11 = nu11; } + public void set_nu02(double nu02) { this.nu02 = nu02; } + public void set_nu30(double nu30) { this.nu30 = nu30; } + public void set_nu21(double nu21) { this.nu21 = nu21; } + public void set_nu12(double nu12) { this.nu12 = nu12; } + public void set_nu03(double nu03) { this.nu03 = nu03; } } diff --git a/bus-opencv/src/main/java/org/opencv/imgproc/Subdiv2D.java b/bus-opencv/src/main/java/org/opencv/imgproc/Subdiv2D.java index c5cfaaca0d..e291c461c7 100644 --- a/bus-opencv/src/main/java/org/opencv/imgproc/Subdiv2D.java +++ b/bus-opencv/src/main/java/org/opencv/imgproc/Subdiv2D.java @@ -12,6 +12,18 @@ public class Subdiv2D { + protected final long nativeObj; + protected Subdiv2D(long addr) { + nativeObj = addr; + long nativeObjCopy = nativeObj; + org.opencv.core.Mat.cleaner.register(this, () -> delete(nativeObjCopy)); + } + + public long getNativeObjAddr() { return nativeObj; } + + // internal usage only + public static Subdiv2D __fromPtr__(long addr) { return new Subdiv2D(addr); } + // C++: enum public static final int PTLOC_ERROR = -2, @@ -27,40 +39,20 @@ public class Subdiv2D { NEXT_AROUND_RIGHT = 0x31, PREV_AROUND_LEFT = 0x20, PREV_AROUND_RIGHT = 0x02; - protected final long nativeObj; - protected Subdiv2D(long addr) { - nativeObj = addr; - } + // + // C++: cv::Subdiv2D::Subdiv2D() + // /** * creates an empty Subdiv2D object. - * To create a new empty Delaunay subdivision you need to use the #initDelaunay function. + * To create a new empty Delaunay subdivision you need to use the #initDelaunay function. */ public Subdiv2D() { - this(Subdiv2D_0()); - } - - /** - * @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. - *

    - * The function creates an empty Delaunay subdivision where 2D points can be added using the function - * insert() . All of the points to be added must be within the specified rectangle, otherwise a runtime - * error is raised. - */ - public Subdiv2D(Rect rect) { - this(Subdiv2D_1(rect.x, rect.y, rect.width, rect.height)); - } - - - // - // C++: cv::Subdiv2D::Subdiv2D() - // - - // internal usage only - public static Subdiv2D __fromPtr__(long addr) { - return new Subdiv2D(addr); + nativeObj = Subdiv2D_0(); + long nativeObjCopy = nativeObj; + org.opencv.core.Mat.cleaner.register(this, () -> delete(nativeObjCopy)); } @@ -68,202 +60,89 @@ public static Subdiv2D __fromPtr__(long addr) { // C++: cv::Subdiv2D::Subdiv2D(Rect rect) // - // C++: cv::Subdiv2D::Subdiv2D() - private static native long Subdiv2D_0(); - - - // - // C++: void cv::Subdiv2D::initDelaunay(Rect rect) - // - - // C++: cv::Subdiv2D::Subdiv2D(Rect rect) - private static native long Subdiv2D_1(int rect_x, int rect_y, int rect_width, int rect_height); + /** + * + * + * @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. + * + * The function creates an empty Delaunay subdivision where 2D points can be added using the function + * insert() . All of the points to be added must be within the specified rectangle, otherwise a runtime + * error is raised. + */ + public Subdiv2D(Rect rect) { + nativeObj = Subdiv2D_1(rect.x, rect.y, rect.width, rect.height); + long nativeObjCopy = nativeObj; + org.opencv.core.Mat.cleaner.register(this, () -> delete(nativeObjCopy)); + } // - // C++: int cv::Subdiv2D::insert(Point2f pt) - // - // C++: void cv::Subdiv2D::initDelaunay(Rect rect) - private static native void initDelaunay_0(long nativeObj, int rect_x, int rect_y, int rect_width, int rect_height); - - - // - // C++: void cv::Subdiv2D::insert(vector_Point2f ptvec) - // - - // C++: int cv::Subdiv2D::insert(Point2f pt) - private static native int insert_0(long nativeObj, double pt_x, double pt_y); - - - // - // C++: int cv::Subdiv2D::locate(Point2f pt, int& edge, int& vertex) - // - - // C++: void cv::Subdiv2D::insert(vector_Point2f ptvec) - private static native void insert_1(long nativeObj, long ptvec_mat_nativeObj); - - - // - // C++: int cv::Subdiv2D::findNearest(Point2f pt, Point2f* nearestPt = 0) - // - - // C++: int cv::Subdiv2D::locate(Point2f pt, int& edge, int& vertex) - private static native int locate_0(long nativeObj, double pt_x, double pt_y, double[] edge_out, double[] vertex_out); - - // C++: int cv::Subdiv2D::findNearest(Point2f pt, Point2f* nearestPt = 0) - private static native int findNearest_0(long nativeObj, double pt_x, double pt_y, double[] nearestPt_out); - - - // - // C++: void cv::Subdiv2D::getEdgeList(vector_Vec4f& edgeList) - // - - private static native int findNearest_1(long nativeObj, double pt_x, double pt_y); - - - // - // C++: void cv::Subdiv2D::getLeadingEdgeList(vector_int& leadingEdgeList) - // - - // C++: void cv::Subdiv2D::getEdgeList(vector_Vec4f& edgeList) - private static native void getEdgeList_0(long nativeObj, long edgeList_mat_nativeObj); - - - // - // C++: void cv::Subdiv2D::getTriangleList(vector_Vec6f& triangleList) - // - - // C++: void cv::Subdiv2D::getLeadingEdgeList(vector_int& leadingEdgeList) - private static native void getLeadingEdgeList_0(long nativeObj, long leadingEdgeList_mat_nativeObj); - - - // - // C++: void cv::Subdiv2D::getVoronoiFacetList(vector_int idx, vector_vector_Point2f& facetList, vector_Point2f& facetCenters) - // - - // C++: void cv::Subdiv2D::getTriangleList(vector_Vec6f& triangleList) - private static native void getTriangleList_0(long nativeObj, long triangleList_mat_nativeObj); - - - // - // C++: Point2f cv::Subdiv2D::getVertex(int vertex, int* firstEdge = 0) - // - - // C++: void cv::Subdiv2D::getVoronoiFacetList(vector_int idx, vector_vector_Point2f& facetList, vector_Point2f& facetCenters) - private static native void getVoronoiFacetList_0(long nativeObj, long idx_mat_nativeObj, long facetList_mat_nativeObj, long facetCenters_mat_nativeObj); - - // C++: Point2f cv::Subdiv2D::getVertex(int vertex, int* firstEdge = 0) - private static native double[] getVertex_0(long nativeObj, int vertex, double[] firstEdge_out); - - - // - // C++: int cv::Subdiv2D::getEdge(int edge, int nextEdgeType) - // - - private static native double[] getVertex_1(long nativeObj, int vertex); - - - // - // C++: int cv::Subdiv2D::nextEdge(int edge) - // - - // C++: int cv::Subdiv2D::getEdge(int edge, int nextEdgeType) - private static native int getEdge_0(long nativeObj, int edge, int nextEdgeType); - - - // - // C++: int cv::Subdiv2D::rotateEdge(int edge, int rotate) // - // C++: int cv::Subdiv2D::nextEdge(int edge) - private static native int nextEdge_0(long nativeObj, int edge); - - - // - // C++: int cv::Subdiv2D::symEdge(int edge) - // - - // C++: int cv::Subdiv2D::rotateEdge(int edge, int rotate) - private static native int rotateEdge_0(long nativeObj, int edge, int rotate); - - - // - // C++: int cv::Subdiv2D::edgeOrg(int edge, Point2f* orgpt = 0) - // - - // C++: int cv::Subdiv2D::symEdge(int edge) - private static native int symEdge_0(long nativeObj, int edge); - - // C++: int cv::Subdiv2D::edgeOrg(int edge, Point2f* orgpt = 0) - private static native int edgeOrg_0(long nativeObj, int edge, double[] orgpt_out); - - - // - // C++: int cv::Subdiv2D::edgeDst(int edge, Point2f* dstpt = 0) - // - - private static native int edgeOrg_1(long nativeObj, int edge); - - // C++: int cv::Subdiv2D::edgeDst(int edge, Point2f* dstpt = 0) - private static native int edgeDst_0(long nativeObj, int edge, double[] dstpt_out); - - private static native int edgeDst_1(long nativeObj, int edge); - - // native support for deleting native object - private static native void delete(long nativeObj); - - public long getNativeObjAddr() { - return nativeObj; - } - /** * Creates a new empty Delaunay subdivision * - * @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. + * @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. */ public void initDelaunay(Rect rect) { initDelaunay_0(nativeObj, rect.x, rect.y, rect.width, rect.height); } + + // + // C++: int cv::Subdiv2D::insert(Point2f pt) + // + /** * Insert a single point into a Delaunay triangulation. * - * @param pt Point to insert. - *

    - * The function inserts a single point into a subdivision and modifies the subdivision topology - * appropriately. If a point with the same coordinates exists already, no new point is added. - * @return the ID of the point. + * @param pt Point to insert. + * + * The function inserts a single point into a subdivision and modifies the subdivision topology + * appropriately. If a point with the same coordinates exists already, no new point is added. + * @return the ID of the point. * - * Note: If the point is outside of the triangulation specified rect a runtime error is raised. + * Note: If the point is outside of the triangulation specified rect a runtime error is raised. */ public int insert(Point pt) { return insert_0(nativeObj, pt.x, pt.y); } + + // + // C++: void cv::Subdiv2D::insert(vector_Point2f ptvec) + // + /** * Insert multiple points into a Delaunay triangulation. * - * @param ptvec Points to insert. - *

    - * The function inserts a vector of points into a subdivision and modifies the subdivision topology - * appropriately. + * @param ptvec Points to insert. + * + * The function inserts a vector of points into a subdivision and modifies the subdivision topology + * appropriately. */ public void insert(MatOfPoint2f ptvec) { Mat ptvec_mat = ptvec; insert_1(nativeObj, ptvec_mat.nativeObj); } + + // + // C++: int cv::Subdiv2D::locate(Point2f pt, int& edge, int& vertex) + // + /** * Returns the location of a point within a Delaunay triangulation. * - * @param pt Point to locate. - * @param edge Output edge that the point belongs to or is located to the right of it. - * @param vertex Optional output vertex the input point coincides with. - *

    - * The function locates the input point within the subdivision and gives one of the triangle edges - * or vertices. - * @return an integer which specify one of the following five cases for point location: + * @param pt Point to locate. + * @param edge Output edge that the point belongs to or is located to the right of it. + * @param vertex Optional output vertex the input point coincides with. + * + * The function locates the input point within the subdivision and gives one of the triangle edges + * or vertices. + * + * @return an integer which specify one of the following five cases for point location: *