diff --git a/LICENSE b/LICENSE index 50fa418..a9ee15f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright © 2020 xrv +Copyright © 2021 xrv 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/SECURITY.md b/SECURITY.md deleted file mode 100644 index 034e848..0000000 --- a/SECURITY.md +++ /dev/null @@ -1,21 +0,0 @@ -# Security Policy - -## Supported Versions - -Use this section to tell people about which versions of your project are -currently being supported with security updates. - -| Version | Supported | -| ------- | ------------------ | -| 5.1.x | :white_check_mark: | -| 5.0.x | :x: | -| 4.0.x | :white_check_mark: | -| < 4.0 | :x: | - -## Reporting a Vulnerability - -Use this section to tell people how to report a vulnerability. - -Tell them where to go, how often they can expect to get an update on a -reported vulnerability, what to expect if the vulnerability is accepted or -declined, etc. diff --git a/budd-common/pom.xml b/budd-common/pom.xml new file mode 100644 index 0000000..59b809c --- /dev/null +++ b/budd-common/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + + io.github.ehlxr + budd + 0.0.1-SNAPSHOT + + + budd-common + budd-common + + + + org.apache.commons + commons-lang3 + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + com.fasterxml.jackson.core + jackson-annotations + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.squareup.okhttp3 + okhttp + + + + com.google.guava + guava + + + diff --git a/src/main/java/io/github/ehlxr/annotation/PkgAnnotation.java b/budd-common/src/main/java/io/github/ehlxr/annotations/NoRequestLog.java similarity index 87% rename from src/main/java/io/github/ehlxr/annotation/PkgAnnotation.java rename to budd-common/src/main/java/io/github/ehlxr/annotations/NoRequestLog.java index f1c1c96..4215b1b 100644 --- a/src/main/java/io/github/ehlxr/annotation/PkgAnnotation.java +++ b/budd-common/src/main/java/io/github/ehlxr/annotations/NoRequestLog.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2020 xrv + * Copyright © 2021 xrv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -22,10 +22,7 @@ * THE SOFTWARE. */ -/** - * - */ -package io.github.ehlxr.annotation; +package io.github.ehlxr.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -33,11 +30,12 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * @author ehlxr + * 请求日志排除注解 * + * @author ehlxr + * @since 2021-08-18 14:03. */ -@Target(ElementType.PACKAGE) @Retention(RetentionPolicy.RUNTIME) -@interface PkgAnnotation { - +@Target(ElementType.METHOD) +public @interface NoRequestLog { } diff --git a/src/main/java/io/github/ehlxr/jvm/stack/ReturnAddressTest.java b/budd-common/src/main/java/io/github/ehlxr/common/Constant.java similarity index 77% rename from src/main/java/io/github/ehlxr/jvm/stack/ReturnAddressTest.java rename to budd-common/src/main/java/io/github/ehlxr/common/Constant.java index 85920c4..9991e7e 100644 --- a/src/main/java/io/github/ehlxr/jvm/stack/ReturnAddressTest.java +++ b/budd-common/src/main/java/io/github/ehlxr/common/Constant.java @@ -22,26 +22,26 @@ * THE SOFTWARE. */ -package io.github.ehlxr.jvm.stack; +package io.github.ehlxr.common; /** + * 常量 + * * @author ehlxr - * @since 2021-07-11 15:19. + * @since 2021-08-29 18:32. */ -public class ReturnAddressTest { +public interface Constant { + /** + * traceID + */ + String LOG_TRACE_ID = "logTraceId"; - public void methodA() { - int k = 10; - int l = 20; + /** + * 接口请求开始时间戳 + */ + String REQUEST_START_TIME = "request_start_time"; - methodB(); - } - - public void methodB() { - int i = 10; - int j = 20; - - int a = i + j; - } + int SUCCESS_CODE = 0; + String SUCCESS_MSG = "success"; } diff --git a/src/main/java/io/github/ehlxr/utils/Result.java b/budd-common/src/main/java/io/github/ehlxr/common/Result.java similarity index 65% rename from src/main/java/io/github/ehlxr/utils/Result.java rename to budd-common/src/main/java/io/github/ehlxr/common/Result.java index 1d555e6..126889e 100644 --- a/src/main/java/io/github/ehlxr/utils/Result.java +++ b/budd-common/src/main/java/io/github/ehlxr/common/Result.java @@ -1,28 +1,4 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; +package io.github.ehlxr.common; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; @@ -30,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.base.Strings; import com.google.common.base.Throwables; +import io.github.ehlxr.enums.CodeEnum; import java.io.Serializable; import java.text.SimpleDateFormat; @@ -38,7 +15,7 @@ import java.util.Objects; /** * 统一输出结果集 * - * @author ehlxr + * @author lixiangrong * @since 2020/3/18. */ @JsonInclude(JsonInclude.Include.NON_NULL) @@ -67,7 +44,7 @@ public class Result implements Serializable { } public static Result success(T data, String message) { - return new Result<>(Code.SUCCESSFUL.getCode(), data, message); + return new Result<>(CodeEnum.SUCCESSFUL.getCode(), data, message); } public static Result success(T data) { @@ -82,35 +59,35 @@ public class Result implements Serializable { return new Result<>(c, d, m); } - public static Result of(Code c, T d, String m) { + public static Result of(CodeEnum c, T d, String m) { return new Result<>(c.getCode(), d, m); } - public static Result fail(Code code, String message) { - return of(code.getCode(), null, message); + public static Result fail(CodeEnum codeEnum, String message) { + return of(codeEnum.getCode(), null, message); } - public static Result fail(Code code) { - return fail(code, code.getMessage()); + public static Result fail(CodeEnum codeEnum) { + return fail(codeEnum, codeEnum.getMessage()); } public static Result fail(Throwable e) { // 格式化异常消息,防止输出异常栈信息到结果集 e = Throwables.getRootCause(e); - return of(Code.UNKNOWN_EXCEPTION.getCode(), null, String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage())); + return of(CodeEnum.UNKNOWN_EXCEPTION.getCode(), null, String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage())); } public String getMessage() { // return Strings.isNullOrEmpty(m) ? c.getMessage() : m; if (Strings.isNullOrEmpty(message)) { - Code code; + CodeEnum codeEnum; try { - code = Code.code(this.code); + codeEnum = CodeEnum.code(this.code); } catch (Exception e) { return message; } - return Objects.isNull(code) ? "" : code.getMessage(); + return Objects.isNull(codeEnum) ? "" : codeEnum.getMessage(); } return message; } diff --git a/budd-common/src/main/java/io/github/ehlxr/config/RedisTemplateConfig.java b/budd-common/src/main/java/io/github/ehlxr/config/RedisTemplateConfig.java new file mode 100644 index 0000000..c3bf66a --- /dev/null +++ b/budd-common/src/main/java/io/github/ehlxr/config/RedisTemplateConfig.java @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021 xrv + * + * 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 io.github.ehlxr.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/** + * @author ehlxr + * @since 2021-08-29 18:32. + */ +@Configuration +public class RedisTemplateConfig { + @Bean(name = "redisTemplate") + public RedisTemplate getRedisTemplate(RedisConnectionFactory factory) { + return buildRedisTemplateByString(factory); + } + + /** + * 构建 redisTemplate 使用 string序列化 + */ + public RedisTemplate buildRedisTemplateByString(RedisConnectionFactory factory) { + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setConnectionFactory(factory); + redisTemplate.setKeySerializer(new StringRedisSerializer()); + redisTemplate.setValueSerializer(new StringRedisSerializer()); + redisTemplate.setHashKeySerializer(new StringRedisSerializer()); + redisTemplate.setHashValueSerializer(new StringRedisSerializer()); + return redisTemplate; + } +} diff --git a/budd-common/src/main/java/io/github/ehlxr/enums/CodeEnum.java b/budd-common/src/main/java/io/github/ehlxr/enums/CodeEnum.java new file mode 100644 index 0000000..5b5a7dc --- /dev/null +++ b/budd-common/src/main/java/io/github/ehlxr/enums/CodeEnum.java @@ -0,0 +1,195 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021 xrv + * + * 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 io.github.ehlxr.enums; + +/** + * 自定义状态码 + * + * @author lixiangrong + * @since 2020/3/18. + */ +public enum CodeEnum { + /** + * 成功 + */ + SUCCESSFUL(200, "success"), + + LOGIN_TYPE_ERROR(201, "登录类型错误"), + + /** + * 用户不存在 + */ + USER_NOT_EXIST(202, "用户不存在"), + + /** + * 医生状态修改失败 + */ + DOCTOR_STATUS_FAILURE(204,"医生状态修改失败"), + + /** + * 医生状态不正常 + */ + DOCTOR_STATUS_NOT_NORMAL(205,"医生状态不正常"), + + DOCTOR_ID_EMPTY(206,"医生不允许为空"), + + DEVICE_LOGIN_NULL(209, "设备尚未登录"), + + /** + * 成功 + */ + UC_CONNECT_ERROR(211, "用户中心异常,请联系管理员"), + + UC_NOT_PHRID(212,"用户中心异常,未返回用户ID"), + + /** + * 诊断记录不存在 + */ + RAINQUIRY_NOT_EXIST(301, "诊断记录不存在"), + + /** + * 成功 + */ + LOGIN_TYPE_NULL(700, "登录方式不能为空"), + + /** + * 成功 + */ + MOBILE_NULL(701, "手机号码不能为空"), + + /** + * 成功 + */ + VCODE_ERROR(702, "验证码错误"), + + MOBILE_HAVE(703, "此手机号已经注册过"), + + /** + * 成功 + */ + VCODE_NULL_ERROR(704, "验证码不能为空"), + /** + * 成功 + */ + GENDER_RELATION_ERROR(705, "性别和关系错误"), + + ID_CARD_NO_ERROR(706, "身份证号不能为空"), + + HEAD_IMG_ERROR(707, "人脸识别照片不能为空"), + + DEVICE_CODE_ERROR(708, "设备号不能为空"), + + /** + * 未知异常 + */ + UNKNOWN_EXCEPTION(600, "unknown server exception"), + + /** + * 请求参数不能为空 + */ + REQUEST_PARAM_NULL_EXCEPTION(601, "required param should not be null"), + + /** + * 业务异常 + */ + SERVICE_EXCEPTION(602, "service exception"), + + /** + * 上善(三疗)的token没有获取到 + */ + NO_SANLIAO_TOKEN(801, "上善(三疗)的Token没有"), + + /** + * No report generated + */ + NO_REPORT_GENERATED(603, "no report generated"), + + NO_MATCH_DOCTOR(604,"没有空闲医生"), + + NO_MATCH_DATA(604,"没有查询到数据"), + + /** + * 未选择全部检查项 + */ + SELECT_EXAM_WRAN(2001, "未选择全部检查项"), + + /** + * 创建订单失败 + */ + CREATE_ORDER_FAIL(2002,"创建订单失败"), + + PENDING_ORDER_ERROR(2003,"抢单失败"), + + INVALID_ORDER_ERROR(2004,"无效订单"), + + INVALID_SHOP_ROLE_ERROR(2005,"当前用户无商铺管理员角色"), + + DUPLICATE_VOUCHING_ORDER_ERROR(2006,"您已审核过此订单"), + + GET_ORDER_ERROR(2007,"获取订单信息失败"), + + GET_SHOP_ROLE_ERROR(2008,"获取商铺角色失败"); + + private final int code; + private final String message; + + CodeEnum(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public String getCodeString() { + return code + ""; + } + + public String getMessage() { + return message; + } + + @Override + public String toString() { + return "Code{" + + "code=" + code + + ", message='" + message + '\'' + + '}'; + } + + private static final CodeEnum[] CODE_ENUMS = CodeEnum.values(); + + public static CodeEnum code(int code) { + for (CodeEnum c : CODE_ENUMS) { + if (code == c.getCode()) { + return c; + } + } + return null; + } + +} + diff --git a/src/main/java/io/github/ehlxr/utils/FormType.java b/budd-common/src/main/java/io/github/ehlxr/enums/FormType.java similarity index 94% rename from src/main/java/io/github/ehlxr/utils/FormType.java rename to budd-common/src/main/java/io/github/ehlxr/enums/FormType.java index 265da99..fbca84a 100644 --- a/src/main/java/io/github/ehlxr/utils/FormType.java +++ b/budd-common/src/main/java/io/github/ehlxr/enums/FormType.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2020 xrv + * Copyright © 2021 xrv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package io.github.ehlxr.utils; +package io.github.ehlxr.enums; /** * FORM 表单提交类型 diff --git a/src/main/java/io/github/ehlxr/utils/HttpContentType.java b/budd-common/src/main/java/io/github/ehlxr/enums/HttpContentType.java similarity index 95% rename from src/main/java/io/github/ehlxr/utils/HttpContentType.java rename to budd-common/src/main/java/io/github/ehlxr/enums/HttpContentType.java index 6172fdb..3c9bb33 100644 --- a/src/main/java/io/github/ehlxr/utils/HttpContentType.java +++ b/budd-common/src/main/java/io/github/ehlxr/enums/HttpContentType.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2020 xrv + * Copyright © 2021 xrv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package io.github.ehlxr.utils; +package io.github.ehlxr.enums; /** * @author ehlxr diff --git a/src/main/java/io/github/ehlxr/ClassLoaderTest.java b/budd-common/src/main/java/io/github/ehlxr/exception/JsonParseException.java similarity index 68% rename from src/main/java/io/github/ehlxr/ClassLoaderTest.java rename to budd-common/src/main/java/io/github/ehlxr/exception/JsonParseException.java index 36a82ec..2375083 100644 --- a/src/main/java/io/github/ehlxr/ClassLoaderTest.java +++ b/budd-common/src/main/java/io/github/ehlxr/exception/JsonParseException.java @@ -22,14 +22,30 @@ * THE SOFTWARE. */ -package io.github.ehlxr; +package io.github.ehlxr.exception; /** * @author ehlxr - * @since 2021-07-07 22:54. + * @since 2020-05-06. */ -public class ClassLoaderTest { - public static void main(String[] args) { - System.out.println(ClassLoader.getSystemClassLoader()); +public class JsonParseException extends RuntimeException { + private static final long serialVersionUID = -2626765995683345473L; + + public JsonParseException(String msg) { + super(msg); + } + + public JsonParseException(String msg, Throwable e) { + super(msg, e); + } + + public JsonParseException(Throwable e) { + super(e); + } + + @Override + public synchronized Throwable fillInStackTrace() { + // 不拷贝栈信息 + return null; } } diff --git a/src/main/java/io/github/ehlxr/singleton/SingleTonStaticInnerClass.java b/budd-common/src/main/java/io/github/ehlxr/exception/ServiceDataException.java similarity index 62% rename from src/main/java/io/github/ehlxr/singleton/SingleTonStaticInnerClass.java rename to budd-common/src/main/java/io/github/ehlxr/exception/ServiceDataException.java index 8d2b049..518db35 100644 --- a/src/main/java/io/github/ehlxr/singleton/SingleTonStaticInnerClass.java +++ b/budd-common/src/main/java/io/github/ehlxr/exception/ServiceDataException.java @@ -22,28 +22,46 @@ * THE SOFTWARE. */ -package io.github.ehlxr.singleton; +package io.github.ehlxr.exception; -import java.util.stream.IntStream; +import io.github.ehlxr.enums.CodeEnum; /** * @author ehlxr - * @since 2021-02-18 11:23. + * @since 2021-08-29 19:18. */ -public class SingleTonStaticInnerClass { - private SingleTonStaticInnerClass() { +public class ServiceDataException extends RuntimeException { + /** + * 错误码 + */ + private int code; + /** + * 异常信息 + */ + private String msg; + + public int getCode() { + return code; } - private static class HandlerInstance { - private static SingleTonStaticInnerClass instance = new SingleTonStaticInnerClass(); + + public String getMsg() { + return msg; } - public static SingleTonStaticInnerClass getInstance() { - return HandlerInstance.instance; + + public ServiceDataException(Throwable throwable) { + super(throwable); } - public static void main(String[] args) { - IntStream.range(0, 5).parallel().forEach(i -> System.out.println(Thread.currentThread().getName() + " => " + SingleTonStaticInnerClass.getInstance())); + public ServiceDataException(CodeEnum codeEnum) { + this.code = codeEnum.getCode(); + this.msg = codeEnum.getMessage(); } -} \ No newline at end of file + public ServiceDataException(int code, String msg) { + super(msg); + this.code = code; + this.msg = msg; + } +} diff --git a/budd-common/src/main/java/io/github/ehlxr/util/DateUtil.java b/budd-common/src/main/java/io/github/ehlxr/util/DateUtil.java new file mode 100644 index 0000000..973e012 --- /dev/null +++ b/budd-common/src/main/java/io/github/ehlxr/util/DateUtil.java @@ -0,0 +1,323 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021 xrv + * + * 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 io.github.ehlxr.util; + +import org.apache.commons.lang3.tuple.ImmutablePair; + +import java.time.*; +import java.time.chrono.ChronoLocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAdjusters; +import java.util.Collections; +import java.util.Date; +import java.util.Map; +import java.util.WeakHashMap; + +/** + * 日期操作 + * + * @author ehlxr + * @since 2021-08-29 18:32. + */ +public class DateUtil { + public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; + public static final String YYYY_MM_DD = "yyyy-MM-dd"; + public static final String MM_DD = "MM-dd"; + public static final String HH_MM_SS = "HH:mm:ss"; + + // private static final DateTimeFormatter DEFAULT_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS); + // private static final DateTimeFormatter DEFAULT_DATE_FORMATTER = DateTimeFormatter.ofPattern(YYYY_MM_DD); + // private static final DateTimeFormatter DEFAULT_DATE_NO_YEAR_FORMATTER = DateTimeFormatter.ofPattern(MM_DD); + // private static final DateTimeFormatter DEFAULT_TIME_FORMATTER = DateTimeFormatter.ofPattern(HH_MM_SS); + private static final Map PATTEN_FORMATTER_MAPPER = Collections.synchronizedMap(new WeakHashMap<>()); + + // static { + // PATTEN_FORMATTER_MAPPER.put(YYYY_MM_DD_HH_MM_SS, DEFAULT_DATE_TIME_FORMATTER); + // PATTEN_FORMATTER_MAPPER.put(YYYY_MM_DD, DEFAULT_DATE_FORMATTER); + // PATTEN_FORMATTER_MAPPER.put(MM_DD, DEFAULT_DATE_NO_YEAR_FORMATTER); + // PATTEN_FORMATTER_MAPPER.put(HH_MM_SS, DEFAULT_TIME_FORMATTER); + // } + + private static DateTimeFormatter cacheFormatterAndGet(String patten) { + DateTimeFormatter dateTimeFormatter = PATTEN_FORMATTER_MAPPER.get(patten); + if (dateTimeFormatter == null) { + dateTimeFormatter = DateTimeFormatter.ofPattern(patten).withZone(ZoneId.of("+8")); + PATTEN_FORMATTER_MAPPER.put(patten, dateTimeFormatter); + } + return dateTimeFormatter; + } + + /** + * @param localDateTime date time + * @return yyyy-MM-dd HH:mm:ss + */ + public static String formatLocalDateTime(LocalDateTime localDateTime) { + return localDateTime.format(cacheFormatterAndGet(YYYY_MM_DD_HH_MM_SS)); + } + + /** + * @param localDateTime time + * @param patten yyyy-MM-dd HH:mm:ss + * @return yyyy-MM-dd HH:mm:ss + */ + public static String formatLocalDateTime(LocalDateTime localDateTime, String patten) { + DateTimeFormatter dateTimeFormatter = cacheFormatterAndGet(patten); + return localDateTime.format(dateTimeFormatter); + } + + /** + * @param localDate date + * @param patten only date patten + * @return yyyy-MM-dd + */ + public static String formatLocalDate(LocalDate localDate, String patten) { + DateTimeFormatter dateTimeFormatter = cacheFormatterAndGet(patten); + return localDate.format(dateTimeFormatter); + } + + /** + * @param localDate localDate + * @return yyyy-MM-dd + */ + public static String formatLocalDate(LocalDate localDate) { + return localDate.format(cacheFormatterAndGet(YYYY_MM_DD)); + } + + /** + * @param localTime localTime + * @param patten patten + * @return HH:mm:ss + */ + public static String formatLocalTime(LocalTime localTime, String patten) { + DateTimeFormatter dateTimeFormatter = cacheFormatterAndGet(patten); + return localTime.format(dateTimeFormatter); + } + + /** + * @param localTime localTime + * @return HH:mm:ss + */ + public static String formatLocalTime(LocalTime localTime) { + return localTime.format(cacheFormatterAndGet(HH_MM_SS)); + } + + /** + * @param date date time + * @param patten patten + * @return yyyy-MM-dd HH:mm:ss + */ + public static String format(Date date, String patten) { + Instant instant = date.toInstant(); + LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("+8")); + return localDateTime.format(cacheFormatterAndGet(patten)); + } + + /** + * @param date date + * @return yyyy-MM-dd HH:mm:ss + */ + public static String format(Date date) { + return format(date, YYYY_MM_DD_HH_MM_SS); + } + + /** + * @param date date + * @return yyyy-MM-dd + */ + public static String formatDate(Date date) { + return format(date, YYYY_MM_DD); + } + + /** + * @param date date + * @return HH:mm:ss + */ + public static String formatTime(Date date) { + return format(date, HH_MM_SS); + } + + /** + * @param mills mills + * @return yyyy-MM-dd HH:mm:ss + */ + public static String formatMills(long mills, String patten) { + Instant instant = Instant.ofEpochMilli(mills); + LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("+8")); + return formatLocalDateTime(localDateTime, patten); + } + + /** + * @param mills mills + * @return yyyy-MM-dd HH:mm:ss + */ + public static String formatMills(long mills) { + return formatMills(mills, YYYY_MM_DD_HH_MM_SS); + } + + /** + * @param mills mills + * @return yyyy-MM-dd + */ + public static String formatMillsDate(long mills) { + return formatMills(mills, YYYY_MM_DD); + } + + /** + * @param date date + * @return HH:mm:ss + */ + public static String formatMillsTime(long date) { + return formatMills(date, HH_MM_SS); + } + + /** + * @param date yyyy-MM-dd HH:mm:ss + * @return Date + */ + public static Date parse(String date) { + LocalDateTime localDateTime = parseToLocalDateTime(date); + Instant instant = localDateTime.toInstant(OffsetDateTime.now().getOffset()); + return Date.from(instant); + } + + /** + * @param date string date + * @param patten formatter patten + * @return LocalDateTime + */ + public static LocalDateTime parseToLocalDateTime(String date, String patten) { + return LocalDateTime.parse(date, DateTimeFormatter.ofPattern(patten)); + } + + /** + * @param date yyyy-MM-dd HH:mm:ss + * @return LocalDateTime + */ + public static LocalDateTime parseToLocalDateTime(String date) { + return LocalDateTime.parse(date, cacheFormatterAndGet(YYYY_MM_DD_HH_MM_SS)); + } + + /** + * @param date yyyy-MM-dd HH:mm:ss + * @return milliseconds + */ + public static Long parseToMillis(String date) { + return parseToMillis(date, YYYY_MM_DD_HH_MM_SS); + } + + /** + * @param date string date + * @param patten formatter patten + * @return milliseconds + */ + public static Long parseToMillis(String date, String patten) { + return toInstant(LocalDateTime.parse(date, cacheFormatterAndGet(patten))).toEpochMilli(); + } + + /** + * @param date yyyy-MM-dd + * @return LocalDate + */ + public static LocalDate parseToLocalDate(String date) { + return LocalDate.parse(date, cacheFormatterAndGet(YYYY_MM_DD)); + } + + /** + * @param date HH:mm:ss + * @return LocalTime + */ + public static LocalTime parseToLocalTime(String date) { + return LocalTime.parse(date, cacheFormatterAndGet(HH_MM_SS)); + } + + /** + * @param dayStart date + * @param dayEnd date + */ + public static Period betweenDays(Date dayStart, Date dayEnd) { + LocalDateTime localDateTimeStart = LocalDateTime.ofInstant(dayStart.toInstant(), OffsetDateTime.now().getOffset()); + LocalDateTime localDateTimeEnd = LocalDateTime.ofInstant(dayEnd.toInstant(), OffsetDateTime.now().getOffset()); + return Period.between(localDateTimeStart.toLocalDate(), localDateTimeEnd.toLocalDate()); + } + + /** + * @param dayStart date + * @param dayEnd date + */ + public static Duration betweenTimes(Date dayStart, Date dayEnd) { + LocalDateTime localDateTimeStart = LocalDateTime.ofInstant(dayStart.toInstant(), OffsetDateTime.now().getOffset()); + LocalDateTime localDateTimeEnd = LocalDateTime.ofInstant(dayEnd.toInstant(), OffsetDateTime.now().getOffset()); + return Duration.between(localDateTimeStart, localDateTimeEnd); + } + + /** + * @param dayStart date + * @param dayEnd date + */ + public static Period betweenDays(String dayStart, String dayEnd) { + return Period.between(parseToLocalDate(dayStart), parseToLocalDate(dayEnd)); + } + + /** + * @param dayStart date + * @param dayEnd date + */ + public static Duration betweenTimes(String dayStart, String dayEnd) { + return Duration.between(parseToLocalDateTime(dayStart), parseToLocalDateTime(dayEnd)); + } + + /** + * 每月开始、结束毫秒时间戳 + */ + public static ImmutablePair firstAndLastMillisOfMonth() { + LocalDate today = LocalDate.now(); + Long firstDay = toInstant(LocalDateTime.of(today.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN)).toEpochMilli(); + Long lastDay = toInstant(LocalDateTime.of(today.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX)).toEpochMilli(); + return ImmutablePair.of(firstDay, lastDay); + } + + public static Instant toInstant(ChronoLocalDateTime d) { + return d.toInstant(ZoneOffset.of("+8")); + } + + /** + * 当前秒级别时间戳 + * + * @return 10 位时间戳 + */ + public static Long currentTimeSecond() { + return toInstant(LocalDateTime.now()).getEpochSecond(); + } + + /** + * 之前的多少天 + * + * @param days 之前的天数 + * @return yyyy-MM-dd + */ + public static String beforeDay(long days) { + return formatLocalDate(LocalDate.now().minusDays(days)); + } +} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/utils/HttpUtil.java b/budd-common/src/main/java/io/github/ehlxr/util/HttpUtil.java similarity index 97% rename from src/main/java/io/github/ehlxr/utils/HttpUtil.java rename to budd-common/src/main/java/io/github/ehlxr/util/HttpUtil.java index 9310e58..c0c5307 100644 --- a/src/main/java/io/github/ehlxr/utils/HttpUtil.java +++ b/budd-common/src/main/java/io/github/ehlxr/util/HttpUtil.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2020 xrv + * Copyright © 2021 xrv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -22,9 +22,11 @@ * THE SOFTWARE. */ -package io.github.ehlxr.utils; +package io.github.ehlxr.util; import com.google.common.collect.Maps; +import io.github.ehlxr.enums.FormType; +import io.github.ehlxr.enums.HttpContentType; import okhttp3.*; import java.io.File; diff --git a/budd-common/src/main/java/io/github/ehlxr/util/IdUtil.java b/budd-common/src/main/java/io/github/ehlxr/util/IdUtil.java new file mode 100644 index 0000000..f45e603 --- /dev/null +++ b/budd-common/src/main/java/io/github/ehlxr/util/IdUtil.java @@ -0,0 +1,108 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021 xrv + * + * 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 io.github.ehlxr.util; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 自增 id 生成工具类 + * + * @author ehlxr + * @since 2021-08-29 18:32. + */ +@Component +public class IdUtil { + private final static String REDIS_ID_KEY = "com.tzld.piaoquan.incentive_"; + /** + * 每一毫秒生成的最大数 + */ + private static final int MAX_NUN = 99; + private static final AtomicInteger ATOMIC_NUM = new AtomicInteger(); + private static RedisTemplate redisTemplate; + private static String cur_date; + + public static long redisId() { + // 生成 17 位的时间戳(每毫秒使用新的时间戳当key) + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"); + String timeStamp = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter); + // 获得 redis-key + String newKey = String.format("%s:%s", REDIS_ID_KEY, timeStamp); + // 获取自增值(时间戳 + 自定义 key) + Long increment = redisTemplate.opsForValue().increment(newKey, 1); + // 设置时间戳生成的 key 的有效期为 1 秒 + redisTemplate.expire(newKey, 1, TimeUnit.SECONDS); + // 获取订单号,时间戳 + 唯一自增 Id(2 位数,不过前方补 0) + return Long.parseLong(String.format("%s%02d", timeStamp, increment)); + } + + // @Autowired + // public IdUtil(RedisTemplate redisTemplate) { + // IdUtil.redisTemplate = redisTemplate; + // } + + /** + * 生成 19 位数 id + *

+ * 17 位日期 + 2 位自增数
+ * 一毫秒最多生成 MAX_NUN 个 id,同一毫秒 id 有序自增 + */ + public static long localId() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"); + String nowStr = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter); + + // 如果当前时间不是 cur_date 时间 设置 cur_date 为当前时间 重新开始计数 + if (!nowStr.equals(cur_date)) { + cur_date = nowStr; + + ATOMIC_NUM.set(0); + } + // 如果同一毫秒最大数大于 最大数 MAX_NUN 则等待 1 毫秒 重新计算 + if (ATOMIC_NUM.get() >= MAX_NUN) { + try { + Thread.sleep(1); + } catch (InterruptedException ignored) { + } + + nowStr = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter); + ATOMIC_NUM.set(0); + } + + // 线程安全的原子操作,所以此方法无需同步 调用 incrementAndGet 函数来进行自增操作 + return Long.parseLong(String.format("%s%02d", nowStr, ATOMIC_NUM.incrementAndGet())); + } + + @Autowired + public void setRedisTemplate(RedisTemplate redisTemplate) { + IdUtil.redisTemplate = redisTemplate; + } +} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/utils/JsonUtils.java b/budd-common/src/main/java/io/github/ehlxr/util/JsonUtils.java similarity index 95% rename from src/main/java/io/github/ehlxr/utils/JsonUtils.java rename to budd-common/src/main/java/io/github/ehlxr/util/JsonUtils.java index 4a11790..6479bce 100644 --- a/src/main/java/io/github/ehlxr/utils/JsonUtils.java +++ b/budd-common/src/main/java/io/github/ehlxr/util/JsonUtils.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2020 xrv + * Copyright © 2021 xrv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package io.github.ehlxr.utils; +package io.github.ehlxr.util; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; @@ -30,6 +30,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; +import io.github.ehlxr.exception.JsonParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -75,7 +76,7 @@ public class JsonUtils { try { return OBJECT_MAPPER.readTree(obj2String(obj)); } catch (JsonProcessingException e) { - throw new RuntimeException(e); + throw new JsonParseException(e); } } @@ -93,7 +94,7 @@ public class JsonUtils { try { return obj instanceof String ? (String) obj : OBJECT_MAPPER.writeValueAsString(obj); } catch (JsonProcessingException e) { - throw new RuntimeException(e); + throw new JsonParseException(e); } } @@ -111,7 +112,7 @@ public class JsonUtils { try { return obj instanceof String ? (String) obj : OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (JsonProcessingException e) { - throw new RuntimeException(e); + throw new JsonParseException(e); } } @@ -130,7 +131,7 @@ public class JsonUtils { try { return clazz.equals(String.class) ? (T) str : OBJECT_MAPPER.readValue(str, clazz); } catch (JsonProcessingException e) { - throw new RuntimeException(e); + throw new JsonParseException(e); } } @@ -149,7 +150,7 @@ public class JsonUtils { try { return typeReference.getType().equals(String.class) ? (T) str : OBJECT_MAPPER.readValue(str, typeReference); } catch (JsonProcessingException e) { - throw new RuntimeException(e); + throw new JsonParseException(e); } } @@ -167,7 +168,7 @@ public class JsonUtils { try { return OBJECT_MAPPER.readValue(str, javaType); } catch (JsonProcessingException e) { - throw new RuntimeException(e); + throw new JsonParseException(e); } } @@ -246,4 +247,3 @@ public class JsonUtils { } } - diff --git a/budd-common/src/main/java/io/github/ehlxr/util/RedisUtil.java b/budd-common/src/main/java/io/github/ehlxr/util/RedisUtil.java new file mode 100644 index 0000000..231805a --- /dev/null +++ b/budd-common/src/main/java/io/github/ehlxr/util/RedisUtil.java @@ -0,0 +1,174 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021 xrv + * + * 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 io.github.ehlxr.util; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.scripting.support.StaticScriptSource; +import org.springframework.stereotype.Component; + +import java.util.Collections; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +/** + * redis 操作 + * + * @author ehlxr + * @since 2021-08-29 18:32. + */ +@SuppressWarnings("unused") +@Component +public class RedisUtil { + /** + * 解锁 lua 脚本 + */ + public static final String UNLOCK = "if (redis.call('hexists', KEYS[1], ARGV[1]) == 0) then " + + "return nil; " + + "end; " + + "local counter = redis.call('hincrby', KEYS[1], ARGV[1], -1); " + + "if (counter > 0) then " + + "return 0; " + + "else " + + "redis.call('del', KEYS[1]); " + + "return 1; " + + "end; " + + "return nil;"; + /** + * 锁前缀 + */ + private static final String LOCK_PREFIX = "LOCK_"; + /** + * 默认重试次数 + */ + private static final Integer DEFAULT_RETRIES = 1; + /** + * 默认 10毫秒 + */ + private static final Long DEFAULT_INTERVAL = 10L; + /** + * 加锁 lua 脚本 + */ + private static final String LOCK = "if (redis.call('exists', KEYS[1]) == 0) then " + + "redis.call('hset', KEYS[1], ARGV[2], 1); " + + "redis.call('pexpire', KEYS[1], ARGV[1]); " + + "return 1; " + + "end; " + + "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " + + "redis.call('hincrby', KEYS[1], ARGV[2], 1); " + + "redis.call('pexpire', KEYS[1], ARGV[1]); " + + "return 1; " + + "end; " + + "return 0;"; + private static RedisTemplate redisTemplate; + + /** + * 加锁 不可重入 + * + * @param timeout 毫秒 + */ + public static Boolean lock(String key, long timeout) { + return redisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + key, "1", timeout, TimeUnit.MILLISECONDS); + } + + /** + * 解锁 不可重入 + */ + public static Boolean unlock(String key) { + return redisTemplate.delete(LOCK_PREFIX + key); + } + + /** + * 加锁 + * + * @param reentrantId 重入Id + * 超时时间 毫秒ms + */ + public static Boolean lock(String key, String reentrantId, long timeout) { + return lock(key, reentrantId, timeout, DEFAULT_RETRIES); + } + + /** + * 加锁 + * + * @param reentrantId 重入Id + * 超时时间 毫秒ms + * @param retries 重试次数 + */ + public static Boolean lock(String key, String reentrantId, long timeout, int retries) { + return lock(key, reentrantId, timeout, retries, DEFAULT_INTERVAL); + } + + /** + * 加锁 + * + * @param reentrantId 重入Id + * 超时时间 毫秒ms + * @param retries 重试次数 + * @param interval 每次重试间隔时间 毫秒 + */ + public static Boolean lock(String key, String reentrantId, long timeout, int retries, long interval) { + String lockKey = LOCK_PREFIX + key; + DefaultRedisScript script = new DefaultRedisScript<>(); + script.setResultType(Long.class); + script.setScriptSource(new StaticScriptSource(LOCK)); + for (int i = 0; i < retries; i++) { + Object result = redisTemplate.execute(script, Collections.singletonList(lockKey), String.valueOf(timeout), reentrantId); + if (Objects.nonNull(result) && Objects.equals(1L, Long.valueOf(result.toString()))) { + return true; + } + try { + TimeUnit.MILLISECONDS.sleep(interval); + } catch (InterruptedException e) { + e.printStackTrace(); + return null; + } + } + return false; + } + + /** + * 解锁 + * + * @param reentrantId 重入ID + */ + public static Boolean unlock(String key, String reentrantId) { + String lockKey = LOCK_PREFIX + key; + DefaultRedisScript script = new DefaultRedisScript<>(); + script.setResultType(Long.class); + script.setScriptSource(new StaticScriptSource(UNLOCK)); + Object result = redisTemplate.execute(script, Collections.singletonList(lockKey), reentrantId); + if (Objects.isNull(result)) { + return null; + } + return Objects.equals(1L, Long.valueOf(result.toString())); + } + + @Autowired + public void setRedisTemplate(RedisTemplate redisTemplate) { + RedisUtil.redisTemplate = redisTemplate; + } +} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/utils/SendAlarmUtil.java b/budd-common/src/main/java/io/github/ehlxr/util/SendAlarmUtil.java similarity index 84% rename from src/main/java/io/github/ehlxr/utils/SendAlarmUtil.java rename to budd-common/src/main/java/io/github/ehlxr/util/SendAlarmUtil.java index 8d7b8f2..276c09f 100644 --- a/src/main/java/io/github/ehlxr/utils/SendAlarmUtil.java +++ b/budd-common/src/main/java/io/github/ehlxr/util/SendAlarmUtil.java @@ -22,9 +22,11 @@ * THE SOFTWARE. */ -package io.github.ehlxr.utils; +package io.github.ehlxr.util; import com.google.common.collect.ImmutableMap; +import io.github.ehlxr.common.Constant; +import org.slf4j.MDC; import java.util.Objects; import java.util.concurrent.CompletableFuture; @@ -48,11 +50,11 @@ public class SendAlarmUtil { /** * 异步发送预警信息 * - * @param msg 预警信息 - * @param action {@link BiConsumer} 完成后回调函数式接口 + * @param message 预警信息 + * @param action {@link BiConsumer} 完成后回调函数式接口 */ - public static void send(String msg, BiConsumer action) { - // String msg = String.format("%s\ntraceid: %s", msg, MDC.get(Constants.LOG_TRACE_ID)); + public static void send(String message, BiConsumer action) { + String msg = String.format("%s\ntraceid: %s", message, MDC.get(Constant.LOG_TRACE_ID)); CompletableFuture.supplyAsync(() -> { Objects.requireNonNull(dingtalkUrl, "SendAlarmUtil not init."); @@ -79,10 +81,10 @@ public class SendAlarmUtil { .trap(System.out::println) .run(); - send("dsfsdf", + send("hello", (t, u) -> System.out.println("send exception message to dingtalk result " + t + ". " + u)); - System.out.println("000000"); + System.out.println("do other something...."); Thread.sleep(2000); } diff --git a/src/main/java/io/github/ehlxr/utils/Try.java b/budd-common/src/main/java/io/github/ehlxr/util/Try.java similarity index 99% rename from src/main/java/io/github/ehlxr/utils/Try.java rename to budd-common/src/main/java/io/github/ehlxr/util/Try.java index e97c515..a9c9eba 100644 --- a/src/main/java/io/github/ehlxr/utils/Try.java +++ b/budd-common/src/main/java/io/github/ehlxr/util/Try.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package io.github.ehlxr.utils; +package io.github.ehlxr.util; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableMap; @@ -84,6 +84,163 @@ public interface Try { return new TryRunnable(runnable); } + @SuppressWarnings({"ConstantConditions", "Convert2MethodRef"}) + static void main(String[] args) { + System.out.println("------------有返回值,无入参----------------"); + // 有返回值,无入参 + String param = "hello"; + Long result = Try.of(() -> Long.valueOf(param)).get(0L); + System.out.println("Long.valueOf 1: " + result); + + result = Try.of(() -> Long.valueOf(param)).get(); + System.out.println("Long.valueOf 2: " + result); + + System.out.println("------------有返回值,有入参----------------"); + // 有返回值,有入参 + result = Try., Long>of(s -> Long.valueOf(s.get("k1"))) + .apply(ImmutableMap.of("k1", param)) + .trap(e -> System.out.println("Long.valueOf exception: " + e.getMessage())) + .andFinally(() -> System.out.println("This message will ignore.")) + .andFinally(s -> { + Map returnMap = JsonUtils.string2Obj(JsonUtils.obj2String(s), new TypeReference>() { + }); + System.out.println("Long.valueOf finally run code." + s); + // 演示抛异常 + String k2 = returnMap.get("k2").toString(); + System.out.println(k2); + }) + .finallyTrap(e -> System.out.println("Long.valueOf finally exception: " + e.getMessage())) + .get(); + System.out.println("Long.valueOf 3: " + result); + + ArrayList list = null; + + System.out.println("-----------无返回值,无入参-----------------"); + // 无返回值,无入参 + Try.of(() -> Thread.sleep(-1L)) + .andFinally(() -> list.clear()) + // .andFinally(list::clear) //https://stackoverflow.com/questions/37413106/java-lang-nullpointerexception-is-thrown-using-a-method-reference-but-not-a-lamb + .run(); + + System.out.println("--------------无返回值,有入参--------------"); + // 无返回值,有入参 + Try.of(v -> list.add(0, v)) + .andFinally(s -> System.out.println(s)) + .accept("hello"); + } + + class TryRunnable extends Tryable { + private final ThrowableRunnable runnable; + + protected TryRunnable(ThrowableRunnable runnable) { + Objects.requireNonNull(runnable, "No runnable present"); + this.runnable = runnable; + + super.c = this; + } + + /** + * 计算结果 + */ + public void run() { + try { + runnable.run(); + } catch (final Throwable e) { + Optional.ofNullable(throwConsumer).ifPresent(tc -> tc.accept(e)); + } finally { + doFinally(); + } + } + } + + class TrySupplier extends Tryable> { + private final ThrowableSupplier supplier; + + protected TrySupplier(ThrowableSupplier supplier) { + Objects.requireNonNull(supplier, "No supplier present"); + this.supplier = supplier; + + super.c = this; + } + + /** + * 如果有异常返回默认值,否则返回计算结果 + * + * @param r 指定默认值 + * @return 实际值或默认值 + */ + public R get(R r) { + try { + return supplier.get(); + } catch (final Throwable e) { + Optional.ofNullable(throwConsumer).ifPresent(tc -> tc.accept(e)); + return r; + } finally { + doFinally(); + } + } + + /** + * 如果有异常返回 null,否则返回计算结果 + * + * @return 实际值或 null + */ + public R get() { + try { + return supplier.get(); + } catch (final Throwable e) { + Optional.ofNullable(throwConsumer).ifPresent(tc -> tc.accept(e)); + return null; + } finally { + doFinally(); + } + } + } + + @FunctionalInterface + interface ThrowableConsumer

{ + /** + * Performs this operation on the given argument. + * + * @param p the input argument + * @throws Throwable throwable + */ + void accept(P p) throws Throwable; + } + + @FunctionalInterface + interface ThrowableSupplier { + /** + * Gets a result. + * + * @return a result + * @throws Throwable throwable + */ + R get() throws Throwable; + } + + @FunctionalInterface + interface ThrowableRunnable { + /** + * Performs this operation + * + * @throws Throwable throwable + */ + void run() throws Throwable; + } + + @FunctionalInterface + interface ThrowableFunction { + /** + * Applies this function to the given argument. + * + * @param p the function argument + * @return the function result + * @throws Throwable throwable + */ + R apply(P p) throws Throwable; + } + abstract class Tryable { Consumer throwConsumer; ThrowableRunnable finallyRunnable; @@ -175,74 +332,6 @@ public interface Try { } } - class TryRunnable extends Tryable { - private final ThrowableRunnable runnable; - - protected TryRunnable(ThrowableRunnable runnable) { - Objects.requireNonNull(runnable, "No runnable present"); - this.runnable = runnable; - - super.c = this; - } - - /** - * 计算结果 - */ - public void run() { - try { - runnable.run(); - } catch (final Throwable e) { - Optional.ofNullable(throwConsumer).ifPresent(tc -> tc.accept(e)); - } finally { - doFinally(); - } - } - } - - class TrySupplier extends Tryable> { - private final ThrowableSupplier supplier; - - protected TrySupplier(ThrowableSupplier supplier) { - Objects.requireNonNull(supplier, "No supplier present"); - this.supplier = supplier; - - super.c = this; - } - - /** - * 如果有异常返回默认值,否则返回计算结果 - * - * @param r 指定默认值 - * @return 实际值或默认值 - */ - public R get(R r) { - try { - return supplier.get(); - } catch (final Throwable e) { - Optional.ofNullable(throwConsumer).ifPresent(tc -> tc.accept(e)); - return r; - } finally { - doFinally(); - } - } - - /** - * 如果有异常返回 null,否则返回计算结果 - * - * @return 实际值或 null - */ - public R get() { - try { - return supplier.get(); - } catch (final Throwable e) { - Optional.ofNullable(throwConsumer).ifPresent(tc -> tc.accept(e)); - return null; - } finally { - doFinally(); - } - } - } - class TryConsumer

extends Tryable> { private final ThrowableConsumer consumer; @@ -335,93 +424,4 @@ public interface Try { } } } - - @FunctionalInterface - interface ThrowableConsumer

{ - /** - * Performs this operation on the given argument. - * - * @param p the input argument - * @throws Throwable throwable - */ - void accept(P p) throws Throwable; - } - - @FunctionalInterface - interface ThrowableSupplier { - /** - * Gets a result. - * - * @return a result - * @throws Throwable throwable - */ - R get() throws Throwable; - } - - @FunctionalInterface - interface ThrowableRunnable { - /** - * Performs this operation - * - * @throws Throwable throwable - */ - void run() throws Throwable; - } - - @FunctionalInterface - interface ThrowableFunction { - /** - * Applies this function to the given argument. - * - * @param p the function argument - * @return the function result - * @throws Throwable throwable - */ - R apply(P p) throws Throwable; - } - - @SuppressWarnings({"ConstantConditions", "Convert2MethodRef"}) - static void main(String[] args) { - System.out.println("------------有返回值,无入参----------------"); - // 有返回值,无入参 - String param = "hello"; - Long result = Try.of(() -> Long.valueOf(param)).get(0L); - System.out.println("Long.valueOf 1: " + result); - - result = Try.of(() -> Long.valueOf(param)).get(); - System.out.println("Long.valueOf 2: " + result); - - System.out.println("------------有返回值,有入参----------------"); - // 有返回值,有入参 - result = Try., Long>of(s -> Long.valueOf(s.get("k1"))) - .apply(ImmutableMap.of("k1", param)) - .trap(e -> System.out.println("Long.valueOf exception: " + e.getMessage())) - .andFinally(() -> System.out.println("This message will ignore.")) - .andFinally(s -> { - Map returnMap = JsonUtils.string2Obj(JsonUtils.obj2String(s), new TypeReference>() { - }); - System.out.println("Long.valueOf finally run code." + s); - // 演示抛异常 - String k2 = returnMap.get("k2").toString(); - System.out.println(k2); - }) - .finallyTrap(e -> System.out.println("Long.valueOf finally exception: " + e.getMessage())) - .get(); - System.out.println("Long.valueOf 3: " + result); - - ArrayList list = null; - - System.out.println("-----------无返回值,无入参-----------------"); - // 无返回值,无入参 - Try.of(() -> Thread.sleep(-1L)) - .andFinally(() -> list.clear()) - // .andFinally(list::clear) //https://stackoverflow.com/questions/37413106/java-lang-nullpointerexception-is-thrown-using-a-method-reference-but-not-a-lamb - .run(); - - System.out.println("--------------无返回值,有入参--------------"); - // 无返回值,有入参 - Try.of(v -> list.add(0, v)) - .andFinally(s -> System.out.println(s)) - .accept("hello"); - } } diff --git a/budd-demo/pom.xml b/budd-demo/pom.xml new file mode 100644 index 0000000..3d3f349 --- /dev/null +++ b/budd-demo/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + + io.github.ehlxr + budd + 0.0.1-SNAPSHOT + + + budd-demo + budd-demo + + diff --git a/budd-server/pom.xml b/budd-server/pom.xml new file mode 100644 index 0000000..b1022fd --- /dev/null +++ b/budd-server/pom.xml @@ -0,0 +1,60 @@ + + 4.0.0 + + io.github.ehlxr + budd + 0.0.1-SNAPSHOT + + + budd-server + budd-server + + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + com.spring4all + swagger-spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-aop + + + + io.github.ehlxr + budd-common + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + + + repackage + + + + + + + diff --git a/src/main/java/io/github/ehlxr/BuddApplication.java b/budd-server/src/main/java/io/github/ehlxr/BuddServerApplication.java similarity index 82% rename from src/main/java/io/github/ehlxr/BuddApplication.java rename to budd-server/src/main/java/io/github/ehlxr/BuddServerApplication.java index 65f4c21..916aa17 100644 --- a/src/main/java/io/github/ehlxr/BuddApplication.java +++ b/budd-server/src/main/java/io/github/ehlxr/BuddServerApplication.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2021 xrv + * Copyright © 2020 xrv * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,14 +26,16 @@ package io.github.ehlxr; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletComponentScan; /** * @author ehlxr - * @since 2021-08-29 09:35. + * @since 2021-08-29 18:32. */ @SpringBootApplication -public class BuddApplication { +@ServletComponentScan("io.github.ehlxr.filter") +public class BuddServerApplication { public static void main(String[] args) { - SpringApplication.run(BuddApplication.class, args); + SpringApplication.run(BuddServerApplication.class, args); } } diff --git a/budd-server/src/main/java/io/github/ehlxr/aop/LogRequestAop.java b/budd-server/src/main/java/io/github/ehlxr/aop/LogRequestAop.java new file mode 100644 index 0000000..c8c1cb5 --- /dev/null +++ b/budd-server/src/main/java/io/github/ehlxr/aop/LogRequestAop.java @@ -0,0 +1,141 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021 xrv + * + * 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 io.github.ehlxr.aop; + +import com.google.common.base.Strings; +import io.github.ehlxr.common.Constant; +import io.github.ehlxr.util.JsonUtils; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * 请求日志记录 + * + * @author ehlxr + * @since 2021-08-17 22:03. + */ +@Aspect +@Component +public class LogRequestAop { + private static final Logger log = LoggerFactory.getLogger(LogRequestAop.class); + + // private final AliyunLogManager aliyunLogManager; + // /** + // * aliyun log 配置 + // */ + // @Value("${aliyun.log.project:}") + // private String projcet; + // @Value("${aliyun.log.logstore.request:}") + // private String logStore; + // @Value("${aliyun.log.topic:}") + // private String topic; + + // @Autowired + // public LogRequestAop(AliyunLogManager aliyunLogManager) { + // this.aliyunLogManager = aliyunLogManager; + // } + + /** + * 切入点 + */ + @Pointcut("execution(public * io.github.ehlxr.*Controller.*(..)) && !@annotation(io.github.ehlxr.annotations.NoRequestLog)") + // @Pointcut("@within(org.springframework.web.bind.annotation.RestController) && !@annotation(com.tzld.piaoquan.incentive.annotations.NoRequestLog)") + public void requestLog() { + } + + /** + * 前置操作 + */ + @Before("requestLog()") + public void beforeLog() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); + + request.setAttribute(Constant.REQUEST_START_TIME, System.currentTimeMillis()); + } + + /** + * 后置操作 + */ + @AfterReturning(pointcut = "requestLog()", returning = "returnValue") + public void afterReturning(JoinPoint point, Object returnValue) { + logRecord(point, JsonUtils.obj2String(returnValue)); + } + + @AfterThrowing(pointcut = "requestLog()", throwing = "ex") + public void afterThrowing(JoinPoint point, Exception ex) { + logRecord(point, ex.getMessage()); + } + + private void logRecord(JoinPoint point, String message) { + try { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); + + Long startTime = (Long) request.getAttribute(Constant.REQUEST_START_TIME); + if (Objects.isNull(startTime)) { + return; + } + + String query = request.getQueryString(); + String uri = request.getRequestURI(); + + Map logMap = new HashMap<>(8); + logMap.put("url", Strings.isNullOrEmpty(query) ? uri : uri + "?" + query); + logMap.put("method", request.getMethod()); + logMap.put("header", getHeaders(request)); + logMap.put("elapsedTime", String.valueOf(System.currentTimeMillis() - startTime)); + logMap.put("clientIp", request.getRemoteAddr()); + logMap.put("requestBody", JsonUtils.obj2String(point.getArgs())); + logMap.put(Constant.LOG_TRACE_ID, Strings.nullToEmpty(MDC.get(Constant.LOG_TRACE_ID))); + logMap.put("responseBody", message); + + // aliyunLogManager.sendLog(projcet, logStore, topic, logMap); + } catch (Exception e) { + log.error("log report request error", e); + } + } + + private String getHeaders(HttpServletRequest request) { + return Collections.list(request.getHeaderNames()) + .stream() + .collect(Collectors.toMap( + name -> name, + request::getHeader)).toString(); + } +} \ No newline at end of file diff --git a/budd-server/src/main/java/io/github/ehlxr/config/Initialization.java b/budd-server/src/main/java/io/github/ehlxr/config/Initialization.java new file mode 100644 index 0000000..02bd275 --- /dev/null +++ b/budd-server/src/main/java/io/github/ehlxr/config/Initialization.java @@ -0,0 +1,72 @@ +package io.github.ehlxr.config; + + +import io.github.ehlxr.util.SendAlarmUtil; +import io.github.ehlxr.util.Try; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +/** + * 项目初始化 + * + * @author ehlxr + * @since 2020/4/22. + */ +@Component +public class Initialization implements ApplicationRunner { + private static final Logger log = LoggerFactory.getLogger(Initialization.class); + + @Value("${aliyun.oss.endpoint:}") + private String endpoint; + @Value("${aliyun.oss.accesskey.id:}") + private String accessKeyId; + @Value("${aliyun.oss.accesskey.secret:}") + private String accessKeySecret; + @Value("${aliyun.oss.bucket:}") + private String bucket; + @Value("${aliyun.oss.key-path:}") + private String keyPath; + @Value("${aliyun.oss.url-lifetime:0}") + private Long urlLifetime; + + @Value("${lk.jmeter.cmd:}") + private String jmeterCmd; + @Value("${location:}") + private String location; + + @Value("${lk.dingtalk-url:}") + private String dingtalkUrl; + + + @Override + public void run(ApplicationArguments args) { + // 初始化阿里云 OSS 配置信息 + // AliyunOssConfig config = AliyunOssConfig.newBuilder() + // .endpoint(endpoint) + // .accessKeyId(accessKeyId) + // .accessKeySecret(accessKeySecret) + // .bucketName(bucket) + // .keyPath(keyPath) + // .urlLifetime(urlLifetime) + // .build(); + // log.info("aliyun oss config {}", config); + // FileUploadUtil.init(config); + // + // if (!"develop".equals(location) && !"PRO2".equals(location)) { + // try { + // ExecShell.execShellCommand(jmeterCmd); + // } catch (Exception e) { + // log.error("exec jmeter cmd error {}", e.getMessage()); + // } + // } + + // 预警信息发送初始化 + Try.of(() -> SendAlarmUtil.init(dingtalkUrl)) + .trap(e -> log.warn("int SendAlarmUtil error: {}", e.getMessage())) + .run(); + } +} diff --git a/src/main/java/io/github/ehlxr/singleton/SingleEnum.java b/budd-server/src/main/java/io/github/ehlxr/controller/IndexController.java similarity index 69% rename from src/main/java/io/github/ehlxr/singleton/SingleEnum.java rename to budd-server/src/main/java/io/github/ehlxr/controller/IndexController.java index a7a4866..2af50b9 100644 --- a/src/main/java/io/github/ehlxr/singleton/SingleEnum.java +++ b/budd-server/src/main/java/io/github/ehlxr/controller/IndexController.java @@ -22,31 +22,29 @@ * THE SOFTWARE. */ -package io.github.ehlxr.singleton; +package io.github.ehlxr.controller; -import java.util.stream.IntStream; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; /** - * 枚举单例模式 - * * @author ehlxr - * @since 2021-02-18 10:28. + * @since 2021-08-29 18:45. */ -public enum SingleEnum { +@RestController +@Api(tags = "测试辅助接口") +public class IndexController { + /** - * 唯一实例 + * 健康检测 */ - INSTANCE; - - public static SingleEnum getInstance() { - return INSTANCE; + @ApiOperation(value = "健康检测", notes = "健康检测") + @GetMapping("/healthcheck") + public String healthcheck() { + return "ok"; } - public String hello(String str) { - return "hello " + str; - } - public static void main(String[] args) { - IntStream.range(0, 5).parallel().forEach(i -> System.out.println(Thread.currentThread().getName() + " => " + SingleEnum.getInstance())); - } } diff --git a/budd-server/src/main/java/io/github/ehlxr/filter/CustomFilter.java b/budd-server/src/main/java/io/github/ehlxr/filter/CustomFilter.java new file mode 100644 index 0000000..b1c0164 --- /dev/null +++ b/budd-server/src/main/java/io/github/ehlxr/filter/CustomFilter.java @@ -0,0 +1,42 @@ +package io.github.ehlxr.filter; + +import io.github.ehlxr.common.Constant; +import io.github.ehlxr.util.IdUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.core.annotation.Order; + +import javax.servlet.*; +import javax.servlet.annotation.WebFilter; +import java.io.IOException; + +/** + * auth filter + * + * @author supeng + * @date 2020/08/31 + */ +@Order(value = 1) +@WebFilter(filterName = "customFilter", urlPatterns = {"/api/*"}) +public class CustomFilter implements Filter { + private static final Logger log = LoggerFactory.getLogger(CustomFilter.class); + + @Override + public void init(FilterConfig filterConfig) { + log.info("customFilter init"); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + MDC.put(Constant.LOG_TRACE_ID, String.valueOf(IdUtil.localId())); + filterChain.doFilter(servletRequest, servletResponse); + MDC.remove(Constant.LOG_TRACE_ID); + } + + @Override + public void destroy() { + log.info("customFilter destroy"); + } +} diff --git a/budd-server/src/main/java/io/github/ehlxr/handler/GlobalExceptionHandler.java b/budd-server/src/main/java/io/github/ehlxr/handler/GlobalExceptionHandler.java new file mode 100644 index 0000000..039a0b9 --- /dev/null +++ b/budd-server/src/main/java/io/github/ehlxr/handler/GlobalExceptionHandler.java @@ -0,0 +1,66 @@ +package io.github.ehlxr.handler; + +import io.github.ehlxr.common.Constant; +import io.github.ehlxr.common.Result; +import io.github.ehlxr.enums.CodeEnum; +import io.github.ehlxr.exception.ServiceDataException; +import org.assertj.core.util.Strings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartException; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import javax.servlet.http.HttpServletRequest; + +/** + * @author ehlxr + * @since 2020/4/20. + */ +@ControllerAdvice +public class GlobalExceptionHandler { + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + @ExceptionHandler(Exception.class) + @ResponseBody + public Result defaultExceptionHandler(HttpServletRequest request, Exception e) { + log.error("request: {}, exception: ", request.getRequestURI(), e); + + // SendAlarmUtil.send(String.format("未知异常 request: %s, exception: %s", request.getRequestURI(), ExceptionUtils.getStackTrace(e)), + // (t, u) -> log.info("send exception message to dingtalk result {} ", t, u)); + + String msg = CodeEnum.UNKNOWN_EXCEPTION.getMessage(); + String traceId = MDC.get(Constant.LOG_TRACE_ID); + if (!Strings.isNullOrEmpty(traceId)) { + msg = String.format("%s(%s)", msg, traceId); + } + + return Result.of(CodeEnum.UNKNOWN_EXCEPTION.getCode(), null, msg); + } + + @ExceptionHandler(ServiceDataException.class) + @ResponseBody + public Result serviceDataExceptionHandler(HttpServletRequest request, ServiceDataException e) { + log.error("request: {} service exception: ", request.getRequestURI(), e); + + // SendAlarmUtil.send(String.format("业务异常 request: %s, service exception: %s", request.getRequestURI(), ExceptionUtils.getStackTrace(e)), + // (t, u) -> log.info("send service exception message to dingtalk result {} ", t, u)); + + String msg = e.getMessage(); + String traceId = MDC.get(Constant.LOG_TRACE_ID); + if (!Strings.isNullOrEmpty(traceId)) { + msg = String.format("%s(%s)", msg, traceId); + } + + return Result.of(e.getCode(), null, msg); + } + + @ExceptionHandler(MultipartException.class) + public String handleError(MultipartException e, RedirectAttributes redirectAttributes) { + redirectAttributes.addFlashAttribute("message", e.getCause().getMessage()); + return "redirect:/uploadStatus"; + } +} diff --git a/src/main/java/io/github/ehlxr/leetcode/ListNode.java b/budd-server/src/main/java/io/github/ehlxr/interceptor/TraceInterceptor.java similarity index 60% rename from src/main/java/io/github/ehlxr/leetcode/ListNode.java rename to budd-server/src/main/java/io/github/ehlxr/interceptor/TraceInterceptor.java index d8532a3..fbb39f5 100644 --- a/src/main/java/io/github/ehlxr/leetcode/ListNode.java +++ b/budd-server/src/main/java/io/github/ehlxr/interceptor/TraceInterceptor.java @@ -22,35 +22,31 @@ * THE SOFTWARE. */ -package io.github.ehlxr.leetcode; +package io.github.ehlxr.interceptor; + +import io.github.ehlxr.common.Constant; +import io.github.ehlxr.util.IdUtil; +import org.slf4j.MDC; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; /** - * 链表结构 + * 日志 traceid Interceptor * * @author ehlxr - * @since 2021-02-27 21:09. + * @since 2020-12-23 11:23. */ -public class ListNode { - int val; - ListNode next; - - ListNode() { - } - - ListNode(int val) { - this.val = val; - } - - ListNode(int val, ListNode next) { - this.val = val; - this.next = next; +public class TraceInterceptor extends HandlerInterceptorAdapter { + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + MDC.put(Constant.LOG_TRACE_ID, String.valueOf(IdUtil.localId())); + return true; } @Override - public String toString() { - return "ListNode{" + - "val=" + val + - ", next=" + next + - '}'; + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { + MDC.remove(Constant.LOG_TRACE_ID); } } \ No newline at end of file diff --git a/budd-server/src/main/resources/application-dev.yml b/budd-server/src/main/resources/application-dev.yml new file mode 100644 index 0000000..5d9f533 --- /dev/null +++ b/budd-server/src/main/resources/application-dev.yml @@ -0,0 +1,17 @@ +server: + port: 8081 + +springfox: + documentation: + enabled: true +swagger: + base-package: io.github.ehlxr + base-path: /** + contact: + email: xrv@live.com + name: rtg + url: https://ehlxr.me + description: swagger of budd server + exclude-path: /error, /ops/** + title: budd swagger + version: 0.0.1-SNAPSHOT diff --git a/src/main/resources/application.yml b/budd-server/src/main/resources/application.yml similarity index 67% rename from src/main/resources/application.yml rename to budd-server/src/main/resources/application.yml index 5e2d0aa..d1d1ad2 100644 --- a/src/main/resources/application.yml +++ b/budd-server/src/main/resources/application.yml @@ -4,11 +4,6 @@ spring: application: name: budd -logging: - file: - path: /datalog/weblog/${spring.application.name} - config: classpath:logback-spring.xml - server: tomcat: uri-encoding: UTF-8 @@ -17,4 +12,7 @@ server: servlet: context-path: /budd session: - timeout: 60 \ No newline at end of file + timeout: 60 +logging: + file: + path: /Users/ehlxr/logs/${spring.application.name} \ No newline at end of file diff --git a/src/main/resources/logback-spring.xml b/budd-server/src/main/resources/logback-spring.xml similarity index 77% rename from src/main/resources/logback-spring.xml rename to budd-server/src/main/resources/logback-spring.xml index c8a8078..7f0e04d 100644 --- a/src/main/resources/logback-spring.xml +++ b/budd-server/src/main/resources/logback-spring.xml @@ -150,71 +150,71 @@ DENY + - - - - - + 104857600 + 0 + 8 + 524288 + 4096 + 2000 + 10 + 100 + 50000 - - - - - - - - - + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level [%X{logTraceId}] %logger{50} [%L] - %msg%n + UTF-8 + - - - - + yyyy-MM-dd'T'HH:mmZ + Asia/Shanghai - - + + INFO + - - - + logTraceId + - - + + ${ALIYUN_LOG_ENDPOINT} + ${ALIYUN_LOG_ACCESSKEYID} + ${ALIYUN_LOG_ACCESSKEYSECRET} + ${ALIYUN_LOG_PROJECT} + ${ALIYUN_LOG_LOGSTORE_ERROR} - - - - - - + 104857600 + 0 + 8 + 524288 + 4096 + 2000 + 10 + 100 + 50000 - - - - - - - - - + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level [%X{logTraceId}] %logger{50} [%L] - %msg%n + UTF-8 + - - - - + yyyy-MM-dd'T'HH:mmZ + Asia/Shanghai - - - - - - - - - + + ERROR + + logTraceId + + --> - - - - - - - - - - - diff --git a/pom.xml b/pom.xml index aef9610..d26b9bf 100644 --- a/pom.xml +++ b/pom.xml @@ -1,25 +1,17 @@ - + 4.0.0 + pom + + budd-common + budd-demo + budd-server + + io.github.ehlxr budd - war 0.0.1-SNAPSHOT - - - - - - - - - - - - - - budd - http://maven.apache.org + budd-parent UTF-8 @@ -28,18 +20,11 @@ 11 11 - 5.2.6.RELEASE - 2.5 - 3.5.6 - 1.1.1 - 1.4.0 - utf-8 - 1.8 - 1.7.1 - 1.3.61 - 2.2.6.RELEASE + 30.0-jre + 2.0.0.RELEASE + @@ -49,430 +34,26 @@ pom import + + + + com.google.guava + guava + ${guava.version} + + + + com.spring4all + swagger-spring-boot-starter + ${spring4all.swagger.version} + + + + io.github.ehlxr + budd-common + ${project.version} + - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - - - org.springframework.boot - spring-boot-starter-data-redis - - - com.jcraft - jsch - 0.1.53 - - - org.bouncycastle - bcprov-jdk16 - 1.46 - - - - junit - junit - 4.13.1 - - - - - commons-logging - commons-logging - 1.1.3 - - - - org.apache.shiro - shiro-core - 1.4.2 - - - slf4j-api - org.slf4j - - - - - - - org.springframework - spring-core - ${spring.version} - - - - org.springframework - spring-beans - ${spring.version} - - - - org.springframework - spring-context - ${spring.version} - - - - org.springframework - spring-web - ${spring.version} - - - - org.springframework - spring-oxm - ${spring.version} - - - - org.springframework - spring-tx - ${spring.version} - - - - org.springframework - spring-jdbc - ${spring.version} - - - - org.springframework - spring-webmvc - ${spring.version} - - - - org.springframework - spring-aop - ${spring.version} - - - - org.springframework - spring-context-support - ${spring.version} - - - - org.springframework - spring-test - ${spring.version} - - - - org.springframework - spring-jms - ${spring.version} - - - - org.springframework - spring-expression - ${spring.version} - - - - - commons-codec - commons-codec - 1.6 - - - - net.sf.json-lib - json-lib - 2.4 - jdk15 - - - - com.caucho - hessian - 4.0.38 - - - - redis.clients - jedis - 3.4.1 - - - slf4j-api - org.slf4j - - - - - - mysql - mysql-connector-java - 8.0.16 - - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - - - org.mybatis - mybatis - ${mybatis.version} - - - - org.mybatis - mybatis-spring - ${mybatis.spring.version} - - - - org.mybatis.generator - mybatis-generator-core - ${mybatis.generator.core.version} - - - - c3p0 - c3p0 - 0.9.1.2 - - - - - org.apache.httpcomponents - httpclient - 4.5.2 - - - - org.apache.cxf - cxf-rt-frontend-jaxws - 3.1.6 - - - - org.apache.cxf - cxf-rt-transports-http - 3.1.6 - - - - - - - - - - org.apache.activemq - activemq-broker - - - org.apache.activemq - activemq-client - - - org.apache.activemq - activemq-pool - - - org.apache.activemq - activemq-spring - - - - javax.jms - javax.jms-api - - - - org.apache.xbean - xbean-spring - 4.5 - - - commons-io - commons-io - 2.5 - - - - org.powermock - powermock-module-junit4 - ${powermock.version} - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - - - io.reactivex - rxjava - 1.3.0 - - - io.reactivex.rxjava2 - rxjava - 2.1.8 - - - com.google.guava - guava - 29.0-jre - - - org.jodd - jodd-props - 3.6.1 - - - - - - - - - - - - - - com.rabbitmq - amqp-client - 4.8.0 - - - slf4j-api - org.slf4j - - - - - - org.apache.hbase - hbase-client - 1.3.5 - - - slf4j-log4j12 - org.slf4j - - - log4j - log4j - - - slf4j-api - org.slf4j - - - - - - com.fasterxml.jackson.core - jackson-annotations - 2.10.3 - - - - com.fasterxml.jackson.core - jackson-databind - 2.10.5.1 - - - - com.squareup.okhttp3 - okhttp - 3.14.7 - - - - io.vavr - vavr - 0.10.3 - - - - pl.touk - throwing-function - 1.3 - - - - did-sdk - io.github.ehlxr - 1.0.2-SNAPSHOT - - - - - - github - https://git.ehlxr.me/ehlxr/maven-repository/raw/branch/main - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - src/test/resources - - - src/main/resources - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - repackage - - - - - - diff --git a/src/main/java/io/github/ehlxr/CharToHex.java b/src/main/java/io/github/ehlxr/CharToHex.java deleted file mode 100644 index 10d0353..0000000 --- a/src/main/java/io/github/ehlxr/CharToHex.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -/** - * Created by ehlxr on 2017/8/3. - */ -public class CharToHex { - private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); - - public static void main(String[] args) throws Exception { - String hex = bytesToHex("彤".getBytes()); - System.out.println(hex); - - System.out.println(toUnicode("彤")); - - // 十六进制 -> 十进制 - int i = Integer.parseInt(hex, 16); - System.out.println(i); - - // 十进制 -> 二进制 - String bin = Integer.toBinaryString(i); - System.out.println(bin); - - // 十进制 -> 十六进制 - String hex1 = Integer.toHexString(i); - System.out.println(hex1); - - // 十进制 -> 八进制 - String oct = Integer.toOctalString(i); - System.out.println(oct); - - System.out.println("---------------"); - System.out.println(Integer.toBinaryString(-22)); - //测试 int 转 byte - int int0 = 234; - byte byte0 = intToByte(int0); - System.out.println("byte0= " + byte0);//byte0=-22 - //测试 byte 转 int - int int1 = byteToInt(byte0); - System.out.println("int1= " + int1);//int1=234 - } - - - //byte 与 int 的相互转换 - public static byte intToByte(int x) { - return (byte) x; - } - - public static int byteToInt(byte b) { - //Java 总是把 byte 当做有符处理;我们可以通过将其和 0xFF 进行二进制与得到它的无符值 - return b & 0xFF; - } - - - /** - * 字符对应编码的哈希值 - * - * @param bytes - * @return - */ - public static String bytesToHex(byte[] bytes) { - char[] hexChars = new char[bytes.length * 2]; - for (int j = 0; j < bytes.length; j++) { - int v = bytes[j] & 0xFF; - hexChars[j * 2] = hexArray[v >>> 4]; - hexChars[j * 2 + 1] = hexArray[v & 0x0F]; - } - return new String(hexChars); - } - - public static String toUnicode(String s) { - String[] as = new String[s.length()]; - StringBuilder s1 = new StringBuilder(); - for (int i = 0; i < s.length(); i++) { - as[i] = Integer.toHexString(s.charAt(i) & 0xffff); - s1.append("\\u").append(as[i]); - } - return s1.toString(); - } - -} diff --git a/src/main/java/io/github/ehlxr/ContentReplace.java b/src/main/java/io/github/ehlxr/ContentReplace.java deleted file mode 100644 index 1501728..0000000 --- a/src/main/java/io/github/ehlxr/ContentReplace.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -import java.io.*; - -/** - * Created by ehlxr on 2017/11/17. - *

- * 递归扫描 Java 文件,添加 CopyRight 信息,已有跳过 - */ -public class ContentReplace { - private static int total = 0; - private static int unDeal = 0; - - public static void main(String[] args) throws IOException { - File dir = new File("/Users/ehlxr/WorkSpaces/Budd"); - deal(dir); - System.out.println("总文件数:" + total); - System.out.println("未处理文件数:" + unDeal); - } - - private static void deal(File file) throws IOException { - if (file.isDirectory()) { - File[] fs = file.listFiles(((dir, name) -> { - File f = new File(dir.getPath() + File.separator + name); - - return (f.getPath().contains("src") && name.endsWith(".java")) || f.isDirectory(); - })); - - for (File f : fs != null ? fs : new File[0]) { - deal(f); - } - } else { - ++total; - // System.out.println(file.getPath()); - - File tmp = File.createTempFile("tmp", null); - try ( - FileOutputStream tmpOut = new FileOutputStream(tmp); - FileInputStream tmpIn = new FileInputStream(tmp); - RandomAccessFile raf = new RandomAccessFile(file, "rw")) { - byte[] buf = new byte[64]; - int hasRead; - while ((hasRead = raf.read(buf)) > 0) { - if (new String(buf).contains("Copyright")) { - ++unDeal; - System.out.println("未处理文件:" + file.getPath()); - return; - } - // 把原有内容读入临时文件 - tmpOut.write(buf, 0, hasRead); - } - raf.seek(0L); - String tmpl = "/*\n" + - " * The MIT License (MIT)\n" + - " *\n" + - " * Copyright © 2020 xrv \n" + - " *\n" + - " * Permission is hereby granted, free of charge, to any person obtaining a copy\n" + - " * of this software and associated documentation files (the \"Software\"), to deal\n" + - " * in the Software without restriction, including without limitation the rights\n" + - " * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n" + - " * copies of the Software, and to permit persons to whom the Software is\n" + - " * furnished to do so, subject to the following conditions:\n" + - " *\n" + - " * The above copyright notice and this permission notice shall be included in\n" + - " * all copies or substantial portions of the Software.\n" + - " *\n" + - " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" + - " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" + - " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" + - " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" + - " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" + - " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n" + - " * THE SOFTWARE.\n" + - " */\n\n"; - raf.write(tmpl.getBytes()); - // raf.write("/*\n".getBytes()); - // raf.write(Files.readAllBytes(Paths.get(System.getProperty("user.dir") + File.separator + "LICENSE"))); - // raf.write("\n*/\n\n".getBytes()); - - // 追加临时文件内容 - while ((hasRead = tmpIn.read(buf)) > 0) { - raf.write(buf, 0, hasRead); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/ContentReplace2.java b/src/main/java/io/github/ehlxr/ContentReplace2.java deleted file mode 100644 index d3cd21e..0000000 --- a/src/main/java/io/github/ehlxr/ContentReplace2.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -import java.io.*; - -@SuppressWarnings("ALL") -public class ContentReplace2 { - public static void main(String[] args) { - File file = new File("/Users/ehlxr/ehlxr/blog/hugoBlog/content/post"); - File[] files = file.listFiles(); - - for (File f : files) { - operationFile(f); - } - } - - private static void operationFile(File file) { - File tmpfile = new File(file.getParentFile().getAbsolutePath() + "\\" + file.getName() + ".tmp"); - try ( - BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); - BufferedWriter writer = new BufferedWriter(new FileWriter(tmpfile))) { - - boolean flag = false; - String line; - while ((line = reader.readLine()) != null) { - - if (line.startsWith("title")) { - System.out.println(line); - // StringBuilder sb = new StringBuilder(); - // line = sb.append("title: \"").append(line.substring(line.indexOf("title") + 7)).append("\"").toString(); - line = line.replaceAll("'", ""); - System.out.println(line); - - flag = true; - } - writer.write(line + "\n"); - } - - if (flag) { - file.delete(); - tmpfile.renameTo(new File(file.getAbsolutePath())); - } else { - tmpfile.delete(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/io/github/ehlxr/DemoECDSA.java b/src/main/java/io/github/ehlxr/DemoECDSA.java deleted file mode 100644 index 41b795d..0000000 --- a/src/main/java/io/github/ehlxr/DemoECDSA.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -import org.apache.commons.codec.binary.Base64; - -import java.security.*; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -/** - * Created by ehlxr on 2017/8/1. - */ -public class DemoECDSA { - - //摘要 - private static final String strMsg = "hold on"; - - public static void main(String[] args) throws Exception { - jdkECDSA(); - } - - /** - * ECDSA 微软的椭圆曲线算法 jdk1.7以后引入的算法 - * - * @throws Exception - */ - public static void jdkECDSA() throws Exception { - //1.初始化密钥 - KeyPair keyPair = initKey(); - - //2.执行签名(用私钥签名) - ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate(); - byte[] sign = privateKeySign(strMsg, ecPrivateKey); - String signStr = Base64.encodeBase64String(sign); - System.out.println("sign String :" + signStr);//数字签名格式转换,以便报文传输用 - - ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic(); - String publicKeyStr = Base64.encodeBase64String(ecPublicKey.getEncoded()); - System.out.println("publicKeyStr String :" + publicKeyStr);//提供给对端,以便于对端使用公钥验证签名 - - - //3.验证签名(公钥验证签名) - boolean result = publicKeyVerify(Base64.decodeBase64(signStr), Base64.decodeBase64(publicKeyStr)); - System.out.println("JDK DSA verify:" + result); - } - - /** - * 1.初始化密钥,采用ECDSA - * - * @return - * @throws Exception - */ - public static KeyPair initKey() throws Exception { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); - keyPairGenerator.initialize(256); //key长度设置 - KeyPair keyPair = keyPairGenerator.generateKeyPair(); - - return keyPair; - } - - - /** - * 2.执行签名(用私钥签名) - * - * @return - * @throws Exception - */ - public static byte[] privateKeySign(String data, ECPrivateKey ecPrivateKey) throws Exception { - PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded()); - KeyFactory keyFactory = KeyFactory.getInstance("EC"); - PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); - Signature signature = Signature.getInstance("SHA1withECDSA"); - signature.initSign(privateKey); - signature.update(strMsg.getBytes()); - byte[] sign = signature.sign(); - - return sign; - } - - /** - * 3.公钥验证签名(摘要+签名串+公钥) - * - * @throws Exception - */ - public static boolean publicKeyVerify(byte[] sign, byte[] dsaPublicKey) throws Exception { - X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dsaPublicKey); - KeyFactory keyFactory = KeyFactory.getInstance("EC"); - PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); - Signature signature = Signature.getInstance("SHA1withECDSA"); - signature.initVerify(publicKey); - signature.update(strMsg.getBytes()); - boolean result = signature.verify(sign); - - return result; - } - -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/DumpStack.java b/src/main/java/io/github/ehlxr/DumpStack.java deleted file mode 100644 index e8db3b1..0000000 --- a/src/main/java/io/github/ehlxr/DumpStack.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -import java.io.*; -import java.lang.management.*; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * Code which writes a stack dump for all threads to a file. - */ -public class DumpStack { - - // directory where the stack files are written - private static final String STACK_DUMP_DIR = "/var/tmp"; - - // here for testing - public static void main(String[] args) throws Exception { - dumpStacks(); - } - - private static void dumpStacks() throws IOException { - ThreadMXBean mxBean = ManagementFactory.getThreadMXBean(); - MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); - RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); - - - ThreadInfo[] threadInfos = mxBean.getThreadInfo(mxBean.getAllThreadIds(), 0); - Map threadInfoMap = new HashMap<>(); - for (ThreadInfo threadInfo : threadInfos) { - threadInfoMap.put(threadInfo.getThreadId(), threadInfo); - } - - // choose our dump-file - File dumpFile = new File(STACK_DUMP_DIR, "stacks." + System.currentTimeMillis()); - try (Writer writer = new BufferedWriter(new FileWriter(dumpFile))) { - dumpTraces(mxBean, threadInfoMap, writer); - } - } - - private static void dumpTraces(ThreadMXBean mxBean, Map threadInfoMap, Writer writer) - throws IOException { - Map stacks = Thread.getAllStackTraces(); - writer.write("Dump of " + stacks.size() + " thread at " - + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z").format(new Date(System.currentTimeMillis())) + "\n\n"); - for (Map.Entry entry : stacks.entrySet()) { - Thread thread = entry.getKey(); - writer.write("\"" + thread.getName() + "\" prio=" + thread.getPriority() + " tid=" + thread.getId() + " " - + thread.getState() + " " + (thread.isDaemon() ? "deamon" : "worker") + "\n"); - ThreadInfo threadInfo = threadInfoMap.get(thread.getId()); - if (threadInfo != null) { - writer.write(" native=" + threadInfo.isInNative() + ", suspended=" + threadInfo.isSuspended() - + ", block=" + threadInfo.getBlockedCount() + ", wait=" + threadInfo.getWaitedCount() + "\n"); - writer.write(" lock=" + threadInfo.getLockName() + " owned by " + threadInfo.getLockOwnerName() - + " (" + threadInfo.getLockOwnerId() + "), cpu=" - + (mxBean.getThreadCpuTime(threadInfo.getThreadId()) / 1000000L) + ", user=" - + (mxBean.getThreadUserTime(threadInfo.getThreadId()) / 1000000L) + "\n"); - } - for (StackTraceElement element : entry.getValue()) { - writer.write(" "); - writer.write(element.toString()); - writer.write("\n"); - } - writer.write("\n"); - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/FindRequestMapping.java b/src/main/java/io/github/ehlxr/FindRequestMapping.java deleted file mode 100644 index 4f25f22..0000000 --- a/src/main/java/io/github/ehlxr/FindRequestMapping.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -import java.io.*; - - -/** - * @author ehlxr - */ -public class FindRequestMapping { - private static final int total = 0; - private static final int unDeal = 0; - - public static void main(String[] args) throws IOException { - File dir = new File("/Users/ehlxr/WorkSpaces/enncloud/ceres-epns/ceres-epns-web/src/main/java/com/ceres/epns/web"); - deal(dir); - } - - private static void deal(File file) throws IOException { - if (file.isDirectory()) { - File[] fs = file.listFiles(((dir, name) -> { - File f = new File(dir.getPath() + File.separator + name); - - return (f.getPath().contains("src") && name.endsWith(".java")) || f.isDirectory(); - })); - - for (File f : fs != null ? fs : new File[0]) { - deal(f); - } - - } else { - InputStreamReader read = new InputStreamReader(new FileInputStream(file)); - BufferedReader bufferedReader = new BufferedReader(read); - String lineTxt; - - while ((lineTxt = bufferedReader.readLine()) != null) { - if (lineTxt.contains("@RequestMapping")) { - System.out.println(lineTxt); - } - } - bufferedReader.close(); - read.close(); - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/MD2Json.java b/src/main/java/io/github/ehlxr/MD2Json.java deleted file mode 100644 index ee9dd65..0000000 --- a/src/main/java/io/github/ehlxr/MD2Json.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -import net.sf.json.JSONObject; -import org.apache.commons.io.FileUtils; - -import java.io.File; -import java.io.IOException; - -/** - * Created by ehlxr on 2016/11/8. - */ -public class MD2Json { - public static void main(String[] args) throws IOException { - resume(); - } - - private static void resume() throws IOException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("show", 1); - String content = FileUtils.readFileToString(new File("E:\\ehlxr\\Git\\md-files\\resume.md"), "UTF-8"); - jsonObject.put("content", content); - System.out.println(jsonObject.toString()); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/Modify.java b/src/main/java/io/github/ehlxr/Modify.java deleted file mode 100644 index 2d99f19..0000000 --- a/src/main/java/io/github/ehlxr/Modify.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -import java.io.*; - -/* - * 替换文件(如果该文件含有子目录,则包括子目录所有文件)中某个字符串并写入新内容(Java代码实现). - * - *原理:逐行读取源文件的内容,一边读取一边同时写一个*.tmp的文件。 - *当读取的行中发现有需要被替换和改写的目标内容‘行’时候,用新的内容‘行’替换之。 - *最终,删掉源文件,把*.tmp的文件重命名为源文件名字。 - * - *注意!代码功能是逐行读取一个字符串,然后检测该字符串‘行’中是否含有替换的内容,有则用新的字符串‘行’替换源文件中该处整个字符串‘行’。没有则继续读。 - *注意!替换是基于‘行’,逐行逐行的替换! - * - * */ -public class Modify { - - private final String target; - private final String newContent; - private final String path; - - public Modify(String path, String target, String newContent) { - // 操作目录。从该目录开始。该文件目录下及其所有子目录的文件都将被替换。 - this.path = path; - // target:需要被替换、改写的内容。 - this.target = target; - // newContent:需要新写入的内容。 - this.newContent = newContent; - - operation(); - } - - public static void main(String[] args) { - //代码测试:假设有一个test文件夹,test文件夹下含有若干文件或者若干子目录,子目录下可能也含有若干文件或者若干子目录(意味着可以递归操作)。 - //把test目录下以及所有子目录下(如果有)中文件含有"hi"的字符串行替换成新的"hello,world!"字符串行。 - new Modify("/Users/ehlxr/WorkSpaces/budd/src/main/java/me/ehlxr/test.txt", "hi", "hello,world!"); - } - - private void operation() { - File file = new File(path); - opeationDirectory(file); - } - - private void opeationDirectory(File file) { - if (file.isFile()) { - operationFile(file); - } - if (file.isDirectory()) { - File[] files = file.listFiles(); - if (files != null) { - for (File f : files) { - opeationDirectory(f); - } - } - } - - } - - private void operationFile(File file) { - - try { - InputStream is = new FileInputStream(file); - BufferedReader reader = new BufferedReader( - new InputStreamReader(is)); - - String filename = file.getName(); - // tmpfile为缓存文件,代码运行完毕后此文件将重命名为源文件名字。 - File tmpfile = new File(file.getParentFile().getAbsolutePath() + "\\" + filename + ".tmp"); - - BufferedWriter writer = new BufferedWriter(new FileWriter(tmpfile)); - - boolean flag = false; - String str; - while (true) { - str = reader.readLine(); - - if (str == null) - break; - - if (str.contains(target)) { - writer.write(newContent + "\n"); - - flag = true; - } else - writer.write(str + "\n"); - } - - is.close(); - - writer.flush(); - writer.close(); - - if (flag) { - file.delete(); - tmpfile.renameTo(new File(file.getAbsolutePath())); - } else { - tmpfile.delete(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/io/github/ehlxr/PrintMatrixClockWisely.java b/src/main/java/io/github/ehlxr/PrintMatrixClockWisely.java deleted file mode 100644 index b297936..0000000 --- a/src/main/java/io/github/ehlxr/PrintMatrixClockWisely.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -/** - * Created by ehlxr on 2018/2/13. - */ -public class PrintMatrixClockWisely { - /** - * 题目:输入一个矩阵,按照从外向里以顺时针的顺序打印出每一个数字。 - * 思路: - * 循环打印: - * 1:先打印一行(第 1 行肯定会打印) - * 2:再打印当前矩阵的最后一列 - * 3:再倒序打印当前矩阵的最后一行 - * 4:再倒序打印当前矩阵的第一列 - * 起始坐标的规律: - * (0,0),(1,1),(2,2)...(startX,startY), 起始坐标的两个坐标值相等。 - * 并且 startX<= (rows-1)/2,startY<=(columns-1)/2 - * 当前矩阵,第 1 行 坐标 (start,columns-1-start) => (start,endX) - * 当前矩阵,最后 1 列 坐标 (start+1,rows-1-start) => (start+1,endY) - * 当前矩阵,最后 1 行 坐标 (start,columns-1-start+1) => (start,endX-1) - * 当前矩阵,第 1 行 坐标 (start+1,columns-1+1) => (start+1,endY-1) - * - */ - public static void main(String[] args) { - // TODO Auto-generated method stub - // 初始化矩阵 arr[][] - int[][] arr = new int[5][5]; - for (int i = 0; i < arr.length; i++) { - for (int j = 0; j < arr[i].length; j++) { - arr[i][j] = i * arr[i].length + j; - System.out.print(arr[i][j] + " " + '\t'); - } - System.out.println(); - } - System.out.println("顺时针打印矩阵:"); - // 顺时针打印矩阵 arr[][] - printMatrixWisely(arr); - } - - // 循环打印 - private static void printMatrixWisely(int[][] arr) { - if (arr == null || arr.length < 1 || arr[0].length < 1) - return; - int start = 0; - int rows = arr.length; - int columns = arr[0].length; - while (2 * start < columns && 2 * start < rows) { - printMatrix(arr, rows, columns, start); - start++; - } - } - - // 打印一圈 - private static void printMatrix(int[][] arr, int rows, int columns, int start) { - int endX = columns - 1 - start; // 最后一列的列号 - int endY = rows - 1 - start; // 最后一行的行号 - // 打印该圈第一行 - for (int i = start; i <= endX; i++) - System.out.print(arr[start][i] + " "); - // 打印该圈最后一列 (至少是两行) - if (start < endY) - for (int i = start + 1; i <= endY; i++) - System.out.print(arr[i][endX] + " "); - // 打印该圈最后一行 (至少是两行两列) - if ((start < endX) && (start < endY)) - for (int i = endX - 1; i >= start; i--) - System.out.print(arr[endY][i] + " "); - // 打印该圈的第一列 (至少是三行两列) - if ((start < endX) && (start < endY - 1)) - for (int i = endY - 1; i >= start + 1; i--) - System.out.print(arr[i][start] + " "); - } -} diff --git a/src/main/java/io/github/ehlxr/ReferenceCountingGC.java b/src/main/java/io/github/ehlxr/ReferenceCountingGC.java deleted file mode 100644 index 2c6a45a..0000000 --- a/src/main/java/io/github/ehlxr/ReferenceCountingGC.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -/** - * @author ehlxr - * @date 2018/8/21 - */ -public class ReferenceCountingGC { - public Object instance = null; - private static final int _1MB = 1024 * 1024; - /** - * 这个成员属性的唯一意义就是占点内存,以便在能在 GC 日志中看清楚是否有回收过 - */ - private final byte[] bigSize = new byte[2 * _1MB]; - - public static void testGC() { - ReferenceCountingGC objA = new ReferenceCountingGC(); - ReferenceCountingGC objB = new ReferenceCountingGC(); - objA.instance = objB; - objB.instance = objA; - - objA = null; - objB = null; - - // 假设在这行发生 GC,objA 和 objB 是否能被回收? - System.gc(); - } - - public static void main(String[] args) { - testGC(); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/Rename.java b/src/main/java/io/github/ehlxr/Rename.java deleted file mode 100644 index 5a48e14..0000000 --- a/src/main/java/io/github/ehlxr/Rename.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -import java.io.*; - -/** - * @author ehlxr - * @date 2017/3/27 - */ -public class Rename { - public static void main(String[] args) { - File dir = new File("/Users/ehlxr/ehlxr/blog/posts"); - - File[] files = dir.listFiles(); - if (null == files || files.length <= 0) { - System.out.println("sources is null!"); - return; - } - int count = 0; - for (File file : files) { - try { - String oName = file.getName(); - - String date = oName.substring(oName.lastIndexOf("-201") + 1, oName.indexOf(".md")); - String title = oName.substring(0, oName.lastIndexOf("-201")); - - String nName = date + "-" + title + ".md"; - - copyFileUsingFileStreams(file, new File("/Users/ehlxr/Desktop/post/" + nName)); - count++; - } catch (Exception e) { - System.out.println("exce file [ " + file.getName() + " ] error, reason: " + e.getMessage()); - } - } - System.out.println("complete: " + count); - } - - private static void copyFileUsingFileStreams(File source, File dest) - throws IOException { - try (InputStream input = new FileInputStream(source); OutputStream output = new FileOutputStream(dest)) { - byte[] buf = new byte[1024]; - int bytesRead; - while ((bytesRead = input.read(buf)) > 0) { - output.write(buf, 0, bytesRead); - } - } - } -} diff --git a/src/main/java/io/github/ehlxr/SerializeUtil.java b/src/main/java/io/github/ehlxr/SerializeUtil.java deleted file mode 100644 index 769fa4a..0000000 --- a/src/main/java/io/github/ehlxr/SerializeUtil.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -public class SerializeUtil { - /** - * 序列化 - * - * @param object - * @return - */ - public static byte[] serialize(Object object) { - ObjectOutputStream oos = null; - ByteArrayOutputStream baos = null; - try { - // 序列化 - baos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(baos); - oos.writeObject(object); - byte[] bytes = baos.toByteArray(); - return bytes; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 反序列化 - * - * @param bytes - * @return - */ - public static Object unserialize(byte[] bytes) { - ByteArrayInputStream bais = null; - try { - // 反序列化 - bais = new ByteArrayInputStream(bytes); - ObjectInputStream ois = new ObjectInputStream(bais); - return ois.readObject(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/src/main/java/io/github/ehlxr/activemq/JMSConsumer.java b/src/main/java/io/github/ehlxr/activemq/JMSConsumer.java deleted file mode 100644 index 48e7570..0000000 --- a/src/main/java/io/github/ehlxr/activemq/JMSConsumer.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.activemq; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; - -import javax.jms.*; - -/** - * 消息的消费者(接受者) - * Created by ehlxr on 2016-07-11 - */ -public class JMSConsumer { - - private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;//默认连接用户名 - private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认连接密码 - private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;//默认连接地址 - - public static void main(String[] args) { - ConnectionFactory connectionFactory;//连接工厂 - Connection connection = null;//连接 - - Session session;//会话 接受或者发送消息的线程 - Destination destination;//消息的目的地 - - MessageConsumer messageConsumer;//消息的消费者 - - //实例化连接工厂 - connectionFactory = new ActiveMQConnectionFactory(JMSConsumer.USERNAME, JMSConsumer.PASSWORD, JMSConsumer.BROKEURL); - - try { - //通过连接工厂获取连接 - connection = connectionFactory.createConnection(); - //启动连接 - connection.start(); - //创建session - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - //创建一个连接HelloWorld的消息队列 - destination = session.createQueue("HelloWorld"); - //创建消息消费者 - messageConsumer = session.createConsumer(destination); - - while (true) { - TextMessage textMessage = (TextMessage) messageConsumer.receive(100000); - if (textMessage != null) { - System.out.println("收到的消息:" + textMessage.getText()); - } else { - break; - } - } - } catch (JMSException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/activemq/JMSProducer.java b/src/main/java/io/github/ehlxr/activemq/JMSProducer.java deleted file mode 100644 index ce12bce..0000000 --- a/src/main/java/io/github/ehlxr/activemq/JMSProducer.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.activemq; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; - -import javax.jms.*; - -/** - * 消息的生产者(发送者) - * Created by ehlxr on 2016-07-11. - */ -public class JMSProducer { - - //默认连接用户名 - private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; - //默认连接密码 - private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; - //默认连接地址 - private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL; - //发送的消息数量 - private static final int SENDNUM = 10; - - public static void main(String[] args) { - //连接工厂 - ConnectionFactory connectionFactory; - //连接 - Connection connection = null; - //会话 接受或者发送消息的线程 - Session session; - //消息的目的地 - Destination destination; - //消息生产者 - MessageProducer messageProducer; - //实例化连接工厂 - connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL); - - try { - //通过连接工厂获取连接 - connection = connectionFactory.createConnection(); - //启动连接 - connection.start(); - //创建session - session = connection.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE); - //创建一个名称为HelloWorld的消息队列 - destination = session.createQueue("HelloWorld"); - //创建消息生产者 - messageProducer = session.createProducer(destination); - //发送消息 - sendMessage(session, messageProducer); - - session.commit(); - - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (connection != null) { - try { - connection.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } - } - - } - - /** - * 发送消息 - * - * @param session - * @param messageProducer 消息生产者 - * @throws Exception - */ - public static void sendMessage(Session session, MessageProducer messageProducer) throws Exception { - for (int i = 0; i < JMSProducer.SENDNUM; i++) { - //创建一条文本消息 - TextMessage message = session.createTextMessage("ActiveMQ 发送消息" + i); - System.out.println("发送消息:Activemq 发送消息" + i); - //通过消息生产者发出消息 - messageProducer.send(message); - } - - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/annotation/TestPkgAnnotation.java b/src/main/java/io/github/ehlxr/annotation/TestPkgAnnotation.java deleted file mode 100644 index be89bb1..0000000 --- a/src/main/java/io/github/ehlxr/annotation/TestPkgAnnotation.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.annotation; - -import java.lang.annotation.Annotation; - -public class TestPkgAnnotation { - - public static void main(String[] args) { - Package pkg = Package.getPackage("osc.git.eh3.annotation"); - Annotation[] annotations = pkg.getAnnotations(); - for (Annotation annotation : annotations) { - System.out.println(annotation); - } - - // ===========================友好类和包内访问常量============== - new MyPackageMethod().myPackageMethod(); - System.out.println(MyPackageConst.PACKAGE_STRING); - } -} diff --git a/src/main/java/io/github/ehlxr/annotation/package-info.java b/src/main/java/io/github/ehlxr/annotation/package-info.java deleted file mode 100644 index ad5defd..0000000 --- a/src/main/java/io/github/ehlxr/annotation/package-info.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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. - */ - -/** - * @author ehlxr - */ -/** - * @author ehlxr - * - */ -@PkgAnnotation -package io.github.ehlxr.annotation; - -/** - * 包内方法 - */ -class MyPackageMethod { - public void myPackageMethod() { - System.out.println("MyPackageMethod..."); - } -} - -/** - * 包内常量 - */ -class MyPackageConst { - static final java.lang.String PACKAGE_STRING = "myPackageConst"; -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/cache/Cache.java b/src/main/java/io/github/ehlxr/cache/Cache.java deleted file mode 100644 index 72516bb..0000000 --- a/src/main/java/io/github/ehlxr/cache/Cache.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.cache; - -public class Cache { - private String key;// 缓存ID - private Object value;// 缓存数据 - private long timeOut;// 更新时间 - private boolean expired; // 是否终止 - - public Cache() { - super(); - } - - public Cache(String key, Object value, long timeOut, boolean expired) { - this.key = key; - this.value = value; - this.timeOut = timeOut; - this.expired = expired; - } - - public String getKey() { - return key; - } - - public long getTimeOut() { - return timeOut; - } - - public Object getValue() { - return value; - } - - public void setKey(String string) { - key = string; - } - - public void setTimeOut(long l) { - timeOut = l; - } - - public void setValue(Object object) { - value = object; - } - - public boolean isExpired() { - return expired; - } - - public void setExpired(boolean b) { - expired = b; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/cache/CacheManager.java b/src/main/java/io/github/ehlxr/cache/CacheManager.java deleted file mode 100644 index 1410d5f..0000000 --- a/src/main/java/io/github/ehlxr/cache/CacheManager.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.cache; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - -public class CacheManager { - private static final HashMap cacheMap = new HashMap(); - - // 单实例构造方法 - private CacheManager() { - super(); - } - - // 得到缓存。同步静态方法 - private synchronized static Cache getCache(String key) { - return (Cache) cacheMap.get(key); - } - - // 判断是否存在一个缓存 - private synchronized static boolean hasCache(String key) { - return cacheMap.containsKey(key); - } - - // 清除所有缓存 - public synchronized static void clearAll() { - cacheMap.clear(); - } - - // 清除某一类特定缓存,通过遍历HASHMAP下的所有对象,来判断它的KEY与传入的TYPE是否匹配 - public synchronized static void clearAll(String type) { - Iterator> i = cacheMap.entrySet().iterator(); - String key; - ArrayList arr = new ArrayList(); - try { - while (i.hasNext()) { - Entry entry = i.next(); - key = entry.getKey(); - if (key.startsWith(type)) { // 如果匹配则删除掉 - arr.add(key); - } - } - for (int k = 0; k < arr.size(); k++) { - clearOnly(arr.get(k)); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - // 清除指定的缓存 - public synchronized static void clearOnly(String key) { - cacheMap.remove(key); - } - - // 载入缓存 - public synchronized static void putCache(String key, Cache obj) { - cacheMap.put(key, obj); - } - - // 获取缓存信息 - public static Cache getCacheInfo(String key) { - if (hasCache(key)) { - Cache cache = getCache(key); - if (cacheExpired(cache)) { // 调用判断是否终止方法 - cache.setExpired(true); - } - return cache; - } else { - return null; - } - } - - // 载入缓存信息 - public static void putCacheInfo(String key, Cache obj, long dt, boolean expired) { - Cache cache = new Cache(); - cache.setKey(key); - cache.setTimeOut(dt + System.currentTimeMillis()); // 设置多久后更新缓存 - cache.setValue(obj); - cache.setExpired(expired); // 缓存默认载入时,终止状态为FALSE - cacheMap.put(key, cache); - } - - // 重写载入缓存信息方法 - public static void putCacheInfo(String key, Cache obj, long dt) { - Cache cache = new Cache(); - cache.setKey(key); - cache.setTimeOut(dt + System.currentTimeMillis()); - cache.setValue(obj); - cache.setExpired(false); - cacheMap.put(key, cache); - } - - // 判断缓存是否终止 - public static boolean cacheExpired(Cache cache) { - if (null == cache) { // 传入的缓存不存在 - return false; - } - long nowDt = System.currentTimeMillis(); // 系统当前的毫秒数 - long cacheDt = cache.getTimeOut(); // 缓存内的过期毫秒数 - // 过期时间小于等于零时,或者过期时间大于当前时间时,则为FALSE - // 大于过期时间 即过期 - return cacheDt > 0 && cacheDt <= nowDt; - } - - // 获取缓存中的大小 - public static int getCacheSize() { - return cacheMap.size(); - } - - // 获取指定的类型的大小 - public static int getCacheSize(String type) { - int k = 0; - Iterator> i = cacheMap.entrySet().iterator(); - String key; - try { - while (i.hasNext()) { - Entry entry = i.next(); - key = entry.getKey(); - if (key.indexOf(type) != -1) { // 如果匹配则删除掉 - k++; - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - - return k; - } - - // 获取缓存对象中的所有键值名称 - public static ArrayList getCacheAllkey() { - ArrayList a = new ArrayList(); - try { - Iterator> i = cacheMap.entrySet().iterator(); - while (i.hasNext()) { - Entry entry = i.next(); - a.add(entry.getKey()); - } - } catch (Exception ex) { - } - return a; - } - - // 获取缓存对象中指定类型 的键值名称 - public static ArrayList getCacheListkey(String type) { - ArrayList a = new ArrayList(); - String key; - try { - Iterator> i = cacheMap.entrySet().iterator(); - while (i.hasNext()) { - Entry entry = i.next(); - key = entry.getKey(); - if (key.indexOf(type) != -1) { - a.add(key); - } - } - } catch (Exception ex) { - } - return a; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/cache/SimpleCache.java b/src/main/java/io/github/ehlxr/cache/SimpleCache.java deleted file mode 100644 index 8bb677b..0000000 --- a/src/main/java/io/github/ehlxr/cache/SimpleCache.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.cache; - -import java.util.Map; -import java.util.WeakHashMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -public final class SimpleCache { - - private final Lock lock = new ReentrantLock(); - private final int maxCapacity; - private final Map eden; - private final Map perm; - - public SimpleCache(int maxCapacity) { - this.maxCapacity = maxCapacity; - this.eden = new ConcurrentHashMap(maxCapacity); - this.perm = new WeakHashMap(maxCapacity); - } - - public V get(K k) { - V v = this.eden.get(k); - if (v == null) { - lock.lock(); - try { - v = this.perm.get(k); - } finally { - lock.unlock(); - } - if (v != null) { - this.eden.put(k, v); - } - } - return v; - } - - public void put(K k, V v) { - if (this.eden.size() >= maxCapacity) { - lock.lock(); - try { - this.perm.putAll(this.eden); - } finally { - lock.unlock(); - } - this.eden.clear(); - } - this.eden.put(k, v); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/cache/SimpleCacheUtil.java b/src/main/java/io/github/ehlxr/cache/SimpleCacheUtil.java deleted file mode 100644 index eff235d..0000000 --- a/src/main/java/io/github/ehlxr/cache/SimpleCacheUtil.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.cache; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -public class SimpleCacheUtil { - private final Map m_objects; - private final Map m_expiredObjects; - private final long m_lExpireTime; - private final ExecutorService m_executor; - - public SimpleCacheUtil() { - this(500); - } - - public SimpleCacheUtil(final int nExpireTime) { - m_objects = Collections.synchronizedMap(new HashMap()); - m_expiredObjects = Collections.synchronizedMap(new HashMap()); - m_lExpireTime = nExpireTime; - m_executor = Executors.newFixedThreadPool(256); - Executors.newScheduledThreadPool(5).scheduleWithFixedDelay(RemoveExpiredObjects(), m_lExpireTime / 2, m_lExpireTime, - TimeUnit.SECONDS); - } - - private final Runnable RemoveExpiredObjects() { - return new Runnable() { - public void run() { - for (final String name : m_expiredObjects.keySet()) { - if (System.currentTimeMillis() > m_expiredObjects.get(name)) { - m_executor.execute(CreateRemoveRunnable(name)); - } - } - } - }; - } - - private final Runnable CreateRemoveRunnable(final String name) { - return new Runnable() { - public void run() { - m_objects.remove(name); - m_expiredObjects.remove(name); - } - }; - } - - public long getExpireTime() { - return m_lExpireTime; - } - - public void put(final String name, final T obj) { - put(name, obj, m_lExpireTime); - } - - public void put(final String name, final T obj, final long expireTime) { - m_objects.put(name, obj); - m_expiredObjects.put(name, System.currentTimeMillis() + expireTime * 1000); - } - - public T get(final String name) { - final Long expireTime = m_expiredObjects.get(name); - if (expireTime == null) - return null; - if (System.currentTimeMillis() > expireTime) { - m_executor.execute(CreateRemoveRunnable(name)); - return null; - } - return m_objects.get(name); - } - - @SuppressWarnings("unchecked") - public R get(final String name, final Class type) { - return (R) get(name); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/cache/Test.java b/src/main/java/io/github/ehlxr/cache/Test.java deleted file mode 100644 index 88cfa78..0000000 --- a/src/main/java/io/github/ehlxr/cache/Test.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.cache; - -public class Test { - - public static void main(String[] args) { - SimpleCacheUtil cache2 = new SimpleCacheUtil<>(5); - cache2.put("123", "fdfd"); - - System.out.println(cache2.get("123")); - } -} diff --git a/src/main/java/io/github/ehlxr/cache/TestCache.java b/src/main/java/io/github/ehlxr/cache/TestCache.java deleted file mode 100644 index 95c5dfc..0000000 --- a/src/main/java/io/github/ehlxr/cache/TestCache.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.cache; - -import java.util.ArrayList; - -public class TestCache { - public static void main(String[] args) { - CacheManager.putCache("abc", new Cache("key", "value", 10, false)); - CacheManager.putCache("def", new Cache()); - CacheManager.putCache("ccc", new Cache()); - CacheManager.clearOnly(""); - Cache c = new Cache(); - for (int i = 0; i < 10; i++) { - CacheManager.putCache("" + i, c); - } - CacheManager.putCache("aaaaaaaa", c); - CacheManager.putCache("abchcy;alskd", c); - CacheManager.putCache("cccccccc", c); - CacheManager.putCache("abcoqiwhcy", c); - System.out.println("删除前的大小:" + CacheManager.getCacheSize()); - ArrayList cacheAllkey = CacheManager.getCacheAllkey(); - for (String key : cacheAllkey) { - System.out.println(key + ":" + CacheManager.getCacheInfo(key).getValue()); - } - CacheManager.clearAll("aaaa"); - System.out.println("删除后的大小:" + CacheManager.getCacheSize()); - cacheAllkey = CacheManager.getCacheAllkey(); - for (String key : cacheAllkey) { - System.out.println(key); - } - } -} diff --git a/src/main/java/io/github/ehlxr/cache/TestFutureCahe.java b/src/main/java/io/github/ehlxr/cache/TestFutureCahe.java deleted file mode 100644 index 7ab36ec..0000000 --- a/src/main/java/io/github/ehlxr/cache/TestFutureCahe.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.cache; - -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Future; -import java.util.concurrent.FutureTask; - -/** - * Created by ehlxr on 2017/4/11. - */ -public class TestFutureCahe { - private final ConcurrentHashMap> cacheMap = new ConcurrentHashMap<>(); - - public static void main(String[] args) { - final TestFutureCahe TestGuaVA = new TestFutureCahe(); - - Thread t1 = new Thread(new Runnable() { - @Override - public void run() { - - System.out.println("T1======start========"); - Object value = TestGuaVA.getCache("key", "T1"); - System.out.println("T1 value==============" + value); - System.out.println("T1======end========"); - - } - }); - - Thread t2 = new Thread(new Runnable() { - @Override - public void run() { - System.out.println("T2======start========"); - Object value = TestGuaVA.getCache("key", "T2"); - System.out.println("T2 value==============" + value); - System.out.println("T2======end========"); - - } - }); - - Thread t3 = new Thread(new Runnable() { - @Override - public void run() { - System.out.println("T3======start========"); - Object value = TestGuaVA.getCache("key", "T3"); - System.out.println("T3 value==============" + value); - System.out.println("T3======end========"); - - } - }); - - t1.start(); - t2.start(); - t3.start(); - - } - - public Object getCache(K keyValue, String ThreadName) { - Future value = null; - try { - System.out.println("ThreadName getCache==============" + ThreadName); - //从缓存获取数据 - value = cacheMap.get(keyValue); - //如果没有的话,把数据放到缓存 - if (value == null) { - value = putCache(keyValue, ThreadName); - return value.get(); - } - return value.get(); - - } catch (Exception e) { - } - return null; - } - - public Future putCache(K keyValue, final String ThreadName) { - // //把数据放到缓存 - Future value = null; - Callable callable = new Callable() { - @SuppressWarnings("unchecked") - @Override - public V call() throws Exception { - //可以根据业务从数据库获取等取得数据,这边就模拟已经获取数据了 - System.out.println("ThreadName 执行业务数据并返回处理结果的数据(访问数据库等)==============" + ThreadName); - return (V) "dataValue"; - } - }; - FutureTask futureTask = new FutureTask(callable); - value = cacheMap.putIfAbsent(keyValue, futureTask); - if (value == null) { - value = futureTask; - futureTask.run(); - } - return value; - } - -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/datastructure/linkedlist/DoubleLinkedListDemo.java b/src/main/java/io/github/ehlxr/datastructure/linkedlist/DoubleLinkedListDemo.java deleted file mode 100644 index d6db5bd..0000000 --- a/src/main/java/io/github/ehlxr/datastructure/linkedlist/DoubleLinkedListDemo.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.datastructure.linkedlist; - -/** - * @author ehlxr - * @since 2021-04-04 14:19. - */ -public class DoubleLinkedListDemo { - public static void main(String[] args) { - HeroNode2 hero1 = new HeroNode2(1, "宋江", "及时雨"); - HeroNode2 hero2 = new HeroNode2(3, "卢俊义", "玉麒麟"); - HeroNode2 hero3 = new HeroNode2(5, "吴用", "智多星"); - HeroNode2 hero4 = new HeroNode2(8, "林冲", "豹子头"); - - DoubleLinkedList doubleLinkedList = new DoubleLinkedList(); - doubleLinkedList.addByOrder(hero1); - doubleLinkedList.addByOrder(hero2); - doubleLinkedList.addByOrder(hero3); - doubleLinkedList.addByOrder(hero4); - - doubleLinkedList.list(); - - doubleLinkedList.update(new HeroNode2(3, "小卢", "玉麒麟--")); - System.out.println("修改后的结果"); - doubleLinkedList.list(); - - doubleLinkedList.del(3); - System.out.println("删除后的结果"); - doubleLinkedList.list(); - } -} - -/** - * 双向链表 - */ -class DoubleLinkedList { - private final HeroNode2 head = new HeroNode2(0, "", ""); - - public HeroNode2 getHead() { - return head; - } - - public void list() { - HeroNode2 temp = head.next; - while (temp != null) { - System.out.println(temp); - temp = temp.next; - } - } - - public void add(HeroNode2 heroNode) { - HeroNode2 temp = head; - while (temp.next != null) { - temp = temp.next; - } - temp.next = heroNode; - heroNode.pre = temp; - } - - public void addByOrder(HeroNode2 heroNode) { - HeroNode2 temp = head; - while (true) { - if (temp.next == null) { - break; - } - - // 找到需要插入位置的前一个节点 - if (temp.next.no > heroNode.no) { - break; - } - - temp = temp.next; - } - - heroNode.next = temp.next; - heroNode.pre = temp; - - if (temp.next != null) { - temp.next.pre = heroNode; - } - temp.next = heroNode; - } - - public void update(HeroNode2 newHeroNode) { - HeroNode2 temp = head.next; - if (temp == null) { - System.out.println("链表为空!"); - } - - while (true) { - if (temp == null) { - System.out.printf("没找到 %d 的节点\n", newHeroNode.no); - break; - } - - if (temp.no == newHeroNode.no) { - temp.name = newHeroNode.name; - temp.nickname = newHeroNode.nickname; - - break; - } - - temp = temp.next; - } - } - - public void del(int no) { - HeroNode2 temp = head.next; - if (temp == null) { - System.out.println("链表为空!"); - } - - while (true) { - if (temp == null) { - System.out.printf("没找到要删除的 %d 节点\n", no); - break; - } - - // 找到待删除节点 - if (temp.no == no) { - temp.pre.next = temp.next; - if (temp.next != null) { - temp.next.pre = temp.pre; - } - break; - } - - temp = temp.next; - } - } -} - -/** - * 定义HeroNode , 每个HeroNode 对象就是一个节点 - */ -class HeroNode2 { - public int no; - public String name; - public String nickname; - public HeroNode2 next; //指向下一个节点 - public HeroNode2 pre;// 指向上一个节点 - - public HeroNode2(int no, String name, String nickname) { - this.no = no; - this.name = name; - this.nickname = nickname; - } - - /** - * 为了显示方法,我们重新 toString - */ - @Override - public String toString() { - return "HeroNode2 [no=" + no + ", name=" + name + ", nickname=" + nickname + "]"; - } - -} diff --git a/src/main/java/io/github/ehlxr/datastructure/linkedlist/Josephu.java b/src/main/java/io/github/ehlxr/datastructure/linkedlist/Josephu.java deleted file mode 100644 index 2e52f14..0000000 --- a/src/main/java/io/github/ehlxr/datastructure/linkedlist/Josephu.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.datastructure.linkedlist; - -/** - * @author ehlxr - * @since 2021-04-09 21:14. - */ -public class Josephu { - public static void main(String[] args) { - CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList(); - circleSingleLinkedList.addBoy(5); - circleSingleLinkedList.show(); - - circleSingleLinkedList.countBoy(1, 2, 5); - } -} - -/** - * 循环单向链表 - */ -class CircleSingleLinkedList { - private Boy first = null; - - public void addBoy(int nums) { - if (nums < 1) { - return; - } - Boy curBoy = null; - for (int i = 1; i <= nums; i++) { - Boy boy = new Boy(i); - if (i == 1) { - first = boy; - curBoy = first; - first.setNext(first); - } else { - curBoy.setNext(boy); - boy.setNext(first); - curBoy = boy; - } - } - } - - public void show() { - if (first == null) { - System.out.println("没有boy"); - return; - } - - Boy curBoy = first; - while (true) { - System.out.printf("boy no %d\n", curBoy.getNo()); - if (curBoy.getNext() == first) { - break; - } - - curBoy = curBoy.getNext(); - } - } - - public void countBoy(int startNo, int countNum, int size) { - if (first == null || startNo > size || startNo < 1) { - return; - } - - // 找到最后一个节点 - Boy helper = first; - while (true) { - if (helper.getNext() == first) { - break; - } - helper = helper.getNext(); - } - - // 找到开始报数的位置 - for (int i = 0; i < startNo - 1; i++) { - helper = helper.getNext(); - first = first.getNext(); - } - - while (true) { - if (helper == first) { - break; - } - - for (int i = 0; i < countNum - 1; i++) { - helper = helper.getNext(); - first = first.getNext(); - } - System.out.printf("出圈的小孩 %d\n", first.getNo()); - - first = first.getNext(); - helper.setNext(first); - } - System.out.printf("最后出圈的小孩 %d\n", first.getNo()); - } -} - -class Boy { - private int no; - private Boy next; - - public Boy(int no) { - this.no = no; - } - - public int getNo() { - return no; - } - - public void setNo(int no) { - this.no = no; - } - - public Boy getNext() { - return next; - } - - public void setNext(Boy next) { - this.next = next; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/datastructure/linkedlist/SingleLinkedListDemo.java b/src/main/java/io/github/ehlxr/datastructure/linkedlist/SingleLinkedListDemo.java deleted file mode 100644 index 0a72300..0000000 --- a/src/main/java/io/github/ehlxr/datastructure/linkedlist/SingleLinkedListDemo.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.datastructure.linkedlist; - -import java.util.Stack; - -/** - * @author ehlxr - * @since 2021-04-04 14:19. - */ -public class SingleLinkedListDemo { - public static void main(String[] args) { - HeroNode hero1 = new HeroNode(1, "宋江", "及时雨"); - HeroNode hero2 = new HeroNode(3, "卢俊义", "玉麒麟"); - HeroNode hero3 = new HeroNode(5, "吴用", "智多星"); - HeroNode hero4 = new HeroNode(8, "林冲", "豹子头"); - - SingleLinkedList singleLinkedList = new SingleLinkedList(); - - // 加入 - // singleLinkedList.add(hero1); - // singleLinkedList.add(hero4); - // singleLinkedList.add(hero2); - // singleLinkedList.add(hero3); - - singleLinkedList.addByOrder(hero1); - singleLinkedList.addByOrder(hero4); - singleLinkedList.addByOrder(hero2); - singleLinkedList.addByOrder(hero3); - singleLinkedList.list(); - - // 反转链表 - // reverseList(singleLinkedList.getHead()); - // System.out.println("反转之后的链表"); - // singleLinkedList.list(); - // - // HeroNode newHeroNode = new HeroNode(3, "小吴", "智多星.."); - // singleLinkedList.update(newHeroNode); - // System.out.println("修改后的链表"); - // singleLinkedList.list(); - // - // singleLinkedList.del(3); - // System.out.println("删除 no 为 3 的节点"); - // singleLinkedList.list(); - - SingleLinkedList singleLinkedList2 = new SingleLinkedList(); - singleLinkedList2.addByOrder(new HeroNode(2, "2", "2")); - singleLinkedList2.addByOrder(new HeroNode(3, "3", "3")); - singleLinkedList2.addByOrder(new HeroNode(8, "8", "8")); - singleLinkedList2.addByOrder(new HeroNode(9, "9", "9")); - singleLinkedList2.list(); - - bind2(singleLinkedList.getHead(), singleLinkedList2.getHead()); - - } - - /** - * 反转链表 - */ - public static void reverseList(HeroNode head) { - HeroNode pre = null; - HeroNode cur = head.next; - while (cur != null) { - HeroNode next = cur.next; - - cur.next = pre; - - pre = cur; - - cur = next; - } - - head.next = pre; - } - - /** - * 合并有序链表 - */ - public static void bind2(HeroNode node1, HeroNode node2) { - Stack stack = new Stack<>(); - - HeroNode cur = node1.next; - while (cur != null) { - stack.push(cur); - cur = cur.next; - } - - cur = node2.next; - while (cur != null) { - stack.push(cur); - cur = cur.next; - } - - SingleLinkedList result = new SingleLinkedList(); - for (HeroNode node : stack) { - result.addByOrder(node); - } - - // 打印结果 - System.out.println("合并结果"); - result.list(); - } - - /** - * 合并有序链表 - */ - public static void bind(HeroNode node1, HeroNode node2) { - SingleLinkedList result = new SingleLinkedList(); - - if (node1.next == null) { - result.add(node2.next); - return; - } - if (node2.next == null) { - result.add(node1.next); - return; - } - while (node1.next != null || node2.next != null) { - HeroNode temp = null; - if (node1.next == null) { - result.add(node2.next); - break; - } - if (node2.next == null) { - result.add(node1.next); - break; - } - - if (node1.next.no < node2.next.no) { - temp = node1.next; - node1.next = node1.next.next; - } else { - temp = node2.next; - node2.next = node2.next.next; - } - - temp.next = null; - result.add(temp); - } - - // 打印结果 - System.out.println("合并结果"); - result.list(); - } -} - -class SingleLinkedList { - private final HeroNode head = new HeroNode(0, "", ""); - - public HeroNode getHead() { - return head; - } - - public void list() { - HeroNode temp = head.next; - while (temp != null) { - System.out.println(temp); - temp = temp.next; - } - } - - public void add(HeroNode heroNode) { - HeroNode temp = head; - while (temp.next != null) { - temp = temp.next; - } - temp.next = heroNode; - } - - public void addByOrder(HeroNode heroNode) { - HeroNode temp = head; - while (true) { - if (temp.next == null) { - break; - } - - // 找到需要插入位置的前一个节点 - if (temp.next.no > heroNode.no) { - break; - } - - temp = temp.next; - } - - heroNode.next = temp.next; - temp.next = heroNode; - } - - public void update(HeroNode newHeroNode) { - HeroNode temp = head.next; - if (temp == null) { - System.out.println("链表为空!"); - } - - while (true) { - if (temp == null) { - System.out.printf("没找到 %d 的节点\n", newHeroNode.no); - break; - } - - if (temp.no == newHeroNode.no) { - temp.name = newHeroNode.name; - temp.nickname = newHeroNode.nickname; - - break; - } - - temp = temp.next; - } - } - - public void del(int no) { - HeroNode temp = head; - if (temp.next == null) { - System.out.println("链表为空!"); - } - - while (true) { - if (temp.next == null) { - System.out.printf("没找到要删除的 %d 节点\n", no); - break; - } - - // 找到待删除节点的前一个节点 - if (temp.next.no == no) { - temp.next = temp.next.next; - - break; - } - - temp = temp.next; - } - } -} - -/** - * 定义HeroNode , 每个HeroNode 对象就是一个节点 - */ -class HeroNode { - public int no; - public String name; - public String nickname; - public HeroNode next; //指向下一个节点 - - // 构造器 - public HeroNode(int no, String name, String nickname) { - this.no = no; - this.name = name; - this.nickname = nickname; - } - - /** - * 为了显示方法,我们重新 toString - */ - @Override - public String toString() { - return "HeroNode [no=" + no + ", name=" + name + ", nickname=" + nickname + "]"; - } - -} diff --git a/src/main/java/io/github/ehlxr/datastructure/queue/ArrayQueueDemo.java b/src/main/java/io/github/ehlxr/datastructure/queue/ArrayQueueDemo.java deleted file mode 100644 index 6288964..0000000 --- a/src/main/java/io/github/ehlxr/datastructure/queue/ArrayQueueDemo.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.datastructure.queue; - -import java.util.Scanner; - -/** - * 使用数组模拟队列 - * - * @author ehlxr - * @since 2021-03-30 22:26. - */ -public class ArrayQueueDemo { - public static void main(String[] args) { - //测试一把 - //创建一个队列 - ArrayQueue queue = new ArrayQueue(3); - char key; //接收用户输入 - Scanner scanner = new Scanner(System.in);// - boolean loop = true; - //输出一个菜单 - while (loop) { - System.out.println("s(show): 显示队列"); - System.out.println("e(exit): 退出程序"); - System.out.println("a(add): 添加数据到队列"); - System.out.println("g(get): 从队列取出数据"); - System.out.println("h(head): 查看队列头的数据"); - key = scanner.next().charAt(0);//接收一个字符 - switch (key) { - case 's': - queue.showQueue(); - break; - case 'a': - System.out.println("输出一个数"); - int value = scanner.nextInt(); - queue.addQueue(value); - break; - case 'g': //取出数据 - try { - int res = queue.getQueue(); - System.out.printf("取出的数据是%d\n", res); - } catch (Exception e) { - // TODO: handle exception - System.out.println(e.getMessage()); - } - break; - case 'h': //查看队列头的数据 - try { - int res = queue.headQueue(); - System.out.printf("队列头的数据是%d\n", res); - } catch (Exception e) { - // TODO: handle exception - System.out.println(e.getMessage()); - } - break; - case 'e': //退出 - scanner.close(); - loop = false; - break; - default: - break; - } - } - - System.out.println("程序退出~~"); - - } -} - -class ArrayQueue { - private final int maxSize; // 表示数组的最大容量 - private int front; // 队列头 - private int rear; // 队列尾 - private final int[] arr; // 该数据用于存放数据, 模拟队列 - - // 创建队列的构造器 - public ArrayQueue(int maxSize) { - this.maxSize = maxSize; - this.arr = new int[maxSize]; - } - - // 判断队列是否满 - public boolean isFull() { - return rear == maxSize; - } - - // 判断队列是否为空 - public boolean isEmpty() { - return rear == front; - } - - // 添加数据到队列 - public void addQueue(int n) { - if (isFull()) { - System.out.println("队列已满,无法添加数据!"); - return; - } - - arr[rear++] = n; - } - - // 获取队列的数据, 出队列 - public int getQueue() { - if (isEmpty()) { - throw new RuntimeException("队列为空,无法获取数据!"); - } - - return arr[front++]; - } - - // 显示队列的所有数据 - public void showQueue() { - if (isEmpty()) { - System.out.println("队列为空!"); - return; - } - - for (int i = front; i < rear; i++) { - System.out.printf("arr[%d]=%d\n", i, arr[i]); - } - } - - // 显示队列的头数据, 注意不是取出数据 - public int headQueue() { - if (isEmpty()) { - throw new RuntimeException("队列为空,无法获取数据!"); - } - - return arr[front]; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/datastructure/queue/CircleArrayQueueDemo.java b/src/main/java/io/github/ehlxr/datastructure/queue/CircleArrayQueueDemo.java deleted file mode 100644 index 0a2419d..0000000 --- a/src/main/java/io/github/ehlxr/datastructure/queue/CircleArrayQueueDemo.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.datastructure.queue; - -import java.util.Scanner; - -/** - * @author ehlxr - * @since 2021-03-30 22:52. - */ -public class CircleArrayQueueDemo { - public static void main(String[] args) { - //创建一个环形队列 - CircleArrayQueue queue = new CircleArrayQueue(3); - char key; //接收用户输入 - Scanner scanner = new Scanner(System.in); - boolean loop = true; - //输出一个菜单 - while (loop) { - System.out.println("s(show): 显示队列"); - System.out.println("e(exit): 退出程序"); - System.out.println("a(add): 添加数据到队列"); - System.out.println("g(get): 从队列取出数据"); - System.out.println("h(head): 查看队列头的数据"); - key = scanner.next().charAt(0);//接收一个字符 - switch (key) { - case 's': - queue.showQueue(); - break; - case 'a': - System.out.println("输出一个数"); - int value = scanner.nextInt(); - queue.addQueue(value); - break; - case 'g': //取出数据 - try { - int res = queue.getQueue(); - System.out.printf("取出的数据是%d\n", res); - } catch (Exception e) { - // TODO: handle exception - System.out.println(e.getMessage()); - } - break; - case 'h': //查看队列头的数据 - try { - int res = queue.headQueue(); - System.out.printf("队列头的数据是%d\n", res); - } catch (Exception e) { - // TODO: handle exception - System.out.println(e.getMessage()); - } - break; - case 'e': //退出 - scanner.close(); - loop = false; - break; - default: - break; - } - } - - System.out.println("程序退出~~"); - - } -} - -class CircleArrayQueue { - private final int maxSize; // 表示数组的最大容量 - private int front; // 队列头 - private int rear; // 队列尾 - private final int[] arr; // 该数据用于存放数据, 模拟队列 - - // 创建队列的构造器 - public CircleArrayQueue(int maxSize) { - this.maxSize = maxSize; - this.arr = new int[maxSize]; - } - - // 判断队列是否满 - public boolean isFull() { - return rear - front == maxSize; - // return (rear + 1) % maxSize == front; - } - - // 判断队列是否为空 - public boolean isEmpty() { - return rear == front; - } - - // 添加数据到队列 - public void addQueue(int n) { - if (isFull()) { - System.out.println("队列已满,无法添加数据!"); - return; - } - - arr[(rear++) % maxSize] = n; - } - - // 获取队列的数据, 出队列 - public int getQueue() { - if (isEmpty()) { - throw new RuntimeException("队列为空,无法获取数据!"); - } - int tem = arr[front % maxSize]; - front++; - return tem; - } - - // 显示队列的所有数据 - public void showQueue() { - if (isEmpty()) { - System.out.println("队列为空!"); - return; - } - - for (int i = front; i < rear; i++) { - System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]); - } - } - - // 显示队列的头数据, 注意不是取出数据 - public int headQueue() { - if (isEmpty()) { - throw new RuntimeException("队列为空,无法获取数据!"); - } - - return arr[front]; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/datastructure/stack/LinkedListStackDemo.java b/src/main/java/io/github/ehlxr/datastructure/stack/LinkedListStackDemo.java deleted file mode 100644 index 5924b4c..0000000 --- a/src/main/java/io/github/ehlxr/datastructure/stack/LinkedListStackDemo.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021 xrv - * - * 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 io.github.ehlxr.datastructure.stack; - -import java.util.Scanner; - -/** - * @author ehlxr - * @since 2021-04-15 22:18. - */ -public class LinkedListStackDemo { - public static void main(String[] args) { - LinkedListStack2 stack = new LinkedListStack2(4); - String key; - boolean loop = true; //控制是否退出菜单 - Scanner scanner = new Scanner(System.in); - - while (loop) { - System.out.println("show: 表示显示栈"); - System.out.println("exit: 退出程序"); - System.out.println("push: 表示添加数据到栈(入栈)"); - System.out.println("pop: 表示从栈取出数据(出栈)"); - System.out.println("请输入你的选择"); - key = scanner.next(); - switch (key) { - case "show": - stack.list(); - break; - case "push": - System.out.println("请输入一个数"); - int value = scanner.nextInt(); - stack.push(value); - break; - case "pop": - try { - int res = stack.pop(); - System.out.printf("出栈的数据是 %d\n", res); - } catch (Exception e) { - // TODO: handle exception - System.out.println(e.getMessage()); - } - break; - case "exit": - scanner.close(); - loop = false; - break; - default: - break; - } - } - - System.out.println("程序退出~~~"); - } - -} - -/** - * 栈顶是链表的最后一个节点 - */ -class LinkedListStack { - private final int maxSize; - private int top = -1; - private final Node head = new Node(0); - - public LinkedListStack(int maxSize) { - this.maxSize = maxSize; - } - - public boolean isFull() { - return maxSize == top + 1; - } - - public boolean isEmpty() { - return top == -1; - } - - public void push(int value) { - if (isFull()) { - System.out.println("栈满"); - return; - } - Node temp = head; - while (true) { - if (temp.next == null) { - temp.next = new Node(value); - top++; - break; - } - temp = temp.next; - } - } - - public int pop() { - if (isEmpty()) { - throw new RuntimeException("栈空"); - } - - Node temp = head; - while (true) { - // if (temp.next == null) { - // throw new RuntimeException("栈空~~~"); - // } - if (temp.next.next == null) { - top--; - int id = temp.next.id; - temp.next = null; - return id; - } - temp = temp.next; - } - } - - public void list() { - if (isEmpty()) { - System.out.println("栈空"); - return; - } - - revert(); - - Node temp = head.next; - while (temp != null) { - System.out.println(temp); - - temp = temp.next; - } - - revert(); - - } - - /** - * 反转单向链表 - */ - private void revert() { - Node pre = null; - Node cur = head.next; - while (cur != null) { - Node next = cur.next; - cur.next = pre; - pre = cur; - cur = next; - } - - head.next = pre; - } -} - -/** - * 栈底是链表的最后一个节点 - */ -class LinkedListStack2 { - private final Node head = new Node(0); - private final int maxSize; - private int top = -1; - - public LinkedListStack2(int maxSize) { - this.maxSize = maxSize; - } - - public boolean isEmpty() { - return top == -1; - } - - public boolean isFull() { - return top == maxSize - 1; - } - - /** - * 入栈:插入新元素到链表第一个节点 - */ - public void push(int id) { - if (isFull()) { - System.out.println("栈满"); - return; - } - Node newNode = new Node(id); - - Node temp = head.next; - head.next = newNode; - newNode.next = temp; - top++; - } - - /** - * 出栈:取出链表第一个元素 - */ - public int pop() { - if (isEmpty()) { - throw new RuntimeException("栈空,无法取出数据"); - } - - Node temp = head.next; - - head.next = temp.next; - top--; - - return temp.id; - } - - public void list() { - if (isEmpty()) { - System.out.println("栈空,无数据"); - } - - Node temp = head.next; - while (temp != null) { - System.out.println(temp); - - temp = temp.next; - } - } -} - -class Node { - public int id; - public Node next; - - public Node(int id) { - this.id = id; - } - - @Override - public String toString() { - return "Node{" + id + "}"; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/date/Main.java b/src/main/java/io/github/ehlxr/date/Main.java deleted file mode 100644 index 0b3bbfc..0000000 --- a/src/main/java/io/github/ehlxr/date/Main.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.date; - -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -/** - * @author ehlxr - * @since 2021-01-28 16:03. - */ -public class Main { - public static void main(String[] args) { - // 旧 API 转新 API - // Date -> Instant: - Instant ins1 = new Date().toInstant(); - System.out.println(ins1); - - ZonedDateTime zonedDateTime = ins1.atZone(ZoneId.systemDefault()); - System.out.println(zonedDateTime); - - LocalDateTime localDateTime = zonedDateTime.toLocalDateTime(); - System.out.println(localDateTime); - - // Calendar -> Instant -> ZonedDateTime: - Calendar calendar = Calendar.getInstance(); - Instant ins2 = calendar.toInstant(); - ZonedDateTime zdt = ins2.atZone(calendar.getTimeZone().toZoneId()); - System.out.println(zdt); - - // 新 API 转旧 API - // ZonedDateTime -> long: - ZonedDateTime zdt1 = ZonedDateTime.now(); - long ts = zdt1.toEpochSecond() * 1000; - - // long -> Date: - Date date = new Date(ts); - - // long -> Calendar: - Calendar calendar1 = Calendar.getInstance(); - calendar1.clear(); - calendar1.setTimeZone(TimeZone.getTimeZone(zdt.getZone().getId())); - calendar1.setTimeInMillis(zdt.toEpochSecond() * 1000); - - - // 在数据库中存储时间戳时,尽量使用 long 型时间戳,它具有省空间,效率高,不依赖数据库的优点 - ts = 1574208900000L; - System.out.println(timestampToString(ts, Locale.CHINA, "Asia/Shanghai")); - System.out.println(timestampToString(ts, Locale.US, "America/New_York")); - } - - /** - * 不同用户以不同的偏好来显示不同的本地时间 - */ - static String timestampToString(long epochMilli, Locale lo, String zoneId) { - Instant ins = Instant.ofEpochMilli(epochMilli); - DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT) - // 按照 Locale 默认习惯格式化 - .withLocale(lo); - - return f.withLocale(lo).format(ZonedDateTime.ofInstant(ins, ZoneId.of(zoneId))); - } -} diff --git a/src/main/java/io/github/ehlxr/dfd.java b/src/main/java/io/github/ehlxr/dfd.java deleted file mode 100644 index 134a594..0000000 --- a/src/main/java/io/github/ehlxr/dfd.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr; - -/** - * Created by ehlxr on 2016/12/23. - */ -public class dfd { - - public static void main(String[] args) { - // var map = Maps.newHashMap(); - // map.put("d", 1); - // System.out.println(map); - } - - public void printCircle(int[][] matrix, int startX, int startY, int endX, int endY) { - // only one column left - if (startY == endY) { - for (int i = startX; i <= endX; i++) { - System.out.println(matrix[i][endY]); - } - return; - } - // only one row left - if (startX == endX) { - for (int i = startY; i <= endY; i++) { - System.out.println(matrix[startX][i]); - } - return; - } - for (int i = startY; i < endY; i++) { - System.out.println(matrix[startX][i]); - } - for (int i = startX; i < endX; i++) { - System.out.println(matrix[i][endY]); - } - for (int i = endY; i > startY; i--) { - System.out.println(matrix[endX][i]); - } - for (int i = endX; i > startX; i--) { - System.out.println(matrix[i][startY]); - } - - } - - public void printMatrix(int[][] matrix) { - - if (matrix == null) { - return; - } - int startX = 0; - int startY = 0; - int endY = matrix[0].length - 1; - int endX = matrix.length - 1; - - while ((startX <= endX) && (startY <= endY)) { - printCircle(matrix, startX, startY, endX, endY); - startX++; - startY++; - endX--; - endY--; - } - } -} diff --git a/src/main/java/io/github/ehlxr/extension/ExtensionLoader.java b/src/main/java/io/github/ehlxr/extension/ExtensionLoader.java deleted file mode 100644 index 05f963c..0000000 --- a/src/main/java/io/github/ehlxr/extension/ExtensionLoader.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.extension; - -import io.netty.util.internal.StringUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.regex.Pattern; - -/** - * 加载和管理扩展(简化版 Dubbo SPI) - * - * @author ehlxr - */ -@SuppressWarnings("unused") -public class ExtensionLoader { - private static final Logger logger = LoggerFactory.getLogger(ExtensionLoader.class); - - private static final String EXTENSIONS_DIRECTORY = "META-INF/extensions/"; - private static final String EXTENSIONS_INTERNAL_DIRECTORY = "META-INF/extensions/internal/"; - - private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*,+\\s*"); - - private static final ConcurrentMap, ExtensionLoader> EXTENSION_LOADERS = new ConcurrentHashMap<>(); - private static final ConcurrentMap, Object> EXTENSION_INSTANCES = new ConcurrentHashMap<>(); - - private final Class type; - private final ConcurrentMap> cachedInstances = new ConcurrentHashMap<>(); - private final ConcurrentMap, String> cachedNames = new ConcurrentHashMap<>(); - private final Holder>> cachedClasses = new Holder<>(); - private final Map exceptions = new ConcurrentHashMap<>(); - private String defaultExtension; - - private ExtensionLoader(Class type) { - this.type = type; - } - - /** - * {@link ExtensionLoader} 的工厂方法。 - * - * @param type 扩展点接口类型 - * @param 扩展点类型 - * @return {@link ExtensionLoader} 实例 - * @throws IllegalArgumentException 参数为 null; - * 或是扩展点接口上没有 {@link SPI} 注解。 - */ - @SuppressWarnings("unchecked") - public static ExtensionLoader getExtensionLoader(Class type) { - if (type == null) { - throw new IllegalArgumentException("SPI type == null"); - } - if (!type.isInterface()) { - throw new IllegalArgumentException("SPI type(" + type.getName() + ") is not interface!"); - } - if (!type.isAnnotationPresent(SPI.class)) { - throw new IllegalArgumentException("type(" + type.getName() + - ") is not a extension, because WITHOUT @SPI Annotation!"); - } - - ExtensionLoader loader = (ExtensionLoader) EXTENSION_LOADERS.get(type); - if (loader == null) { - EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<>(type)); - loader = (ExtensionLoader) EXTENSION_LOADERS.get(type); - } - return loader; - } - - /** - * Get the String of Throwable, like the output of {@link Throwable#printStackTrace()}. - * - * @param throwable the input throwable. - */ - private static String throwable2String(Throwable throwable) { - StringWriter w = new StringWriter(1024); - try (PrintWriter p = new PrintWriter(w)) { - throwable.printStackTrace(p); - return w.toString(); - } - } - - public T getExtension(String name) { - if (StringUtil.isNullOrEmpty(name)) { - throw new IllegalArgumentException("SPI name == null"); - } - - Holder holder = cachedInstances.get(name); - if (holder == null) { - cachedInstances.putIfAbsent(name, new Holder<>()); - holder = cachedInstances.get(name); - } - - Object instance = holder.get(); - if (instance == null) { - synchronized (cachedInstances) { - instance = holder.get(); - if (instance == null) { - instance = createExtension(name); - holder.set(instance); - } - } - } - //noinspection unchecked - return (T) instance; - } - - /** - * 返回缺省的扩展。 - * - * @throws IllegalStateException 指定的扩展没有设置缺省扩展点 - */ - public T getDefaultExtension() { - loadExtensionClasses0(); - - if (null == defaultExtension || defaultExtension.length() == 0) { - throw new IllegalStateException("No default extension on extension " + type.getName()); - } - return getExtension(defaultExtension); - } - - /** - * 获取扩展点实现的所有扩展点名。 - * - * @since 0.1.0 - */ - public Set getSupportedExtensions() { - Map> classes = getExtensionClasses(); - return Collections.unmodifiableSet(new HashSet<>(classes.keySet())); - } - - public String getExtensionName(Class spi) { - getExtensionClasses(); - return cachedNames.get(spi); - } - - private T createExtension(String name) { - Class clazz = getExtensionClasses().get(name); - if (clazz == null) { - throw findExtensionClassLoadException(name); - } - try { - //noinspection unchecked - T instance = (T) EXTENSION_INSTANCES.get(clazz); - if (instance == null) { - EXTENSION_INSTANCES.putIfAbsent(clazz, clazz.newInstance()); - //noinspection unchecked - instance = (T) EXTENSION_INSTANCES.get(clazz); - } - - return instance; - } catch (Throwable t) { - throw new IllegalStateException("SPI instance(name: " + name + ", class: " + - type + ") could not be instantiated: " + t.getMessage(), t); - } - } - - private Map> getExtensionClasses() { - Map> classes = cachedClasses.get(); - if (classes == null) { - synchronized (cachedClasses) { - classes = cachedClasses.get(); - if (classes == null) { - loadExtensionClasses0(); - classes = cachedClasses.get(); - } - } - } - return classes; - } - - private IllegalStateException findExtensionClassLoadException(String name) { - for (Map.Entry entry : exceptions.entrySet()) { - if (entry.getKey().toLowerCase().contains(name.toLowerCase())) { - return entry.getValue(); - } - } - - int i = 1; - StringBuilder buf = new StringBuilder("No such extension " + type.getName() + " by name " + name); - for (Map.Entry entry : exceptions.entrySet()) { - if (i == 1) { - buf.append(", possible causes: "); - } - - buf.append("\r\n("); - buf.append(i++); - buf.append(") "); - buf.append(entry.getKey()); - buf.append(":\r\n"); - buf.append(throwable2String(entry.getValue())); - } - return new IllegalStateException(buf.toString()); - } - - private void loadExtensionClasses0() { - final SPI annotation = type.getAnnotation(SPI.class); - if (annotation != null) { - String value = annotation.value(); - if ((value = value.trim()).length() > 0) { - String[] names = NAME_SEPARATOR.split(value); - if (names.length > 1) { - throw new IllegalStateException("more than 1 default extension name on extension " + - type.getName() + ": " + Arrays.toString(names)); - } - if (names.length == 1 && names[0].trim().length() > 0) { - defaultExtension = names[0].trim(); - } - } - } - - Map> extensionClasses = new HashMap<>(); - loadFile(extensionClasses, EXTENSIONS_DIRECTORY); - loadFile(extensionClasses, EXTENSIONS_INTERNAL_DIRECTORY); - cachedClasses.set(extensionClasses); - } - - private void loadFile(Map> extensionClasses, String dir) { - String fileName = dir + type.getName(); - try { - Enumeration urls; - ClassLoader classLoader = ExtensionLoader.class.getClassLoader(); - if (classLoader != null) { - urls = classLoader.getResources(fileName); - } else { - urls = ClassLoader.getSystemResources(fileName); - } - - if (urls != null) { - while (urls.hasMoreElements()) { - URL url = urls.nextElement(); - - try ( - BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) - ) { - String line; - while ((line = reader.readLine()) != null) { - // delete comments - final int ci = line.indexOf('#'); - if (ci >= 0) { - line = line.substring(0, ci); - } - line = line.trim(); - if (line.length() == 0) { - continue; - } - - try { - String name = null; - int i = line.indexOf('='); - - if (i > 0) { - name = line.substring(0, i).trim(); - line = line.substring(i + 1).trim(); - } - - if (line.length() > 0) { - Class clazz = Class.forName(line, true, classLoader).asSubclass(type); - if (!type.isAssignableFrom(clazz)) { - throw new IllegalStateException("Error when load extension class(interface: " + - type.getName() + ", class line: " + clazz.getName() + "), class " - + clazz.getName() + "is not subtype of interface."); - } - - if (name == null || name.length() == 0) { - // clazz: xxx.xxx.ZfyAPI - // type: xxx.xxx.API - // -> name: zfy - if (clazz.getSimpleName().length() > type.getSimpleName().length() - && clazz.getSimpleName().endsWith(type.getSimpleName())) { - name = clazz.getSimpleName().substring(0, clazz.getSimpleName().length() - - type.getSimpleName().length()).toLowerCase(); - } else { - throw new IllegalStateException("No such extension name for the class " - + clazz.getName() + " in the config " + url); - } - } - - - if (!cachedNames.containsKey(clazz)) { - cachedNames.put(clazz, name); - } - - Class c = extensionClasses.get(name); - if (c == null) { - extensionClasses.put(name, clazz); - } else if (c != clazz) { - throw new IllegalStateException("Duplicate extension " - + type.getName() + " name " + name + " on " + c.getName() - + " and " + clazz.getName()); - } - } - } catch (Throwable t) { - IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " - + type + ", class line: " + line + ") in " + url + ", cause: " + t.getMessage(), t); - exceptions.put(line, e); - } - } - } catch (Throwable t) { - logger.error("Exception when load extension class(interface: " + - type + ", class file: " + url + ") in " + url, t); - } - } - } - } catch (Throwable t) { - logger.error("Exception when load extension class(interface: " + - type + ", description file: " + fileName + ").", t); - } - } - - @Override - public String toString() { - return this.getClass().getName() + "[" + type.getName() + "]"; - } - - /** - * Holds a value of type T. - */ - @SuppressWarnings("unused") - private static final class Holder { - /** - * The value contained in the holder. - */ - private volatile T value; - - /** - * Creates a new holder with a null value. - */ - Holder() { - } - - /** - * Create a new holder with the specified value. - * - * @param value The value to be stored in the holder. - */ - public Holder(T value) { - this.value = value; - } - - public T get() { - return value; - } - - public void set(T value) { - this.value = value; - } - } -} diff --git a/src/main/java/io/github/ehlxr/extension/SPI.java b/src/main/java/io/github/ehlxr/extension/SPI.java deleted file mode 100644 index e88ece2..0000000 --- a/src/main/java/io/github/ehlxr/extension/SPI.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.extension; - -import java.lang.annotation.*; - -/** - * 把一个接口标识成扩展点。 - *

- * 没有此注释的接口 {@link ExtensionLoader} 会拒绝接管 - * - * @author ehlxr - * @see ExtensionLoader - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface SPI { - - /** - * the default extension name. - */ - String value() default ""; -} diff --git a/src/main/java/io/github/ehlxr/forkjoin/Main.java b/src/main/java/io/github/ehlxr/forkjoin/Main.java deleted file mode 100644 index 8d36eab..0000000 --- a/src/main/java/io/github/ehlxr/forkjoin/Main.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.forkjoin; - -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.RecursiveTask; -import java.util.stream.IntStream; - -/** - * @author ehlxr - * @since 2020-12-30 17:59. - */ -public class Main { - - public static void main(String[] args) { - ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors()); - - // Future future = forkJoinPool.submit(new RecursiveTaskDemo(arr, 0, arr.length)); - // System.out.println("计算出来的总和="+future.get()); - - - int[] arr = IntStream.range(0, 1000).toArray(); - Integer integer = forkJoinPool.invoke(new RecursiveTaskDemo(arr, 0, arr.length)); - System.out.println("计算出来的总和=" + integer); - - // 关闭线程池 - forkJoinPool.shutdown(); - - System.out.println(IntStream.range(0, 1000).parallel().reduce((i, j) -> i + j)); - System.out.println(IntStream.range(0, 1000).parallel().reduce(Integer::sum)); - System.out.println(IntStream.range(0, 1000).parallel().sum()); - } - - static class RecursiveTaskDemo extends RecursiveTask { - /** - * 每个"小任务"最多只打印70个数 - */ - private static final int MAX = 100; - private static final long serialVersionUID = -134954066152987391L; - private final int[] arr; - private final int start; - private final int end; - - public RecursiveTaskDemo(int[] arr, int start, int end) { - this.arr = arr; - this.start = start; - this.end = end; - } - - @Override - protected Integer compute() { - int sum = 0; - // 当end-start的值小于MAX时候,开始打印 - if ((end - start) < MAX) { - for (int i = start; i < end; i++) { - sum += arr[i]; - } - return sum; - } else { - System.err.println("=====任务分解======"); - // 将大任务分解成两个小任务 - int middle = (start + end) / 2; - RecursiveTaskDemo left = new RecursiveTaskDemo(arr, start, middle); - RecursiveTaskDemo right = new RecursiveTaskDemo(arr, middle, end); - // 并行执行两个小任务 - left.fork(); - right.fork(); - // 把两个小任务累加的结果合并起来 - return left.join() + right.join(); - } - } - - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/hashing/Cluster.java b/src/main/java/io/github/ehlxr/hashing/Cluster.java deleted file mode 100644 index 9849cdc..0000000 --- a/src/main/java/io/github/ehlxr/hashing/Cluster.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hashing; - -public class Cluster { - private static final int SERVER_SIZE_MAX = 1024; - - private final Server[] servers = new Server[SERVER_SIZE_MAX]; - private int size = 0; - - public void put(Entry e) { - int index = e.hashCode() % size; - servers[index].put(e); - } - - public Entry get(Entry e) { - int index = e.hashCode() % size; - return servers[index].get(e); - } - - public boolean addServer(Server s) { - if (size >= SERVER_SIZE_MAX) - return false; - - servers[size++] = s; - return true; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/hashing/Entry.java b/src/main/java/io/github/ehlxr/hashing/Entry.java deleted file mode 100644 index e9a67bc..0000000 --- a/src/main/java/io/github/ehlxr/hashing/Entry.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hashing; - -public class Entry { - private final String key; - - Entry(String key) { - this.key = key; - } - - @Override - public String toString() { - return key; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/hashing/Main.java b/src/main/java/io/github/ehlxr/hashing/Main.java deleted file mode 100644 index bf2d3a0..0000000 --- a/src/main/java/io/github/ehlxr/hashing/Main.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hashing; - -public class Main { - - public static void main(String[] args) { - Cluster c = createCluster(); - - Entry[] entries = { - new Entry("i"), - new Entry("have"), - new Entry("a"), - new Entry("pen"), - new Entry("an"), - new Entry("apple"), - new Entry("applepen"), - new Entry("pineapple"), - new Entry("pineapplepen"), - new Entry("PPAP") - }; - - for (Entry e : entries) { - c.put(e); - } - - c.addServer(new Server("192.168.0.6")); - - findEntries(c, entries); - - } - - private static Cluster createCluster() { - Cluster c = new Cluster(); - c.addServer(new Server("192.168.0.0")); - c.addServer(new Server("192.168.0.1")); - c.addServer(new Server("192.168.0.2")); - c.addServer(new Server("192.168.0.3")); - c.addServer(new Server("192.168.0.4")); - c.addServer(new Server("192.168.0.5")); - return c; - } - - private static void findEntries(Cluster c, Entry[] entries) { - for (Entry e : entries) { - if (e == c.get(e)) { - System.out.println("重新找到了entry:" + e); - } else { - System.out.println("entry已失效:" + e); - } - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/hashing/Server.java b/src/main/java/io/github/ehlxr/hashing/Server.java deleted file mode 100644 index a962a4b..0000000 --- a/src/main/java/io/github/ehlxr/hashing/Server.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hashing; - -import java.util.HashMap; -import java.util.Map; - -public class Server { - private final String name; - private final Map entries; - - Server(String name) { - this.name = name; - entries = new HashMap<>(); - } - - public void put(Entry e) { - entries.put(e, e); - } - - public Entry get(Entry e) { - return entries.get(e); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/hashing/consistent/Cluster.java b/src/main/java/io/github/ehlxr/hashing/consistent/Cluster.java deleted file mode 100644 index 59a2f7c..0000000 --- a/src/main/java/io/github/ehlxr/hashing/consistent/Cluster.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hashing.consistent; - -import java.util.SortedMap; -import java.util.TreeMap; - -public class Cluster { - private static final int SERVER_SIZE_MAX = 1024; - - private final SortedMap servers = new TreeMap<>(); - private int size = 0; - - public void put(Entry e) { - routeServer(e.hashCode()).put(e); - } - - public Entry get(Entry e) { - return routeServer(e.hashCode()).get(e); - } - - public Server routeServer(int hash) { - if (servers.isEmpty()) - return null; - - if (!servers.containsKey(hash)) { - SortedMap tailMap = servers.tailMap(hash); - hash = tailMap.isEmpty() ? servers.firstKey() : tailMap.firstKey(); - // hash = servers.firstKey(); - } - return servers.get(hash); - } - - public boolean addServer(Server s) { - if (size >= SERVER_SIZE_MAX) - return false; - - servers.put(s.hashCode(), s); - - size++; - return true; - } -} diff --git a/src/main/java/io/github/ehlxr/hashing/consistent/Entry.java b/src/main/java/io/github/ehlxr/hashing/consistent/Entry.java deleted file mode 100644 index 6bafb27..0000000 --- a/src/main/java/io/github/ehlxr/hashing/consistent/Entry.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hashing.consistent; - -public class Entry { - private final String key; - - Entry(String key) { - this.key = key; - } - - @Override - public String toString() { - return key; - } - - public int hashCode() { - return key.hashCode(); - } -} diff --git a/src/main/java/io/github/ehlxr/hashing/consistent/Main.java b/src/main/java/io/github/ehlxr/hashing/consistent/Main.java deleted file mode 100644 index 0ae1141..0000000 --- a/src/main/java/io/github/ehlxr/hashing/consistent/Main.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hashing.consistent; - -public class Main { - public static void main(String[] args) { - Cluster c = createCluster(); - - Entry[] entries = { - new Entry("i"), - new Entry("have"), - new Entry("a"), - new Entry("pen"), - new Entry("an"), - new Entry("apple"), - new Entry("applepen"), - new Entry("pineapple"), - new Entry("pineapplepen"), - new Entry("PPAP") - }; - - for (Entry e : entries) { - c.put(e); - } - - c.addServer(new Server("achuguniadsfaang")); - findEntries(c, entries); - - } - - private static Cluster createCluster() { - Cluster c = new Cluster(); - c.addServer(new Server("international")); - c.addServer(new Server("china")); - c.addServer(new Server("japanjapan")); - c.addServer(new Server("Amarica")); - c.addServer(new Server("samsungtsisger")); - c.addServer(new Server("achuguniang")); - return c; - } - - private static void findEntries(Cluster c, Entry[] entries) { - for (Entry e : entries) { - if (e == c.get(e)) { - System.out.println("重新找到了entry: " + e); - } else { - System.out.println("entry已失效: " + e); - } - } - } -} diff --git a/src/main/java/io/github/ehlxr/hashing/consistent/Server.java b/src/main/java/io/github/ehlxr/hashing/consistent/Server.java deleted file mode 100644 index 85bd436..0000000 --- a/src/main/java/io/github/ehlxr/hashing/consistent/Server.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hashing.consistent; - -import java.util.HashMap; -import java.util.Map; - -public class Server { - private final String name; - private final Map entries; - - Server(String name) { - this.name = name; - entries = new HashMap<>(); - } - - public void put(Entry e) { - entries.put(e, e); - } - - public Entry get(Entry e) { - return entries.get(e); - } - - public int hashCode() { - return name.hashCode(); - } - -} diff --git a/src/main/java/io/github/ehlxr/hbase/HBaseUtils.java b/src/main/java/io/github/ehlxr/hbase/HBaseUtils.java deleted file mode 100644 index 3f42e7a..0000000 --- a/src/main/java/io/github/ehlxr/hbase/HBaseUtils.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hbase; - -import io.github.ehlxr.utils.Pair; -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.hbase.HBaseConfiguration; -import org.apache.hadoop.hbase.HColumnDescriptor; -import org.apache.hadoop.hbase.HTableDescriptor; -import org.apache.hadoop.hbase.TableName; -import org.apache.hadoop.hbase.client.*; -import org.apache.hadoop.hbase.filter.FilterList; -import org.apache.hadoop.hbase.util.Bytes; - -import java.io.IOException; -import java.util.List; - -/** - * @author ehlxr - */ -public class HBaseUtils { - private static Connection connection; - - static { - Configuration configuration = HBaseConfiguration.create(); - configuration.set("hbase.zookeeper.property.clientPort", "2181"); - // 如果是集群 则主机名用逗号分隔 - configuration.set("hbase.zookeeper.quorum", "127.0.0.1"); - // configuration.set("hbase.master", "127.0.0.1:16000"); - try { - connection = ConnectionFactory.createConnection(configuration); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 创建 HBase 表 - * - * @param tableName 表名 - * @param columnFamilies 列族的数组 - */ - public static boolean createTable(String tableName, List columnFamilies) { - try { - HBaseAdmin admin = (HBaseAdmin) connection.getAdmin(); - if (admin.tableExists(tableName)) { - return false; - } - HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName)); - columnFamilies.forEach(columnFamily -> { - HColumnDescriptor columnDescriptor = new HColumnDescriptor(columnFamily); - columnDescriptor.setMaxVersions(1); - tableDescriptor.addFamily(columnDescriptor); - }); - admin.createTable(tableDescriptor); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - return true; - } - - - /** - * 删除 hBase 表 - * - * @param tableName 表名 - */ - public static boolean deleteTable(String tableName) { - try { - HBaseAdmin admin = (HBaseAdmin) connection.getAdmin(); - // 删除表前需要先禁用表 - admin.disableTable(tableName); - admin.deleteTable(tableName); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - return true; - } - - /** - * 插入数据 - * - * @param tableName 表名 - * @param rowKey 唯一标识 - * @param columnFamilyName 列族名 - * @param qualifier 列标识 - * @param value 数据 - */ - public static boolean putRow(String tableName, String rowKey, String columnFamilyName, String qualifier, - String value) { - try { - Table table = connection.getTable(TableName.valueOf(tableName)); - Put put = new Put(Bytes.toBytes(rowKey)); - put.addColumn(Bytes.toBytes(columnFamilyName), Bytes.toBytes(qualifier), Bytes.toBytes(value)); - table.put(put); - table.close(); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - return true; - } - - - /** - * 插入数据 - * - * @param tableName 表名 - * @param rowKey 唯一标识 - * @param columnFamilyName 列族名 - * @param pairList 列标识和值的集合 - */ - public static boolean putRow(String tableName, String rowKey, String columnFamilyName, List> pairList) { - try { - Table table = connection.getTable(TableName.valueOf(tableName)); - Put put = new Put(Bytes.toBytes(rowKey)); - pairList.forEach(pair -> put.addColumn(Bytes.toBytes(columnFamilyName), Bytes.toBytes(pair.getKey()), Bytes.toBytes(pair.getValue()))); - table.put(put); - table.close(); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - return true; - } - - - /** - * 根据 rowKey 获取指定行的数据 - * - * @param tableName 表名 - * @param rowKey 唯一标识 - */ - public static Result getRow(String tableName, String rowKey) { - try { - Table table = connection.getTable(TableName.valueOf(tableName)); - Get get = new Get(Bytes.toBytes(rowKey)); - return table.get(get); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - - /** - * 获取指定行指定列 (cell) 的最新版本的数据 - * - * @param tableName 表名 - * @param rowKey 唯一标识 - * @param columnFamily 列族 - * @param qualifier 列标识 - */ - public static String getCell(String tableName, String rowKey, String columnFamily, String qualifier) { - try { - Table table = connection.getTable(TableName.valueOf(tableName)); - Get get = new Get(Bytes.toBytes(rowKey)); - if (!get.isCheckExistenceOnly()) { - get.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(qualifier)); - Result result = table.get(get); - byte[] resultValue = result.getValue(Bytes.toBytes(columnFamily), Bytes.toBytes(qualifier)); - return Bytes.toString(resultValue); - } else { - return null; - } - - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - - /** - * 检索全表 - * - * @param tableName 表名 - */ - public static ResultScanner getScanner(String tableName) { - try { - Table table = connection.getTable(TableName.valueOf(tableName)); - Scan scan = new Scan(); - return table.getScanner(scan); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - - /** - * 检索表中指定数据 - * - * @param tableName 表名 - * @param filterList 过滤器 - */ - - public static ResultScanner getScanner(String tableName, FilterList filterList) { - try { - Table table = connection.getTable(TableName.valueOf(tableName)); - Scan scan = new Scan(); - scan.setFilter(filterList); - return table.getScanner(scan); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * 检索表中指定数据 - * - * @param tableName 表名 - * @param startRowKey 起始 RowKey - * @param endRowKey 终止 RowKey - * @param filterList 过滤器 - */ - - public static ResultScanner getScanner(String tableName, String startRowKey, String endRowKey, - FilterList filterList) { - try { - Table table = connection.getTable(TableName.valueOf(tableName)); - Scan scan = new Scan(); - scan.setStartRow(Bytes.toBytes(startRowKey)); - scan.setStopRow(Bytes.toBytes(endRowKey)); - scan.setFilter(filterList); - return table.getScanner(scan); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * 删除指定行记录 - * - * @param tableName 表名 - * @param rowKey 唯一标识 - */ - public static boolean deleteRow(String tableName, String rowKey) { - try { - Table table = connection.getTable(TableName.valueOf(tableName)); - Delete delete = new Delete(Bytes.toBytes(rowKey)); - table.delete(delete); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - return true; - } - - - /** - * 删除指定行的指定列 - * - * @param tableName 表名 - * @param rowKey 唯一标识 - * @param familyName 列族 - * @param qualifier 列标识 - */ - public static boolean deleteColumn(String tableName, String rowKey, String familyName, - String qualifier) { - try { - Table table = connection.getTable(TableName.valueOf(tableName)); - Delete delete = new Delete(Bytes.toBytes(rowKey)); - delete.addColumn(Bytes.toBytes(familyName), Bytes.toBytes(qualifier)); - table.delete(delete); - table.close(); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - return true; - } - -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/hbase/Main.java b/src/main/java/io/github/ehlxr/hbase/Main.java deleted file mode 100644 index 40e6a5c..0000000 --- a/src/main/java/io/github/ehlxr/hbase/Main.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.hbase; - -import io.github.ehlxr.utils.Pair; -import org.apache.hadoop.hbase.client.Result; -import org.apache.hadoop.hbase.client.ResultScanner; -import org.apache.hadoop.hbase.filter.CompareFilter; -import org.apache.hadoop.hbase.filter.FilterList; -import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; -import org.apache.hadoop.hbase.util.Bytes; - -import java.util.Arrays; -import java.util.List; - -/** - * @author ehlxr - * @since 2020/2/26. - */ -public class Main { - private static final String TABLE_NAME = "class"; - private static final String TEACHER = "teacher"; - private static final String STUDENT = "student"; - - public static void main(String[] args) { - createTable(); - insertData(); - getScanner(); - // deleteTable(); - } - - - private static void createTable() { - // 新建表 - List columnFamilies = Arrays.asList(TEACHER, STUDENT); - boolean table = HBaseUtils.createTable(TABLE_NAME, columnFamilies); - System.out.println("表创建结果:" + table); - } - - private static void insertData() { - List> pairs1 = Arrays.asList(new Pair<>("name", "Tom"), - new Pair<>("age", "22"), - new Pair<>("gender", "1")); - HBaseUtils.putRow(TABLE_NAME, "rowKey1", STUDENT, pairs1); - - List> pairs2 = Arrays.asList(new Pair<>("name", "Jack"), - new Pair<>("age", "33"), - new Pair<>("gender", "2")); - HBaseUtils.putRow(TABLE_NAME, "rowKey2", STUDENT, pairs2); - - List> pairs3 = Arrays.asList(new Pair<>("name", "Mike"), - new Pair<>("age", "44"), - new Pair<>("gender", "1")); - HBaseUtils.putRow(TABLE_NAME, "rowKey3", STUDENT, pairs3); - } - - - private static void getRow() { - Result result = HBaseUtils.getRow(TABLE_NAME, "rowKey1"); - if (result != null) { - System.out.println(Bytes - .toString(result.getValue(Bytes.toBytes(STUDENT), Bytes.toBytes("name")))); - } - - } - - private static void getCell() { - String cell = HBaseUtils.getCell(TABLE_NAME, "rowKey2", STUDENT, "age"); - System.out.println("cell age :" + cell); - - } - - private static void getScanner() { - ResultScanner scanner = HBaseUtils.getScanner(TABLE_NAME); - if (scanner != null) { - scanner.forEach(result -> System.out.println(Bytes.toString(result.getRow()) + "->" + Bytes - .toString(result.getValue(Bytes.toBytes(STUDENT), Bytes.toBytes("name"))))); - scanner.close(); - } - } - - - private static void getScannerWithFilter() { - FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL); - SingleColumnValueFilter nameFilter = new SingleColumnValueFilter(Bytes.toBytes(STUDENT), - Bytes.toBytes("name"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes("Jack")); - filterList.addFilter(nameFilter); - ResultScanner scanner = HBaseUtils.getScanner(TABLE_NAME, filterList); - if (scanner != null) { - scanner.forEach(result -> System.out.println(Bytes.toString(result.getRow()) + "->" + Bytes - .toString(result.getValue(Bytes.toBytes(STUDENT), Bytes.toBytes("name"))))); - scanner.close(); - } - } - - private static void deleteColumn() { - boolean b = HBaseUtils.deleteColumn(TABLE_NAME, "rowKey2", STUDENT, "age"); - System.out.println("删除结果: " + b); - } - - private static void deleteRow() { - boolean b = HBaseUtils.deleteRow(TABLE_NAME, "rowKey2"); - System.out.println("删除结果: " + b); - } - - private static void deleteTable() { - boolean b = HBaseUtils.deleteTable(TABLE_NAME); - System.out.println("删除结果: " + b); - } -} diff --git a/src/main/java/io/github/ehlxr/http/Main.java b/src/main/java/io/github/ehlxr/http/Main.java deleted file mode 100644 index 7deb58c..0000000 --- a/src/main/java/io/github/ehlxr/http/Main.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.http; - -import java.io.IOException; -import java.net.URI; -// import java.net.http.HttpClient; -// import java.net.http.HttpRequest; -// import java.net.http.HttpResponse; -import java.time.Duration; - -/** - * @author ehlxr - * @since 2021-01-31 20:54. - */ -public class Main { - public static void main(String[] args) throws IOException, InterruptedException { - - // HttpClient client = HttpClient.newBuilder() - // .version(HttpClient.Version.HTTP_1_1) - // .followRedirects(HttpClient.Redirect.NORMAL) - // .connectTimeout(Duration.ofSeconds(20)) - // // .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80))) - // // .authenticator(Authenticator.getDefault()) - // .build(); - // - // HttpRequest request = HttpRequest.newBuilder() - // .uri(URI.create("https://ehlxr.me/")) - // .timeout(Duration.ofMinutes(2)) - // .header("Content-Type", "application/json") - // .GET() - // // .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("file.json"))) - // .build(); - // - // // Synchronous Example - // // HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - // // System.out.println(response.statusCode()); - // // System.out.println(response.body()); - // - // - // // Asynchronous Example - // - // client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) - // .thenApply(HttpResponse::body) - // .thenAccept(body -> System.out.println("response body is:\n" + body)) - // .join(); - - } -} diff --git a/src/main/java/io/github/ehlxr/io/BioServer.java b/src/main/java/io/github/ehlxr/io/BioServer.java deleted file mode 100644 index 27b9595..0000000 --- a/src/main/java/io/github/ehlxr/io/BioServer.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.io; - -import org.apache.commons.io.IOUtils; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.nio.charset.StandardCharsets; - -/** - * @author ehlxr - * @since 2021-01-23 20:07. - */ -public class BioServer { - public static void main(String[] args) throws IOException { - ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); - - // 监听 8080 端口进来的 TCP 链接 - serverSocketChannel.socket().bind(new InetSocketAddress(8080)); - - //noinspection InfiniteLoopStatement - while (true) { - // 这里会阻塞,直到有一个请求的连接进来 - SocketChannel socketChannel = serverSocketChannel.accept(); - - // 开启一个新的线程来处理这个请求,然后在 while 循环中继续监听 8080 端口 - SocketHandler handler = new SocketHandler(socketChannel); - //noinspection AlibabaAvoidManuallyCreateThread - new Thread(handler).start(); - } - } - - static class SocketHandler implements Runnable { - private final SocketChannel socketChannel; - - public SocketHandler(SocketChannel socketChannel) { - this.socketChannel = socketChannel; - } - - @Override - public void run() { - - ByteBuffer buffer = ByteBuffer.allocate(1024); - try { - // 将请求数据读入 Buffer 中 - int num; - while ((num = socketChannel.read(buffer)) > 0) { - // 读取 Buffer 内容之前先 flip 一下 - buffer.flip(); - - // 提取 Buffer 中的数据 - byte[] bytes = new byte[num]; - buffer.get(bytes); - - String re = new String(bytes, StandardCharsets.UTF_8); - System.out.println("收到请求:" + re); - - // 回应客户端 - ByteBuffer writeBuffer = ByteBuffer.wrap(("我已经收到你的请求,你的请求内容是:" + re).getBytes()); - socketChannel.write(writeBuffer); - - buffer.clear(); - } - } catch (IOException e) { - IOUtils.closeQuietly(socketChannel); - } - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/io/Client.java b/src/main/java/io/github/ehlxr/io/Client.java deleted file mode 100644 index 34a6ee8..0000000 --- a/src/main/java/io/github/ehlxr/io/Client.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.io; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.SocketChannel; -import java.nio.charset.StandardCharsets; - -/** - * @author ehlxr - * @since 2021-01-23 20:09. - */ -public class Client { - public static void main(String[] args) throws IOException { - SocketChannel socketChannel = SocketChannel.open(); - socketChannel.connect(new InetSocketAddress("localhost", 8080)); - - // 发送请求 - ByteBuffer buffer = ByteBuffer.wrap("1234567890".getBytes()); - socketChannel.write(buffer); - - // 读取响应 - ByteBuffer readBuffer = ByteBuffer.allocate(1024); - int num; - if ((num = socketChannel.read(readBuffer)) > 0) { - readBuffer.flip(); - - byte[] re = new byte[num]; - readBuffer.get(re); - - String result = new String(re, StandardCharsets.UTF_8); - System.out.println("返回值: " + result); - } - } -} diff --git a/src/main/java/io/github/ehlxr/io/SelectorServer.java b/src/main/java/io/github/ehlxr/io/SelectorServer.java deleted file mode 100644 index fa9d95e..0000000 --- a/src/main/java/io/github/ehlxr/io/SelectorServer.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.io; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.Iterator; -import java.util.Set; - -/** - * @author ehlxr - * @since 2021-01-23 20:18. - */ -public class SelectorServer { - public static void main(String[] args) throws IOException { - Selector selector = Selector.open(); - - ServerSocketChannel server = ServerSocketChannel.open(); - server.socket().bind(new InetSocketAddress(8080)); - - // 将其注册到 Selector 中,监听 OP_ACCEPT 事件 - server.configureBlocking(false); - server.register(selector, SelectionKey.OP_ACCEPT); - - //noinspection InfiniteLoopStatement - while (true) { - int readyChannels = selector.select(); - if (readyChannels == 0) { - continue; - } - Set readyKeys = selector.selectedKeys(); - // 遍历 - Iterator iterator = readyKeys.iterator(); - while (iterator.hasNext()) { - SelectionKey key = iterator.next(); - iterator.remove(); - - if (key.isAcceptable()) { - // 有已经接受的新的到服务端的连接 - SocketChannel socketChannel = server.accept(); - - // 有新的连接并不代表这个通道就有数据, - // 这里将这个新的 SocketChannel 注册到 Selector,监听 OP_READ 事件,等待数据 - socketChannel.configureBlocking(false); - socketChannel.register(selector, SelectionKey.OP_READ); - } else if (key.isReadable()) { - // 有数据可读 - // 上面一个 if 分支中注册了监听 OP_READ 事件的 SocketChannel - SocketChannel socketChannel = (SocketChannel) key.channel(); - ByteBuffer readBuffer = ByteBuffer.allocate(1024); - int num = socketChannel.read(readBuffer); - if (num > 0) { - // 处理进来的数据... - System.out.println("收到数据:" + new String(readBuffer.array()).trim()); - ByteBuffer buffer = ByteBuffer.wrap("返回给客户端的数据...".getBytes()); - socketChannel.write(buffer); - } else if (num == -1) { - // -1 代表连接已经关闭 - socketChannel.close(); - } - } - } - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/leetcode/Solution206.java b/src/main/java/io/github/ehlxr/leetcode/Solution206.java deleted file mode 100644 index b291c6a..0000000 --- a/src/main/java/io/github/ehlxr/leetcode/Solution206.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.leetcode; - -/** - * 反转链表 - * 假设链表为 1 → 2 → 3 → null,我们想要把它改成 null ← 1 ← 2 ← 3 - * - * @author ehlxr - * @since 2021-02-27 21:08. - */ -public class Solution206 { - /* - 方法一:迭代 - https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcode-solution-d1k2/ - */ - public static ListNode reverseList1(ListNode head) { - ListNode prev = null; - while (head != null) { - // 先存储当前节点的下一个节点 - ListNode next = head.next; - - // 将当前节点的下一个节点改为前一个节点 - head.next = prev; - - // 指针后移 - // 更改前一个节点为当前节点 - prev = head; - // 更改当前节点为下一个节点 - head = next; - } - - return prev; - } - - /* - 方法一:递归 - https://leetcode-cn.com/problems/reverse-linked-list/solution/shi-pin-jiang-jie-die-dai-he-di-gui-hen-hswxy/ - */ - public static ListNode reverseList2(ListNode head) { - // 递归终止条件 - if (head == null || head.next == null) { - return head; - } - - ListNode h = reverseList2(head.next); - - head.next.next = head; - // 防止链表循环 - head.next = null; - - return h; - } - - public static void main(String[] args) { - ListNode n1 = new ListNode(1); - ListNode n2 = new ListNode(2); - ListNode n3 = new ListNode(3); - ListNode n4 = new ListNode(4); - - n1.next = n2; - n2.next = n3; - n3.next = n4; - - System.out.println(n1); - - System.out.println(reverseList2(n1)); - } -} diff --git a/src/main/java/io/github/ehlxr/leetcode/Solution4.java b/src/main/java/io/github/ehlxr/leetcode/Solution4.java deleted file mode 100644 index cf8c190..0000000 --- a/src/main/java/io/github/ehlxr/leetcode/Solution4.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.leetcode; - -/** - * 4. 寻找两个正序数组的中位数 - * - * @author ehlxr - * @since 2020-09-27 21:12. - */ -public class Solution4 { - /** - * 解法一 - * 简单粗暴,先将两个数组合并,两个有序数组的合并也是归并排序中的一部分。然后根据奇数,还是偶数,返回中位数。 - */ - public static double findMedianSortedArrays(int[] nums1, int[] nums2) { - int[] result = new int[nums1.length + nums2.length]; - - int x = 0, y = 0, z = 0; - while (x < nums1.length || y < nums2.length) { - if (x >= nums1.length) { - result[z] = nums2[y]; - y++; - z++; - continue; - } - - if (y >= nums2.length) { - result[z] = nums1[x]; - x++; - z++; - continue; - } - - if (nums1[x] < nums2[y]) { - result[z] = nums1[x]; - x++; - } else { - result[z] = nums2[y]; - y++; - } - z++; - } - - int m = result.length / 2; - if (result.length % 2 == 0) { - return (result[m] + result[m - 1]) / 2.0; - } else { - return result[m]; - } - } - - /** - * 用 len 表示合并后数组的长度, - * 如果是奇数,我们需要知道第 (len+1)/2 个数就可以了,如果遍历的话需要遍历 int(len/2 ) + 1 次。 - * 如果是偶数,我们需要知道第 len/2 和 len/2+1 个数,也是需要遍历 len/2+1 次。 - * - * 所以遍历的话,奇数和偶数都是 len/2+1 次。 - * - * https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-2/ - */ - public static double findMedianSortedArrays2(int[] nums1, int[] nums2) { - int l1 = nums1.length, l2 = nums2.length, - left = 0, right = 0, - len = l1 + l2, - x = 0, y = 0; - - for (int i = 0; i < len/2 +1; i++) { - left = right; - - if (x >= nums1.length) { - right = nums2[y]; - y++; - continue; - } - - if (y >= nums2.length) { - right = nums1[x]; - x++; - continue; - } - - if (nums1[x] < nums2[y]) { - right = nums1[x]; - x++; - } else { - right = nums2[y]; - y++; - } - } - - if (len % 2 == 0) { - return (left + right) / 2.0; - } else { - return right; - } - } - - public static void main(String[] args) { - System.out.println(findMedianSortedArrays(new int[]{}, new int[]{2, 3})); - System.out.println(findMedianSortedArrays2(new int[]{1, 4}, new int[]{2, 3})); - System.out.println(findMedianSortedArrays2(new int[]{3}, new int[]{1, 4, 6})); - } -} diff --git a/src/main/java/io/github/ehlxr/leetcode/Solution5.java b/src/main/java/io/github/ehlxr/leetcode/Solution5.java deleted file mode 100644 index 50192ce..0000000 --- a/src/main/java/io/github/ehlxr/leetcode/Solution5.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.leetcode; - -import java.util.Arrays; -import java.util.PriorityQueue; - -/** - * @author ehlxr - * @since 2020-10-20 17:54. - */ -public class Solution5 { - - public int findKthLargest(int[] nums, int k) { - PriorityQueue queue = new PriorityQueue<>(); - for (int val : nums) { - queue.add(val); - if (queue.size() > k) { - queue.poll(); - } - } - return queue.peek(); - } - - public static void main(String[] args) { - int[] arr = {4, 6, 8, 5, 9}; - // PriorityQueue queue = new PriorityQueue<>(); - // for (int val : arr) { - // queue.add(val); - // } - // System.out.println(Arrays.toString(queue.toArray())); - // - // - // arr = new int[]{4, 6, 8, 5, 9}; - PriorityQueue maxHeap = new PriorityQueue<>(arr.length, (o1, o2) -> o2 - o1); - for (int val : arr) { - maxHeap.add(val); - } - System.out.println(Arrays.toString(maxHeap.toArray())); - } -} diff --git a/src/main/java/io/github/ehlxr/lock/Locker.java b/src/main/java/io/github/ehlxr/lock/Locker.java deleted file mode 100644 index 3c3aec6..0000000 --- a/src/main/java/io/github/ehlxr/lock/Locker.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.lock; - -import java.util.concurrent.locks.ReentrantLock; - -/** - * @author ehlxr - * @since 2021-02-15 18:11. - */ -public class Locker { - - - public static void main(String[] args) { - ReentrantLock lock = new ReentrantLock(); - - lock.lock(); // block until condition holds - try { - // ... method body - } finally { - lock.unlock(); - } - } - -} diff --git a/src/main/java/io/github/ehlxr/pack/FileUtil.java b/src/main/java/io/github/ehlxr/pack/FileUtil.java deleted file mode 100644 index 27e6419..0000000 --- a/src/main/java/io/github/ehlxr/pack/FileUtil.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.pack; - -import javax.swing.*; -import java.awt.*; -import java.io.*; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class FileUtil { - private static int sumError = 0; - private static int sumExistError = 0; - private static int sumNotFoundError = 0; - private static int sumSuccess = 0; - private static int sumNum = 1; - - private static String getDate(Date date) { - SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return sd.format(date); - } - - private static BufferedReader getBufferedReader(String path) throws FileNotFoundException { - return new BufferedReader(new InputStreamReader(new FileInputStream(path))); - } - - public static void setInfo(String info, JFrame root) { - sumError += 1; - info.equals(""); - - Component[] components = root.getRootPane().getContentPane().getComponents(); - for (int i = 0; i < components.length; i++) { - if (components[i].getClass().toString().equals("class javax.swing.JScrollPane")) { - JTextArea textarea = (JTextArea) ((JScrollPane) components[i]).getViewport().getView(); - if (info.equals("")) { - sumError = 0; - sumExistError = 0; - sumNotFoundError = 0; - sumSuccess = 0; - sumNum = 1; - textarea.setText(""); - } else if ((textarea.getText().equals("")) || (textarea.getText() == null)) { - textarea.setText(sumNum + ". " + info); - } else { - textarea.setText(textarea.getText() + "\n" + sumNum + ". " + info); - } - } - } - } - - private static boolean copy(String from, String dirPath, JFrame root) { - boolean isCommon = true; - File fromFile = new File(from); - if (!fromFile.exists()) { - sumExistError += 1; - setInfo(from + "-------未找到!", root); - - System.out.println(from + "---------------未找到!"); - return false; - } - makeDirs(dirPath); - try { - File toFile = new File(dirPath + File.separatorChar + fromFile.getName()); - if (toFile.exists()) { - sumNotFoundError += 1; - int k = checkFileVersion(fromFile, toFile); - if (k == -1) { - setInfo(fromFile.getAbsolutePath() + "--输出失败(已存在!)", root); - System.out.println( - "文件版本在目标版本之前,处理为不覆盖!若要处理请人工处理!\n原文件:" + fromFile.getAbsolutePath() + "\n目标文件:" + toFile.getAbsolutePath()); - JOptionPane jp = new JOptionPane(); - jp.setBounds(new Rectangle(new Point(400, 400))); - - int isYes = JOptionPane.showConfirmDialog(root, "发现相同的文件,文件版本在目标版本之前!是否要进行覆盖?\n当前文件:" + - - fromFile.getAbsolutePath() + ",修改日期:" + getDate(new Date(fromFile.lastModified())) + "\n目标文件:" - + toFile.getAbsolutePath() + ",修改日期:" + getDate(new Date(toFile.lastModified()))); - if (isYes == 0) { - isCommon = false; - System.out.println("您选择了是!"); - } else { - return false; - } - } - if (k == 0) { - setInfo(fromFile.getAbsolutePath() + "--输出失败(已存在)", root); - System.out - .println("相同文件重复,处理为不覆盖!若要处理请人工处理!\n原文件:" + fromFile.getAbsolutePath() + "\n目标文件:" + toFile.getAbsolutePath()); - return true; - } - if (k == 1) { - isCommon = false; - } - } else if (!toFile.exists()) { - toFile.createNewFile(); - isCommon = false; - } - if (!isCommon) { - InputStream is = new FileInputStream(fromFile); - OutputStream out = new FileOutputStream(toFile); - byte[] b = new byte[1024]; - int len = -1; - while ((len = is.read(b)) != -1) { - out.write(b, 0, len); - } - out.flush(); - out.close(); - is.close(); - toFile.setLastModified(fromFile.lastModified()); - sumSuccess += 1; - return true; - } - } catch (Exception e) { - System.out.println("Copy Error!"); - } - return false; - } - - private static void makeDirs(String path) { - File f = new File(path); - if (!f.exists()) { - f.mkdirs(); - } - } - - private static int checkFileVersion(File file1, File file2) { - long file1LastTime = file1.lastModified(); - long file2LastTime = file2.lastModified(); - if (file1LastTime > file2LastTime) { - return 1; - } - if (file1LastTime < file2LastTime) { - return -1; - } - return 0; - } - - public static boolean becomePackage(String fileList, String cutStr, String dir, JFrame root) throws Exception { - dir = dir + "\\"; - - String filePath = null; - String addStr = null; - String fromFile = null; - String toFile = null; - boolean flag = false; - try { - BufferedReader br = getBufferedReader(fileList); - addStr = br.readLine(); - addStr = addStr.trim(); - setInfo("", root); - while ((filePath = br.readLine()) != null) { - sumNum += 1; - if (!"".equals(filePath.trim())) { - filePath = filePath.replaceAll("/", "\\\\"); - - System.out.println(filePath.replaceAll("\\\\", "/")); - if (filePath.startsWith(cutStr)) { - fromFile = filePath.trim(); - toFile = dir + addStr + File.separatorChar + getCenter(cutStr, fromFile); - flag = copy(fromFile, toFile, root); - } else { - fromFile = cutStr + File.separatorChar + filePath.trim(); - toFile = dir + addStr + File.separatorChar + filePath.substring(0, filePath.trim().lastIndexOf("\\")); - - flag = copy(fromFile, toFile, root); - } - } - } - br.close(); - setInfo("----成功:" + sumSuccess + "\n" + "----失败:" + sumError + "\n" + "--------未找到:" + sumNotFoundError + "\n" + "--------已存在:" - + sumExistError, root); - return flag; - } catch (FileNotFoundException e) { - System.out.println("列表文件没有找到!"); - throw new Exception("列表文件没有找到!"); - } catch (IOException e) { - System.out.println("列表文件读取出错!"); - throw new Exception("列表文件读取出错!"); - } - } - - private static String getCenter(String flag, String message) { - int k1 = message.trim().indexOf(flag); - int k2 = message.trim().lastIndexOf("\\"); - if ((k1 != -1) && (k2 != -1)) { - return message.substring(flag.length() + 1, k2 + 1); - } - return null; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/pack/PackView.java b/src/main/java/io/github/ehlxr/pack/PackView.java deleted file mode 100644 index 700f13b..0000000 --- a/src/main/java/io/github/ehlxr/pack/PackView.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.pack; - -import javax.swing.*; -import javax.swing.filechooser.FileFilter; -import javax.swing.filechooser.FileSystemView; -import java.awt.*; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -@SuppressWarnings("serial") -public class PackView extends JFrame { - private final JButton jb = new JButton(); - private final JButton jb1 = new JButton(); - private final JButton jb2 = new JButton(); - private final JLabel jl0 = new JLabel(); - private final JButton cancel = new JButton("退出"); - private final JTextPane jText1 = new JTextPane(); - private final JTextPane jText2 = new JTextPane(); - public JTextArea jArea = new JTextArea(); - public JScrollPane p = new JScrollPane(this.jArea); - private String inputPath = "D:\\wins-dsp"; - private String outputPath = "C:\\Users\\ehlxr\\Desktop"; - - private PackView() { - setTitle("打包工具(By:Henry)"); - setBounds(400, 400, 500, 300); - setLayout(null); - setResizable(false); - this.jb.setText("打包清单"); - this.jb1.setText("打包根目录"); - this.jb2.setText("输出目录"); - - this.jText1.setText(this.inputPath); - this.jText2.setText(this.outputPath); - - this.jb.addMouseListener(new MouseListener() { - public void mouseReleased(MouseEvent e) { - if (PackView.this.packs()) { - PackView.this.jl0.setText("成功打包!"); - PackView.this.jb.setText("...继续"); - } else { - PackView.this.jl0.setText("打包失败!"); - } - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - }); - this.jb1.addMouseListener(new MouseListener() { - public void mouseReleased(MouseEvent e) { - PackView.this.choosePath(1); - PackView.this.jText1.setText(PackView.this.inputPath); - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - }); - this.jb2.addMouseListener(new MouseListener() { - public void mouseReleased(MouseEvent e) { - PackView.this.choosePath(2); - PackView.this.jText2.setText(PackView.this.outputPath); - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - }); - this.cancel.addMouseListener(new MouseListener() { - public void mouseReleased(MouseEvent e) { - PackView.this.close(); - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - }); - this.jb1.setBounds(10, 5, 100, 30); - this.jText1.setBounds(120, 5, 250, 30); - - this.jb2.setBounds(10, 40, 100, 30); - this.jText2.setBounds(120, 40, 250, 30); - - this.jb.setBounds(10, 100, 100, 30); - this.cancel.setBounds(120, 100, 100, 30); - this.jl0.setBounds(230, 100, 100, 30); - this.jArea.setLineWrap(true); - this.jArea.setForeground(Color.red); - this.jArea.setEditable(false); - - this.p.setBounds(10, 130, 480, 130); - - this.p.setVerticalScrollBarPolicy(22); - this.p.setHorizontalScrollBarPolicy(32); - - add(this.jb1); - add(this.jText1); - add(this.jb2); - add(this.jText2); - add(this.jb); - add(this.cancel); - add(this.jl0); - - add(this.p); - setVisible(true); - setDefaultCloseOperation(3); - } - - public static void main(String[] args) { - new PackView(); - } - - private List chooseFile(int chooseMode) { - try { - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setMultiSelectionEnabled(true); - fileChooser.setDialogTitle("文件打包"); - fileChooser.setDragEnabled(true); - fileChooser.setAutoscrolls(true); - - fileChooser.setFileFilter(new FileFilter() { - public boolean accept(File f) { - if (f.isDirectory()) { - return true; - } - return (f.getName().endsWith(".TXT")) || (f.getName().endsWith(".txt")); - } - - public String getDescription() { - return ".txt"; - } - }); - fileChooser.setCurrentDirectory(FileSystemView.getFileSystemView().getHomeDirectory()); - - fileChooser.setOpaque(true); - fileChooser.setDoubleBuffered(true); - int returnVal = -1; - switch (chooseMode) { - case 1: - returnVal = fileChooser.showOpenDialog(this); - break; - case 2: - returnVal = fileChooser.showSaveDialog(this); - } - File[] fileName; - if (returnVal == 0) { - fileName = fileChooser.getSelectedFiles(); - } else { - fileName = null; - } - List list = new ArrayList(); - System.out.println("打包文件路径列表:"); - String filePath = null; - for (int i = 0; i < fileName.length; i++) { - filePath = fileName[i].getAbsolutePath(); - if (filePath.toUpperCase().endsWith("TXT")) { - list.add(filePath); - System.out.println("序号 " + i + " " + filePath); - } else { - System.out.println("序号 " + i + " " + filePath + " >>该文件不能作为打包文件! "); - } - } - return list; - } catch (Exception e) { - } - return null; - } - - private boolean choosePath(int id) { - try { - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setMultiSelectionEnabled(true); - switch (id) { - case 1: - fileChooser.setDialogTitle("打包文件根目录"); - fileChooser.setCurrentDirectory(new File(this.inputPath)); - break; - case 2: - fileChooser.setDialogTitle("输出文件目录"); - fileChooser.setCurrentDirectory(new File(this.outputPath)); - } - fileChooser.setDragEnabled(true); - fileChooser.setAutoscrolls(true); - fileChooser.setAcceptAllFileFilterUsed(true); - fileChooser.setOpaque(true); - fileChooser.setDoubleBuffered(true); - fileChooser.setFileSelectionMode(1); - - fileChooser.showOpenDialog(this); - switch (id) { - case 1: - this.inputPath = fileChooser.getSelectedFile().toString(); - break; - case 2: - this.outputPath = fileChooser.getSelectedFile().toString(); - } - return true; - } catch (Exception e) { - } - return false; - } - - private void close() { - dispose(); - } - - private boolean packs() { - boolean flag = true; - List fileName = chooseFile(1); - if ((fileName == null) || (fileName.size() <= 0)) { - System.out.println("打包原始文件没有找到"); - flag = false; - } else { - for (int i = 0; i < fileName.size(); i++) { - try { - flag = FileUtil.becomePackage(fileName.get(i), this.inputPath, this.outputPath, this); - } catch (Exception e) { - return false; - } - } - } - return flag; - } -} diff --git a/src/main/java/io/github/ehlxr/powermock/ClassDependency.java b/src/main/java/io/github/ehlxr/powermock/ClassDependency.java deleted file mode 100644 index 6d46643..0000000 --- a/src/main/java/io/github/ehlxr/powermock/ClassDependency.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.powermock; - -/** - * Created by ehlxr on 2017/11/3. - */ -public class ClassDependency { - public static boolean isExist() { - // do something - return false; - } - - public final boolean isAlive() { - // do something - return false; - } - - public boolean isGod(String oh){ - System.out.println(oh); - return false; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/powermock/ClassUnderTest.java b/src/main/java/io/github/ehlxr/powermock/ClassUnderTest.java deleted file mode 100644 index e791c6a..0000000 --- a/src/main/java/io/github/ehlxr/powermock/ClassUnderTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.powermock; - -/** - * Created by ehlxr on 2017/11/3. - */ - -import java.io.File; - -/** - * Created by ehlxr on 2017/7/21. - */ -public class ClassUnderTest { - private final String f1 = "test"; - - public boolean callArgumentInstance(File file) { - return file.exists(); - } - - public boolean callInternalInstance(String path) { - File file = new File(path); - return file.exists(); - } - - public boolean callFinalMethod(ClassDependency refer) { - return refer.isAlive(); - } - - public boolean callSystemFinalMethod(String str) { - return str.isEmpty(); - } - - public boolean callStaticMethod() { - return ClassDependency.isExist(); - } - - public String callSystemStaticMethod(String str) { - return System.getProperty(str); - } - - public boolean callPrivateMethod() { - return isExist(); - } - - public boolean callVoidPrivateMethod() { - testVoid(); - return true; - } - - private boolean isExist() { - // do something - return false; - } - - private void testVoid() { - System.out.println("do nothing"); - } - - public boolean callDependency() { - ClassDependency classDependency = new ClassDependency(); - return classDependency.isGod("hh"); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/powermock/TestClassUnderTest.java b/src/main/java/io/github/ehlxr/powermock/TestClassUnderTest.java deleted file mode 100644 index b934cc0..0000000 --- a/src/main/java/io/github/ehlxr/powermock/TestClassUnderTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.powermock; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; - -import java.io.File; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.powermock.api.mockito.PowerMockito.*; - -/** - * Created by ehlxr on 2017/7/21. - */ -@RunWith(PowerMockRunner.class) -public class TestClassUnderTest { - @Test - public void testCallArgumentInstance() { - File file = mock(File.class); - ClassUnderTest underTest = new ClassUnderTest(); - PowerMockito.when(file.exists()).thenReturn(true); - Assert.assertTrue(underTest.callArgumentInstance(file)); - } - - @Test - @PrepareForTest(ClassUnderTest.class) - public void testCallInternalInstance() throws Exception { - File file = mock(File.class); - ClassUnderTest underTest = new ClassUnderTest(); - PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file); - PowerMockito.when(file.exists()).thenReturn(true); - Assert.assertTrue(underTest.callInternalInstance("bbb")); - } - - @Test - @PrepareForTest(ClassDependency.class) - public void testCallFinalMethod() { - ClassDependency depencency = mock(ClassDependency.class); - ClassUnderTest underTest = new ClassUnderTest(); - when(depencency.isAlive()).thenReturn(true); - Assert.assertTrue(underTest.callFinalMethod(depencency)); - } - - @Test - @PrepareForTest(ClassUnderTest.class) - public void testCallSystemFinalMethod() { - String str = mock(String.class); - ClassUnderTest underTest = new ClassUnderTest(); - PowerMockito.when(str.isEmpty()).thenReturn(false); - Assert.assertFalse(underTest.callSystemFinalMethod(str)); - } - - @Test - @PrepareForTest(ClassDependency.class) - public void testCallStaticMethod() { - ClassUnderTest underTest = new ClassUnderTest(); - PowerMockito.mockStatic(ClassDependency.class); - when(ClassDependency.isExist()).thenReturn(true); - Assert.assertTrue(underTest.callStaticMethod()); - } - - @Test - @PrepareForTest(ClassUnderTest.class) - public void testCallSystemStaticMethod() { - ClassUnderTest underTest = new ClassUnderTest(); - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb"); - Assert.assertEquals("bbb", underTest.callSystemStaticMethod("aaa")); - } - - @Test - @PrepareForTest(ClassUnderTest.class) - public void testCallPrivateMethod() throws Exception { - ClassUnderTest underTest = mock(ClassUnderTest.class); - when(underTest.callPrivateMethod()).thenCallRealMethod(); - when(underTest, "isExist").thenReturn(true); - Assert.assertTrue(underTest.callPrivateMethod()); - } - - @Test - @PrepareForTest(ClassUnderTest.class) - public void testCallVoidPrivateMethod() throws Exception { - ClassUnderTest underTest = mock(ClassUnderTest.class); - when(underTest.callVoidPrivateMethod()).thenCallRealMethod(); - PowerMockito.doNothing().when(underTest, "testVoid"); - Assert.assertTrue(underTest.callVoidPrivateMethod()); - } - - - @Test - @PrepareForTest(ClassUnderTest.class) - public void testDependency() throws Exception { - ClassUnderTest underTest = new ClassUnderTest(); - ClassDependency dependency = mock(ClassDependency.class); - - // @PrepareForTest(ClassUnderTest.class) - whenNew(ClassDependency.class).withAnyArguments().thenReturn(dependency); - - when(dependency.isGod(anyString())).thenReturn(true); - Assert.assertTrue(underTest.callDependency()); - } - - @Test - @PrepareForTest(ClassUnderTest.class) - public void testInvokPrivate() throws Exception { - ClassUnderTest underTest = PowerMockito.spy(new ClassUnderTest()); - - Whitebox.invokeMethod(underTest, "isExist"); - verifyPrivate(underTest).invoke("isExist"); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/proxy/Bird.java b/src/main/java/io/github/ehlxr/proxy/Bird.java deleted file mode 100644 index 6c1a29b..0000000 --- a/src/main/java/io/github/ehlxr/proxy/Bird.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.proxy; - -import java.util.Random; - -/** - * @author ehlxr - * @since 2019-06-28. - */ -public class Bird implements Flyable { - @Override - public void fly() { - System.out.println("Bird is flying..."); - try { - Thread.sleep(new Random().nextInt(1000)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - // @Override - // public void run() { - // System.out.println("Bird is running..."); - // } -} diff --git a/src/main/java/io/github/ehlxr/proxy/Flyable.java b/src/main/java/io/github/ehlxr/proxy/Flyable.java deleted file mode 100644 index 4bf730f..0000000 --- a/src/main/java/io/github/ehlxr/proxy/Flyable.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.proxy; - -/** - * @author ehlxr - * @since 2019-06-28. - */ -public interface Flyable { - void fly(); - - // void run(); -} diff --git a/src/main/java/io/github/ehlxr/proxy/Main.java b/src/main/java/io/github/ehlxr/proxy/Main.java deleted file mode 100644 index 3a17294..0000000 --- a/src/main/java/io/github/ehlxr/proxy/Main.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.proxy; - -import java.lang.reflect.Proxy; - -/** - * @author ehlxr - * @since 2019-06-28. - */ -public class Main { - public static void main(String[] args) { - Flyable proxy = (Flyable) Proxy.newProxyInstance(Flyable.class.getClassLoader(), - new Class[]{Flyable.class}, new MyInvocationHandler(new Bird())); - - // 动态代理会生成类似以下的 Java 代码 - /* - package me.ehlxr.proxy; - - import java.lang.reflect.InvocationHandler; - import java.lang.reflect.Method; - - public class Proxy implements Flyable { - private InvocationHandler handler; - - public Proxy(InvocationHandler handler) { - this.handler = handler; - } - - @Override - public void fly() { - try { - Method method = Flyable.class.getMethod("fly"); - this.handler.invoke(this, method, null); - } catch (Throwable e) { - e.printStackTrace(); - } - } - } - */ - - proxy.fly(); - } -} diff --git a/src/main/java/io/github/ehlxr/proxy/MyInvocationHandler.java b/src/main/java/io/github/ehlxr/proxy/MyInvocationHandler.java deleted file mode 100644 index 286ea05..0000000 --- a/src/main/java/io/github/ehlxr/proxy/MyInvocationHandler.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.proxy; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @author ehlxr - * @since 2019-06-28. - */ -public class MyInvocationHandler implements InvocationHandler { - private final Bird bird; - - public MyInvocationHandler(Bird bird) { - this.bird = bird; - } - - @Override - public Object invoke(Object proxy, Method method, Object[] args) { - long start = System.currentTimeMillis(); - - try { - method.invoke(bird, args); - } catch (IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } - - long end = System.currentTimeMillis(); - System.out.println("Fly time = " + (end - start)); - return null; - } -} diff --git a/src/main/java/io/github/ehlxr/queue/Order.java b/src/main/java/io/github/ehlxr/queue/Order.java deleted file mode 100644 index 0a82e23..0000000 --- a/src/main/java/io/github/ehlxr/queue/Order.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.queue; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.concurrent.DelayQueue; -import java.util.concurrent.Delayed; -import java.util.concurrent.TimeUnit; - -/** - * 订单延迟队列 - * - * @author ehlxr - * @since 2021-02-20 16:28. - */ -public class Order implements Delayed { - /** - * 延迟时间 - */ - private long time; - String name; - - public Order(String name, long time, TimeUnit unit) { - this.name = name; - this.time = System.currentTimeMillis() + (time > 0 ? unit.toMillis(time) : 0); - } - - @Override - public long getDelay(TimeUnit unit) { - return time - System.currentTimeMillis(); - } - - @Override - public int compareTo(Delayed delayed) { - Order order = (Order) delayed; - long diff = this.time - order.time; - if (diff <= 0) { - return -1; - } else { - return 1; - } - } - - - public static void main(String[] args) throws InterruptedException { - Order order1 = new Order("Order1", 5, TimeUnit.SECONDS); - Order order2 = new Order("Order2", 10, TimeUnit.SECONDS); - Order order3 = new Order("Order3", 15, TimeUnit.SECONDS); - DelayQueue delayQueue = new DelayQueue<>(); - delayQueue.put(order1); - delayQueue.put(order3); - delayQueue.put(order2); - - System.out.println("订单延迟队列开始时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); - while (delayQueue.size() != 0) { - /* - * 取队列头部元素是否过期 - */ - Order task = delayQueue.take(); // 阻塞 - // Order task = delayQueue.poll(); // 非阻塞 - // if (task != null) { - System.out.format("订单:{%s}被取消, 取消时间:{%s}\n", task.name, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); - // } - // TimeUnit.SECONDS.sleep(1); - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/rabbitmq/ConnectionUtil.java b/src/main/java/io/github/ehlxr/rabbitmq/ConnectionUtil.java deleted file mode 100644 index 302d5f8..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/ConnectionUtil.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq; - -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * @author ehlxr - * @since 2019-01-22. - */ -public class ConnectionUtil { - public static Connection getConnection() throws IOException, TimeoutException { - // 连接工厂 - ConnectionFactory factory = new ConnectionFactory(); - factory.setHost("localhost"); - // 连接 5672 端口;注意 15672 为工具界面端口;25672 为集群端口 - factory.setPort(5672); - /* - * 当我们在创建用户时,会指定用户能访问一个虚拟机,并且该用户只能访问该虚拟机下的队列和交换机,如果没有指定,默认的是”/”; - * 一个 rabbitmq 服务器上可以运行多个 vhost,以便于适用不同的业务需要, - * 这样做既可以满足权限配置的要求,也可以避免不同业务之间队列、交换机的命名冲突问题,因为不同 vhost 之间是隔离的。 - */ - factory.setVirtualHost("/tdd"); - factory.setUsername("ehlxr"); - factory.setPassword("123456"); - - //获取连接 - return factory.newConnection(); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/rabbitmq/routing/Receiver1.java b/src/main/java/io/github/ehlxr/rabbitmq/routing/Receiver1.java deleted file mode 100755 index b17607c..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/routing/Receiver1.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.routing; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.QueueingConsumer; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * 发送消息到交换机并且要指定路由 key ,消费者将队列绑定到交换机时需要指定路由 key - * - * @author ehlxr - * @since 2019-01-22. - */ -public class Receiver1 { - private final static String QUEUE_NAME = "queue_routing"; - private final static String EXCHANGE_NAME = "exchange_direct"; - - public static void main(String[] args) throws IOException, InterruptedException, TimeoutException { - // 获取到连接以及mq通道 - Connection connection = ConnectionUtil.getConnection(); - Channel channel = connection.createChannel(); - - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key"); - channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key2"); - - channel.basicQos(1); - - QueueingConsumer consumer = new QueueingConsumer(channel); - channel.basicConsume(QUEUE_NAME, false, consumer); - - while (true) { - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - System.out.println("[x] Received1 " + message); - Thread.sleep(10); - - channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); - } - - - } -} diff --git a/src/main/java/io/github/ehlxr/rabbitmq/routing/Receiver2.java b/src/main/java/io/github/ehlxr/rabbitmq/routing/Receiver2.java deleted file mode 100755 index acfd54f..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/routing/Receiver2.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.routing; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.QueueingConsumer; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * 发送消息到交换机并且要指定路由 key ,消费者将队列绑定到交换机时需要指定路由 key - * - * @author ehlxr - * @since 2019-01-22. - */ -public class Receiver2 { - private final static String QUEUE_NAME = "queue_routing2"; - private final static String EXCHANGE_NAME = "exchange_direct"; - - public static void main(String[] args) throws IOException, InterruptedException, TimeoutException { - // 获取到连接以及mq通道 - Connection connection = ConnectionUtil.getConnection(); - Channel channel = connection.createChannel(); - - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key2"); - - channel.basicQos(1); - - QueueingConsumer consumer = new QueueingConsumer(channel); - channel.basicConsume(QUEUE_NAME, false, consumer); - - while (true) { - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - System.out.println("[x] Received2 " + message); - Thread.sleep(10); - - channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); - } - - - } -} diff --git a/src/main/java/io/github/ehlxr/rabbitmq/routing/Sender.java b/src/main/java/io/github/ehlxr/rabbitmq/routing/Sender.java deleted file mode 100755 index 4862ff4..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/routing/Sender.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.routing; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * 发送消息到交换机并且要指定路由 key ,消费者将队列绑定到交换机时需要指定路由 key - * - * @author ehlxr - * @since 2019-01-22. - */ -public class Sender { - private final static String EXCHANGE_NAME = "exchange_direct"; - private final static String EXCHANGE_TYPE = "direct"; - - public static void main(String[] args) throws IOException, TimeoutException { - Connection connection = ConnectionUtil.getConnection(); - Channel channel = connection.createChannel(); - - channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE); - - String message = "那一定是蓝色"; - channel.basicPublish(EXCHANGE_NAME, "key2", null, message.getBytes()); - System.out.println("[x] Sent '" + message + "'"); - - channel.close(); - connection.close(); - } -} diff --git a/src/main/java/io/github/ehlxr/rabbitmq/simple/Receiver.java b/src/main/java/io/github/ehlxr/rabbitmq/simple/Receiver.java deleted file mode 100644 index e2e18c3..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/simple/Receiver.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.simple; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.QueueingConsumer; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * 简单模式:一个生产者,一个消费者 - * - * @author ehlxr - * @since 2019-01-22. - */ -public class Receiver { - private final static String QUEUE_NAME = "simple_queue"; - - public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { - //获取连接 - Connection connection = ConnectionUtil.getConnection(); - //获取通道 - Channel channel = connection.createChannel(); - - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - QueueingConsumer consumer = new QueueingConsumer(channel); - channel.basicConsume(QUEUE_NAME, true, consumer); - - while (true) { - //该方法会阻塞 - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - System.out.println("[x] Received '" + message + "'"); - - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/rabbitmq/simple/Sender.java b/src/main/java/io/github/ehlxr/rabbitmq/simple/Sender.java deleted file mode 100644 index 3d1aef3..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/simple/Sender.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.simple; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * 简单模式:一个生产者,一个消费者 - * - * @author ehlxr - * @since 2019-01-22. - */ - -public class Sender { - private final static String QUEUE_NAME = "simple_queue"; - - public static void main(String[] args) throws IOException, TimeoutException { - //创建连接 - Connection connection = ConnectionUtil.getConnection(); - //创建通道 - Channel channel = connection.createChannel(); - - - /* - * 声明队列 - * 1. 队列名 - * 2. 是否持久化 - * 3. 是否排外(即只允许该channel访问该队列 一般等于true的话用于一个队列只能有一个消费者来消费的场景) - * 4. 是否自动删除(消费完删除) - * 6. 其他属性 - * - */ - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - - /* - * 消息内容 - * 1. 交换机 - * 2. 队列名 - * 3. 其他属性(路由) - * 4. 消息body - */ - String message = "错的不是我,是这个世界~"; - channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); - System.out.println("[x]Sent '" + message + "'"); - - //最后关闭通关和连接 - channel.close(); - connection.close(); - } - -} diff --git a/src/main/java/io/github/ehlxr/rabbitmq/topic/Receiver1.java b/src/main/java/io/github/ehlxr/rabbitmq/topic/Receiver1.java deleted file mode 100755 index b349a71..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/topic/Receiver1.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.topic; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.QueueingConsumer; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * topic 模式:将路由键和某模式进行匹配,此时队列需要绑定在一个模式上,“#” 匹配一个词或多个词,“*” 只匹配一个词。 - * - * @author ehlxr - * @since 2019-01-22. - */ -@SuppressWarnings("ALL") -public class Receiver1 { - private final static String QUEUE_NAME = "queue_topic2"; - private final static String EXCHANGE_NAME = "exchange_topic"; - - public static void main(String[] args) throws IOException, InterruptedException, TimeoutException { - Connection connection = ConnectionUtil.getConnection(); - Channel channel = connection.createChannel(); - - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "*.*"); - - channel.basicQos(1); - - QueueingConsumer consumer = new QueueingConsumer(channel); - channel.basicConsume(QUEUE_NAME, false, consumer); - - while (true) { - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - System.out.println("[x] Received1 '" + message + "'"); - Thread.sleep(10); - - channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); - } - } -} diff --git a/src/main/java/io/github/ehlxr/rabbitmq/topic/Receiver2.java b/src/main/java/io/github/ehlxr/rabbitmq/topic/Receiver2.java deleted file mode 100755 index 920031c..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/topic/Receiver2.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.topic; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.QueueingConsumer; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * topic 模式:将路由键和某模式进行匹配,此时队列需要绑定在一个模式上,“#” 匹配一个词或多个词,“*” 只匹配一个词。 - * - * @author ehlxr - * @since 2019-01-22. - */ -public class Receiver2 { - private final static String QUEUE_NAME = "queue_topic2"; - private final static String EXCHANGE_NAME = "exchange_topic"; - - public static void main(String[] args) throws IOException, InterruptedException, TimeoutException { - Connection connection = ConnectionUtil.getConnection(); - Channel channel = connection.createChannel(); - - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "*.*"); - - channel.basicQos(1); - - QueueingConsumer consumer = new QueueingConsumer(channel); - channel.basicConsume(QUEUE_NAME, false, consumer); - - while (true) { - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - System.out.println("[x] Received2 '" + message + "'"); - Thread.sleep(10); - - channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); - } - } -} diff --git a/src/main/java/io/github/ehlxr/rabbitmq/topic/Sender.java b/src/main/java/io/github/ehlxr/rabbitmq/topic/Sender.java deleted file mode 100755 index 7160929..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/topic/Sender.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.topic; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * topic 模式:将路由键和某模式进行匹配,此时队列需要绑定在一个模式上,“#” 匹配一个词或多个词,“*” 只匹配一个词。 - * - * @author ehlxr - * @since 2019-01-22. - */ -public class Sender { - private final static String EXCHANGE_NAME = "exchange_topic"; - private final static String EXCHANGE_TYPE = "topic"; - - public static void main(String[] args) throws IOException, TimeoutException { - Connection connection = ConnectionUtil.getConnection(); - Channel channel = connection.createChannel(); - - channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE); - - //消息内容 - String message = "如果真爱有颜色"; - channel.basicPublish(EXCHANGE_NAME, "key.1", null, message.getBytes()); - System.out.println("[x] Sent '" + message + "'"); - - //关通道 关连接 - channel.close(); - connection.close(); - } -} diff --git a/src/main/java/io/github/ehlxr/rabbitmq/worker/Receiver1.java b/src/main/java/io/github/ehlxr/rabbitmq/worker/Receiver1.java deleted file mode 100644 index 8a45d16..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/worker/Receiver1.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.worker; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.QueueingConsumer; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * work 模式:一个生产者,多个消费者,每个消费者获取到的消息唯一 - * - * @author ehlxr - * @since 2019-01-22. - */ -public class Receiver1 { - private final static String QUEUE_NAME = "queue_work"; - - public static void main(String[] args) throws IOException, InterruptedException, TimeoutException { - Connection connection = ConnectionUtil.getConnection(); - Channel channel = connection.createChannel(); - - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - - /* - * 同一时刻服务器只会发送一条消息给消费者 - * - * channel.basicQos: 是指通道 channel 每次能够接收的消费者最大值 https://www.rabbitmq.com/consumer-prefetch.html - * 若将该行代码注释,则 channel 无限制,消息将很快发送完毕,只不过消息阻塞在队列中 - * - */ - channel.basicQos(1); - - QueueingConsumer consumer = new QueueingConsumer(channel); - channel.basicConsume(QUEUE_NAME, false, consumer); - - while (true) { - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - System.out.println("[x] Received1 '" + message + "'"); - - Thread.sleep(10); - //返回确认状态 - channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); - } - } - -} diff --git a/src/main/java/io/github/ehlxr/rabbitmq/worker/Receiver2.java b/src/main/java/io/github/ehlxr/rabbitmq/worker/Receiver2.java deleted file mode 100644 index 25e9f9d..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/worker/Receiver2.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.worker; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.QueueingConsumer; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * work 模式:一个生产者,多个消费者,每个消费者获取到的消息唯一 - * - * @author ehlxr - * @since 2019-01-22. - */ -public class Receiver2 { - private final static String QUEUE_NAME = "queue_work"; - - public static void main(String[] args) throws IOException, InterruptedException, TimeoutException { - Connection connection = ConnectionUtil.getConnection(); - Channel channel = connection.createChannel(); - - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - channel.basicQos(1); - - QueueingConsumer consumer = new QueueingConsumer(channel); - channel.basicConsume(QUEUE_NAME, false, consumer); - - while (true) { - QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - String message = new String(delivery.getBody()); - System.out.println("[x] Received2 '" + message + "'"); - - Thread.sleep(10); - channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); - } - } -} diff --git a/src/main/java/io/github/ehlxr/rabbitmq/worker/Sender.java b/src/main/java/io/github/ehlxr/rabbitmq/worker/Sender.java deleted file mode 100644 index 71d285c..0000000 --- a/src/main/java/io/github/ehlxr/rabbitmq/worker/Sender.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rabbitmq.worker; - -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import io.github.ehlxr.rabbitmq.ConnectionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * work 模式:一个生产者,多个消费者,每个消费者获取到的消息唯一 - * - * @author ehlxr - * @since 2019-01-22. - */ -public class Sender { - private final static String QUEUE_NAME = "queue_work"; - - public static void main(String[] args) throws IOException, InterruptedException, TimeoutException { - Connection connection = ConnectionUtil.getConnection(); - Channel channel = connection.createChannel(); - - channel.queueDeclare(QUEUE_NAME, false, false, false, null); - for (int i = 0; i < 100; i++) { - String message = "冬马小三" + i; - channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); - System.out.println("[x] Sent '" + message + "'"); - Thread.sleep(i * 10); - } - - channel.close(); - connection.close(); - } -} diff --git a/src/main/java/io/github/ehlxr/rate/RateBarrier.java b/src/main/java/io/github/ehlxr/rate/RateBarrier.java deleted file mode 100644 index 1dc4ede..0000000 --- a/src/main/java/io/github/ehlxr/rate/RateBarrier.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rate; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.IntStream; - -/** - * 按比例控制流量 - * - * @author ehlxr - * @since 2019-07-19. - */ -public class RateBarrier { - private final AtomicInteger op = new AtomicInteger(0); - private List source; - private int base; - - public int rate() { - return source.get(op.incrementAndGet() % base); - } - - private RateBarrier() { - } - - public RateBarrier(int base) { - this.base = base; - - source = new ArrayList<>(base); - for (int i = 0; i < base; i++) { - source.add(i); - } - - // 打乱集合顺序 - Collections.shuffle(source); - } - - public static void main(String[] args) { - RateBarrier rateBarrier = new RateBarrier(10); - - IntStream.range(0, 20).parallel().forEach(i -> { - int rate = rateBarrier.rate(); - if (rate < 2) { - System.out.println("this is on 2"); - } else if (rate < 5) { - System.out.println("this is on 3"); - } else { - System.out.println("this is on 5"); - } - }); - - // final Thread[] threads = new Thread[20]; - // for (int i = 0; i < threads.length; i++) { - // threads[i] = new Thread(() -> { - // if (rateBarrier.allow()) { - // System.out.println("this is on 3"); - // } else { - // System.out.println("this is on 7"); - // } - // }); - // threads[i].start(); - // } - // - // for (Thread t : threads) { - // try { - // t.join(); - // } catch (InterruptedException e) { - // e.printStackTrace(); - // } - // } - - } -} diff --git a/src/main/java/io/github/ehlxr/rate/SlideWindow.java b/src/main/java/io/github/ehlxr/rate/SlideWindow.java deleted file mode 100644 index 72e7ae9..0000000 --- a/src/main/java/io/github/ehlxr/rate/SlideWindow.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.rate; - -import java.util.LinkedList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * 滑动时间窗口限流工具 - * 参考:https://www.cnblogs.com/dijia478/p/13807826.html#!comments - * - * @author ehlxr - * @since 2021-07-15 22:04. - */ -public class SlideWindow { - /** - * 限制次数 - */ - private final int count; - - /** - * 时间窗口大小(毫秒) - */ - private final long timeWindow; - - /** - * 限流队列 - */ - private final List list; - - public SlideWindow(int count, long timeWindow) { - this.count = count; - this.timeWindow = timeWindow; - - list = new LinkedList<>(); - } - - /** - * 滑动时间窗口限流算法 - * 在指定时间窗口,指定限制次数内,是否允许通过 - * - * @return 是否允许通过 - */ - public synchronized boolean acquire() { - // 获取当前时间 - long nowTime = System.currentTimeMillis(); - // 如果队列还没满,则允许通过,并添加当前时间戳到队列开始位置 - if (list.size() < count) { - // 把之前这个位置的数据给依次向后移动 - list.add(0, nowTime); - return true; - } - - // 队列已满(达到限制次数),则获取队列中最早添加的时间戳 - // 用当前时间戳 减去 最早添加的时间戳 - if (nowTime - list.get(count - 1) <= timeWindow) { - // 若结果小于等于timeWindow,则说明在timeWindow内,通过的次数大于count - // 不允许通过 - return false; - } else { - // 若结果大于timeWindow,则说明在timeWindow内,通过的次数小于等于count - // 允许通过,并删除最早添加的时间戳,将当前时间添加到队列开始位置 - list.remove(count - 1); - list.add(0, nowTime); - return true; - } - } - - /** - * 等待直到获得允许 - */ - public synchronized void tryAcquire(long timeout, TimeUnit unit) throws Exception { - if (!acquire()) { - long microsToWait = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis() - list.get(count - 1)); - if (unit.toMicros(timeout) < microsToWait) { - throw new TimeoutException(); - } - // 等待 - TimeUnit.MICROSECONDS.sleep(microsToWait); - acquire(); - } - } - - public static void main(String[] args) throws Exception { - SlideWindow slideWindow = new SlideWindow(5, 1000); - - while (true) { - // 任意1秒内,只允许5次通过 - // if (slideWindow.acquire()) { - // System.out.println(System.currentTimeMillis()); - // } - slideWindow.tryAcquire(2, TimeUnit.SECONDS); - - System.out.println(System.currentTimeMillis()); - - // 睡眠0-10ms - Thread.sleep(new Random().nextInt(10)); - } - - } - -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/reactive/HelloRxJava.java b/src/main/java/io/github/ehlxr/reactive/HelloRxJava.java deleted file mode 100644 index 4a4a4a9..0000000 --- a/src/main/java/io/github/ehlxr/reactive/HelloRxJava.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.reactive; - -import rx.Observable; -import rx.Subscriber; - -/** - * Created by ehlxr on 2018/1/16. - */ -public class HelloRxJava { - - public static void main(String[] args) { - hello("wer", "wd"); - } - - private static void hello(String... names) { - Observable.from(names).subscribe(new Subscriber() { - @Override - public void onCompleted() { - System.out.println("Completed!"); - } - - @Override - public void onError(Throwable throwable) { - throwable.printStackTrace(); - } - - @Override - public void onNext(String strings) { - System.out.println("say hello " + strings); - } - - }); - - // Observable.from(names).subscribe(name -> System.out.println("say hello " + name), Throwable::printStackTrace, () -> System.out.println("Completed!")); - } -} diff --git a/src/main/java/io/github/ehlxr/reactive/SchedulerTest.java b/src/main/java/io/github/ehlxr/reactive/SchedulerTest.java deleted file mode 100644 index 65e9fea..0000000 --- a/src/main/java/io/github/ehlxr/reactive/SchedulerTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.reactive; - - -import io.reactivex.Flowable; -import io.reactivex.schedulers.Schedulers; - -/** - * Created by ehlxr on 2018/1/16. - */ -public class SchedulerTest { - public static void main(String[] args) throws InterruptedException { - Flowable.fromCallable(() -> { - Thread.sleep(1000); // imitate expensive computation - return "Done"; - }) - .subscribeOn(Schedulers.io()) - .observeOn(Schedulers.single()) - .subscribe(System.out::println, Throwable::printStackTrace); - - Thread.sleep(2000); // <--- wait for the flow to finish - } -} diff --git a/src/main/java/io/github/ehlxr/reactive/TestFuture.java b/src/main/java/io/github/ehlxr/reactive/TestFuture.java deleted file mode 100644 index 46a7f40..0000000 --- a/src/main/java/io/github/ehlxr/reactive/TestFuture.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.reactive; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -/** - * @author ehlxr - * @date 2018/1/16 - *

- * Future 是一个泛型接口,如果一个可运行的函数(实现 Callable 或 Runable 的类)在一个线程中运行, - * 利用 Future 可以用它的 get() 方法返回 V 类型的结果。 注意, get() 会阻塞当前线程 - *

- * 问题 - * get() 顺序会影响出结果时间,关键 get 的阻塞; - * 如果能按这些线程出结果的时间序列,把数据结果交给后面的线程并行加工处理,CPU就不用阻塞在 get() 了。但编程无疑会很复杂。 - */ -public class TestFuture { - // https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html - private static final ExecutorService executor = Executors.newCachedThreadPool(); - - public static void main(String[] args) { - TestFuture test = new TestFuture(); - test.testTaskRunning("fa", 300); - test.testAsyncTaskRunning(); - executor.shutdown(); - } - - private void testTaskRunning(String name, Integer waiting) { - System.out.println("Prepare for execution:" + name); - long startTime = System.currentTimeMillis(); - - Future fa = executor.submit( - () -> { - try { - Thread.sleep(waiting); - } catch (Exception e) { - e.printStackTrace(); - } - return String.format("service exec time: %d", waiting); - }); - - System.out.println("Start execute: " + (System.currentTimeMillis() - startTime) + "ms"); - - try { - String s = fa.get(); // Future to Blocked - System.out.println(s); - } catch (Exception e) { - e.printStackTrace(); - } - - System.out.println("End execute: " + (System.currentTimeMillis() - startTime) + "ms"); - - } - - private void testAsyncTaskRunning() { - System.out.println("Prepare for execution: composite task"); - long startTime = System.currentTimeMillis(); - - Future fa = executor.submit(new TimeConsumingService("fa", 200, new String[]{})); - Future fb = executor.submit(new TimeConsumingService("fb", 400, new String[]{})); - - System.out.println("Start execute: " + (System.currentTimeMillis() - startTime) + "ms"); - - try { - // What will happen when change line fc and fd ? - Future fc = executor.submit(new TimeConsumingService("fc", 400, new String[]{fa.get()})); - Future fd = executor.submit(new TimeConsumingService("fd", 200, new Object[]{fb.get()})); - Future fe = executor.submit(new TimeConsumingService("fe", 200, new Object[]{fb.get()})); - System.out.println(fc.get()); - System.out.println(fd.get()); - System.out.println(fe.get()); - } catch (Exception e) { - e.printStackTrace(); - } - - System.out.println("End execute: " + (System.currentTimeMillis() - startTime) + "ms"); - } - - -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/reactive/TestLambda.java b/src/main/java/io/github/ehlxr/reactive/TestLambda.java deleted file mode 100644 index 27d445e..0000000 --- a/src/main/java/io/github/ehlxr/reactive/TestLambda.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.reactive; - -/** - * Created by ehlxr on 2018/1/16. - */ -public class TestLambda { - public static void main(String[] args) { - - System.out.println("=== RunnableTest ==="); - - // Anonymous Runnable - Runnable r1 = new Runnable() { - @Override - public void run() { - System.out.println("Hello world one!"); - } - }; - - // Lambda Runnable - Runnable r2 = () -> System.out.println("Hello world two!"); - - // Run em! - r1.run(); - r2.run(); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/reactive/TestRx.java b/src/main/java/io/github/ehlxr/reactive/TestRx.java deleted file mode 100644 index 15dbe8e..0000000 --- a/src/main/java/io/github/ehlxr/reactive/TestRx.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.reactive; - -import rx.Observable; -import rx.schedulers.Schedulers; - -/** - * Created by ehlxr on 2018/1/16. - */ -public class TestRx { - public static void main(String[] args) { - TestRx testRx = new TestRx(); - testRx.testAsyncCompositeJoin(); - // testRx.testAsyncCompositeJoin(); - } - - private void testAsyncCompositeJoin() { - System.out.println("Prepare for execution:Async Composite Join"); - long startTime = System.currentTimeMillis(); - - // Tasks oa -> oc, both in the same thread 1. - Observable oa = Observable.just("oa").observeOn(Schedulers.io()).flatMap( - soa -> { - System.out.println("oa Thread: " + Thread.currentThread().getName()); - return Observable.fromCallable(new TimeConsumingService("fa", 2000, new String[]{soa})); - } - ); - Observable oc = oa.flatMap( - res -> { - System.out.println("oc Thread: " + Thread.currentThread().getName()); - // System.out.println(res); - // System.out.println("Executed At: " + (System.currentTimeMillis() - startTime) + "ms"); - return Observable.fromCallable(new TimeConsumingService("fc", 1000, new String[]{res})); - }); - - // tasks ob -> (od,oe), ob, od, oe have special thread 2,3,4. - Observable ob = Observable.just("ob").observeOn(Schedulers.io()).flatMap( - sob -> { - System.out.println("ob Thread: " + Thread.currentThread().getName()); - return Observable.fromCallable(new TimeConsumingService("fb", 2000, new String[]{sob})); - } - ); - Observable od_oe = ob.flatMap( - res -> { - System.out.println("od_oe Thread: " + Thread.currentThread().getName()); - // System.out.println(res); - // System.out.println("Executed At: " + (System.currentTimeMillis() - startTime) + "ms"); - Observable od = Observable.just("od").observeOn(Schedulers.io()).flatMap( - sod -> { - System.out.println("od Thread: " + Thread.currentThread().getName()); - return Observable.fromCallable(new TimeConsumingService("fd", 1000, new String[]{sod})); - } - ); - Observable oe = Observable.just("oe").observeOn(Schedulers.io()).flatMap( - soe -> { - System.out.println("oe Thread: " + Thread.currentThread().getName()); - return Observable.fromCallable(new TimeConsumingService("fe", 1000, new String[]{soe})); - } - ); - return Observable.merge(od, oe); - }); - - System.out.println("Observable build: " + (System.currentTimeMillis() - startTime) + "ms"); - - // tasks join oc,(od_oe) and subscribe - Observable.merge(oc, od_oe).toBlocking().subscribe( - res -> { - System.out.println("ss Thread: " + Thread.currentThread().getName()); - // System.out.println(res); - // System.out.println("Executed At: " + (System.currentTimeMillis() - startTime) + "ms"); - }); - - System.out.println("End executed: " + (System.currentTimeMillis() - startTime) + "ms"); - } -} diff --git a/src/main/java/io/github/ehlxr/reactive/TestRx01.java b/src/main/java/io/github/ehlxr/reactive/TestRx01.java deleted file mode 100644 index 1877e3b..0000000 --- a/src/main/java/io/github/ehlxr/reactive/TestRx01.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.reactive; - - -import rx.Observable; -import rx.Subscriber; - -import java.util.concurrent.CountDownLatch; - -/** - * Created by ehlxr on 2018/1/16. - * 链式函数式处理 - */ -public class TestRx01 { - public static void main(String[] args) throws Exception { - // hello(1, 2, 3, 4, 5); - testRxJavaWithoutBlocking(10000); - - Observable.create((Observable.OnSubscribe) observer -> { - try { - if (!observer.isUnsubscribed()) { - for (int i = 1; i < 5; i++) { - observer.onNext(i); - } - observer.onCompleted(); - } - } catch (Exception e) { - observer.onError(e); - } - }).subscribe(new Subscriber() { - @Override - public void onNext(Integer item) { - System.out.println("Next: " + item); - } - - @Override - public void onError(Throwable error) { - System.err.println("Error: " + error.getMessage()); - } - - @Override - public void onCompleted() { - System.out.println("Sequence complete."); - } - }); - } - - private static void hello(Integer... integers) { - Observable workflow = Observable.from(integers) - .filter(i -> (i < 10) && (i > 0)) - .map(i -> i * 2).reduce((x, y) -> x + y); - workflow.subscribe(i -> System.out.print(i + "! ")); - } - - private static void testRxJavaWithoutBlocking(int count) throws Exception { - CountDownLatch finishedLatch = new CountDownLatch(1); - long t = System.nanoTime(); - - Observable.range(0, count) - .map(i -> 200) - .subscribe(s -> { - }, Throwable::printStackTrace, finishedLatch::countDown); - - finishedLatch.await(); - t = (System.nanoTime() - t) / 1000000; //ms - System.out.println("RxJavaWithoutBlocking TPS: " + count * 1000 / t); - } -} diff --git a/src/main/java/io/github/ehlxr/reactive/TimeConsumingService.java b/src/main/java/io/github/ehlxr/reactive/TimeConsumingService.java deleted file mode 100644 index 89f4ad1..0000000 --- a/src/main/java/io/github/ehlxr/reactive/TimeConsumingService.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.reactive; - -import java.util.Arrays; -import java.util.concurrent.Callable; - -/** - * Created by ehlxr on 2018/1/16. - */ -public class TimeConsumingService implements Callable { - - private final String service_name; - private final int wait_ms; - private final Object[] depandencies; - - TimeConsumingService(String name, Integer waiting, Object[] depandencies) { - this.service_name = name; - this.wait_ms = waiting; - this.depandencies = depandencies; - } - - @Override - public String call() throws Exception { - Thread.sleep(wait_ms); - return String.format("service %s exec time is: %d, depandencies: %s", service_name, wait_ms, Arrays.toString(depandencies)); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/readlogs/IReadLogs.java b/src/main/java/io/github/ehlxr/readlogs/IReadLogs.java deleted file mode 100644 index e6397de..0000000 --- a/src/main/java/io/github/ehlxr/readlogs/IReadLogs.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.readlogs; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -public interface IReadLogs { - String readFile(Date startDate, Date endDate, List mapids, String groupid, Map adxs); -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/redis/JRedisPoolConfig.java b/src/main/java/io/github/ehlxr/redis/JRedisPoolConfig.java deleted file mode 100644 index e92e308..0000000 --- a/src/main/java/io/github/ehlxr/redis/JRedisPoolConfig.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.redis; - -import java.io.InputStream; -import java.util.Properties; - -public class JRedisPoolConfig { - - public static String REDIS_IP; - public static int REDIS_PORT; - public static String REDIS_PASSWORD; - public static int MAX_ACTIVE; - public static int MAX_IDLE; - public static long MAX_WAIT; - public static boolean TEST_ON_BORROW; - public static boolean TEST_ON_RETURN; - - static { - init(); - } - - public static void init() { - try { - InputStream propFile = JRedisPoolConfig.class.getResourceAsStream("redis.properties"); - if(propFile != null){ - Properties p = new Properties(); - p.load(propFile); - REDIS_IP = p.getProperty("redis.ip"); - REDIS_PORT = Integer.parseInt(p.getProperty("redis.port")); - REDIS_PASSWORD = p.getProperty("redis.password"); - MAX_ACTIVE = Integer.parseInt(p.getProperty("redis.pool.maxActive")); - MAX_IDLE = Integer.parseInt(p.getProperty("redis.pool.maxIdle")); - MAX_WAIT = Integer.parseInt(p.getProperty("redis.pool.maxWait")); - TEST_ON_BORROW = Boolean.parseBoolean(p.getProperty("redis.pool.testOnBorrow")); - TEST_ON_RETURN = Boolean.parseBoolean(p.getProperty("redis.pool.testOnReturn")); - propFile.close(); - propFile=null; - }else{ - } - } catch (Exception e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/redis/JedisUtil.java b/src/main/java/io/github/ehlxr/redis/JedisUtil.java deleted file mode 100644 index c72e886..0000000 --- a/src/main/java/io/github/ehlxr/redis/JedisUtil.java +++ /dev/null @@ -1,411 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.redis; - -import io.github.ehlxr.SerializeUtil; -import org.springframework.util.StringUtils; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; - - -public class JedisUtil { - - - private static JedisPool jedisPool = null; - - /** 缓存生存时间 */ - private final static int expire = 60000; - - private final static String PUBLISH_CHANNEL = "dsp_news"; - - private static final int DEFAULT_SINGLE_EXPIRE_TIME = 3; - - private static final String CONST_STR = "_storm"; - - static { - JedisPoolConfig config = new JedisPoolConfig(); - config.setMaxTotal(JRedisPoolConfig.MAX_ACTIVE); - config.setMaxIdle(JRedisPoolConfig.MAX_IDLE); - config.setMaxWaitMillis(JRedisPoolConfig.MAX_WAIT); - config.setTestOnBorrow(JRedisPoolConfig.TEST_ON_BORROW); - config.setTestOnReturn(JRedisPoolConfig.TEST_ON_RETURN); - // redis如果设置了密码: - if (StringUtils.isEmpty(JRedisPoolConfig.REDIS_PASSWORD)) { - jedisPool = new JedisPool(config, JRedisPoolConfig.REDIS_IP, - JRedisPoolConfig.REDIS_PORT, 10000); - } else { - jedisPool = new JedisPool(config, JRedisPoolConfig.REDIS_IP, - JRedisPoolConfig.REDIS_PORT, 10000, - JRedisPoolConfig.REDIS_PASSWORD); - } - } - - public static JedisPool getPool() { - return jedisPool; - } - - /** - * 从jedis连接池中获取获取jedis对象 - */ - public static Jedis getJedis() { - return jedisPool.getResource(); - } - - /** - * 回收jedis - */ - public static void returnJedis(Jedis jedis) { - // if (jedis != null) - // jedisPool.returnResource(jedis); - } - - /** - * 设置过期时间 - */ - public static void expire(String key, int seconds) { - if (seconds <= 0) { - return; - } - Jedis jedis = getJedis(); - jedis.expire(key, seconds); - returnJedis(jedis); - } - - /** - * 设置默认过期时间 - */ - public static void expire(String key) { - expire(key, expire); - } - - public static void set(String key, String value) { - if (isBlank(key)) - return; - Jedis jedis = getJedis(); - jedis.set(key, value); - returnJedis(jedis); - } - - public static void set(String key, Object value) { - if (isBlank(key)) - return; - Jedis jedis = getJedis(); - jedis.set(key.getBytes(), SerializeUtil.serialize(value)); - returnJedis(jedis); - } - - public static void set(String key, int value) { - if (isBlank(key)) - return; - set(key, String.valueOf(value)); - } - - public static void set(String key, long value) { - if (isBlank(key)) - return; - set(key, String.valueOf(value)); - } - - public static void set(String key, float value) { - if (isBlank(key)) - return; - set(key, String.valueOf(value)); - } - - public static void set(String key, double value) { - if (isBlank(key)) - return; - set(key, String.valueOf(value)); - } - - public static Float getFloat(String key) { - if (isBlank(key)) - return null; - return Float.valueOf(getStr(key)); - } - - public static Double getDouble(String key) { - if (isBlank(key)) - return null; - return Double.valueOf(getStr(key)); - } - - public static Long getLong(String key) { - if (isBlank(key)) - return null; - return Long.valueOf(getStr(key)); - } - - public static Integer getInt(String key) { - if (isBlank(key)) - return null; - return Integer.valueOf(getStr(key)); - } - - public static String getStr(String key) { - if (isBlank(key)) - return null; - Jedis jedis = getJedis(); - String value = jedis.get(key); - returnJedis(jedis); - return value; - } - - public static Object getObj(String key) { - if (isBlank(key)) - return null; - Jedis jedis = getJedis(); - if(jedis.get(key.getBytes()) == null) { - return null; - } - byte[] bits = jedis.get(key.getBytes()); - Object obj = SerializeUtil.unserialize(bits); - returnJedis(jedis); - return obj; - } - - public static void delete(String key) { - Jedis jedis = getJedis(); - if (jedis.get(key) != null) { - jedis.del(key); - } - returnJedis(jedis); - } - - public static String[] getKeys(String pattern) { - if(isBlank(pattern)) { - return null; - } - Jedis jedis = getJedis(); - Set keySet = jedis.keys(pattern); - String[] keys = new String[keySet.size()]; - int index = 0; - for(String key : keySet) { - keys[index] = key; - index ++; - } - returnJedis(jedis); - return keys; - } - - public static void deleteByPattern(String pattern) { - Jedis jedis = getJedis(); - String[] keys = getKeys(pattern); - if(keys != null && keys.length != 0) { - if(keys.length == 1) { - jedis.del(keys[0]); - }else { - jedis.del(keys); - } - } - returnJedis(jedis); - } - - public static Set sget(String key) { - Jedis jedis = getJedis(); - returnJedis(jedis); - return jedis.smembers(key); - } - - public static void sset(String key, String... members) { - Jedis jedis = getJedis(); - jedis.sadd(key, members); - returnJedis(jedis); - } - - public static boolean sismember(String key, String member) { - Jedis jedis = getJedis(); - boolean res = jedis.sismember(key, member); - returnJedis(jedis); - return res; - } - - public static void sdelete(String key, String... members) { - Jedis jedis = getJedis(); - jedis.srem(key, members); - returnJedis(jedis); - } - - public static void hset(String key, Map value) { - Jedis jedis = getJedis(); - jedis.hmset(key, value); - returnJedis(jedis); - } - - public static void hdelete(String key) { - Jedis jedis = getJedis(); - if (jedis.hgetAll(key) != null) { - jedis.del(key); - } - returnJedis(jedis); - } - - public static boolean isBlank(String str) { - return str == null || "".equals(str.trim()); - } - - public static boolean exists(String key) { - Jedis jedis = getJedis(); - boolean isexist = jedis.exists(key); - returnJedis(jedis); - return isexist; - } - - public static void publishNews(String str){ - Jedis jedis = getJedis(); - jedis.publish(PUBLISH_CHANNEL, str); - returnJedis(jedis); - } - - /** - * 锁在给定的等待时间内空闲,则获取锁成功 返回true, 否则返回false - * @param key - * @param timeout - * @param unit - * @return - */ - private static boolean trylock(String key) { - Jedis jedis = null; - TimeUnit timeUnit = TimeUnit.SECONDS; - long timeout = 4; - try { - jedis = getJedis(); - long nano = System.nanoTime(); - do { - Long i = jedis.setnx(key + CONST_STR, key); - if (i == 1) { - jedis.expire(key + CONST_STR, DEFAULT_SINGLE_EXPIRE_TIME); - return Boolean.TRUE; - } else { // 存在锁 - String desc = jedis.get(key + CONST_STR); - System.out.println(desc); - } - Thread.sleep(300); - } while ((System.nanoTime() - nano) < timeUnit.toNanos(timeout)); - } catch (RuntimeException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - returnJedis(jedis); - } - return Boolean.FALSE; - } - - /** - * 释放锁 - * @param key - */ - public static void unlock(String key) { - delete(key + CONST_STR); - } - - public static void setWithLock(String key, String value) { - Jedis jedis = null; - try { - jedis = getJedis(); - jedis.set(key, value); - if (jedis.get(key + CONST_STR) != null) { - unlock(key); - } - } catch (RuntimeException e) { - e.printStackTrace(); - } finally { - returnJedis(jedis); - } - } - - public static String getStrWithLock(String key) { - String value = null; - Jedis jedis = null; - try { - jedis = getJedis(); - if (jedis.get(key) != null && trylock(key)) { - value = jedis.get(key); - if (value == null) { - unlock(key); - } - } - } catch (RuntimeException e) { - e.printStackTrace(); - } finally { - returnJedis(jedis); - } - return value; - } - - public static void lpush(String key, String value) { - if (isBlank(key)) - return; - Jedis jedis = getJedis(); - jedis.lpush(key, value); - returnJedis(jedis); - } - - public static String[] hkeys(String key){ - if (isBlank(key)) - return null; - Jedis jedis = getJedis(); - Set keySet = jedis.hkeys(key); - List keys = new ArrayList(); - for(String hkey : keySet) { - keys.add(hkey); - } - returnJedis(jedis); - return keys.toArray(new String[keys.size()]); - } - - public static String hget(String key, String hkey) { - if (isBlank(key)||isBlank(hkey)) - return ""; - Jedis jedis = getJedis(); - String value = jedis.hget(key, hkey); - returnJedis(jedis); - - return value; - } - - public static List hmget(String key, String[] hkey) { - if (isBlank(key)) - return null; - Jedis jedis = getJedis(); - List value = jedis.hmget(key, hkey); - returnJedis(jedis); - - return value; - } - - public static void main(String[] args) { - JedisUtil.set("lxr", "hah ehlxr"); - System.out.println(JedisUtil.getStr("lxr")); - } -} diff --git a/src/main/java/io/github/ehlxr/redis/Main.java b/src/main/java/io/github/ehlxr/redis/Main.java deleted file mode 100644 index a0258e2..0000000 --- a/src/main/java/io/github/ehlxr/redis/Main.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021 xrv - * - * 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 io.github.ehlxr.redis; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.stereotype.Component; - -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -/** - * @author ehlxr - * @since 2021-08-29 12:18. - */ -@Component -public class Main implements ApplicationListener { - private static final Logger log = LoggerFactory.getLogger(Main.class); - @Autowired - @Qualifier("lettuceDAOImpl") - private RedisDAO redisDAO; - - @Override - public void onApplicationEvent(ContextRefreshedEvent event) { - Runnable runnable = () -> { - String uuid = UUID.randomUUID().toString(); - log.info("{} retry lock...", Thread.currentThread().getName()); - Boolean lock = redisDAO.getDistributedLock("lock", uuid, 30_000); - if (lock) { - log.info("{} get lock!", Thread.currentThread().getName()); - - try { - TimeUnit.SECONDS.sleep(1); - // ... - } catch (InterruptedException e) { - e.printStackTrace(); - } finally { - Boolean locak = redisDAO.releaseDistributedLock("lock", uuid); - log.info("{} release lock {}", Thread.currentThread().getName(), locak); - } - } - }; - new Thread(runnable, "t1").start(); - new Thread(runnable, "t2").start(); - } -} diff --git a/src/main/java/io/github/ehlxr/redis/RedisDAO.java b/src/main/java/io/github/ehlxr/redis/RedisDAO.java deleted file mode 100644 index a21b23d..0000000 --- a/src/main/java/io/github/ehlxr/redis/RedisDAO.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.redis; - -/** - * redis lock/滑动时间窗口限流 - * - * @author ehlxr - * @since 2021-07-15 22:42. - */ -public interface RedisDAO { - - /** - * 释放分布式锁时使用的 lua 脚本,保证原子性 - *

- * if (redis.call('get', KEYS[1]) == ARGV[1]) - * then - * return redis.call('del', KEYS[1]) - * else - * return 0 - * end - */ - String RELEASE_LOCK_LUA = "if (redis.call('get', KEYS[1]) == ARGV[1]) then return redis.call('del', KEYS[1]) else return 0 end"; - - /** - * 滑动窗口限流使用的 lua 脚本,保证原子性 - *

- * local key = KEYS[1]; - * local index = tonumber(ARGV[1]); - * local time_window = tonumber(ARGV[2]); - * local now_time = tonumber(ARGV[3]); - * local far_time = redis.call('lindex', key, index); - * if (not far_time) - * then - * redis.call('lpush', key, now_time); - * redis.call('pexpire', key, time_window+1000); - * return 1; - * end - * if (now_time - far_time > time_window) - * then - * redis.call('rpop', key); - * redis.call('lpush', key, now_time); - * redis.call('pexpire', key, time_window+1000); - * return 1; - * else - * return 0; - * end - */ - String SLIDE_WINDOW_LUA = "local key = KEYS[1];\n" + "local index = tonumber(ARGV[1]);\n" + "local time_window = tonumber(ARGV[2]);\n" + "local now_time = tonumber(ARGV[3]);\n" + "local far_time = redis.call('lindex', key, index);\n" + "if (not far_time)\n" + "then\n" + " redis.call('lpush', key, now_time);\n" + " redis.call('pexpire', key, time_window+1000);\n" + " return 1;\n" + "end\n" + "\n" + "if (now_time - far_time > time_window)\n" + "then\n" + " redis.call('rpop', key);\n" + " redis.call('lpush', key, now_time);\n" + " redis.call('pexpire', key, time_window+1000);\n" + " return 1;\n" + "else\n" + " return 0;\n" + "end"; - - /** - * 获取分布式锁 - * - * @param key key - * @param value value,需要保证全局唯一,用来删除分布式锁时判断身份使用 - * @param expireTime 锁过期时间,毫秒,防止业务崩溃未删除锁,导致死锁 - * @return 是否获取成功锁 - */ - Boolean getDistributedLock(String key, String value, long expireTime); - - /** - * 释放分布式锁 - * - * @param key key - * @param value value,需要和获取锁时传入的一致 - * @return 是否释放成功锁 - */ - Boolean releaseDistributedLock(String key, String value); - - /** - * 分布式限流队列,在时间窗口内(包含该时间点),判断是否达到限流的阀值 - * 本接口实现的方法通过加锁避免并发问题,性能不高。只是为了说明限流逻辑如何实现 - * - * @param key key - * @param count 限流阀值 - * @param timeWindow 限流时间窗口 - * @return 是否允许通过(通过即不进行限流) - */ - Boolean slideWindow(String key, int count, long timeWindow); - - /** - * 分布式限流队列,在时间窗口内(包含该时间点),判断是否达到限流的阀值 - * 本接口实现的方法通过 Lua 脚本避免并发问题,性能较高。 - * - * @param key key - * @param count 限流阀值 - * @param timeWindow 限流时间窗口 - * @return 是否允许通过(通过即不进行限流) - */ - Boolean slideWindowLua(String key, int count, long timeWindow); - -} - - diff --git a/src/main/java/io/github/ehlxr/redis/RedisTemplateConfig.java b/src/main/java/io/github/ehlxr/redis/RedisTemplateConfig.java deleted file mode 100644 index 8b17958..0000000 --- a/src/main/java/io/github/ehlxr/redis/RedisTemplateConfig.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.github.ehlxr.redis; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.StringRedisSerializer; - -/** - * @author ehlxr - */ -@Configuration -public class RedisTemplateConfig { - @Bean(name = "redisTemplate") - public RedisTemplate getRedisTemplate(RedisConnectionFactory factory) { - return buildRedisTemplateByString(factory); - } - - /** - * 构建 redisTemplate 使用 string序列化 - */ - public RedisTemplate buildRedisTemplateByString(RedisConnectionFactory factory) { - RedisTemplate redisTemplate = new RedisTemplate<>(); - redisTemplate.setConnectionFactory(factory); - redisTemplate.setKeySerializer(new StringRedisSerializer()); - redisTemplate.setValueSerializer(new StringRedisSerializer()); - redisTemplate.setHashKeySerializer(new StringRedisSerializer()); - redisTemplate.setHashValueSerializer(new StringRedisSerializer()); - return redisTemplate; - } -} diff --git a/src/main/java/io/github/ehlxr/redis/impl/JedisDAOImpl.java b/src/main/java/io/github/ehlxr/redis/impl/JedisDAOImpl.java deleted file mode 100644 index 75a23e3..0000000 --- a/src/main/java/io/github/ehlxr/redis/impl/JedisDAOImpl.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.redis.impl; - -import io.github.ehlxr.redis.RedisDAO; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import redis.clients.jedis.JedisCluster; -import redis.clients.jedis.params.SetParams; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * redis lock/滑动时间窗口限流 - * - * @author ehlxr - * @since 2021-07-15 22:44. - */ -// @Component("jedisDAOImpl") -public class JedisDAOImpl implements RedisDAO { - private final Logger log = LoggerFactory.getLogger(JedisDAOImpl.class); - - // @Autowired - private JedisCluster jc; - - @Override - public Boolean getDistributedLock(String key, String value, long expireTime) { - String set = null; - try { - set = jc.set(key, value, SetParams.setParams().nx().px(expireTime)); - log.debug("getLock redis key: {}, value: {}, expireTime: {}, result: {}", key, value, expireTime, set); - } catch (Exception e) { - log.error("getLock redis key: {}, value: {}, expireTime: {}", key, value, expireTime, e); - } - return "OK".equals(set); - } - - @Override - public Boolean releaseDistributedLock(String key, String value) { - Object eval = null; - try { - eval = jc.eval(RELEASE_LOCK_LUA, Collections.singletonList(key), Collections.singletonList(value)); - log.debug("releaseLock redis key: {}, value: {}, result: {}", key, value, eval); - } catch (Exception e) { - log.error("releaseLock redis key: {}, value: {}", key, value, e); - } - return Long.valueOf(1L).equals(eval); - } - - @Override - public synchronized Boolean slideWindow(String key, int count, long timeWindow) { - if (count <= 0 || timeWindow <= 0) { - return false; - } - try { - // 获取当前时间 - long nowTime = System.currentTimeMillis(); - // 获取队列中,达到限流数量的位置,存储的时间戳 - String farTime = jc.lindex(key, count - 1); - // 如果为空,说明限流队列还没满,则允许通过,并添加当前时间戳到队列开始位置 - if (farTime == null) { - jc.lpush(key, String.valueOf(nowTime)); - // 给限流队列增加过期时间,防止长时间不用导致内存一直占用 - jc.pexpire(key, timeWindow + 1000L); - return true; - } - - // 队列已满(达到限制次数),用当前时间戳 减去 最早添加的时间戳 - if (nowTime - Long.parseLong(farTime) > timeWindow) { - // 若结果大于 timeWindow,则说明在 timeWindow 内,通过的次数小于等于 count - // 允许通过,并删除最早添加的时间戳,将当前时间添加到队列开始位置 - jc.rpop(key); - jc.lpush(key, String.valueOf(nowTime)); - // 给限流队列增加过期时间,防止长时间不用导致内存一直占用 - jc.pexpire(key, timeWindow + 1000L); - return true; - } - // 若结果小于等于 timeWindow,则说明在 timeWindow 内,通过的次数大于 count - // 不允许通过 - return false; - } catch (Exception e) { - log.error("[logId:{}]", e); - return false; - } - } - - @Override - public Boolean slideWindowLua(String key, int count, long timeWindow) { - if (count <= 0 || timeWindow <= 0) { - return false; - } - Object eval = null; - try { - List argvList = new ArrayList<>(); - argvList.add(String.valueOf(count - 1)); - argvList.add(String.valueOf(timeWindow)); - argvList.add(String.valueOf(System.currentTimeMillis())); - eval = jc.eval(SLIDE_WINDOW_LUA, Collections.singletonList(key), argvList); - log.debug("slideWindowLua redis key: {}, count: {}, timeWindow: {}, result: {}", key, count, timeWindow, eval); - } catch (Exception e) { - log.error("slideWindowLua redis key: {}, count: {}, timeWindow: {}", key, count, timeWindow, e); - } - return Long.valueOf(1L).equals(eval); - } -} diff --git a/src/main/java/io/github/ehlxr/redis/impl/LettuceDAOImpl.java b/src/main/java/io/github/ehlxr/redis/impl/LettuceDAOImpl.java deleted file mode 100644 index 5d70625..0000000 --- a/src/main/java/io/github/ehlxr/redis/impl/LettuceDAOImpl.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.redis.impl; - -import io.github.ehlxr.redis.RedisDAO; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.ListOperations; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.script.DefaultRedisScript; -import org.springframework.data.redis.core.script.RedisScript; -import org.springframework.stereotype.Component; - -import java.util.Collections; -import java.util.concurrent.TimeUnit; - -/** - * @author ehlxr - * @since 2021-07-15 22:51. - */ -@Component("lettuceDAOImpl") -public class LettuceDAOImpl implements RedisDAO { - private static final Logger log = LoggerFactory.getLogger(LettuceDAOImpl.class); - - @Autowired - private RedisTemplate redisTemplate; - - @Override - public Boolean getDistributedLock(String key, String value, long expireTime) { - Boolean set = false; - try { - set = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.MILLISECONDS); - log.info("getLock redis key: {}, value: {}, expireTime: {}, result: {}", key, value, expireTime, set); - } catch (Exception e) { - log.error("getLock redis key: {}, value: {}, expireTime: {}", key, value, expireTime, e); - } - return set; - } - - @Override - public Boolean releaseDistributedLock(String key, String value) { - Long execute = null; - try { - RedisScript redisScript = new DefaultRedisScript<>(RELEASE_LOCK_LUA, Long.class); - execute = redisTemplate.execute(redisScript, Collections.singletonList(key), value); - log.debug("releaseLock redis key: {}, value: {}, result: {}", key, value, execute); - } catch (Exception e) { - log.error("releaseLock redis key: {}, value: {}", key, value, e); - } - return Long.valueOf(1L).equals(execute); - } - - @Override - public synchronized Boolean slideWindow(String key, int count, long timeWindow) { - try { - long nowTime = System.currentTimeMillis(); - ListOperations list = redisTemplate.opsForList(); - String farTime = list.index(key, count - 1); - if (farTime == null) { - list.leftPush(key, String.valueOf(nowTime)); - redisTemplate.expire(key, timeWindow + 1000L, TimeUnit.MILLISECONDS); - return true; - } - if (nowTime - Long.parseLong(farTime) > timeWindow) { - list.rightPop(key); - list.leftPush(key, String.valueOf(nowTime)); - redisTemplate.expire(key, timeWindow + 1000L, TimeUnit.MILLISECONDS); - return true; - } - return false; - } catch (Exception e) { - log.error("", e); - return false; - } - } - - @Override - public Boolean slideWindowLua(String key, int count, long timeWindow) { - if (count <= 0 || timeWindow <= 0) { - return false; - } - Long execute = null; - try { - RedisScript redisScript = new DefaultRedisScript<>(SLIDE_WINDOW_LUA, Long.class); - execute = redisTemplate.execute(redisScript, Collections.singletonList(key), String.valueOf(count - 1), String.valueOf(timeWindow), String.valueOf(System.currentTimeMillis())); - log.debug("slideWindowLua redis key: {}, count: {}, timeWindow: {}, result: {}", key, count, timeWindow, execute); - } catch (Exception e) { - log.error("slideWindowLua redis key: {}, count: {}, timeWindow: {}", key, count, timeWindow, e); - } - return Long.valueOf(1L).equals(execute); - } - -} diff --git a/src/main/java/io/github/ehlxr/redis/redis.properties b/src/main/java/io/github/ehlxr/redis/redis.properties deleted file mode 100644 index 5c0f22b..0000000 --- a/src/main/java/io/github/ehlxr/redis/redis.properties +++ /dev/null @@ -1,9 +0,0 @@ -redis.pool.maxActive=1024 -redis.pool.maxIdle=200 -redis.pool.maxWait=1000 -redis.pool.testOnBorrow=true -redis.pool.testOnReturn=true -#redis.ip=192.168.3.166 -redis.ip=115.182.33.143 -redis.port=47379 -redis.password= \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/sftp/SFTPUtil.java b/src/main/java/io/github/ehlxr/sftp/SFTPUtil.java deleted file mode 100644 index 62b3688..0000000 --- a/src/main/java/io/github/ehlxr/sftp/SFTPUtil.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.sftp; - -import com.jcraft.jsch.*; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.File; -import java.io.InputStream; -import java.util.Properties; -import java.util.Vector; - -/** - * SFTP工具类 - * - * @author ehlxr - */ -public class SFTPUtil { - private static final Log log = LogFactory.getLog(SFTPUtil.class); - private static String ip; - private static String user; - private static String psw; - private static int port; - - private static Session session = null; - private static Channel channel = null; - - static { - try { - InputStream propFile = SFTPUtil.class.getResourceAsStream("sftp.properties"); - if (propFile != null) { - Properties p = new Properties(); - p.load(propFile); - ip = p.getProperty("sftp.ip"); - user = p.getProperty("sftp.user"); - psw = p.getProperty("sftp.psw"); - String portStr = p.getProperty("sftp.port"); - port = (portStr != null ? Integer.parseInt(portStr) : -1); - propFile.close(); - propFile = null; - } - } catch (Exception e) { - log.error("读取sftp配置文件失败:" + e.getMessage()); - e.printStackTrace(); - } - } - - private static ChannelSftp getSFTP() throws Exception { - log.info("正在连接服务器[" + ip + "]....."); - ChannelSftp sftp = null; - JSch jsch = new JSch(); - if (port <= 0) { - // 连接服务器,采用默认端口 - session = jsch.getSession(user, ip); - } else { - // 采用指定的端口连接服务器 - session = jsch.getSession(user, ip, port); - } - - // 如果服务器连接不上,则抛出异常 - if (session == null) { - log.error("连接服务器[" + ip + "]失败....."); - throw new Exception("session is null"); - } - - // 设置登陆主机的密码 - session.setPassword(psw);// 设置密码 - // 设置第一次登陆的时候提示,可选值:(ask | yes | no) - session.setConfig("StrictHostKeyChecking", "no"); - // 设置登陆超时时间 - session.connect(30000); - - try { - // 创建sftp通信通道 - channel = session.openChannel("sftp"); - channel.connect(1000); - sftp = (ChannelSftp) channel; - log.info("连接服务器[" + ip + "]成功....."); - } catch (Exception e) { - log.error("服务器[" + ip + "]创建sftp通信通道失败:" + e.getMessage()); - e.printStackTrace(); - closeSFTP(); - } - return sftp; - } - - private static void closeSFTP() { - if (session != null && session.isConnected()) { - session.disconnect(); - } - if (channel != null && channel.isConnected()) { - channel.disconnect(); - } - } - - /** - * SFTP上传文件 - * - * @param desPath ftp服务器目录 - * @param desFileName 上传后的文件名 - * @param resFile 要上传的文件 - * @throws Exception - */ - public static void putFile(String desPath, String desFileName, File resFile) { - try { - ChannelSftp sftp = getSFTP(); - mkdirs(sftp, desPath); - - // 进入服务器指定的文件夹 - sftp.cd(desPath); - - sftp.put(resFile.getAbsolutePath(), desFileName, ChannelSftp.OVERWRITE); - log.info("文件[" + desPath + desFileName + "]上传完成..."); - closeSFTP(); - } catch (Exception e) { - log.error("文件[" + desPath + desFileName + "]上传失败:" + e.getMessage()); - e.printStackTrace(); - closeSFTP(); - } - } - - public static void main(String[] args) { - try { - SFTPUtil.putFile("/upload/222/1111", "212321.txt", new File("D:/1.txt")); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 在远程服务器创建多级目录 - * - * @param sftp - * @param desPath - * @throws Exception - */ - private static void mkdirs(ChannelSftp sftp, String desPath) throws Exception { - String[] paths = desPath.split("/"); - String path = ""; - for (int i = 0; i < paths.length; i++) { - path += paths[i] + "/"; - if (!isExistDir(sftp, path)) { - sftp.mkdir(path); - } - } - } - - /** - * 判断远程目录是否存在 - * - * @param sftp - * @param desPath - * @return - */ - private static boolean isExistDir(ChannelSftp sftp, String desPath) { - boolean isExist = false; - try { - Vector content = sftp.ls(desPath); - if (content != null) { - isExist = true; - } - } catch (SftpException e) { - isExist = false; - } - return isExist; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/sftp/sftp.properties b/src/main/java/io/github/ehlxr/sftp/sftp.properties deleted file mode 100644 index 2f008ed..0000000 --- a/src/main/java/io/github/ehlxr/sftp/sftp.properties +++ /dev/null @@ -1,4 +0,0 @@ -sftp.ip=192.168.3.166 -sftp.user=root -sftp.psw=PowerXene123 -sftp.port=22 \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/shiro/LoginLogoutTest.java b/src/main/java/io/github/ehlxr/shiro/LoginLogoutTest.java deleted file mode 100644 index ef65b98..0000000 --- a/src/main/java/io/github/ehlxr/shiro/LoginLogoutTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.shiro; - -import org.apache.shiro.SecurityUtils; -import org.apache.shiro.authc.AuthenticationException; -import org.apache.shiro.authc.UsernamePasswordToken; -import org.apache.shiro.config.IniSecurityManagerFactory; -import org.apache.shiro.subject.Subject; -import org.apache.shiro.util.Factory; -import org.junit.Assert; -import org.junit.Test; - -public class LoginLogoutTest { - @Test - public void testHelloworld() { - // 1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager - Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini"); - // 2、得到SecurityManager实例并绑定给SecurityUtils - org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); - SecurityUtils.setSecurityManager(securityManager); - // 3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证) - Subject subject = SecurityUtils.getSubject(); - UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123"); - try { - // 4、登录,即身份验证 - subject.login(token); - } catch (AuthenticationException e) { - // 5、身份验证失败 - } - Assert.assertEquals(true, subject.isAuthenticated()); // 断言用户已经登录 - // 6、退出 - subject.logout(); - } -} diff --git a/src/main/java/io/github/ehlxr/singleton/SingletonDcl.java b/src/main/java/io/github/ehlxr/singleton/SingletonDcl.java deleted file mode 100644 index a9fee12..0000000 --- a/src/main/java/io/github/ehlxr/singleton/SingletonDcl.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.singleton; - -import java.lang.reflect.Constructor; -import java.util.stream.IntStream; - -/** - * double check lock - *

- * 懒汉模式 - * - * @author ehlxr - * @since 2021-02-18 10:23. - */ -public class SingletonDcl { - private SingletonDcl() { - } - - private volatile static SingletonDcl INSTANCE; - - public static SingletonDcl getInstance() { - if (INSTANCE == null) { - synchronized (SingletonDcl.class) { - if (INSTANCE == null) { - // 非原子性操作 - // 有可能会出现 JVM 优化指令重排序 - INSTANCE = new SingletonDcl(); - } - } - } - - return INSTANCE; - } - - public static void main(String[] args) throws Exception { - IntStream.range(0, 5).parallel().forEach(i -> System.out.println(Thread.currentThread().getName() + " => " + SingletonDcl.getInstance())); - - // 反射破坏 - Constructor dc = SingletonDcl.class.getDeclaredConstructor(); - dc.setAccessible(true); - - System.out.println(dc.newInstance()); - System.out.println(dc.newInstance()); - System.out.println(dc.newInstance()); - } -} diff --git a/src/main/java/io/github/ehlxr/singleton/SingletonHungry.java b/src/main/java/io/github/ehlxr/singleton/SingletonHungry.java deleted file mode 100644 index 4bd9bb6..0000000 --- a/src/main/java/io/github/ehlxr/singleton/SingletonHungry.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.singleton; - -import java.io.*; -import java.util.stream.IntStream; - -/** - * 饿汉模式 - * - * @author ehlxr - * @since 2021-02-18 10:20. - */ -public class SingletonHungry implements Serializable { - private static final long serialVersionUID = -3654446367492818614L; - - private SingletonHungry() { - } - - private static final SingletonHungry INSTANCE = new SingletonHungry(); - - public static SingletonHungry getInstance() { - return INSTANCE; - } - - // 防止 jdk 反序列化破坏单例 - private Object readResolve() { - return INSTANCE; - } - - public static void main(String[] args) throws Exception{ - IntStream.range(0, 5).parallel().forEach(i -> System.out.println(Thread.currentThread().getName() + " => " + SingleTonStaticInnerClass.getInstance())); - - // 序列化破坏 - SingletonHungry instance = SingletonHungry.getInstance(); - ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton_file")); - // 序列化【写】操作 - oos.writeObject(instance); - File file = new File("singleton_file"); - ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); - - // 反序列化【读】操作 - SingletonHungry newInstance = (SingletonHungry) ois.readObject(); - System.out.println(instance); - System.out.println(newInstance); - System.out.println(instance == newInstance); - - } - -} diff --git a/src/main/java/io/github/ehlxr/sort/BubbleSort.java b/src/main/java/io/github/ehlxr/sort/BubbleSort.java deleted file mode 100644 index c7a4af7..0000000 --- a/src/main/java/io/github/ehlxr/sort/BubbleSort.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.sort; - -/** - * 冒泡排序 - *

- * 从无序序列头部开始,进行两两比较,根据大小交换位置,直到最后将最大(小)的数据元素交换到了无序队列的队尾,从而成为有序序列的一部分; - * 下一次继续这个过程,直到所有数据元素都排好序。 - *

- * 算法的核心在于每次通过两两比较交换位置,选出剩余无序序列里最大(小)的数据元素放到队尾。 - * 时间复杂度:O(n²) - * - * @author ehlxr - * @since 2020-10-01 16:40. - */ -public class BubbleSort { - - /** - * 冒泡排序算法的算法过程如下: - * ①. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 - * ②. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,最后的元素会是最大的数。 - * ③. 针对所有的元素重复以上的步骤,除了最后一个。 - * ④. 持续每次对越来越少的元素重复上面的步骤①~③,直到没有任何一对数字需要比较。 - */ - public static void sort(int[] arr) { - //外层:需要 length-1 次循环比较 - for (int i = 0; i < arr.length - 1; i++) { - - boolean flag = false; - //内层:每次循环需要两两比较的次数,每次比较后,都会将当前最大的数放到最后位置,所以每次比较次数递减一次 - for (int j = 0; j < arr.length - 1 - i; j++) { - if (arr[j] > arr[j + 1]) { - flag = true; - swap(arr, j, j + 1); - } - } - // System.out.println("Sorting: " + Arrays.toString(arr)); - if (!flag) { - break; - } - } - } - - public static void swap(int[] arr, int i, int j) { - // arr[i] = arr[i] + arr[j]; - // arr[j] = arr[i] - arr[j]; - // arr[i] = arr[i] - arr[j]; - - int tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; - } - - public static void main(String[] args) { - int[] arr = new int[80000]; - for (int i = 0; i < 80000; i++) { - arr[i] = (int) (Math.random() * 8000000); //生成一个[0, 8000000) 数 - } - - long startTime = System.currentTimeMillis(); - sort(arr); - System.out.printf("排序花费时间 %dms.", System.currentTimeMillis() - startTime); - } -} diff --git a/src/main/java/io/github/ehlxr/sort/HeapSort.java b/src/main/java/io/github/ehlxr/sort/HeapSort.java deleted file mode 100644 index 0d5c4b5..0000000 --- a/src/main/java/io/github/ehlxr/sort/HeapSort.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.sort; - -import java.util.Arrays; -import java.util.PriorityQueue; - -/** - * 堆排序 - *

- * 完全二叉树: - * 若设二叉树的深度为 h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边。 - *

- * 数组存储二叉树: - * 数组实现一个完全二叉树时,叶子节点可以按从上到下、从左到右的顺序依次添加到数组中 - * 父节点 i 的左子节点在位置:(2*i+1); - * 父节点 i 的右子节点在位置:(2*i+2); - * 子节点 i 的父节点在位置:(i-1)/2; - *

- * 堆: - * 堆是具有以下性质的完全二叉树: - * ① 每个结点的值都大于或等于其左右孩子结点的值,称为大顶堆(arr [i] >= arr [2i+1] && arr [i] >= arr [2i+2]) - * ② 每个结点的值都小于或等于其左右孩子结点的值,称为小顶堆(arr [i] <= arr [2i+1] && arr [i] <= arr [2i+2]) - *

- * 堆排序的基本思想是: - * ① 将待排序序列构造成一个大(小)顶堆,此时,整个序列的最大(小)值就是堆顶的根节点。 - * ② 将其与末尾元素进行交换,此时末尾就为最大(小)值。 - * ③ 然后将剩余 n-1 个元素重新构造成一个大(小)顶堆,这样会得到 n 个元素的次小(大)值。 - * ④ 如此反复执行,便能得到一个有序序列了。 - * - * @author ehlxr - * @since 2020-10-17 22:17. - */ -public class HeapSort { - public static void main(String[] args) { - int[] arr = {4, 6, 8, 5, 9}; - sort(arr); - System.out.println("results: " + Arrays.toString(arr)); - - // PriorityQueue queue = new PriorityQueue<>(); - // for (int val : arr) { - // queue.add(val); - // } - // System.out.println(Arrays.toString(queue.toArray())); - // - // - arr = new int[]{4, 6, 8, 5, 9}; - PriorityQueue maxHeap = new PriorityQueue<>(arr.length, (o1, o2) -> o2 - o1); - for (int val : arr) { - maxHeap.add(val); - } - System.out.println(Arrays.toString(maxHeap.toArray())); - } - - public static void sort(int[] arr) { - // 1. 将无序序列构建为一个堆 - for (int i = arr.length / 2 - 1; i >= 0; i--) { - // 从最后一个非叶子结点从下至上,从右至左调整结构 - adjustHeap(arr, i, arr.length); - } - System.out.println("max heap: " + Arrays.toString(arr)); - - // 2. 将堆顶元素与末尾元素交换,将最大元素"沉"到数组末端 - // 3. 重新调整结构,使其满足堆定义,然后继续交换堆顶元素与当前末尾元素,反复执行调整 + 交换,直到整个序列有序 - for (int j = arr.length - 1; j > 0; j--) { - swap(arr, 0, j); - - adjustHeap(arr, 0, j); - System.out.println(Arrays.toString(arr)); - } - } - - /** - * 调整大顶堆(仅是调整过程,建立在大顶堆已构建的基础上) - * - * @param arr 调整的数组 - * @param i 非叶子结点在数组中的索引 - * @param length 对多少个元素进行调整,length 在逐渐减少 - */ - public static void adjustHeap(int[] arr, int i, int length) { - // 先取出当前元素 i - int temp = arr[i]; - // 从 i 结点的左子结点开始,也就是 2i+1 处开始 - for (int k = i * 2 + 1; k < length; k = k * 2 + 1) { - // 如果左子结点小于右子结点,k 指向右子结点 - if (k + 1 < length && arr[k] < arr[k + 1]) { - k++; - } - // 如果子节点大于父节点,将子节点和父节点交换 - // if (arr[k] > arr[i]) { - // swap(arr, k, i); - if (arr[k] > temp) { - // 不用进行交换 - arr[i] = arr[k]; - - i = k; - } else { - break; - } - } - - // 将 temp 值放到最终的位置 - arr[i] = temp; - } - - public static void swap(int[] arr, int i, int j) { - int tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; - } -} diff --git a/src/main/java/io/github/ehlxr/sort/InsertSort.java b/src/main/java/io/github/ehlxr/sort/InsertSort.java deleted file mode 100644 index 6f37a66..0000000 --- a/src/main/java/io/github/ehlxr/sort/InsertSort.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.sort; - -/** - * 插入排序 - *

- * 基本思想是: - * 将数组中的所有元素依次跟前面已经排好的元素相比较,如果选择的元素比已排序的元素小, - * 则交换,直到全部元素都比较过为止。 - * - * @author ehlxr - * @since 2020-09-28 22:30. - */ -public class InsertSort { - - /** - * ①. 从第一个元素开始,该元素可以认为已经被排序 - * ②. 取出下一个元素(新元素),在已经排序的元素序列中从后向前扫描 - * ③. 如果该元素(已排序)大于新元素,将该元素移到下一位置 - * ④. 重复步骤 3,直到找到已排序的元素小于或者等于新元素的位置 - * ⑤. 将新元素插入到该位置后 - * ⑥. 重复步骤 ②~⑤ - */ - public static void sort(int[] arr) { - for (int i = 1; i < arr.length; i++) { - for (int j = i - 1; j >= 0; j--) { - if (arr[j + 1] < arr[j]) { - swap(arr, j, j + 1); - } else { - break; - } - } - // System.out.println("第" + i + "轮:" + Arrays.toString(arr)); - } - } - - public static void sort3(int[] arr) { - for (int i = 1; i < arr.length; i++) { - int j = i - 1; // 已排序的最后一个元素下标 - int temp = arr[i]; // 下一个元素(待排序元素) - for (; j >= 0; j--) { - if (temp < arr[j]) { - arr[j + 1] = arr[j]; // arr[j] 后移 - } else { - break; - } - } - - if (j + 1 != i) { - arr[j + 1] = temp; - } - // System.out.println("第" + i + "轮:" + Arrays.toString(arr)); - } - } - - public static void sort2(int[] arr) { - for (int i = 1; i < arr.length; i++) { - int temp = arr[i]; // 下一个元素(待排序元素) - int j = i - 1; // 已排序的最后一个元素下标 - while (j >= 0 && arr[j] > temp) { - arr[j + 1] = arr[j]; // arr[j] 后移 - j--; - } - - if (j + 1 != i) { - arr[j + 1] = temp; - } - // i=2, temp=1 - // 4, 9, 1, 8, 6, 2 - // 4, 9, 9, 8, 6, 2 - // 4, 4, 9, 8, 6, 2 - // 1, 4, 9, 8, 6, 2 - // System.out.println(Arrays.toString(arr)); - } - } - - public static void swap(int[] arr, int i, int j) { - // arr[i] = arr[i] + arr[j]; - // arr[j] = arr[i] - arr[j]; - // arr[i] = arr[i] - arr[j]; - - int tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; - } - - public static void main(String[] args) { - int[] arr = new int[80_000]; - for (int i = 0; i < 80_000; i++) { - arr[i] = (int) (Math.random() * 8_000_000); //生成一个[0, 8000000) 数 - } - // int[] arr = {4, 9, 1, 8, 6, 2}; - - - long startTime = System.currentTimeMillis(); - sort3(arr); - System.out.printf("排序花费时间 %dms.", System.currentTimeMillis() - startTime); - } -} diff --git a/src/main/java/io/github/ehlxr/sort/MergeSort.java b/src/main/java/io/github/ehlxr/sort/MergeSort.java deleted file mode 100644 index e7a12b9..0000000 --- a/src/main/java/io/github/ehlxr/sort/MergeSort.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.sort; - -import java.util.Arrays; - -/** - * 归并排序 - *

- * 归并排序算法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列, - * 每个子序列是有序的。然后再把有序子序列合并为整体有序序列。 - * - * @author ehlxr - * @since 2020-10-04 21:09. - */ -public class MergeSort { - public static void main(String[] args) { - int[] arr = new int[800_000]; - for (int i = 0; i < 800_000; i++) { - arr[i] = (int) (Math.random() * 80_000_000); //生成一个[0, 8000000) 数 - } - long startTime = System.currentTimeMillis(); - sort(arr); - System.out.printf("排序花费时间 %dms.", System.currentTimeMillis() - startTime); - - // int[] arr = {4, 9, 1, 8, 6, 2}; - // merge(new int[]{1, 4, 9}, new int[]{2, 6, 8}); - // System.out.println(Arrays.toString(sort(arr))); - } - - /** - * ①. 将序列每相邻两个数字进行归并操作,形成 floor (n/2) 个序列,排序后每个序列包含两个元素; - * ②. 将上述序列再次归并,形成 floor (n/4) 个序列,每个序列包含四个元素; - * ③. 重复步骤②,直到所有元素排序完毕 - */ - public static int[] sort(int[] arr) { - if (arr.length <= 1) { - return arr; - } - // arr.length/2 - int num = arr.length >> 1; - int[] left = Arrays.copyOfRange(arr, 0, num); - int[] right = Arrays.copyOfRange(arr, num, arr.length); - return merge(sort(left), sort(right)); - } - - /** - * 将两个有序的数组进行归并排序操作 - */ - public static int[] merge(int[] arr1, int[] arr2) { - int l1 = 0; - int l2 = 0; - int i = 0; - - int[] r = new int[arr1.length + arr2.length]; - while (l1 < arr1.length || l2 < arr2.length) { - if (l1 >= arr1.length) { - r[i++] = arr2[l2]; - l2++; - continue; - } - - if (l2 >= arr2.length) { - r[i++] = arr1[l1]; - l1++; - continue; - } - - if (arr1[l1] < arr2[l2]) { - r[i++] = arr1[l1]; - l1++; - } else { - r[i++] = arr2[l2]; - l2++; - } - } - return r; - } -} diff --git a/src/main/java/io/github/ehlxr/sort/QuickSort.java b/src/main/java/io/github/ehlxr/sort/QuickSort.java deleted file mode 100644 index 66b4a47..0000000 --- a/src/main/java/io/github/ehlxr/sort/QuickSort.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.sort; - -import java.util.Arrays; - -/** - * 快速排序 - *

- * 快速排序(Quicksort)是对冒泡排序的一种改进,借用了分治的思想, - * 它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分, - * 其中一部分的所有数据都比另外一部分的所有数据都要小, - * 然后再按此方法对这两部分数据分别进行快速排序, - * 整个排序过程可以递归进行,以此达到整个数据变成有序序列。 - * - * @author ehlxr - * @since 2020-10-01 16:40. - */ -public class QuickSort { - public static void main(String[] args) { - // int[] arr = {4, 9, 1, 8, 6, 2}; - int[] arr = new int[800_000]; - for (int i = 0; i < 800_000; i++) { - arr[i] = (int) (Math.random() * 80_000_000); //生成一个[0, 8000000) 数 - } - long startTime = System.currentTimeMillis(); - sort(arr, 0, arr.length - 1); - System.out.printf("排序花费时间 %dms.", System.currentTimeMillis() - startTime); - } - - /** - * 快速排序使用分治策略来把一个序列(list)分为两个子序列(sub-lists)。 - * 步骤为: - * ①. 从数列中挑出一个元素,称为 "基准"(pivot)。 - * ②. 重新排序数列,所有比基准值小的元素摆放在基准前面,所有比基准值大的元素摆在基准后面(相同的数可以到任一边)。 - * 在这个分区结束之后,该基准就处于数列的中间位置。这个称为分区(partition)操作。 - * ③. 递归地(recursively)把小于基准值元素的子数列和大于基准值元素的子数列排序。 - *

- * 递归到最底部时,数列的大小是零或一,也就是已经排序好了。 - * 这个算法一定会结束,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。 - * - * @param arr 待排序数组 - * @param l 左边界 - * @param r 右边界 - */ - public static void sort(int[] arr, int l, int r) { - if (l >= r) { - return; - } - - if (arr == null || arr.length <= 0) { - return; - } - - int i = l, j = r, - // 一般选择数组左边界作为基准 - k = l; - while (l < r) { - // 首先循环递减右边界,直到找到小于基准的元素,相互交换 - while (l < r && arr[r] >= arr[k]) { - r--; - } - swap(arr, k, r); - k = r; - - // 其次循环递增左边界,直到找到大于基准的元素,相互交换 - while (l < r && arr[l] <= arr[k]) { - l++; - } - swap(arr, k, l); - k = l; - // 循环以上步骤,直到 l 和 r 相遇 - } - // arr[k] = p; - // System.out.println("Sorting: " + Arrays.toString(arr)); - - sort(arr, i, k - 1); - sort(arr, k + 1, j); - } - - /* - * 左右指针法 - */ - // public static void sort(int[] arr, int low, int high) { - // if (arr == null || arr.length <= 0) { - // return; - // } - // if (low >= high) { - // return; - // } - // - // int left = low; - // int right = high; - // - // int key = arr[left]; - // - // while (left < right) { - // while (left < right && arr[right] >= key) { - // right--; - // } - // while (left < right && arr[left] <= key) { - // left++; - // } - // if (left < right) { - // swap(arr, left, right); - // } - // } - // swap(arr, low, left); - // System.out.println("Sorting: " + Arrays.toString(arr)); - // sort(arr, low, left - 1); - // sort(arr, left + 1, high); - // } - - /* - * 挖坑法递归 - */ - // public static void sort2(int[] arr, int low, int high) { - // if (arr == null || arr.length <= 0) { - // return; - // } - // if (low >= high) { - // return; - // } - // - // int left = low; - // int right = high; - // // 挖坑1:保存基准的值 - // int temp = arr[left]; - // - // while (left < right) { - // while (left < right && arr[right] >= temp) { - // right--; - // } - // //坑2:从后向前找到比基准小的元素,插入到基准位置坑1中 - // arr[left] = arr[right]; - // while (left < right && arr[left] <= temp) { - // left++; - // } - // //坑3:从前往后找到比基准大的元素,放到刚才挖的坑2中 - // arr[right] = arr[left]; - // } - // //基准值填补到坑3中,准备分治递归快排 - // arr[left] = temp; - // System.out.println("Sorting: " + Arrays.toString(arr)); - // sort2(arr, low, left - 1); - // sort2(arr, left + 1, high); - // } - - public static void swap(int[] arr, int low, int high) { - int tmp = arr[low]; - arr[low] = arr[high]; - arr[high] = tmp; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/sort/SelectSort.java b/src/main/java/io/github/ehlxr/sort/SelectSort.java deleted file mode 100644 index ac131ea..0000000 --- a/src/main/java/io/github/ehlxr/sort/SelectSort.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.sort; - -import java.util.Arrays; - -/** - * 选择排序 - *

- * 在未排序序列中找到最小(大)元素,存放到未排序序列的起始位置 - * - * @author ehlxr - * @since 2020-10-01 16:55. - */ -public class SelectSort { - - /** - * ①. 从待排序序列中,找到关键字最小的元素; - * ②. 如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换; - * ③. 从余下的 N - 1 个元素中,找出关键字最小的元素,重复①、②步,直到排序结束。 - */ - public static void sort(int[] arr) { - for (int i = 0; i < arr.length - 1; i++) { - // for (int j = i + 1; j < arr.length; j++) { - // if (arr[i] > arr[j]) { - // swap(arr, i, j); - // } - // } - int min = i; - for (int j = i + 1; j < arr.length; j++) { - if (arr[min] > arr[j]) { - min = j; - } - } - if (min != i) { - swap(arr, min, i); - } - System.out.println("Sorting: " + Arrays.toString(arr)); - } - } - - public static void swap(int[] arr, int i, int j) { - // arr[i] = arr[i] + arr[j]; - // arr[j] = arr[i] - arr[j]; - // arr[i] = arr[i] - arr[j]; - - int tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; - } - - public static void main(String[] args) { - sort(new int[]{4, 9, 1, 6, 8, 2}); - } -} diff --git a/src/main/java/io/github/ehlxr/sort/ShellSort.java b/src/main/java/io/github/ehlxr/sort/ShellSort.java deleted file mode 100644 index 07921a3..0000000 --- a/src/main/java/io/github/ehlxr/sort/ShellSort.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.sort; - -/** - * 希尔排序 - *

- * 先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序, - * 待整个序列中的记录 “基本有序” 时,再对全体记录进行依次直接插入排序。 - * - * @author ehlxr - * @since 2020-10-01 16:40. - */ -public class ShellSort { - /** - * ① 将待排序数组按照步长 gap 进行分组 - * ② 然后将每组的元素利用直接插入排序的方法进行排序 - * ③ 每次再将 gap 折半减小,循环上述 ①~② 操作;直到 gap=1 时,完成排序。 - *

- * 可以看到步长的选择是希尔排序的重要部分。只要最终步长为 1 任何步长序列都可以工作。 - * 一般来说最简单的步长取值是初次取数组长度的一半为增量,之后每次再减半,直到增量为 1 - */ - public static void sort(int[] arr, int gap) { - if (arr == null || arr.length <= 0 || gap < 1) { - return; - } - for (int i = 0; i < gap; i++) { - // 对按照 gap 进行分组的元素进行插入排序 - for (int j = gap + i; j < arr.length; j += gap) { - for (int k = j - gap; k >= 0; k -= gap) { - if (arr[k] > arr[k + gap]) { - swap(arr, k, k + gap); - } else { - break; - } - } - } - } - - // System.out.println(Arrays.toString(arr)); - - // 每次将 gap 折半减小,循环上述操作 - sort(arr, gap / 2); - } - - public static void sort2(int[] arr, int gap) { - if (arr == null || arr.length <= 0 || gap < 1) { - return; - } - for (int i = 0; i < gap; i++) { - // 对按照 gap 进行分组的元素进行插入排序 - for (int j = gap + i; j < arr.length; j += gap) { - int k = j - gap; - int temp = arr[j]; - for (; k >= 0; k -= gap) { - if (arr[k] > temp) { - arr[k + gap] = arr[k]; - } else { - break; - } - } - - if (k + gap != j) { - arr[k + gap] = temp; - } - } - } - // System.out.println(Arrays.toString(arr)); - - // 每次将 gap 折半减小,循环上述操作 - sort2(arr, gap / 2); - } - - public static void swap(int[] arr, int i, int j) { - int tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; - } - - public static void main(String[] args) { - int[] arr = new int[800_000]; - for (int i = 0; i < 800_000; i++) { - arr[i] = (int) (Math.random() * 80_000_000); //生成一个[0, 8000000) 数 - } - // int[] arr = {4, 9, 1, 8, 6, 2}; - - long startTime = System.currentTimeMillis(); - sort2(arr, arr.length / 2); - System.out.printf("排序花费时间 %dms.", System.currentTimeMillis() - startTime); - } - - // public static void sort(int[] arr) { - // int gap = arr.length / 2; - // for (; gap > 0; gap = gap / 2) { - // //不断缩小gap,直到1为止 - // for (int j = 0; (j + gap) < arr.length; j++) { - // //使用当前gap进行组内插入排序 - // for (int k = 0; (k + gap) < arr.length; k += gap) { - // //交换操作 - // if (arr[k] > arr[k + gap]) { - // arr[k] = arr[k] + arr[k + gap]; - // arr[k + gap] = arr[k] - arr[k + gap]; - // arr[k] = arr[k] - arr[k + gap]; - // } - // } - // } - // System.out.println(" Sorting: " + Arrays.toString(arr)); - // - // } - // } -} diff --git a/src/main/java/io/github/ehlxr/springamq/controller/ActivemqController.java b/src/main/java/io/github/ehlxr/springamq/controller/ActivemqController.java deleted file mode 100644 index 2c9b379..0000000 --- a/src/main/java/io/github/ehlxr/springamq/controller/ActivemqController.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.springamq.controller; - -import io.github.ehlxr.springamq.mq.producer.queue.QueueSender; -import io.github.ehlxr.springamq.mq.producer.topic.TopicSender; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.annotation.Resource; - - -/** - * @description controller测试 - */ -// @Controller -// @RequestMapping("/activemq") -public class ActivemqController { - - @Resource - QueueSender queueSender; - @Resource - TopicSender topicSender; - - /** - * 发送消息到队列 - * Queue队列:仅有一个订阅者会收到消息,消息一旦被处理就不会存在队列中 - * @param message - * @return String - */ - @ResponseBody - @RequestMapping("queueSender") - public String queueSender(@RequestParam("message")String message){ - String opt=""; - try { - queueSender.send("test.queue", message); - opt = "suc"; - } catch (Exception e) { - opt = e.getCause().toString(); - } - return opt; - } - - /** - * 发送消息到主题 - * Topic主题 :放入一个消息,所有订阅者都会收到 - * 这个是主题目的地是一对多的 - * @param message - * @return String - */ - @ResponseBody - @RequestMapping("topicSender") - public String topicSender(@RequestParam("message")String message){ - String opt = ""; - try { - topicSender.send("test.topic", message); - opt = "suc"; - } catch (Exception e) { - opt = e.getCause().toString(); - } - return opt; - } -} diff --git a/src/main/java/io/github/ehlxr/springamq/mq/consumer/queue/QueueReceiver1.java b/src/main/java/io/github/ehlxr/springamq/mq/consumer/queue/QueueReceiver1.java deleted file mode 100644 index abbfdb8..0000000 --- a/src/main/java/io/github/ehlxr/springamq/mq/consumer/queue/QueueReceiver1.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.springamq.mq.consumer.queue; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.TextMessage; - -/** - * @description 队列消息监听器 - */ -// @Component -public class QueueReceiver1 implements MessageListener { - - @Override - public void onMessage(Message message) { - try { - System.out.println("QueueReceiver1接收到消息:"+((TextMessage)message).getText()); - } catch (JMSException e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/io/github/ehlxr/springamq/mq/consumer/queue/QueueReceiver2.java b/src/main/java/io/github/ehlxr/springamq/mq/consumer/queue/QueueReceiver2.java deleted file mode 100644 index 1e8f1f4..0000000 --- a/src/main/java/io/github/ehlxr/springamq/mq/consumer/queue/QueueReceiver2.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.springamq.mq.consumer.queue; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.TextMessage; - -/** - * @description 队列消息监听器 - */ -// @Component -public class QueueReceiver2 implements MessageListener { - - @Override - public void onMessage(Message message) { - try { - System.out.println("QueueReceiver2接收到消息:"+((TextMessage)message).getText()); - } catch (JMSException e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/io/github/ehlxr/springamq/mq/consumer/topic/TopicReceiver1.java b/src/main/java/io/github/ehlxr/springamq/mq/consumer/topic/TopicReceiver1.java deleted file mode 100644 index 9f6345a..0000000 --- a/src/main/java/io/github/ehlxr/springamq/mq/consumer/topic/TopicReceiver1.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.springamq.mq.consumer.topic; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.TextMessage; - -/** - * @description Topic消息监听器 - */ -// @Component -public class TopicReceiver1 implements MessageListener{ - - @Override - public void onMessage(Message message) { - try { - System.out.println("TopicReceiver1接收到消息:"+((TextMessage)message).getText()); - } catch (JMSException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/springamq/mq/consumer/topic/TopicReceiver2.java b/src/main/java/io/github/ehlxr/springamq/mq/consumer/topic/TopicReceiver2.java deleted file mode 100644 index 2dbe2d5..0000000 --- a/src/main/java/io/github/ehlxr/springamq/mq/consumer/topic/TopicReceiver2.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.springamq.mq.consumer.topic; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.TextMessage; - -/** - * @description Topic消息监听器 - */ -// @Component -public class TopicReceiver2 implements MessageListener{ - - @Override - public void onMessage(Message message) { - try { - System.out.println("TopicReceiver2接收到消息:"+((TextMessage)message).getText()); - } catch (JMSException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/main/java/io/github/ehlxr/springamq/mq/producer/queue/QueueSender.java b/src/main/java/io/github/ehlxr/springamq/mq/producer/queue/QueueSender.java deleted file mode 100644 index 2e28553..0000000 --- a/src/main/java/io/github/ehlxr/springamq/mq/producer/queue/QueueSender.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.springamq.mq.producer.queue; - -import org.springframework.jms.core.JmsTemplate; -import org.springframework.jms.core.MessageCreator; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Session; - -/** - * @description 队列消息生产者,发送消息到队列 - */ -// @Component("queueSender") -public class QueueSender { - - // @Autowired - // @Qualifier("jmsQueueTemplate") - private JmsTemplate jmsTemplate;//通过@Qualifier修饰符来注入对应的bean - - /** - * 发送一条消息到指定的队列(目标) - * @param queueName 队列名称 - * @param message 消息内容 - */ - public void send(String queueName, final String message) { - jmsTemplate.send(queueName, new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - return session.createTextMessage(message); - } - }); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/springamq/mq/producer/topic/TopicSender.java b/src/main/java/io/github/ehlxr/springamq/mq/producer/topic/TopicSender.java deleted file mode 100644 index c0b65a0..0000000 --- a/src/main/java/io/github/ehlxr/springamq/mq/producer/topic/TopicSender.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.springamq.mq.producer.topic; - -import org.springframework.jms.core.JmsTemplate; -import org.springframework.jms.core.MessageCreator; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Session; - -/** - * @description Topic生产者发送消息到Topic - */ - -// @Component("topicSender") -public class TopicSender { - - // @Autowired - // @Qualifier("jmsTopicTemplate") - private JmsTemplate jmsTemplate; - - /** - * 发送一条消息到指定的队列(目标) - * - * @param topicName 队列名称 - * @param message 消息内容 - */ - public void send(String topicName, final String message) { - jmsTemplate.send(topicName, new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - return session.createTextMessage(message); - } - }); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test.txt b/src/main/java/io/github/ehlxr/test.txt deleted file mode 100644 index becb76a..0000000 --- a/src/main/java/io/github/ehlxr/test.txt +++ /dev/null @@ -1,2 +0,0 @@ -hello,world! -hello,world! diff --git a/src/main/java/io/github/ehlxr/test/DidSdkTest.java b/src/main/java/io/github/ehlxr/test/DidSdkTest.java deleted file mode 100644 index d8ff9d1..0000000 --- a/src/main/java/io/github/ehlxr/test/DidSdkTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; -// -// import cn.ceres.did.client.SdkClient; -// import cn.ceres.did.sdk.SdkProto; -// -// import java.util.concurrent.CountDownLatch; -// -// /** -// * @author ehlxr -// */ -// public class DidSdkTest { -// -// public static void main(String[] args) throws Exception { -// SdkClient client = new SdkClient("10.19.248.200", 30581); -// // SdkClient client = new SdkClient(); -// client.init(); -// client.start(); -// -// // client.invokeOneWay(new SdkProto(), 2000); -// // System.out.println(client.invokeSync(new SdkProto(), 2000).getDid()); -// CountDownLatch countDownLatch = new CountDownLatch(1); -// client.invokeAsync(new SdkProto(), 2000, responseFuture -> { -// System.out.println(responseFuture.getSdkProto().getDid()); -// countDownLatch.countDown(); -// }); -// countDownLatch.await(); -// client.shutdown(); -// } -// } diff --git a/src/main/java/io/github/ehlxr/test/DirList.java b/src/main/java/io/github/ehlxr/test/DirList.java deleted file mode 100644 index 0dfecc6..0000000 --- a/src/main/java/io/github/ehlxr/test/DirList.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.io.File; -import java.io.FilenameFilter; - -public class DirList { - public static void main(String[] args) { - File path = new File("D://"); - String arg = "dsp_impclk_15"; - String[] list; - if (arg.length() == 0) - list = path.list(); - else - list = path.list(new DirFilter(arg)); - for (int i = 0; i < list.length; ++i) { - System.out.println(list[i]); - } - } -} - -class DirFilter implements FilenameFilter { - String afn; - - DirFilter(String afn) { - this.afn = afn; - } - - public boolean accept(File dir, String name) { - String f = new File(name).getName(); - return f.indexOf(afn) != -1; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test/ExecBaics50Log.java b/src/main/java/io/github/ehlxr/test/ExecBaics50Log.java deleted file mode 100644 index de6ad1f..0000000 --- a/src/main/java/io/github/ehlxr/test/ExecBaics50Log.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.TimeZone; - -public class ExecBaics50Log { - - public static void main(String[] args) throws Exception { - StringBuffer sb = new StringBuffer(); - - FileReader reader = new FileReader("C:\\Users\\ehlxr\\Desktop\\minisite\\20160606\\3\\2016-06-06(3、4、5).txt"); - BufferedReader br = new BufferedReader(reader); - String str = null; - while ((str = br.readLine()) != null) { - String[] split = str.split(","); - String ssString = ""; - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - for (String s : split) { - - String substring = s.substring(s.indexOf("=") + 1); - if (substring.contains("CST")) { - substring = formatDate(substring); - - - ssString += "'" + substring + "'"; - } else { - - ssString += "'" + substring + "',"; - } - } - - System.out.println( - "insert into user_info (`u_name`, `u_gender`, `u_tel`, `u_province`, `u_city`, `u_dealername`,`u_dealercode`, `u_scheduledtime`, `addtime`) VALUES(" - + ssString + ");"); - } - - br.close(); - reader.close(); - - } - - private static String formatDate(String date) throws Exception { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.ENGLISH); - TimeZone tz = TimeZone.getTimeZone("CST"); - sdf1.setTimeZone(tz); - sdf.setTimeZone(tz); - - Calendar c = Calendar.getInstance(); - c.setTime(sdf1.parse(date)); - - c.set(Calendar.HOUR, c.get(Calendar.HOUR) - 1); - return sdf.format(c.getTime()); - } -} diff --git a/src/main/java/io/github/ehlxr/test/IChargeCounter.java b/src/main/java/io/github/ehlxr/test/IChargeCounter.java deleted file mode 100644 index 6854113..0000000 --- a/src/main/java/io/github/ehlxr/test/IChargeCounter.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.math.BigDecimal; - -public interface IChargeCounter { - /** - * 按点击计费 - * - * @param campaignid - * @param groupid - * @param cost - */ - void chargeForThisResult(String campaignid, String groupid, BigDecimal cost); - - /** - * 投放次数控制 - * - * @param groupid - * @param count - * @param type - */ - void counterControlForThisSumResult(String groupid, int count, String type); -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test/LambdaTest.java b/src/main/java/io/github/ehlxr/test/LambdaTest.java deleted file mode 100644 index 92a2032..0000000 --- a/src/main/java/io/github/ehlxr/test/LambdaTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.util.Arrays; -import java.util.List; - -/** - * Created by ehlxr on 2017/6/20. - */ -public class LambdaTest { - public static void main(String[] args) { - // @FunctionalInterface 函数式接口 - new Thread(new Runnable() { - @Override - public void run() { - System.out.println("hello thread"); - } - }).start(); - new Thread(() -> System.out.println("hello lambda")).start(); - - List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7); - - System.out.println("------------打印集合元素----old way----"); - for (Integer n : list) { - System.out.println(n); - } - System.out.println("------------打印集合元素----new way----"); - // list.forEach(n -> System.out.println(n));// list.forEach((Integer n) -> {System.out.println(n)}); - list.forEach(System.out::println); - - System.out.println("------------求平方----old way------"); - for (Integer n : list) { - int x = n * n; - System.out.println(x); - } - System.out.println("------------求平方-----new way-----"); - // list.stream().map(n -> n * n).forEach(x -> System.out.println(x)); - list.stream().map(n -> n * n).forEach(System.out::println); - - System.out.println("------------求平方和----old way------"); - int sum = 0; - for (Integer n : list) { - int x = n * n; - sum = sum + x; - } - System.out.println(sum); - System.out.println("------------求平方和-----new way-----"); - System.out.println(list.stream().map(n -> n * n).reduce((x, y) -> x + y).get()); - - System.out.println(); - - } -} diff --git a/src/main/java/io/github/ehlxr/test/OOMTest.java b/src/main/java/io/github/ehlxr/test/OOMTest.java deleted file mode 100644 index 26b1d61..0000000 --- a/src/main/java/io/github/ehlxr/test/OOMTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021 xrv - * - * 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 io.github.ehlxr.test; - -import java.util.ArrayList; -import java.util.Random; - -/** - * -Xms600m -Xmx600m -XX:SurvivorRatio=8 -XX:+PrintGCDetails - * -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/Users/ehlxr/Downloads/hprof/1.hprof - * - * @author ehlxr - * @since 2021-08-08 21:26. - */ -public class OOMTest { - public static void main(String[] args) { - ArrayList list = new ArrayList<>(); - while (true) { - try { - Thread.sleep(5); - } catch (InterruptedException e) { - e.printStackTrace(); - } - list.add(new Picture(new Random().nextInt(100 * 50))); - } - } -} - -class Picture { - private final byte[] pixels; - - public Picture(int length) { - this.pixels = new byte[length]; - } -} diff --git a/src/main/java/io/github/ehlxr/test/OperateKPIBudgetRedisData.java b/src/main/java/io/github/ehlxr/test/OperateKPIBudgetRedisData.java deleted file mode 100644 index d22c076..0000000 --- a/src/main/java/io/github/ehlxr/test/OperateKPIBudgetRedisData.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import io.github.ehlxr.redis.JedisUtil; - -import java.io.IOException; -import java.math.BigDecimal; - -public class OperateKPIBudgetRedisData { - - - public static void main(String[] args) throws IOException { - showSom("58d355d7-4c66-461c-b63c-146c149bdcac"); - // delete("c46b8885-4c1d-48f9-befb-3ba3a0f33d4a"); - } - - public static void showSom(String groupid){ - String[] keys = JedisUtil.getKeys("dsp_budget_*_"+groupid); - BigDecimal totals = new BigDecimal(0); - for (String key : keys) { - System.out.println(key+"-----------:"+JedisUtil.getStr(key)); - totals = totals.add(new BigDecimal(JedisUtil.getStr(key))); - } - System.out.println("budget_balance_"+groupid+"----------:"+JedisUtil.getStr("budget_balance_"+groupid)); - totals = totals.add(new BigDecimal(JedisUtil.getStr("budget_balance_"+groupid))); - System.out.println("-------------------------------------------------------------:"+totals.toPlainString()); - System.out.println(); - - totals = new BigDecimal(0); - keys = JedisUtil.getKeys("dsp_counter_*_"+groupid); - for (String key : keys) { - System.out.println(key+"-----------:"+JedisUtil.getStr(key)); - String[] split = JedisUtil.getStr(key).split(","); - if(split.length>1){ - totals = totals.add(new BigDecimal(split[1])); - }else{ - totals = totals.add(new BigDecimal(split[0])); - } - } - System.out.println("counter_balance_"+groupid+"---------:"+JedisUtil.getStr("counter_balance_"+groupid)); - String[] split = JedisUtil.getStr("counter_balance_"+groupid).split(","); - if(split.length>1){ - totals = totals.add(new BigDecimal(split[1])); - }else{ - totals = totals.add(new BigDecimal(split[0])); - } - System.out.println("-------------------------------------------------------------:"+totals.toPlainString()); - } - - - public static void delete(String groupid){ - - - String[] keys ={"d012aa41-35b8-4ef9-a3ee-9bc918d0da82", - "f26701ea-3bfc-4b4f-ae88-f39bff59c77c", - "a4e14ee1-1ae3-4e04-8850-c1345c5af200", - "d3ca7a1a-7a8d-4e43-be28-46f450a84d99", - "f9fdd963-558c-4d5a-b18f-c7d8386fac2d", - "a4dbe6b6-bd69-4bab-aa84-d5459860ad7b", - "6d3508d8-c978-4446-ba4c-895196af5021", - "033d5820-2ca8-4304-87ab-aaad6a0d0652", - "b4572eae-3f4f-46e2-95be-78ec3cb47b75", - "8c6f32fc-450d-4912-a7e3-7bbc7e4341a9", - "7275405b-b12d-4f8b-95a4-7274cbf3f942", - "6f1d947b-bc03-4560-b3ff-1200725f352c", - "52a9558d-bada-4e2b-8e71-d83ee40e804f", - "92b8bd98-6698-48b7-b402-5ccf49e9c674", - "b605daa7-6a85-40dc-8c5e-d9022e8fc3d2", - "853aad03-a2f5-4665-aaac-26aadd42be84", - "5f3668bf-ebb9-4db7-ac29-62216fd86f2d"}; - - for (String key : keys) { - JedisUtil.delete("dsp_mapid_"+key); - } - - - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test/StatisByHourModel.java b/src/main/java/io/github/ehlxr/test/StatisByHourModel.java deleted file mode 100644 index da1dd44..0000000 --- a/src/main/java/io/github/ehlxr/test/StatisByHourModel.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.math.BigDecimal; -import java.util.Date; - -public class StatisByHourModel { - private Date time; - - private String creativeid; - - private Short category; - - private Integer imprs; - - private Integer clks; - - private BigDecimal cost; - - private Integer downloads; - - private Integer regists; - - private Integer flag; - - private Date createtime; - - public Date getTime() { - return time; - } - - public void setTime(Date time) { - this.time = time; - } - - public String getCreativeid() { - return creativeid; - } - - public void setCreativeid(String creativeid) { - this.creativeid = creativeid == null ? null : creativeid.trim(); - } - - public Short getCategory() { - return category; - } - - public void setCategory(Short category) { - this.category = category; - } - - public Integer getImprs() { - return imprs; - } - - public void setImprs(Integer imprs) { - this.imprs = imprs; - } - - public Integer getClks() { - return clks; - } - - public void setClks(Integer clks) { - this.clks = clks; - } - - public BigDecimal getCost() { - return cost; - } - - public void setCost(BigDecimal cost) { - this.cost = cost; - } - - public Integer getDownloads() { - return downloads; - } - - public void setDownloads(Integer downloads) { - this.downloads = downloads; - } - - public Integer getRegists() { - return regists; - } - - public void setRegists(Integer regists) { - this.regists = regists; - } - - public Integer getFlag() { - return flag; - } - - public void setFlag(Integer flag) { - this.flag = flag; - } - - public Date getCreatetime() { - return createtime; - } - - public void setCreatetime(Date createtime) { - this.createtime = createtime; - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test/StudentTrace.java b/src/main/java/io/github/ehlxr/test/StudentTrace.java deleted file mode 100644 index 6d13f70..0000000 --- a/src/main/java/io/github/ehlxr/test/StudentTrace.java +++ /dev/null @@ -1,111 +0,0 @@ -package io.github.ehlxr.test; - -import java.util.ArrayList; -import java.util.List; - -/** - * 有一个学生浏览网页的记录程序,它将记录 每个学生访问过的网站地址。 - * 它由三个部分组成:Student、WebPage和StudentTrace三个类 - *

- * -XX:+HeapDumpBeforeFullGC -XX:HeapDumpPath=/Users/ehlxr/Downloads/hprof/student.hprof - * - * @author shkstart - * @create 16:11 - */ -public class StudentTrace { - static List webpages = new ArrayList<>(); - - - public static void createWebPages() { - for (int i = 0; i < 100; i++) { - WebPage wp = new WebPage(); - wp.setUrl("http://www." + i + ".com"); - wp.setContent(Integer.toString(i)); - webpages.add(wp); - } - } - - public static void main(String[] args) { - createWebPages();//创建了100个网页 - //创建3个学生对象 - Student st3 = new Student(3, "Tom"); - Student st5 = new Student(5, "Jerry"); - Student st7 = new Student(7, "Lily"); - - for (int i = 0; i < webpages.size(); i++) { - if (i % st3.getId() == 0) - st3.visit(webpages.get(i)); - if (i % st5.getId() == 0) - st5.visit(webpages.get(i)); - if (i % st7.getId() == 0) - st7.visit(webpages.get(i)); - } - webpages.clear(); - System.gc(); - - } -} - -class Student { - private int id; - private String name; - private List history = new ArrayList<>(); - - public Student(int id, String name) { - super(); - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getHistory() { - return history; - } - - public void setHistory(List history) { - this.history = history; - } - - public void visit(WebPage wp) { - if (wp != null) { - history.add(wp); - } - } -} - - -class WebPage { - private String url; - private String content; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } -} diff --git a/src/main/java/io/github/ehlxr/test/Test.java b/src/main/java/io/github/ehlxr/test/Test.java deleted file mode 100644 index ca2a20f..0000000 --- a/src/main/java/io/github/ehlxr/test/Test.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.io.IOException; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.StringJoiner; -import java.util.stream.Collectors; - -/** - * Created by ehlxr on 2016/12/15. - */ -public class Test { - public static void main(String[] args) throws IOException { - // String s0 = "kvill"; - // String s1 = "kvill"; - // String s2 = "kvill"; - // System.out.println(s0 == s1); - // System.out.println("**********"); - // s1.intern(); - // s2 = s2.intern(); //把常量池中"kvill"的引用赋给s2 - // System.out.println(s0 == s1); - // System.out.println(s0 == s1.intern()); - // System.out.println(s0 == s2); - - - // LinkedHashMap - System.out.println("*****LinkedHashMap*****"); - - LinkedHashMap map = new LinkedHashMap<>(); - map.put("a", "111"); - map.put("b", "222"); - map.put("c", "333"); - map.put("d", "444"); - map.put("a", "555"); - - System.out.println(map); - - - // The String "[George:Sally:Fred]" may be constructed as follows: - - StringJoiner sj = new StringJoiner(":", "[", "]"); - sj.add("George").add("Sally").add("Fred"); - System.out.println(sj); - // A StringJoiner may be employed to create formatted output from a java.util.stream.Stream using java.util.stream.Collectors.joining(CharSequence). For example: - - List numbers = Arrays.asList(1, 2, 3, 4); - String commaSeparatedNumbers = numbers.stream() - .map(Object::toString) - .collect(Collectors.joining(", ")); - System.out.println(commaSeparatedNumbers); - - - System.out.println("------------" + (-1 >>> Integer.numberOfLeadingZeros(3))); - - String s = new String("1"); - String t = new String("1"); - String s1 = s.intern(); - String s2 = "1"; - System.out.println(s == s1); - System.out.println(s1 == s2); - System.out.println(s == t); // false - System.out.println(s.intern() == t.intern()); // true - - System.in.read(); - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestAudiQ2.java b/src/main/java/io/github/ehlxr/test/TestAudiQ2.java deleted file mode 100644 index 92bc43d..0000000 --- a/src/main/java/io/github/ehlxr/test/TestAudiQ2.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import io.github.ehlxr.utils.HttpClientUtil; - -public class TestAudiQ2 { - public static String URL = "http://127.0.0.1:8080/Audi2016Q2Wap/getUserInfo"; - - public static void main(String[] args) throws Exception { - System.out.println(HttpClientUtil.sendPostJSONData(URL, "")); - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestCalendar.java b/src/main/java/io/github/ehlxr/test/TestCalendar.java deleted file mode 100644 index 5ffd585..0000000 --- a/src/main/java/io/github/ehlxr/test/TestCalendar.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.util.Calendar; -import java.util.TimeZone; - -/** - * Created by ehlxr on 2016/8/11. - */ -public class TestCalendar { - - public static void main(String[] args) { - long date = 1470844800000l; - Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8")); - TimeZone timeZone = calendar.getTimeZone(); - System.out.println(timeZone); - calendar.setTimeInMillis(date); - - calendar.set(Calendar.HOUR_OF_DAY, 0); - - calendar.set(Calendar.MINUTE, 0); - - calendar.set(Calendar.SECOND, 0); - Long startDate = calendar.getTimeInMillis(); - System.out.println(startDate); - - calendar.setTimeInMillis(date); - - calendar.set(Calendar.HOUR_OF_DAY, 23); - - calendar.set(Calendar.MINUTE, 59); - - calendar.set(Calendar.SECOND, 59); - Long endDate = calendar.getTimeInMillis(); - System.out.println(endDate); - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestCode.java b/src/main/java/io/github/ehlxr/test/TestCode.java deleted file mode 100644 index c609063..0000000 --- a/src/main/java/io/github/ehlxr/test/TestCode.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; - -public class TestCode { - - public static void main(String[] args) throws Exception { - // TODO Auto-generated method stub - // String pathName = "/dsp/archer/dddfd/jkjl"; - // - // String projectName = pathName.substring(0, - // pathName.indexOf("archer")); - // - // System.out.println(projectName); - - // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); - // ParsePosition pos = new ParsePosition(0); - // System.out.println(formatter.parse("dsd", pos)); - - // System.out.println(parseDate("") - 2232); - - // Map resultMap = new HashMap(); - // System.out.println((String)resultMap.get("dd")); - - // try { - // String str = null; - // str.equals(""); - // } catch (Exception e) { - // System.out.println(e.getMessage()); - // e.printStackTrace(); - // } - // System.out.println("fffff"); - - // String[] s = {"111","eee"}; - // System.out.println(Arrays.toString(s)); - - // List list = new ArrayList(); - // list.add("2"); - // list.add("3"); - // list.add("7"); - // list.add("1"); - // - // System.out.println(list.toString()); - - // JSONArray areaTarget = new JSONArray(); - // areaTarget.add("3"); - // areaTarget.add("5"); - // areaTarget.add("4"); - // areaTarget.add("7"); - // System.out.println(JSONArray.toList(areaTarget)); - - // String whiteStr = "2,4,5,8,3"; - // System.out.println(JSONArray.fromObject(whiteStr.split(","))); - - // for (int i = 0;i<2;i++) { - // - // if ("1".equals("1")) { - // if ("1".equals("1")) { - // System.out.println("111111111111111"); - // continue; - // } - // System.out.println("2222222222222222"); - // } - // System.out.println("3333333333333333333333"); - // } - - // String str = "http://www.test.com"; - // System.out.println(str.replace("http://www.", "").replace("www.", - // "")); - - // SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); - // SimpleDateFormat sdf = new SimpleDateFormat("HH"); - // String str = "23:59:59"; - // System.out.println(sdf.format(formatter.parse(str))); - - // Spring Hessian代理Servelet - // String url = "http://localhost:8080/sync-logs/remote/readlogs"; - // HessianProxyFactory factory = new HessianProxyFactory(); - // - // IReadLogs readLogs = (IReadLogs) factory.create(IReadLogs.class, - // url); - // JSONArray result = JSONArray.fromObject(readLogs.readFile("2016-02-22 - // 15:00:00", "00000000000000")); - // System.out.println(result); - - // JSONArray jonsArr = new JSONArray(); - // JSONArray arr = new JSONArray(); - // jonsArr = JSONArray.fromObject("[ { 'category': 2, 'clks': 4, 'cost': - // 13, 'createtime': null, 'creativeid': - // 'cf0714f4-8b92-41f2-a843-19c94fe3af74', 'downloads': 0, 'flag': 0, - // 'imprs': 5, 'regists': 0, 'time': null } ]"); - // arr.addAll(JSONArray.toCollection(jonsArr)); - // System.out.println(arr); - - // String str = - // "20160222,18:59:50.523,DBG,ip:36.100.240.103,adx:3,bid:08a2d93b-0153-1000-fd75-3f89c5394190,mapid:62367312-d881-426d-81b4-fe635d1db989,deviceid:726e14bf3ba615e5387c256059e9f24a94721f76,deviceidtype:97,mtype:m"; - // for(String dd : str.split(",")){ - // - // System.out.println(dd); - // } - - // BigDecimal dd = new BigDecimal("1111.10"); - // JSONObject jj = new JSONObject(); - // jj.put("test", dd); - // System.out.println(jj.optDouble("test")); - - // JSONObject jj = new JSONObject(); - // System.out.println(jj.optString("pring")); - - - // // 根据网卡取本机配置的IP - // InetAddress inet = null; - // try { - // inet = InetAddress.getLocalHost(); - // } catch (UnknownHostException e) { - // e.printStackTrace(); - // } - // String ipAddress = inet.getHostAddress(); - // - // System.out.println(ipAddress); - - - // TestCode test = new TestCode(); - // System.out.println(test.dd("ddd")); - - - // Package pkg = Package.getPackage("osc.git.eh3.test"); - // Annotation[] annotations = pkg.getAnnotations(); - // for (Annotation annotation : annotations) { - // System.out.println(annotation); - // } - - // String[] arrs = new String[]{"111","111","2222"}; - // for (String string : Array2Set(arrs)) { - // - // System.out.println(string); - // } - - // Class clazz = StatisByHourModel.class; - // Method[] methods = clazz.getMethods(); - // for (Method method : methods) { - // System.out.println(method.getName()); - // } - // Object dd = new Date(); - // - // System.out.println(dd instanceof Date); - // - // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - // System.out.println(sdf.format(dd)); - - // JSONObject groupAdxs = JSONObject.fromObject("{\"4ebdb328-5d4b-42e6-80c3-a6aaaecdcea1\":[\"1e03319c-425d-4a17-a6bf-eeec2f48db29\",\"1fed4171-9925-4834-aa7b-9b4d3a58841b\",\"ce579246-e707-4cb9-b982-88cad7944b92\"],\"9262cbe8-a9dc-4f4e-888b-cf3ffe65defd\":\"ce579246-e707-4cb9-b982-88cad7944b92\"}"); - // Set keySet = groupAdxs.keySet(); - // for (Object object : keySet) { - // System.out.println(groupAdxs.get(object).getClass().isArray()); - // } - - // System.out.println(UUID.randomUUID().toString()); - - // System.out.println(new Integer(0x11)); - // System.out.println(Integer.toBinaryString(30000)); - // System.out.println(Integer.valueOf("11", 16)); - // System.out.println(Integer.valueOf("11", 2)); - - - // System.out.println(AESTool.encrypt("ehlxr")); - // System.out.println(AESTool.decrypt(AESEncrypter.encrypt("ehlxr"))); - - // System.out.println(AESTool.encrypt("liixangrong","adjdjfjfjfjdkdkd")); - // System.out.println(AESTool.decrypt("bfb0c038342ffead45511879853279bf","adjdjfjfjfjdkdkd")); - // System.out.println(Base64.encodeToString(AESTool.encrypt("fa4d7d90618dcba5fa1d969cffc04def","002020202").getBytes(), false)); - - // byte[] bytes = "ehlxr".getBytes(); - // for (int i = 0; i < bytes.length; i++) { - // System.out.println(bytes[i]); - // } - - // System.out.println(Base64.encodeToString("ehlxr".getBytes(), false)); - - // double lon1 = 109.0145193759; - // double lat1 = 34.236080797698; - // System.out.println(GeoHash.encode(lat1, lon1)); - // System.out.println(GeoHash.decode("wmtdgn5esrb1")[0]+" "+GeoHash.decode("wmtdgn5esrb1")[1]); - - // String url = "http://api.map.baidu.com/place/v2/search?query=银行&location=39.915,116.404&radius=2000&output=json&ak=LCG4dyrXyadeD8hFhi8SGCv6"; - // System.out.println(HttpClientUtil.sendGet(url)); - - // JSONArray array = new JSONArray(); - // array.add("1"); - // array.add("2"); - // array.add("3"); - // array.add("4"); - // array.add("5"); - // List list = JSONArray.toList(array, new String(), new JsonConfig()); - // System.out.println(list); - - // System.out.println(System.nanoTime()); - // System.out.println(System.nanoTime()); - - - // Map postParam = new HashMap(); - // postParam.put("groupid", "100003"); - // postParam.put("count", "1"); - // postParam.put("type", "m"); - // for(int i=0;i<5;i++){ - // try { - // HttpClientUtil.sendPostParam("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", postParam); - //// HttpClientUtil.sendPost("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", "groupid=100003&count=1&type=m"); - // break; - // } catch (Exception e) { - // System.out.println(e.getMessage()); - // try { - // Thread.sleep(1000); - // } catch (InterruptedException e1) { - // e1.printStackTrace(); - // } - // } - // } - - // String str = "0,"; - // System.out.println(str.split(",").length); - - // System.out.println(JedisUtil.getStr("0000")); - // Map result = new HashMap(); - // System.out.println(result.get("jj")); - // double budgets = 10000; - // System.out.println((budgets/100)); - - // String str = null; - // BigDecimal budget = new BigDecimal(str); - // budget = budget.subtract(new BigDecimal(10)); - // if (budget.compareTo(new BigDecimal(0)) <= 0) { - // System.out.println("1"); - // } else { - // System.out.println("2"); - // } - // System.out.println(budget.doubleValue()); - - // String REG_FLOAT = "^[1-9]\\d*.?\\d+$"; // 浮点正数 - // System.out.println(Pattern.compile(REG_FLOAT).matcher("1.21").matches()); - - // String str ="浮点数sss"; - // String s1 = new String(str.getBytes("utf-8"),"gbk"); - // System.out.println(s1); - // System.out.println(new String(s1.getBytes("gbk"))); - // System.out.println(); - //// - // String s2 = URLEncoder.encode(str, "utf-8"); - // System.out.println(s2); - // System.out.println(URLDecoder.decode(s2,"utf-8")); - - //System.out.println(new String(Hex.decodeHex("E8AFB7E6B182E5A4B1E8B4A5EFBC8CE8AFB7E7A88DE5908EE9878DE8AF95".toCharArray()), "utf-8")); - // Object object = null; - // JSONObject creativeGroupObj = JSONObject.fromObject(object); - // System.out.println(creativeGroupObj.isEmpty()); - // - // System.out.println(UUID.randomUUID().toString()); - - // JSONArray putTime = JSONArray.fromObject("[{\"monday\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"tuesday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"wednesday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"thursday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"friday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"saturday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},{\"sunday\":[\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]}]"); - // JSONArray periods = new JSONArray(); - // for (Object object : putTime) { - // JSONObject putTimeObj = JSONObject.fromObject(object); - // if (!putTimeObj.isEmpty()) { - // Set keySet = putTimeObj.keySet(); - // JSONObject period = new JSONObject(); - // for (String key : keySet) { - // JSONArray value = putTimeObj.optJSONArray(key); - // int start = -1,end = -1; - // StringBuffer sb = new StringBuffer(); - // for (int i = 0; i < value.size(); i++) { - // Object object2 = value.get(i); - // // 第一次出现 1 - // if (object2.equals("1") && start==-1) { - // start=i; - // end = 0; - // } - // // 出现1后的第一次出现0结束 - // if (object2.equals("0") && start>-1) { - // end=i-1; - // sb.append(start+"-"+end+","); - // start = -1;end = -1; - // } - // } - // period.put("week", key); - // period.put("ranges",sb.toString().substring(0, (sb.length()-1))); - // } - // periods.add(period); - // } - // } - // System.out.println(periods.toString()); - - // JSONObject period = new JSONObject(); - // period.put("test", 100.32); - // System.out.println(period.optString("test")); - - // BigDecimal clicks = new BigDecimal(100.23); - // System.out.println(clicks.intValue()); - - // System.out.println(Long.parseLong("8000.01")); - - // JSONObject jsonParam = new JSONObject(); - // JSONArray jsonArray = new JSONArray(); - // jsonArray.add("000000"); - // jsonParam.put("app", jsonArray); - // System.out.println(jsonParam); - - - // String head = "00,"; - // head = head.substring(0, head.lastIndexOf(",")); - // System.out.println(head); - // - // String ip = "127, 0, 0,1"; - // // String [] s = ip.split("."); - // String[] s = ip.split("\\,"); - // for (String string : s) { - // System.out.println(string); - // } - // - // Object str = null; - //// String dd = (String)str; - // String dd = String.valueOf(str); - // System.out.println(String.valueOf(str) == String.valueOf("null")); - - - //String sr = "2016-05-25 00:39:33,285 zanadu INFO \"39.159.247.16\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4\" \"http://site.pxene.com/Audi2016Q2Wap/?bid=7ef9ab83e32c4f9c80312b92fba261b1&mapid=0055cb29-dee1-4e77-81bb-0991d2d644c8\" \"load success:Audi load success:bid=7ef9ab83e32c4f9c80312b92fba261b1&mapid=0055cb29-dee1-4e77-81bb-0991d2d644c8\""; - //String[] split = sr.split("\""); - //for (String s1 : split) { - // System.out.println(s1); - //} - // - // - //String date = "Mon May 30 14:42:42 GMT+08:00 2016"; - //System.out.println(date); - // - //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - //SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US); - // - //System.out.println(sdf.format(sdf1.parse(date))); - // - //System.out.println("可吉可吉"); - - //JSONObject json = new JSONObject(); - //String ss = "233"; - //json.put("d","["+ss+"]"); - //System.out.println(json); - //System.out.println(Integer.parseInt("110000")); - - //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - //Calendar cl = Calendar.getInstance(); - //cl.setTime(new Date()); - //cl.add(Calendar.DAY_OF_MONTH,-1); - //String nowStr = sdf.format(cl.getTime()); - //System.out.println(nowStr); - - //Calendar calendar = Calendar.getInstance(); - //calendar.set(Calendar.HOUR_OF_DAY, 0); // 控制时 - //calendar.set(Calendar.MINUTE, 0); // 控制分 - //calendar.set(Calendar.SECOND, 1); // 控制秒 - // - //Date time = calendar.getTime(); // 得出执行任务的时间,此处为今天的00:00:01 - //System.out.println(time); - - //List list = new ArrayList(); - //list.add("str1"); - //list.add("str2"); - //int size = list.size(); - //String[] arr = list.toArray(new String[size]);//使用了第二种接口,返回值和参数均为结果 - - //String str = null; - //System.out.println((String)str == null); - - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); - String date = sdf.format(new java.util.Date(1477451581136L)); - - System.out.println(date); - - Long min = 19000001L; - Long mx = 19000500L; - - Long n = 19000000L; - - if ((n >= min && n <= mx) || (n >= min && n <= mx)) { - System.out.println("ture"); - } else { - System.out.println("false"); - } - - } - - public static Long parseDate(String s) { - Long time = null; - if (s == null || "" == s) { - time = null; - } else { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - try { - Date date = format.parse(s); - time = date.getTime(); - } catch (ParseException e) { - e.printStackTrace(); - } - } - return time; - } - - public B dd(B t) { - return t; - } - - public static Set Array2Set(T[] tArray) { - Set tSet = new HashSet(Arrays.asList(tArray)); - return tSet; - } - - public static void printArrs(T[] arrs) { - for (T t : arrs) { - System.out.println(t); - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test/TestCompletableFuture.java b/src/main/java/io/github/ehlxr/test/TestCompletableFuture.java deleted file mode 100644 index 39753ee..0000000 --- a/src/main/java/io/github/ehlxr/test/TestCompletableFuture.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.util.Random; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Future; - -/** - * https://colobu.com/2016/02/29/Java-CompletableFuture/ - * - * @author ehlxr - * @since 2020-12-18 10:12. - */ -public class TestCompletableFuture { - // public static void main(String[] args) throws ExecutionException, InterruptedException { - // ExecutorService es = Executors.newFixedThreadPool(10); - // Future f = es.submit(() -> { - // // 长时间的异步计算 - // Thread.sleep(3000); - // // 然后返回结果 - // return 100; - // }); - // // while (!f.isDone()); - // System.out.println(f.get()); - // } - - // public static CompletableFuture compute() { - // return new CompletableFuture<>(); - // } - // - // public static void main(String[] args) throws Exception { - // final CompletableFuture f = compute(); - // class Client extends Thread { - // final CompletableFuture f; - // - // Client(String threadName, CompletableFuture f) { - // super(threadName); - // this.f = f; - // } - // - // @Override - // public void run() { - // try { - // System.out.println(this.getName() + ": " + f.get()); - // } catch (InterruptedException | ExecutionException e) { - // e.printStackTrace(); - // } - // } - // } - // new Client("Client1", f).start(); - // new Client("Client2", f).start(); - // System.out.println("waiting"); - // // 完成,客户端 get() 阻塞通过 - // f.complete(100); - // //f.completeExceptionally(new Exception()); - // } - - - private static final long t = System.currentTimeMillis(); - - static int getMoreData() { - System.out.println("begin to start compute"); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - System.out.println("end to start compute. passed " + (System.currentTimeMillis() - t) / 1000 + " seconds"); - return 1000; - } - - public static void main(String[] args) throws Exception { - CompletableFuture future = CompletableFuture.supplyAsync(TestCompletableFuture::getMoreData); - Future f = future.whenComplete((v, e) -> { - System.out.println("the result is " + v); - e.printStackTrace(); - }); - // System.out.println(f.get()); - - System.out.println("wait for result....."); - - - CompletableFuture f1 = future.thenAccept((x) -> System.out.println("thenAccept " + x)); - // System.out.println(f1.get()); - - - CompletableFuture f2 = future.thenAcceptBoth(CompletableFuture.completedFuture(5), (x, y) -> System.out.println("thenAcceptBoth " + x * y)); - // System.out.println(f2.get()); - - Random rand = new Random(); - CompletableFuture future2 = CompletableFuture.supplyAsync(() -> { - try { - Thread.sleep(1000 + rand.nextInt(1000)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return 200; - }); - CompletableFuture f3 = future.applyToEither(future2, Object::toString); - System.out.println("applyToEither " + f3.get()); - - - CompletableFuture future3 = CompletableFuture.supplyAsync(() -> { - try { - Thread.sleep(1000 + rand.nextInt(1000)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return "abc"; - }); - CompletableFuture f4 = CompletableFuture.allOf(future, future2, future3); - // CompletableFuture f4 = CompletableFuture.anyOf(future, future2, future3); - // System.out.println("anyOf " + f4.get()); - - System.in.read(); - } - - -} diff --git a/src/main/java/io/github/ehlxr/test/TestCountDownLatch.java b/src/main/java/io/github/ehlxr/test/TestCountDownLatch.java deleted file mode 100644 index ca4c7bb..0000000 --- a/src/main/java/io/github/ehlxr/test/TestCountDownLatch.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; - -public class TestCountDownLatch { - private static final int N = 10; - - private static final Map cache = new ConcurrentHashMap<>(); - - public static void main(String[] args) throws InterruptedException { - CountDownLatch doneSignal = new CountDownLatch(N); - - for (int i = 1; i <= N; i++) { - new Thread(new Worker(i, doneSignal)).start();// 线程启动了 - } - System.out.println("begin------------"); - doneSignal.await();// 等待所有的线程执行完毕 - System.out.println("Ok"); - - System.out.println(cache.size()); - - Set keySet = cache.keySet(); - for (String key : keySet) { - System.out.println(key + " = " + cache.get(key)); - } - } - - static class Worker implements Runnable { - private final CountDownLatch doneSignal; - private int beginIndex; - - Worker(int beginIndex, CountDownLatch doneSignal) { - this.beginIndex = beginIndex; - this.doneSignal = doneSignal; - } - - public void run() { - beginIndex = (beginIndex - 1) * 10 + 1; - for (int i = beginIndex; i <= beginIndex + 10; i++) { - cache.put(i + "key", i); - } - doneSignal.countDown(); - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test/TestCounter.java b/src/main/java/io/github/ehlxr/test/TestCounter.java deleted file mode 100644 index 55eb020..0000000 --- a/src/main/java/io/github/ehlxr/test/TestCounter.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -public class TestCounter { - public static void main(String[] args) throws Exception { - - for (int i = 0; i < 8000; i++) { - new Thread(new TestThread()).start(); - // Thread.sleep(5); - } - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test/TestDecodeHex.java b/src/main/java/io/github/ehlxr/test/TestDecodeHex.java deleted file mode 100644 index bf143ec..0000000 --- a/src/main/java/io/github/ehlxr/test/TestDecodeHex.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import org.apache.commons.codec.binary.Hex; - -import java.nio.charset.StandardCharsets; - -/** - * Created by ehlxr on 2016/9/12. - */ -public class TestDecodeHex { - // 十六进制转字符串 - public static void main(String[] args) throws Exception { - String data = "E88194E7B3BBE4BABAE6B7BBE58AA0E5A4B1E8B4A5"; - System.out.println(new String(Hex.decodeHex(data.toCharArray()), StandardCharsets.UTF_8)); - - System.out.println(Hex.encodeHexString("测试粗我".getBytes())); - - - String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(1474963778670L)); - System.out.println(date); - - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestException.java b/src/main/java/io/github/ehlxr/test/TestException.java deleted file mode 100644 index e075848..0000000 --- a/src/main/java/io/github/ehlxr/test/TestException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -/** - * Created by ehlxr on 2016/8/31. - */ -public class TestException { - - public static void main(String[] args) { - System.out.println("0000"); - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestFile.java b/src/main/java/io/github/ehlxr/test/TestFile.java deleted file mode 100644 index 0719d44..0000000 --- a/src/main/java/io/github/ehlxr/test/TestFile.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; - -public class TestFile { - public static void main(String[] args) { - File file = new File("C:\\Users\\ehlxr\\Desktop\\20160628\\161845"); - BufferedReader reader = null; - try { - - reader = new BufferedReader(new FileReader(file)); - String tempString = null; - while ((tempString = reader.readLine()) != null) { - String[] tempArr = tempString.split("\\|"); - long time = Long.parseLong(tempArr[0]); - long rang = 1467100800000L; - if (time < rang) { - System.out.println(tempString); - } - } - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e1) { - } - } - } - - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestGeoHash.java b/src/main/java/io/github/ehlxr/test/TestGeoHash.java deleted file mode 100644 index 6670606..0000000 --- a/src/main/java/io/github/ehlxr/test/TestGeoHash.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import io.github.ehlxr.utils.GeoHash; - -public class TestGeoHash { - - - public static void main(String[] args) { - // double lon1 = 109.014520; - // double lat1 = 34.236080; - // - // double lon2 = 108.9644583556; - // double lat2 = 34.286439088548; - // double dist; - // String geocode; - // - // dist = CommonUtils.getDistance(lon1, lat1, lon2, lat2); - // System.out.println("两点相距:" + dist + " 米"); - // - // geocode = GeoHash.encode(lat1, lon1); - // System.out.println("当前位置编码:" + geocode); - // - // geocode = GeoHash.encode(lat2, lon2); - // System.out.println("远方位置编码:" + geocode); - // - // System.out.println(GeoHash.decode("wqjdb8mzw7vspswfydscen0002")[0]+" "+GeoHash.decode("wqjdb8mzw7vspswfydscen0002")[1]); - - double lon1 = 112.014520; - double lat1 = 69.236080; - System.out.println(GeoHash.encode(lat1, lon1)); - - double lat = 34.236088; - double lon = 109.01455; - System.out.println(GeoHash.encode(lat, lon)); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test/TestJdbc.java b/src/main/java/io/github/ehlxr/test/TestJdbc.java deleted file mode 100644 index 06e6176..0000000 --- a/src/main/java/io/github/ehlxr/test/TestJdbc.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import io.github.ehlxr.redis.JedisUtil; -import net.sf.json.JSONObject; - -import java.sql.*; -import java.util.Date; -import java.util.*; - -public class TestJdbc { - private static Connection getConn() { - String driver = "com.mysql.jdbc.Driver"; - String url = "jdbc:mysql://192.168.3.11:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000"; - String username = "root"; - String password = "pxene"; - Connection conn = null; - try { - Class.forName(driver); // classLoader,加载对应驱动 - conn = DriverManager.getConnection(url, username, password); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } - return conn; - } - - private static Integer getAll() { - Connection conn = getConn(); - String sql = "SELECT v.* FROM dsp_v_app_motionclick_day_count v WHERE v.time BETWEEN 1433088000000 AND 1453046400000 "; - // String sql = "SELECT * FROM dsp_t_ad_group_adx_creative WHERE groupid - // = 'd092c630-abfd-45a1-92f3-d0530c1caee8' LIMIT 1,3;"; - PreparedStatement pstmt; - try { - pstmt = conn.prepareStatement(sql); - ResultSet rs = pstmt.executeQuery(); - ResultSetMetaData metaData = rs.getMetaData(); - while (rs.next()) { - JSONObject jsonObject = new JSONObject(); - String time = ""; - String mapid = ""; - String appid = ""; - String adxtype = ""; - for (int i = 1; i <= metaData.getColumnCount(); i++) { - String columnName = metaData.getColumnName(i); - if ("time".equals(columnName)) { - time = rs.getString(i); - } - if ("mapid".equals(columnName)) { - mapid = rs.getString(i); - } - if ("appid".equals(columnName)) { - appid = rs.getString(i); - } - if ("adxtype".equals(columnName)) { - adxtype = rs.getString(i); - } - - jsonObject.put(columnName, rs.getString(i)); - } - Map map = new HashMap<>(); - map.put(time + "_" + appid + "_" + adxtype, jsonObject.toString()); - JedisUtil.hset("HistoryAPPData_" + mapid, map); - - // JedisUtil.lpush("HistoryAPPData_"+mapid+"_"+time, - // jsonObject.toString()); - System.out.println("HistoryAPPData_" + mapid); - } - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - - public static void main(String[] args) { - - insertData(); - - // getAll(); - // JedisUtil.deleteByPattern("HistoryAPPData_*"); - /* - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date start = new Date(); - - List mapids = getMapid(); - // String[] keys = JedisUtil.getKeys("HistoryAPPData_*"); - List alldata = new ArrayList(); - for (String mapid : mapids) { - String key = "HistoryAPPData_" + mapid; - String[] hkeys = JedisUtil.hkeys(key); -// for (String hkey : hkeys) { -// System.out.println(JedisUtil.hget(key, hkey)); -// } - if(hkeys.length>0){ - List hmget = JedisUtil.hmget(key, hkeys); - alldata.addAll(hmget); - } - } - System.out.println(alldata.size()); - Date end = new Date(); - System.out.println(sdf.format(start)); - System.out.println(sdf.format(end)); - */ - } - - private static List getMapid() { - List mapids = new ArrayList(); - Connection conn = getConn(); - String sql = "SELECT t2.id AS mapid FROM dsp_t_ad_group_creative t2 LEFT JOIN dsp_t_ad_group t3 ON t2.groupid = t3.id LEFT JOIN dsp_t_campaign t4 ON t3.campaignid = t4.id LEFT JOIN dsp_t_advertiser_account t5 ON t4.accountid = t5.id LEFT JOIN dsp_t_advertiser t6 ON t5.advertiserid = t6.id WHERE ( t4.accountid IN ( SELECT id FROM dsp_t_advertiser_account t6 WHERE t6.advertiserid IN ( SELECT id FROM dsp_t_advertiser t7 WHERE t7.parentid = 'dfecbd8a-2d7e-4941-bd89-e39c576c5ee5' ) ) OR t4.accountid = 'dfecbd8a-2d7e-4941-bd89-e39c576c5ee5' )"; - // String sql = "SELECT * FROM dsp_t_ad_group_adx_creative WHERE groupid - // = 'd092c630-abfd-45a1-92f3-d0530c1caee8' LIMIT 1,3;"; - PreparedStatement pstmt; - try { - pstmt = conn.prepareStatement(sql); - ResultSet rs = pstmt.executeQuery(); - ResultSetMetaData metaData = rs.getMetaData(); - while (rs.next()) { - for (int i = 1; i <= metaData.getColumnCount(); i++) { - mapids.add(rs.getString(i)); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } - return mapids; - } - - private static void insertData() { - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i > -1; i++) { - String cid = UUID.randomUUID().toString(); - String sql = "INSERT INTO `dsp_t_statis_by_day` (`time`, `creativeid`, `category`, `imprs`, `clks`, `cost`, `downloads`, `regists`, `flag`, `createtime`) VALUES ('2014-12-06 00:00:00', '" + cid + "', '2', '961', '9', '201860.7000', '0', '0', '0', '2015-09-14 15:07:42');"; - PreparedStatement pstmt; - try { - pstmt = conn.prepareStatement(sql); - pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestJdbc143.java b/src/main/java/io/github/ehlxr/test/TestJdbc143.java deleted file mode 100644 index 7ec5579..0000000 --- a/src/main/java/io/github/ehlxr/test/TestJdbc143.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Date; - -public class TestJdbc143 { - private static Connection getConn() { - String driver = "com.mysql.jdbc.Driver"; - String url = "jdbc:mysql://111.235.158.31:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000"; - String username = "root"; - String password = "pxene"; - Connection conn = null; - try { - Class.forName(driver); // classLoader,加载对应驱动 - conn = DriverManager.getConnection(url, username, password); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } - return conn; - } - - public static void main(String[] args) { - insertData(); - // updateData(); - } - - private static void insertData() { - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i < 1; i++) { - // String cid = UUID.randomUUID().toString(); - String cid = "0123456789"; - String sql = "INSERT INTO `dsp_t_statis_by_day` (`time`, `creativeid`, `category`, `imprs`, `clks`, `cost`, `downloads`, `regists`, `flag`, `createtime`) VALUES ('2014-12-06 00:00:00', '" + cid + "', '2', '961', '9', '201860.7000', '0', '0', '0', '2015-09-14 15:07:42');"; - PreparedStatement pstmt; - try { - pstmt = conn.prepareStatement(sql); - pstmt.executeUpdate(); - - if (i % 200 == 0) { - Thread.sleep(200); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } - - private static void updateData() { - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i < 800; i++) { - String sql = "UPDATE `dsp_t_statis_by_day` SET `clks`='" + i + "' WHERE `creativeid`='068860ba-2df2-42cb-bf66-f0515c5a83aa'"; - PreparedStatement pstmt; - try { - pstmt = conn.prepareStatement(sql); - pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestJdbc26.java b/src/main/java/io/github/ehlxr/test/TestJdbc26.java deleted file mode 100644 index dfcc43c..0000000 --- a/src/main/java/io/github/ehlxr/test/TestJdbc26.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Date; -import java.util.UUID; - -public class TestJdbc26 { - private static Connection getConn() { - String driver = "com.mysql.jdbc.Driver"; - String url = "jdbc:mysql://111.235.158.26:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000"; - String username = "root"; - String password = "pxene"; - Connection conn = null; - try { - Class.forName(driver); // classLoader,加载对应驱动 - conn = DriverManager.getConnection(url, username, password); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } - return conn; - } - - public static void main(String[] args) { - insertData(); - // updateData(); - } - - private static void insertData() { - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i > -1; i++) { - String cid = UUID.randomUUID().toString(); - String sql = "INSERT INTO `dsp_t_statis_by_day` (`time`, `creativeid`, `category`, `imprs`, `clks`, `cost`, `downloads`, `regists`, `flag`, `createtime`) VALUES ('2014-12-06 00:00:00', '" + cid + "', '2', '961', '9', '201860.7000', '0', '0', '0', '2015-09-14 15:07:42');"; - PreparedStatement pstmt; - try { - pstmt = conn.prepareStatement(sql); - pstmt.executeUpdate(); - if (i % 200 == 0) { - Thread.sleep(200); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } - - private static void updateData() { - Connection conn = getConn(); - System.out.println(new Date()); - for (int i = 0; i < 800; i++) { - String sql = "UPDATE `dsp_t_statis_by_day` SET `clks`='" + i + "' WHERE `creativeid`='068860ba-2df2-42cb-bf66-f0515c5a83aa'"; - PreparedStatement pstmt; - try { - pstmt = conn.prepareStatement(sql); - pstmt.executeUpdate(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - System.out.println(new Date()); - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestReadFile.java b/src/main/java/io/github/ehlxr/test/TestReadFile.java deleted file mode 100644 index 2e2d772..0000000 --- a/src/main/java/io/github/ehlxr/test/TestReadFile.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class TestReadFile { - - public static void readFile() { - File file = new File("C:/Users/ehlxr/Desktop/IPB.txt"); - BufferedReader reader = null; - Map resultMap = null; - List startList = null; - List endList = null; - try { - resultMap = new HashMap(); - startList = new ArrayList(); - endList = new ArrayList(); - - reader = new BufferedReader(new FileReader(file)); - String tempString = null; - while ((tempString = reader.readLine()) != null) { - String[] tempArr = tempString.split(" "); - - resultMap.put(tempArr[0], tempArr); - startList.add(Long.parseLong(tempArr[0])); - endList.add(Long.parseLong(tempArr[1])); - } - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e1) { - } - } - } - - long des = 17301504l; - long key = binarySearch(startList.toArray(new Long[startList.size()]), des); - String[] tempArr = (String[]) resultMap.get(key); - for (int i = 0; i < tempArr.length; i++) { - System.out.println(tempArr[i]); - } - } - - public static void readFile1() { - File file = new File("C:\\Users\\ehlxr\\Desktop\\白名单\\IMEI\\000000_0"); - BufferedReader reader = null; - try { - reader = new BufferedReader(new FileReader(file)); - String tempString = null; - while ((tempString = reader.readLine()) != null) { - System.out.println(tempString); - } - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException ignored) { - } - } - } - } - - public static void main(String[] args) { - readFile1(); - } - - /** - * * 二分查找算法 * * - * - * @param srcArray 有序数组 * - * @param des 查找元素 * - * @return des的数组下标,没找到返回-1 - */ - public static long binarySearch(Long[] srcArray, long des) { - int low = 0; - int high = srcArray.length - 1; - while (low <= high) { - int middle = (low + high) / 2; - if (des == srcArray[middle]) { - return middle; - } else if (des < srcArray[middle]) { - high = middle - 1; - } else { - low = middle + 1; - } - } - return -1; - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestReference.java b/src/main/java/io/github/ehlxr/test/TestReference.java deleted file mode 100644 index 3ca44e5..0000000 --- a/src/main/java/io/github/ehlxr/test/TestReference.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -/** - * Created by ehlxr on 2017/4/14. - */ -public class TestReference { - public static void main(String[] args) { - Person person = new Person(); - - person.age = 20; - person.name = "test20"; - System.out.println(person); - TestReference testReference = new TestReference(); - testReference.test(person); - System.out.println(person); - } - - public void test(Person person) { - person = new Person(); - person.age = 21; - person.name = "test21"; - } - - static class Person { - String name; - int age; - - @Override - public String toString() { - return "Person{" + - "name='" + name + '\'' + - ", age=" + age + - '}'; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestSingleThreadExecutor.java b/src/main/java/io/github/ehlxr/test/TestSingleThreadExecutor.java deleted file mode 100644 index d7376e6..0000000 --- a/src/main/java/io/github/ehlxr/test/TestSingleThreadExecutor.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -class MyThread extends Thread { - private final String name; - - - public MyThread(String name) { - this.name = name; - } - - - @Override - public void run() { - try { - Thread.sleep(500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.out.println(name + "正在进行。。。。。"); - } -} - - -public class TestSingleThreadExecutor { - public static void main(String[] args) { - ExecutorService executorService = Executors.newSingleThreadExecutor(); - Thread t1 = new MyThread("t1"); - Thread t2 = new MyThread("t2"); - Thread t3 = new MyThread("t3"); - Thread t4 = new MyThread("t4"); - executorService.execute(t1); - executorService.execute(t2); - executorService.execute(t3); - executorService.execute(t4); - executorService.shutdown(); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/test/TestString.java b/src/main/java/io/github/ehlxr/test/TestString.java deleted file mode 100644 index 1d38f35..0000000 --- a/src/main/java/io/github/ehlxr/test/TestString.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021 xrv - * - * 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 io.github.ehlxr.test; - -/** - * @author ehlxr - * @since 2021-05-14 16:17. - */ -public class TestString { - public static void main(String[] args) { - String s1 = "abc"; - String s2 = "ab"; - String s3 = s2 + "c"; - System.out.println(s1 == s3);//false - - String s4 = s3.intern(); - System.out.println(s1 == s3);//false - System.out.println(s1 == s4);//true - - String s5 = "abc"; - System.out.println(s1 == s5);//true - - String s6 = new String("abc"); - String s7 = new String("abc"); - System.out.println(s6 == s7);//false - - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestSyncLogData.java b/src/main/java/io/github/ehlxr/test/TestSyncLogData.java deleted file mode 100644 index 324b9c5..0000000 --- a/src/main/java/io/github/ehlxr/test/TestSyncLogData.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import com.caucho.hessian.client.HessianProxyFactory; -import io.github.ehlxr.readlogs.IReadLogs; -import net.sf.json.JSONArray; -import net.sf.json.JSONObject; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class TestSyncLogData { - - public static void main(String[] args) throws Exception { - List mapids = new ArrayList(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH"); - SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd_HH"); - - // 测试数据 - mapids.add("ad2176a7-74f2-4eab-965f-04c509653a93"); - mapids.add("63cae342-3288-4591-8097-53a9ac8bbe48"); - mapids.add("b38749f5-d5f9-441f-89de-a97c9b35adb0"); - mapids.add("3bc9a763-b5ad-4ade-a46c-12ce6f7a9479"); - mapids.add("cf384c11-0b25-4462-80ae-8a7eaedbf765"); - mapids.add("e9d823fe-379a-4d86-b9cd-93bb21c085a3"); - mapids.add("fa3c7262-4538-4192-bbca-ac1114f690c1"); - mapids.add("441af98d-917a-423a-ad3d-6faa8609e722"); - mapids.add("60112069-7c05-4135-8430-836ed61576e8"); - mapids.add("62367312-d881-426d-81b4-fe635d1db989"); - mapids.add("c41c1d40-1f71-44d2-88ab-478a584cd030"); - mapids.add("5f9735cf-6036-4902-9cff-5c7a40c76f24"); - - Map adxs = new HashMap<>(); - adxs.put("15", 1.0000); - adxs.put("14", 1.0000); - adxs.put("2", 1.0000); - adxs.put("8", 1.0000); - adxs.put("11", 1.0000); - adxs.put("1122331", 1.0000); - adxs.put("1", 1.0000); - adxs.put("4", 1.0000); - adxs.put("9", 1.0000); - adxs.put("13", 1.0000); - adxs.put("10", 1.0000); - adxs.put("5", 1.0000); - adxs.put("7", 1.0000); - adxs.put("112233", 1.0000); - adxs.put("3", 0.1569); - - HessianProxyFactory factory = new HessianProxyFactory(); - IReadLogs readLogs = (IReadLogs) factory.create(IReadLogs.class, "http://localhost:8080/sync-logs/remote/readlogs"); - String results = readLogs.readFile(sdf.parse("2016-02-24 09"), sdf.parse("2016-02-24 10"), mapids, - "6692a223-2ae1-439a-93f4-09fb36e718ef", adxs); - System.out.println(results); - JSONArray dataArr = new JSONArray(); - dataArr = JSONArray.fromObject(results); - // List dataList = (List) - // JSONArray.toCollection(dataArr, StatisByHourModel.class); - - // List> result = new ArrayList>(); - // for (Object object : dataArr) { - // if(object == null) { - // continue; - // } - // JSONObject data = JSONObject.fromObject(object); - // String time = data.optString("time"); - // if (result.size() <= 0) { - // Map resultMap = new HashMap(); - // resultMap.put("time", time); - // resultMap.put("imprs",data.optInt("imprs")); - // resultMap.put("clks", data.optInt("clks")); - // resultMap.put("cost", data.optDouble("cost")); - // - // result.add(resultMap); - // continue; - // } - // List> temp = new ArrayList>(); - // for (Map map : result) { - // if (time.equals(map.get("time"))) { - // map.put("imprs",((null == map.get("imprs") || - // "".equals(map.get("imprs"))) ? 0 : - // Integer.parseInt(map.get("imprs").toString())) + - // data.optInt("imprs")); - // map.put("clks",((null == map.get("clks") || - // "".equals(map.get("clks"))) ? 0 : - // Integer.parseInt(map.get("clks").toString())) + data.optInt("clks")); - // map.put("cost", ((null == map.get("cost") || - // "".equals(map.get("cost"))) ? 0 : - // Double.parseDouble(map.get("cost").toString()))+ - // data.optDouble("cost")); - // } else { - // Map resultMap = new HashMap(); - // resultMap.put("time", time); - // resultMap.put("imprs", data.optInt("imprs")); - // resultMap.put("clks", data.optInt("clks")); - // resultMap.put("cost",data.optInt("cost")); - // - // temp.add(resultMap); - // } - // } - // result.addAll(temp); - // } - // System.out.println(result); - - // JSONArray dataList = new JSONArray(); - // dataList.addAll(JSONArray.toCollection(JSONArray.fromObject(results))); - // List result = (List) - // JSONArray.toCollection(dataList, StatisByHourModel.class); - // for (StatisByHourModel statisByHourModel : result) { - // if(null==statisByHourModel){ - // continue; - // } - // System.out.println(statisByHourModel.getCreativeid()); - // } - - // dataArr.addAll(JSONArray.toCollection(JSONArray.fromObject(results))); - // List dataList = (List) - // JSONArray.toCollection(dataArr, StatisByHourModel.class); - - // List result = new ArrayList(); - // Map result = new HashMap<>(); - // - // for (StatisByHourModel data : dataList) { - // if(data == null) { - // continue; - // } - // String time = dateToStrLong(data.getTime()); - // - // if(result.containsKey(time)){ - // StatisByHourModel tempData = result.get(time); - // tempData.setImprs(tempData.getImprs()+data.getImprs()); - // tempData.setClks(tempData.getClks()+data.getClks()); - // tempData.setCost(tempData.getCost().add(data.getCost())); - // }else{ - // result.put(time, data); - // } - // } - - // Map> resultMap = new HashMap<>(); - // for (StatisByHourModel data : dataList) { - // if(data == null) { - // continue; - // } - // Map tData = new HashMap<>(); - // tData.put("time", sdf.format(data.getTime())); - // tData.put("imprs", data.getImprs()); - // tData.put("clks", data.getClks()); - // tData.put("cost", data.getCost()); - // - // String time = dateToStrLong(data.getTime()); - // if(resultMap.containsKey(time)){ - // Map tempData = resultMap.get(time); - // tempData.put("imprs",((null == tempData.get("imprs") || - // "".equals(tempData.get("imprs"))) ? 0 : - // Integer.parseInt(tempData.get("imprs").toString())) + - // data.getImprs()); - // tempData.put("clks",((null == tempData.get("clks") || - // "".equals(tempData.get("clks"))) ? 0 : - // Integer.parseInt(tempData.get("clks").toString())) + data.getClks()); - // tempData.put("cost", ((null == tempData.get("cost") || - // "".equals(tempData.get("cost"))) ? BigDecimal.ZERO : new - // BigDecimal(tempData.get("cost").toString())).add(data.getCost())); - // }else{ - // resultMap.put(time, tData); - // } - // } - // - // List dd = new ArrayList<>(); - // for (String key : resultMap.keySet()) { - // dd.add(resultMap.get(key)); - // } - // System.out.println(dd); - - Map resultMap = new HashMap<>(); - for (Object object : dataArr) { - try { - if (object == null) { - continue; - } - JSONObject data = JSONObject.fromObject(object); - String time = data.optString("time"); - if (resultMap.containsKey(time)) { - JSONObject tempData = resultMap.get(time); - tempData.put("imprs", tempData.optInt("imprs") + data.optInt("imprs")); - tempData.put("clks", tempData.optInt("clks") + data.optInt("clks")); - tempData.put("cost", tempData.optInt("cost") + data.optInt("cost")); - } else { - data.put("time", sdf.format(sdf1.parse(time))); - resultMap.put(time, data); - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - } - - List dd = new ArrayList<>(); - for (String key : resultMap.keySet()) { - dd.add(resultMap.get(key)); - } - System.out.println(dd); - - } - - public static String dateToStrLong(java.util.Date dateDate) { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String dateString = formatter.format(dateDate); - return dateString; - } -} diff --git a/src/main/java/io/github/ehlxr/test/TestThread.java b/src/main/java/io/github/ehlxr/test/TestThread.java deleted file mode 100644 index 7aae2d7..0000000 --- a/src/main/java/io/github/ehlxr/test/TestThread.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import io.github.ehlxr.utils.HttpClientUtil; - -import java.util.HashMap; -import java.util.Map; - -public class TestThread implements Runnable { - - @Override - public void run() { - // HessianProxyFactory factory = new HessianProxyFactory(); - // IChargeCounter readLogs; - // for(int i=0;i<5;i++){ - // try { - // readLogs = (IChargeCounter) factory.create(IChargeCounter.class, "http://localhost:8080/dsp-counter/remote/chargeCounter"); - // readLogs.counterControlForThisSumResult("100003", 1, "m"); - // //System.out.println(JedisUtil.getStr("dsp_counter_100003")); - // break; - // } catch (Exception e) { - // try { - // Thread.sleep(1000); - // } catch (InterruptedException e1) { - // e1.printStackTrace(); - // } - // } - // } - - - Map postParam = new HashMap(); - postParam.put("groupid", "100003"); - postParam.put("count", "1"); - postParam.put("type", "m"); - for (int i = 0; i < 5; i++) { - try { - HttpClientUtil.sendPostParam("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", postParam); - // HttpClientUtil.sendPost("http://192.168.1.135:8080/dsp-counter/remote/chargeCounter/counterControlForThisSumResult", "groupid=100003&count=1&type=m"); - break; - } catch (Exception e) { - System.out.println(e.getMessage()); - try { - Thread.sleep(1000); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - } - } - } -} diff --git a/src/main/java/io/github/ehlxr/test/ThreadPoolExecutorTest.java b/src/main/java/io/github/ehlxr/test/ThreadPoolExecutorTest.java deleted file mode 100644 index dff9573..0000000 --- a/src/main/java/io/github/ehlxr/test/ThreadPoolExecutorTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * @author ehlxr - * @date 2016/12/22 - */ -//@SuppressWarnings({"AlibabaRemoveCommentedCode", "Convert2Lambda", "UnnecessaryLocalVariable"}) -public class ThreadPoolExecutorTest { - public static void main(String[] args) { - ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); - for (int i = 0; i < 10; i++) { - final int index = i; - //try { - // Thread.sleep(index * 1000); - //} catch (InterruptedException e) { - // e.printStackTrace(); - //} - cachedThreadPool.execute(new Runnable() { - @Override - public void run() { - //System.out.println(index); - System.out.println("Thread: " + Thread.currentThread().getName()); - } - }); - } - } -} diff --git a/src/main/java/io/github/ehlxr/test/VarArgsTest.java b/src/main/java/io/github/ehlxr/test/VarArgsTest.java deleted file mode 100644 index 0054e00..0000000 --- a/src/main/java/io/github/ehlxr/test/VarArgsTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.test; - -/** - * Created by ehlxr on 2018/1/16. - * 可变参数 - */ -public class VarArgsTest { - private static void m1(String s, String... ss) { - for (String s1 : ss) { - System.out.println(s1); - } - } - - public static void main(String[] args) { - m1(""); - m1("aaa"); - m1("aaa", "bbb"); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/thread/Main.java b/src/main/java/io/github/ehlxr/thread/Main.java deleted file mode 100644 index b282096..0000000 --- a/src/main/java/io/github/ehlxr/thread/Main.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.thread; - -/** - * @author ehlxr - * @since 2021-02-13 17:29. - */ -public class Main { - private static volatile boolean flag = false; - - /** - * 1、子线程阻塞主线程将会结束 - * 2、JVM 会等待待所有子线程结束 - *

- * When a Java Virtual Machine starts up, there is usually a single - * non-daemon thread (which typically calls the method named main of some - * designated class). The Java Virtual Machine continues to execute - * threads until either of the following occurs: - *

- * The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. - * All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception - * that propagates beyond the run method. - */ - @SuppressWarnings("AlibabaAvoidManuallyCreateThread") - public static void main(String[] args) throws InterruptedException { - new Thread(() -> { - System.out.println("wating data...." + Thread.currentThread().getName()); - while (!flag) { - } - - System.out.println("complete!" + Thread.currentThread().getName()); - - }).start(); - - Thread.sleep(2000); - - new Thread(() -> { - System.out.println("prepare data..." + Thread.currentThread().getName()); - flag = true; - - System.out.println("prepare data end..." + Thread.currentThread().getName()); - }).start(); - } -} diff --git a/src/main/java/io/github/ehlxr/token/Base62.java b/src/main/java/io/github/ehlxr/token/Base62.java deleted file mode 100644 index 44db990..0000000 --- a/src/main/java/io/github/ehlxr/token/Base62.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.token; - - -import java.io.ByteArrayOutputStream; - -/** - * BASE62编码类 - */ -public class Base62 { - - private static final char[] encodes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" - .toCharArray(); - private static final byte[] decodes = new byte[256]; - - static { - for (int i = 0; i < encodes.length; i++) { - decodes[encodes[i]] = (byte) i; - } - } - - public static StringBuffer encodeBase62(byte[] data) { - StringBuffer sb = new StringBuffer(data.length * 2); - int pos = 0, val = 0; - for (int i = 0; i < data.length; i++) { - val = (val << 8) | (data[i] & 0xFF); - pos += 8; - while (pos > 5) { - char c = encodes[val >> (pos -= 6)]; - sb.append( - /**/c == 'i' ? "ia" : - /**/c == '+' ? "ib" : - /**/c == '/' ? "ic" : String.valueOf(c)); - val &= ((1 << pos) - 1); - } - } - if (pos > 0) { - char c = encodes[val << (6 - pos)]; - sb.append( - /**/c == 'i' ? "ia" : - /**/c == '+' ? "ib" : - /**/c == '/' ? "ic" : String.valueOf(c)); - } - return sb; - } - - public static byte[] decodeBase62(char[] data) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length); - int pos = 0, val = 0; - for (int i = 0; i < data.length; i++) { - char c = data[i]; - if (c == 'i') { - c = data[++i]; - c = - /**/c == 'a' ? 'i' : - /**/c == 'b' ? '+' : - /**/c == 'c' ? '/' : data[--i]; - } - val = (val << 6) | decodes[c]; - pos += 6; - while (pos > 7) { - baos.write(val >> (pos -= 8)); - val &= ((1 << pos) - 1); - } - } - return baos.toByteArray(); - } - - -} diff --git a/src/main/java/io/github/ehlxr/token/TokenCommonUtil.java b/src/main/java/io/github/ehlxr/token/TokenCommonUtil.java deleted file mode 100644 index 626cfa3..0000000 --- a/src/main/java/io/github/ehlxr/token/TokenCommonUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.token; - -import java.security.MessageDigest; -import java.util.Date; - -public class TokenCommonUtil { - - //使用ThreadLocal变量,防止线程冲突 - private static final ThreadLocal mdThreadLocal = new ThreadLocal(); - - - /** - * 计算MD5 - * - * @param bytes - * @return - */ - public static byte[] calculateMD5(byte[] bytes) { - byte[] b; - MessageDigest md = getMD(); - md.reset(); - md.update(bytes); - return md.digest(); - } - - private static MessageDigest getMD() { - MessageDigest md = mdThreadLocal.get(); - if (md == null) { - try { - md = MessageDigest.getInstance("MD5"); - mdThreadLocal.set(md); - } catch (Exception e) { - e.printStackTrace(); - } - } - return md; - } - - /** - * 将两个byte数组结合为一个bytes数组 - * - * @param byte_1 - * @param byte_2 - * @return - */ - public static byte[] byteMerger(byte[] byte_1, byte[] byte_2) { - byte[] byte_3 = new byte[byte_1.length + byte_2.length]; - System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length); - System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length); - return byte_3; - } - - /** - * 将int转为bytes - * - * @param byteNum - * @return - */ - public static int bytes2Int(byte[] byteNum) { - int num = 0; - for (int ix = 0; ix < 4; ++ix) { - num <<= 8; - num |= (byteNum[ix] & 0xff); - } - return num; - } - - /** - * 将bytes转为int - * - * @param num - * @return - */ - public static byte[] int2Bytes(int num) { - byte[] byteNum = new byte[4]; - for (int ix = 0; ix < 4; ++ix) { - int offset = 32 - (ix + 1) * 8; - byteNum[ix] = (byte) ((num >> offset) & 0xff); - } - return byteNum; - } - - /** - * 使用32位来表示时间,可以精确到秒 - * - * @return - */ - public static int getSecondTime() { - long timeLong = System.currentTimeMillis(); - Long timeInt = timeLong / 1000; - return timeInt.intValue(); - } - - /** - * 时间转化为日期 - * - * @param time - * @return - */ - public static Date secondTimeToDate(int time) { - long timeStamp = time * 1000l; - Date date = new Date(); - date.setTime(timeStamp); - return date; - } - - public static byte[] long2Bytes(long value) { - int binaryLength = getBytesLength(value); - long temp = value; - byte[] b = new byte[binaryLength]; - for (int i = binaryLength - 1; i > -1; i--) { - b[i] = new Long(temp & 0xff).byteValue(); - temp = temp >> 8; - } - return b; - } - - private static int getBytesLength(Long value) { - return Long.toBinaryString(value).length() % 8 == 0 ? Long.toBinaryString(value).length() / 8 : Long.toBinaryString(value).length() / 8 + 1; - } - - public static long bytes2long(byte[] b, int length) { - int num = 0; - for (int ix = 0; ix < length; ++ix) { - num <<= 8; - num |= (b[ix] & 0xff); - } - return num; - } - - -} diff --git a/src/main/java/io/github/ehlxr/token/TokenServerUtil.java b/src/main/java/io/github/ehlxr/token/TokenServerUtil.java deleted file mode 100644 index e657d5d..0000000 --- a/src/main/java/io/github/ehlxr/token/TokenServerUtil.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.token; - - -import java.io.IOException; - -/** - * Created by ehlxr on 2018/2/2. - */ -public class TokenServerUtil { - - - public static void main(String[] args) throws Exception { - Long uid = 178934567l; - // System.out.println(Long.toBinaryString(uid)); - // System.out.println(Long.toBinaryString(uid).length() % 8 == 0 ? Long.toBinaryString(uid).length() / 8 : Long.toBinaryString(uid).length() / 8 + 1); - //// long ct1 = System.currentTimeMillis() / 1000;//用秒来表示 - //// System.out.println("当前系统时间戳为:" + ct1); - String token1 = generatorToken(uid, TokenVersionEnum.VERSION_2.getValue()); - System.out.println("生成的token1为:" + token1 + "\n长度1为:" + token1.length()); - // - //// long ct2 = System.currentTimeMillis() / 1000;//用秒来表示 - //// System.out.println("当前系统时间戳为:" + ct2); - // String token2 = generatorToken(uid, TokenVersionEnum.VERSION_2.getValue()); - // System.out.println("生成的token2为:" + token2 + "\n长度2为:" + token2.length()); - // String wrongToken = "AVok"; - // String rightToken = "AVRibaN9MFUo9rOc9ocjXqqw"; - // byte[] rBytes = TokenCommonUtil.calculateMD5(rightToken.getBytes()); - // byte[] wBytes = TokenCommonUtil.calculateMD5(wrongToken.getBytes()); - // byte[] a = Base62.decodeBase62(rightToken.toCharArray()); - // byte[] b = Base62.decodeBase62(wrongToken.toCharArray()); - // System.out.println("rightToken MD5:" + rBytes); - // System.out.println("wrongToken MD5:" + wBytes); - // boolean isTrue1 = checkToken(wrongToken); - // System.out.println("对比结果为:" + isTrue1); - // boolean isTrue2 = checkToken(rightToken); - // System.out.println("对比结果为:" + isTrue2); - // TokenInfo tokenInfo = checkToken(token1); - // if (tokenInfo != null) { - // boolean isOK = tokenInfo.isOK(); - // System.out.println("version 1:"); - // System.out.println(isOK); - // } - // TokenInfo tokenInfo1 = checkToken("AVU4uP10CD1XYIlrJgLubtM"); - // if (tokenInfo1 != null) { - // boolean isOK = tokenInfo1.isOK(); - // Long uidR = tokenInfo1.getUid(); - // System.out.println("version 2:"); - // System.out.println(isOK); - // System.out.println(uidR); - // } - } - - - /** - * 计算token - * token规则为: - * {8位版本}{32位时间戳}{64位随机字符串}{32位校验} - * {1字节版本}{4字节时间戳}{8字节随机字符串}{4字节校验} - * - * @param uid 用户的唯一标识 - * @param version token的版本号 - * @return - */ - public static String generatorToken(Long uid, int version) - throws IOException { - - //获取当前系统时间,以秒为单位 - int time = TokenCommonUtil.getSecondTime(); - - return generatorToken(uid, version, time); - - - } - - /** - * 计算token - * token规则为: - * {8位版本}{32位时间戳}{64位随机字符串}{32位校验} - * {1字节版本}{4字节时间戳}{8字节随机字符串}{4字节校验} - * - * @param uid 用户的唯一标识 - * @param version token的版本号 - * @return - */ - public static String generatorToken(Long uid, int version, int time) - throws IOException { - - //读取配置文件,通过版本号取得对应的token的加密解密的密钥,及自校验位的生成方式 - TokenVersionConfig tokenVersionConfig = TokenVersionFactory.getTokenConfig(version); - //生成token时用的密钥 - String create_token_key = tokenVersionConfig.getCreate_token_key(); - //生成自校验位时的密钥 - String check_token_key = tokenVersionConfig.getCheck_token_key(); - //分别取MD5加密后串的哪四个字节做为自校验位 - String check = tokenVersionConfig.getCheck(); - String[] checkArray = check.split(","); - int i1 = Integer.valueOf(checkArray[0]); - int i2 = Integer.valueOf(checkArray[1]); - int i3 = Integer.valueOf(checkArray[2]); - int i4 = Integer.valueOf(checkArray[3]); - // - // //获取当前系统时间,以秒为单位 - // int time = TokenCommonUtil.getSecondTime(); - - //计算{136位随机字符串,共17字节} - byte[] timeBytes = TokenCommonUtil.int2Bytes(time); - - byte[] udidHalfBytes = generate8MD5ByVersion(version, uid, create_token_key); - - //添加{1字节版本}{4字节时间戳} - byte vByte = (byte) version; - byte[] sidBytes = TokenCommonUtil.byteMerger(new byte[]{vByte}, timeBytes); - - //添加{1字节版本}{4字节时间戳}{中间8字节根据不同版本生成方法有变} - sidBytes = TokenCommonUtil.byteMerger(sidBytes, udidHalfBytes); - - //计算校验位 - byte[] sidMd5Bytes = TokenCommonUtil.byteMerger(sidBytes, check_token_key.getBytes()); - sidMd5Bytes = TokenCommonUtil.calculateMD5(sidMd5Bytes); - //根据配置文件中取相应版本对应的元素组成校验位 - byte[] sidCheckBytes = new byte[]{sidMd5Bytes[i1], sidMd5Bytes[i2], sidMd5Bytes[i3], sidMd5Bytes[i4]}; - - //添加校验位{1字节版本}{4字节时间戳}{中间8字节根据不同版本生成方法有变}{4字节校验} - sidBytes = TokenCommonUtil.byteMerger(sidBytes, sidCheckBytes); - //Base62编码 - String token = Base62.encodeBase62(sidBytes).toString(); - - return token; - } - - - /** - * 中间8字节根据不同版本号生成方式不同 - * - * @param version 当前生成token的版本号 - * @param uid 用户唯一标识 - * @param create_token_key token生成的密钥 - * @return 中间8字节 - */ - private static byte[] generate8MD5ByVersion(int version, Long uid, String create_token_key) { - if (version == TokenVersionEnum.VERSION_1.getValue()) { - String udidBuilder = uid + create_token_key + System.currentTimeMillis(); - byte[] udidBytes = TokenCommonUtil.calculateMD5(udidBuilder.getBytes()); - byte[] udidHalfBytes = new byte[8]; - System.arraycopy(udidBytes, 0, udidHalfBytes, 0, udidHalfBytes.length); - return udidHalfBytes; - } else if (version == TokenVersionEnum.VERSION_2.getValue()) { - //{1字节的uid字节长度} - int binaryLength = getBytesLength(uid); - byte lengthBinary = (byte) binaryLength; - //{1字节的uid字节长度}{binaryLength字节的uid串} - byte[] uByte = TokenCommonUtil.long2Bytes(uid); - byte[] sidBytes = TokenCommonUtil.byteMerger(new byte[]{lengthBinary}, uByte); - //{7 - binaryLength字节MD5的串} - String udidBuilder = create_token_key + System.currentTimeMillis(); - byte[] udidBytes = TokenCommonUtil.calculateMD5(udidBuilder.getBytes()); - - byte[] udidHalfBytes = new byte[7 - binaryLength]; - System.arraycopy(udidBytes, 0, udidHalfBytes, 0, udidHalfBytes.length); - //{1字节的uid字节长度}{binaryLength字节的uid串}{7 - binaryLength字节MD5的串} - sidBytes = TokenCommonUtil.byteMerger(sidBytes, udidHalfBytes); - return sidBytes; - } - return null; - } - - private static int getBytesLength(Long uid) { - return Long.toBinaryString(uid).length() % 8 == 0 ? Long.toBinaryString(uid).length() / 8 : Long.toBinaryString(uid).length() / 8 + 1; - } - -} diff --git a/src/main/java/io/github/ehlxr/token/TokenVersionConfig.java b/src/main/java/io/github/ehlxr/token/TokenVersionConfig.java deleted file mode 100644 index 6c70aaf..0000000 --- a/src/main/java/io/github/ehlxr/token/TokenVersionConfig.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.token; - -/** - * token版本相关的配置 - * User: erin - * Date: 14-10-30 - * Time: 下午5:34 - */ -public class TokenVersionConfig { - - private int version;//token的版本号 - private String create_token_key;//生成token的key - private String check_token_key;//自校验token的key - private String check;//获取自校验位时,取哪些元素 - - public int getVersion() { - return version; - } - - public void setVersion(int version) { - this.version = version; - } - - public String getCreate_token_key() { - return create_token_key; - } - - public void setCreate_token_key(String create_token_key) { - this.create_token_key = create_token_key; - } - - public String getCheck_token_key() { - return check_token_key; - } - - public void setCheck_token_key(String check_token_key) { - this.check_token_key = check_token_key; - } - - public String getCheck() { - return check; - } - - public void setCheck(String check) { - this.check = check; - } -} diff --git a/src/main/java/io/github/ehlxr/token/TokenVersionEnum.java b/src/main/java/io/github/ehlxr/token/TokenVersionEnum.java deleted file mode 100644 index 2a51911..0000000 --- a/src/main/java/io/github/ehlxr/token/TokenVersionEnum.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.token; - -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; - -public enum TokenVersionEnum { - - VERSION_1(1), - VERSION_2(2); - - // provider数字与字符串映射字典表 - private static final BiMap VERSION_MAPPING_DICT = HashBiMap.create(); - - static { - VERSION_MAPPING_DICT.put("1", VERSION_1.getValue()); - VERSION_MAPPING_DICT.put("2", VERSION_2.getValue()); - } - - private final int value; - - TokenVersionEnum(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - - public static String getStringVersion(int version) { - return VERSION_MAPPING_DICT.inverse().get(version); - } - - public static boolean checkKeyIsExist(String version) { - return VERSION_MAPPING_DICT.containsKey(version); - } - -} diff --git a/src/main/java/io/github/ehlxr/token/TokenVersionFactory.java b/src/main/java/io/github/ehlxr/token/TokenVersionFactory.java deleted file mode 100644 index 2b21645..0000000 --- a/src/main/java/io/github/ehlxr/token/TokenVersionFactory.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.token; - - -import com.google.common.base.Strings; -import com.google.common.collect.Maps; -import jodd.props.Props; - -import java.io.IOException; -import java.io.InputStream; -import java.util.concurrent.ConcurrentMap; - -/** - * token版本控制工厂类 - * User: erin - * Date: 14-10-30 - * Time: 下午5:34 - */ -public class TokenVersionFactory { - - private static final String TOKEN_VERSION = "tokenVersion"; - private static final String RESOURCE_NAME = "token_version.properties"; - - private static Props properties = null; - - protected static ConcurrentMap versionMap = Maps.newConcurrentMap(); - - public static TokenVersionConfig getTokenConfig(int version) throws IOException { - - String versionString = TokenVersionEnum.getStringVersion(version); - TokenVersionConfig oAuthConsumer = versionMap.get(buildVersionKey(versionString)); - if (oAuthConsumer == null) { - oAuthConsumer = newResource(RESOURCE_NAME, versionString); - versionMap.putIfAbsent(buildVersionKey(versionString), oAuthConsumer); - } - return oAuthConsumer; - } - - private static synchronized TokenVersionConfig newResource(String resourceName, String versionStr) throws IOException { - properties = new Props(); - InputStream input = TokenVersionConfig.class.getClassLoader().getResourceAsStream(resourceName); - properties.load(input); - TokenVersionConfig tokenVersionConfig = new TokenVersionConfig(); - tokenVersionConfig.setVersion(Integer.valueOf(versionStr)); - tokenVersionConfig.setCheck_token_key(getValue("check_token_key", versionStr)); - tokenVersionConfig.setCreate_token_key(getValue("create_token_key", versionStr)); - tokenVersionConfig.setCheck(getValue("check", versionStr)); - return tokenVersionConfig; - } - - private static String getValue(String name, String provider) { - name = TOKEN_VERSION + "." + name; - String url = properties.getValue(name, provider); - if (Strings.isNullOrEmpty(url)) { - return null; - } - return url; - } - - private static String buildVersionKey(String versionStr) { - return versionStr + "_" + RESOURCE_NAME; - } - -} diff --git a/src/main/java/io/github/ehlxr/utils/AESTool.java b/src/main/java/io/github/ehlxr/utils/AESTool.java deleted file mode 100644 index 1da852f..0000000 --- a/src/main/java/io/github/ehlxr/utils/AESTool.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.engines.AESFastEngine; -import org.bouncycastle.crypto.modes.CBCBlockCipher; -import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; -import org.bouncycastle.crypto.params.KeyParameter; -import org.bouncycastle.crypto.params.ParametersWithIV; -import org.bouncycastle.util.encoders.Hex; -/** - * AES encryption and decryption tool. - */ -public class AESTool { - private static final byte[] initVector = {0x32, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, - 0x38, 0x27, 0x36, 0x35, 0x33, 0x23, 0x32, 0x31}; - - /** - * Encrypt the content with a given key using aes algorithm. - * - * @param content - * @param key must contain exactly 32 characters - * @return - * @throws Exception - */ - public static String encrypt(String content, String key) throws Exception { - if (key == null) { - throw new IllegalArgumentException("Key cannot be null!"); - } - String encrypted = null; - byte[] keyBytes = key.getBytes(); - if (keyBytes.length != 32 && keyBytes.length != 24 - && keyBytes.length != 16) { - throw new IllegalArgumentException( - "Key length must be 128/192/256 bits!"); - } - byte[] encryptedBytes = null; - encryptedBytes = encrypt(content.getBytes(), keyBytes, initVector); - encrypted = new String(Hex.encode(encryptedBytes)); - return encrypted; - } - - /** - * Decrypt the content with a given key using aes algorithm. - * - * @param content - * @param key - * must contain exactly 32 characters - * @return - * @throws Exception - */ - public static String decrypt(String content, String key) throws Exception { - if (key == null) { - throw new IllegalArgumentException("Key cannot be null!"); - } - String decrypted = null; - byte[] encryptedContent = Hex.decode(content); - byte[] keyBytes = key.getBytes(); - byte[] decryptedBytes = null; - if (keyBytes.length != 32 && keyBytes.length != 24 - && keyBytes.length != 16) { - throw new IllegalArgumentException( - "Key length must be 128/192/256 bits!"); - } - decryptedBytes = decrypt(encryptedContent, keyBytes, initVector); - decrypted = new String(decryptedBytes); - return decrypted; - } - - /** - * Encrypt data. - * - * @param plain - * @param key - * @param iv - * @return - * @throws Exception - */ - public static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception { - PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( - new CBCBlockCipher(new AESFastEngine())); - CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), - iv); - aes.init(true, ivAndKey); - return cipherData(aes, plain); - } - - /** - * Decrypt data. - * - * @param cipher - * @param key - * @param iv - * @return - * @throws Exception - */ - public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) - throws Exception { - PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( - new CBCBlockCipher(new AESFastEngine())); - CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), - iv); - aes.init(false, ivAndKey); - return cipherData(aes, cipher); - } - - /** - * Encrypt or decrypt data. - * - * @param cipher - * @param data - * @return - * @throws Exception - */ - private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) - throws Exception { - int minSize = cipher.getOutputSize(data.length); - byte[] outBuf = new byte[minSize]; - int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0); - int length2 = cipher.doFinal(outBuf, length1); - int actualLength = length1 + length2; - byte[] result = new byte[actualLength]; - System.arraycopy(outBuf, 0, result, 0, result.length); - return result; - } - - public static void main(String[] args) throws Exception { - String appid = "canairport001"; - String key = "1111111111111111"; - String xml = "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"; - String str ="fbac6c10aa8e0f946e02e0b57b35c7483b57b485c41147c31511ad1c212e3388ed223a2ddadd8d98c2306841b58927d8d8da4013d4057a20d00d87fb6c8ad3a66495638b6ddb42e405acdd4e28d0de2928f5f03b3b049070d4d1302f9cd9886c3b0052e1e61edb0f4de74c0f592a22d10bceb06944688c5a0521adb37b74648a2647357229058094deae4950053f6d67db76c4d013c024a1128b471f8d5a0f4765a447fd92eb6c84f5db6c5b2aa0721ce027d311cdb95e285f6e6f1deb6027e9a666ab5600fe3d094f7008a08b415c876d8fa48f5cd0e1b66e2a81fb8763c242620f4109607e17a9ef8e61fedf630f3900b34b39efd19674d1a9968b8ed5ecb7f344becbf2d9928ab6e52cca89dd261538335a3e14b11c216dff10ac1567d5a52a26c600265557d20b8bfff97007526371b381652dc12dd92034f8d62d4a760497dc3c7168d03932e33e455661157b36a13c6ac3cffb32a2a21816333e410dea8a147346de7a83b26d823056be8e9ec18406bb7e5e95f164e0e69c6ed398d3163133d6aa912d239897720db3392766ee5780da46b8ecb626aeb22ce4ab2cd1e397ca8f9063796301403d1b9a26cdaae1a90789d1d036c74da0566a4a9428dcb4af17d743cbda2de768d90001f485145254da6a60fb4ada8419ba906bd38c991649f8422d98fc9ec8d55503753e274e8a16ec9a6f06f04bd4ea99c9e4c9b5389bb077c8a63959fbc2574456e614bb3b64d4469c8d8d773fd774f366c4f50dbc5f985afc2511f74001dbb1947d88134faf58fb4f9cb43047e4aa5e821147d6aa1b868cc46fbae459e5a784269739b157ea59e3c7bff6b28b6f0f9895c1ddc23467d221a55ac9ca3cb6b773a94b7dcc86e73bf3e467609f4f700a5458e09aaa0502cbd60e48ec9b832274e262bb1112299ae455f00e7ee6fb1c80cdcc7dd6fe3b34648194d7fbea874d75c3ab27f9f7d086c45c57ae6dafc19164372f7a5d73bfdde04c8b99979be281618e12f5c272757c4029ace9f6404aa48653a12f95e42dcdcdca201c5efed5d428c4c366dea3af9eb095f81b6daa4521b2171585666342e9d64f6e80555da4bda8444969fc9fe02c0b7ec6aad78f0286dcb39f0b2c1a358993c7a9920213ec814496a8cd345a25ddbd41ca6e31fe9f6abca80caac322a613ad28004dfafad578c283b7ebf4066fc16f269e4a407087c1ba90a0d7c6ad53a9787b75b69eb87cd610b4cecfaa1da06194dd03503a4025a861e283fa72f70bbcc6eeb1c7018a13e4570c9e42cf6e844fbf1de486277440bf7bb2ebf956fa6f35507681645fd4bf0fbd055d7c2345b7eb495952948bd5ea12e965c190ef6dec77f838520ebe691d95f3d2ba2cc996b67e961423a3a8873ca617276090ef06152bab734986e74674a51d44deb8979cefc535f43c24482918463d8c5f64becb3f05ff01ee79664ef2569931ffb861205781ffd2ab558c3d40cfd7a93821b218ff92926f92ff1ab666d8464b97b76f724e399231cd50f95826d1c9c37ec6b919c5c994635d416979f89e263cac32253c2f823b435c5456fcae93be60e0ac11bff83613503a148c67f4faa4d69a541e907979b15b2b3286180e125299f593a7e25ef3f41d9b0abf0f36e576ea2ca352dcbf911b423686da8ffc8c7c19e9fc68eba8740a3278907bad0e8abf3b853f849bd6bc94b88ddef0f773ee7af3d057d4991a1e947ccd3cb1376e69479177ee66be454845375fc60fdd244f25797480b0fcec66ca98c98f0c6b8438d04a5488b371ea5e09b06b304a50019c7c937ccaae38530de324b765bd76a86837c6c0d69728e4c5c2b2aca45fa2046d8d93c676f37b02013c0b3adae166ce251d4588f8714af8568d9ab35d3bcde421e9477bea3eed0389332f8b45684af4ebbb441e8a672b06c78974748de20faa2ae4a18e80120c4d33a08dda7f7ed386a76152e67ed5846e089fad1e39d5050d58b8a2fe2b6a4b25a5d7fa4984916b1953292fc7c6afa6d1d5579e1c9f567d153f52abc4b9e33ed1c02c531c2b5895761a0f070988659e1eafe2103997955ef1780199f0862c503230be370aa49e45c81d70fa5eca0dcda5bf017878f6b95476f3512e3fb43b780659b977af63aff58a3378f510d63c17057709c20f5e0300679ab70fe224b2de34bda56f5c21d0d45a4460bd286440e17cec82796da2e0d8af245a35db1e29020bc7e9030891c7af357de4c32400244ba1c837a2a1a9780d8297b9705b0d64a4073b8998e0c60bce73327eb8f25534ad31ca0b2ad2fd3c650328db045fb0ec28e992935eab465391c4b9682e2ea49a152232c332a0134d7104d7b5a497a927de813fd7002596ce441f35038c4af03f5743de311f2e7737c318f964363270e28d308cf523eb26d27c593437b4442f4af2f4a59413459c01c723e7bb3e0ff6e99e2b49e961075a0424318bce841b3d734cbb01ff9a2c85465280ff5b1b9d1bb7621f32632c76ba5556b5e667111f58ef125ca0b526d483414b8621501d9122717d30d40d46bdf9a67458ad2c9d196904154302190a336d422a461594b1060dfd30810c79037741bea437e4b27eb2befb07922bfe2c6f714e75f4f7a0db9e59c3c94fe02fcc2b315d1f518621b1d2a2711b7141f720697468ed8bbb5f54552ef4d59c0421bc3b07f0a8daa2c8de0e8239a92bbdb6d6bac60a9da08ee3e495382af4bfe673f6a74ba25b86ef54b0205acbcd31d29cc5109b3a49e8648a0db21746b0479c3dc25b5765ee5ccfb3ad484bf1b21d9408410f4863f01704ae9caa83ba1a19743641c69fcb0bc8c7012202c0e86917b9758fbf1d2475da7b8c714dcc87362b1a6b0efc831af6abe6bc64ee5b908c90530c86295d548bc4e60d626ef706b3cb2fb996f14dbba2208befbd68ea9418eabbdc1d87f0dc463b48a5b2e0bcc11be8fe697321c74aef6c4afd662e16e861f9c6f5a90e5289e7af998cedbb73121ecbdf0ea3ef32ad45452481afeabb166aa0c064686450616441ea6c66f5a9cbd9ab18ebcebd219acfeecef9fd369b1742db9b0a2c9db6f2c55b59d650a387d4ec6e106d69915d733e7a32b7ca9d9850b44547af581630dfcf4711f78a967daf9b9ca22e8c4be5adbbb1da4cacab3061f928207e6de93f6a675c272163868101dd80c83cdec0d8166190ec08bf4c38c5c05eec84fc6c8abb02dd672aa901f87430a4b329f280f61b431cf4357c010b4ad3e308b36bb4dd92e8abd27eed8688ced05327ac42f27e6bd448645b0ad5a9d0afe597e87504fe78648df10671d89617b422bc5492faa73876c4e8a8861c3d4e69a13de32a214c1a89fecae026225e62004ae3dd937e27fd557ce68a84c1575b0910cddf28a92932414cd9fb1dd29ea2bce3444a6d0a98152b1991f028236784c5bc937ebafd7decda605c4e372933ab6975a0db312d791f231fb6aba5564468933e16cfcab5433fdb4a9baa2e0805be97ce09b452b29f7d1aa03c2c79a8dd8796e356b18c598cbb0f943c62ebb9c39ecf9f99c013301621d55079f7a6cabd8bb2937c535d6aa802a16d6451ce1aed115550781ebaff01738800739c2877e63e8c499128d8e15d5b4b3291f48e8507cfcdc7ec76e095be149f27fb1dacaaa2ca09b4161bdd1217cba428884b885356befdd8371ca9df05eb394b2be93f24135b23603f42106865202175e34bdade14c14725426189eee00bc3f070ced7b07bca5c263f4f3c1ba69cf45092c236afe9bab54e2b09d9dcde437233665ff4af14b871c0ead96d34a315832f4d3d1decc48e89d47168c86d68565645cad3b3ed6ca4a95b19d1acb678ed2ea8cdda36100dd6e57a76ee53bdc65bde1fca8a0b21ef66d0f36f0a4dc3b9c9350178fc8614442cc63aee58f5fe23c83fdbf4393f65a34494439577034d5eee6b76d2ebabcd0d4a846cb9a6c884d7789872a1c653edb82fa814f6fdf7436ad835d04771f579f6261bfff6f3ff23e3054f63f54582c43f49be2142b6aa99962f87b342d4c771874e924b92c175167016de0a67d3807ec298b44e9c9fff071b0fefc1fd449b38b999e1b711c6dc8a1a85eba594b03550ce89db6d2918ae2fa5e5ef87bb2432201aac1b2548b8556cfec7061d7f37b38ceecbc87dfbd819a725c7908f89b5b1dabdc65a460d418d0eb7895c99994d71c85c41ea9db57088586093501a41baa9fd40df3278c2df3f1c1f788e5a821054cc577df114777934c5fccc18b5d9299e32596478e1f8b5742fcab870ace51cf3601767388fc998a45d0006f9c010e1ffbb1bbf192866fe6da787d9de9e16b202835ee3067b8a5710a6f9f1e5e374924697189eede8f05d5a41d526473d084bdb0a13d012ab5fe258f1d2eef68a51fd813588c8fd5b6608c6c541077e6ad137c6c1eaa93c93d3b326a44f4995f4e1cad48a8d386369ee16f3ad7c1d49609a504fb2ba49efca355cc8c53a0a448972c6419c1d696fdaf237264bd06069c2f613e45f867af01ad781adde5ca2d566019f08fd2fe9ada26c35f3095c1384709062e240bafd9d5711a2478bbb39af17366d5082dd300b92ac6581820e0cb183d2b4eaca538831ea3778681b519ec4ec96c1f20d34eff13ecb71d8a1a7184904f866bb2dc814c80c455de5f2e5017b1e38b28c9d26f49f175e158a7de318561e5fa97f6ba9eb29ffc521b94466ab4b4c00b6275b19965974867f1380787b345f23652a2a06b1cb0c4b36547d60700d915cdaff7a5dae4ccc5902c8dce37d9be2e8eed228d5bd64212a516bb35c39e9f69e52e22f2b9e6913c53d35f11eca8b84557539e631154b6a71ec4eab16babc158af1caaa742523754884ef69c62a3e53a3db0f551d4767db571fe0a8ad6ede1ae3396b40cdc19ab01117d44ef5da09963183db0151024e235aa97f644b99435b61f7c60d4c50d4f9fc48e3bac8bd57028744e377b829c44cf77451808589d3d6b19a09511d1bceee9d0cd094d2bb181b5148b23c456dde5e54e97daa5cdcd8c33973d51b7f2c08a5a6f26b58cc7bdc21108059f04497149a28cca5740e3eeb72306ce4344c86e2fc50843655972ce54a3c6a2c1fed2ac23d36666e9a8369b51d206636615c6a539cae30e7d0fcbf6275bbdfd9d509bb7914f2728a8c0ce039161b08bd7010a539cbafad0a97d0847e24a3e05cc2daf50c0acf4409376859bc201b9397a7d5ed07f4059dd1607a564bc0ec54ece5b5c1680a846616e0c058b192cd8780092107df2d47b84c161b79845d1bc6ca1043ad6977a1dca3264a54b8e4db17047de9bfa2cf77717ffe1549230c2afa1684dc2a3bc7590b098e7a896c57e0caa172cb1174e51bc8d77d831051fdfc01a7026d8904599fe87659c6781ca120e011bebd6e111bacb09743c37c0bb20545df91c6ca2ecee2112a4eae506a35754f7d0d302222c2a70c665f3ec001aab8c375cbc11f0b5f095e75e3ad5d2d18eb3827a44de165e92ff980cc2a1043b1049cffd185a49131b7d6e58c90eed17b4a4a82000e7bb5d79269fa6097b37a854d9a097f2e3c83238ff4efd0e46d46accf0ade825b8b60702a068f1302e6e4115abf25254998830cffd6a6119412dce6c6f7c6f9f28a01999c4afbe2cd4fda127cd883303ad954af1275de70fa7beacebcbb4b2c6fb98db13996ce62f1c391d222241555ab9856d2bc8cd5813b7ff8da47a4bfa4d935d22399713fa76cd827f0844a8912a230146236ca61578b692f11c5def686fd96364f8a69a98d8116a92303a961a1e025a7e39a7d2a210168359c751771333b3a539a24c45724a33f64460dd32503de82e709aec0b9d98d5e730e1126179349f9820e09cbac110a9864678311c7a5f043e1f54bb2202d59b6cdb7f9622d9bd9b5778a48b3f1d42207e762d2afdd107a20ba985d6fd6f9955bfb9df3884c1c305d4ee2fa9fa90aab2c23019b631350561456ef70659af1ca1853f91619993f8a00429485bb7ce0a77c816a6e770ea07aeccecf5a8785020311749212cd00223b62512280205294429276cc70926a8564b09fc962fbaf993aeafc61d386b0693041088f2ada92940e4f8e51794875859ef60007d700ecbe9008b39ccf670a563c844d88d1468b9ce1258a76d4ba80ae2ba12dc2bddee2c0bce309f025d7735230da73769837ab031cd6949ff5396a59fd9d76c5afdb708d31d4c29a19c4111f963502d8b1db0db6debe8bb635cd924c1e2c269398f110d77a5bcabdfac88873a1c33cd1747429c3798bfd1548d2e38bd189a9d33e4b65280733e011d9437ea28953379c7433d8d383412cfcfbe838b8d10ef2697c84c6695dfba005b0b4d36f8a3f627566551b02c27e2549c253110ff7cdfcd643e2379f61073e75b1d948e8ccb831014f5c525af48ad6643b25640497efe02fafc996a5db4d02ea8cc1baf565c976f049f77f88fad8864b196792fe58174eab7ece45f00a6e7ab13fe58b9f023a58623def2a24a5ccebd6f6205da136d53ae9263bfd558f64ff0f002c94f252a4bcab6bf514f5d87e63fe69aaa6609894d77a1b2dd6c8ba30fd360f0fbb6fdc8d86ad91582b726675d92ba54d5fc422d3f4cd85a53bf78ca9d8790d2fd0f1e9bfabbd9bb8a6e484564344d3d4f49caa2b69cd3593f2465cbd475a16c8d37a3066fad9453af1687e0090457eae90b3ece7faadb8b9b681ec5b65587532f2164b1b5befc5b46224f1a670c6f7f2d2e2bdba6141305bb2b7a607f9d8f2ef72d622cc766c093560e51e87cdb7a937c8904e1ae093e7fda741038d0537386ae8426bf16045a38f1e2eb905b05f3adad3fc82bf54839bd7b9630179582c4c51d2a8fa58191a6755844588a5d004d1c1b6255a8b91f7a03c3d528b621f67b332486cb2b89f09dababff6dbc7eaf079058cb7fd507bd49b76fc77ab3372d7589e3eb25f4730ae52428c0d9c12ac399e2836d59c84b757df3aafb1f50e4021120bf64c13eb304e89a9eef31665faefc6ae952c5b808465cb5847b9731c4cd789a86bddcdca5d6120013a335ee57a8c848a8b94d6520f35a61a211ce37f26d954ab6a90f5ce78e1f9fc59f059d5494140b03159ab1d213bc6a7d6df9326e38ac9ed6481afafb49a8e77be93cdf1944b8a6e27d9a094a5bea3227284dcb82758db0b7be7cff7a1e609f9d2d7e99920c855593ce73b05c9a1753793699c351f01c5d502c19d0287546c774736950922280986844a8c9c7b80a1e34093ce16da0c87667c1384a622063f3804e09c62f18cbc9487e0963dfd856fbd30097bfb695db1ad04f53ee765869c7925adb42a8066940e0f1bd0dc70e09f5539eb3a9aa885f8e73dd505a8ec1599f66025bc1cbf8359d16d96595bdf93b003da12faa6d0bad0ed0e4e86e2168cd212357348ede4e29e7be72d4b9c05d789f17b4ff383cb68671da6c323603ccf16b7b68c22aa9ac49c60f7062e40a81ce12e92a1b805bcbb225a99654ee54308e3c7de3f95a0f583ddc6772f20258d56e0631371be878e0f7895f677d1b730581aaadedd71658ecac4648932a8098c5093c84adf28a25db83255350ca821e5f52d083abbf9c2badc3aa80c6498a6c1a1083fc788cccf123f802e08ad87d4eb9bcceb4006c093823e87d950734af8b96fbf62045a6c557844e8cc48a31b7a27f1a87982538ddd5499d002e35e2c8298957c588d757ab5a9228726e7ded98466d439a55b6e51c614eefc16878c19c9d3b6c6b8069c19ad7c1798118cc49f33c2e20986f57e5dfe626ba08f8c2692bc3a6f745d3306804120c7f2c31a5970d9242f2ef0df07b97df3fd21188140909aafc6abe8eaaaa20fb85ebf60a12e4b97d77723fc756c94601e47c0594e866bb89c766caf2d26fdc0e4bd583040ea64f76025929aab4e6e6fc52c8aea37d29d88babbed8874a1f77f8fa4b80f67bc9bc8117f06e7c4a9415039d40f97eb4a1aaa4660fde0fe898b15f5488eba4f703484f2853f91ba314170b3ef4eb609dcbd7706be4d69a23b44a9fcc66155388f9ad463401a6984d337e7cd3a3ce1dd67ab91b205630c07b2c8967e291ec07b3137d1ca493daeec28de3a188e930c645eb22bcb91a2bb6ef6546ba257b88e92cd7d507acce6fcc2e5eb42755a3edb930c26271e4416e17a619be680863700860c8e93f47c035a90ac134b645744df0e04f8724876822979568109e6ff2692d56cfff74cbf7ba43296196b4cae1f2ce3652cf6d86e9e2c29266d0b1d2241eff62d4b5eb684c521bc5a81bc5869764958d3c17e7b36d73dc610d190d12835baff8b1774550c7660f153701ad7ac39140ca923cbb33aaac15d4c56699c7fcbfff96a01f2c1951857d0245c2d202c758d29e7452fdbf0f4ce29ba1610b94f6fc781b66d13bdaa08dda551a07972e84fe64296a069887ad13315900bc034b1c3d2748ac8166bc87b421a22eb2b213ae05e8f4449fab2699a149d64b7e88c5123615baf6f5479a700e4ec9e7f0605ef2927b252f13a5872082c09ef3534f7faed1f05910f60ffb23b4aafab763557680279dbbdb39da01952e766daca892fe6134b78aaa2b85ad50b3a6b26323a696f88ec478545e68b01886cf7a5fdd6254bd78c579d421c73274da92626e0cbcf857cf5d8f2bbd171b7ec000efa955f02821f6d6d9a32c4750472038a377051782abeabb84bf680a2d3b53fc0e356640a0735a25cb1894350fe7e9b6b399f2dbf352a1c51dd45e4f85053f5b534973262829e9f324082693c960ab0f9d73ff23db68efb09396e8cac04fa90e0e3d1591f9233c882922bafa0e310f2cf717b33b9d954d9fa972a06b9c04cf5515faed843066cbb3316f725cce7468c9d475a2cccb26eb6867787817fefd878c3710e5e65211168f69f2a293fdbb72d59b33fdebc4fe2130073cbb1505eba12a52e466414ab6dfc886fb7eb3fd70603f077a9cc2e1b7ace14eadf011e6373d22eb2748f71f1f7aa83935c4c82fcb85b317d077d251a9c1eec08837109417c9e6609f5fe80b752e8adba3635e4a5b2fdebd8dac1c07d081c0b73c98397f3f961af4968d0702dc7aba230f2da6863fa4e662e5cedc8148a9d69e7ad07da558d6ee905356219a9367fb970596017329014653311b3dd08789736c4c8482ea3c783ba70b7b3aac3675b5ec70d61878073ebceb530b3f377431184dc79035e6c030ca86f8af1a754df4f8ce6f085ebcfabb035f1f78f3b917901c1a3148fa4c0160512994b29c06bdccd6322a22a45f7e5fe5a4d8f5c68de0fee7973194708b9dbc95bc5a4c826ecab8dcfd61ed391e6fae0348564fd6404b6e732834db2589ed9cb2cfbe3e97c2241e684e8051e998c3afe3a7e60a373c87dcc905f4bd1160a7266067aa058367643cc66dc37213d94c7efb264ab98aae9eee92efc4812261d4383481b293143bec7edf57f22ff7ab0b63975c27212eca0cc41babf8da97bfd78a83c2d2298a398a3742cfe85d3fbe225c2c24e34145d47c8488a6917de1385c8e2529a91b7d2b93b702dca61b946dca955fbd0fc2d05167e93f79e8e19134559881bdb8eff0f9570ef5232cef7bd20992d2038da12fb483f1d54912737e7d51b83da88bc2655a710aacd2cd78fa46e6c997b0b5984f103b72de334646ec751a011d7b264308028252f9dcf728cc3c06b9d9ca8e3bc1a1ff54a3064f1b344446c7575d1276a8bc9db9ffbca4a2ea8e5b1e61f67af346dce56c9b37ea706a6ff32a19b9b4067e5e655168b7a73976613630e877e5dc03d25e3be92ad1b0cd813c1df124d39641d0858eb99b6a756fd1f207ace0648433edc47261b5b222dbb218a13f1456e875888dd2b61284d3d5561ca36eb65c609f52e17b126f85986216962f1625829d18d94d389639e107e39aaba878f07400d73dc63177c4d9627dd26ddcc801161274ef21e965453d09207e700513e79ebae00c384ccc0ca81bbd78880d22f491f9d4dc1c0877145427fa1e04a7bdfa8402b9030837e8fd2666bffb99a205fb2e365a1d27cab81dc396b7b116f159e3ef7cf6cfe92f7b223c0c1217d867de5e9a34bbaf4b8c7d6b1dc737dc75276f83e608a18aac5088b9b2f437741f0d50629dd2120407d92d1f4d263c5454b152e8806c53875e956529c8d13a50eb99a16de7b2e80dbf2dbcdb065d42010354bf57f03d7df22ce95c279cac35e6ca7b18a8296a4841ba07b734ee8463d4e78e6acfd48457d24e1527f6105199cf1eac36454842315befa348d24966fb6b2942b9b6fa28e026c0d66cc806294429d3163b9ee26128f4c4e7e49e5b233114a7eb8e6c3a6d45d3780d9111e8ac0f30708036eae99e8fd69f915b4d9d48225fe4336080394c5f726dcf9f2eace37b55b5d43412e1826eb6e295ec8da5062199de904ecd2fdf8a4d15924b2160bfadc5b303722965691cf99d5cccbd8c29f010a9838a64c09d5bce90bc08f486812e638001223a448921a689afa6d81b7fbfdd922d3c285e9182abcfbe305c037e21102a8731aa05d8c1cd4db39155f5d1335d02b15422e0ef328776006129fc0483e79a310e3efb2500060a361e204033d48be6249b66739142a82e03ee06f5b16c829e647bc29bfc9b661225820d2cb849319b6d0448f7609ec723e611e8d1f03da1448538fa2ab9344992d4bca82ad71325d3575996f8fc7d91c191028fe1f6f246ad41b63abc65fa1e52d6417ee71c0e5da26ac61c82a57e7e4cc26fd3deb1491eaa248a49479977b353142c39ee018f1262137d37d1f38edfc9a2e635d5153699d976e5aa986db9a65204e5346482275ec21dfb482e836c6cfe8d494e64dd13561479c7ed46f27eae0d80366c836cc11f0cbf8f197db5bb07245263249ed530d4642d1e241f231b795ffbb7b18d28e4962f77163a10cbef7db92a19a0fa866e81ea53a3d36f21242d05c5f1c0bb4279d3521f902806665a04357990cf1d72460ae0ca2e273467ed5f8333717d321b3ddd92f0b2d31f5744b5d49810d8c4ba6c47a51d7d24e30e631b8e20002b040a1de5075023ae897daafb4285146f33688e4792a79fcb36824c1a98091c7692b1e023c548c40afd8d0586fed448f2e7da560c6902c85935c5449ed2e101610d34ffdc6076fc74f87ca3a76d1b667ec38c9cdb33c486f8579e4fb861f1d3bfdcd7c4ff114572a4f18fba187ed4b030a513f9ed252ba1b6a9d4bb1c5bd70e9e6dbdf516ccad5c69d4b9cc28b8059ffbe0ac48adf1340b4a414fb897f51a3d9c57299da011f6a57aa58995c6de5814c70e6caf7a3249bc1ac29b4b9ca99c6656fa35d7846a34ea40796f8c1f05c5d20f05d57e1deabeb5a84537694213b934476293fa694922f684f66617e9c97628fe9efc0c7295907744b67140fccc1690405fd3d6b185566652e1e18c685088cfa016cb194c2c86ec2e39d7825c977f68b46096c238734226e30fb014f774660c5f1c0116faccdd19aa4f3906d734450a5f31f0ae22ffe49534bd20a09eabacd7a49f0e738c333555dc0877cbb778b840a038d281a597bb6ff79d033843c0c8df0de3c0454862ee428303a80eab6571ab61a66a19bec2d8a8ff5d573f468ea26cacb3c96745c4678c795d742b98533bc61d8c930a100cb9a757d62c554f8fa7bde7d019fddab57bf2d6ac7cbbb5b85d5471e39314c3faa59e5df2400658394df152a8f779ebcd0dc489e5eb85fb4fb41806a4e40c14b226236f0e419880ccdf739b5fad7958c35beb243aa33713eab7a8ce29f3b2130cd7460a6ddaa62cc4abdd8df7c04465396482f9d84c8bc0dffba4eca9f7b10f043194566cad0408033ad53b704752964bc354877cc7c494f2714103a2d6fe12ab20a5ac6042168cbef3d0448c12fad8366d09b03830bbd359d01139b8e515660217d82692f5be30999cf60e2e7e3c78f00fed47de7994a6b45c9843c7da8ed08998f392e48b72270ba7375b61babab937410848b3afa70f9e7c5bd68a0902e12a4ae9617f933ec03270e7560cfd333a4fc525d17122913e7d24985a9becd1cfa864477eb5ac2e061616b52f89b4e8e893449ff951ee102ff45e266d5c0a1225b5c0e57ac95e557e6a67f331ef68012323b0fb73a6779f715b69d41dff6fde128fe71676eea5999c97da5e6e0c0ed4cbb3d3fe70e3e8ea2d03f59e64fa9d45c81bd11b99ff33e62503935e50f6c04477f45e00c014454ef64dd49bb92fc20084766988adbc9b35142dfab262f456f0d9e3dfac8b6d4106ee5b1513f9cc215343cefa7854ff68db1da31db4d2f80caf1e52e4e14338137dfe9667852a3eca6f42dfe381796fad39d932adfa6b847199eb56dd04cae2697a7ba7754f35c37317f81d62f3eb7f5a764874efaf1c9a700d5261eb8c109921b453398f459ae6482be8cf6d9705a8263d4c67767e88997d078c15a246bf59b4d53d407e16950366d8f126ec5cdaedf514789364364b4485ed7a325d7c8fb964eaa9b140e797e773c608e7994c066b889832590c6ff7469bd154c3535ca326009aa23f1c9d19f947b978b2b08e3059db117d7d20da5394b549e0931d29af53070f8b40f0cc5cad338e4026687e73e87f452f1e51db39bf3334e1ea69496c9688609fb22c0e51619c80bd8c5cd573f636243b25941ecfa17063e8ca1a21fec58aeff87fc1bc3a92ee72d9501f300172e683d6e04b38b7e89de1ff5e801d0d881c314a75a014754a9d2354551e4b24b6b2d6b486ed49026b9df0e82cb1aefb84866fa849911c61c599365ddaf73c8679ea4d9d22285fd72634f5dc700978d7fdb61befe301012dca2dd103d6752807cc204a6101d110b6a5ecd5aefa8af2b1fed1ecf15b18e686d202daef48825213e302269ba386a17049b5c4fab54de595a5e2328f27088d9f56c6bc129ffbac88aa5638e5449f361abd1d2d91f2f65ad1ad385b6d5cf3e3d9fddbe1cc5dcba2583601a81ac376bf07a5a10be0c27c0424cc38c04c2f253dd9fd01a205ff68aa49c0725e129eb3d9ba390b25afe3cac92a38c050a205549a0aee293850081ca71d3f4b86c72a282072a7e454c66a1304be0123e6cbbdc3d855bd433379d194ececebf86163d37f31ee15e5edee526cb7cd1cf96c863a20b2f90b4b58e02210998026c88e8e1acfea900518a8138034c6fe0d39a54ddedb04a3c66748bbf6785cb74b3e8d3518f8079d005cf3ae15cdac1abaf93d5827589d089cd7daccd2da464ed3f87d4b0cf32cbf298aa6b09c660068b6b3b588bc7f0f33f918bfdd33c75353b623c26476c4e9ea9b5400bca8a17a6b5ccfae433f63095e2c0792d601487c47c035999067135d61b0f1946db4b851aa2f7d586c19e838c2cd38e10f575d0b49a215482ec6ce25fddfbb00f616296846007d5271520fa7f1ac003efd7b1a0bd7eb7a7bfa7ccef8b402369d22165e07c9476fdf2aea66c34e8c92a6ccbda6719ec368893bfcca150c6829513eaabdbe7bf2f37245e3b160e7ce7ecfd654d3360a77931d50c63daea7579b4a0c92fa1a6a9c971f27e5e6e2e19a077227f6bf69aa6bd7556dcdcc088646468b4ab2db6437a66e045b15393a50b73f9a76b9816142fa10f324f488cd6215b7967a49f097abf6955e22732cfd3ec4473e73557f56de4db376b9af48ca9f83135ee7220eba45c377b01ad135811b8ed810c0a3fcaf10469a265ef4f3f737270b9a80f617f2458bf38523575c9022668c3760df9d88e5c05367b6ba0079ef9cece2f61b8d0eb23cd40670975e74b4c5a3607f2c4410fe0bd59b6b01e3c7f2ef03437672093b43bdbc8fc82be83544af3c7d53150ab1b3ebccc9219e8e72decde672e233e80030dd2c69e9abaa0b0db9baed49218c7a6940ec6fc4a887c22c3a5141362a7b6f615c15d60fc558c997603085895617e6ce71a57d34a30485907d27703eae64991262fbcbfc8cf78219b6fca49f1671edb0215c1b75b1e266137bd6a142ade281a0895099d58803e0a450cb8e2a171613f63e3c417cd166e2cc0de70e152af55743dc12b5f1c69a740ef28f7ec06562495fd3cce4b2ededb368492f6e2509417f4f0cb09dd4f57e0c33e7816387ad6b47922361f6d86210fe516a048738db895c0a2957031883704df1346ac31b626e0f0221f602a98f126f8962513e54bb2a5494c98b220f30f564980fac36dbd33ce7b5090201b106d169e86ec8f0fc189f85ecd5beb5b2a3282dec14e52aa4e2f0a08c651ad6bfcfee47eef72d139c72184d7715c49b3dbbbaba3a7f55546da5bdf45704d132d9cf3524906c9943d66a0c0289863821fe4dcf1fb001f44ca95b005039d2467d49ccce0ff947c3ad9497edbc36aa227ad9e1389f5b9b2df87dcb1bb6029d6141559218323ef7f99f86ee9e937654cfa20e829ac33ebb44fdaae313b4fdb85f2e4e0780a52f6cb9b4b709d5b70eddd93d45109e11e579bd4b2d8ca82bc3b4b3e1909088d9d15d598dde6d44b107f8711e16bc04beeefaa3aeeb815af7f594461e0946337cdcf0b14feb35ef42aef3455b057ec56fc04aaa30ed1cb6d53ba35e3eaf0df4046eeffa3fab285ea31598e7309ddddcc587ed4ebcf37b2e317b0e1785a53f616d767152ef313146704c80990e3ce9f91bded474695cc227c8174f5f5a1dc8129ee37759756d54a3f09e9e642e56bfbc800effa2643b99f265c9d0ec39c0e4b54a9c34ad71686a082e371bdfa3fb286f91113b22d99d7c4acef7c7da5b8d1e0f9c4c553ec798132b98894f33eba0cd30b40374e686a521e8a566148e5425f72f7750fa108aa12741a1b04fdcfb1df6b027f45c4f1cd8d1b695509b907280e49e96b8afdc71cdc576a51a9944429c10a9026cc52e45e0ad4"; -// //使用aes加密 -// String encrypted = AESTool.encrypt(xml, key); -// System.out.println("encrypted: \n" + encrypted); -// System.out.println("encrypted length: \n" + encrypted.length()); -// -// //解密 -// String decrypted = AESTool.decrypt(encrypted, key); -// System.out.println("decrypted: \n" + decrypted); -// System.out.println("decrypted length: \n" + decrypted.length()); -// -// -// boolean isSuccessful = StringUtils.equals(decrypted, xml); -// System.out.println(isSuccessful); - System.out.println(AESTool.decrypt(str, "adjdjfjfjfjdkdkd")); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/utils/Base64.java b/src/main/java/io/github/ehlxr/utils/Base64.java deleted file mode 100644 index b1b5de3..0000000 --- a/src/main/java/io/github/ehlxr/utils/Base64.java +++ /dev/null @@ -1,615 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import java.util.Arrays; - -public class Base64 { - private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); - private static final int[] IA = new int[256]; - - static { - Arrays.fill(IA, -1); - for (int i = 0, iS = CA.length; i < iS; i++) - IA[CA[i]] = i; - IA['='] = 0; - } - - // **************************************************************************************** - // * char[] version - // **************************************************************************************** - - /** - * Encodes a raw byte array into a BASE64 char[] representation - * i accordance with RFC 2045. - * - * @param sArr - * The bytes to convert. If null or length 0 an - * empty array will be returned. - * @param lineSep - * Optional "\r\n" after 76 characters, unless end of file.
- * No line separator will be in breach of RFC 2045 which - * specifies max 76 per line but will be a little faster. - * @return A BASE64 encoded array. Never null. - */ - public final static char[] encodeToChar(byte[] sArr, boolean lineSep) { - // Check special case - int sLen = sArr != null ? sArr.length : 0; - if (sLen == 0) - return new char[0]; - - int eLen = (sLen / 3) * 3; // Length of even 24-bits. - int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count - int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of - // returned - // array - char[] dArr = new char[dLen]; - - // Encode even 24-bits - for (int s = 0, d = 0, cc = 0; s < eLen;) { - // Copy next three bytes into lower 24 bits of int, paying attension - // to sign. - int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); - - // Encode the int into four chars - dArr[d++] = CA[(i >>> 18) & 0x3f]; - dArr[d++] = CA[(i >>> 12) & 0x3f]; - dArr[d++] = CA[(i >>> 6) & 0x3f]; - dArr[d++] = CA[i & 0x3f]; - - // Add optional line separator - if (lineSep && ++cc == 19 && d < dLen - 2) { - dArr[d++] = '\r'; - dArr[d++] = '\n'; - cc = 0; - } - } - - // Pad and encode last bits if source isn't even 24 bits. - int left = sLen - eLen; // 0 - 2. - if (left > 0) { - // Prepare the int - int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); - - // Set last four chars - dArr[dLen - 4] = CA[i >> 12]; - dArr[dLen - 3] = CA[(i >>> 6) & 0x3f]; - dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '='; - dArr[dLen - 1] = '='; - } - return dArr; - } - - /** - * Decodes a BASE64 encoded char array. All illegal characters will be - * ignored and can handle both arrays with and without line separators. - * - * @param sArr - * The source array. null or length 0 will return an - * empty array. - * @return The decoded array of bytes. May be of length 0. Will be - * null if the legal characters (including '=') isn't - * divideable by 4. (I.e. definitely corrupted). - */ - public final static byte[] decode(char[] sArr) { - // Check special case - int sLen = sArr != null ? sArr.length : 0; - if (sLen == 0) - return new byte[0]; - - // Count illegal characters (including '\r', '\n') to know what size the - // returned array will be, - // so we don't have to reallocate & copy it later. - int sepCnt = 0; // Number of separator characters. (Actually illegal - // characters, but that's a bonus...) - for (int i = 0; i < sLen; i++) - // If input is "pure" (I.e. no line separators or illegal chars) - // base64 this loop can be commented out. - if (IA[sArr[i]] < 0) - sepCnt++; - - // Check so that legal chars (including '=') are evenly divideable by 4 - // as specified in RFC 2045. - if ((sLen - sepCnt) % 4 != 0) - return null; - - int pad = 0; - for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0;) - if (sArr[i] == '=') - pad++; - - int len = ((sLen - sepCnt) * 6 >> 3) - pad; - - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - for (int s = 0, d = 0; d < len;) { - // Assemble three bytes into an int from four "valid" characters. - int i = 0; - for (int j = 0; j < 4; j++) { // j only increased if a valid char - // was found. - int c = IA[sArr[s++]]; - if (c >= 0) - i |= c << (18 - j * 6); - else - j--; - } - // Add the bytes - dArr[d++] = (byte) (i >> 16); - if (d < len) { - dArr[d++] = (byte) (i >> 8); - if (d < len) - dArr[d++] = (byte) i; - } - } - return dArr; - } - - /** - * Decodes a BASE64 encoded char array that is known to be resonably well - * formatted. The method is about twice as fast as {@link #decode(char[])}. - * The preconditions are:
- * + The array must have a line length of 76 chars OR no line separators at - * all (one line).
- * + Line separator must be "\r\n", as specified in RFC 2045 + The array - * must not contain illegal characters within the encoded string
- * + The array CAN have illegal characters at the beginning and end, those - * will be dealt with appropriately.
- * - * @param sArr - * The source array. Length 0 will return an empty array. - * null will throw an exception. - * @return The decoded array of bytes. May be of length 0. - */ - public final static byte[] decodeFast(char[] sArr) { - // Check special case - int sLen = sArr.length; - if (sLen == 0) - return new byte[0]; - - int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. - - // Trim illegal chars from start - while (sIx < eIx && IA[sArr[sIx]] < 0) - sIx++; - - // Trim illegal chars from end - while (eIx > 0 && IA[sArr[eIx]] < 0) - eIx--; - - // get the padding count (=) (0, 1 or 2) - int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count - // '=' - // at - // end. - int cCnt = eIx - sIx + 1; // Content count including possible separators - int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; - - int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded - // bytes - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - // Decode all but the last 0 - 2 bytes. - int d = 0; - for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { - // Assemble three bytes into an int from four "valid" characters. - int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; - - // Add the bytes - dArr[d++] = (byte) (i >> 16); - dArr[d++] = (byte) (i >> 8); - dArr[d++] = (byte) i; - - // If line separator, jump over it. - if (sepCnt > 0 && ++cc == 19) { - sIx += 2; - cc = 0; - } - } - - if (d < len) { - // Decode last 1-3 bytes (incl '=') into 1-3 bytes - int i = 0; - for (int j = 0; sIx <= eIx - pad; j++) - i |= IA[sArr[sIx++]] << (18 - j * 6); - - for (int r = 16; d < len; r -= 8) - dArr[d++] = (byte) (i >> r); - } - - return dArr; - } - - // **************************************************************************************** - // * byte[] version - // **************************************************************************************** - - /** - * Encodes a raw byte array into a BASE64 byte[] representation - * i accordance with RFC 2045. - * - * @param sArr - * The bytes to convert. If null or length 0 an - * empty array will be returned. - * @param lineSep - * Optional "\r\n" after 76 characters, unless end of file.
- * No line separator will be in breach of RFC 2045 which - * specifies max 76 per line but will be a little faster. - * @return A BASE64 encoded array. Never null. - */ - public final static byte[] encodeToByte(byte[] sArr, boolean lineSep) { - // Check special case - int sLen = sArr != null ? sArr.length : 0; - if (sLen == 0) - return new byte[0]; - - int eLen = (sLen / 3) * 3; // Length of even 24-bits. - int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count - int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of - // returned - // array - byte[] dArr = new byte[dLen]; - - // Encode even 24-bits - for (int s = 0, d = 0, cc = 0; s < eLen;) { - // Copy next three bytes into lower 24 bits of int, paying attension - // to sign. - int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); - - // Encode the int into four chars - dArr[d++] = (byte) CA[(i >>> 18) & 0x3f]; - dArr[d++] = (byte) CA[(i >>> 12) & 0x3f]; - dArr[d++] = (byte) CA[(i >>> 6) & 0x3f]; - dArr[d++] = (byte) CA[i & 0x3f]; - - // Add optional line separator - if (lineSep && ++cc == 19 && d < dLen - 2) { - dArr[d++] = '\r'; - dArr[d++] = '\n'; - cc = 0; - } - } - - // Pad and encode last bits if source isn't an even 24 bits. - int left = sLen - eLen; // 0 - 2. - if (left > 0) { - // Prepare the int - int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); - - // Set last four chars - dArr[dLen - 4] = (byte) CA[i >> 12]; - dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f]; - dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '='; - dArr[dLen - 1] = '='; - } - return dArr; - } - - /** - * Decodes a BASE64 encoded byte array. All illegal characters will be - * ignored and can handle both arrays with and without line separators. - * - * @param sArr - * The source array. Length 0 will return an empty array. - * null will throw an exception. - * @return The decoded array of bytes. May be of length 0. Will be - * null if the legal characters (including '=') isn't - * divideable by 4. (I.e. definitely corrupted). - */ - public final static byte[] decode(byte[] sArr) { - // Check special case - int sLen = sArr.length; - - // Count illegal characters (including '\r', '\n') to know what size the - // returned array will be, - // so we don't have to reallocate & copy it later. - int sepCnt = 0; // Number of separator characters. (Actually illegal - // characters, but that's a bonus...) - for (int i = 0; i < sLen; i++) - // If input is "pure" (I.e. no line separators or illegal chars) - // base64 this loop can be commented out. - if (IA[sArr[i] & 0xff] < 0) - sepCnt++; - - // Check so that legal chars (including '=') are evenly divideable by 4 - // as specified in RFC 2045. - if ((sLen - sepCnt) % 4 != 0) - return null; - - int pad = 0; - for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0;) - if (sArr[i] == '=') - pad++; - - int len = ((sLen - sepCnt) * 6 >> 3) - pad; - - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - for (int s = 0, d = 0; d < len;) { - // Assemble three bytes into an int from four "valid" characters. - int i = 0; - for (int j = 0; j < 4; j++) { // j only increased if a valid char - // was found. - int c = IA[sArr[s++] & 0xff]; - if (c >= 0) - i |= c << (18 - j * 6); - else - j--; - } - - // Add the bytes - dArr[d++] = (byte) (i >> 16); - if (d < len) { - dArr[d++] = (byte) (i >> 8); - if (d < len) - dArr[d++] = (byte) i; - } - } - - return dArr; - } - - /** - * Decodes a BASE64 encoded byte array that is known to be resonably well - * formatted. The method is about twice as fast as {@link #decode(byte[])}. - * The preconditions are:
- * + The array must have a line length of 76 chars OR no line separators at - * all (one line).
- * + Line separator must be "\r\n", as specified in RFC 2045 + The array - * must not contain illegal characters within the encoded string
- * + The array CAN have illegal characters at the beginning and end, those - * will be dealt with appropriately.
- * - * @param sArr - * The source array. Length 0 will return an empty array. - * null will throw an exception. - * @return The decoded array of bytes. May be of length 0. - */ - public final static byte[] decodeFast(byte[] sArr) { - // Check special case - int sLen = sArr.length; - if (sLen == 0) - return new byte[0]; - - int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. - - // Trim illegal chars from start - while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0) - sIx++; - - // Trim illegal chars from end - while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0) - eIx--; - - // get the padding count (=) (0, 1 or 2) - int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count - // '=' - // at - // end. - int cCnt = eIx - sIx + 1; // Content count including possible separators - int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; - - int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded - // bytes - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - // Decode all but the last 0 - 2 bytes. - int d = 0; - for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { - // Assemble three bytes into an int from four "valid" characters. - int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; - - // Add the bytes - dArr[d++] = (byte) (i >> 16); - dArr[d++] = (byte) (i >> 8); - dArr[d++] = (byte) i; - - // If line separator, jump over it. - if (sepCnt > 0 && ++cc == 19) { - sIx += 2; - cc = 0; - } - } - - if (d < len) { - // Decode last 1-3 bytes (incl '=') into 1-3 bytes - int i = 0; - for (int j = 0; sIx <= eIx - pad; j++) - i |= IA[sArr[sIx++]] << (18 - j * 6); - - for (int r = 16; d < len; r -= 8) - dArr[d++] = (byte) (i >> r); - } - - return dArr; - } - - // **************************************************************************************** - // * String version - // **************************************************************************************** - - /** - * Encodes a raw byte array into a BASE64 String representation - * i accordance with RFC 2045. - * - * @param sArr - * The bytes to convert. If null or length 0 an - * empty array will be returned. - * @param lineSep - * Optional "\r\n" after 76 characters, unless end of file.
- * No line separator will be in breach of RFC 2045 which - * specifies max 76 per line but will be a little faster. - * @return A BASE64 encoded array. Never null. - */ - public final static String encodeToString(byte[] sArr, boolean lineSep) { - // Reuse char[] since we can't create a String incrementally anyway and - // StringBuffer/Builder would be slower. - return new String(encodeToChar(sArr, lineSep)); - } - - /** - * Decodes a BASE64 encoded String. All illegal characters will - * be ignored and can handle both strings with and without line separators. - *
- * Note! It can be up to about 2x the speed to call - * decode(str.toCharArray()) instead. That will create a - * temporary array though. This version will use str.charAt(i) - * to iterate the string. - * - * @param str - * The source string. null or length 0 will return - * an empty array. - * @return The decoded array of bytes. May be of length 0. Will be - * null if the legal characters (including '=') isn't - * divideable by 4. (I.e. definitely corrupted). - */ - public final static byte[] decode(String str) { - // Check special case - int sLen = str != null ? str.length() : 0; - if (sLen == 0) - return new byte[0]; - - // Count illegal characters (including '\r', '\n') to know what size the - // returned array will be, - // so we don't have to reallocate & copy it later. - int sepCnt = 0; // Number of separator characters. (Actually illegal - // characters, but that's a bonus...) - for (int i = 0; i < sLen; i++) - // If input is "pure" (I.e. no line separators or illegal chars) - // base64 this loop can be commented out. - if (IA[str.charAt(i)] < 0) - sepCnt++; - - // Check so that legal chars (including '=') are evenly divideable by 4 - // as specified in RFC 2045. - if ((sLen - sepCnt) % 4 != 0) - return null; - - // Count '=' at end - int pad = 0; - for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;) - if (str.charAt(i) == '=') - pad++; - - int len = ((sLen - sepCnt) * 6 >> 3) - pad; - - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - for (int s = 0, d = 0; d < len;) { - // Assemble three bytes into an int from four "valid" characters. - int i = 0; - for (int j = 0; j < 4; j++) { // j only increased if a valid char - // was found. - int c = IA[str.charAt(s++)]; - if (c >= 0) - i |= c << (18 - j * 6); - else - j--; - } - // Add the bytes - dArr[d++] = (byte) (i >> 16); - if (d < len) { - dArr[d++] = (byte) (i >> 8); - if (d < len) - dArr[d++] = (byte) i; - } - } - return dArr; - } - - /** - * Decodes a BASE64 encoded string that is known to be resonably well - * formatted. The method is about twice as fast as {@link #decode(String)}. - * The preconditions are:
- * + The array must have a line length of 76 chars OR no line separators at - * all (one line).
- * + Line separator must be "\r\n", as specified in RFC 2045 + The array - * must not contain illegal characters within the encoded string
- * + The array CAN have illegal characters at the beginning and end, those - * will be dealt with appropriately.
- * - * @param s - * The source string. Length 0 will return an empty array. - * null will throw an exception. - * @return The decoded array of bytes. May be of length 0. - */ - public final static byte[] decodeFast(String s) { - // Check special case - int sLen = s.length(); - if (sLen == 0) - return new byte[0]; - - int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. - - // Trim illegal chars from start - while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0) - sIx++; - - // Trim illegal chars from end - while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0) - eIx--; - - // get the padding count (=) (0, 1 or 2) - int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count - // '=' - // at - // end. - int cCnt = eIx - sIx + 1; // Content count including possible separators - int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; - - int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded - // bytes - byte[] dArr = new byte[len]; // Preallocate byte[] of exact length - - // Decode all but the last 0 - 2 bytes. - int d = 0; - for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { - // Assemble three bytes into an int from four "valid" characters. - int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)]; - - // Add the bytes - dArr[d++] = (byte) (i >> 16); - dArr[d++] = (byte) (i >> 8); - dArr[d++] = (byte) i; - - // If line separator, jump over it. - if (sepCnt > 0 && ++cc == 19) { - sIx += 2; - cc = 0; - } - } - - if (d < len) { - // Decode last 1-3 bytes (incl '=') into 1-3 bytes - int i = 0; - for (int j = 0; sIx <= eIx - pad; j++) - i |= IA[s.charAt(sIx++)] << (18 - j * 6); - - for (int r = 16; d < len; r -= 8) - dArr[d++] = (byte) (i >> r); - } - - return dArr; - } -} diff --git a/src/main/java/io/github/ehlxr/utils/Builder.java b/src/main/java/io/github/ehlxr/utils/Builder.java deleted file mode 100644 index 41d37ad..0000000 --- a/src/main/java/io/github/ehlxr/utils/Builder.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * @author ehlxr - * @since 2021-02-04 14:40. - */ -public class Builder { - private final Supplier instantiator; - private final List> modifiers = new ArrayList<>(); - - public Builder(Supplier instantiator) { - this.instantiator = instantiator; - } - - public static Builder of(Supplier instantiator) { - return new Builder<>(instantiator); - } - - public Builder with(Consumer1 consumer, P1 p1) { - Consumer c = instance -> consumer.accept(instance, p1); - modifiers.add(c); - return this; - } - - public Builder with(Consumer2 consumer, P1 p1, P2 p2) { - Consumer c = instance -> consumer.accept(instance, p1, p2); - modifiers.add(c); - return this; - } - - public Builder with(Consumer3 consumer, P1 p1, P2 p2, P3 p3) { - Consumer c = instance -> consumer.accept(instance, p1, p2, p3); - modifiers.add(c); - return this; - } - - public T build() { - T value = instantiator.get(); - modifiers.forEach(modifier -> modifier.accept(value)); - modifiers.clear(); - return value; - } - - /** - * 1 参数 Consumer - */ - @FunctionalInterface - public interface Consumer1 { - void accept(T t, P1 p1); - } - - /** - * 2 参数 Consumer - */ - @FunctionalInterface - public interface Consumer2 { - void accept(T t, P1 p1, P2 p2); - } - - /** - * 3 参数 Consumer - */ - @FunctionalInterface - public interface Consumer3 { - void accept(T t, P1 p1, P2 p2, P3 p3); - } -} diff --git a/src/main/java/io/github/ehlxr/utils/CCRDFile.java b/src/main/java/io/github/ehlxr/utils/CCRDFile.java deleted file mode 100644 index 69848d1..0000000 --- a/src/main/java/io/github/ehlxr/utils/CCRDFile.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -/** - * Created by ehlxr on 2017/3/18. - */ - -import java.io.File; -import java.io.IOException; - -/** - * 创建新文件和目录 - */ -public class CCRDFile { - // 验证字符串是否为正确路径名的正则表达式 - private static final String matches = "[A-Za-z]:\\\\[^:?\"><*]*"; - // 通过 sPath.matches(matches) 方法的返回值判断是否正确 - // sPath 为路径字符串 - boolean flag = false; - File file; - - // 创建单个文件 - public static boolean createFile(String filePath) { - File file = new File(filePath); - if (file.exists()) {// 判断文件是否存在 - System.out.println("目标文件已存在" + filePath); - return false; - } - if (filePath.endsWith(File.separator)) {// 判断文件是否为目录 - System.out.println("目标文件不能为目录!"); - return false; - } - if (!file.getParentFile().exists()) {// 判断目标文件所在的目录是否存在 - // 如果目标文件所在的文件夹不存在,则创建父文件夹 - System.out.println("目标文件所在目录不存在,准备创建它!"); - if (!file.getParentFile().mkdirs()) {// 判断创建目录是否成功 - System.out.println("创建目标文件所在的目录失败!"); - return false; - } - } - try { - if (file.createNewFile()) {// 创建目标文件 - System.out.println("创建文件成功:" + filePath); - return true; - } else { - System.out.println("创建文件失败!"); - return false; - } - } catch (IOException e) {// 捕获异常 - e.printStackTrace(); - System.out.println("创建文件失败!" + e.getMessage()); - return false; - } - } - - // 创建目录 - public static boolean createDir(String destDirName) { - File dir = new File(destDirName); - if (dir.exists()) {// 判断目录是否存在 - System.out.println("创建目录失败,目标目录已存在!"); - return false; - } - if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束 - destDirName = destDirName + File.separator; - } - if (dir.mkdirs()) {// 创建目标目录 - System.out.println("创建目录成功!" + destDirName); - return true; - } else { - System.out.println("创建目录失败!"); - return false; - } - } - - // 创建临时文件 - public static String createTempFile(String prefix, String suffix, - String dirName) { - File tempFile = null; - if (dirName == null) {// 目录如果为空 - try { - tempFile = File.createTempFile(prefix, suffix);// 在默认文件夹下创建临时文件 - return tempFile.getCanonicalPath();// 返回临时文件的路径 - } catch (IOException e) {// 捕获异常 - e.printStackTrace(); - System.out.println("创建临时文件失败:" + e.getMessage()); - return null; - } - } else { - // 指定目录存在 - File dir = new File(dirName);// 创建目录 - if (!dir.exists()) { - // 如果目录不存在则创建目录 - if (CCRDFile.createDir(dirName)) { - System.out.println("创建临时文件失败,不能创建临时文件所在的目录!"); - return null; - } - } - try { - tempFile = File.createTempFile(prefix, suffix, dir);// 在指定目录下创建临时文件 - return tempFile.getCanonicalPath();// 返回临时文件的路径 - } catch (IOException e) {// 捕获异常 - e.printStackTrace(); - System.out.println("创建临时文件失败!" + e.getMessage()); - return null; - } - } - } - - public boolean DeleteFolder(String deletePath) {// 根据路径删除指定的目录或文件,无论存在与否 - flag = false; - if (deletePath.matches(matches)) { - file = new File(deletePath); - if (!file.exists()) {// 判断目录或文件是否存在 - return flag; // 不存在返回 false - } else { - - if (file.isFile()) {// 判断是否为文件 - return deleteFile(deletePath);// 为文件时调用删除文件方法 - } else { - return deleteDirectory(deletePath);// 为目录时调用删除目录方法 - } - } - } else { - System.out.println("要传入正确路径!"); - return false; - } - } - - public boolean deleteFile(String filePath) {// 删除单个文件 - flag = false; - file = new File(filePath); - if (file.isFile() && file.exists()) {// 路径为文件且不为空则进行删除 - file.delete();// 文件删除 - flag = true; - } - return flag; - } - - public boolean deleteDirectory(String dirPath) {// 删除目录(文件夹)以及目录下的文件 - // 如果sPath不以文件分隔符结尾,自动添加文件分隔符 - if (!dirPath.endsWith(File.separator)) { - dirPath = dirPath + File.separator; - } - File dirFile = new File(dirPath); - // 如果dir对应的文件不存在,或者不是一个目录,则退出 - if (!dirFile.exists() || !dirFile.isDirectory()) { - return false; - } - flag = true; - File[] files = dirFile.listFiles();// 获得传入路径下的所有文件 - for (int i = 0; i < files.length; i++) {// 循环遍历删除文件夹下的所有文件(包括子目录) - if (files[i].isFile()) {// 删除子文件 - flag = deleteFile(files[i].getAbsolutePath()); - System.out.println(files[i].getAbsolutePath() + " 删除成功"); - if (!flag) - break;// 如果删除失败,则跳出 - } else {// 运用递归,删除子目录 - flag = deleteDirectory(files[i].getAbsolutePath()); - if (!flag) - break;// 如果删除失败,则跳出 - } - } - if (!flag) - return false; - // 删除当前目录 - return dirFile.delete(); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/utils/Code.java b/src/main/java/io/github/ehlxr/utils/Code.java deleted file mode 100644 index b04e686..0000000 --- a/src/main/java/io/github/ehlxr/utils/Code.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -/** - * 自定义状态码 - * - * @author ehlxr - * @since 2020/3/18. - */ -public enum Code { - /** - * 成功 - */ - SUCCESSFUL(200, "success"), - - /** - * 未知异常 - */ - UNKNOWN_EXCEPTION(600, "unknown server exception"), - - /** - * 请求参数不能为空 - */ - REQUEST_PARAM_NULL_EXCEPTION(601, "required param should not be null"), - - /** - * 业务异常 - */ - SERVICE_EXCEPTION(602, "service exception"); - - - private final int code; - private final String message; - - Code(int code, String message) { - this.code = code; - this.message = message; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - @Override - public String toString() { - return "Code{" + - "code=" + code + - ", message='" + message + '\'' + - '}'; - } - - private static final Code[] CODES = Code.values(); - - public static Code code(int code) { - for (Code c : CODES) { - if (code == c.getCode()) { - return c; - } - } - return null; - } - -} - diff --git a/src/main/java/io/github/ehlxr/utils/CommonUtils.java b/src/main/java/io/github/ehlxr/utils/CommonUtils.java deleted file mode 100644 index 46e32f3..0000000 --- a/src/main/java/io/github/ehlxr/utils/CommonUtils.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import javax.servlet.http.HttpServletRequest; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -public class CommonUtils { - private static final double EARTH_RADIUS = 6371; // 默认地球半径(单位km) - - /** - * 转化为弧度(rad) - * - * @param d - * @return - */ - private static double rad(double d) { - return d * Math.PI / 180.0; - } - - /** - * 对象转换成另一个类对象 - * - * @param bean - * 转换的数据对象 - * @param clazz - * 转换后类对象 - * @return 转换后数据对象 - */ - public static T convertClass(Object bean, Class clazz) { - - Map maps = new HashMap(); - T dataBean = null; - if (null == bean) { - return null; - } - try { - Class cls = bean.getClass(); - dataBean = clazz.newInstance(); - Field[] fields = cls.getDeclaredFields(); - Field[] beanFields = clazz.getDeclaredFields(); - for (Field field : fields) { - try { - String fieldName = field.getName().toLowerCase(); - String strGet = "get" + fieldName; - - Method[] methods = cls.getMethods(); - for (Method method : methods) { - if (strGet.equalsIgnoreCase(method.getName())) { - Object object = method.invoke(bean); - maps.put(fieldName, object == null ? "" : object); - } - } - } catch (Exception e) { - } - } - for (Field field : beanFields) { - field.setAccessible(true); - String fieldName = field.getName().toLowerCase(); - Class fieldType = field.getType(); - Object fieldValue = (maps.get(fieldName) == null || "".equals(maps.get(fieldName))) ? null : maps.get(fieldName); - if (fieldValue != null) { - if (String.class.equals(fieldType)) { - if (fieldValue instanceof Date) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - field.set(dataBean, sdf.format(fieldValue)); - } else { - field.set(dataBean, fieldValue.toString()); - } - } else if (byte.class.equals(fieldType)) { - field.setByte(dataBean, Byte.parseByte(fieldValue.toString())); - - } else if (Byte.class.equals(fieldType)) { - field.set(dataBean, Byte.valueOf(fieldValue.toString())); - - } else if (boolean.class.equals(fieldType)) { - field.setBoolean(dataBean, Boolean.parseBoolean(fieldValue.toString())); - - } else if (Boolean.class.equals(fieldType)) { - field.set(dataBean, Boolean.valueOf(fieldValue.toString())); - - } else if (short.class.equals(fieldType)) { - field.setShort(dataBean, Short.parseShort(fieldValue.toString())); - - } else if (Short.class.equals(fieldType)) { - field.set(dataBean, Short.valueOf(fieldValue.toString())); - - } else if (int.class.equals(fieldType)) { - field.setInt(dataBean, Integer.parseInt(fieldValue.toString())); - - } else if (Integer.class.equals(fieldType)) { - field.set(dataBean, Integer.valueOf(fieldValue.toString())); - - } else if (long.class.equals(fieldType)) { - field.setLong(dataBean, Long.parseLong(fieldValue.toString())); - - } else if (Long.class.equals(fieldType)) { - field.set(dataBean, Long.valueOf(fieldValue.toString())); - - } else if (float.class.equals(fieldType)) { - field.setFloat(dataBean, Float.parseFloat(fieldValue.toString())); - - } else if (Float.class.equals(fieldType)) { - field.set(dataBean, Float.valueOf(fieldValue.toString())); - - } else if (double.class.equals(fieldType)) { - field.setDouble(dataBean, Double.parseDouble(fieldValue.toString())); - - } else if (Double.class.equals(fieldType)) { - field.set(dataBean, Double.valueOf(fieldValue.toString())); - - } else if (Date.class.equals(fieldType)) { - field.set(dataBean, fieldValue); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - return dataBean; - } - - /** - * 获取当前网络ip - * - * @param request - * @return - */ - public static String getIpAddr(HttpServletRequest request) { - String ipAddress = request.getHeader("x-forwarded-for"); - if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("WL-Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getRemoteAddr(); - if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) { - // 根据网卡取本机配置的IP - InetAddress inet = null; - try { - inet = InetAddress.getLocalHost(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - ipAddress = inet.getHostAddress(); - } - } - // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 - if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()=15 - if (ipAddress.indexOf(",") > 0) { - ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); - } - } - return ipAddress; - } - - /** - * 计算经纬度点对应正方形4个点的坐标 - * - * @param longitude - * @param latitude - * @param distance - * @return - */ - public static Map returnLLSquarePoint(double longitude, double latitude, double distance) { - Map squareMap = new HashMap(); - // 计算经度弧度,从弧度转换为角度 - double dLongitude = 2 * (Math.asin(Math.sin(distance / (2 * EARTH_RADIUS)) / Math.cos(Math.toRadians(latitude)))); - dLongitude = Math.toDegrees(dLongitude); - // 计算纬度角度 - double dLatitude = distance / EARTH_RADIUS; - dLatitude = Math.toDegrees(dLatitude); - // 正方形 - double[] leftTopPoint = { latitude + dLatitude, longitude - dLongitude }; - double[] rightTopPoint = { latitude + dLatitude, longitude + dLongitude }; - double[] leftBottomPoint = { latitude - dLatitude, longitude - dLongitude }; - double[] rightBottomPoint = { latitude - dLatitude, longitude + dLongitude }; - squareMap.put("leftTopPoint", leftTopPoint); - squareMap.put("rightTopPoint", rightTopPoint); - squareMap.put("leftBottomPoint", leftBottomPoint); - squareMap.put("rightBottomPoint", rightBottomPoint); - return squareMap; - } - - /** - * 基于googleMap中的算法得到两经纬度之间的距离,计算精度与谷歌地图的距离精度差不多,相差范围在0.2米以下 - * - * @param lon1 - * 第一点的精度 - * @param lat1 - * 第一点的纬度 - * @param lon2 - * 第二点的精度 - * @param lat3 - * 第二点的纬度 - * @return 返回的距离,单位m - */ - public static double getDistance(double lon1, double lat1, double lon2, double lat2) { - double radLat1 = rad(lat1); - double radLat2 = rad(lat2); - double a = radLat1 - radLat2; - double b = rad(lon1) - rad(lon2); - double s = 2 - * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); - s = s * EARTH_RADIUS * 1000; - s = Math.round(s * 10000) / 10000; - return s; - } -} diff --git a/src/main/java/io/github/ehlxr/utils/DateUtil.java b/src/main/java/io/github/ehlxr/utils/DateUtil.java deleted file mode 100644 index a1e1198..0000000 --- a/src/main/java/io/github/ehlxr/utils/DateUtil.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; -import java.util.Calendar; -import java.util.Date; - -/** - * 时间工具类 - * - * @author ehlxr - * @since 2020-12-09 16:51. - */ -public class DateUtil { - public static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - private static final DateTimeFormatter FORMAT_1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); - public static final DateTimeFormatter FORMAT_2 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - public static final DateTimeFormatter FORMAT_3 = DateTimeFormatter.ofPattern("yyyyMMdd"); - public static final DateTimeFormatter FORMAT_4 = DateTimeFormatter.ofPattern("yyyy-MM"); - /** - * "Asia/Shanghai" - */ - private static final ZoneId ZONE_ID = ZoneId.of(ZoneId.SHORT_IDS.get("CTT")); - - private DateUtil() { - } - - /** - * 获取当前日期时间 - * - * @return 当前日期时间 {@link LocalDateTime} - */ - public static LocalDateTime currentDateTime() { - return LocalDateTime.now(ZONE_ID); - } - - /** - * 获取当前日期时间字符串 - * - * @return "yyyy-MM-dd HH:mm:ss" 格式字符串 - */ - public static String currentDateTimeStr() { - return LocalDateTime.now(ZONE_ID).format(FORMAT); - } - - /** - * 获取当前日期字符串 - * - * @return "yyyy-MM-dd" 格式字符串 - */ - public static String currentDateStr() { - return LocalDate.now(ZONE_ID).toString(); - } - - /** - * 计算当前时间以前几个月的时间 - * - * @param amount 月份 - * @return "yyyy-MM-dd HH:mm:ss" 格式字符串 - */ - public static String pastMonthsDateTime(long amount) { - return LocalDateTime.now(ZONE_ID).minus(amount, ChronoUnit.MONTHS).format(FORMAT); - } - - /** - * 计算当前时间以前几个月的时间 - * - * @param amount 月份 - * @return "yyyy-MM-dd" 格式字符串 - */ - public static String pastMonthsDate(long amount) { - return LocalDate.now(ZONE_ID).minus(amount, ChronoUnit.MONTHS).toString(); - } - - /** - * 计算指定时间(yyyy-MM-dd HH:mm:ss 格式字符串)以前几个月的时间 - * - * @param amount 月份 - * @return "yyyy-MM-dd HH:mm:ss" 格式字符串 - */ - public static String pastMonthsDate(String localDateTime, long amount) { - return LocalDateTime.parse(localDateTime, FORMAT).minus(amount, ChronoUnit.MONTHS).format(FORMAT); - } - - /** - * 指定日期格式化,带星期 - */ - public static String asStringWithWeek(String date) { - LocalDateTime localDateTime = LocalDateTime.parse(date, FORMAT); - String[] weekDays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"}; - int w = localDateTime.getDayOfWeek().getValue() - 1; - return localDateTime.format(FORMAT) + " " + weekDays[w]; - } - - /** - * LocalDate 转 Date - * - * @param localDate 要转换的 {@link LocalDate} - * @return {@link Date} - */ - public static Date asDate(LocalDate localDate) { - return Date.from(localDate.atStartOfDay().atZone(ZONE_ID).toInstant()); - } - - /** - * LocalDateTime 转 Date - * - * @param localDateTime 要转换的 {@link LocalDateTime} - * @return {@link Date} - */ - public static Date asDate(LocalDateTime localDateTime) { - return Date.from(localDateTime.atZone(ZONE_ID).toInstant()); - } - - /** - * Date 转 LocalDate - * - * @param date 要转换的 {@link Date} - * @return {@link LocalDate} - */ - public static LocalDate asLocalDate(Date date) { - return date.toInstant().atZone(ZONE_ID).toLocalDate(); - // return Instant.ofEpochMilli(date.getTime()).atZone(ZONE_ID).toLocalDate(); - } - - /** - * Date 转 LocalDateTime - * - * @param date 要转换的 {@link Date} - * @return {@link LocalDateTime} - */ - public static LocalDateTime asLocalDateTime(Date date) { - return LocalDateTime.ofInstant(date.toInstant(), ZONE_ID); - // return date.toInstant().atZone(ZONE_ID).toLocalDateTime(); - // return Instant.ofEpochMilli(date.getTime()).atZone(ZONE_ID).toLocalDateTime(); - } - - /** - * 日期字符串转 LocalDateTime - * - * @param date 要转换的 yyyy-MM-dd HH:mm:ss 类型字符串 - * @return {@link LocalDateTime} - */ - public static LocalDateTime asLocalDateTime(String date) { - return asLocalDateTime(date, FORMAT); - } - - /** - * 日期字符串转 LocalDateTime - * - * @param date 要转换的字符串 - * @param pattern 模式字符串,例如:yyyy-MM-dd HH:mm:ss - * @return {@link LocalDateTime} - */ - public static LocalDateTime asLocalDateTime(String date, String pattern) { - return asLocalDateTime(date, DateTimeFormatter.ofPattern(pattern)); - } - - private static LocalDateTime asLocalDateTime(String date, DateTimeFormatter formatter) { - return LocalDateTime.parse(date, formatter); - } - - public static Date parse(String strDate) throws ParseException { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - return sdf.parse(strDate); - } - - - /** - * 出生日期换年龄 - * - * @param birthDay - * @return - */ - public static int getAge(Date birthDay) { - Calendar cal = Calendar.getInstance(); - //出生日期晚于当前时间,无法计算 - if (cal.before(birthDay)) { - throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!"); - } - //当前年份 - int yearNow = cal.get(Calendar.YEAR); - //当前月份 - int monthNow = cal.get(Calendar.MONTH); - //当前日期 - int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); - cal.setTime(birthDay); - int yearBirth = cal.get(Calendar.YEAR); - int monthBirth = cal.get(Calendar.MONTH); - int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); - //计算整岁数 - int age = yearNow - yearBirth; - if (monthNow <= monthBirth) { - if (monthNow == monthBirth) { - //当前日期在生日之前,年龄减一 - if (dayOfMonthNow < dayOfMonthBirth) { - age--; - } - } else { - //当前月份在生日之前,年龄减一 - age--; - } - } - return age; - } - - public static Integer getDifMonth(Date startDate, Date endDate) { - Calendar start = Calendar.getInstance(); - Calendar end = Calendar.getInstance(); - start.setTime(startDate); - end.setTime(endDate); - int result = end.get(Calendar.MONTH) - start.get(Calendar.MONTH); - int month = (end.get(Calendar.YEAR) - start.get(Calendar.YEAR)) * 12; - return Math.abs(month + result); - } - - public static void main(String[] args) { - try { - System.out.println(getDifMonth(DateUtil.parse("2020-11-02 15:43:37"), DateUtil.parse("2020-10-01 15:43:37"))); - } catch (ParseException e) { - e.printStackTrace(); - } - - System.out.println(asStringWithWeek(currentDateTimeStr())); - System.out.println("DateUtil.currentDateTime():" + DateUtil.currentDateTimeStr()); - System.out.println("DateUtil.currentDate():" + DateUtil.currentDateStr()); - System.out.println("DateUtil.passMonthsDateTime(3):" + DateUtil.pastMonthsDateTime(3)); - System.out.println("DateUtil.passMonthsDate(3):" + DateUtil.pastMonthsDate(3)); - - // DateTimeFormatter t = new DateTimeFormatterBuilder() - // .parseCaseInsensitive() - // .append(ISO_LOCAL_DATE) - // .appendLiteral(' ') - // .append(new DateTimeFormatterBuilder() - // .appendValue(HOUR_OF_DAY, 2) - // .appendLiteral(':') - // .appendValue(MINUTE_OF_HOUR, 2) - // .optionalStart() - // .appendLiteral(':') - // .appendValue(SECOND_OF_MINUTE, 2).toFormatter(Locale.CHINA)).toFormatter(Locale.CHINA); - // - // System.out.println(LocalDateTime.now().format(t)); - - - System.out.println("FORMAT Pattern(\"yyyy-MM-dd HH:mm:ss\"):"); - System.out.println("FORMAT_1 Pattern(\"yyyy-MM-dd HH:mm:ss.S\")"); - System.out.println("LocalDateTime.parse(\"2019-07-25 17:15:23.0\", FORMAT_1):" + LocalDateTime.parse("2019-07-25 17:15:23.0", FORMAT_1)); - System.out.println("passMonthsDate(\"2019-07-25 17:15:23\", 3):" + pastMonthsDate("2019-07-25 17:15:23", 3)); - System.out.println("LocalDateTime.parse(\"2019-07-25 17:15:23.0\", FORMAT_1).format(FORMAT):" + LocalDateTime.parse("2019-07-25 17:15:23.0", FORMAT_1).format(FORMAT)); - System.out.println("LocalDate.parse(\"2019-07-25 17:15:23.0\", FORMAT).toString():" + LocalDate.parse("2019-07-25 17:15:23.0", FORMAT_1).toString()); - - - // Set set = ZoneId.getAvailableZoneIds(); - // set.forEach(System.out::println); - - // createTime = "2019-07-25 17:15:23"; - // createTime = createTime.substring(0, 19); - // System.out.println(createTime); - - Date date = new Date(); - System.out.println("当前时间 Date:" + date); - System.out.println("当前时间 Date asLocalDate:" + DateUtil.asLocalDate(date)); - System.out.println("当前时间 Date asLocalDateTime:" + DateUtil.asLocalDateTime(date).format(FORMAT)); - - LocalDateTime localDateTime = DateUtil.currentDateTime(); - System.out.println("当前时间 localDateTime:" + localDateTime); - System.out.println("当前时间 LocalDateTime asDate:" + DateUtil.asDate(localDateTime)); - System.out.println("当前时间 LocalDate asDate:" + DateUtil.asDate(LocalDate.now())); - - System.out.println(ChronoUnit.YEARS.between(LocalDate.now(), LocalDate.parse("1991-08-30", FORMAT_2))); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/utils/ExecShell.java b/src/main/java/io/github/ehlxr/utils/ExecShell.java deleted file mode 100644 index 2ec4c7c..0000000 --- a/src/main/java/io/github/ehlxr/utils/ExecShell.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; - -/** - * Java 执行 shell 命令 - * - * @author ehlxr - * @since 2020/5/6. - */ -public class ExecShell { - private static final Logger log = LoggerFactory.getLogger(ExecShell.class); - - public static void execShellCommand(final String command) { - Process process = null; - DataOutputStream dataOutputStream = null; - try { - process = Runtime.getRuntime().exec("/bin/sh"); - dataOutputStream = new DataOutputStream(process.getOutputStream()); - dataOutputStream.writeBytes(command + "\n"); - dataOutputStream.writeBytes("exit\n"); - dataOutputStream.flush(); - readStdStream(process); - process.waitFor(); - } catch (IOException | InterruptedException | IllegalMonitorStateException e) { - log.error("execShellCommand: {} error", command, e); - - throw new RuntimeException(e); - } finally { - try { - if (dataOutputStream != null) { - dataOutputStream.close(); - } - if (process != null) { - process.destroy(); - } - } catch (IOException e) { - log.error("execShellCommand: {} close stream error", command, e); - } - } - } - - /** - * 读取 Shell 进程标准输出流和错误流 - */ - private static void readStdStream(final Process process) { - String readLine; - BufferedReader stdInput = null; - BufferedReader stdError = null; - try { - // 读取Shell进程标准输出流 - stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); - while ((readLine = stdInput.readLine()) != null) { - log.info("[stdInputStream]: {}", readLine); - } - // 读取Shell进程标准错误流 - stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); - while ((readLine = stdError.readLine()) != null) { - log.error("[stdErrorStream]: {}", readLine); - } - } catch (IOException e) { - log.error("readStdStream error", e); - - throw new RuntimeException(e); - } finally { - try { - if (stdInput != null) { - stdInput.close(); - } - if (stdError != null) { - stdError.close(); - } - } catch (IOException e) { - log.error("readStdStream close stream error", e); - } - } - } - - public static void main(String[] args) { - ExecShell.execShellCommand("pwd"); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/utils/GeoHash.java b/src/main/java/io/github/ehlxr/utils/GeoHash.java deleted file mode 100644 index 60d9c8c..0000000 --- a/src/main/java/io/github/ehlxr/utils/GeoHash.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import java.util.BitSet; -import java.util.HashMap; - - -/** - * GeoHash算法实现 - * - * @author ehlxr - *

- * 1、GeoHash将经纬度转换成一个可以排序,可以比较的字符串编码 - * 2、GeoHash表示的并不是一个点,而是一个矩形区域。比如编码wx4g0ec19,它表示的是一个矩形区域 - */ -public class GeoHash { - private static final int numbits = 6 * 5; - final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; - - final static HashMap lookup = new HashMap(); - - static { - int i = 0; - for (char c : digits) - lookup.put(c, i++); - } - - public static double[] decode(String geohash) { - StringBuilder buffer = new StringBuilder(); - for (char c : geohash.toCharArray()) { - - int i = lookup.get(c) + 32; - buffer.append(Integer.toString(i, 2).substring(1)); - } - - BitSet lonset = new BitSet(); - BitSet latset = new BitSet(); - - // even bits - int j = 0; - for (int i = 0; i < numbits * 2; i += 2) { - boolean isSet = false; - if (i < buffer.length()) - isSet = buffer.charAt(i) == '1'; - lonset.set(j++, isSet); - } - - // odd bits - j = 0; - for (int i = 1; i < numbits * 2; i += 2) { - boolean isSet = false; - if (i < buffer.length()) - isSet = buffer.charAt(i) == '1'; - latset.set(j++, isSet); - } - // 中国地理坐标:东经73°至东经135°,北纬4°至北纬53° -// double lon = decode(lonset, 70, 140); -// double lat = decode(latset, 0, 60); - double lon = decode(lonset, -180, 180); - double lat = decode(latset, -90, 90); - - return new double[] { lat, lon }; - } - - private static double decode(BitSet bs, double floor, double ceiling) { - double mid = 0; - for (int i = 0; i < bs.length(); i++) { - mid = (floor + ceiling) / 2; - if (bs.get(i)) - floor = mid; - else - ceiling = mid; - } - return mid; - } - - public static String encode(double lat, double lon) { -// BitSet latbits = getBits(lat, 0, 60); -// BitSet lonbits = getBits(lon, 70, 140); - BitSet latbits = getBits(lat, -90, 90); - BitSet lonbits = getBits(lon, -180, 180); - StringBuilder buffer = new StringBuilder(); - for (int i = 0; i < numbits; i++) { - buffer.append((lonbits.get(i)) ? '1' : '0'); - buffer.append((latbits.get(i)) ? '1' : '0'); - } - return base32(Long.parseLong(buffer.toString(), 2)); - } - - private static BitSet getBits(double lat, double floor, double ceiling) { - BitSet buffer = new BitSet(numbits); - for (int i = 0; i < numbits; i++) { - double mid = (floor + ceiling) / 2; - if (lat >= mid) { - buffer.set(i); - floor = mid; - } else { - ceiling = mid; - } - } - return buffer; - } - - private static String base32(long i) { - char[] buf = new char[65]; - int charPos = 64; - boolean negative = (i < 0); - if (!negative) - i = -i; - while (i <= -32) { - buf[charPos--] = digits[(int) (-(i % 32))]; - i /= 32; - } - buf[charPos] = digits[(int) (-i)]; - - if (negative) - buf[--charPos] = '-'; - return new String(buf, charPos, (65 - charPos)); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/utils/HttpClientUtil.java b/src/main/java/io/github/ehlxr/utils/HttpClientUtil.java deleted file mode 100644 index 078f9ac..0000000 --- a/src/main/java/io/github/ehlxr/utils/HttpClientUtil.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.NameValuePair; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.cookie.BestMatchSpecFactory; -import org.apache.http.impl.cookie.BrowserCompatSpec; -import org.apache.http.impl.cookie.BrowserCompatSpecFactory; -import org.apache.http.message.BasicNameValuePair; - -import java.io.*; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * @author ehlxr - */ -@SuppressWarnings("deprecation") -public class HttpClientUtil { - private static final int TIME_OUT = 300000; - private static final int BUFFERSIZE = 2048; - private static final Log log = LogFactory.getLog(HttpClientUtil.class); - - private static Registry getRegistry() { - return RegistryBuilder.create().register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory()) - .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()).register("easy", getCookieProvider()).build(); - } - - private static CookieSpecProvider getCookieProvider() { - return arg0 -> { - // TODO Auto-generated method stub - return new BrowserCompatSpec() { - @Override - public void validate(Cookie cookie, CookieOrigin origin) { - // Oh, I am easy - } - }; - }; - } - - public static String sendPostParamDefaultCookie(String url, Map postParam) throws Exception { - String result; - StringBuffer out = null; - CloseableHttpClient httpclient = null; - HttpPost postmethod = null; - RequestConfig requestConfig; - HttpEntity entity; - CloseableHttpResponse response = null; - BasicCookieStore cookieStore; - Registry r; - List nvps; - BufferedReader br = null; - InputStreamReader isr = null; - InputStream inputStream = null; - try { - out = new StringBuffer();// 返回数据 - cookieStore = new BasicCookieStore(); - r = getRegistry(); - postmethod = new HttpPost(url); - requestConfig = RequestConfig.custom().setCookieSpec("easy").setConnectionRequestTimeout(TIME_OUT).setConnectTimeout(TIME_OUT) - .setSocketTimeout(TIME_OUT).build(); - httpclient = HttpClients.custom().setDefaultCookieSpecRegistry(r).setDefaultRequestConfig(requestConfig) - .setDefaultCookieStore(cookieStore).build(); - nvps = new ArrayList<>(); - if (postParam != null && postParam.size() != 0) { - for (String param : postParam.keySet()) { - nvps.add(new BasicNameValuePair(param, postParam.get(param))); - } - } - postmethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); - response = httpclient.execute(postmethod); - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode == HttpStatus.SC_OK) { - entity = response.getEntity(); - inputStream = entity.getContent(); - isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8); - br = new BufferedReader(isr); - int count; - char[] b = new char[BUFFERSIZE]; - while ((count = br.read(b, 0, BUFFERSIZE)) != -1) { - out.append(new String(b, 0, count)); - } - } else { - out.append(SystemConstants.SYSTEM_ERROR); - } - } catch (Exception e) { - out.append(SystemConstants.SYSTEM_ERROR); - } finally { - if (br != null) { - br.close(); - } - if (isr != null) { - isr.close(); - } - if (inputStream != null) { - inputStream.close(); - } - if (response != null) { - response.close(); - } - if (postmethod != null) { - postmethod.releaseConnection(); - } - if (httpclient != null) { - httpclient.close(); - } - result = out.toString(); - out.setLength(0); - out = null; - } - return result; - } - - public static String sendPostParam(String url, Map postParam) throws Exception { - log.debug("请求地址:" + url); - String result = null; - StringBuffer out = null; - CloseableHttpClient httpclient = null; - HttpPost postmethod = null; - RequestConfig requestConfig = null; - HttpEntity entity = null; - CloseableHttpResponse response = null; - List nvps = null; - BufferedReader br = null; - InputStreamReader isr = null; - InputStream inputStream = null; - try { - out = new StringBuffer();// 返回数据 - httpclient = HttpClients.createDefault(); - postmethod = new HttpPost(url); - requestConfig = RequestConfig.custom().setConnectionRequestTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).setSocketTimeout(TIME_OUT) - .build(); - postmethod.setConfig(requestConfig); - nvps = new ArrayList(); - if (postParam != null && postParam.size() != 0) { - for (String param : postParam.keySet()) { - nvps.add(new BasicNameValuePair(param, postParam.get(param))); - } - } - postmethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); - response = httpclient.execute(postmethod); - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode == HttpStatus.SC_OK) { - entity = response.getEntity(); - inputStream = entity.getContent(); - isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8); - br = new BufferedReader(isr); - int count = 0; - char[] b = new char[BUFFERSIZE]; - while ((count = br.read(b, 0, BUFFERSIZE)) != -1) { - out.append(new String(b, 0, count)); - } - } else { - out.append(SystemConstants.SYSTEM_ERROR); - } - } catch (Exception e) { - out.append(SystemConstants.SYSTEM_ERROR); - } finally { - if (br != null) { - br.close(); - } - if (isr != null) { - isr.close(); - } - if (inputStream != null) { - inputStream.close(); - } - if (response != null) { - response.close(); - } - if (postmethod != null) { - postmethod.releaseConnection(); - } - if (httpclient != null) { - httpclient.close(); - } - result = out.toString(); - out.setLength(0); - out = null; - } - return result; - } - - public static String sendPostJSONData(String url, String json) throws Exception { - System.out.println("请求地址:" + url); - String result = null; - StringBuffer out = null; - CloseableHttpClient httpclient = null; - HttpPost postmethod = null; - RequestConfig requestConfig = null; - HttpEntity entity = null; - StringEntity strentity = null; - CloseableHttpResponse response = null; - BufferedReader br = null; - InputStreamReader isr = null; - InputStream inputStream = null; - try { - out = new StringBuffer();// 返回数据 - httpclient = HttpClients.createDefault(); - postmethod = new HttpPost(url); - requestConfig = RequestConfig.custom().setConnectionRequestTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).setSocketTimeout(TIME_OUT) - .build(); - postmethod.setConfig(requestConfig); - strentity = new StringEntity(URLEncoder.encode(json, "UTF-8")); - postmethod.addHeader("Content-Type", "application/json"); - postmethod.setEntity(strentity); - response = httpclient.execute(postmethod); - System.out.println(response); - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode == HttpStatus.SC_OK) { - entity = response.getEntity(); - inputStream = entity.getContent(); - isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8); - br = new BufferedReader(isr); - int count = 0; - char[] b = new char[BUFFERSIZE]; - while ((count = br.read(b, 0, BUFFERSIZE)) != -1) { - out.append(new String(b, 0, count)); - } - } else { - out.append(SystemConstants.SYSTEM_ERROR); - } - } catch (Exception e) { - out.append(SystemConstants.SYSTEM_ERROR); - } finally { - if (br != null) { - br.close(); - } - if (isr != null) { - isr.close(); - } - if (inputStream != null) { - inputStream.close(); - } - if (response != null) { - response.close(); - } - if (postmethod != null) { - postmethod.releaseConnection(); - } - if (httpclient != null) { - httpclient.close(); - } - result = out.toString(); - out.setLength(0); - out = null; - } - return result; - } - - /** - * 向指定URL发送GET方法的请求 - * - * @param url 发送请求的URL - * @return URL 所代表远程资源的响应结果 - */ - public static String sendGet(String url) { - String result = ""; - BufferedReader in = null; - try { - URL realUrl = new URL(url); - // 打开和URL之间的连接 - URLConnection connection = realUrl.openConnection(); - // 设置通用的请求属性 - connection.setRequestProperty("accept", "*/*"); - connection.setRequestProperty("connection", "Keep-Alive"); - connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); - // 建立实际的连接 - connection.connect(); - // 定义 BufferedReader输入流来读取URL的响应 - in = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String line; - while ((line = in.readLine()) != null) { - result += line; - } - } catch (Exception e) { - System.out.println("发送GET请求出现异常!" + e); - e.printStackTrace(); - } - // 使用finally块来关闭输入流 - finally { - try { - if (in != null) { - in.close(); - } - } catch (Exception e2) { - e2.printStackTrace(); - } - } - return result; - } - - /** - * 向指定 URL 发送POST方法的请求 - * - * @param url 发送请求的 URL - * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 - * @return 所代表远程资源的响应结果 - */ - public static String sendPost(String url, String param) { - PrintWriter out = null; - BufferedReader in = null; - String result = ""; - try { - URL realUrl = new URL(url); - // 打开和URL之间的连接 - URLConnection conn = realUrl.openConnection(); - // 设置通用的请求属性 - conn.setRequestProperty("accept", "*/*"); - conn.setRequestProperty("connection", "Keep-Alive"); - conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); - // 发送POST请求必须设置如下两行 - conn.setDoOutput(true); - conn.setDoInput(true); - // 获取URLConnection对象对应的输出流 - out = new PrintWriter(conn.getOutputStream()); - // 发送请求参数 - out.print(param); - // flush输出流的缓冲 - out.flush(); - // 定义BufferedReader输入流来读取URL的响应 - in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - while ((line = in.readLine()) != null) { - result += line; - } - } catch (Exception e) { - System.out.println("发送 POST 请求出现异常!" + e); - e.printStackTrace(); - } - // 使用finally块来关闭输出流、输入流 - finally { - try { - if (out != null) { - out.close(); - } - if (in != null) { - in.close(); - } - } catch (IOException ex) { - ex.printStackTrace(); - } - } - return result; - } -} diff --git a/src/main/java/io/github/ehlxr/utils/MD5.java b/src/main/java/io/github/ehlxr/utils/MD5.java deleted file mode 100644 index 2f9d362..0000000 --- a/src/main/java/io/github/ehlxr/utils/MD5.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import org.apache.commons.codec.digest.DigestUtils; - -import java.io.UnsupportedEncodingException; - -public class MD5 { - - public static String sign(String text, String key) { - return sign(text, key, "UTF-8"); - } - - public static String sign(String text, String key, String input_charset) { - text = text + key; - return DigestUtils.md5Hex(getContentBytes(text, input_charset)); - } - - public static boolean verify(String text, String sign, String key) { - return verify(text, sign, key, "UTF-8"); - } - - public static boolean verify(String text, String sign, String key, String input_charset) { - text = text + key; - String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset)); - return mysign.equals(sign); - } - - private static byte[] getContentBytes(String content, String charset) { - if (charset == null || "".equals(charset)) { - return content.getBytes(); - } - try { - return content.getBytes(charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset); - } - } -} diff --git a/src/main/java/io/github/ehlxr/utils/MyUrlDemo.java b/src/main/java/io/github/ehlxr/utils/MyUrlDemo.java deleted file mode 100644 index d73588a..0000000 --- a/src/main/java/io/github/ehlxr/utils/MyUrlDemo.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import java.io.File; -import java.io.IOException; -import java.net.URL; - -/** - * Created by ehlxr on 2017/3/15. - */ -public class MyUrlDemo { - - - public static void main(String[] args) { - MyUrlDemo muDemo = new MyUrlDemo(); - try { - muDemo.showURL(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public void showURL() throws IOException { - - // 第一种:获取类加载的根路径 D:\git\daotie\daotie\target\classes - File f = new File(this.getClass().getResource("/").getPath()); - System.out.println("第一种:获取类加载的根路径 == " + f); - - // 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录 D:\git\daotie\daotie\target\classes\my - File f2 = new File(this.getClass().getResource("").getPath()); - System.out.println("获取当前类的所在工程路径 == " + f2); - - // 第二种:获取项目路径 D:\git\daotie\daotie - String courseFile = new File("LICENSE").getCanonicalPath(); - System.out.println("第二种:获取项目路径 == " + courseFile); - - - // 第三种: file:/D:/git/daotie/daotie/target/classes/ - URL xmlpath = this.getClass().getClassLoader().getResource(""); - System.out.println("第三种 == " + xmlpath); - - - // 第四种: D:\git\daotie\daotie - System.out.println("第四种 == " + System.getProperty("user.dir")); - /* - * 结果: C:\Documents and Settings\Administrator\workspace\projectName - * 获取当前工程路径 - */ - - // 第五种: 获取所有的类路径 包括jar包的路径 - System.out.println(System.getProperty("java.class.path")); - - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/utils/Pair.java b/src/main/java/io/github/ehlxr/utils/Pair.java deleted file mode 100644 index 9a5d045..0000000 --- a/src/main/java/io/github/ehlxr/utils/Pair.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - - -import java.io.Serializable; - -/** - *

A convenience class to represent name-value pairs.

- * - * @since JavaFX 2.0 (javafx.util.Pair;) - */ -public class Pair implements Serializable { - - /** - * Key of this Pair. - */ - private final K key; - - /** - * Gets the key for this pair. - * - * @return key for this pair - */ - public K getKey() { - return key; - } - - /** - * Value of this this Pair. - */ - private final V value; - - /** - * Gets the value for this pair. - * - * @return value for this pair - */ - public V getValue() { - return value; - } - - /** - * Creates a new pair - * - * @param key The key for this pair - * @param value The value to use for this pair - */ - public Pair(K key, V value) { - this.key = key; - this.value = value; - } - - /** - *

String representation of this - * Pair.

- * - *

The default name/value delimiter '=' is always used.

- * - * @return String representation of this Pair - */ - @Override - public String toString() { - return key + "=" + value; - } - - /** - *

Generate a hash code for this Pair.

- * - *

The hash code is calculated using both the name and - * the value of the Pair.

- * - * @return hash code for this Pair - */ - @Override - public int hashCode() { - // name's hashCode is multiplied by an arbitrary prime number (13) - // in order to make sure there is a difference in the hashCode between - // these two parameters: - // name: a value: aa - // name: aa value: a - return key.hashCode() * 13 + (value == null ? 0 : value.hashCode()); - } - - /** - *

Test this Pair for equality with another - * Object.

- * - *

If the Object to be tested is not a - * Pair or is null, then this method - * returns false.

- * - *

Two Pairs are considered equal if and only if - * both the names and values are equal.

- * - * @param o the Object to test for - * equality with this Pair - * @return true if the given Object is - * equal to this Pair else false - */ - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o instanceof Pair) { - Pair pair = (Pair) o; - if (key != null ? !key.equals(pair.key) : pair.key != null) - return false; - return value != null ? value.equals(pair.value) : pair.value == null; - } - return false; - } -} - diff --git a/src/main/java/io/github/ehlxr/utils/SnowflakeIdUtil.java b/src/main/java/io/github/ehlxr/utils/SnowflakeIdUtil.java deleted file mode 100644 index 89bdd59..0000000 --- a/src/main/java/io/github/ehlxr/utils/SnowflakeIdUtil.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.ForkJoinPool; -import java.util.stream.IntStream; - -/** - * Twitter_Snowflake - *

- * SnowFlake 的结构如下 (每部分用 - 分开): - * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 - * SnowFlake 的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生 id 碰撞 (由数据中心 id 和机器 id 作区分) - * - * @author ehlxr - * @since 2020-12-23 11:26. - */ -public class SnowflakeIdUtil { - /** - * 开始时间截 (2020-12-23) - */ - private final long twepoch = 1608652800000L; - - /** - * 机器 id 所占的位数 - */ - private final long workerIdBits = 5L; - - /** - * 数据标识 id 所占的位数 - */ - private final long datacenterIdBits = 5L; - - /** - * 支持的最大机器 id,结果是 31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) - */ - private final long maxWorkerId = -1L ^ (-1L << workerIdBits); - - /** - * 支持的最大数据标识 id,结果是 31 - */ - private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); - - /** - * 序列在 id 中占的位数 - */ - private final long sequenceBits = 12L; - - /** - * 机器 id 向左移 12 位 - */ - private final long workerIdShift = sequenceBits; - - /** - * 数据标识 id 向左移 17 位 (12+5) - */ - private final long datacenterIdShift = sequenceBits + workerIdBits; - - /** - * 时间截向左移 22 位 (5+5+12) - */ - private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; - - /** - * 生成序列的掩码,这里为 4095 (0b111111111111=0xfff=4095) - */ - private final long sequenceMask = -1L ^ (-1L << sequenceBits); - - /** - * 工作机器 id (0~31) - */ - private final long workerId; - - /** - * 数据中心 id (0~31) - */ - private final long datacenterId; - - /** - * 毫秒内序列 (0~4095) - */ - private long sequence = 0L; - - /** - * 上次生成 id 的时间截 - */ - private long lastTimestamp = -1L; - - /** - * 构造函数 - * - * @param workerId 工作 id (0~31) - * @param datacenterId 数据中心 id (0~31) - */ - private SnowflakeIdUtil(long workerId, long datacenterId) { - if (workerId > maxWorkerId || workerId < 0) { - throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); - } - if (datacenterId > maxDatacenterId || datacenterId < 0) { - throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); - } - this.workerId = workerId; - this.datacenterId = datacenterId; - } - - /** - * 获得下一个 id (该方法是线程安全的) - * - * @return SnowflakeId - */ - private synchronized long nextId() { - long timestamp = System.currentTimeMillis(); - - // 如果当前时间小于上一次 id 生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 - if (timestamp < lastTimestamp) { - throw new RuntimeException( - String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); - } - - // 如果是同一时间生成的,则进行毫秒内序列 - if (lastTimestamp == timestamp) { - sequence = (sequence + 1) & sequenceMask; - // 毫秒内序列溢出 - if (sequence == 0) { - // 阻塞到下一个毫秒,获得新的时间戳 - timestamp = tilNextMillis(lastTimestamp); - } - } else { - // 时间戳改变,毫秒内序列重置 - sequence = 0L; - } - - // 上次生成 id 的时间截 - lastTimestamp = timestamp; - - // 移位并通过或运算拼到一起组成 64 位的 id - return ((timestamp - twepoch) << timestampLeftShift) - | (datacenterId << datacenterIdShift) - | (workerId << workerIdShift) - | sequence; - } - - /** - * 阻塞到下一个毫秒,直到获得新的时间戳 - * - * @param lastTimestamp 上次生成 id 的时间截 - * @return 当前时间戳 - */ - private long tilNextMillis(long lastTimestamp) { - long timestamp = System.currentTimeMillis(); - while (timestamp <= lastTimestamp) { - timestamp = System.currentTimeMillis(); - } - return timestamp; - } - - private static SnowflakeIdUtil snowflakeIdUtil; - - public static void init(long workerId, long datacenterId) { - snowflakeIdUtil = new SnowflakeIdUtil(workerId, datacenterId); - } - - public static long id() { - return snowflakeIdUtil.nextId(); - } - - public static void main(String[] args) { - SnowflakeIdUtil.init(1, 2); - Set ids = new CopyOnWriteArraySet<>(); - - // int threads = 10000; - // int rounds = 1; - // - // CountDownLatch latch = new CountDownLatch(threads * rounds); - // ExecutorService executorService = Executors.newFixedThreadPool(10); - // - // long start = System.currentTimeMillis(); - // for (int i = 0; i < threads; i++) { - // executorService.execute(() -> { - // int j = 0; - // while (j < rounds) { - // long id = SnowflakeIdUtil.id(); - // if (!ids.add(id)) { - // System.out.println(id); - // } - // j++; - // latch.countDown(); - // } - // }); - // } - // - // latch.await(); - // System.out.println("over: qps= " + ((long) threads * rounds * 1000 / (System.currentTimeMillis() - start + 1))); - // - // executorService.shutdown(); - // System.out.println(ids.size()); - - // 并发数 - int count = 4000; - CyclicBarrier cyclicBarrier = new CyclicBarrier(count); - - // ExecutorService pool = Executors.newFixedThreadPool(count); - ForkJoinPool pool = new ForkJoinPool(count); - long now = System.currentTimeMillis(); - - IntStream.range(0, count).forEach(i -> - pool.execute(() -> { - // 等待所有任务准备就绪 - Try.of((Try.ThrowableRunnable) cyclicBarrier::await).trap(System.out::println).run(); - - long id = SnowflakeIdUtil.id(); - if (!ids.add(id)) { - System.out.println(id); - } - })); - - pool.shutdown(); - while (!pool.isTerminated()) { - Try.of(() -> Thread.sleep(10)).trap(System.out::println).run(); - } - long end = System.currentTimeMillis(); - System.out.println(ids.size() + " ids create at " + (end - now) + "ms."); - } -} diff --git a/src/main/java/io/github/ehlxr/utils/StringAlign.java b/src/main/java/io/github/ehlxr/utils/StringAlign.java deleted file mode 100644 index 450c774..0000000 --- a/src/main/java/io/github/ehlxr/utils/StringAlign.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -/** - * Created by ehlxr on 2017/8/17. - * 字符串对齐器。可以指定对齐格式和一行的最大字符数 对齐格式有左对齐、居中、右对齐 - */ -public class StringAlign { - /** - * 左对齐格式 - */ - public static final int JUST_LEFT = 0; - /** - * 居中格式 - */ - public static final int JUST_CENTER = 1; - /** - * 右对齐格式 - */ - public static final int JUST_RIGHT = 2; - - /** - * 当前对齐格式 - */ - private int just; - /** - * 一行的最大长度 - */ - private int maxChars; - - /** - * 默认构造函数 - */ - public StringAlign() { - // 默认为居中对齐 - this.just = JUST_CENTER; - // 默认一行的最大长度为80 - this.maxChars = 80; - } - - /** - * 构造一个字符串对齐器,需要传入一行的最大长度和对齐的格式。 - * - * @param maxChars - * @param just - */ - public StringAlign(int maxChars, int just) { - // 首先构造一个默认字符串对齐器 - this(); - // 根据传入参数修改字符串对齐器的属性 - this.setJust(just); - this.setMaxChars(maxChars); - } - - public static void main(String[] args) { - // 一行最多70个字符,居中显示。 - StringAlign formatter = new StringAlign(20, StringAlign.JUST_CENTER); - // 比如显示页码 - System.out.println(formatter.format("- i -")); - System.out.println(formatter.format(Integer.toString(444))); - System.out.println(formatter.format("kkkkkkkkkkkkkkkkkkkkkkkkkkkk")); - // 左对齐 - System.out.println(); - formatter = new StringAlign(20, StringAlign.JUST_LEFT); - System.out.println(formatter.format("- i -") + "1"); - System.out.println(formatter.format(Integer.toString(444)) + "1"); - System.out.println(formatter.format("kkkkkkkkkkkkkkkkkkkkkkkkkkkk") + "1"); - // 右对齐 - System.out.println(); - formatter = new StringAlign(20, StringAlign.JUST_RIGHT); - System.out.println(formatter.format("- i -")); - System.out.println(formatter.format(Integer.toString(444))); - System.out.println(formatter.format("kkkkkkkkkkkkkkkkkkkkkkkkkkkk")); - } - - /** - * 对齐一个字符串 - * - * @param s 待对齐的字符串 - */ - public String format(String s) { - StringBuffer where = new StringBuffer(); - // 从待对齐的字符串中取出一段子字符串,子串的长度为行最大长度和s长度的较小值 - int wantedLength = Math.min(s.length(), this.maxChars); - String wanted = s.substring(0, wantedLength); - // 根据对齐模式,将空格放在合适的位置 - switch (this.just) { - case JUST_RIGHT: - // 如果是右对齐,那么将缺少的的字符用空格代替放在左边 - pad(where, maxChars - wantedLength); - // 将字符串添加在右边 - where.append(wanted); - break; - case JUST_CENTER: - // 居中对齐,将空格字符平均分在字符串两边。 - int startPos = where.length(); - pad(where, (maxChars - wantedLength) / 2); - where.append(wanted); - pad(where, (maxChars - wantedLength) / 2); - // 调整舍入误差 - pad(where, maxChars - (where.length() - startPos)); - break; - case JUST_LEFT: - // 左对齐,将空格字符放在字符串右边。 - where.append(wanted); - pad(where, maxChars - wantedLength); - break; - } - // 如果原字符串的长度大于一行的最大长度,则将余下部分放入下一行 - if (s.length() > wantedLength) { - String remainStr = s.substring(wantedLength); - where.append("\n").append(this.format(remainStr)); - } - return where.toString(); - } - - /** - * 在to的后面append howMany个空格字符。 - * - * @param to - * @param howMany - */ - protected final void pad(StringBuffer to, int howMany) { - for (int i = 0; i < howMany; i++) - to.append(" "); - } - - public int getJust() { - return just; - } - - /** - * 设置字符串对齐器的对齐格式 - * - * @param just - */ - public void setJust(int just) { - switch (just) { - case JUST_LEFT: - case JUST_CENTER: - case JUST_RIGHT: - this.just = just; - break; - default: - System.out.println("invalid justification arg."); - } - } - - public int getMaxChars() { - return maxChars; - } - - /** - * 设置字符串对齐器的一行最大字符数 - * - * @param maxChars - */ - public void setMaxChars(int maxChars) { - if (maxChars < 0) { - System.out.println("maxChars must be positive."); - } else { - this.maxChars = maxChars; - } - } -} diff --git a/src/main/java/io/github/ehlxr/utils/SystemConstants.java b/src/main/java/io/github/ehlxr/utils/SystemConstants.java deleted file mode 100644 index ea9d5b3..0000000 --- a/src/main/java/io/github/ehlxr/utils/SystemConstants.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.utils; - -public class SystemConstants { - public final static String RES_CODE = "rescode"; - - public final static String RES_DES = "resdes"; - - public final static String SYSTEM_ERROR = "201"; - - public final static String SYSTEM_SUCCESS = "200"; - - public final static String SYSTEM_SUCCESS_HEART = "203"; - - public final static String SYSTEM_ERROR_CANOT_CALL_INSURE = "206"; -} diff --git a/src/main/java/io/github/ehlxr/viplugin/CheckLicenseFile.java b/src/main/java/io/github/ehlxr/viplugin/CheckLicenseFile.java deleted file mode 100644 index a4106b4..0000000 --- a/src/main/java/io/github/ehlxr/viplugin/CheckLicenseFile.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.viplugin; - -import org.apache.commons.codec.binary.Base64; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; - -public class CheckLicenseFile { - private static final String publicKey = "308201b83082012d"; - private static SecretKeySpec key; - private static Cipher cipher; - private static final byte[] linebreak = new byte[0]; - private static Base64 coder; - - static { - try { - key = new SecretKeySpec("308201b83082012d".getBytes(), "AES"); - cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); - coder = new Base64(32, linebreak, true); - } catch (Throwable t) { - t.printStackTrace(); - } - } - - public static boolean checkLicenseLocations(String[] paths) throws Exception { - String path = ""; - boolean found = false; - for (int i = 0; i < paths.length; i++) { - path = paths[i] + "viPlugin2.lic"; - if (new File(path).exists()) { - found = true; - break; - } - path = paths[i] + "viplugin2.lic"; - if (new File(path).exists()) { - found = true; - break; - } - } - if (!found) { - throw new Exception("License should be in one of the following locations:\n" + paths[0] + "\n" + paths[1]); - } - return checkLicenseFile(path); - } - - private static boolean checkLicenseFile(String fileName) throws Exception { - char[] buffer = new char[(int) new File(fileName).length()]; - try { - FileReader fileReader = new FileReader(fileName); - fileReader.read(buffer); - fileReader.close(); - } catch (FileNotFoundException e) { - throw new Exception("License file not found: " + fileName); - } catch (IOException e) { - throw new Exception("Can't read license file: " + fileName); - } - FileReader fileReader; - String license = new String(buffer); - if (!decrypt(license)) { - throw new Exception("Invalid license found: " + fileName); - } - return true; - } - - public static synchronized String encrypt(String name, String email) throws Exception { - String plainText = name + "viPlugin 2.0" + email; - cipher.init(1, key); - byte[] cipherText = cipher.doFinal(plainText.getBytes()); - return new String(coder.encode(cipherText)); - } - - public static synchronized boolean decrypt(String codedText) throws Exception { - byte[] encypted = coder.decode(codedText.getBytes()); - cipher.init(2, key); - byte[] decrypted = cipher.doFinal(encypted); - String decoded = new String(decrypted); - return decoded.contains("viPlugin 2.0"); - } -} \ No newline at end of file diff --git a/src/main/java/io/github/ehlxr/viplugin/CreateLicense.java b/src/main/java/io/github/ehlxr/viplugin/CreateLicense.java deleted file mode 100644 index 262f0fa..0000000 --- a/src/main/java/io/github/ehlxr/viplugin/CreateLicense.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2020 xrv - * - * 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 io.github.ehlxr.viplugin; - -public class CreateLicense { - - @SuppressWarnings("static-access") - public static void main(String[] args) throws Exception { - CheckLicenseFile licenseFile = new CheckLicenseFile(); - String valueString = licenseFile.encrypt("elvin_lee", "elvin_lee@126.com"); - System.out.println("viPlugin2.lic:" + valueString); - } -} \ No newline at end of file diff --git a/src/main/resources/ActiveMQ.xml b/src/main/resources/ActiveMQ.xml deleted file mode 100644 index 735e8f6..0000000 --- a/src/main/resources/ActiveMQ.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml deleted file mode 100644 index dfc592a..0000000 --- a/src/main/resources/application-dev.yml +++ /dev/null @@ -1,7 +0,0 @@ -server: - port: 8081 - -spring: - redis: - host: 127.0.0.1 - port: 6379 \ No newline at end of file diff --git a/src/main/resources/applicationContext.xml b/src/main/resources/applicationContext.xml deleted file mode 100644 index 143da5e..0000000 --- a/src/main/resources/applicationContext.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/generatorConfig.xml b/src/main/resources/generatorConfig.xml deleted file mode 100644 index d16b47b..0000000 --- a/src/main/resources/generatorConfig.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/hbase-site.xml b/src/main/resources/hbase-site.xml deleted file mode 100644 index 1165c71..0000000 --- a/src/main/resources/hbase-site.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - hbase.rootdir - file:///usr/local/var/hbase - - - hbase.zookeeper.property.clientPort - 2181 - - - hbase.zookeeper.property.dataDir - /usr/local/var/zookeeper - - - hbase.zookeeper.dns.interface - lo0 - - - hbase.regionserver.dns.interface - lo0 - - - hbase.master.dns.interface - lo0 - - - diff --git a/src/main/resources/shiro.ini b/src/main/resources/shiro.ini deleted file mode 100644 index 5975506..0000000 --- a/src/main/resources/shiro.ini +++ /dev/null @@ -1,3 +0,0 @@ -[users] -zhang=123 -wang=123 \ No newline at end of file diff --git a/src/main/resources/spring-mvc.xml b/src/main/resources/spring-mvc.xml deleted file mode 100644 index 19d5d35..0000000 --- a/src/main/resources/spring-mvc.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/token_version.properties b/src/main/resources/token_version.properties deleted file mode 100644 index 91e9dc9..0000000 --- a/src/main/resources/token_version.properties +++ /dev/null @@ -1,15 +0,0 @@ -###token生成和校验相关配置 -[tokenVersion<1>]= -###生成token时的密钥 -create_token_key=QJ=*S:y^s0$!@#&*()%xZ~&U8($*_+r? -###自校验时的密钥 -check_token_key=QJs#!@%er!#E#$%^%@@!@=**I()^%? -###取MD5加密后的哪几位做为自校验位,共计4字节,32位。最大数字不能超过16 -check=1,4,6,7 -[tokenVersion<2>]= -###生成token时的密钥 -create_token_key=D#$%^@W#Rj8)@9o%&rgyYL_+!Ldcr5td -###自校验时的密钥 -check_token_key=TL9$_q+Yv^zR):f8)e@P@z&*1@)^o? -###取MD5加密后的哪几位做为自校验位,共计4字节,32位。最大数字不能超过16 -check=8,2,2,5 \ No newline at end of file diff --git a/src/main/resources/tst.json b/src/main/resources/tst.json deleted file mode 100644 index c75c131..0000000 --- a/src/main/resources/tst.json +++ /dev/null @@ -1 +0,0 @@ -{"uid":19184,"ip":"58.213.63.58","resultCode":"0","operation":"/group/findGroups","deviceId":"862983020006783","deviceType":"1","gid":null,"channelId":null,"os":"android SZJY MSM8916 for arm64 5.1.1","appVersion":"Q8611-2137.1-2.1.1.35","appid":"10000","date":"2016-09-01 03:17:13","data":null,"requestParam":{"lastAccessTime":"0"}} \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 080b3d7..0000000 --- a/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp deleted file mode 100644 index 7e7aa76..0000000 --- a/src/main/webapp/index.jsp +++ /dev/null @@ -1,104 +0,0 @@ -<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> -<% - String path = request.getContextPath(); - System.out.println(path); - String basePath = request.getScheme() + "://" - + request.getServerName() + ":" + request.getServerPort() - + path + "/"; - System.out.println(basePath); -%> - - - - - - -ActiveMQ Demo程序 - - - - - - - - - - -

Hello ActiveMQ

-
-

Producer

- -
- - -
- -
- - diff --git a/src/main/webapp/resources/jquery-1.11.0.min.js b/src/main/webapp/resources/jquery-1.11.0.min.js deleted file mode 100644 index 73f33fb..0000000 --- a/src/main/webapp/resources/jquery-1.11.0.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ -!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f -}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML="
a",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/\s*$/g,sb={option:[1,""],legend:[1,"

","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:l.htmlSerialize?[0,"",""]:[1,"X
","
"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?""!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("