file_id
int64 1
66.7k
| content
stringlengths 14
343k
| repo
stringlengths 6
92
| path
stringlengths 5
169
|
---|---|---|---|
894 |
/**
* @author Anonymous
* @since 2019/12/7
*/
public class Solution {
/**
* 求连续子数组的最大和
*
* @param array 数组
* @return 最大和
*/
public int FindGreatestSumOfSubArray(int[] array) {
int n = array.length;
int[] res = new int[n];
res[0] = array[0];
int max = res[0];
for (int i = 1; i < n; ++i) {
res[i] = res[i - 1] > 0 ? res[i - 1] + array[i] : array[i];
max = Math.max(max, res[i]);
}
return max;
}
}
| geekxh/hello-algorithm | 算法读物/剑指offer/42_GreatestSumOfSubarrays/Solution.java |
895 | package test;
import java.util.Date;
import java.util.Properties;
import com.toshiba.mwcloud.gs.Aggregation;
import com.toshiba.mwcloud.gs.AggregationResult;
import com.toshiba.mwcloud.gs.GSException;
import com.toshiba.mwcloud.gs.GridStore;
import com.toshiba.mwcloud.gs.GridStoreFactory;
import com.toshiba.mwcloud.gs.Query;
import com.toshiba.mwcloud.gs.RowKey;
import com.toshiba.mwcloud.gs.RowSet;
import com.toshiba.mwcloud.gs.TimeOperator;
import com.toshiba.mwcloud.gs.TimeSeries;
import com.toshiba.mwcloud.gs.TimestampUtils;
import com.toshiba.mwcloud.gs.TimeUnit;
// 時系列データの検索と集計
public class Sample3 {
static class Point {
@RowKey Date timestamp;
boolean active;
double voltage;
}
public static void main(String[] args) throws GSException {
// 読み取りのみなので、一貫性レベルを緩和(デフォルトはIMMEDIATE)
Properties props = new Properties();
props.setProperty("notificationAddress", args[0]);
props.setProperty("notificationPort", args[1]);
props.setProperty("clusterName", args[2]);
props.setProperty("user", args[3]);
props.setProperty("password", args[4]);
props.setProperty("consistency", "EVENTUAL");
// GridStoreインスタンスの取得
GridStore store = GridStoreFactory.getInstance().getGridStore(props);
// 時系列の取得
// ※Sample2と同じPointクラスを使用
TimeSeries<Point> ts = store.getTimeSeries("point01", Point.class);
// 停止中にもかかわらず電圧が基準値以上の箇所を検索
Query<Point> query = ts.query(
"select * from point01" +
" where not active and voltage > 50");
RowSet<Point> rs = query.fetch();
while (rs.hasNext()) {
// 各異常ポイントについて調査
Point hotPoint = rs.next();
Date hot = hotPoint.timestamp;
// 10分前付近のデータを取得
Date start = TimestampUtils.add(hot, -10, TimeUnit.MINUTE);
Point startPoint = ts.get(start, TimeOperator.NEXT);
// 前後10分間の平均値を計算
Date end = TimestampUtils.add(hot, 10, TimeUnit.MINUTE);
AggregationResult avg = ts.aggregate(
start, end, "voltage", Aggregation.AVERAGE);
System.out.println(
"[Alert] " + TimestampUtils.format(hot) +
" start=" + startPoint.voltage +
" hot=" + hotPoint.voltage +
" avg=" + avg.getDouble());
}
// リソースの解放
store.close();
}
} | griddb/griddb | sample/guide/ja/Sample3.java |
897 | package com.study.sort;
import java.util.Arrays;
/**
* 冒泡,选择,插入,快速,归并
*
* @author ldb
* @date 2019-10-08 16:09
*/
public class Sorts {
/**
* 冒泡排序
*
* @param arr
*/
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
/**
* 优化冒泡排序
*
* @param arr
*/
public static void bubbleSort2(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
boolean flag = true;
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = false;
}
}
if (flag) {
break;
}
}
}
/**
* 插入排序
*
* @param arr
*/
public static void insertSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int val = arr[i];
int index = i - 1;
while (index >= 0 && arr[index] > val) {
arr[index + 1] = arr[index];
index--;
}
arr[index + 1] = val;
}
}
/**
* 插入排序
*
* @param arr
* @param n 表示数组有用大小
*/
public static void insertSort(int[] arr, int n) {
for (int i = 1; i < n; i++) {
int val = arr[i];
int index = i - 1;
while (index >= 0 && arr[index] > val) {
arr[index + 1] = arr[index];
index--;
}
arr[index + 1] = val;
}
}
/**
* 选择排序
*
* @param arr
*/
public static void selectSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
// 交换
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
/**
* 归并排序
*
* @param arr
*/
public static void mergeSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int q = (left + right) / 2;
mergeSort(arr, left, q);
mergeSort(arr, q + 1, right);
merge2(arr, left, q, right);
}
private static void merge2(int[] arr, int left, int q, int right) {
int[] leftArr = new int[q - left + 2];
int[] rightArr = new int[right - q + 1];
for (int i = 0; i <= q - left; i++) {
leftArr[i] = arr[left + i];
}
// 第一个数组添加哨兵(最大值)
leftArr[q - left + 1] = Integer.MAX_VALUE;
for (int i = 0; i < right - q; i++) {
rightArr[i] = arr[q + 1 + i];
}
// 第二个数组添加哨兵(最大值)
rightArr[right - q] = Integer.MAX_VALUE;
int i = 0;
int j = 0;
int k = left;
while (k <= right) {
// 当左边数组到达哨兵值时,i不再增加,直到右边数组读取完剩余值,同理右边数组也一样
if (leftArr[i] <= rightArr[j]) {
arr[k++] = leftArr[i++];
} else {
arr[k++] = rightArr[j++];
}
}
}
private static void merge(int[] arr, int left, int q, int right) {
int i = left;
int j = q + 1;
int k = 0;
int[] tmp = new int[right - left + 1];
while (i <= q && j <= right) {
if (arr[i] <= arr[j]) {
tmp[k++] = arr[i++];
} else {
tmp[k++] = arr[j++];
}
}
int start = i;
int end = q;
if (j <= right) {
start = j;
end = right;
}
while (start <= end) {
tmp[k++] = arr[start++];
}
for (int l = 0; l <= right - left; l++) {
arr[l + left] = tmp[l];
}
}
/**
* 快速排序
*
* @param arr
*/
public static void quickSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int q = partition2(arr, left, right);
quickSort(arr, left, q - 1);
quickSort(arr, q + 1, right);
}
private static int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int i = left;
for (int j = left; j < right; j++) {
if (arr[j] < pivot) {
if (i == j) {
++i;
} else {
int tmp = arr[i];
arr[i++] = arr[j];
arr[j] = tmp;
}
}
}
int tmp = arr[i];
arr[i] = arr[right];
arr[right] = tmp;
return i;
}
private static int partition2(int[] arr, int left, int right) {
// 三数取中法 , 随机数在这里写
int middle = (left + right) / 2;
int pivot = arr[middle];
// 交换到最右边
int val = arr[right];
arr[right] = pivot;
arr[middle] = val;
int i = left;
for (int j = left; j < right; j++) {
if (arr[j] < pivot) {
if (i == j) {
++i;
} else {
int tmp = arr[i];
arr[i++] = arr[j];
arr[j] = tmp;
}
}
}
int tmp = arr[i];
arr[i] = arr[right];
arr[right] = tmp;
return i;
}
/**
* 三向切分快速排序
*
* @param arr
* @param left
* @param right
* @return
*/
private static void quickSort3(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int l = left;
int k = left + 1;
int r = right;
int pivot = arr[l];
while (k <= r) {
if (arr[k] < pivot) {
int tmp = arr[l];
arr[l] = arr[k];
arr[k] = tmp;
l++;
k++;
} else if (arr[k] == pivot) {
k++;
} else {
if (arr[r] > pivot) {
r--;
} else if (arr[r] == pivot) {
int tmp = arr[k];
arr[k] = arr[r];
arr[r] = tmp;
k++;
r--;
} else {
int tmp = arr[l];
arr[l] = arr[r];
arr[r] = arr[k];
arr[k] = tmp;
l++;
k++;
r--;
}
}
}
quickSort(arr, left, l - 1);
quickSort(arr, r + 1, right);
}
/**
* 双轴快速排序
*
* @param arr
* @param left
* @param right
*/
private static void quickSort4(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int l = left;
int k = left + 1;
int r = right;
// 判断pivot1 与 pivot2 大小
if (arr[l] > arr[r]) {
int tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
}
int pivot1 = arr[l];
int pivot2 = arr[r];
while (k < r) {
if (arr[k] < pivot1) {
l++;
if (l != k) {
int tmp = arr[l];
arr[l] = arr[k];
arr[k] = tmp;
}
k++;
} else if (arr[k] >= pivot1 && arr[k] <= pivot2) {
k++;
} else {
--r;
if (arr[r] > pivot2) {
} else if (arr[r] >= pivot1 && arr[r] <= pivot2) {
int tmp = arr[k];
arr[k] = arr[r];
arr[r] = tmp;
k++;
} else {
l++;
int tmp = arr[l];
arr[l] = arr[r];
arr[r] = arr[k];
arr[k] = tmp;
k++;
}
}
}
// 交换pivot1 和 pivot2
arr[left] = arr[l];
arr[l] = pivot1;
arr[right] = arr[r];
arr[r] = pivot2;
quickSort(arr, left, l - 1);
quickSort(arr, l + 1, r - 1);
quickSort(arr, r + 1, right);
}
/**
* O(n) 时间复杂度内求无序数组中的第 K 大元素。比如, 4 , 2 , 5 , 12 , 3 这样一组数据,第 3 大元素就是 4 。
*
* @param arr
*/
public static int sort(int[] arr, int l, int r, int k) {
if (l >= r) {
return 0;
}
int p = partition(arr, l, r);
if ((p + 1) == k) {
return arr[p];
} else if ((p + 1) < k) {
return sort(arr, p + 1, r, k);
} else {
return sort(arr, l, p - 1, k);
}
}
public static void main(String[] args) {
int[] arr = {2, 1, 5, 6, 8, 4, 12, 11, 13, 15, 7, 9, 0, -1};
// bubbleSort(arr);
// bubbleSort2(arr);
// selectSort(arr);
// mergeSort(arr, 0, arr.length - 1);
// quickSort4(arr, 0, arr.length - 1);
Arrays.sort(arr);
print(arr);
}
public static void print(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
}
| wangzheng0822/algo | java/12_sorts/Sorts.java |
898 | package org.jeecg.config;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.constant.CommonConstant;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Author scott
*/
@Configuration
@EnableSwagger2WebMvc
@Import(BeanValidatorPluginsConfiguration.class)
public class Swagger2Config implements WebMvcConfigurer {
/**
*
* 显示swagger-ui.html文档展示页,还必须注入swagger资源:
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
*
* @return Docket
*/
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//此包路径下的类,才生成接口文档
.apis(RequestHandlerSelectors.basePackage("org.jeecg"))
//加了ApiOperation注解的类,才生成接口文档
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.securitySchemes(Collections.singletonList(securityScheme()))
.securityContexts(securityContexts())
.globalOperationParameters(setHeaderToken());
}
/***
* oauth2配置
* 需要增加swagger授权回调地址
* http://localhost:8888/webjars/springfox-swagger-ui/o2c.html
* @return
*/
@Bean
SecurityScheme securityScheme() {
return new ApiKey(CommonConstant.X_ACCESS_TOKEN, CommonConstant.X_ACCESS_TOKEN, "header");
}
/**
* JWT token
* @return
*/
private List<Parameter> setHeaderToken() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name(CommonConstant.X_ACCESS_TOKEN).description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return pars;
}
/**
* api文档的详细信息函数,注意这里的注解引用的是哪个
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// //大标题
.title("JeecgBoot 后台服务API接口文档")
// 版本号
.version("1.0")
// .termsOfServiceUrl("NO terms of service")
// 描述
.description("后台API接口")
// 作者
.contact(new Contact("北京国炬信息技术有限公司","www.jeccg.com","[email protected]"))
.license("The Apache License, Version 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
/**
* 新增 securityContexts 保持登录状态
*/
private List<SecurityContext> securityContexts() {
return new ArrayList(
Collections.singleton(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build())
);
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return new ArrayList(
Collections.singleton(new SecurityReference(CommonConstant.X_ACCESS_TOKEN, authorizationScopes)));
}
/**
* 解决springboot2.6 和springfox不兼容问题
* @return
*/
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
}
| jeecgboot/jeecg-boot | jeecg-boot-base-core/src/main/java/org/jeecg/config/Swagger2Config.java |
899 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.demo.okgo;
import android.os.Bundle;
import android.view.View;
import com.lzy.demo.R;
import com.lzy.demo.base.BaseDetailActivity;
import com.lzy.demo.callback.StringDialogCallback;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class HttpsActivity extends BaseDetailActivity {
private static final String CER_12306 = "-----BEGIN CERTIFICATE-----\n" + //
"MIICmjCCAgOgAwIBAgIIbyZr5/jKH6QwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ04xKTAn\n" + //
"BgNVBAoTIFNpbm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMB4X\n" + //
"DTA5MDUyNTA2NTYwMFoXDTI5MDUyMDA2NTYwMFowRzELMAkGA1UEBhMCQ04xKTAnBgNVBAoTIFNp\n" + //
"bm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMIGfMA0GCSqGSIb3\n" + //
"DQEBAQUAA4GNADCBiQKBgQDMpbNeb34p0GvLkZ6t72/OOba4mX2K/eZRWFfnuk8e5jKDH+9BgCb2\n" + //
"9bSotqPqTbxXWPxIOz8EjyUO3bfR5pQ8ovNTOlks2rS5BdMhoi4sUjCKi5ELiqtyww/XgY5iFqv6\n" + //
"D4Pw9QvOUcdRVSbPWo1DwMmH75It6pk/rARIFHEjWwIDAQABo4GOMIGLMB8GA1UdIwQYMBaAFHle\n" + //
"tne34lKDQ+3HUYhMY4UsAENYMAwGA1UdEwQFMAMBAf8wLgYDVR0fBCcwJTAjoCGgH4YdaHR0cDov\n" + //
"LzE5Mi4xNjguOS4xNDkvY3JsMS5jcmwwCwYDVR0PBAQDAgH+MB0GA1UdDgQWBBR5XrZ3t+JSg0Pt\n" + //
"x1GITGOFLABDWDANBgkqhkiG9w0BAQUFAAOBgQDGrAm2U/of1LbOnG2bnnQtgcVaBXiVJF8LKPaV\n" + //
"23XQ96HU8xfgSZMJS6U00WHAI7zp0q208RSUft9wDq9ee///VOhzR6Tebg9QfyPSohkBrhXQenvQ\n" + //
"og555S+C3eJAAVeNCTeMS3N/M5hzBRJAoffn3qoYdAO1Q8bTguOi+2849A==\n" + //
"-----END CERTIFICATE-----";
@Override
protected void onActivityCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_https);
ButterKnife.bind(this);
setTitle("支持https请求");
}
@Override
protected void onDestroy() {
super.onDestroy();
//Activity销毁时,取消网络请求
OkGo.getInstance().cancelTag(this);
}
@OnClick(R.id.btn_none_https_request)
public void btn_none_https_request(View view) {
//CA 认证的证书不需要任何设置,和http请求一样
OkGo.<String>get("https://github.com/jeasonlzy")//
.tag(this)//
.headers("header1", "headerValue1")//
.params("param1", "paramValue1")//
.execute(new StringDialogCallback(this) {
@Override
public void onError(Response<String> response) {
handleError(response);
}
@Override
public void onSuccess(Response<String> response) {
handleResponse(response);
}
});
}
@OnClick(R.id.btn_https_request)
public void btn_https_request(View view) {
//自签名的证书需要在全局初始化的时候设置,详细看初始化的代码
OkGo.<String>get("https://kyfw.12306.cn/otn")//
.tag(this)//
.headers("Connection", "close") //如果对于部分自签名的https访问不成功,需要加上该控制头
.headers("header1", "headerValue1")//
.params("param1", "paramValue1")//
.execute(new StringDialogCallback(this) {
@Override
public void onError(Response<String> response) {
handleError(response);
}
@Override
public void onSuccess(Response<String> response) {
handleResponse(response);
}
});
}
}
| jeasonlzy/okhttp-OkGo | demo/src/main/java/com/lzy/demo/okgo/HttpsActivity.java |
900 | package sorts;
/**
* Created by wangzheng on 2018/10/16.
*/
public class MergeSort {
// 归并排序算法, a是数组,n表示数组大小
public static void mergeSort(int[] a, int n) {
mergeSortInternally(a, 0, n-1);
}
// 递归调用函数
private static void mergeSortInternally(int[] a, int p, int r) {
// 递归终止条件
if (p >= r) return;
// 取p到r之间的中间位置q,防止(p+r)的和超过int类型最大值
int q = p + (r - p)/2;
// 分治递归
mergeSortInternally(a, p, q);
mergeSortInternally(a, q+1, r);
// 将A[p...q]和A[q+1...r]合并为A[p...r]
merge(a, p, q, r);
}
private static void merge(int[] a, int p, int q, int r) {
int i = p;
int j = q+1;
int k = 0; // 初始化变量i, j, k
int[] tmp = new int[r-p+1]; // 申请一个大小跟a[p...r]一样的临时数组
while (i<=q && j<=r) {
if (a[i] <= a[j]) {
tmp[k++] = a[i++]; // i++等于i:=i+1
} else {
tmp[k++] = a[j++];
}
}
// 判断哪个子数组中有剩余的数据
int start = i;
int end = q;
if (j <= r) {
start = j;
end = r;
}
// 将剩余的数据拷贝到临时数组tmp
while (start <= end) {
tmp[k++] = a[start++];
}
// 将tmp中的数组拷贝回a[p...r]
for (i = 0; i <= r-p; ++i) {
a[p+i] = tmp[i];
}
}
/**
* 合并(哨兵)
*
* @param arr
* @param p
* @param q
* @param r
*/
private static void mergeBySentry(int[] arr, int p, int q, int r) {
int[] leftArr = new int[q - p + 2];
int[] rightArr = new int[r - q + 1];
for (int i = 0; i <= q - p; i++) {
leftArr[i] = arr[p + i];
}
// 第一个数组添加哨兵(最大值)
leftArr[q - p + 1] = Integer.MAX_VALUE;
for (int i = 0; i < r - q; i++) {
rightArr[i] = arr[q + 1 + i];
}
// 第二个数组添加哨兵(最大值)
rightArr[r-q] = Integer.MAX_VALUE;
int i = 0;
int j = 0;
int k = p;
while (k <= r) {
// 当左边数组到达哨兵值时,i不再增加,直到右边数组读取完剩余值,同理右边数组也一样
if (leftArr[i] <= rightArr[j]) {
arr[k++] = leftArr[i++];
} else {
arr[k++] = rightArr[j++];
}
}
}
}
| wangzheng0822/algo | java/12_sorts/MergeSort.java |
901 | package com.taobao.tddl.dbsync.binlog.event;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import com.taobao.tddl.dbsync.binlog.CharsetConversion;
import com.taobao.tddl.dbsync.binlog.LogBuffer;
import com.taobao.tddl.dbsync.binlog.LogEvent;
/**
* A Query_log_event is created for each query that modifies the database,
* unless the query is logged row-based. The Post-Header has five components:
* <table>
* <caption>Post-Header for Query_log_event</caption>
* <tr>
* <th>Name</th>
* <th>Format</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>slave_proxy_id</td>
* <td>4 byte unsigned integer</td>
* <td>An integer identifying the client thread that issued the query. The id is
* unique per server. (Note, however, that two threads on different servers may
* have the same slave_proxy_id.) This is used when a client thread creates a
* temporary table local to the client. The slave_proxy_id is used to
* distinguish temporary tables that belong to different clients.</td>
* </tr>
* <tr>
* <td>exec_time</td>
* <td>4 byte unsigned integer</td>
* <td>The time from when the query started to when it was logged in the binlog,
* in seconds.</td>
* </tr>
* <tr>
* <td>db_len</td>
* <td>1 byte integer</td>
* <td>The length of the name of the currently selected database.</td>
* </tr>
* <tr>
* <td>error_code</td>
* <td>2 byte unsigned integer</td>
* <td>Error code generated by the master. If the master fails, the slave will
* fail with the same error code, except for the error codes ER_DB_CREATE_EXISTS
* == 1007 and ER_DB_DROP_EXISTS == 1008.</td>
* </tr>
* <tr>
* <td>status_vars_len</td>
* <td>2 byte unsigned integer</td>
* <td>The length of the status_vars block of the Body, in bytes. See
* query_log_event_status_vars "below".</td>
* </tr>
* </table>
* The Body has the following components:
* <table>
* <caption>Body for Query_log_event</caption>
* <tr>
* <th>Name</th>
* <th>Format</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>query_log_event_status_vars status_vars</td>
* <td>status_vars_len bytes</td>
* <td>Zero or more status variables. Each status variable consists of one byte
* identifying the variable stored, followed by the value of the variable. The
* possible variables are listed separately in the table
* Table_query_log_event_status_vars "below". MySQL always writes events in the
* order defined below; however, it is capable of reading them in any order.</td>
* </tr>
* <tr>
* <td>db</td>
* <td>db_len+1</td>
* <td>The currently selected database, as a null-terminated string. (The
* trailing zero is redundant since the length is already known; it is db_len
* from Post-Header.)</td>
* </tr>
* <tr>
* <td>query</td>
* <td>variable length string without trailing zero, extending to the end of the
* event (determined by the length field of the Common-Header)</td>
* <td>The SQL query.</td>
* </tr>
* </table>
* The following table lists the status variables that may appear in the
* status_vars field. Table_query_log_event_status_vars
* <table>
* <caption>Status variables for Query_log_event</caption>
* <tr>
* <th>Status variable</th>
* <th>1 byte identifier</th>
* <th>Format</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>flags2</td>
* <td>Q_FLAGS2_CODE == 0</td>
* <td>4 byte bitfield</td>
* <td>The flags in thd->options, binary AND-ed with OPTIONS_WRITTEN_TO_BIN_LOG.
* The thd->options bitfield contains options for "SELECT". OPTIONS_WRITTEN
* identifies those options that need to be written to the binlog (not all do).
* Specifically, OPTIONS_WRITTEN_TO_BIN_LOG equals (OPTION_AUTO_IS_NULL |
* OPTION_NO_FOREIGN_KEY_CHECKS | OPTION_RELAXED_UNIQUE_CHECKS |
* OPTION_NOT_AUTOCOMMIT), or 0x0c084000 in hex. These flags correspond to the
* SQL variables SQL_AUTO_IS_NULL, FOREIGN_KEY_CHECKS, UNIQUE_CHECKS, and
* AUTOCOMMIT, documented in the "SET Syntax" section of the MySQL Manual. This
* field is always written to the binlog in version >= 5.0, and never written in
* version < 5.0.</td>
* </tr>
* <tr>
* <td>sql_mode</td>
* <td>Q_SQL_MODE_CODE == 1</td>
* <td>8 byte bitfield</td>
* <td>The sql_mode variable. See the section "SQL Modes" in the MySQL manual,
* and see mysql_priv.h for a list of the possible flags. Currently
* (2007-10-04), the following flags are available:
*
* <pre>
* MODE_REAL_AS_FLOAT==0x1
* MODE_PIPES_AS_CONCAT==0x2
* MODE_ANSI_QUOTES==0x4
* MODE_IGNORE_SPACE==0x8
* MODE_NOT_USED==0x10
* MODE_ONLY_FULL_GROUP_BY==0x20
* MODE_NO_UNSIGNED_SUBTRACTION==0x40
* MODE_NO_DIR_IN_CREATE==0x80
* MODE_POSTGRESQL==0x100
* MODE_ORACLE==0x200
* MODE_MSSQL==0x400
* MODE_DB2==0x800
* MODE_MAXDB==0x1000
* MODE_NO_KEY_OPTIONS==0x2000
* MODE_NO_TABLE_OPTIONS==0x4000
* MODE_NO_FIELD_OPTIONS==0x8000
* MODE_MYSQL323==0x10000
* MODE_MYSQL323==0x20000
* MODE_MYSQL40==0x40000
* MODE_ANSI==0x80000
* MODE_NO_AUTO_VALUE_ON_ZERO==0x100000
* MODE_NO_BACKSLASH_ESCAPES==0x200000
* MODE_STRICT_TRANS_TABLES==0x400000
* MODE_STRICT_ALL_TABLES==0x800000
* MODE_NO_ZERO_IN_DATE==0x1000000
* MODE_NO_ZERO_DATE==0x2000000
* MODE_INVALID_DATES==0x4000000
* MODE_ERROR_FOR_DIVISION_BY_ZERO==0x8000000
* MODE_TRADITIONAL==0x10000000
* MODE_NO_AUTO_CREATE_USER==0x20000000
* MODE_HIGH_NOT_PRECEDENCE==0x40000000
* MODE_PAD_CHAR_TO_FULL_LENGTH==0x80000000
* </pre>
*
* All these flags are replicated from the server. However, all flags except
* MODE_NO_DIR_IN_CREATE are honored by the slave; the slave always preserves
* its old value of MODE_NO_DIR_IN_CREATE. For a rationale, see comment in
* Query_log_event::do_apply_event in log_event.cc. This field is always written
* to the binlog.</td>
* </tr>
* <tr>
* <td>catalog</td>
* <td>Q_CATALOG_NZ_CODE == 6</td>
* <td>Variable-length string: the length in bytes (1 byte) followed by the
* characters (at most 255 bytes)</td>
* <td>Stores the client's current catalog. Every database belongs to a catalog,
* the same way that every table belongs to a database. Currently, there is only
* one catalog, "std". This field is written if the length of the catalog is >
* 0; otherwise it is not written.</td>
* </tr>
* <tr>
* <td>auto_increment</td>
* <td>Q_AUTO_INCREMENT == 3</td>
* <td>two 2 byte unsigned integers, totally 2+2=4 bytes</td>
* <td>The two variables auto_increment_increment and auto_increment_offset, in
* that order. For more information, see "System variables" in the MySQL manual.
* This field is written if auto_increment > 1. Otherwise, it is not written.</td>
* </tr>
* <tr>
* <td>charset</td>
* <td>Q_CHARSET_CODE == 4</td>
* <td>three 2 byte unsigned integers, totally 2+2+2=6 bytes</td>
* <td>The three variables character_set_client, collation_connection, and
* collation_server, in that order. character_set_client is a code identifying
* the character set and collation used by the client to encode the query.
* collation_connection identifies the character set and collation that the
* master converts the query to when it receives it; this is useful when
* comparing literal strings. collation_server is the default character set and
* collation used when a new database is created. See also
* "Connection Character Sets and Collations" in the MySQL 5.1 manual. All three
* variables are codes identifying a (character set, collation) pair. To see
* which codes map to which pairs, run the query "SELECT id, character_set_name,
* collation_name FROM COLLATIONS". Cf. Q_CHARSET_DATABASE_CODE below. This
* field is always written.</td>
* </tr>
* <tr>
* <td>time_zone</td>
* <td>Q_TIME_ZONE_CODE == 5</td>
* <td>Variable-length string: the length in bytes (1 byte) followed by the
* characters (at most 255 bytes).
* <td>The time_zone of the master. See also "System Variables" and
* "MySQL Server Time Zone Support" in the MySQL manual. This field is written
* if the length of the time zone string is > 0; otherwise, it is not written.</td>
* </tr>
* <tr>
* <td>lc_time_names_number</td>
* <td>Q_LC_TIME_NAMES_CODE == 7</td>
* <td>2 byte integer</td>
* <td>A code identifying a table of month and day names. The mapping from codes
* to languages is defined in sql_locale.cc. This field is written if it is not
* 0, i.e., if the locale is not en_US.</td>
* </tr>
* <tr>
* <td>charset_database_number</td>
* <td>Q_CHARSET_DATABASE_CODE == 8</td>
* <td>2 byte integer</td>
* <td>The value of the collation_database system variable (in the source code
* stored in thd->variables.collation_database), which holds the code for a
* (character set, collation) pair as described above (see Q_CHARSET_CODE).
* collation_database was used in old versions (???WHEN). Its value was loaded
* when issuing a "use db" query and could be changed by issuing a
* "SET collation_database=xxx" query. It used to affect the "LOAD DATA INFILE"
* and "CREATE TABLE" commands. In newer versions, "CREATE TABLE" has been
* changed to take the character set from the database of the created table,
* rather than the character set of the current database. This makes a
* difference when creating a table in another database than the current one.
* "LOAD DATA INFILE" has not yet changed to do this, but there are plans to
* eventually do it, and to make collation_database read-only. This field is
* written if it is not 0.</td>
* </tr>
* <tr>
* <td>table_map_for_update</td>
* <td>Q_TABLE_MAP_FOR_UPDATE_CODE == 9</td>
* <td>8 byte integer</td>
* <td>The value of the table map that is to be updated by the multi-table
* update query statement. Every bit of this variable represents a table, and is
* set to 1 if the corresponding table is to be updated by this statement. The
* value of this variable is set when executing a multi-table update statement
* and used by slave to apply filter rules without opening all the tables on
* slave. This is required because some tables may not exist on slave because of
* the filter rules.</td>
* </tr>
* </table>
* Query_log_event_notes_on_previous_versions Notes on Previous Versions Status
* vars were introduced in version 5.0. To read earlier versions correctly,
* check the length of the Post-Header. The status variable Q_CATALOG_CODE == 2
* existed in MySQL 5.0.x, where 0<=x<=3. It was identical to Q_CATALOG_CODE,
* except that the string had a trailing '\0'. The '\0' was removed in 5.0.4
* since it was redundant (the string length is stored before the string). The
* Q_CATALOG_CODE will never be written by a new master, but can still be
* understood by a new slave. See Q_CHARSET_DATABASE_CODE in the table above.
* When adding new status vars, please don't forget to update the
* MAX_SIZE_LOG_EVENT_STATUS, and update function code_name
*
* @see mysql-5.1.6/sql/logevent.cc - Query_log_event
* @author <a href="mailto:[email protected]">Changyuan.lh</a>
* @version 1.0
*/
public class QueryLogEvent extends LogEvent {
/**
* The maximum number of updated databases that a status of Query-log-event
* can carry. It can redefined within a range [1..
* OVER_MAX_DBS_IN_EVENT_MTS].
*/
public static final int MAX_DBS_IN_EVENT_MTS = 16;
/**
* When the actual number of databases exceeds MAX_DBS_IN_EVENT_MTS the
* value of OVER_MAX_DBS_IN_EVENT_MTS is is put into the mts_accessed_dbs
* status.
*/
public static final int OVER_MAX_DBS_IN_EVENT_MTS = 254;
public static final int SYSTEM_CHARSET_MBMAXLEN = 3;
public static final int NAME_CHAR_LEN = 64;
/* Field/table name length */
public static final int NAME_LEN = (NAME_CHAR_LEN * SYSTEM_CHARSET_MBMAXLEN);
/**
* Max number of possible extra bytes in a replication event compared to a
* packet (i.e. a query) sent from client to master; First, an auxiliary
* log_event status vars estimation:
*/
public static final int MAX_SIZE_LOG_EVENT_STATUS = (1 + 4 /* type, flags2 */
+ 1 + 8 /*
* type,
* sql_mode
*/
+ 1 + 1 + 255/*
* type,
* length
* ,
* catalog
*/
+ 1 + 4 /*
* type,
* auto_increment
*/
+ 1 + 6 /*
* type,
* charset
*/
+ 1 + 1 + 255 /*
* type,
* length
* ,
* time_zone
*/
+ 1 + 2 /*
* type,
* lc_time_names_number
*/
+ 1 + 2 /*
* type,
* charset_database_number
*/
+ 1 + 8 /*
* type,
* table_map_for_update
*/
+ 1 + 4 /*
* type,
* master_data_written
*/
/*
* type, db_1, db_2,
* ...
*/
/* type, microseconds */
/*
* MariaDb type,
* sec_part of NOW()
*/
+ 1 + (MAX_DBS_IN_EVENT_MTS * (1 + NAME_LEN)) + 3 /*
* type
* ,
* microseconds
*/+ 1 + 32
* 3 + 1 + 60/*
* type ,
* user_len
* , user ,
* host_len
* , host
*/)
+ 1 + 1 /*
* type,
* explicit_def
* ..ts
*/+ 1 + 8 /*
* type,
* xid
* of
* DDL
*/+ 1 + 2 /*
* type
* ,
* default_collation_for_utf8mb4_number
*/+ 1 /* sql_require_primary_key */;
/**
* Fixed data part:
* <ul>
* <li>4 bytes. The ID of the thread that issued this statement. Needed for
* temporary tables. This is also useful for a DBA for knowing who did what
* on the master.</li>
* <li>4 bytes. The time in seconds that the statement took to execute. Only
* useful for inspection by the DBA.</li>
* <li>1 byte. The length of the name of the database which was the default
* database when the statement was executed. This name appears later, in the
* variable data part. It is necessary for statements such as INSERT INTO t
* VALUES(1) that don't specify the database and rely on the default
* database previously selected by USE.</li>
* <li>2 bytes. The error code resulting from execution of the statement on
* the master. Error codes are defined in include/mysqld_error.h. 0 means no
* error. How come statements with a non-zero error code can exist in the
* binary log? This is mainly due to the use of non-transactional tables
* within transactions. For example, if an INSERT ... SELECT fails after
* inserting 1000 rows into a MyISAM table (for example, with a
* duplicate-key violation), we have to write this statement to the binary
* log, because it truly modified the MyISAM table. For transactional
* tables, there should be no event with a non-zero error code (though it
* can happen, for example if the connection was interrupted (Control-C)).
* The slave checks the error code: After executing the statement itself, it
* compares the error code it got with the error code in the event, and if
* they are different it stops replicating (unless --slave-skip-errors was
* used to ignore the error).</li>
* <li>2 bytes (not present in v1, v3). The length of the status variable
* block.</li>
* </ul>
* Variable part:
* <ul>
* <li>Zero or more status variables (not present in v1, v3). Each status
* variable consists of one byte code identifying the variable stored,
* followed by the value of the variable. The format of the value is
* variable-specific, as described later.</li>
* <li>The default database name (null-terminated).</li>
* <li>The SQL statement. The slave knows the size of the other fields in
* the variable part (the sizes are given in the fixed data part), so by
* subtraction it can know the size of the statement.</li>
* </ul>
* Source : http://forge.mysql.com/wiki/MySQL_Internals_Binary_Log
*/
private String user;
private String host;
/* using byte for query string */
protected String query;
protected String catalog;
protected final String dbname;
/** The number of seconds the query took to run on the master. */
// The time in seconds that the statement took to execute. Only useful for
// inspection by the DBA
private final long execTime;
private final int errorCode;
private final long sessionId; /* thread_id */
/**
* 'flags2' is a second set of flags (on top of those in Log_event), for
* session variables. These are thd->options which is & against a mask
* (OPTIONS_WRITTEN_TO_BIN_LOG).
*/
private long flags2;
/** In connections sql_mode is 32 bits now but will be 64 bits soon */
private long sql_mode;
private long autoIncrementIncrement = -1;
private long autoIncrementOffset = -1;
private int clientCharset = -1;
private int clientCollation = -1;
private int serverCollation = -1;
private int tvSec = -1;
private BigInteger ddlXid = BigInteger.valueOf(-1L);
private Charset charset;
private String timezone;
private boolean compatiablePercona = false;
public QueryLogEvent(LogHeader header, LogBuffer buffer, FormatDescriptionLogEvent descriptionEvent)
throws IOException{
this(header, buffer, descriptionEvent, false);
}
public QueryLogEvent(LogHeader header, LogBuffer buffer, FormatDescriptionLogEvent descriptionEvent,
boolean compatiablePercona) throws IOException{
this(header, buffer, descriptionEvent, compatiablePercona, false);
}
public QueryLogEvent(LogHeader header, LogBuffer buffer, FormatDescriptionLogEvent descriptionEvent,
boolean compatiablePercona,
boolean compress) throws IOException{
super(header);
this.compatiablePercona = compatiablePercona;
final int commonHeaderLen = descriptionEvent.commonHeaderLen;
final int postHeaderLen = descriptionEvent.postHeaderLen[header.type - 1];
/*
* We test if the event's length is sensible, and if so we compute
* data_len. We cannot rely on QUERY_HEADER_LEN here as it would not be
* format-tolerant. We use QUERY_HEADER_MINIMAL_LEN which is the same
* for 3.23, 4.0 & 5.0.
*/
if (buffer.limit() < (commonHeaderLen + postHeaderLen)) {
throw new IOException("Query event length is too short.");
}
int dataLen = buffer.limit() - (commonHeaderLen + postHeaderLen);
buffer.position(commonHeaderLen + Q_THREAD_ID_OFFSET);
sessionId = buffer.getUint32(); // Q_THREAD_ID_OFFSET
execTime = buffer.getUint32(); // Q_EXEC_TIME_OFFSET
// TODO: add a check of all *_len vars
final int dbLen = buffer.getUint8(); // Q_DB_LEN_OFFSET
errorCode = buffer.getUint16(); // Q_ERR_CODE_OFFSET
/*
* 5.0 format starts here. Depending on the format, we may or not have
* affected/warnings etc The remaining post-header to be parsed has
* length:
*/
int statusVarsLen = 0;
if (postHeaderLen > QUERY_HEADER_MINIMAL_LEN) {
statusVarsLen = buffer.getUint16(); // Q_STATUS_VARS_LEN_OFFSET
/*
* Check if status variable length is corrupt and will lead to very
* wrong data. We could be even more strict and require data_len to
* be even bigger, but this will suffice to catch most corruption
* errors that can lead to a crash.
*/
if (statusVarsLen > Math.min(dataLen, MAX_SIZE_LOG_EVENT_STATUS)) {
throw new IOException("status_vars_len (" + statusVarsLen + ") > data_len (" + dataLen + ")");
}
dataLen -= statusVarsLen;
}
/*
* We have parsed everything we know in the post header for QUERY_EVENT,
* the rest of post header is either comes from older version MySQL or
* dedicated to derived events (e.g. Execute_load_query...)
*/
/* variable-part: the status vars; only in MySQL 5.0 */
final int start = commonHeaderLen + postHeaderLen;
final int limit = buffer.limit(); /* for restore */
final int end = start + statusVarsLen;
buffer.position(start).limit(end);
unpackVariables(buffer, end);
buffer.position(end);
buffer.limit(limit);
/* A 2nd variable part; this is common to all versions */
dbname = buffer.getFixName(dbLen + 1);
int queryLen = dataLen - dbLen - 1;
if (compress) {
// mariadb compress log event
// see https://github.com/alibaba/canal/issues/4388
buffer = buffer.uncompressBuf();
queryLen = buffer.limit();
}
if (clientCharset >= 0) {
charset = CharsetConversion.getNioCharset(clientCharset);
if (charset != null) {
query = buffer.getFixString(queryLen, charset);
} else {
logger.warn("unsupported character set in query log: " + "\n ID = " + clientCharset + ", Charset = "
+ CharsetConversion.getCharset(clientCharset) + ", Collation = "
+ CharsetConversion.getCollation(clientCharset));
query = buffer.getFixString(queryLen);
}
} else {
query = buffer.getFixString(queryLen);
}
}
/* query event post-header */
public static final int Q_THREAD_ID_OFFSET = 0;
public static final int Q_EXEC_TIME_OFFSET = 4;
public static final int Q_DB_LEN_OFFSET = 8;
public static final int Q_ERR_CODE_OFFSET = 9;
public static final int Q_STATUS_VARS_LEN_OFFSET = 11;
public static final int Q_DATA_OFFSET = QUERY_HEADER_LEN;
/* these are codes, not offsets; not more than 256 values (1 byte). */
public static final int Q_FLAGS2_CODE = 0;
public static final int Q_SQL_MODE_CODE = 1;
/**
* Q_CATALOG_CODE is catalog with end zero stored; it is used only by MySQL
* 5.0.x where 0<=x<=3. We have to keep it to be able to replicate these old
* masters.
*/
public static final int Q_CATALOG_CODE = 2;
public static final int Q_AUTO_INCREMENT = 3;
public static final int Q_CHARSET_CODE = 4;
public static final int Q_TIME_ZONE_CODE = 5;
/**
* Q_CATALOG_NZ_CODE is catalog withOUT end zero stored; it is used by MySQL
* 5.0.x where x>=4. Saves one byte in every Query_log_event in binlog,
* compared to Q_CATALOG_CODE. The reason we didn't simply re-use
* Q_CATALOG_CODE is that then a 5.0.3 slave of this 5.0.x (x>=4) master
* would crash (segfault etc) because it would expect a 0 when there is
* none.
*/
public static final int Q_CATALOG_NZ_CODE = 6;
public static final int Q_LC_TIME_NAMES_CODE = 7;
public static final int Q_CHARSET_DATABASE_CODE = 8;
public static final int Q_TABLE_MAP_FOR_UPDATE_CODE = 9;
public static final int Q_MASTER_DATA_WRITTEN_CODE = 10;
public static final int Q_INVOKER = 11;
/**
* Q_UPDATED_DB_NAMES status variable collects of the updated databases
* total number and their names to be propagated to the slave in order to
* facilitate the parallel applying of the Query events.
*/
public static final int Q_UPDATED_DB_NAMES = 12;
public static final int Q_MICROSECONDS = 13;
/**
* A old (unused now) code for Query_log_event status similar to
* G_COMMIT_TS.
*/
public static final int Q_COMMIT_TS = 14;
/**
* A code for Query_log_event status, similar to G_COMMIT_TS2.
*/
public static final int Q_COMMIT_TS2 = 15;
/**
* The master connection @@session.explicit_defaults_for_timestamp which is
* recorded for queries, CREATE and ALTER table that is defined with a
* TIMESTAMP column, that are dependent on that feature. For pre-WL6292
* master's the associated with this code value is zero.
*/
public static final int Q_EXPLICIT_DEFAULTS_FOR_TIMESTAMP = 16;
/**
* The variable carries xid info of 2pc-aware (recoverable) DDL queries.
*/
public static final int Q_DDL_LOGGED_WITH_XID = 17;
/**
* This variable stores the default collation for the utf8mb4 character set.
* Used to support cross-version replication.
*/
public static final int Q_DEFAULT_COLLATION_FOR_UTF8MB4 = 18;
/**
* Replicate sql_require_primary_key.
*/
public static final int Q_SQL_REQUIRE_PRIMARY_KEY = 19;
/**
* Replicate default_table_encryption.
*/
public static final int Q_DEFAULT_TABLE_ENCRYPTION = 20;
/**
* @since percona 8.0.31 Replicate ddl_skip_rewrite.
*/
public static final int Q_DDL_SKIP_REWRITE = 21;
/**
* @since percona 8.0.31 Replicate Q_WSREP_SKIP_READONLY_CHECKS.
*/
public static final int Q_WSREP_SKIP_READONLY_CHECKS = 128;
/**
* FROM MariaDB 5.5.34
*/
public static final int Q_HRNOW = 128;
/**
* Support MariaDB 10.10.1
*/
public static final int Q_XID = 129;
public static final int Q_GTID_FLAGS3 = 130;
public static final int Q_CHARACTER_SET_COLLATIONS = 131;
private final void unpackVariables(LogBuffer buffer, final int end) throws IOException {
int code = -1;
try {
while (buffer.position() < end) {
switch (code = buffer.getUint8()) {
case Q_FLAGS2_CODE:
flags2 = buffer.getUint32();
break;
case Q_SQL_MODE_CODE:
sql_mode = buffer.getLong64(); // QQ: Fix when sql_mode
// is ulonglong
break;
case Q_CATALOG_NZ_CODE:
catalog = buffer.getName();
break;
case Q_AUTO_INCREMENT:
autoIncrementIncrement = buffer.getUint16();
autoIncrementOffset = buffer.getUint16();
break;
case Q_CHARSET_CODE:
// Charset: 6 byte character set flag.
// 1-2 = character set client
// 3-4 = collation client
// 5-6 = collation server
clientCharset = buffer.getUint16();
clientCollation = buffer.getUint16();
serverCollation = buffer.getUint16();
break;
case Q_TIME_ZONE_CODE:
timezone = buffer.getName();
break;
case Q_CATALOG_CODE: /* for 5.0.x where 0<=x<=3 masters */
final int len = buffer.getUint8();
catalog = buffer.getFixString(len + 1);
break;
case Q_LC_TIME_NAMES_CODE:
// lc_time_names_number = buffer.getUint16();
buffer.forward(2);
break;
case Q_CHARSET_DATABASE_CODE:
// charset_database_number = buffer.getUint16();
buffer.forward(2);
break;
case Q_TABLE_MAP_FOR_UPDATE_CODE:
// table_map_for_update = buffer.getUlong64();
buffer.forward(8);
break;
case Q_MASTER_DATA_WRITTEN_CODE:
// data_written = master_data_written =
// buffer.getUint32();
buffer.forward(4);
break;
case Q_INVOKER:
user = buffer.getName();
host = buffer.getName();
break;
case Q_MICROSECONDS:
// when.tv_usec= uint3korr(pos);
tvSec = buffer.getInt24();
break;
case Q_UPDATED_DB_NAMES:
int mtsAccessedDbs = buffer.getUint8();
/**
* Notice, the following check is positive also in case
* of the master's MAX_DBS_IN_EVENT_MTS > the slave's
* one and the event contains e.g the master's
* MAX_DBS_IN_EVENT_MTS db:s.
*/
if (mtsAccessedDbs > MAX_DBS_IN_EVENT_MTS) {
mtsAccessedDbs = OVER_MAX_DBS_IN_EVENT_MTS;
break;
}
String mtsAccessedDbNames[] = new String[mtsAccessedDbs];
for (int i = 0; i < mtsAccessedDbs && buffer.position() < end; i++) {
int length = end - buffer.position();
mtsAccessedDbNames[i] = buffer.getFixName(length < NAME_LEN ? length : NAME_LEN);
}
break;
case Q_EXPLICIT_DEFAULTS_FOR_TIMESTAMP:
// thd->variables.explicit_defaults_for_timestamp
buffer.forward(1);
break;
case Q_DDL_LOGGED_WITH_XID:
ddlXid = buffer.getUlong64();
break;
case Q_DEFAULT_COLLATION_FOR_UTF8MB4:
// int2store(start,
// default_collation_for_utf8mb4_number);
buffer.forward(2);
break;
case Q_SQL_REQUIRE_PRIMARY_KEY:
// *start++ = thd->variables.sql_require_primary_key;
buffer.forward(1);
break;
case Q_DEFAULT_TABLE_ENCRYPTION:
// *start++ = thd->variables.default_table_encryption;
buffer.forward(1);
case Q_DDL_SKIP_REWRITE:
// *start++ = thd->variables.binlog_ddl_skip_rewrite;
buffer.forward(1);
case Q_HRNOW:
// https://github.com/alibaba/canal/issues/4940
// percona 和 mariadb各自扩展mysql binlog的格式后有冲突
// 需要精确识别一下数据库类型做兼容处理
if (compatiablePercona) {
// percona 8.0.31
// Q_WSREP_SKIP_READONLY_CHECKS *start++ = 1;
buffer.forward(1);
} else {
// int when_sec_part = buffer.getUint24();
buffer.forward(3);
}
break;
case Q_XID:
// xid= uint8korr(pos);
buffer.forward(8);
break;
case Q_GTID_FLAGS3:
// gtid_flags_extra= *pos++;
// if (gtid_flags_extra & (Gtid_log_event::FL_COMMIT_ALTER_E1 |
// Gtid_log_event::FL_ROLLBACK_ALTER_E1)) {
// sa_seq_no = uint8korr(pos);
// pos+= 8;
// }
int gtid_flags_extra = buffer.getUint8();
final int FL_COMMIT_ALTER_E1= 4;
final int FL_ROLLBACK_ALTER_E1= 8;
if ((gtid_flags_extra & (FL_COMMIT_ALTER_E1 | FL_ROLLBACK_ALTER_E1))> 0) {
buffer.forward(8);
}
break;
case Q_CHARACTER_SET_COLLATIONS :
// mariadb
int count = buffer.getUint8();
// character_set_collations= Lex_cstring((const char *) pos0 , (const char *) pos);
buffer.forward(count * 4);
default:
/*
* That's why you must write status vars in growing
* order of code
*/
logger.error("Query_log_event has unknown status vars (first has code: " + code
+ "), skipping the rest of them");
break; // Break loop
}
}
} catch (RuntimeException e) {
throw new IOException("Read " + findCodeName(code) + " error: " + e.getMessage(), e);
}
}
private static final String findCodeName(final int code) {
switch (code) {
case Q_FLAGS2_CODE:
return "Q_FLAGS2_CODE";
case Q_SQL_MODE_CODE:
return "Q_SQL_MODE_CODE";
case Q_CATALOG_CODE:
return "Q_CATALOG_CODE";
case Q_AUTO_INCREMENT:
return "Q_AUTO_INCREMENT";
case Q_CHARSET_CODE:
return "Q_CHARSET_CODE";
case Q_TIME_ZONE_CODE:
return "Q_TIME_ZONE_CODE";
case Q_CATALOG_NZ_CODE:
return "Q_CATALOG_NZ_CODE";
case Q_LC_TIME_NAMES_CODE:
return "Q_LC_TIME_NAMES_CODE";
case Q_CHARSET_DATABASE_CODE:
return "Q_CHARSET_DATABASE_CODE";
case Q_TABLE_MAP_FOR_UPDATE_CODE:
return "Q_TABLE_MAP_FOR_UPDATE_CODE";
case Q_MASTER_DATA_WRITTEN_CODE:
return "Q_MASTER_DATA_WRITTEN_CODE";
case Q_INVOKER:
return "case Q_INVOKER";
case Q_MICROSECONDS:
return "Q_MICROSECONDS";
case Q_UPDATED_DB_NAMES:
return "Q_UPDATED_DB_NAMES";
case Q_EXPLICIT_DEFAULTS_FOR_TIMESTAMP:
return "Q_EXPLICIT_DEFAULTS_FOR_TIMESTAMP";
case Q_DDL_LOGGED_WITH_XID:
return "Q_DDL_LOGGED_WITH_XID";
case Q_DEFAULT_COLLATION_FOR_UTF8MB4:
return "Q_DEFAULT_COLLATION_FOR_UTF8MB4";
case Q_SQL_REQUIRE_PRIMARY_KEY:
return "Q_SQL_REQUIRE_PRIMARY_KEY";
case Q_DEFAULT_TABLE_ENCRYPTION:
return "Q_DEFAULT_TABLE_ENCRYPTION";
case Q_DDL_SKIP_REWRITE:
return "Q_DDL_SKIP_REWRITE";
case Q_HRNOW:
return "Q_HRNOW";
case Q_XID:
return "Q_XID";
case Q_GTID_FLAGS3:
return "Q_GTID_FLAGS3";
case Q_CHARACTER_SET_COLLATIONS :
return "Q_CHARACTER_SET_COLLATIONS";
}
return "CODE#" + code;
}
public final String getUser() {
return user;
}
public final String getHost() {
return host;
}
public final String getQuery() {
return query;
}
public final String getCatalog() {
return catalog;
}
public final String getDbName() {
return dbname;
}
/**
* The number of seconds the query took to run on the master.
*/
public final long getExecTime() {
return execTime;
}
public final int getErrorCode() {
return errorCode;
}
public final long getSessionId() {
return sessionId;
}
public final long getAutoIncrementIncrement() {
return autoIncrementIncrement;
}
public final long getAutoIncrementOffset() {
return autoIncrementOffset;
}
public final Charset getCharset() {
return charset;
}
public final String getTimezone() {
return timezone;
}
/**
* Returns the charsetID value.
*
* @return Returns the charsetID.
*/
public final int getClientCharset() {
return clientCharset;
}
/**
* Returns the clientCollationId value.
*
* @return Returns the clientCollationId.
*/
public final int getClientCollation() {
return clientCollation;
}
/**
* Returns the serverCollationId value.
*
* @return Returns the serverCollationId.
*/
public final int getServerCollation() {
return serverCollation;
}
public int getTvSec() {
return tvSec;
}
public BigInteger getDdlXid() {
return ddlXid;
}
/**
* Returns the sql_mode value.
* <p>
* The sql_mode variable. See the section "SQL Modes" in the MySQL manual,
* and see mysql_priv.h for a list of the possible flags. Currently
* (2007-10-04), the following flags are available:
* <ul>
* <li>MODE_REAL_AS_FLOAT==0x1</li>
* <li>MODE_PIPES_AS_CONCAT==0x2</li>
* <li>MODE_ANSI_QUOTES==0x4</li>
* <li>MODE_IGNORE_SPACE==0x8</li>
* <li>MODE_NOT_USED==0x10</li>
* <li>MODE_ONLY_FULL_GROUP_BY==0x20</li>
* <li>MODE_NO_UNSIGNED_SUBTRACTION==0x40</li>
* <li>MODE_NO_DIR_IN_CREATE==0x80</li>
* <li>MODE_POSTGRESQL==0x100</li>
* <li>MODE_ORACLE==0x200</li>
* <li>MODE_MSSQL==0x400</li>
* <li>MODE_DB2==0x800</li>
* <li>MODE_MAXDB==0x1000</li>
* <li>MODE_NO_KEY_OPTIONS==0x2000</li>
* <li>MODE_NO_TABLE_OPTIONS==0x4000</li>
* <li>MODE_NO_FIELD_OPTIONS==0x8000</li>
* <li>MODE_MYSQL323==0x10000</li>
* <li>MODE_MYSQL40==0x20000</li>
* <li>MODE_ANSI==0x40000</li>
* <li>MODE_NO_AUTO_VALUE_ON_ZERO==0x80000</li>
* <li>MODE_NO_BACKSLASH_ESCAPES==0x100000</li>
* <li>MODE_STRICT_TRANS_TABLES==0x200000</li>
* <li>MODE_STRICT_ALL_TABLES==0x400000</li>
* <li>MODE_NO_ZERO_IN_DATE==0x800000</li>
* <li>MODE_NO_ZERO_DATE==0x1000000</li>
* <li>MODE_INVALID_DATES==0x2000000</li>
* <li>MODE_ERROR_FOR_DIVISION_BY_ZERO==0x4000000</li>
* <li>MODE_TRADITIONAL==0x8000000</li>
* <li>MODE_NO_AUTO_CREATE_USER==0x10000000</li>
* <li>MODE_HIGH_NOT_PRECEDENCE==0x20000000</li>
* <li>MODE_NO_ENGINE_SUBSTITUTION=0x40000000</li>
* <li>MODE_PAD_CHAR_TO_FULL_LENGTH==0x80000000</li>
* </ul>
* All these flags are replicated from the server. However, all flags except
* MODE_NO_DIR_IN_CREATE are honored by the slave; the slave always
* preserves its old value of MODE_NO_DIR_IN_CREATE. This field is always
* written to the binlog.
*/
public final long getSqlMode() {
return sql_mode;
}
/* FLAGS2 values that can be represented inside the binlog */
public static final int OPTION_AUTO_IS_NULL = 1 << 14;
public static final int OPTION_NOT_AUTOCOMMIT = 1 << 19;
public static final int OPTION_NO_FOREIGN_KEY_CHECKS = 1 << 26;
public static final int OPTION_RELAXED_UNIQUE_CHECKS = 1 << 27;
/**
* The flags in thd->options, binary AND-ed with OPTIONS_WRITTEN_TO_BIN_LOG.
* The thd->options bitfield contains options for "SELECT". OPTIONS_WRITTEN
* identifies those options that need to be written to the binlog (not all
* do). Specifically, OPTIONS_WRITTEN_TO_BIN_LOG equals (OPTION_AUTO_IS_NULL
* | OPTION_NO_FOREIGN_KEY_CHECKS | OPTION_RELAXED_UNIQUE_CHECKS |
* OPTION_NOT_AUTOCOMMIT), or 0x0c084000 in hex. These flags correspond to
* the SQL variables SQL_AUTO_IS_NULL, FOREIGN_KEY_CHECKS, UNIQUE_CHECKS,
* and AUTOCOMMIT, documented in the "SET Syntax" section of the MySQL
* Manual. This field is always written to the binlog in version >= 5.0, and
* never written in version < 5.0.
*/
public final long getFlags2() {
return flags2;
}
/**
* Returns the OPTION_AUTO_IS_NULL flag.
*/
public final boolean isAutoIsNull() {
return ((flags2 & OPTION_AUTO_IS_NULL) == OPTION_AUTO_IS_NULL);
}
/**
* Returns the OPTION_NO_FOREIGN_KEY_CHECKS flag.
*/
public final boolean isForeignKeyChecks() {
return ((flags2 & OPTION_NO_FOREIGN_KEY_CHECKS) != OPTION_NO_FOREIGN_KEY_CHECKS);
}
/**
* Returns the OPTION_NOT_AUTOCOMMIT flag.
*/
public final boolean isAutocommit() {
return ((flags2 & OPTION_NOT_AUTOCOMMIT) != OPTION_NOT_AUTOCOMMIT);
}
/**
* Returns the OPTION_NO_FOREIGN_KEY_CHECKS flag.
*/
public final boolean isUniqueChecks() {
return ((flags2 & OPTION_RELAXED_UNIQUE_CHECKS) != OPTION_RELAXED_UNIQUE_CHECKS);
}
}
| alibaba/canal | dbsync/src/main/java/com/taobao/tddl/dbsync/binlog/event/QueryLogEvent.java |
902 | /**
* 堆排序
*/
public class HeapSort {
/**
* 排序
* <p>
* 堆元素是从数组下标0开始
*
* @param arr
*/
public static void sort(int[] arr) {
if (arr.length <= 1) {
return;
}
// 1、建堆
buildHeap(arr);
// 2、排序
int k = arr.length - 1;
while (k > 0) {
// 将堆顶元素(最大)与最后一个元素交换位置
swap(arr, 0, k);
// 将剩下元素重新堆化,堆顶元素变成最大元素
heapify(arr, --k, 0);
}
}
/**
* 建堆
*
* @param arr
*/
private static void buildHeap(int[] arr) {
// (arr.length - 1) / 2 为最后一个叶子节点的父节点
// 也就是最后一个非叶子节点,依次堆化直到根节点
for (int i = (arr.length - 1) / 2; i >= 0; i--) {
heapify(arr, arr.length - 1, i);
}
}
/**
* 堆化
*
* @param arr 要堆化的数组
* @param n 最后堆元素下标
* @param i 要堆化的元素下标
*/
private static void heapify(int[] arr, int n, int i) {
while (true) {
// 最大值位置
int maxPos = i;
// 与左子节点(i * 2 + 1)比较,获取最大值位置
if (i * 2 + 1 <= n && arr[i] < arr[i * 2 + 1]) {
maxPos = i * 2 + 1;
}
// 最大值与右子节点(i * 2 + 2)比较,获取最大值位置
if (i * 2 + 2 <= n && arr[maxPos] < arr[i * 2 + 2]) {
maxPos = i * 2 + 2;
}
// 最大值是当前位置结束循环
if (maxPos == i) {
break;
}
// 与子节点交换位置
swap(arr, i, maxPos);
// 以交换后子节点位置接着往下查找
i = maxPos;
}
}
} | wangzheng0822/algo | java/28_sorts/HeapSort.java |
903 | /**
* File: bucket_sort.java
* Created Time: 2023-03-17
* Author: krahets ([email protected])
*/
package chapter_sorting;
import java.util.*;
public class bucket_sort {
/* 桶排序 */
static void bucketSort(float[] nums) {
// 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素
int k = nums.length / 2;
List<List<Float>> buckets = new ArrayList<>();
for (int i = 0; i < k; i++) {
buckets.add(new ArrayList<>());
}
// 1. 将数组元素分配到各个桶中
for (float num : nums) {
// 输入数据范围为 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
int i = (int) (num * k);
// 将 num 添加进桶 i
buckets.get(i).add(num);
}
// 2. 对各个桶执行排序
for (List<Float> bucket : buckets) {
// 使用内置排序函数,也可以替换成其他排序算法
Collections.sort(bucket);
}
// 3. 遍历桶合并结果
int i = 0;
for (List<Float> bucket : buckets) {
for (float num : bucket) {
nums[i++] = num;
}
}
}
public static void main(String[] args) {
// 设输入数据为浮点数,范围为 [0, 1)
float[] nums = { 0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f };
bucketSort(nums);
System.out.println("桶排序完成后 nums = " + Arrays.toString(nums));
}
}
| krahets/hello-algo | codes/java/chapter_sorting/bucket_sort.java |
904 | /*
* Copyright (C) 2017 hutool.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hutool;
import cn.hutool.core.lang.ConsoleTable;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import java.util.Set;
/**
* <p>
* 秋千水,竹马道,一眼见你,万物不及。<br>
* 春水生,春林初胜,春风十里不如你。
* </p>
*
* <p>
* Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。
* </p>
*
* <p>
* Hutool中的工具方法来自于每个用户的精雕细琢,它涵盖了Java开发底层代码中的方方面面,它既是大型项目开发中解决小问题的利器,也是小型项目中的效率担当;<br>
* </p>
*
* <p>Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的bug。</p>
*
* @author Looly
*/
public class Hutool {
public static final String AUTHOR = "Looly";
private Hutool() {
}
/**
* 显示Hutool所有的工具类
*
* @return 工具类名集合
* @since 5.5.2
*/
public static Set<Class<?>> getAllUtils() {
return ClassUtil.scanPackage("cn.hutool",
(clazz) -> (false == clazz.isInterface()) && StrUtil.endWith(clazz.getSimpleName(), "Util"));
}
/**
* 控制台打印所有工具类
*/
public static void printAllUtils() {
final Set<Class<?>> allUtils = getAllUtils();
final ConsoleTable consoleTable = ConsoleTable.create().addHeader("工具类名", "所在包");
for (Class<?> clazz : allUtils) {
consoleTable.addBody(clazz.getSimpleName(), clazz.getPackage().getName());
}
consoleTable.print();
}
}
| dromara/hutool | hutool-all/src/main/java/cn/hutool/Hutool.java |
910 | package com.xkcoding.websocket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
/**
* <p>
* WebSocket配置
* </p>
*
* @author yangkai.shen
* @date Created in 2018-12-14 15:58
*/
@Configuration
@EnableWebSocket
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// 注册一个 /notification 端点,前端通过这个端点进行连接
registry.addEndpoint("/notification")
//解决跨域问题
.setAllowedOrigins("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//定义了一个客户端订阅地址的前缀信息,也就是客户端接收服务端发送消息的前缀信息
registry.enableSimpleBroker("/topic");
}
}
| xkcoding/spring-boot-demo | demo-websocket/src/main/java/com/xkcoding/websocket/config/WebSocketConfig.java |
911 | package io.mycat.manager.response;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import io.mycat.MycatServer;
import io.mycat.backend.mysql.PacketUtil;
import io.mycat.config.Fields;
import io.mycat.config.model.SystemConfig;
import io.mycat.manager.ManagerConnection;
import io.mycat.net.mysql.EOFPacket;
import io.mycat.net.mysql.FieldPacket;
import io.mycat.net.mysql.ResultSetHeaderPacket;
import io.mycat.net.mysql.RowDataPacket;
import io.mycat.util.StringUtil;
/**
* show Sysconfig param detail info
*
* @author rainbow
*
*/
public class ShowSysParam {
private static final int FIELD_COUNT = 3;
private static final ResultSetHeaderPacket header = PacketUtil
.getHeader(FIELD_COUNT);
private static final FieldPacket[] fields = new FieldPacket[FIELD_COUNT];
private static final EOFPacket eof = new EOFPacket();
static {
int i = 0;
byte packetId = 0;
header.packetId = ++packetId;
fields[i] = PacketUtil.getField("PARAM_NAME", Fields.FIELD_TYPE_VARCHAR);
fields[i++].packetId = ++packetId;
fields[i] = PacketUtil.getField("PARAM_VALUE", Fields.FIELD_TYPE_VARCHAR);
fields[i++].packetId = ++packetId;
fields[i] = PacketUtil.getField("PARAM_DESCR", Fields.FIELD_TYPE_VARCHAR);
fields[i++].packetId = ++packetId;
eof.packetId = ++packetId;
}
public static void execute(ManagerConnection c) {
ByteBuffer buffer = c.allocate();
// write header
buffer = header.write(buffer, c, true);
// write fields
for (FieldPacket field : fields) {
buffer = field.write(buffer, c, true);
}
// write eof
buffer = eof.write(buffer, c, true);
// write rows
byte packetId = eof.packetId;
SystemConfig sysConfig = MycatServer.getInstance().getConfig().getSystem();
List<String> paramValues = new ArrayList<String>();
paramValues.add(sysConfig.getProcessors() + "");
paramValues.add(sysConfig.getBufferPoolChunkSize() + "B");
paramValues.add(sysConfig.getBufferPoolPageSize() + "B");
paramValues.add(sysConfig.getProcessorBufferLocalPercent() + "");
paramValues.add(sysConfig.getProcessorExecutor() + "");
paramValues.add(sysConfig.getSequenceHandlerType() == 1 ? "数据库方式" : "本地文件方式");
paramValues.add(sysConfig.getPacketHeaderSize() + "B");
paramValues.add(sysConfig.getMaxPacketSize()/1024/1024 + "M");
paramValues.add(sysConfig.getIdleTimeout()/1000/60 + "分钟");
paramValues.add(sysConfig.getCharset() + "");
paramValues.add(ISOLATIONS[sysConfig.getTxIsolation()]);
paramValues.add(sysConfig.getSqlExecuteTimeout() + "秒");
paramValues.add(sysConfig.getProcessorCheckPeriod()/1000 + "秒");
paramValues.add(sysConfig.getDataNodeIdleCheckPeriod()/1000 + "秒");
paramValues.add(sysConfig.getDataNodeHeartbeatPeriod()/1000 + "秒");
paramValues.add(sysConfig.getBindIp() + "");
paramValues.add(sysConfig.getServerPort()+ "");
paramValues.add(sysConfig.getManagerPort() + "");
paramValues.add(sysConfig.getUseSqlStat() + "");
for(int i = 0; i < PARAMNAMES.length ; i++){
RowDataPacket row = new RowDataPacket(FIELD_COUNT);
row.add(StringUtil.encode(PARAMNAMES[i], c.getCharset()));
row.add(StringUtil.encode(paramValues.get(i), c.getCharset()));
row.add(StringUtil.encode(PARAM_DESCRIPTION[i], c.getCharset()));
row.packetId = ++packetId;
buffer = row.write(buffer, c,true);
}
// write last eof
EOFPacket lastEof = new EOFPacket();
lastEof.packetId = ++packetId;
buffer = lastEof.write(buffer, c, true);
// write buffer
c.write(buffer);
}
private static final String[] PARAMNAMES = {
"processors",
"processorBufferChunk",
"processorBufferPool",
"processorBufferLocalPercent",
"processorExecutor",
"sequnceHandlerType",
"Mysql_packetHeaderSize",
"Mysql_maxPacketSize",
"Mysql_idleTimeout",
"Mysql_charset",
"Mysql_txIsolation",
"Mysql_sqlExecuteTimeout",
"Mycat_processorCheckPeriod",
"Mycat_dataNodeIdleCheckPeriod",
"Mycat_dataNodeHeartbeatPeriod",
"Mycat_bindIp",
"Mycat_serverPort",
"Mycat_managerPort",
"Mycat_useSqlStat"};
private static final String[] PARAM_DESCRIPTION = {
"主要用于指定系统可用的线程数,默认值为Runtime.getRuntime().availableProcessors()方法返回的值。主要影响processorBufferPool、processorBufferLocalPercent、processorExecutor属性。NIOProcessor的个数也是由这个属性定义的,所以调优的时候可以适当的调高这个属性。",
"指定每次分配Socket Direct Buffer的大小,默认是4096个字节。这个属性也影响buffer pool的长度。",
"指定bufferPool计算 比例值。由于每次执行NIO读、写操作都需要使用到buffer,系统初始化的时候会建立一定长度的buffer池来加快读、写的效率,减少建立buffer的时间",
"就是用来控制分配这个pool的大小用的,但其也并不是一个准确的值,也是一个比例值。这个属性默认值为100。线程缓存百分比 = bufferLocalPercent / processors属性。",
"主要用于指定NIOProcessor上共享的businessExecutor固定线程池大小。mycat在需要处理一些异步逻辑的时候会把任务提交到这个线程池中。新版本中这个连接池的使用频率不是很大了,可以设置一个较小的值。",
"指定使用Mycat全局序列的类型。",
"指定Mysql协议中的报文头长度。默认4",
"指定Mysql协议可以携带的数据最大长度。默认16M",
"指定连接的空闲超时时间。某连接在发起空闲检查下,发现距离上次使用超过了空闲时间,那么这个连接会被回收,就是被直接的关闭掉。默认30分钟",
"连接的初始化字符集。默认为utf8",
"前端连接的初始化事务隔离级别,只在初始化的时候使用,后续会根据客户端传递过来的属性对后端数据库连接进行同步。默认为REPEATED_READ",
"SQL执行超时的时间,Mycat会检查连接上最后一次执行SQL的时间,若超过这个时间则会直接关闭这连接。默认时间为300秒",
"清理NIOProcessor上前后端空闲、超时和关闭连接的间隔时间。默认是1秒",
"对后端连接进行空闲、超时检查的时间间隔,默认是300秒",
"对后端所有读、写库发起心跳的间隔时间,默认是10秒",
"mycat服务监听的IP地址,默认值为0.0.0.0",
"mycat的使用端口,默认值为8066",
"mycat的管理端口,默认值为9066",
"mycat是否开启SQL统计,1开启,0未开启"};
public static final String[] ISOLATIONS = {"", "READ_UNCOMMITTED", "READ_COMMITTED", "REPEATED_READ", "SERIALIZABLE"};
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/manager/response/ShowSysParam.java |
914 | /**
* Copyright (c) 2011-2023, James Zhan 詹波 ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jfinal.kit;
import java.util.HashMap;
import java.util.Map;
import com.jfinal.json.Json;
/**
* Ret 用于返回值封装,也用于服务端与客户端的 json 数据通信
*
* <pre>
* 一、主要应用场景:
* 1:业务层需要返回多个返回值,例如要返回业务状态以及数据
* 2:renderJson(ret) 响应 json 数据给客户端
*
* 二、实例
* 1:服务端
* Ret ret = service.justDoIt(paras);
* renderJson(ret);
*
* 2:javascript 客户端 ajax 回调函数通常这么用:
* success: function(ret) {
* if(ret.state == "ok") {
* ...
* }
*
* if (ret.state == "fail") {
* ...
* }
* }
*
* 3:普通应用程序通常这么用:
* String json = getRawData();
* Ret ret = FastJson.getJson().parse(json, Ret.class);
* if (ret.isOk()) {
* ...
* }
*
* if (ret.isFail()) {
* ...
* }
*
* 三、定制 Ret
* 1:将状态字段名由 "state" 改为 "success",将状态值 "ok" 改为 true、"fail" 改为 false
* CPI.setRetState("success", true, false);
*
* 2:将状态字段名由 "state" 改为 "code",将状态值 "ok" 改为 200、"fail" 改为 500
* CPI.setRetState("code", 200, 500);
*
* 3:将消息字段名由 "msg" 改为 "message"
* CPI.setRetMsgName("message")
*
* 4:配置 Ret 的 data(Object) 方法伴随 ok 状态,默认值为:false
* CPI.setRetDataWithOkState(true)
*
* 5:配置监听 state 值,当值为 "ok" 时,额外放入 "success" 值为 true,否则为 false
* CPI.setRetStateWatcher((ret, state, value) -> {
* ret.set("success", "ok".equals(value));
* });
* 在前后端分离项目中,有些前端框架需要该返回值:"success" : true/false
*
* 6:配置 Ret.isOk()、Ret.isFail() 在前两个 if 判断都没有 return 之后的处理回调
* 用于支持多于两个状态的情况,也即在 ok、fail 两个状态之外还引入了其它状态
* CPI.setRetOkFailHandler((isOkMethod, value) -> {
* if (isOkMethod == Boolean.TRUE) {
* return false;
* } else {
* return true;
* }
* });
* </pre>
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class Ret extends HashMap {
private static final long serialVersionUID = -2150729333382285526L;
/**
* 状态
*/
static String STATE = "state";
static Object STATE_OK = "ok";
static Object STATE_FAIL = "fail";
static Func.F30<Ret, String, Object> stateWatcher = null;
static Func.F21<Boolean, Object, Boolean> okFailHandler = null;
/**
* 数据
*/
static String DATA = "data";
static boolean dataWithOkState = false; // data(Object) 方法伴随 ok 状态
/**
* 消息
*/
static String MSG = "msg";
public Ret() {
}
public static Ret of(Object key, Object value) {
return new Ret().set(key, value);
}
public static Ret by(Object key, Object value) {
return new Ret().set(key, value);
}
public static Ret create() {
return new Ret();
}
public static Ret ok() {
return new Ret().setOk();
}
public static Ret ok(String msg) {
return new Ret().setOk()._setMsg(msg);
}
public static Ret ok(Object key, Object value) {
return new Ret().setOk().set(key, value);
}
public static Ret fail() {
return new Ret().setFail();
}
public static Ret fail(String msg) {
return new Ret().setFail()._setMsg(msg);
}
@Deprecated
public static Ret fail(Object key, Object value) {
return new Ret().setFail().set(key, value);
}
public static Ret state(Object value) {
return new Ret()._setState(value);
}
public static Ret data(Object data) {
return new Ret()._setData(data);
}
public static Ret msg(String msg) {
return new Ret()._setMsg(msg);
}
/**
* 避免产生 setter/getter 方法,以免影响第三方 json 工具的行为
*
* 如果未来开放为 public,当 stateWatcher 不为 null 且 dataWithOkState 为 true
* 与 _setData 可以形成死循环调用
*/
protected Ret _setState(Object value) {
super.put(STATE, value);
if (stateWatcher != null) {
stateWatcher.call(this, STATE, value);
}
return this;
}
/**
* 避免产生 setter/getter 方法,以免影响第三方 json 工具的行为
*
* 如果未来开放为 public,当 stateWatcher 不为 null 且 dataWithOkState 为 true
* 与 _setState 可以形成死循环调用
*/
protected Ret _setData(Object data) {
super.put(DATA, data);
if (dataWithOkState) {
_setState(STATE_OK);
}
return this;
}
// 避免产生 setter/getter 方法,以免影响第三方 json 工具的行为
protected Ret _setMsg(String msg) {
super.put(MSG, msg);
return this;
}
public Ret setOk() {
return _setState(STATE_OK);
}
public Ret setFail() {
return _setState(STATE_FAIL);
}
public boolean isOk() {
Object state = get(STATE);
if (STATE_OK.equals(state)) {
return true;
}
if (STATE_FAIL.equals(state)) {
return false;
}
if (okFailHandler != null) {
return okFailHandler.call(Boolean.TRUE, state);
}
throw new IllegalStateException("调用 isOk() 之前,必须先调用 ok()、fail() 或者 setOk()、setFail() 方法");
}
public boolean isFail() {
Object state = get(STATE);
if (STATE_FAIL.equals(state)) {
return true;
}
if (STATE_OK.equals(state)) {
return false;
}
if (okFailHandler != null) {
return okFailHandler.call(Boolean.FALSE, state);
}
throw new IllegalStateException("调用 isFail() 之前,必须先调用 ok()、fail() 或者 setOk()、setFail() 方法");
}
public Ret set(Object key, Object value) {
super.put(key, value);
return this;
}
public Ret setIfNotBlank(Object key, String value) {
if (StrKit.notBlank(value)) {
set(key, value);
}
return this;
}
public Ret setIfNotNull(Object key, Object value) {
if (value != null) {
set(key, value);
}
return this;
}
public Ret set(Map map) {
super.putAll(map);
return this;
}
public Ret set(Ret ret) {
super.putAll(ret);
return this;
}
public Ret delete(Object key) {
super.remove(key);
return this;
}
public <T> T getAs(Object key) {
return (T)get(key);
}
public <T> T getAs(Object key, T defaultValue) {
Object ret = get(key);
return ret != null ? (T) ret : defaultValue;
}
public String getStr(Object key) {
Object s = get(key);
return s != null ? s.toString() : null;
}
public Integer getInt(Object key) {
Number n = (Number)get(key);
return n != null ? n.intValue() : null;
}
public Long getLong(Object key) {
Number n = (Number)get(key);
return n != null ? n.longValue() : null;
}
public Double getDouble(Object key) {
Number n = (Number)get(key);
return n != null ? n.doubleValue() : null;
}
public Float getFloat(Object key) {
Number n = (Number)get(key);
return n != null ? n.floatValue() : null;
}
public Number getNumber(Object key) {
return (Number)get(key);
}
public Boolean getBoolean(Object key) {
return (Boolean)get(key);
}
/**
* key 存在,并且 value 不为 null
*/
public boolean notNull(Object key) {
return get(key) != null;
}
/**
* key 不存在,或者 key 存在但 value 为null
*/
public boolean isNull(Object key) {
return get(key) == null;
}
/**
* key 存在,并且 value 为 true,则返回 true
*/
public boolean isTrue(Object key) {
Object value = get(key);
return (value instanceof Boolean && ((Boolean)value == true));
}
/**
* key 存在,并且 value 为 false,则返回 true
*/
public boolean isFalse(Object key) {
Object value = get(key);
return (value instanceof Boolean && ((Boolean)value == false));
}
public String toJson() {
return Json.getJson().toJson(this);
}
public boolean equals(Object ret) {
return ret instanceof Ret && super.equals(ret);
}
}
| jfinal/jfinal | src/main/java/com/jfinal/kit/Ret.java |
916 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.demo.okgo;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.lzy.demo.R;
import com.lzy.demo.base.BaseDetailActivity;
import com.lzy.demo.callback.DialogCallback;
import com.lzy.demo.model.LzyResponse;
import com.lzy.demo.model.ServerModel;
import com.lzy.demo.utils.GlideImageLoader;
import com.lzy.demo.utils.Urls;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class UpActivity extends BaseDetailActivity {
@Bind(R.id.images) TextView tvImages;
private ImageItem imageItem;
@Override
protected void onActivityCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_up_text);
ButterKnife.bind(this);
setTitle("普通上传数据");
}
@Override
protected void onDestroy() {
super.onDestroy();
//Activity销毁时,取消网络请求
OkGo.getInstance().cancelTag(this);
}
@OnClick(R.id.selectImage)
public void selectImage(View view) {
ImagePicker imagePicker = ImagePicker.getInstance();
imagePicker.setImageLoader(new GlideImageLoader());
imagePicker.setMultiMode(false); //单选
imagePicker.setShowCamera(true); //显示拍照按钮
imagePicker.setSelectLimit(9); //最多选择9张
imagePicker.setCrop(false); //不进行裁剪
Intent intent = new Intent(this, ImageGridActivity.class);
startActivityForResult(intent, 100);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
if (data != null && requestCode == 100) {
//noinspection unchecked
List<ImageItem> imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
if (imageItems != null && imageItems.size() > 0) {
imageItem = imageItems.get(0);
tvImages.setText(imageItem.path);
} else {
tvImages.setText("--");
}
} else {
Toast.makeText(this, "没有选择图片", Toast.LENGTH_SHORT).show();
tvImages.setText("--");
}
}
}
@OnClick(R.id.upJson)
public void upJson(View view) {
HashMap<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "这里是需要提交的json格式数据");
params.put("key3", "也可以使用三方工具将对象转成json字符串");
params.put("key4", "其实你怎么高兴怎么写都行");
JSONObject jsonObject = new JSONObject(params);
OkGo.<LzyResponse<ServerModel>>post(Urls.URL_TEXT_UPLOAD)//
.tag(this)//
.headers("header1", "headerValue1")//
// .params("param1", "paramValue1")// 这里不要使用params,upJson 与 params 是互斥的,只有 upJson 的数据会被上传
.upJson(jsonObject)//
.execute(new DialogCallback<LzyResponse<ServerModel>>(this) {
@Override
public void onSuccess(Response<LzyResponse<ServerModel>> response) {
handleResponse(response);
}
@Override
public void onError(Response<LzyResponse<ServerModel>> response) {
handleError(response);
}
});
}
@OnClick(R.id.upString)
public void upString(View view) {
OkGo.<LzyResponse<ServerModel>>post(Urls.URL_TEXT_UPLOAD)//
.tag(this)//
.headers("header1", "headerValue1")//
// .params("param1", "paramValue1")// 这里不要使用params,upString 与 params 是互斥的,只有 upString 的数据会被上传
.upString("这是要上传的长文本数据!")//
// .upString("这是要上传的长文本数据!", MediaType.parse("application/xml"))// 比如上传xml数据,这里就可以自己指定请求头
.execute(new DialogCallback<LzyResponse<ServerModel>>(this) {
@Override
public void onSuccess(Response<LzyResponse<ServerModel>> response) {
handleResponse(response);
}
@Override
public void onError(Response<LzyResponse<ServerModel>> response) {
handleError(response);
}
});
}
@OnClick(R.id.upBytes)
public void upBytes(View view) {
OkGo.<LzyResponse<ServerModel>>post(Urls.URL_TEXT_UPLOAD)//
.tag(this)//
.headers("header1", "headerValue1")//
// .params("param1", "paramValue1")// 这里不要使用params,upBytes 与 params 是互斥的,只有 upBytes 的数据会被上传
.upBytes("这是字节数据".getBytes())//
.execute(new DialogCallback<LzyResponse<ServerModel>>(this) {
@Override
public void onSuccess(Response<LzyResponse<ServerModel>> response) {
handleResponse(response);
}
@Override
public void onError(Response<LzyResponse<ServerModel>> response) {
handleError(response);
}
});
}
@OnClick(R.id.upFile)
public void upFile(View view) {
if (imageItem == null) {
showToast("请先选择文件!");
return;
}
OkGo.<LzyResponse<ServerModel>>post(Urls.URL_TEXT_UPLOAD)//
.tag(this)//
.headers("header1", "headerValue1")//
// .params("param1", "paramValue1")// 这里不要使用params,upBytes 与 params 是互斥的,只有 upBytes 的数据会被上传
.upFile(new File(imageItem.path))//
.execute(new DialogCallback<LzyResponse<ServerModel>>(this) {
@Override
public void onSuccess(Response<LzyResponse<ServerModel>> response) {
handleResponse(response);
}
@Override
public void onError(Response<LzyResponse<ServerModel>> response) {
handleError(response);
}
});
}
}
| jeasonlzy/okhttp-OkGo | demo/src/main/java/com/lzy/demo/okgo/UpActivity.java |
917 | /*
* Copyright 2010-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.spring;
import static org.springframework.util.Assert.notNull;
import static org.springframework.util.Assert.state;
import static org.springframework.util.ObjectUtils.isEmpty;
import static org.springframework.util.StringUtils.hasLength;
import static org.springframework.util.StringUtils.tokenizeToStringArray;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Stream;
import javax.sql.DataSource;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.TypeHandler;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.util.ClassUtils;
/**
* {@code FactoryBean} that creates a MyBatis {@code SqlSessionFactory}. This is the usual way to set up a shared MyBatis {@code SqlSessionFactory} in
* a Spring application context; the SqlSessionFactory can then be passed to MyBatis-based DAOs via dependency injection.
*
* Either {@code DataSourceTransactionManager} or {@code JtaTransactionManager} can be used for transaction demarcation in combination with a
* {@code SqlSessionFactory}. JTA should be used for transactions which span multiple databases or when container managed transactions (CMT) are being
* used.
*
* @author Putthiphong Boonphong
* @author Hunter Presnall
* @author Eduardo Macarron
* @author Eddú Meléndez
* @author Kazuki Shimizu
*
* @see #setConfigLocation
* @see #setDataSource
* @desctiption 增加刷新xml文件
*/
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(SqlSessionFactoryBean.class);
private static final ResourcePatternResolver RESOURCE_PATTERN_RESOLVER = new PathMatchingResourcePatternResolver();
private static final MetadataReaderFactory METADATA_READER_FACTORY = new CachingMetadataReaderFactory();
private Resource configLocation;
private Configuration configuration;
private Resource[] mapperLocations;
private DataSource dataSource;
private TransactionFactory transactionFactory;
private Properties configurationProperties;
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private SqlSessionFactory sqlSessionFactory;
// EnvironmentAware requires spring 3.1
private String environment = SqlSessionFactoryBean.class.getSimpleName();
private boolean failFast;
private Interceptor[] plugins;
private TypeHandler<?>[] typeHandlers;
private String typeHandlersPackage;
@SuppressWarnings("rawtypes")
private Class<? extends TypeHandler> defaultEnumTypeHandler;
private Class<?>[] typeAliases;
private String typeAliasesPackage;
private Class<?> typeAliasesSuperType;
private LanguageDriver[] scriptingLanguageDrivers;
private Class<? extends LanguageDriver> defaultScriptingLanguageDriver;
// issue #19. No default provider.
private DatabaseIdProvider databaseIdProvider;
private Class<? extends VFS> vfs;
private Cache cache;
private ObjectFactory objectFactory;
private ObjectWrapperFactory objectWrapperFactory;
/**
* Sets the ObjectFactory.
*
* @since 1.1.2
* @param objectFactory a custom ObjectFactory
*/
public void setObjectFactory(ObjectFactory objectFactory) {
this.objectFactory = objectFactory;
}
/**
* Sets the ObjectWrapperFactory.
*
* @since 1.1.2
* @param objectWrapperFactory a specified ObjectWrapperFactory
*/
public void setObjectWrapperFactory(ObjectWrapperFactory objectWrapperFactory) {
this.objectWrapperFactory = objectWrapperFactory;
}
/**
* Gets the DatabaseIdProvider
*
* @since 1.1.0
* @return a specified DatabaseIdProvider
*/
public DatabaseIdProvider getDatabaseIdProvider() {
return databaseIdProvider;
}
/**
* Sets the DatabaseIdProvider. As of version 1.2.2 this variable is not initialized by default.
*
* @since 1.1.0
* @param databaseIdProvider a DatabaseIdProvider
*/
public void setDatabaseIdProvider(DatabaseIdProvider databaseIdProvider) {
this.databaseIdProvider = databaseIdProvider;
}
/**
* Gets the VFS.
*
* @return a specified VFS
*/
public Class<? extends VFS> getVfs() {
return this.vfs;
}
/**
* Sets the VFS.
*
* @param vfs a VFS
*/
public void setVfs(Class<? extends VFS> vfs) {
this.vfs = vfs;
}
/**
* Gets the Cache.
*
* @return a specified Cache
*/
public Cache getCache() {
return this.cache;
}
/**
* Sets the Cache.
*
* @param cache a Cache
*/
public void setCache(Cache cache) {
this.cache = cache;
}
/**
* Mybatis plugin list.
*
* @since 1.0.1
*
* @param plugins list of plugins
*
*/
public void setPlugins(Interceptor... plugins) {
this.plugins = plugins;
}
/**
* Packages to search for type aliases.
*
* <p>
* Since 2.0.1, allow to specify a wildcard such as {@code com.example.*.model}.
*
* @since 1.0.1
*
* @param typeAliasesPackage package to scan for domain objects
*
*/
public void setTypeAliasesPackage(String typeAliasesPackage) {
this.typeAliasesPackage = typeAliasesPackage;
}
/**
* Super class which domain objects have to extend to have a type alias created. No effect if there is no package to scan configured.
*
* @since 1.1.2
*
* @param typeAliasesSuperType super class for domain objects
*
*/
public void setTypeAliasesSuperType(Class<?> typeAliasesSuperType) {
this.typeAliasesSuperType = typeAliasesSuperType;
}
/**
* Packages to search for type handlers.
*
* <p>
* Since 2.0.1, allow to specify a wildcard such as {@code com.example.*.typehandler}.
*
* @since 1.0.1
*
* @param typeHandlersPackage package to scan for type handlers
*
*/
public void setTypeHandlersPackage(String typeHandlersPackage) {
this.typeHandlersPackage = typeHandlersPackage;
}
/**
* Set type handlers. They must be annotated with {@code MappedTypes} and optionally with {@code MappedJdbcTypes}
*
* @since 1.0.1
*
* @param typeHandlers Type handler list
*/
public void setTypeHandlers(TypeHandler<?>... typeHandlers) {
this.typeHandlers = typeHandlers;
}
/**
* Set the default type handler class for enum.
*
* @since 2.0.5
* @param defaultEnumTypeHandler The default type handler class for enum
*/
public void setDefaultEnumTypeHandler(@SuppressWarnings("rawtypes") Class<? extends TypeHandler> defaultEnumTypeHandler) {
this.defaultEnumTypeHandler = defaultEnumTypeHandler;
}
/**
* List of type aliases to register. They can be annotated with {@code Alias}
*
* @since 1.0.1
*
* @param typeAliases Type aliases list
*/
public void setTypeAliases(Class<?>... typeAliases) {
this.typeAliases = typeAliases;
}
/**
* If true, a final check is done on Configuration to assure that all mapped statements are fully loaded and there is no one still pending to
* resolve includes. Defaults to false.
*
* @since 1.0.1
*
* @param failFast enable failFast
*/
public void setFailFast(boolean failFast) {
this.failFast = failFast;
}
/**
* Set the location of the MyBatis {@code SqlSessionFactory} config file. A typical value is "WEB-INF/mybatis-configuration.xml".
*
* @param configLocation a location the MyBatis config file
*/
public void setConfigLocation(Resource configLocation) {
this.configLocation = configLocation;
}
/**
* Set a customized MyBatis configuration.
*
* @param configuration MyBatis configuration
* @since 1.3.0
*/
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
/**
* Set locations of MyBatis mapper files that are going to be merged into the {@code SqlSessionFactory} configuration at runtime.
*
* This is an alternative to specifying "<sqlmapper>" entries in an MyBatis config file. This property being based on Spring's resource
* abstraction also allows for specifying resource patterns here: e.g. "classpath*:sqlmap/*-mapper.xml".
*
* @param mapperLocations location of MyBatis mapper files
*/
public void setMapperLocations(Resource... mapperLocations) {
this.mapperLocations = mapperLocations;
}
/**
* Set optional properties to be passed into the SqlSession configuration, as alternative to a {@code <properties>} tag in the configuration
* xml file. This will be used to resolve placeholders in the config file.
*
* @param sqlSessionFactoryProperties optional properties for the SqlSessionFactory
*/
public void setConfigurationProperties(Properties sqlSessionFactoryProperties) {
this.configurationProperties = sqlSessionFactoryProperties;
}
/**
* Set the JDBC {@code DataSource} that this instance should manage transactions for. The {@code DataSource} should match the one used by the
* {@code SqlSessionFactory}: for example, you could specify the same JNDI DataSource for both.
*
* A transactional JDBC {@code Connection} for this {@code DataSource} will be provided to application code accessing this {@code DataSource}
* directly via {@code DataSourceUtils} or {@code DataSourceTransactionManager}.
*
* The {@code DataSource} specified here should be the target {@code DataSource} to manage transactions for, not a
* {@code TransactionAwareDataSourceProxy}. Only data access code may work with {@code TransactionAwareDataSourceProxy}, while the transaction
* manager needs to work on the underlying target {@code DataSource}. If there's nevertheless a {@code TransactionAwareDataSourceProxy} passed in,
* it will be unwrapped to extract its target {@code DataSource}.
*
* @param dataSource a JDBC {@code DataSource}
*
*/
public void setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
// If we got a TransactionAwareDataSourceProxy, we need to perform
// transactions for its underlying target DataSource, else data
// access code won't see properly exposed transactions (i.e.
// transactions for the target DataSource).
this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
} else {
this.dataSource = dataSource;
}
}
/**
* Sets the {@code SqlSessionFactoryBuilder} to use when creating the {@code SqlSessionFactory}.
*
* This is mainly meant for testing so that mock SqlSessionFactory classes can be injected. By default, {@code SqlSessionFactoryBuilder} creates
* {@code DefaultSqlSessionFactory} instances.
*
* @param sqlSessionFactoryBuilder a SqlSessionFactoryBuilder
*
*/
public void setSqlSessionFactoryBuilder(SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
}
/**
* Set the MyBatis TransactionFactory to use. Default is {@code SpringManagedTransactionFactory}
*
* The default {@code SpringManagedTransactionFactory} should be appropriate for all cases: be it Spring transaction management, EJB CMT or plain
* JTA. If there is no active transaction, SqlSession operations will execute SQL statements non-transactionally.
*
* <b>It is strongly recommended to use the default {@code TransactionFactory}.</b> If not used, any attempt at getting an SqlSession through
* Spring's MyBatis framework will throw an exception if a transaction is active.
*
* @see SpringManagedTransactionFactory
* @param transactionFactory the MyBatis TransactionFactory
*/
public void setTransactionFactory(TransactionFactory transactionFactory) {
this.transactionFactory = transactionFactory;
}
/**
* <b>NOTE:</b> This class <em>overrides</em> any {@code Environment} you have set in the MyBatis config file. This is used only as a placeholder
* name. The default value is {@code SqlSessionFactoryBean.class.getSimpleName()}.
*
* @param environment the environment name
*/
public void setEnvironment(String environment) {
this.environment = environment;
}
/**
* Set scripting language drivers.
*
* @param scriptingLanguageDrivers scripting language drivers
* @since 2.0.2
*/
public void setScriptingLanguageDrivers(LanguageDriver... scriptingLanguageDrivers) {
this.scriptingLanguageDrivers = scriptingLanguageDrivers;
}
/**
* Set a default scripting language driver class.
*
* @param defaultScriptingLanguageDriver A default scripting language driver class
* @since 2.0.2
*/
public void setDefaultScriptingLanguageDriver(Class<? extends LanguageDriver> defaultScriptingLanguageDriver) {
this.defaultScriptingLanguageDriver = defaultScriptingLanguageDriver;
}
/**
* {@inheritDoc}
*/
@Override
public void afterPropertiesSet() throws Exception {
notNull(dataSource, "Property 'dataSource' is required");
notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
"Property 'configuration' and 'configLocation' can not specified with together");
this.sqlSessionFactory = buildSqlSessionFactory();
}
/**
* Build a {@code SqlSessionFactory} instance.
*
* The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a {@code SqlSessionFactory} instance based on a
* Reader. Since 1.3.0, it can be specified a {@link Configuration} instance directly(without config file).
*
* @return SqlSessionFactory
* @throws Exception if configuration is failed
*/
protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
final Configuration targetConfiguration;
XMLConfigBuilder xmlConfigBuilder = null;
if (this.configuration != null) {
targetConfiguration = this.configuration;
if (targetConfiguration.getVariables() == null) {
targetConfiguration.setVariables(this.configurationProperties);
} else if (this.configurationProperties != null) {
targetConfiguration.getVariables().putAll(this.configurationProperties);
}
} else if (this.configLocation != null) {
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
targetConfiguration = xmlConfigBuilder.getConfiguration();
} else {
LOGGER.debug(() -> "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
targetConfiguration = new Configuration();
Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
}
Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);
if (hasLength(this.typeAliasesPackage)) {
scanClasses(this.typeAliasesPackage, this.typeAliasesSuperType).stream().filter(clazz -> !clazz.isAnonymousClass())
.filter(clazz -> !clazz.isInterface()).filter(clazz -> !clazz.isMemberClass())
.forEach(targetConfiguration.getTypeAliasRegistry()::registerAlias);
}
if (!isEmpty(this.typeAliases)) {
Stream.of(this.typeAliases).forEach(typeAlias -> {
targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
LOGGER.debug(() -> "Registered type alias: '" + typeAlias + "'");
});
}
if (!isEmpty(this.plugins)) {
Stream.of(this.plugins).forEach(plugin -> {
targetConfiguration.addInterceptor(plugin);
LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
});
}
if (hasLength(this.typeHandlersPackage)) {
scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass())
.filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
.forEach(targetConfiguration.getTypeHandlerRegistry()::register);
}
if (!isEmpty(this.typeHandlers)) {
Stream.of(this.typeHandlers).forEach(typeHandler -> {
targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
LOGGER.debug(() -> "Registered type handler: '" + typeHandler + "'");
});
}
targetConfiguration.setDefaultEnumTypeHandler(defaultEnumTypeHandler);
if (!isEmpty(this.scriptingLanguageDrivers)) {
Stream.of(this.scriptingLanguageDrivers).forEach(languageDriver -> {
targetConfiguration.getLanguageRegistry().register(languageDriver);
LOGGER.debug(() -> "Registered scripting language driver: '" + languageDriver + "'");
});
}
Optional.ofNullable(this.defaultScriptingLanguageDriver).ifPresent(targetConfiguration::setDefaultScriptingLanguage);
if (this.databaseIdProvider != null) {// fix #64 set databaseId before parse mapper xmls
try {
targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
} catch (SQLException e) {
throw new NestedIOException("Failed getting a databaseId", e);
}
}
Optional.ofNullable(this.cache).ifPresent(targetConfiguration::addCache);
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
} catch (Exception ex) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
} finally {
ErrorContext.instance().reset();
}
}
targetConfiguration.setEnvironment(new Environment(this.environment,
this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory, this.dataSource));
// TODO 增加location 获取加载xml的路径,也可配置
String location = null;
if (this.mapperLocations != null) {
if (this.mapperLocations.length == 0) {
LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
} else {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
if (location == null) {
location = mapperLocation.toString();
}
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), targetConfiguration,
mapperLocation.toString(), targetConfiguration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
e.printStackTrace(); // 出现错误抛出异常
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
}
// TODO 编译sqlsession时,启动定时器
new org.apache.ibatis.thread.Runnable(location, targetConfiguration).run();
return this.sqlSessionFactoryBuilder.build(targetConfiguration);
}
/**
* {@inheritDoc}
*/
@Override
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
/**
* {@inheritDoc}
*/
@Override
public Class<? extends SqlSessionFactory> getObjectType() {
return this.sqlSessionFactory == null ? SqlSessionFactory.class : this.sqlSessionFactory.getClass();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isSingleton() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (failFast && event instanceof ContextRefreshedEvent) {
// fail-fast -> check all statements are completed
this.sqlSessionFactory.getConfiguration().getMappedStatementNames();
}
}
private Set<Class<?>> scanClasses(String packagePatterns, Class<?> assignableType) throws IOException {
Set<Class<?>> classes = new HashSet<>();
String[] packagePatternArray = tokenizeToStringArray(packagePatterns, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packagePattern : packagePatternArray) {
Resource[] resources = RESOURCE_PATTERN_RESOLVER.getResources(
ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(packagePattern) + "/**/*.class");
for (Resource resource : resources) {
// 注意:这里只扫描 entity 的包
if (!resource.getURI().toString().contains("entity")) {
continue;
}
try {
ClassMetadata classMetadata = METADATA_READER_FACTORY.getMetadataReader(resource).getClassMetadata();
Class<?> clazz = Resources.classForName(classMetadata.getClassName());
if (assignableType == null || assignableType.isAssignableFrom(clazz)) {
classes.add(clazz);
}
} catch (Throwable e) {
LOGGER.warn(() -> "Cannot load the '" + resource + "'. Cause by " + e.toString());
}
}
}
return classes;
}
/**
* 刷新
* @param inputStream
* @param resource
* @param configuration
* @throws NestedIOException
*/
public static void refresh(java.io.InputStream inputStream, String resource, Configuration configuration) throws NestedIOException {
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
xmlMapperBuilder.parse1();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + resource + "'", e);
} finally {
ErrorContext.instance().reset();
}
}
}
| thinkgem/jeesite | src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java |
919 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.filter.config;
import com.alibaba.druid.util.Base64;
import com.alibaba.druid.util.JdbcUtils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
@Deprecated
public class ConfigTools {
@Deprecated
private static final String DEFAULT_PRIVATE_KEY_STRING = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAocbCrurZGbC5GArEHKlAfDSZi7gFBnd4yxOt0rwTqKBFzGyhtQLu5PRKjEiOXVa95aeIIBJ6OhC2f8FjqFUpawIDAQABAkAPejKaBYHrwUqUEEOe8lpnB6lBAsQIUFnQI/vXU4MV+MhIzW0BLVZCiarIQqUXeOhThVWXKFt8GxCykrrUsQ6BAiEA4vMVxEHBovz1di3aozzFvSMdsjTcYRRo82hS5Ru2/OECIQC2fAPoXixVTVY7bNMeuxCP4954ZkXp7fEPDINCjcQDywIgcc8XLkkPcs3Jxk7uYofaXaPbg39wuJpEmzPIxi3k0OECIGubmdpOnin3HuCP/bbjbJLNNoUdGiEmFL5hDI4UdwAdAiEAtcAwbm08bKN7pwwvyqaCBC//VnEWaq39DCzxr+Z2EIk=";
@Deprecated
public static final String DEFAULT_PUBLIC_KEY_STRING = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKHGwq7q2RmwuRgKxBypQHw0mYu4BQZ3eMsTrdK8E6igRcxsobUC7uT0SoxIjl1WveWniCASejoQtn/BY6hVKWsCAwEAAQ==";
public static void main(String[] args) throws Exception {
String password = args[0];
String[] arr = genKeyPair(512);
System.out.println("privateKey:" + arr[0]);
System.out.println("publicKey:" + arr[1]);
System.out.println("password:" + encrypt(arr[0], password));
}
public static String decrypt(String cipherText) throws Exception {
return decrypt((String) null, cipherText);
}
public static String decrypt(String publicKeyText, String cipherText)
throws Exception {
PublicKey publicKey = getPublicKey(publicKeyText);
return decrypt(publicKey, cipherText);
}
public static PublicKey getPublicKeyByX509(String x509File) {
if (x509File == null || x509File.length() == 0) {
return ConfigTools.getPublicKey(null);
}
FileInputStream in = null;
try {
in = new FileInputStream(x509File);
CertificateFactory factory = CertificateFactory
.getInstance("X.509");
Certificate cer = factory.generateCertificate(in);
return cer.getPublicKey();
} catch (Exception e) {
throw new IllegalArgumentException("Failed to get public key", e);
} finally {
JdbcUtils.close(in);
}
}
public static PublicKey getPublicKey(String publicKeyText) {
if (publicKeyText == null || publicKeyText.length() == 0) {
publicKeyText = ConfigTools.DEFAULT_PUBLIC_KEY_STRING;
}
try {
byte[] publicKeyBytes = Base64.base64ToByteArray(publicKeyText);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(
publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign");
return keyFactory.generatePublic(x509KeySpec);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to get public key", e);
}
}
public static PublicKey getPublicKeyByPublicKeyFile(String publicKeyFile) {
if (publicKeyFile == null || publicKeyFile.length() == 0) {
return ConfigTools.getPublicKey(null);
}
FileInputStream in = null;
try {
in = new FileInputStream(publicKeyFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len = 0;
byte[] b = new byte[512 / 8];
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
byte[] publicKeyBytes = out.toByteArray();
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory factory = KeyFactory.getInstance("RSA", "SunRsaSign");
return factory.generatePublic(spec);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to get public key", e);
} finally {
JdbcUtils.close(in);
}
}
public static String decrypt(PublicKey publicKey, String cipherText)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
try {
cipher.init(Cipher.DECRYPT_MODE, publicKey);
} catch (InvalidKeyException e) {
// 因为 IBM JDK 不支持私钥加密, 公钥解密, 所以要反转公私钥
// 也就是说对于解密, 可以通过公钥的参数伪造一个私钥对象欺骗 IBM JDK
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
cipher = Cipher.getInstance("RSA"); //It is a stateful object. so we need to get new one.
cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
}
if (cipherText == null || cipherText.length() == 0) {
return cipherText;
}
byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
byte[] plainBytes = cipher.doFinal(cipherBytes);
return new String(plainBytes);
}
public static String encrypt(String plainText) throws Exception {
return encrypt((String) null, plainText);
}
public static String encrypt(String key, String plainText) throws Exception {
if (key == null) {
key = DEFAULT_PRIVATE_KEY_STRING;
}
byte[] keyBytes = Base64.base64ToByteArray(key);
return encrypt(keyBytes, plainText);
}
public static String encrypt(byte[] keyBytes, String plainText)
throws Exception {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory factory = KeyFactory.getInstance("RSA", "SunRsaSign");
PrivateKey privateKey = factory.generatePrivate(spec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
try {
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
} catch (InvalidKeyException e) {
//For IBM JDK, 原因请看解密方法中的说明
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, fakePublicKey);
}
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
String encryptedString = Base64.byteArrayToBase64(encryptedBytes);
return encryptedString;
}
public static byte[][] genKeyPairBytes(int keySize)
throws NoSuchAlgorithmException, NoSuchProviderException {
byte[][] keyPairBytes = new byte[2][];
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
gen.initialize(keySize, new SecureRandom());
KeyPair pair = gen.generateKeyPair();
keyPairBytes[0] = pair.getPrivate().getEncoded();
keyPairBytes[1] = pair.getPublic().getEncoded();
return keyPairBytes;
}
public static String[] genKeyPair(int keySize)
throws NoSuchAlgorithmException, NoSuchProviderException {
byte[][] keyPairBytes = genKeyPairBytes(keySize);
String[] keyPairs = new String[2];
keyPairs[0] = Base64.byteArrayToBase64(keyPairBytes[0]);
keyPairs[1] = Base64.byteArrayToBase64(keyPairBytes[1]);
return keyPairs;
}
}
| alibaba/druid | core/src/main/java/com/alibaba/druid/filter/config/ConfigTools.java |
922 | package org.jeecg.common.system.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.constant.TenantConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysUserCacheInfo;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
/**
* @Author Scott
* @Date 2018-07-12 14:23
* @Desc JWT工具类
**/
@Slf4j
public class JwtUtil {
/**Token有效期为7天(Token在reids中缓存时间为两倍)*/
public static final long EXPIRE_TIME = (7 * 12) * 60 * 60 * 1000;
static final String WELL_NUMBER = SymbolConstant.WELL_NUMBER + SymbolConstant.LEFT_CURLY_BRACKET;
/**
*
* @param response
* @param code
* @param errorMsg
*/
public static void responseError(ServletResponse response, Integer code, String errorMsg) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
// issues/I4YH95浏览器显示乱码问题
httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
Result jsonResult = new Result(code, errorMsg);
jsonResult.setSuccess(false);
OutputStream os = null;
try {
os = httpServletResponse.getOutputStream();
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setStatus(code);
os.write(new ObjectMapper().writeValueAsString(jsonResult).getBytes("UTF-8"));
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 校验token是否正确
*
* @param token 密钥
* @param secret 用户的密码
* @return 是否正确
*/
public static boolean verify(String token, String username, String secret) {
try {
// 根据密码生成JWT效验器
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
// 效验TOKEN
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception exception) {
return false;
}
}
/**
* 获得token中的信息无需secret解密也能获得
*
* @return token中包含的用户名
*/
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("username").asString();
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 生成签名,5min后过期
*
* @param username 用户名
* @param secret 用户的密码
* @return 加密的token
*/
public static String sign(String username, String secret) {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带username信息
return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
}
/**
* 根据request中的token获取用户账号
*
* @param request
* @return
* @throws JeecgBootException
*/
public static String getUserNameByToken(HttpServletRequest request) throws JeecgBootException {
String accessToken = request.getHeader("X-Access-Token");
String username = getUsername(accessToken);
if (oConvertUtils.isEmpty(username)) {
throw new JeecgBootException("未获取到用户");
}
return username;
}
/**
* 从session中获取变量
* @param key
* @return
*/
public static String getSessionData(String key) {
//${myVar}%
//得到${} 后面的值
String moshi = "";
String wellNumber = WELL_NUMBER;
if(key.indexOf(SymbolConstant.RIGHT_CURLY_BRACKET)!=-1){
moshi = key.substring(key.indexOf("}")+1);
}
String returnValue = null;
if (key.contains(wellNumber)) {
key = key.substring(2,key.indexOf("}"));
}
if (oConvertUtils.isNotEmpty(key)) {
HttpSession session = SpringContextUtils.getHttpServletRequest().getSession();
returnValue = (String) session.getAttribute(key);
}
//结果加上${} 后面的值
if(returnValue!=null){returnValue = returnValue + moshi;}
return returnValue;
}
/**
* 从当前用户中获取变量
* @param key
* @param user
* @return
*/
public static String getUserSystemData(String key, SysUserCacheInfo user) {
//1.优先获取 SysUserCacheInfo
if(user==null) {
try {
user = JeecgDataAutorUtils.loadUserInfo();
} catch (Exception e) {
log.warn("获取用户信息异常:" + e.getMessage());
}
}
//2.通过shiro获取登录用户信息
LoginUser sysUser = null;
try {
sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
} catch (Exception e) {
log.warn("SecurityUtils.getSubject() 获取用户信息异常:" + e.getMessage());
}
//#{sys_user_code}%
String moshi = "";
String wellNumber = WELL_NUMBER;
if(key.indexOf(SymbolConstant.RIGHT_CURLY_BRACKET)!=-1){
moshi = key.substring(key.indexOf("}")+1);
}
String returnValue = null;
//针对特殊标示处理#{sysOrgCode},判断替换
if (key.contains(wellNumber)) {
key = key.substring(2,key.indexOf("}"));
} else {
key = key;
}
//替换为当前系统时间(年月日)
if (key.equals(DataBaseConstant.SYS_DATE)|| key.toLowerCase().equals(DataBaseConstant.SYS_DATE_TABLE)) {
returnValue = DateUtils.formatDate();
}
//替换为当前系统时间(年月日时分秒)
else if (key.equals(DataBaseConstant.SYS_TIME)|| key.toLowerCase().equals(DataBaseConstant.SYS_TIME_TABLE)) {
returnValue = DateUtils.now();
}
//流程状态默认值(默认未发起)
else if (key.equals(DataBaseConstant.BPM_STATUS)|| key.toLowerCase().equals(DataBaseConstant.BPM_STATUS_TABLE)) {
returnValue = "1";
}
//后台任务获取用户信息异常,导致程序中断
if(sysUser==null && user==null){
return null;
}
//替换为系统登录用户帐号
if (key.equals(DataBaseConstant.SYS_USER_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_USER_CODE_TABLE)) {
if(user==null) {
returnValue = sysUser.getUsername();
}else {
returnValue = user.getSysUserCode();
}
}
//替换为系统登录用户真实名字
else if (key.equals(DataBaseConstant.SYS_USER_NAME)|| key.toLowerCase().equals(DataBaseConstant.SYS_USER_NAME_TABLE)) {
if(user==null) {
returnValue = sysUser.getRealname();
}else {
returnValue = user.getSysUserName();
}
}
//替换为系统用户登录所使用的机构编码
else if (key.equals(DataBaseConstant.SYS_ORG_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_ORG_CODE_TABLE)) {
if(user==null) {
returnValue = sysUser.getOrgCode();
}else {
returnValue = user.getSysOrgCode();
}
}
//替换为系统用户所拥有的所有机构编码
else if (key.equals(DataBaseConstant.SYS_MULTI_ORG_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_MULTI_ORG_CODE_TABLE)) {
if(user==null){
//TODO 暂时使用用户登录部门,存在逻辑缺陷,不是用户所拥有的部门
returnValue = sysUser.getOrgCode();
}else{
if(user.isOneDepart()) {
returnValue = user.getSysMultiOrgCode().get(0);
}else {
returnValue = Joiner.on(",").join(user.getSysMultiOrgCode());
}
}
}
//update-begin-author:taoyan date:20210330 for:多租户ID作为系统变量
else if (key.equals(TenantConstant.TENANT_ID) || key.toLowerCase().equals(TenantConstant.TENANT_ID_TABLE)){
try {
returnValue = SpringContextUtils.getHttpServletRequest().getHeader(CommonConstant.TENANT_ID);
} catch (Exception e) {
log.warn("获取系统租户异常:" + e.getMessage());
}
}
//update-end-author:taoyan date:20210330 for:多租户ID作为系统变量
if(returnValue!=null){returnValue = returnValue + moshi;}
return returnValue;
}
// public static void main(String[] args) {
// String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjUzMzY1MTMsInVzZXJuYW1lIjoiYWRtaW4ifQ.xjhud_tWCNYBOg_aRlMgOdlZoWFFKB_givNElHNw3X0";
// System.out.println(JwtUtil.getUsername(token));
// }
}
| jeecgboot/jeecg-boot | jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/JwtUtil.java |
923 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2023 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.pagehelper.page;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.Page;
import com.github.pagehelper.util.PageObjectUtil;
import java.util.Properties;
/**
* 基础分页方法
*
* @author liuzh
*/
public abstract class PageMethod {
protected static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();
protected static boolean DEFAULT_COUNT = true;
/**
* 设置 Page 参数
*
* @param page
*/
public static void setLocalPage(Page page) {
LOCAL_PAGE.set(page);
}
/**
* 获取 Page 参数
*
* @return
*/
public static <T> Page<T> getLocalPage() {
return LOCAL_PAGE.get();
}
/**
* 移除本地变量
*/
public static void clearPage() {
LOCAL_PAGE.remove();
}
/**
* 获取任意查询方法的count总数
*
* @param select
* @return
*/
public static long count(ISelect select) {
//单纯count查询时禁用异步count
Page<?> page = startPage(1, -1, true).disableAsyncCount();
select.doSelect();
return page.getTotal();
}
/**
* 开始分页
*
* @param params
*/
public static <E> Page<E> startPage(Object params) {
Page<E> page = PageObjectUtil.getPageFromObject(params, true);
//当已经执行过orderBy的时候
Page<E> oldPage = getLocalPage();
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
}
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
*/
public static <E> Page<E> startPage(int pageNum, int pageSize) {
return startPage(pageNum, pageSize, DEFAULT_COUNT);
}
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
* @param count 是否进行count查询
*/
public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count) {
return startPage(pageNum, pageSize, count, null, null);
}
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
* @param orderBy 排序
*/
public static <E> Page<E> startPage(int pageNum, int pageSize, String orderBy) {
Page<E> page = startPage(pageNum, pageSize);
page.setOrderBy(orderBy);
return page;
}
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
* @param count 是否进行count查询
* @param reasonable 分页合理化,null时用默认配置
* @param pageSizeZero true且pageSize=0时返回全部结果,false时分页,null时用默认配置
*/
public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
Page<E> page = new Page<E>(pageNum, pageSize, count);
page.setReasonable(reasonable);
page.setPageSizeZero(pageSizeZero);
//当已经执行过orderBy的时候
Page<E> oldPage = getLocalPage();
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
}
/**
* 开始分页
*
* @param offset 起始位置,偏移位置
* @param limit 每页显示数量
*/
public static <E> Page<E> offsetPage(int offset, int limit) {
return offsetPage(offset, limit, DEFAULT_COUNT);
}
/**
* 开始分页
*
* @param offset 起始位置,偏移位置
* @param limit 每页显示数量
* @param count 是否进行count查询
*/
public static <E> Page<E> offsetPage(int offset, int limit, boolean count) {
Page<E> page = new Page<E>(new int[]{offset, limit}, count);
//当已经执行过orderBy的时候
Page<E> oldPage = getLocalPage();
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
}
/**
* 排序
*
* @param orderBy
*/
public static void orderBy(String orderBy) {
Page<?> page = getLocalPage();
if (page != null) {
page.setOrderBy(orderBy);
if (page.getPageSizeZero() != null && page.getPageSizeZero() && page.getPageSize() == 0) {
page.setOrderByOnly(true);
}
} else {
page = new Page();
page.setOrderBy(orderBy);
page.setOrderByOnly(true);
setLocalPage(page);
}
}
/**
* 设置参数
*
* @param properties 插件属性
*/
protected static void setStaticProperties(Properties properties) {
//defaultCount,这是一个全局生效的参数,多数据源时也是统一的行为
if (properties != null) {
DEFAULT_COUNT = Boolean.valueOf(properties.getProperty("defaultCount", "true"));
}
}
}
| pagehelper/Mybatis-PageHelper | src/main/java/com/github/pagehelper/page/PageMethod.java |
926 | /**
* <p>
* Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。
* </p>
*
* <p>
* Hutool中的工具方法来自于每个用户的精雕细琢,它涵盖了Java开发底层代码中的方方面面,它既是大型项目开发中解决小问题的利器,也是小型项目中的效率担当;<br>
* </p>
*
* <p>Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的bug。</p>
*
* @author looly
*/
package cn.hutool;
| dromara/hutool | hutool-all/src/main/java/cn/hutool/package-info.java |
927 | package cn.hutool.cron.task;
import cn.hutool.cron.pattern.CronPattern;
/**
* 定时作业,此类除了定义了作业,也定义了作业的执行周期以及ID。
*
* @author looly
* @since 5.4.7
*/
public class CronTask implements Task{
private final String id;
private CronPattern pattern;
private final Task task;
/**
* 构造
* @param id ID
* @param pattern 表达式
* @param task 作业
*/
public CronTask(String id, CronPattern pattern, Task task) {
this.id = id;
this.pattern = pattern;
this.task = task;
}
@Override
public void execute() {
task.execute();
}
/**
* 获取作业ID
*
* @return 作业ID
*/
public String getId() {
return id;
}
/**
* 获取表达式
*
* @return 表达式
*/
public CronPattern getPattern() {
return pattern;
}
/**
* 设置新的定时表达式
* @param pattern 表达式
* @return this
*/
public CronTask setPattern(CronPattern pattern){
this.pattern = pattern;
return this;
}
/**
* 获取原始作业
*
* @return 作业
*/
public Task getRaw(){
return this.task;
}
}
| dromara/hutool | hutool-cron/src/main/java/cn/hutool/cron/task/CronTask.java |
928 | package cn.hutool.core.lang.func;
import cn.hutool.core.exceptions.ExceptionUtil;
import java.io.Serializable;
/**
* 只有一个参数的函数对象<br>
* 接口灵感来自于<a href="http://actframework.org/">ActFramework</a><br>
* 一个函数接口代表一个一个函数,用于包装一个函数为对象<br>
* 在JDK8之前,Java的函数并不能作为参数传递,也不能作为返回值存在,此接口用于将一个函数包装成为一个对象,从而传递对象
*
* @author Looly
*
* @param <P> 参数类型
* @param <R> 返回值类型
* @since 4.2.2
*/
@FunctionalInterface
public interface Func1<P, R> extends Serializable {
/**
* 执行函数
*
* @param parameter 参数
* @return 函数执行结果
* @throws Exception 自定义异常
*/
R call(P parameter) throws Exception;
/**
* 执行函数,异常包装为RuntimeException
*
* @param parameter 参数
* @return 函数执行结果
* @since 5.3.6
*/
default R callWithRuntimeException(P parameter){
try {
return call(parameter);
} catch (Exception e) {
throw ExceptionUtil.wrapRuntime(e);
}
}
}
| dromara/hutool | hutool-core/src/main/java/cn/hutool/core/lang/func/Func1.java |
930 | package cn.hutool.core.lang.func;
import cn.hutool.core.exceptions.ExceptionUtil;
import java.io.Serializable;
/**
* 无参数的函数对象<br>
* 接口灵感来自于<a href="http://actframework.org/">ActFramework</a><br>
* 一个函数接口代表一个一个函数,用于包装一个函数为对象<br>
* 在JDK8之前,Java的函数并不能作为参数传递,也不能作为返回值存在,此接口用于将一个函数包装成为一个对象,从而传递对象
*
* @author Looly
*
* @param <R> 返回值类型
* @since 4.5.2
*/
@FunctionalInterface
public interface Func0<R> extends Serializable {
/**
* 执行函数
*
* @return 函数执行结果
* @throws Exception 自定义异常
*/
R call() throws Exception;
/**
* 执行函数,异常包装为RuntimeException
*
* @return 函数执行结果
* @since 5.3.6
*/
default R callWithRuntimeException(){
try {
return call();
} catch (Exception e) {
throw ExceptionUtil.wrapRuntime(e);
}
}
}
| dromara/hutool | hutool-core/src/main/java/cn/hutool/core/lang/func/Func0.java |
931 | package cn.hutool.setting;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.io.resource.NoResourceException;
import cn.hutool.core.map.SafeConcurrentHashMap;
import cn.hutool.core.util.StrUtil;
import java.util.Map;
/**
* Setting工具类<br>
* 提供静态方法获取配置文件
*
* @author looly
*/
public class SettingUtil {
/**
* 配置文件缓存
*/
private static final Map<String, Setting> SETTING_MAP = new SafeConcurrentHashMap<>();
/**
* 获取当前环境下的配置文件<br>
* name可以为不包括扩展名的文件名(默认.setting为结尾),也可以是文件名全称
*
* @param name 文件名,如果没有扩展名,默认为.setting
* @return 当前环境下配置文件
*/
public static Setting get(String name) {
return SETTING_MAP.computeIfAbsent(name, (filePath)->{
final String extName = FileNameUtil.extName(filePath);
if (StrUtil.isEmpty(extName)) {
filePath = filePath + "." + Setting.EXT_NAME;
}
return new Setting(filePath, true);
});
}
/**
* 获取给定路径找到的第一个配置文件<br>
* * name可以为不包括扩展名的文件名(默认.setting为结尾),也可以是文件名全称
*
* @param names 文件名,如果没有扩展名,默认为.setting
*
* @return 当前环境下配置文件
* @since 5.1.3
*/
public static Setting getFirstFound(String... names) {
for (String name : names) {
try {
return get(name);
} catch (NoResourceException e) {
//ignore
}
}
return null;
}
}
| dromara/hutool | hutool-setting/src/main/java/cn/hutool/setting/SettingUtil.java |
934 | E
1522133098
tags: Bit Manipulation
count 一个 32-bit number binary format 里面有多少1
#### Bit Manipulation
- shift >> i
- apply mask & 1
#### Convert to string O(n) space
可以把integer -> string -> char array.
```
/*
LintCode
Count how many 1 in binary representation of a 32-bit integer.
Example
Given 32, return 1
Given 5, return 2
Given 1023, return 9
Challenge
If the integer is n bits with m 1 bits. Can you do it in O(m) time?
Tags Expand
Binary Bit Manipulation
Thoughts:
1. break string into char[]
2. convert char[] into integer using Character.getNumericValue()
*/
/*
Thoughts:
Shift the 32 bit integer and apply mask 1
*/
public class Solution {
public int countOnes(int num) {
int count = 0;
for (int i = 1; i <= 32; i++) {
count += num >> i & 1;
}
return count;
}
};
public class Solution {
/**
* @param num: an integer
* @return: an integer, the number of ones in num
*/
public int countOnes(int num) {
if (num < 0) {
return 0;
}
String bits = Integer.toBinaryString(num);
char[] bitArray = bits.toCharArray();
int sum = 0;
for (int i = 0; i < bitArray.length; i++) {
sum += Character.getNumericValue(bitArray[i]);
}
return sum;
}
};
``` | awangdev/leet-code | Java/Count 1 in Binary.java |
935 | package cn.hutool.core.annotation;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Map;
/**
* <p>注解合成器,用于处理一组给定的与{@link #getSource()}具有直接或间接联系的注解对象,
* 并返回与原始注解对象具有不同属性的“合成”注解。
*
* <p>合成注解一般被用于处理类层级结果中具有直接或间接关联的注解对象,
* 当实例被创建时,会获取到这些注解对象,并使用{@link SynthesizedAnnotationSelector}对类型相同的注解进行过滤,
* 并最终得到类型不重复的有效注解对象。这些有效注解将被包装为{@link SynthesizedAnnotation},
* 然后最终用于“合成”一个{@link SynthesizedAggregateAnnotation}。<br>
* {@link SynthesizedAnnotationSelector}是合成注解生命周期中的第一个钩子,
* 自定义选择器以拦截原始注解被扫描的过程。
*
* <p>当合成注解完成对待合成注解的扫描,并完成了必要属性的加载后,
* 将会按顺序依次调用{@link SynthesizedAnnotationPostProcessor},
* 注解后置处理器允许用于对完成注解的待合成注解进行二次调整,
* 该钩子一般用于根据{@link Link}注解对属性进行调整。<br>
* {@link SynthesizedAnnotationPostProcessor}是合成注解生命周期中的第二个钩子,
* 自定义后置处理器以拦截原始在转为待合成注解后的初始化过程。
*
* <p>使用{@link #synthesize(Class)}用于获取“合成”后的注解,
* 该注解对象的属性可能会与原始的对象属性不同。
*
* @author huangchengxing
*/
public interface AnnotationSynthesizer {
/**
* 获取合成注解来源最初来源
*
* @return 合成注解来源最初来源
*/
Object getSource();
/**
* 合成注解选择器
*
* @return 注解选择器
*/
SynthesizedAnnotationSelector getAnnotationSelector();
/**
* 获取合成注解后置处理器
*
* @return 合成注解后置处理器
*/
Collection<SynthesizedAnnotationPostProcessor> getAnnotationPostProcessors();
/**
* 获取已合成的注解
*
* @param annotationType 注解类型
* @return 已合成的注解
*/
SynthesizedAnnotation getSynthesizedAnnotation(Class<?> annotationType);
/**
* 获取全部的合成注解
*
* @return 合成注解
*/
Map<Class<? extends Annotation>, SynthesizedAnnotation> getAllSynthesizedAnnotation();
/**
* 获取合成注解
*
* @param annotationType 注解类型
* @param <T> 注解类型
* @return 类型
*/
<T extends Annotation> T synthesize(Class<T> annotationType);
}
| dromara/hutool | hutool-core/src/main/java/cn/hutool/core/annotation/AnnotationSynthesizer.java |
940 | package base.scope;
import base.Student;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
/**
* {@link org.springframework.beans.factory.config.Scope}简单实现,每调用一次变返回一个
* 新的对象.
*
* @author skywalker
*/
public class OneScope implements Scope {
private int index = 0;
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
System.out.println("get被调用");
return new Student("skywalker-" + (index++), index);
}
@Override
public Object remove(String name) {
return null;
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return null;
}
}
| seaswalker/spring-analysis | src/main/java/base/scope/OneScope.java |
942 | package org.ansj.util;
import org.ansj.domain.Term;
import org.ansj.library.NatureLibrary;
import org.ansj.library.NgramLibrary;
import org.ansj.recognition.impl.NatureRecognition.NatureTerm;
import java.util.Map;
public class MathUtil {
// 平滑参数
private static final double dSmoothingPara = 0.1;
// 分隔符我最喜欢的
private static final String TAB = "\t";
// 一个参数
private static final int MAX_FREQUENCE = 2079997;// 7528283+329805;
// Two linked Words frequency
private static final double dTemp = (double) 1 / MAX_FREQUENCE;
/**
* 从一个词的词性到另一个词的词的分数
*
* @param from
* 前面的词
* @param to
* 后面的词
* @return 分数
*/
public static double compuScore(Term from, Term to, Map<String, Double> relationMap) {
double frequency = from.termNatures().allFreq + 1;
if (frequency < 0) {
double score = from.score() + MAX_FREQUENCE;
from.score(score);
return score;
}
double nTwoWordsFreq = NgramLibrary.getTwoWordFreq(from, to);
if (relationMap != null) {
Double d = relationMap.get(from.getName() + TAB + to.getName());
if (d != null) {
nTwoWordsFreq += d;
}
}
double value = -Math.log(dSmoothingPara * frequency / (MAX_FREQUENCE + 80000) + (1 - dSmoothingPara) * ((1 - dTemp) * nTwoWordsFreq / frequency + dTemp));
if (value < 0) {
value += frequency;
}
return from.score() + value;
}
/**
* 词性词频词长.计算出来一个分数
*
* @param from
* @param term
* @return
*/
public static double compuScoreFreq(Term from, Term term) {
return from.termNatures().allFreq + term.termNatures().allFreq;
}
/**
* 两个词性之间的分数计算
*
* @param from
* @param to
* @return
*/
public static double compuNatureFreq(NatureTerm from, NatureTerm to) {
double twoWordFreq = NatureLibrary.getTwoNatureFreq(from.termNature.nature, to.termNature.nature);
if (twoWordFreq == 0) {
twoWordFreq = Math.log(from.selfScore + to.selfScore);
}
double score = from.score + Math.log((from.selfScore + to.selfScore) * twoWordFreq) + to.selfScore;
return score;
}
public static double lnSum(float... fs) {
double result = 0 ;
for (int i =0 ;i<fs.length ;i++) {
result += -Math.log(fs[i]);
}
return result;
}
}
| NLPchina/ansj_seg | src/main/java/org/ansj/util/MathUtil.java |
943 | package com.springboot.util;
import javax.servlet.http.HttpServletRequest;
public class IPUtils {
/**
* 获取IP地址
*
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
}
| wuyouzhuguli/SpringAll | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/util/IPUtils.java |
945 | package com.xkcoding.ratelimit.redis.util;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* <p>
* IP 工具类
* </p>
*
* @author yangkai.shen
* @date Created in 2019-09-30 10:38
*/
@Slf4j
public class IpUtil {
private final static String UNKNOWN = "unknown";
private final static int MAX_LENGTH = 15;
/**
* 获取IP地址
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StrUtil.isEmpty(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
log.error("IPUtils ERROR ", e);
}
// 使用代理,则获取第一个IP地址
if (!StrUtil.isEmpty(ip) && ip.length() > MAX_LENGTH) {
if (ip.indexOf(StrUtil.COMMA) > 0) {
ip = ip.substring(0, ip.indexOf(StrUtil.COMMA));
}
}
return ip;
}
}
| xkcoding/spring-boot-demo | demo-ratelimit-redis/src/main/java/com/xkcoding/ratelimit/redis/util/IpUtil.java |
946 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2023 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.pagehelper.parser;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParser;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.parser.ParseException;
import net.sf.jsqlparser.statement.Statement;
/**
* 为了能自己控制是否使用单线程池,是否支持超时控制,所以自己实现了一个
*
* @author liuzh
*/
public interface SqlParser {
/**
* 不使用单线程池,不支持超时控制
*/
SqlParser DEFAULT = statementReader -> {
CCJSqlParser parser = CCJSqlParserUtil.newParser(statementReader);
parser.withSquareBracketQuotation(true);
return parser.Statement();
};
/**
* 解析 SQL
*
* @param statementReader SQL
* @return
* @throws JSQLParserException
*/
Statement parse(String statementReader) throws JSQLParserException, ParseException;
}
| pagehelper/Mybatis-PageHelper | src/main/java/com/github/pagehelper/parser/SqlParser.java |
948 | /*
* Copyright 2024 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.http;
import org.springframework.http.HttpStatus;
import java.util.LinkedList;
import java.util.List;
/**
* 一个Response中包含多个ResponseEntity
*/
public class MultiResponseEntity<T> {
private int code;
private List<RichResponseEntity<T>> entities = new LinkedList<>();
private MultiResponseEntity(HttpStatus httpCode) {
this.code = httpCode.value();
}
public static <T> MultiResponseEntity<T> instance(HttpStatus statusCode) {
return new MultiResponseEntity<>(statusCode);
}
public static <T> MultiResponseEntity<T> ok() {
return new MultiResponseEntity<>(HttpStatus.OK);
}
public void addResponseEntity(RichResponseEntity<T> responseEntity) {
if (responseEntity == null){
throw new IllegalArgumentException("sub response entity can not be null");
}
entities.add(responseEntity);
}
}
| apolloconfig/apollo | apollo-common/src/main/java/com/ctrip/framework/apollo/common/http/MultiResponseEntity.java |
949 | /*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
This source code is licensed under the Apache License Version 2.0.*/
package apijson.orm.model;
import static apijson.orm.AbstractVerifier.ADMIN;
import static apijson.orm.AbstractVerifier.LOGIN;
import java.io.Serializable;
import java.sql.Timestamp;
import apijson.MethodAccess;
/**测试结果。5.0.0 之后可能改名为 Test
* @author Lemon
*/
@MethodAccess(GET = { LOGIN, ADMIN }, HEAD = { LOGIN, ADMIN })
public class TestRecord implements Serializable {
private static final long serialVersionUID = 1L;
private Long id; //唯一标识
private Long userId; //用户id
private Long documentId; //测试用例文档id
private Timestamp date; //创建日期
private String compare; //对比结果
private String response; //接口返回结果JSON 用json格式会导致强制排序,而请求中引用赋值只能引用上面的字段,必须有序。
private String standard; //response 的校验标准,是一个 JSON 格式的 AST ,描述了正确 Response 的结构、里面的字段名称、类型、长度、取值范围 等属性。
public TestRecord() {
super();
}
public TestRecord(long id) {
this();
setId(id);
}
public Long getId() {
return id;
}
public TestRecord setId(Long id) {
this.id = id;
return this;
}
public Long getUserId() {
return userId;
}
public TestRecord setUserId(Long userId) {
this.userId = userId;
return this;
}
public Long getDocumentId() {
return documentId;
}
public TestRecord setDocumentId(Long documentId) {
this.documentId = documentId;
return this;
}
public Timestamp getDate() {
return date;
}
public TestRecord setDate(Timestamp date) {
this.date = date;
return this;
}
public String getCompare() {
return compare;
}
public TestRecord setCompare(String compare) {
this.compare = compare;
return this;
}
public String getResponse() {
return response;
}
public TestRecord setResponse(String response) {
this.response = response;
return this;
}
public String getStandard() {
return standard;
}
public TestRecord setStandard(String standard) {
this.standard = standard;
return this;
}
} | Tencent/APIJSON | APIJSONORM/src/main/java/apijson/orm/model/TestRecord.java |
950 | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.base;
import android.app.Application;
import android.content.Context;
import androidx.annotation.NonNull;
import com.jess.arms.base.delegate.AppDelegate;
import com.jess.arms.base.delegate.AppLifecycles;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.Preconditions;
/**
* ================================================
* MVPArms 是一个整合了大量主流开源项目的 Android MVP 快速搭建框架, 其中包含 Dagger2、Retrofit、RxJava 以及
* RxLifecycle、RxCache 等 Rx 系三方库, 并且提供 UI 自适应方案, 本框架将它们结合起来, 并全部使用 Dagger2 管理
* 并提供给开发者使用, 使用本框架开发您的项目, 就意味着您已经拥有一个 MVP + Dagger2 + Retrofit + RxJava 项目
*
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki">请配合官方 Wiki 文档学习本框架</a>
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki/UpdateLog">更新日志, 升级必看!</a>
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki/Issues">常见 Issues, 踩坑必看!</a>
* @see <a href="https://github.com/JessYanCoding/ArmsComponent/wiki">MVPArms 官方组件化方案 ArmsComponent, 进阶指南!</a>
* Created by JessYan on 22/03/2016
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class BaseApplication extends Application implements App {
private AppLifecycles mAppDelegate;
/**
* 这里会在 {@link BaseApplication#onCreate} 之前被调用,可以做一些较早的初始化
* 常用于 MultiDex 以及插件化框架的初始化
*
* @param base
*/
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
if (mAppDelegate == null) {
this.mAppDelegate = new AppDelegate(base);
}
this.mAppDelegate.attachBaseContext(base);
}
@Override
public void onCreate() {
super.onCreate();
if (mAppDelegate != null) {
this.mAppDelegate.onCreate(this);
}
}
/**
* 在模拟环境中程序终止时会被调用
*/
@Override
public void onTerminate() {
super.onTerminate();
if (mAppDelegate != null) {
this.mAppDelegate.onTerminate(this);
}
}
/**
* 将 {@link AppComponent} 返回出去, 供其它地方使用, {@link AppComponent} 接口中声明的方法所返回的实例, 在 {@link #getAppComponent()} 拿到对象后都可以直接使用
*
* @return AppComponent
* @see ArmsUtils#obtainAppComponentFromContext(Context) 可直接获取 {@link AppComponent}
*/
@NonNull
@Override
public AppComponent getAppComponent() {
Preconditions.checkNotNull(mAppDelegate, "%s cannot be null", AppDelegate.class.getName());
Preconditions.checkState(mAppDelegate instanceof App, "%s must be implements %s", mAppDelegate.getClass().getName(), App.class.getName());
return ((App) mAppDelegate).getAppComponent();
}
}
| JessYanCoding/MVPArms | arms/src/main/java/com/jess/arms/base/BaseApplication.java |
951 | package practice;
/**
* @program: leetcode
* @description:
* @author: [email protected]
* @create: 2022-06-30 22:33
**/
public class L0021 {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
// 异常处理之一:list1为空,返回list2
if (null==list1) {
return list2;
}
// 异常处理之二:list2为空,返回list1
if (null==list2) {
return list1;
}
// 现在,只需要处理list1和list2都不为空的情况
// 返回值是个新的链表
ListNode rlt = new ListNode();
// 返回链表的最后一个元素
ListNode rltTail = rlt;
// 一旦有一个指针移动到尾部,就不需要再比较了,while就结束了
while (null!=list1 && null!=list2) {
// 比较两个指针指向的对象的值,将小的放入返回链表,并且指针往后移动一次
if(list1.val<=list2.val) {
// 让返回链表的尾部连接到一号指针指向的元素
rltTail.next = list1;
// 一号指针指向下一个
list1 = list1.next;
} else {
// 让返回链表的尾部连接到二号指针指向的元素
rltTail.next = list2;
// 二号指针指向下一个
list2 = list2.next;
}
// 刚刚新增一条记录,尾部指针往后移动
rltTail = rltTail.next;
}
// 如果一号链表已经遍历完成,那么此时只要将返回链表的指正连接到二号链表即可
if(null==list1) {
rltTail.next = list2;
} else {
rltTail.next = list1;
}
// 注意rlt的第一个节点是new出来的,不是链表1或者链表2的内容,所以返回的时候,要从rlt.next返回
return rlt.next;
}
public static void main(String[] args) {
ListNode list1 = new ListNode(1);
list1.next = new ListNode(2);
list1.next.next = new ListNode(4);
ListNode list2 = new ListNode(1);
list2.next = new ListNode(3);
list2.next.next = new ListNode(4);
Tools.print(new L0021().mergeTwoLists(list1, list2));
}
}
| zq2599/blog_demos | leetcode/src/practice/L0021.java |
954 | /*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dianping.cat;
import com.dianping.cat.analyzer.MetricTagAggregator;
import com.dianping.cat.analyzer.TransactionAggregator;
import com.dianping.cat.configuration.ApplicationEnvironment;
import com.dianping.cat.configuration.ClientConfigProvider;
import com.dianping.cat.configuration.client.entity.ClientConfig;
import com.dianping.cat.configuration.client.entity.Server;
import com.dianping.cat.configuration.client.transform.DefaultSaxParser;
import com.dianping.cat.log.CatLogger;
import com.dianping.cat.message.Trace;
import com.dianping.cat.message.internal.*;
import com.dianping.cat.util.Properties;
import com.dianping.cat.util.StringUtils;
import com.dianping.cat.util.Threads;
import com.dianping.cat.analyzer.EventAggregator;
import com.dianping.cat.analyzer.LocalAggregator;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.MessageProducer;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.io.TcpSocketSender;
import com.dianping.cat.message.spi.MessageManager;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.status.StatusUpdateTask;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
public class Cat {
private static MessageProducer producer;
private static MessageManager manager;
private static int errorCount;
private static final Cat instance = new Cat();
private static volatile boolean init = false;
private static volatile boolean enabled = true;
private static volatile boolean JSTACK_ENABLED = true;
private static volatile boolean MULTI_INSTANCES = false;
private static volatile boolean DATASOURCE_MONITOR_ENABLED = true;
public final static String CLIENT_CONFIG = "cat-client-config";
public final static String UNKNOWN = "unknown";
public static boolean isJstackEnabled() {
String enable = Properties.forString().fromEnv().fromSystem().getProperty("jstack_enable", "true");
return JSTACK_ENABLED && Boolean.valueOf(enable);
}
private static void checkAndInitialize() {
try {
if (!init) {
ClientConfig clientConfig = getSpiClientConfig();
if (clientConfig == null) {
initializeInternal();
} else {
initializeInternal(clientConfig);
}
}
} catch (Exception e) {
errorHandler(e);
}
}
private static ClientConfig getSpiClientConfig() {
ServiceLoader<ClientConfigProvider> clientConfigProviders = ServiceLoader.load(ClientConfigProvider.class);
if (clientConfigProviders == null) {
return null;
}
Iterator<ClientConfigProvider> iterator = clientConfigProviders.iterator();
if (iterator.hasNext()){
//只支持一个ClientConfigProvider的实现,默认取查询结果第一个
ClientConfigProvider clientConfigProvider = (ClientConfigProvider)iterator.next();
return clientConfigProvider.getClientConfig();
} else {
return null;
}
}
public static String createMessageId() {
if (isEnabled()) {
try {
return Cat.getProducer().createMessageId();
} catch (Exception e) {
errorHandler(e);
return NullMessageProducer.NULL_MESSAGE_PRODUCER.createMessageId();
}
} else {
return NullMessageProducer.NULL_MESSAGE_PRODUCER.createMessageId();
}
}
public static void enable() {
enabled = true;
}
public static void disable() {
enabled = false;
}
/**
* disable datasource auto monitor
*/
public static void disableDataSourceMonitor() {
DATASOURCE_MONITOR_ENABLED = false;
}
public static void disableJstack() {
JSTACK_ENABLED = false;
}
public static void disableMultiInstances() {
MULTI_INSTANCES = false;
}
public static void enableMultiInstances() {
MULTI_INSTANCES = true;
}
private static void errorHandler(Exception e) {
if (isEnabled() && errorCount < 3) {
errorCount++;
CatLogger.getInstance().error(e.getMessage(), e);
}
}
public static String getCatHome() {
return Properties.forString().fromEnv().fromSystem().getProperty("CAT_HOME", "/data/appdatas/cat/");
}
public static String getCurrentMessageId() {
if (isEnabled()) {
try {
MessageTree tree = Cat.getManager().getThreadLocalMessageTree();
if (tree != null) {
String messageId = tree.getMessageId();
if (messageId == null) {
messageId = Cat.getProducer().createMessageId();
tree.setMessageId(messageId);
}
return messageId;
} else {
return null;
}
} catch (Exception e) {
errorHandler(e);
return NullMessageProducer.NULL_MESSAGE_PRODUCER.createMessageId();
}
} else {
return NullMessageProducer.NULL_MESSAGE_PRODUCER.createMessageId();
}
}
private static String getCustomDomain() {
String config = System.getProperty(Cat.CLIENT_CONFIG);
if (StringUtils.isNotEmpty(config)) {
try {
ClientConfig clientConfig = DefaultSaxParser.parse(config);
return clientConfig.getDomain();
} catch (Exception e) {
// ignore
}
}
return null;
}
public static Cat getInstance() {
return instance;
}
public static MessageManager getManager() {
try {
checkAndInitialize();
if (manager != null) {
return manager;
} else {
return NullMessageManager.NULL_MESSAGE_MANAGER;
}
} catch (Exception e) {
errorHandler(e);
return NullMessageManager.NULL_MESSAGE_MANAGER;
}
}
public static MessageProducer getProducer() {
try {
checkAndInitialize();
if (producer != null) {
return producer;
} else {
return NullMessageProducer.NULL_MESSAGE_PRODUCER;
}
} catch (Exception e) {
errorHandler(e);
return NullMessageProducer.NULL_MESSAGE_PRODUCER;
}
}
public static void initialize() {
checkAndInitialize();
}
public static void initialize(String... servers) {
if (isEnabled() && !init) {
try {
ClientConfig config = new ClientConfig();
for (String server : servers) {
config.addServer(new Server(server));
}
final String domain = ApplicationEnvironment.loadAppName(UNKNOWN);
config.setDomain(domain);
initializeInternal(config);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void initializeByDomain(String domain) {
if (isEnabled() && !init) {
try {
String domainName = ApplicationEnvironment.loadAppName(domain);
ClientConfig config = ApplicationEnvironment.loadClientConfig(domainName);
initializeInternal(config);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void initializeByDomain(String domain, int port, int httpPort, String... servers) {
if (isEnabled() && !init) {
try {
ClientConfig config = new ClientConfig();
config.setDomain(ApplicationEnvironment.loadAppName(domain));
for (String server : servers) {
Server serverObj = new Server(server);
serverObj.setHttpPort(httpPort);
serverObj.setPort(port);
config.addServer(serverObj);
}
initializeInternal(config);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void initializeByDomain(String domain, String... servers) {
if (isEnabled() && !init) {
try {
initializeByDomain(domain, 2280, 8080, servers);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void initializeByDomainForce(String domain) {
if (isEnabled() && !init) {
try {
ClientConfig config = ApplicationEnvironment.loadClientConfig(domain);
initializeInternal(config);
} catch (Exception e) {
errorHandler(e);
}
}
}
private static void initializeInternal() {
validate();
if (isEnabled()) {
try {
if (!init) {
synchronized (instance) {
if (!init) {
producer = DefaultMessageProducer.getInstance();
manager = DefaultMessageManager.getInstance();
StatusUpdateTask heartbeatTask = new StatusUpdateTask();
TcpSocketSender messageSender = TcpSocketSender.getInstance();
Threads.forGroup("cat").start(heartbeatTask);
Threads.forGroup("cat").start(messageSender);
Threads.forGroup("cat").start(new LocalAggregator.DataUploader());
CatLogger.getInstance().info("Cat is lazy initialized!");
init = true;
}
}
}
} catch (Exception e) {
errorHandler(e);
disable();
}
}
}
private static void initializeInternal(ClientConfig config) {
if (isEnabled()) {
System.setProperty(Cat.CLIENT_CONFIG, config.toString());
CatLogger.getInstance().info("init cat with config:" + config.toString());
initializeInternal();
}
}
public static boolean isDataSourceMonitorEnabled() {
return DATASOURCE_MONITOR_ENABLED;
}
public static boolean isEnabled() {
return enabled;
}
public static boolean isInitialized() {
return init;
}
public static boolean isMultiInstanceEnable() {
return MULTI_INSTANCES;
}
/**
* Log batch event in one shot with SUCCESS status.
*
* @param type event type
* @param name event name
* @param error error count
* @param count total count , failure% = error/total
*/
public static void logBatchEvent(String type, String name, int count, int error) {
if (isEnabled()) {
try {
EventAggregator.getInstance().logBatchEvent(type, name, count, error);
} catch (Exception e) {
errorHandler(e);
}
}
}
/**
* log batch transaction with type name
*
* @param type transaction type
* @param name transaction name
* @param error error count
* @param count total count, failure% = error/total
* @param sum avg = sum/total sum in milliseconds
*/
public static void logBatchTransaction(String type, String name, int count, int error, long sum) {
if (isEnabled()) {
TransactionAggregator.getInstance().logBatchTransaction(type, name, count, error, sum);
}
}
public static void logError(String message, Throwable cause) {
if (isEnabled()) {
try {
Cat.getProducer().logError(message, cause);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logError(Throwable cause) {
if (isEnabled()) {
try {
Cat.getProducer().logError(cause);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logErrorWithCategory(String category, String message, Throwable cause) {
if (isEnabled()) {
try {
Cat.getProducer().logErrorWithCategory(category, message, cause);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logErrorWithCategory(String category, Throwable cause) {
if (isEnabled()) {
try {
Cat.getProducer().logErrorWithCategory(category, cause);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logEvent(String type, String name) {
if (isEnabled()) {
try {
Cat.getProducer().logEvent(type, name);
} catch (Exception e) {
errorHandler(e);
}
}
}
/**
* Log an event in one shot.
*
* @param type event type
* @param name event name
* @param status "0" means success, otherwise means error code
* @param nameValuePairs name value pairs in the format of "a=1&b=2&..."
*/
public static void logEvent(String type, String name, String status, String nameValuePairs) {
if (isEnabled()) {
try {
Cat.getProducer().logEvent(type, name, status, nameValuePairs);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logMetricForCount(String name) {
logMetricForCount(name, null);
}
public static void logMetricForCount(String name, int quantity) {
logMetricForCount(name, quantity, null);
}
public static void logMetricForCount(String name, int quantity, Map<String, String> tags) {
if (isEnabled()) {
checkAndInitialize();
try {
MetricTagAggregator.getInstance().addCountMetric(name, quantity, tags);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logMetricForCount(String name, Map<String, String> tags) {
if (isEnabled()) {
checkAndInitialize();
try {
MetricTagAggregator.getInstance().addCountMetric(name, 1, tags);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logMetricForDuration(String name, long durationInMillis) {
logMetricForDuration(name, durationInMillis, null);
}
public static void logMetricForDuration(String name, long durationInMillis, Map<String, String> tags) {
if (isEnabled()) {
checkAndInitialize();
try {
MetricTagAggregator.getInstance().addTimerMetric(name, durationInMillis, tags);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logRemoteCallClient(Context ctx) {
if (isEnabled()) {
try {
logRemoteCallClient(ctx, "default");
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logRemoteCallClient(Context ctx, String domain) {
if (isEnabled()) {
try {
MessageTree tree = Cat.getManager().getThreadLocalMessageTree();
String messageId = tree.getMessageId();
if (messageId == null) {
messageId = Cat.getProducer().createMessageId();
tree.setMessageId(messageId);
}
String childId = Cat.getProducer().createRpcServerId(domain);
Cat.logEvent(CatConstants.TYPE_REMOTE_CALL, "", Event.SUCCESS, childId);
String root = tree.getRootMessageId();
if (root == null) {
root = messageId;
}
ctx.addProperty(Context.ROOT, root);
ctx.addProperty(Context.PARENT, messageId);
ctx.addProperty(Context.CHILD, childId);
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void logRemoteCallServer(Context ctx) {
if (isEnabled()) {
try {
MessageTree tree = Cat.getManager().getThreadLocalMessageTree();
String childId = ctx.getProperty(Context.CHILD);
String rootId = ctx.getProperty(Context.ROOT);
String parentId = ctx.getProperty(Context.PARENT);
if (parentId != null) {
tree.setParentMessageId(parentId);
}
if (rootId != null) {
tree.setRootMessageId(rootId);
}
if (childId != null) {
tree.setMessageId(childId);
}
} catch (Exception e) {
errorHandler(e);
}
}
}
public static void newCompletedTransactionWithDuration(String type, String name, long duration) {
if (isEnabled()) {
try {
final Transaction transaction = Cat.getProducer().newTransaction(type, name);
try {
transaction.setDurationInMillis(duration);
if (duration > 0 && duration < 60 * 1000) {
transaction.setTimestamp(System.currentTimeMillis() - duration);
}
transaction.setStatus(Transaction.SUCCESS);
} catch (Exception e) {
transaction.setStatus(e);
} finally {
transaction.complete();
}
} catch (Exception e) {
errorHandler(e);
}
}
}
public static Event newEvent(String type, String name) {
if (isEnabled()) {
try {
return Cat.getProducer().newEvent(type, name);
} catch (Exception e) {
errorHandler(e);
return NullMessage.EVENT;
}
} else {
return NullMessage.EVENT;
}
}
public static Trace newTrace(String type, String name) {
if (isEnabled()) {
try {
return Cat.getProducer().newTrace(type, name);
} catch (Exception e) {
errorHandler(e);
return NullMessage.TRACE;
}
} else {
return NullMessage.TRACE;
}
}
/**
* Create a new transaction with given type and name.
*
* @param type transaction type
* @param name transaction name
*/
public static Transaction newTransaction(String type, String name) {
if (isEnabled()) {
try {
return Cat.getProducer().newTransaction(type, name);
} catch (Exception e) {
errorHandler(e);
return NullMessage.TRANSACTION;
}
} else {
return NullMessage.TRANSACTION;
}
}
/**
* Create a new transaction with given type and name and duration, duration time in millisecond
*
* @param type transaction type
* @param name transaction name
*/
public static Transaction newTransactionWithDuration(String type, String name, long duration) {
if (isEnabled()) {
try {
final Transaction transaction = Cat.getProducer().newTransaction(type, name);
transaction.setDurationInMillis(duration);
if (duration < 60 * 1000) {
transaction.setTimestamp(System.currentTimeMillis() - duration);
}
return transaction;
} catch (Exception e) {
errorHandler(e);
return NullMessage.TRANSACTION;
}
} else {
return NullMessage.TRANSACTION;
}
}
private static void validate() {
String enable = Properties.forString().fromEnv().fromSystem().getProperty("CAT_ENABLED", "true");
if ("false".equals(enable)) {
CatLogger.getInstance().info("CAT is disable due to system environment CAT_ENABLED is false.");
enabled = false;
} else {
String customDomain = getCustomDomain();
if (customDomain == null && UNKNOWN.equals(ApplicationEnvironment.loadAppName(UNKNOWN))) {
CatLogger.getInstance().info("CAT is disable due to no app name in resource file /META-INF/app.properties");
enabled = false;
}
}
}
private Cat() {
}
public interface Context {
String ROOT = "_catRootMessageId";
String PARENT = "_catParentMessageId";
String CHILD = "_catChildMessageId";
String DISCARD = "_catDiscard";
void addProperty(String key, String value);
String getProperty(String key);
}
}
| dianping/cat | lib/java/src/main/java/com/dianping/cat/Cat.java |
956 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.sys.web;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
/**
* 用户Controller
* @author ThinkGem
* @version 2013-8-29
*/
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {
@Autowired
private SystemService systemService;
@ModelAttribute
public User get(@RequestParam(required=false) String id) {
if (StringUtils.isNotBlank(id)){
return systemService.getUser(id);
}else{
return new User();
}
}
@RequiresPermissions("sys:user:view")
@RequestMapping(value = {"index"})
public String index(User user, Model model) {
return "modules/sys/userIndex";
}
@RequiresPermissions("sys:user:view")
@RequestMapping(value = {"list", ""})
public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<User> page = systemService.findUser(new Page<User>(request, response), user);
model.addAttribute("page", page);
return "modules/sys/userList";
}
@ResponseBody
@RequiresPermissions("sys:user:view")
@RequestMapping(value = {"listData"})
public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<User> page = systemService.findUser(new Page<User>(request, response), user);
return page;
}
@RequiresPermissions("sys:user:view")
@RequestMapping(value = "form")
public String form(User user, Model model) {
if (user.getCompany()==null || user.getCompany().getId()==null){
user.setCompany(UserUtils.getUser().getCompany());
}
if (user.getOffice()==null || user.getOffice().getId()==null){
user.setOffice(UserUtils.getUser().getOffice());
}
model.addAttribute("user", user);
model.addAttribute("allRoles", systemService.findAllRole());
return "modules/sys/userForm";
}
@RequiresPermissions("sys:user:edit")
@RequestMapping(value = "save")
public String save(User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
if(Global.isDemoMode()){
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/user/list?repage";
}
// 修正引用赋值问题,不知道为何,Company和Office引用的一个实例地址,修改了一个,另外一个跟着修改。
user.setCompany(new Office(request.getParameter("company.id")));
user.setOffice(new Office(request.getParameter("office.id")));
// 如果新密码为空,则不更换密码
if (StringUtils.isNotBlank(user.getNewPassword())) {
user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
}
if (!beanValidator(model, user)){
return form(user, model);
}
if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
addMessage(model, "保存用户'" + user.getLoginName() + "'失败,登录名已存在");
return form(user, model);
}
// 角色数据有效性验证,过滤不在授权内的角色
List<Role> roleList = Lists.newArrayList();
List<String> roleIdList = user.getRoleIdList();
for (Role r : systemService.findAllRole()){
if (roleIdList.contains(r.getId())){
roleList.add(r);
}
}
user.setRoleList(roleList);
// 保存用户信息
systemService.saveUser(user);
// 清除当前用户缓存
if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
UserUtils.clearCache(UserUtils.getUser());
//UserUtils.getCacheMap().clear();
}
addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
return "redirect:" + adminPath + "/sys/user/list?repage";
}
@RequiresPermissions("sys:user:edit")
@RequestMapping(value = "delete")
public String delete(User user, RedirectAttributes redirectAttributes) {
if(Global.isDemoMode()){
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/user/list?repage";
}
if (UserUtils.getUser().getId().equals(user.getId())){
addMessage(redirectAttributes, "删除用户失败, 不允许删除当前用户");
}else if (User.isAdmin(user.getId())){
addMessage(redirectAttributes, "删除用户失败, 不允许删除超级管理员用户");
}else{
systemService.deleteUser(user);
addMessage(redirectAttributes, "删除用户成功");
}
return "redirect:" + adminPath + "/sys/user/list?repage";
}
/**
* 导出用户数据
* @param user
* @param request
* @param response
* @param redirectAttributes
* @return
*/
@RequiresPermissions("sys:user:view")
@RequestMapping(value = "export", method=RequestMethod.POST)
public String exportFile(User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
String fileName = "用户数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose();
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "导出用户失败!失败信息:"+e.getMessage());
}
return "redirect:" + adminPath + "/sys/user/list?repage";
}
/**
* 导入用户数据
* @param file
* @param redirectAttributes
* @return
*/
@RequiresPermissions("sys:user:edit")
@RequestMapping(value = "import", method=RequestMethod.POST)
public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
if(Global.isDemoMode()){
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/user/list?repage";
}
try {
int successNum = 0;
int failureNum = 0;
StringBuilder failureMsg = new StringBuilder();
ImportExcel ei = new ImportExcel(file, 1, 0);
List<User> list = ei.getDataList(User.class);
for (User user : list){
try{
if ("true".equals(checkLoginName("", user.getLoginName()))){
user.setPassword(SystemService.entryptPassword("123456"));
BeanValidators.validateWithException(validator, user);
systemService.saveUser(user);
successNum++;
}else{
failureMsg.append("<br/>登录名 "+user.getLoginName()+" 已存在; ");
failureNum++;
}
}catch(ConstraintViolationException ex){
failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败:");
List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
for (String message : messageList){
failureMsg.append(message+"; ");
failureNum++;
}
}catch (Exception ex) {
failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败:"+ex.getMessage());
}
}
if (failureNum>0){
failureMsg.insert(0, ",失败 "+failureNum+" 条用户,导入信息如下:");
}
addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);
} catch (Exception e) {
addMessage(redirectAttributes, "导入用户失败!失败信息:"+e.getMessage());
}
return "redirect:" + adminPath + "/sys/user/list?repage";
}
/**
* 下载导入用户数据模板
* @param response
* @param redirectAttributes
* @return
*/
@RequiresPermissions("sys:user:view")
@RequestMapping(value = "import/template")
public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
String fileName = "用户数据导入模板.xlsx";
List<User> list = Lists.newArrayList(); list.add(UserUtils.getUser());
new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "导入模板下载失败!失败信息:"+e.getMessage());
}
return "redirect:" + adminPath + "/sys/user/list?repage";
}
/**
* 验证登录名是否有效
* @param oldLoginName
* @param loginName
* @return
*/
@ResponseBody
@RequiresPermissions("sys:user:edit")
@RequestMapping(value = "checkLoginName")
public String checkLoginName(String oldLoginName, String loginName) {
if (loginName !=null && loginName.equals(oldLoginName)) {
return "true";
} else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
return "true";
}
return "false";
}
/**
* 用户信息显示及保存
* @param user
* @param model
* @return
*/
@RequiresPermissions("user")
@RequestMapping(value = "info")
public String info(User user, HttpServletResponse response, Model model) {
User currentUser = UserUtils.getUser();
if (StringUtils.isNotBlank(user.getName())){
if(Global.isDemoMode()){
model.addAttribute("message", "演示模式,不允许操作!");
return "modules/sys/userInfo";
}
currentUser.setEmail(user.getEmail());
currentUser.setPhone(user.getPhone());
currentUser.setMobile(user.getMobile());
currentUser.setRemarks(user.getRemarks());
currentUser.setPhoto(user.getPhoto());
systemService.updateUserInfo(currentUser);
model.addAttribute("message", "保存用户信息成功");
}
model.addAttribute("user", currentUser);
//修改Global 没有私有构造函数,实现懒汉式单例模式.在第一次调用的时候实例化自己!
model.addAttribute("Global", Global.getInstance());
return "modules/sys/userInfo";
}
/**
* 返回用户信息
* @return
*/
@RequiresPermissions("user")
@ResponseBody
@RequestMapping(value = "infoData")
public User infoData() {
return UserUtils.getUser();
}
/**
* 修改个人用户密码
* @param oldPassword
* @param newPassword
* @param model
* @return
*/
@RequiresPermissions("user")
@RequestMapping(value = "modifyPwd")
public String modifyPwd(String oldPassword, String newPassword, Model model) {
User user = UserUtils.getUser();
if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
if(Global.isDemoMode()){
model.addAttribute("message", "演示模式,不允许操作!");
return "modules/sys/userModifyPwd";
}
if (SystemService.validatePassword(oldPassword, user.getPassword())){
systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
model.addAttribute("message", "修改密码成功");
}else{
model.addAttribute("message", "修改密码失败,旧密码错误");
}
}
model.addAttribute("user", user);
return "modules/sys/userModifyPwd";
}
@RequiresPermissions("user")
@ResponseBody
@RequestMapping(value = "treeData")
public List<Map<String, Object>> treeData(@RequestParam(required=false) String officeId, HttpServletResponse response) {
List<Map<String, Object>> mapList = Lists.newArrayList();
List<User> list = systemService.findUserByOfficeId(officeId);
for (int i=0; i<list.size(); i++){
User e = list.get(i);
Map<String, Object> map = Maps.newHashMap();
map.put("id", "u_"+e.getId());
map.put("pId", officeId);
map.put("name", StringUtils.replace(e.getName(), " ", ""));
mapList.add(map);
}
return mapList;
}
// @InitBinder
// public void initBinder(WebDataBinder b) {
// b.registerCustomEditor(List.class, "roleList", new PropertyEditorSupport(){
// @Autowired
// private SystemService systemService;
// @Override
// public void setAsText(String text) throws IllegalArgumentException {
// String[] ids = StringUtils.split(text, ",");
// List<Role> roles = new ArrayList<Role>();
// for (String id : ids) {
// Role role = systemService.getRole(Long.valueOf(id));
// roles.add(role);
// }
// setValue(roles);
// }
// @Override
// public String getAsText() {
// return Collections3.extractToString((List) getValue(), "id", ",");
// }
// });
// }
}
| thinkgem/jeesite | src/main/java/com/thinkgem/jeesite/modules/sys/web/UserController.java |
957 | package org.hswebframework.web.dict;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializable;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.bean.ClassDescription;
import org.hswebframework.web.bean.ClassDescriptions;
import org.hswebframework.web.dict.defaults.DefaultItemDefine;
import org.hswebframework.web.exception.ValidationException;
import org.hswebframework.web.i18n.LocaleUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 枚举字典,使用枚举来实现数据字典,可通过集成此接口来实现一些有趣的功能.
* ⚠️:如果使用了位运算来判断枚举,枚举数量不要超过64个,且顺序不要随意变动!
* ⚠️:如果要开启在反序列化json的时候,支持将对象反序列化枚举,由于fastJson目前的版本还不支持从父类获取注解,
* 所以需要在实现类上注解:<code>@JSONType(deserializer = EnumDict.EnumDictJSONDeserializer.class)</code>.
*
* @author zhouhao
* @see 3.0
* @see EnumDictJSONDeserializer
* @see JSONSerializable
*/
@JSONType(deserializer = EnumDict.EnumDictJSONDeserializer.class)
@JsonDeserialize(contentUsing = EnumDict.EnumDictJSONDeserializer.class)
public interface EnumDict<V> extends JSONSerializable, Serializable {
/**
* 枚举选项的值,通常由字母或者数字组成,并且在同一个枚举中值唯一;对应数据库中的值通常也为此值
*
* @return 枚举的值
* @see ItemDefine#getValue()
*/
V getValue();
/**
* 枚举字典选项的文本,通常为中文
*
* @return 枚举的文本
* @see ItemDefine#getText()
*/
String getText();
/**
* {@link Enum#ordinal()}
*
* @return 枚举序号, 如果枚举顺序改变, 此值将被变动
*/
int ordinal();
default long index() {
return ordinal();
}
default long getMask() {
return 1L << index();
}
/**
* 对比是否和value相等,对比地址,值,value转为string忽略大小写对比,text忽略大小写对比
*
* @param v value
* @return 是否相等
*/
@SuppressWarnings("all")
default boolean eq(Object v) {
if (v == null) {
return false;
}
if (v instanceof Object[]) {
v = Arrays.asList(v);
}
if (v instanceof Collection) {
return ((Collection) v).stream().anyMatch(this::eq);
}
if (v instanceof Map) {
v = ((Map) v).getOrDefault("value", ((Map) v).get("text"));
}
if (v instanceof Number) {
v = ((Number) v).intValue();
}
if (v instanceof EnumDict) {
EnumDict dict = ((EnumDict<?>) v);
v = dict.getValue();
if (v == null) {
v = dict.getText();
}
}
return this == v
|| getValue() == v
|| Objects.equals(getValue(), v)
|| Objects.equals(ordinal(), v)
|| String.valueOf(getValue()).equalsIgnoreCase(String.valueOf(v))
|| getText().equalsIgnoreCase(String.valueOf(v)
);
}
default boolean in(long mask) {
return (mask & getMask()) != 0;
}
default boolean in(EnumDict<V>... dict) {
return in(toMask(dict));
}
/**
* 枚举选项的描述,对一个选项进行详细的描述有时候是必要的.默认值为{@link EnumDict#getText()}
*
* @return 描述
*/
default String getComments() {
return getText();
}
/**
* 从指定的枚举类中查找想要的枚举,并返回一个{@link Optional},如果未找到,则返回一个{@link Optional#empty()}
*
* @param type 实现了{@link EnumDict}的枚举类
* @param predicate 判断逻辑
* @param <T> 枚举类型
* @return 查找到的结果
*/
@SuppressWarnings("all")
static <T extends Enum<?> & EnumDict<?>> Optional<T> find(Class<T> type, Predicate<T> predicate) {
ClassDescription description = ClassDescriptions.getDescription(type);
if (description.isEnumType()) {
for (Object enumDict : description.getEnums()) {
if (predicate.test((T) enumDict)) {
return Optional.of((T) enumDict);
}
}
}
return Optional.empty();
}
@SuppressWarnings("all")
static <T extends Enum<?> & EnumDict<?>> List<T> findList(Class<T> type, Predicate<T> predicate) {
ClassDescription description = ClassDescriptions.getDescription(type);
if (description.isEnumType()) {
return Arrays.stream(description.getEnums())
.map(v -> (T) v)
.filter(predicate)
.collect(Collectors.toList());
}
return Collections.emptyList();
}
/**
* 根据枚举的{@link EnumDict#getValue()}来查找.
*
* @see EnumDict#find(Class, Predicate)
*/
static <T extends Enum<?> & EnumDict<?>> Optional<T> findByValue(Class<T> type, Object value) {
if (value == null) {
return Optional.empty();
}
return find(type, e -> e.getValue() == value || e.getValue().equals(value) || String
.valueOf(e.getValue())
.equalsIgnoreCase(String.valueOf(value)));
}
/**
* 根据枚举的{@link EnumDict#getText()} 来查找.
*
* @see EnumDict#find(Class, Predicate)
*/
static <T extends Enum<?> & EnumDict<?>> Optional<T> findByText(Class<T> type, String text) {
return find(type, e -> e.getText().equalsIgnoreCase(text));
}
/**
* 根据枚举的{@link EnumDict#getValue()},{@link EnumDict#getText()}来查找.
*
* @see EnumDict#find(Class, Predicate)
*/
static <T extends Enum<?> & EnumDict<?>> Optional<T> find(Class<T> type, Object target) {
return find(type, v -> v.eq(target));
}
@SafeVarargs
static <T extends EnumDict<?>> long toMask(T... t) {
if (t == null) {
return 0L;
}
long value = 0L;
for (T t1 : t) {
value |= t1.getMask();
}
return value;
}
@SafeVarargs
static <T extends Enum<?> & EnumDict<?>> boolean in(T target, T... t) {
ClassDescription description = ClassDescriptions.getDescription(target.getClass());
Object[] all = description.getEnums();
if (all.length >= 64) {
Set<Object> allSet = new HashSet<>(Arrays.asList(all));
for (T t1 : t) {
if (allSet.contains(t1)) {
return true;
}
}
return false;
}
return maskIn(toMask(t), target);
}
@SafeVarargs
static <T extends EnumDict<?>> boolean maskIn(long mask, T... t) {
long value = toMask(t);
return (mask & value) == value;
}
@SafeVarargs
static <T extends EnumDict<?>> boolean maskInAny(long mask, T... t) {
long value = toMask(t);
return (mask & value) != 0;
}
static <T extends EnumDict<?>> List<T> getByMask(List<T> allOptions, long mask) {
if (allOptions.size() >= 64) {
throw new UnsupportedOperationException("不支持选项超过64个数据字典!");
}
List<T> arr = new ArrayList<>();
for (T t : allOptions) {
if (t.in(mask)) {
arr.add(t);
}
}
return arr;
}
static <T extends EnumDict<?>> List<T> getByMask(Supplier<List<T>> allOptionsSupplier, long mask) {
return getByMask(allOptionsSupplier.get(), mask);
}
static <T extends Enum<?> & EnumDict<?>> List<T> getByMask(Class<T> tClass, long mask) {
return getByMask(Arrays.asList(tClass.getEnumConstants()), mask);
}
/**
* 默认在序列化为json时,默认会以对象方式写出枚举,可通过系统环境变量 <code>hsweb.enum.dict.disableWriteJSONObject</code>关闭默认设置。
* 比如: java -jar -Dhsweb.enum.dict.disableWriteJSONObject=true
*/
boolean DEFAULT_WRITE_JSON_OBJECT = !Boolean.getBoolean("hsweb.enum.dict.disableWriteJSONObject");
/**
* @return 是否在序列化为json的时候, 将枚举以对象方式序列化
* @see EnumDict#DEFAULT_WRITE_JSON_OBJECT
*/
default boolean isWriteJSONObjectEnabled() {
return DEFAULT_WRITE_JSON_OBJECT;
}
default String getI18nCode() {
return getText();
}
default String getI18nMessage(Locale locale) {
return LocaleUtils.resolveMessage(getI18nCode(), locale, getText());
}
/**
* 当{@link EnumDict#isWriteJSONObjectEnabled()}返回true时,在序列化为json的时候,会写出此方法返回的对象
*
* @return 最终序列化的值
* @see EnumDict#isWriteJSONObjectEnabled()
*/
@JsonValue
default Object getWriteJSONObject() {
if (isWriteJSONObjectEnabled()) {
Map<String, Object> jsonObject = new HashMap<>();
jsonObject.put("value", getValue());
jsonObject.put("text", getI18nMessage(LocaleUtils.current()));
// jsonObject.put("index", index());
// jsonObject.put("mask", getMask());
return jsonObject;
}
return this.getValue();
}
@Override
default void write(JSONSerializer jsonSerializer, Object o, Type type, int i) {
if (isWriteJSONObjectEnabled()) {
jsonSerializer.write(getWriteJSONObject());
} else {
jsonSerializer.write(getValue());
}
}
/**
* 自定义fastJson枚举序列化
*/
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
class EnumDictJSONDeserializer extends JsonDeserializer<Object> implements ObjectDeserializer {
private Function<Object, Object> mapper;
@Override
@SuppressWarnings("all")
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
try {
Object value;
final JSONLexer lexer = parser.lexer;
final int token = lexer.token();
if (token == JSONToken.LITERAL_INT) {
int intValue = lexer.intValue();
lexer.nextToken(JSONToken.COMMA);
return (T) EnumDict.find((Class) type, intValue).orElse(null);
} else if (token == JSONToken.LITERAL_STRING) {
String name = lexer.stringVal();
lexer.nextToken(JSONToken.COMMA);
if (name.length() == 0) {
return (T) null;
}
return (T) EnumDict.find((Class) type, name).orElse(null);
} else if (token == JSONToken.NULL) {
lexer.nextToken(JSONToken.COMMA);
return null;
} else {
value = parser.parse();
if (value instanceof Map) {
return (T) EnumDict.find(((Class) type), ((Map) value).get("value"))
.orElseGet(() ->
EnumDict
.find(((Class) type), ((Map) value).get("text"))
.orElse(null));
}
}
throw new JSONException("parse enum " + type + " error, value : " + value);
} catch (JSONException e) {
throw e;
} catch (Exception e) {
throw new JSONException(e.getMessage(), e);
}
}
@Override
public int getFastMatchToken() {
return JSONToken.LITERAL_STRING;
}
@Override
@SuppressWarnings("all")
@SneakyThrows
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
if (mapper != null) {
if (node.isTextual()) {
return mapper.apply(node.asText());
}
if (node.isNumber()) {
return mapper.apply(node.asLong());
}
}
String currentName = jp.currentName();
Object currentValue = jp.getCurrentValue();
Class findPropertyType;
if (StringUtils.isEmpty(currentName) || StringUtils.isEmpty(currentValue)) {
return null;
} else {
findPropertyType = BeanUtils.findPropertyType(currentName, currentValue.getClass());
}
Supplier<ValidationException> exceptionSupplier = () -> {
List<Object> values = Stream
.of(findPropertyType.getEnumConstants())
.map(Enum.class::cast)
.map(e -> {
if (e instanceof EnumDict) {
return ((EnumDict) e).getValue();
}
return e.name();
}).collect(Collectors.toList());
return new ValidationException(currentName, "validation.parameter_does_not_exist_in_enums", currentName);
};
if (EnumDict.class.isAssignableFrom(findPropertyType) && findPropertyType.isEnum()) {
if (node.isObject()) {
JsonNode valueNode = node.get("value");
Object value = null;
if (valueNode != null) {
if (valueNode.isTextual()) {
value = valueNode.textValue();
} else if (valueNode.isNumber()) {
value = valueNode.numberValue();
}
}
return (EnumDict) EnumDict
.findByValue(findPropertyType, value)
.orElseThrow(exceptionSupplier);
}
if (node.isNumber()) {
return (EnumDict) EnumDict
.find(findPropertyType, node.numberValue())
.orElseThrow(exceptionSupplier);
}
if (node.isTextual()) {
return (EnumDict) EnumDict
.find(findPropertyType, node.textValue())
.orElseThrow(exceptionSupplier);
}
return exceptionSupplier.get();
}
if (findPropertyType.isEnum()) {
return Stream
.of(findPropertyType.getEnumConstants())
.filter(o -> {
if (node.isTextual()) {
return node.textValue().equalsIgnoreCase(((Enum) o).name());
}
if (node.isNumber()) {
return node.intValue() == ((Enum) o).ordinal();
}
return false;
})
.findAny()
.orElseThrow(exceptionSupplier);
}
log.warn("unsupported deserialize enum json : {}", node);
return null;
}
}
/**
* 创建动态的字典选项
*
* @param value 值
* @return 字典选项
*/
static EnumDict<String> create(String value) {
return create(value, null);
}
/**
* 创建动态的字典选项
*
* @param value 值
* @param text 说明
* @return 字典选项
*/
static EnumDict<String> create(String value, String text) {
return DefaultItemDefine
.builder()
.value(value)
.text(text)
.build();
}
}
| hs-web/hsweb-framework | hsweb-core/src/main/java/org/hswebframework/web/dict/EnumDict.java |
958 | import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.util.Duration;
import javafx.util.Pair;
import jdk.nashorn.internal.runtime.regexp.joni.exception.ValueException;
import tableElements.*;
import javax.swing.*;
import javax.swing.text.Style;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Optional;
import java.util.ResourceBundle;
public class MainSceneController implements Initializable {
private final int SAMPLE_COUNT = 7;
private final String[] RS_NAME = {"ADD", "MULT", "LOAD", "STORE"};
private final String[] OP_NAME = {"ADD", "SUB", "MUL", "DIV", "LD", "ST"};
private final int[] CONTINUE_STEPS = {5, 10, 15, 20};
public Label clockLabel;
public Label clockTimeLabel;
public TableView<RSRow> rsTableView;
public TableView<CodeRow> codeTableView;
public TableView<FPRegRow> fpRegTableView;
public TableView<CPURegRow> cpuRegTableView;
public TableView<MemRow> memTableView;
public Menu changeMenu;
public TableView<LsQueueRow> lsQueueTableView;
public Label hintTextLabel;
private int currentTime;
private boolean timerRunning;
@FXML
private Button inputButton;
@FXML
private MenuButton sampleButton;
@FXML
private Button startButton;
@FXML
private Button stepButton;
@FXML
private MenuButton continueButton;
@FXML
private Button tailButton;
private Pipeline pipeline;
@FXML
void inputClicked(ActionEvent event) {
String inputCode = "";
while (true) {
// Create the custom dialog.
Dialog<String> dialog = new Dialog<>();
dialog.setTitle("输入指令");
// Set the button types.
ButtonType loginButtonType = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
TextArea tArea = new TextArea(inputCode);
tArea.setPromptText("请在这里输入代码");
BorderPane borderPane = new BorderPane(tArea);
BorderPane.setMargin(borderPane, new Insets(20, 20, 20, 20));
dialog.getDialogPane().setContent(borderPane);
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return tArea.getText();
}
return null;
});
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
inputCode = result.get();
if (inputCode(inputCode)) {
refreshCodeSection();
break;
}
} else {
return;
}
}
}
private boolean inputCode(String code) {
String[] codeLines = code.split("\\r?\\n");
// Cache current pipeline code
ArrayList<String> cachedList = new ArrayList<>(pipeline.cmdList.size());
cachedList.addAll(pipeline.cmdList);
pipeline.cmdList.clear();
for (String line : codeLines) {
line = line.trim();
if (line.startsWith("#") || line.startsWith("//")) {
continue;
}
if (line.matches(".*\\w.*")) {
System.out.println(line);
pipeline.addCmd(line);
}
}
int parseResult = pipeline.parser();
if (parseResult == -1) {
showAlert(Alert.AlertType.ERROR, "错误", "语法错误", pipeline.parseErrMessage);
pipeline.cmdList.clear();
pipeline.cmdList.addAll(cachedList);
pipeline.parser();
return false;
} else {
return true;
}
}
@FXML
void startClicked(ActionEvent event) {
if (pipeline.isRunning) {
pipeline.clean();
pipeline.isRunning = false;
currentTime = 0;
switchStatus(false);
refreshAll();
} else {
if (pipeline.decodedList.size() == 0) {
showAlert(Alert.AlertType.ERROR, "错误", "操作错误",
"当前指令队列中没有指令,您可以考虑输入指令或使用示例指令。");
return;
}
currentTime = 0;
pipeline.run();
switchStatus(true);
refreshAll();
}
}
private void continueClicked(int step) {
if (allFinished()) return;
for (int i = 0; i < step; ++ i) {
pipeline.nextStep();
currentTime += 1;
if (allFinished()) {
stepButton.setDisable(true);
continueButton.setDisable(true);
tailButton.setDisable(true);
hintTextLabel.setText("指令全部执行完毕");
break;
}
}
refreshAll();
}
@FXML
void stepClicked(ActionEvent event) {
if (allFinished()) return;
pipeline.nextStep();
currentTime += 1;
refreshAll();
if (allFinished()) {
stepButton.setDisable(true);
continueButton.setDisable(true);
tailButton.setDisable(true);
hintTextLabel.setText("指令全部执行完毕");
}
}
@FXML
void tailClicked(ActionEvent event) {
if (timerRunning) {
tailButton.setGraphic(new ImageView("/resources/tail.png"));
tailButton.setText("自动执行");
stepButton.setDisable(false);
continueButton.setDisable(false);
timerRunning = false;
} else {
tailButton.setGraphic(new ImageView("/resources/pause.png"));
tailButton.setText("暂停执行");
stepButton.setDisable(true);
continueButton.setDisable(true);
timerRunning = true;
}
}
private void backgroundSchedulePlay() {
if (!timerRunning) return;
stepClicked(null);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
inputButton.setGraphic(new ImageView("/resources/input.png"));
sampleButton.setGraphic(new ImageView("/resources/sample.png"));
startButton.setGraphic(new ImageView("/resources/simulate.png"));
stepButton.setGraphic(new ImageView("/resources/step.png"));
continueButton.setGraphic(new ImageView("/resources/continue.png"));
tailButton.setGraphic(new ImageView("/resources/tail.png"));
clockLabel.setGraphic(new ImageView("/resources/time.png"));
memTableView.setPlaceholder(new Label("内存中所有值均为0"));
codeTableView.setPlaceholder(new Label("当前没有任何指令,点击左侧的输入指令或示例指令进行添加"));
lsQueueTableView.setPlaceholder(new Label("当前队列中没有值,所有Load-Store保留栈均为非Busy状态"));
switchStatus(false);
pipeline = new Pipeline();
refreshAll();
for (int i = 0; i < SAMPLE_COUNT; ++ i) {
MenuItem sampleItem = new MenuItem("示例" + String.valueOf(i + 1));
int finalI = i;
sampleItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
InputStream in = getClass().getResourceAsStream(String.format("/samples/s%d.txt", finalI + 1));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line = reader.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line).append("\n");
line = reader.readLine();
}
if (inputCode(sb.toString())) {
// TODO: Deduplicate this code.
refreshCodeSection();
}
} catch (IOException e) {
showAlert(Alert.AlertType.ERROR, "错误", "内部错误", "示例不可用,请直接输入代码");
}
}
});
sampleButton.getItems().add(sampleItem);
}
for (int cs : CONTINUE_STEPS) {
MenuItem contItem = new MenuItem(String.format("执行%d步", cs));
contItem.setOnAction(event -> continueClicked(cs));
continueButton.getItems().add(contItem);
}
timerRunning = false;
Timeline backgroundTask = new Timeline(new KeyFrame(Duration.seconds(1),
event -> backgroundSchedulePlay()));
backgroundTask.setCycleCount(Timeline.INDEFINITE);
backgroundTask.play();
}
private void setClockTime(int time) {
clockTimeLabel.setText(String.valueOf(time));
}
private void switchStatus(boolean isRunning) {
if (isRunning) {
inputButton.setDisable(true);
sampleButton.setDisable(true);
startButton.setText("结束模拟");
stepButton.setDisable(false);
continueButton.setDisable(false);
tailButton.setDisable(false);
changeMenu.setDisable(true);
} else {
inputButton.setDisable(false);
sampleButton.setDisable(false);
startButton.setText("开始模拟");
setClockTime(0);
stepButton.setDisable(true);
continueButton.setDisable(true);
tailButton.setDisable(true);
fpRegTableView.setEditable(true);
changeMenu.setDisable(false);
tailButton.setGraphic(new ImageView("/resources/tail.png"));
tailButton.setText("自动执行");
hintTextLabel.setText("欢迎使用");
timerRunning = false;
}
}
private void refreshAll() {
refreshReservationStation();
refreshCodeSection();
refreshRegisters();
refreshMemory();
refreshLsQueue();
setClockTime(currentTime);
}
private void refreshReservationStation() {
ObservableList<RSRow> a = FXCollections.observableArrayList();
for (int i = 0; i < 2; ++ i) {
for (int j = 0; j < 3; ++ j) {
if (i == 1 && j == 2) continue;
String rsName = RS_NAME[i] + String.valueOf(j + 1);
RSRow rRow = new RSRow(rsName);
TMLBuffer thisBuffer = pipeline.buffers[i][j];
if (thisBuffer.busy) {
rRow.setBusy("Yes");
int op = thisBuffer.operator;
rRow.setOp(OP_NAME[i * 2 + op]);
if (thisBuffer.rsIndex[0][0] != -1) {
rRow.setQj(RS_NAME[thisBuffer.rsIndex[0][0]] +
String.valueOf(thisBuffer.rsIndex[0][1] + 1));
} else {
rRow.setVj(String.valueOf(thisBuffer.value[0]));
}
if (thisBuffer.rsIndex[1][0] != -1) {
rRow.setQk(RS_NAME[thisBuffer.rsIndex[1][0]] +
String.valueOf(thisBuffer.rsIndex[1][1] + 1));
} else {
rRow.setVk(String.valueOf(thisBuffer.value[1]));
}
} else {
rRow.setBusy("No");
}
a.add(rRow);
}
}
rsTableView.getItems().setAll(a);
}
private void refreshCodeSection() {
ObservableList<CodeRow> a = FXCollections.observableArrayList();
for (Cmd cmd : pipeline.decodedList) {
CodeRow cRow = new CodeRow(a.size() + 1, cmd.text);
if (cmd.state >= 1) cRow.setSt1("OK");
if (cmd.state >= 2) cRow.setSt2("OK");
if (cmd.state >= 3) cRow.setSt3("OK");
a.add(cRow);
}
codeTableView.getItems().setAll(a);
}
private void refreshRegisters() {
ObservableList<CPURegRow> a = FXCollections.observableArrayList();
for (int i = 0; i < 8; ++ i) {
CPURegRow cRow = new CPURegRow("R" + String.valueOf(i));
cRow.setValue(String.valueOf(pipeline.cpuRegisters[i]));
a.add(cRow);
}
cpuRegTableView.getItems().setAll(a);
ObservableList<FPRegRow> b = FXCollections.observableArrayList();
for (int i = 0; i <= 30; i += 2) {
FPRegRow fRow = new FPRegRow("F" + String.valueOf(i));
fRow.setValue(String.valueOf(pipeline.fpRegisters[i]));
String rsName;
if (pipeline.fpRegistersStatus[i][0] == -1) {
// if Qi is empty
rsName = "";
} else {
// if this register is going to be filled by an RS, show it.
rsName = RS_NAME[pipeline.fpRegistersStatus[i][0]] +
String.valueOf(pipeline.fpRegistersStatus[i][1] + 1);
}
fRow.setRs(rsName);
b.add(fRow);
}
fpRegTableView.getItems().setAll(b);
}
private void refreshMemory() {
ObservableList<MemRow> a = FXCollections.observableArrayList();
for (int i = 0; i < 4096; ++ i) {
if (pipeline.memory[i] != 0.0) {
MemRow memRow = new MemRow();
memRow.setOffset(String.valueOf(i));
memRow.setValue(String.valueOf(pipeline.memory[i]));
a.add(memRow);
}
}
memTableView.getItems().setAll(a);
}
private void refreshLsQueue() {
ObservableList<LsQueueRow> a = FXCollections.observableArrayList();
int id = 1;
for (Integer queueId : pipeline.loadStoreQueue) {
LsQueueRow lsQueueRow = new LsQueueRow();
lsQueueRow.setId(String.valueOf(id));
int rsId = queueId / 3;
int inId = queueId % 3;
TMLBuffer thisBuffer = pipeline.buffers[rsId + 2][inId];
if (!thisBuffer.busy) {
showAlert(Alert.AlertType.INFORMATION, "错误", "内部错误",
"一个在LS队列中的队员对应的保留栈非busy");
}
lsQueueRow.setOp(OP_NAME[rsId + 4]);
lsQueueRow.setRsName(RS_NAME[rsId + 2] + String.valueOf(inId + 1));
if (rsId == 1) {
// Only store need to know qj and vj
if (thisBuffer.rsIndex[0][0] != -1) {
lsQueueRow.setQj(RS_NAME[thisBuffer.rsIndex[0][0]] +
String.valueOf(thisBuffer.rsIndex[0][1] + 1));
} else {
lsQueueRow.setVj(String.valueOf(thisBuffer.value[0]));
}
}
lsQueueRow.setAddress(String.valueOf(thisBuffer.address));
a.add(lsQueueRow);
id += 1;
}
lsQueueTableView.getItems().setAll(a);
}
private void showAlert(Alert.AlertType type, String title, String header, String content) {
Alert alert = new Alert(type);
alert.setTitle(title);
alert.setHeaderText(header);
alert.setContentText(content);
alert.showAndWait();
}
public void exitClicked(ActionEvent actionEvent) {
System.exit(0);
}
public void aboutClicked(ActionEvent actionEvent) {
showAlert(Alert.AlertType.INFORMATION, "信息", "关于本项目",
"本项目是计算机系统结构课程的第二次大作业,内容是Tomasulo算法模拟器。");
}
public void registerChangeClicked(ActionEvent actionEvent) {
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("更改寄存器");
dialog.setHeaderText("输入寄存器名以更改寄存器,以R开头的为CPU通用寄存器,以F开头的为浮点寄存器\n" +
"浮点寄存器可以填写F0, F2, ..., F30,CPU寄存器可以填写R0, R1, ..., R7");
// Set the button types.
ButtonType loginButtonType = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
GridPane gridPane = new GridPane();
TextField regTextField = new TextField();
regTextField.setPromptText("寄存器名");
Label equalLabel = new Label("=");
TextField regValueField = new TextField();
regValueField.setPromptText("寄存器值");
gridPane.add(regTextField, 0, 0);
gridPane.add(equalLabel, 1, 0);
gridPane.add(regValueField, 2, 0);
gridPane.setAlignment(Pos.CENTER);
GridPane.setMargin(equalLabel, new Insets(0, 20, 0, 20));
dialog.getDialogPane().setContent(gridPane);
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return new Pair<>(regTextField.getText(), regValueField.getText());
}
return null;
});
Optional<Pair<String, String>> result = dialog.showAndWait();
if (result.isPresent()) {
try {
Pair<String, String> res = result.get();
String reg = res.getKey().trim();
String val = res.getValue().trim();
if (reg.startsWith("R")) {
int id = Integer.valueOf(reg.substring(1));
int v = Integer.valueOf(val);
if (id >= 0 && id <= 7) {
pipeline.cpuRegisters[id] = v;
} else {
throw new ValueException("寄存器越界");
}
} else if (reg.startsWith("F")) {
int id = Integer.valueOf(reg.substring(1));
float v = Float.valueOf(val);
if (id >= 0 && id <= 30 && id % 2 == 0) {
pipeline.fpRegisters[id] = v;
} else {
throw new ValueException("寄存器越界");
}
} else {
throw new ValueException("寄存器不识别");
}
} catch (Exception e) {
showAlert(Alert.AlertType.ERROR, "错误", "赋值错误", "赋值过程产生错误:\n" +
e.getMessage() + "\n一个忠告:看清提示再填写。");
}
refreshRegisters();
}
}
public void memoryChangeClicked(ActionEvent actionEvent) {
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("更改内存");
dialog.setHeaderText("输入内存偏移(0-4095)和对应的值(浮点值)进行改变");
// Set the button types.
ButtonType loginButtonType = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
GridPane gridPane = new GridPane();
TextField regTextField = new TextField();
regTextField.setPromptText("内存偏移");
Label equalLabel = new Label("=");
TextField regValueField = new TextField();
regValueField.setPromptText("值");
gridPane.add(regTextField, 0, 0);
gridPane.add(equalLabel, 1, 0);
gridPane.add(regValueField, 2, 0);
gridPane.setAlignment(Pos.CENTER);
GridPane.setMargin(equalLabel, new Insets(0, 20, 0, 20));
dialog.getDialogPane().setContent(gridPane);
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return new Pair<>(regTextField.getText(), regValueField.getText());
}
return null;
});
Optional<Pair<String, String>> result = dialog.showAndWait();
if (result.isPresent()) {
try {
Pair<String, String> res = result.get();
String reg = res.getKey().trim();
String val = res.getValue().trim();
int offset = Integer.valueOf(reg);
if (offset < 0 || offset > 4095) {
throw new ValueException("内存越界");
}
float v = Float.valueOf(val);
pipeline.memory[offset] = v;
} catch (Exception e) {
showAlert(Alert.AlertType.ERROR, "错误", "赋值错误", "赋值过程产生错误:\n" +
e.getMessage() + "\n一个忠告:看清提示再填写。");
}
refreshMemory();
}
}
private boolean allFinished() {
for (Cmd cmd : pipeline.decodedList) {
if (cmd.state != 3) return false;
}
return true;
}
}
| PKUanonym/REKCARC-TSC-UHT | 大三下/计算机系统结构/hw/实验/实验二/src/MainSceneController.java |
960 | package org.jeecg.common.util;
import cn.hutool.core.util.ReUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgSqlInjectionException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* sql注入处理工具类
*
* @author zhoujf
*/
@Slf4j
public class SqlInjectionUtil {
/**
* 默认—sql注入关键词
*/
private final static String XSS_STR = "and |exec |peformance_schema|information_schema|extractvalue|updatexml|geohash|gtid_subset|gtid_subtract|insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|or |+|--";
/**
* online报表专用—sql注入关键词
*/
private static String specialReportXssStr = "exec |peformance_schema|information_schema|extractvalue|updatexml|geohash|gtid_subset|gtid_subtract|insert |alter |delete |grant |update |drop |master |truncate |declare |--";
/**
* 字典专用—sql注入关键词
*/
private static String specialDictSqlXssStr = "exec |peformance_schema|information_schema|extractvalue|updatexml|geohash|gtid_subset|gtid_subtract|insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|+|--";
/**
* 完整匹配的key,不需要考虑前空格
*/
private static List<String> FULL_MATCHING_KEYWRODS = new ArrayList<>();
static {
FULL_MATCHING_KEYWRODS.add(";");
FULL_MATCHING_KEYWRODS.add("+");
FULL_MATCHING_KEYWRODS.add("--");
}
/**
* sql注入风险的 正则关键字
*
* 函数匹配,需要用正则模式
*/
private final static String[] XSS_REGULAR_STR_ARRAY = new String[]{
"chr\\s*\\(",
"mid\\s*\\(",
" char\\s*\\(",
"sleep\\s*\\(",
"user\\s*\\(",
"show\\s+tables",
"user[\\s]*\\([\\s]*\\)",
"show\\s+databases",
"sleep\\(\\d*\\)",
"sleep\\(.*\\)",
};
/**
* sql注释的正则
*/
private final static Pattern SQL_ANNOTATION = Pattern.compile("/\\*[\\s\\S]*\\*/");
private final static String SQL_ANNOTATION2 = "--";
/**
* sql注入提示语
*/
private final static String SQL_INJECTION_KEYWORD_TIP = "请注意,存在SQL注入关键词---> {}";
private final static String SQL_INJECTION_TIP = "请注意,值可能存在SQL注入风险!--->";
private final static String SQL_INJECTION_TIP_VARIABLE = "请注意,值可能存在SQL注入风险!---> {}";
/**
* sql注入过滤处理,遇到注入关键字抛异常
* @param values
*/
public static void filterContent(String... values) {
filterContent(values, null);
}
/**
* 校验比较严格
*
* sql注入过滤处理,遇到注入关键字抛异常
*
* @param value
* @return
*/
public static void filterContent(String value, String customXssString) {
if (value == null || "".equals(value)) {
return;
}
// 一、校验sql注释 不允许有sql注释
checkSqlAnnotation(value);
// 转为小写进行后续比较
value = value.toLowerCase().trim();
// 二、SQL注入检测存在绕过风险 (普通文本校验)
//https://gitee.com/jeecg/jeecg-boot/issues/I4NZGE
String[] xssArr = XSS_STR.split("\\|");
for (int i = 0; i < xssArr.length; i++) {
if (value.indexOf(xssArr[i]) > -1) {
log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssArr[i]);
log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value);
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
}
}
// 三、SQL注入检测存在绕过风险 (自定义传入普通文本校验)
if (customXssString != null) {
String[] xssArr2 = customXssString.split("\\|");
for (int i = 0; i < xssArr2.length; i++) {
if (value.indexOf(xssArr2[i]) > -1) {
log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssArr2[i]);
log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value);
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
}
}
}
// 四、SQL注入检测存在绕过风险 (正则校验)
for (String regularOriginal : XSS_REGULAR_STR_ARRAY) {
String regular = ".*" + regularOriginal + ".*";
if (Pattern.matches(regular, value)) {
log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, regularOriginal);
log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value);
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
}
}
return;
}
/**
* 判断是否存在SQL注入关键词字符串
*
* @param keyword
* @return
*/
@SuppressWarnings("AlibabaUndefineMagicConstant")
private static boolean isExistSqlInjectKeyword(String sql, String keyword) {
if (sql.startsWith(keyword.trim())) {
return true;
} else if (sql.contains(keyword)) {
// 需要匹配的,sql注入关键词
String matchingText = " " + keyword;
if(FULL_MATCHING_KEYWRODS.contains(keyword)){
matchingText = keyword;
}
if (sql.contains(matchingText)) {
return true;
} else {
String regularStr = "\\s+\\S+" + keyword;
List<String> resultFindAll = ReUtil.findAll(regularStr, sql, 0, new ArrayList<String>());
for (String res : resultFindAll) {
log.info("isExistSqlInjectKeyword —- 匹配到的SQL注入关键词:{}", res);
/**
* SQL注入中可以替换空格的字符(%09 %0A %0D +都可以替代空格)
* http://blog.chinaunix.net/uid-12501104-id-2932639.html
* https://www.cnblogs.com/Vinson404/p/7253255.html
* */
if (res.contains("%") || res.contains("+") || res.contains("#") || res.contains("/") || res.contains(")")) {
return true;
}
}
}
}
return false;
}
/**
* sql注入过滤处理,遇到注入关键字抛异常
*
* @param values
* @return
*/
public static void filterContent(String[] values, String customXssString) {
for (String val : values) {
if (oConvertUtils.isEmpty(val)) {
return;
}
filterContent(val, customXssString);
}
return;
}
/**
* 【提醒:不通用】
* 仅用于字典条件SQL参数,注入过滤
*
* @param value
* @return
*/
public static void specialFilterContentForDictSql(String value) {
String[] xssArr = specialDictSqlXssStr.split("\\|");
if (value == null || "".equals(value)) {
return;
}
// 一、校验sql注释 不允许有sql注释
checkSqlAnnotation(value);
value = value.toLowerCase().trim();
// 二、SQL注入检测存在绕过风险 (普通文本校验)
for (int i = 0; i < xssArr.length; i++) {
if (isExistSqlInjectKeyword(value, xssArr[i])) {
log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssArr[i]);
log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value);
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
}
}
// 三、SQL注入检测存在绕过风险 (正则校验)
for (String regularOriginal : XSS_REGULAR_STR_ARRAY) {
String regular = ".*" + regularOriginal + ".*";
if (Pattern.matches(regular, value)) {
log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, regularOriginal);
log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value);
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
}
}
return;
}
/**
* 【提醒:不通用】
* 仅用于Online报表SQL解析,注入过滤
* @param value
* @return
*/
public static void specialFilterContentForOnlineReport(String value) {
String[] xssArr = specialReportXssStr.split("\\|");
if (value == null || "".equals(value)) {
return;
}
// 一、校验sql注释 不允许有sql注释
checkSqlAnnotation(value);
value = value.toLowerCase().trim();
// 二、SQL注入检测存在绕过风险 (普通文本校验)
for (int i = 0; i < xssArr.length; i++) {
if (isExistSqlInjectKeyword(value, xssArr[i])) {
log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssArr[i]);
log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value);
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
}
}
// 三、SQL注入检测存在绕过风险 (正则校验)
for (String regularOriginal : XSS_REGULAR_STR_ARRAY) {
String regular = ".*" + regularOriginal + ".*";
if (Pattern.matches(regular, value)) {
log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, regularOriginal);
log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value);
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
}
}
return;
}
/**
* 校验是否有sql注释
* @return
*/
public static void checkSqlAnnotation(String str){
if(str.contains(SQL_ANNOTATION2)){
String error = "请注意,SQL中不允许含注释,有安全风险!";
log.error(error);
throw new RuntimeException(error);
}
Matcher matcher = SQL_ANNOTATION.matcher(str);
if(matcher.find()){
String error = "请注意,值可能存在SQL注入风险---> \\*.*\\";
log.error(error);
throw new JeecgSqlInjectionException(error);
}
}
/**
* 返回查询表名
* <p>
* sql注入过滤处理,遇到注入关键字抛异常
*
* @param table
*/
private static Pattern tableNamePattern = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_\\$]{0,63}$");
public static String getSqlInjectTableName(String table) {
if(oConvertUtils.isEmpty(table)){
return table;
}
table = table.trim();
/**
* 检验表名是否合法
*
* 表名只能由字母、数字和下划线组成。
* 表名必须以字母开头。
* 表名长度通常有限制,例如最多为 64 个字符。
*/
boolean isValidTableName = tableNamePattern.matcher(table).matches();
if (!isValidTableName) {
String errorMsg = "表名不合法,存在SQL注入风险!--->" + table;
log.error(errorMsg);
throw new JeecgSqlInjectionException(errorMsg);
}
//进一步验证是否存在SQL注入风险
filterContent(table);
return table;
}
/**
* 返回查询字段
* <p>
* sql注入过滤处理,遇到注入关键字抛异常
*
* @param field
*/
static final Pattern fieldPattern = Pattern.compile("^[a-zA-Z0-9_]+$");
public static String getSqlInjectField(String field) {
if(oConvertUtils.isEmpty(field)){
return field;
}
field = field.trim();
if (field.contains(SymbolConstant.COMMA)) {
return getSqlInjectField(field.split(SymbolConstant.COMMA));
}
/**
* 校验表字段是否有效
*
* 字段定义只能是是字母 数字 下划线的组合(不允许有空格、转义字符串等)
*/
boolean isValidField = fieldPattern.matcher(field).matches();
if (!isValidField) {
String errorMsg = "字段不合法,存在SQL注入风险!--->" + field;
log.error(errorMsg);
throw new JeecgSqlInjectionException(errorMsg);
}
//进一步验证是否存在SQL注入风险
filterContent(field);
return field;
}
/**
* 获取多个字段
* 返回: 逗号拼接
*
* @param fields
* @return
*/
public static String getSqlInjectField(String... fields) {
for (String s : fields) {
getSqlInjectField(s);
}
return String.join(SymbolConstant.COMMA, fields);
}
/**
* 获取排序字段
* 返回:字符串
*
* 1.将驼峰命名转化成下划线
* 2.限制sql注入
* @param sortField 排序字段
* @return
*/
public static String getSqlInjectSortField(String sortField) {
String field = SqlInjectionUtil.getSqlInjectField(oConvertUtils.camelToUnderline(sortField));
return field;
}
/**
* 获取多个排序字段
* 返回:数组
*
* 1.将驼峰命名转化成下划线
* 2.限制sql注入
* @param sortFields 多个排序字段
* @return
*/
public static List getSqlInjectSortFields(String... sortFields) {
List list = new ArrayList<String>();
for (String sortField : sortFields) {
list.add(getSqlInjectSortField(sortField));
}
return list;
}
/**
* 获取 orderBy type
* 返回:字符串
* <p>
* 1.检测是否为 asc 或 desc 其中的一个
* 2.限制sql注入
*
* @param orderType
* @return
*/
public static String getSqlInjectOrderType(String orderType) {
if (orderType == null) {
return null;
}
orderType = orderType.trim();
if (CommonConstant.ORDER_TYPE_ASC.equalsIgnoreCase(orderType)) {
return CommonConstant.ORDER_TYPE_ASC;
} else {
return CommonConstant.ORDER_TYPE_DESC;
}
}
}
| jeecgboot/jeecg-boot | jeecg-boot-base-core/src/main/java/org/jeecg/common/util/SqlInjectionUtil.java |
961 | package com.alibaba.otter.canal.client;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.alibaba.otter.canal.protocol.FlatMessage;
import com.alibaba.otter.canal.protocol.Message;
import com.alibaba.otter.canal.protocol.exception.CanalClientException;
/**
* canal MQ数据操作客户端
*
* <pre>
* 1. canal server写入MQ消息,考虑性能会合并多条数据写入为一个MQ消息,一个Message对应一个MQ消息
* 2. canal client消费MQ消息,因为client性能会弱于server的写入,MQ数据获取时会拿到堆积的多条MQ消息,会拿到List<Message>
* 3. client的ack/rollback,都是和MQ直接交互,不存在对应的batchId概念
* </pre>
*
* @author agapple 2018年10月28日 下午6:42:27
* @since 1.1.1
*/
public interface CanalMQConnector extends CanalConnector {
/**
* 获取数据,自动进行确认,设置timeout时间直到拿到数据为止
*
* <pre>
* 该方法返回的条件:
* a. 如果timeout=0,有多少取多少,不会阻塞等待
* b. 如果timeout不为0,尝试阻塞对应的超时时间,直到拿到数据就返回
* </pre>
*
* @return
* @throws CanalClientException
*/
List<Message> getList(Long timeout, TimeUnit unit) throws CanalClientException;
/**
* 获取数据,设置timeout时间直到拿到数据为止
*
* <pre>
* 该方法返回的条件:
* a. 如果timeout=0,有多少取多少,不会阻塞等待
* b. 如果timeout不为0,尝试阻塞对应的超时时间,直到拿到数据就返回
* </pre>
*
* @throws CanalClientException
*/
List<Message> getListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException;
/**
* 获取数据,自动进行确认,设置timeout时间直到拿到数据为止
*
* <pre>
* 该方法返回的条件:
* a. 如果timeout=0,有多少取多少,不会阻塞等待
* b. 如果timeout不为0,尝试阻塞对应的超时时间,直到拿到数据就返回
* </pre>
*
* @return
* @throws CanalClientException
*/
List<FlatMessage> getFlatList(Long timeout, TimeUnit unit) throws CanalClientException;
/**
* 获取数据,设置timeout时间直到拿到数据为止
*
* <pre>
* 该方法返回的条件:
* a. 如果timeout=0,有多少取多少,不会阻塞等待
* b. 如果timeout不为0,尝试阻塞对应的超时时间,直到拿到数据就返回
* </pre>
*
* @throws CanalClientException
*/
List<FlatMessage> getFlatListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException;
/**
* 消费确认。
*
* @throws CanalClientException
*/
void ack() throws CanalClientException;
/**
* 回滚到未进行 {@link #ack} 的地方,下次fetch的时候,可以从最后一个没有 {@link #ack} 的地方开始拿
*
* @throws CanalClientException
*/
void rollback() throws CanalClientException;
}
| alibaba/canal | client/src/main/java/com/alibaba/otter/canal/client/CanalMQConnector.java |
962 | package com.blankj.bus;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/10
* desc :
* </pre>
*/
public class BusInfo {
public String className; // 函数所在类名
public String funName; // 方法名
public List<ParamsInfo> paramsInfo; // 参数列表信息
public boolean sticky; // 是否粘性
public String threadMode; // 线程模式
public int priority; // 优先级
public boolean isParamSizeNoMoreThanOne; // 参数是否不多于 1 个
public BusInfo(String className, String funName) {
this.className = className;
this.funName = funName;
paramsInfo = new ArrayList<>();
sticky = false;
threadMode = "POSTING";
priority = 0;
isParamSizeNoMoreThanOne = true;
}
@Override
public String toString() {
String paramsInfoString = paramsInfo.toString();
return "{ desc: " + className + "#" + funName +
"(" + paramsInfoString.substring(1, paramsInfoString.length() - 1) + ")" +
(!sticky ? "" : ", sticky: true") +
(threadMode.equals("POSTING") ? "" : ", threadMode: " + threadMode) +
(priority == 0 ? "" : ", priority: " + priority) +
(isParamSizeNoMoreThanOne ? "" : ", paramSize: " + paramsInfo.size()) +
" }";
}
public static class ParamsInfo {
public String className;
public String name;
public ParamsInfo(String className, String name) {
this.className = className;
this.name = name;
}
@Override
public String toString() {
return ("".equals(className) ? "" : (className + " " + name));
}
}
}
| Blankj/AndroidUtilCode | plugin/bus-gradle-plugin/src/main/java/com/blankj/bus/BusInfo.java |
963 | /**
* File: time_complexity.java
* Created Time: 2022-11-25
* Author: krahets ([email protected])
*/
package chapter_computational_complexity;
public class time_complexity {
/* 常数阶 */
static int constant(int n) {
int count = 0;
int size = 100000;
for (int i = 0; i < size; i++)
count++;
return count;
}
/* 线性阶 */
static int linear(int n) {
int count = 0;
for (int i = 0; i < n; i++)
count++;
return count;
}
/* 线性阶(遍历数组) */
static int arrayTraversal(int[] nums) {
int count = 0;
// 循环次数与数组长度成正比
for (int num : nums) {
count++;
}
return count;
}
/* 平方阶 */
static int quadratic(int n) {
int count = 0;
// 循环次数与数据大小 n 成平方关系
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
count++;
}
}
return count;
}
/* 平方阶(冒泡排序) */
static int bubbleSort(int[] nums) {
int count = 0; // 计数器
// 外循环:未排序区间为 [0, i]
for (int i = nums.length - 1; i > 0; i--) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // 元素交换包含 3 个单元操作
}
}
}
return count;
}
/* 指数阶(循环实现) */
static int exponential(int n) {
int count = 0, base = 1;
// 细胞每轮一分为二,形成数列 1, 2, 4, 8, ..., 2^(n-1)
for (int i = 0; i < n; i++) {
for (int j = 0; j < base; j++) {
count++;
}
base *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* 指数阶(递归实现) */
static int expRecur(int n) {
if (n == 1)
return 1;
return expRecur(n - 1) + expRecur(n - 1) + 1;
}
/* 对数阶(循环实现) */
static int logarithmic(int n) {
int count = 0;
while (n > 1) {
n = n / 2;
count++;
}
return count;
}
/* 对数阶(递归实现) */
static int logRecur(int n) {
if (n <= 1)
return 0;
return logRecur(n / 2) + 1;
}
/* 线性对数阶 */
static int linearLogRecur(int n) {
if (n <= 1)
return 1;
int count = linearLogRecur(n / 2) + linearLogRecur(n / 2);
for (int i = 0; i < n; i++) {
count++;
}
return count;
}
/* 阶乘阶(递归实现) */
static int factorialRecur(int n) {
if (n == 0)
return 1;
int count = 0;
// 从 1 个分裂出 n 个
for (int i = 0; i < n; i++) {
count += factorialRecur(n - 1);
}
return count;
}
/* Driver Code */
public static void main(String[] args) {
// 可以修改 n 运行,体会一下各种复杂度的操作数量变化趋势
int n = 8;
System.out.println("输入数据大小 n = " + n);
int count = constant(n);
System.out.println("常数阶的操作数量 = " + count);
count = linear(n);
System.out.println("线性阶的操作数量 = " + count);
count = arrayTraversal(new int[n]);
System.out.println("线性阶(遍历数组)的操作数量 = " + count);
count = quadratic(n);
System.out.println("平方阶的操作数量 = " + count);
int[] nums = new int[n];
for (int i = 0; i < n; i++)
nums[i] = n - i; // [n,n-1,...,2,1]
count = bubbleSort(nums);
System.out.println("平方阶(冒泡排序)的操作数量 = " + count);
count = exponential(n);
System.out.println("指数阶(循环实现)的操作数量 = " + count);
count = expRecur(n);
System.out.println("指数阶(递归实现)的操作数量 = " + count);
count = logarithmic(n);
System.out.println("对数阶(循环实现)的操作数量 = " + count);
count = logRecur(n);
System.out.println("对数阶(递归实现)的操作数量 = " + count);
count = linearLogRecur(n);
System.out.println("线性对数阶(递归实现)的操作数量 = " + count);
count = factorialRecur(n);
System.out.println("阶乘阶(递归实现)的操作数量 = " + count);
}
}
| krahets/hello-algo | codes/java/chapter_computational_complexity/time_complexity.java |
964 | M
tags: Hash Table, Sort, Bucket Sort
time: O(n)
space: O(n)
找到h-index, 给的citation int[] 并不是sorted. h-index 的definition 具体看题目.
#### Sort, find h from end
- 例子写出来,发现可以sort以后按照定义搜索一遍。 nlogn.
- 搜索一遍时候可以优化,用binary search. 但是没意义,因为array.sort已经用了nlogn
- 题目给的规则, 从小到大排序后: 剩下的 paper `n-h`, 全部要 <= h 个 citation.
- time O(nlogn), search O(n)
##### 正向思考
- 从i = 0 开始找第一个 `citations[i] >= h`, 就是第一个符合 h-index 规则的paper, return h
##### 反向思考
- 如果从 h = n, 每次h--; 那么 `x = n - h` 就是从 `[0 ~ n)` 开始找第一个 `dictations[x] >= h`, 就是结果
- 同时, `dictations[x-1]` 就是最后一个(dictation最多的)其余的paper.
#### Couting Sort / Bucket Sort
- O(n)
- Bucket sort的思想(更像是counting sort?): 过一遍 input, 把dictation value 作为 index, 分布在bucket[index]上++
- bucket[x] 是 count when # of citation == x.
- 如果 x 大于 n的时候, 就超出了index范围, 但是刚好这个问题可以包容, 把这样的情况记位在bucket[n]就可以
- 巧妙: `sum += bucket[h]` where `h = [n ~ 0]` 利用了h-index的definition:
- #of papers (sum of bucket[n]...bucket[0]) has more than h cidations
- 这里运用到了bucket sort的思想, 但是并不是sorting, 而h-index的定义运用的很巧妙.
- Read more about actual bucket sort: https://en.wikipedia.org/wiki/Bucket_sort
#### More about Counting Sort
1. Application: for number/character range
1. Steps:
- Find range, define countArray
- Count element and record in the array
- PreSum the countArray
- Start from beginning of the array, `print & decrese count` to produce the sorted elements
```
/*
Given an array of citations (each citation is a non-negative integer) of a researcher,
write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers
have at least h citations each,
and the other N − h papers have no more than h citations each."
For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and
each of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
Hint:
An easy approach is to sort the array first.
What are the possible values of h-index?
A faster approach is to use extra space.
Google Facebook
Hide Tags Hash Table Sort
Hide Similar Problems (M) H-Index II
*/
/*
Thoughts: as the hint shows, use extra space and make it faster.
citations = [3, 0, 6, 1, 5],
(http://buttercola.blogspot.com/2015/09/leetcode-h-index.html?_sm_au_=iHVFjb76ZHj7ND5D)
1. For loop to count++ in correct buttkit regardless of the index.
If arr[x] <= n, then bucket[arr[x]]++. that means, the bucket with index of arr[x] should store this arr[x] element.
If arr[x] > n, well, that means it exceeds bucket.length (in this application, it means it's already greater than the max of h=n)
so let's just put it in bucket[n]++.
Obvisouly, we need bucket[n + 1]
2. Each bucket slot now stores #of values that's >= it's index h, in ascending order ofcourse.
so we can do another for loop, to sum one by one, from h = n ~ 0, (because we need higest possible h)
if sum >= h, that is the rst.
*/
// O(n), feel likes hashtable, where the key = citation value.
// when citation value > n, then value must > h, so put the # into bucket[n]
public class Solution {
public int hIndex(int[] citations) {
if (citations == null || citations.length == 0) {
return 0;
}
int n = citations.length;
int[] bucket = new int[n + 1]; // bucket[n] stores all extras
//fill bucket
for (int i = 0; i < n; i++) {
int bucketSlot = citations[i];
if (bucketSlot <= n) bucket[bucketSlot]++;
else bucket[n]++; //bucketSlot > n
}
//Find best H
int sum = 0;
for (int h = n; h >= 0; h--) {
sum += bucket[h]; // sum = # of citation canditate who has citationCount >= h
if (sum >= h) return h; // h-index definition
}
return 0;
}
}
// with while loop, start from beginning, O(nlogn)
public class Solution {
public int hIndex(int[] citations) {
if (citations == null || citations.length == 0) {
return 0;
}
int n = citations.length;
Arrays.sort(citations);
int i = 0;
// by definition, break when the first citations[i] >= h, where h = n - i
while (i < n && citations[i] < n - i) {
i++;
}
return n - i;
}
}
// with for loop, start from end, O(nlogn)
// 反向思考
public class Solution {
public int hIndex(int[] citations) {
if (citations == null || citations.length == 0) {
return 0;
}
int n = citations.length;
Arrays.sort(citations);
// by definition, break when the first citations[i] < h, where h = n - i
// to start, h = length of citation
int index = n;
for (int i = n - 1; i >= 0; i--) {
if (citations[i] >= n - i) {
index = i;
continue;
}
break;
}
return n - index;
}
}
/*
Thoughts:O(nlogn)
N = 5, so max of h = 5. min of h = 0.
1. h = 5, loop through the array and count the # of citations that are >= h.
2 .h = 4 ... h=1, h=0.
=> O(n^2).
If sort it : 0,1,3,5,6
Find find index x = N - h, and arr[x] >= h
that becomes find index x that arr[x] >=h ,where h = N - x.
Foor loop on h, O(n)
pick x = N - h, and check if arr[x] >= h
h = 5, x = 5 -5 = 0. arr[x] = 0 < h. not working
h = 4, x = 5 - 4 = 1. arr[x] = 1. no.
h=3,x=5-3 =2,arr[x]=3 3>=3, okay.
nLogn + N = O(nlogn)
*/
// 正向思考
public class Solution {
public int hIndex(int[] citations) {
if (citations == null || citations.length == 0) {
return 0;
}
int n = citations.length;
Arrays.sort(citations); // nlogn
for (int i = 0; i < n; i++) {
int h = n - i;
if (citations[i] >= h) {
return h;
}
}
return 0;
}
}
```
| awangdev/leet-code | Java/274.H-Index.java |
970 | package cn.hutool.db.sql;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.db.DbRuntimeException;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import java.util.Collection;
import java.util.Set;
/**
* 查询对象,用于传递查询所需的字段值<br>
* 查询对象根据表名(可以多个),多个条件 {@link Condition} 构建查询对象完成查询。<br>
* 如果想自定义返回结果,则可在查询对象中自定义要查询的字段名,分页{@link Page}信息来自定义结果。
*
* @author Looly
*
*/
public class Query {
/** 查询的字段名列表 */
Collection<String> fields;
/** 查询的表名 */
String[] tableNames;
/** 查询的条件语句 */
Condition[] where;
/** 分页对象 */
Page page;
/**
* 从{@link Entity}构建Query
* @param where 条件查询{@link Entity},包含条件Map和表名
* @return Query
* @since 5.5.3
*/
public static Query of(Entity where){
final Query query = new Query(SqlUtil.buildConditions(where), where.getTableName());
final Set<String> fieldNames = where.getFieldNames();
if(CollUtil.isNotEmpty(fieldNames)){
query.setFields(fieldNames);
}
return query;
}
// --------------------------------------------------------------- Constructor start
/**
* 构造
*
* @param tableNames 表名
*/
public Query(String... tableNames) {
this(null, tableNames);
this.tableNames = tableNames;
}
/**
* 构造
*
* @param where 条件语句
* @param tableNames 表名
*/
public Query(Condition[] where, String... tableNames) {
this(where, null, tableNames);
}
/**
* 构造
*
* @param where 条件语句
* @param page 分页
* @param tableNames 表名
*/
public Query(Condition[] where, Page page, String... tableNames) {
this(null, tableNames, where, page);
}
/**
* 构造
*
* @param fields 字段
* @param tableNames 表名
* @param where 条件
* @param page 分页
*/
public Query(Collection<String> fields, String[] tableNames, Condition[] where, Page page) {
this.fields = fields;
this.tableNames = tableNames;
this.where = where;
this.page = page;
}
// --------------------------------------------------------------- Constructor end
// --------------------------------------------------------------- Getters and Setters start
/**
* 获得查询的字段名列表
*
* @return 查询的字段名列表
*/
public Collection<String> getFields() {
return fields;
}
/**
* 设置查询的字段名列表
*
* @param fields 查询的字段名列表
* @return this
*/
public Query setFields(Collection<String> fields) {
this.fields = fields;
return this;
}
/**
* 设置查询的字段名列表
*
* @param fields 查询的字段名列表
* @return this
*/
public Query setFields(String... fields) {
this.fields = CollectionUtil.newArrayList(fields);
return this;
}
/**
* 获得表名数组
*
* @return 表名数组
*/
public String[] getTableNames() {
return tableNames;
}
/**
* 设置表名
*
* @param tableNames 表名
* @return this
*/
public Query setTableNames(String... tableNames) {
this.tableNames = tableNames;
return this;
}
/**
* 获得条件语句
*
* @return 条件语句
*/
public Condition[] getWhere() {
return where;
}
/**
* 设置条件语句
*
* @param where 条件语句
* @return this
*/
public Query setWhere(Condition... where) {
this.where = where;
return this;
}
/**
* 获得分页对象,无分页返回{@code null}
*
* @return 分页对象 or {@code null}
*/
public Page getPage() {
return page;
}
/**
* 设置分页对象
*
* @param page 分页对象
* @return this
*/
public Query setPage(Page page) {
this.page = page;
return this;
}
// --------------------------------------------------------------- Getters and Setters end
/**
* 获得第一个表名
*
* @return 表名
* @throws DbRuntimeException 没有表
*/
public String getFirstTableName() throws DbRuntimeException {
if (ArrayUtil.isEmpty(this.tableNames)) {
throw new DbRuntimeException("No tableName!");
}
return this.tableNames[0];
}
}
| dromara/hutool | hutool-db/src/main/java/cn/hutool/db/sql/Query.java |
972 | package com.macro.mall.model;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class UmsMember implements Serializable {
private Long id;
private Long memberLevelId;
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "密码")
private String password;
@ApiModelProperty(value = "昵称")
private String nickname;
@ApiModelProperty(value = "手机号码")
private String phone;
@ApiModelProperty(value = "帐号启用状态:0->禁用;1->启用")
private Integer status;
@ApiModelProperty(value = "注册时间")
private Date createTime;
@ApiModelProperty(value = "头像")
private String icon;
@ApiModelProperty(value = "性别:0->未知;1->男;2->女")
private Integer gender;
@ApiModelProperty(value = "生日")
private Date birthday;
@ApiModelProperty(value = "所做城市")
private String city;
@ApiModelProperty(value = "职业")
private String job;
@ApiModelProperty(value = "个性签名")
private String personalizedSignature;
@ApiModelProperty(value = "用户来源")
private Integer sourceType;
@ApiModelProperty(value = "积分")
private Integer integration;
@ApiModelProperty(value = "成长值")
private Integer growth;
@ApiModelProperty(value = "剩余抽奖次数")
private Integer luckeyCount;
@ApiModelProperty(value = "历史积分数量")
private Integer historyIntegration;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getMemberLevelId() {
return memberLevelId;
}
public void setMemberLevelId(Long memberLevelId) {
this.memberLevelId = memberLevelId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getPersonalizedSignature() {
return personalizedSignature;
}
public void setPersonalizedSignature(String personalizedSignature) {
this.personalizedSignature = personalizedSignature;
}
public Integer getSourceType() {
return sourceType;
}
public void setSourceType(Integer sourceType) {
this.sourceType = sourceType;
}
public Integer getIntegration() {
return integration;
}
public void setIntegration(Integer integration) {
this.integration = integration;
}
public Integer getGrowth() {
return growth;
}
public void setGrowth(Integer growth) {
this.growth = growth;
}
public Integer getLuckeyCount() {
return luckeyCount;
}
public void setLuckeyCount(Integer luckeyCount) {
this.luckeyCount = luckeyCount;
}
public Integer getHistoryIntegration() {
return historyIntegration;
}
public void setHistoryIntegration(Integer historyIntegration) {
this.historyIntegration = historyIntegration;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberLevelId=").append(memberLevelId);
sb.append(", username=").append(username);
sb.append(", password=").append(password);
sb.append(", nickname=").append(nickname);
sb.append(", phone=").append(phone);
sb.append(", status=").append(status);
sb.append(", createTime=").append(createTime);
sb.append(", icon=").append(icon);
sb.append(", gender=").append(gender);
sb.append(", birthday=").append(birthday);
sb.append(", city=").append(city);
sb.append(", job=").append(job);
sb.append(", personalizedSignature=").append(personalizedSignature);
sb.append(", sourceType=").append(sourceType);
sb.append(", integration=").append(integration);
sb.append(", growth=").append(growth);
sb.append(", luckeyCount=").append(luckeyCount);
sb.append(", historyIntegration=").append(historyIntegration);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | macrozheng/mall | mall-mbg/src/main/java/com/macro/mall/model/UmsMember.java |
973 | /*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dianping.cat.server;
public enum MetricType {
AVG("mean", "平均值"),
SUM("sum", "总和"),
MAX("max", "最大值"),
MIN("min", "最小值"),
COUNT("count", "个数");
private String m_name;
private String m_title;
private MetricType(String name, String title) {
m_name = name;
m_title = title;
}
public static MetricType getByName(String name, MetricType defaultType) {
for (MetricType type : values()) {
if (type.getName().equals(name)) {
return type;
}
}
return defaultType;
}
public String getName() {
return m_name;
}
public void setName(String name) {
m_name = name;
}
public String getTitle() {
return m_title;
}
public void setTitle(String title) {
m_title = title;
}
}
| dianping/cat | cat-core/src/main/java/com/dianping/cat/server/MetricType.java |
977 | package io.mycat.buffer;
import java.nio.ByteBuffer;
import java.util.BitSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import sun.nio.ch.DirectBuffer;
/*
* 用来保存一个一个ByteBuffer为底层存储的内存页
*/
@SuppressWarnings("restriction")
public class ByteBufferPage {
private final ByteBuffer buf;
private final int chunkSize; //chunk的大小 一般为4k
private final int chunkCount; //chunk的个数
private final BitSet chunkAllocateTrack; //某个chunk是否被分配
private final AtomicBoolean allocLockStatus = new AtomicBoolean(false); //锁
private final long startAddress;
private final ConcurrentHashMap<Long, Long> relationBufferThreadId;
public ByteBufferPage(ByteBuffer buf, int chunkSize) {
super();
this.chunkSize = chunkSize;
chunkCount = buf.capacity() / chunkSize;
chunkAllocateTrack = new BitSet(chunkCount);
relationBufferThreadId = new ConcurrentHashMap<>(chunkCount);
this.buf = buf;
startAddress = ((sun.nio.ch.DirectBuffer) buf).address();
}
public ByteBuffer allocatChunk(int theChunkCount) {
//加锁 成功执行不成功返回
if (!allocLockStatus.compareAndSet(false, true)) {
return null;
}
int startChunk = -1;//从startChunk开始的
int contiueCount = 0;//连续的chunk个数
try {
///枚举寻找连续的N个chunk
for (int i = 0; i < chunkCount; i++) {
//找到一个可用的
if (chunkAllocateTrack.get(i) == false) {
//如果是第一个 则设置startChunk
if (startChunk == -1) {
//从头开始找
startChunk = i;
contiueCount = 1;
if (theChunkCount == 1) {
break;
}
} else {
//连续chunk个数加一 ,是否找到连续的chunk个数,是则返回.
if (++contiueCount == theChunkCount) {
break;
}
}
} else {
//不连续了
startChunk = -1;
contiueCount = 0;
}
}
//找到了
if (contiueCount == theChunkCount) {
int offStart = startChunk * chunkSize;
int offEnd = offStart + theChunkCount * chunkSize;
buf.limit(offEnd);
buf.position(offStart);
ByteBuffer newBuf = buf.slice(); //分配buffer
//sun.nio.ch.DirectBuffer theBuf = (DirectBuffer) newBuf;
//System.out.println("offAddress " + (theBuf.address() - startAddress));
//设置chunk为已用
markChunksUsed(startChunk, theChunkCount);
relationBufferThreadId.put(((DirectBuffer) newBuf).address(), Thread.currentThread().getId());
return newBuf;
} else {
//System.out.println("contiueCount " + contiueCount + " theChunkCount " + theChunkCount);
return null;
}
} finally {
allocLockStatus.set(false);
}
}
//设置已用
private void markChunksUsed(int startChunk, int theChunkCount) {
for (int i = 0; i < theChunkCount; i++) {
chunkAllocateTrack.set(startChunk + i);
}
}
//清空不可用
private void markChunksUnused(int startChunk, int theChunkCount) {
for (int i = 0; i < theChunkCount; i++) {
chunkAllocateTrack.clear(startChunk + i);
}
}
/**
* 回收buffer
* @param parent 当前要释放的buf的parent
* @param recycleBuf 当前要释放的recycleBuf
* @param startChunk
* @param chunkCount
* @param relatedThreadId 用于返回当前要释放的recycleBuf关联的线程id
* @return
*/
public boolean recycleBuffer(ByteBuffer parent, ByteBuffer recycleBuf, int startChunk, int chunkCount,
StringBuilder relatedThreadId) {
if (parent == this.buf) {
//获取锁 必须获取成功
while (!this.allocLockStatus.compareAndSet(false, true)) {
Thread.yield();
}
//清空已用状态
try {
markChunksUnused(startChunk,chunkCount);
Long threadId = relationBufferThreadId.remove(((DirectBuffer) recycleBuf).address());
if (threadId != null) {
relatedThreadId.append(threadId);
}
} finally {
//释放锁
allocLockStatus.set(false);
}
return true;
}
return false;
}
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/buffer/ByteBufferPage.java |
981 | package org.jeecg.common.util;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.constant.ServiceNameConstants;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.filter.SsrfFileTypeFilter;
import org.jeecg.common.util.oss.OssBootUtil;
import org.jeecgframework.poi.util.PoiPublicUtil;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Description: 通用工具
* @author: jeecg-boot
*/
@Slf4j
public class CommonUtils {
/**
* 中文正则
*/
private static Pattern ZHONGWEN_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");
/**
* 文件名 正则字符串
* 文件名支持的字符串:字母数字中文.-_()() 除此之外的字符将被删除
*/
private static String FILE_NAME_REGEX = "[^A-Za-z\\.\\(\\)\\-()\\_0-9\\u4e00-\\u9fa5]";
public static String uploadOnlineImage(byte[] data,String basePath,String bizPath,String uploadType){
String dbPath = null;
String fileName = "image" + Math.round(Math.random() * 100000000000L);
fileName += "." + PoiPublicUtil.getFileExtendName(data);
try {
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
File file = new File(basePath + File.separator + bizPath + File.separator );
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
FileCopyUtils.copy(data, savefile);
dbPath = bizPath + File.separator + fileName;
}else {
InputStream in = new ByteArrayInputStream(data);
String relativePath = bizPath+"/"+fileName;
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
dbPath = MinioUtil.upload(in,relativePath);
}else if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
dbPath = OssBootUtil.upload(in,relativePath);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return dbPath;
}
/**
* 判断文件名是否带盘符,重新处理
* @param fileName
* @return
*/
public static String getFileName(String fileName){
//判断是否带有盘符信息
// Check for Unix-style path
int unixSep = fileName.lastIndexOf('/');
// Check for Windows-style path
int winSep = fileName.lastIndexOf('\\');
// Cut off at latest possible point
int pos = (winSep > unixSep ? winSep : unixSep);
if (pos != -1) {
// Any sort of path separator found...
fileName = fileName.substring(pos + 1);
}
//替换上传文件名字的特殊字符
fileName = fileName.replace("=","").replace(",","").replace("&","")
.replace("#", "").replace("“", "").replace("”", "");
//替换上传文件名字中的空格
fileName=fileName.replaceAll("\\s","");
//update-beign-author:taoyan date:20220302 for: /issues/3381 online 在线表单 使用文件组件时,上传文件名中含%,下载异常
fileName = fileName.replaceAll(FILE_NAME_REGEX, "");
//update-end-author:taoyan date:20220302 for: /issues/3381 online 在线表单 使用文件组件时,上传文件名中含%,下载异常
return fileName;
}
/**
* java 判断字符串里是否包含中文字符
* @param str
* @return
*/
public static boolean ifContainChinese(String str) {
if(str.getBytes().length == str.length()){
return false;
}else{
Matcher m = ZHONGWEN_PATTERN.matcher(str);
if (m.find()) {
return true;
}
return false;
}
}
/**
* 统一全局上传
* @Return: java.lang.String
*/
public static String upload(MultipartFile file, String bizPath, String uploadType) {
String url = "";
try {
if (CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)) {
url = MinioUtil.upload(file, bizPath);
} else {
url = OssBootUtil.upload(file, bizPath);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new JeecgBootException(e.getMessage());
}
return url;
}
/**
* 本地文件上传
* @param mf 文件
* @param bizPath 自定义路径
* @return
*/
public static String uploadLocal(MultipartFile mf,String bizPath,String uploadpath){
try {
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
SsrfFileTypeFilter.checkUploadFileType(mf);
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
String fileName = null;
File file = new File(uploadpath + File.separator + bizPath + File.separator );
if (!file.exists()) {
// 创建文件根目录
file.mkdirs();
}
// 获取文件名
String orgName = mf.getOriginalFilename();
orgName = CommonUtils.getFileName(orgName);
if(orgName.indexOf(SymbolConstant.SPOT)!=-1){
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
}else{
fileName = orgName+ "_" + System.currentTimeMillis();
}
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
FileCopyUtils.copy(mf.getBytes(), savefile);
String dbpath = null;
if(oConvertUtils.isNotEmpty(bizPath)){
dbpath = bizPath + File.separator + fileName;
}else{
dbpath = fileName;
}
if (dbpath.contains(SymbolConstant.DOUBLE_BACKSLASH)) {
dbpath = dbpath.replace("\\", "/");
}
return dbpath;
} catch (IOException e) {
log.error(e.getMessage(), e);
}catch (Exception e) {
log.error(e.getMessage(), e);
}
return "";
}
/**
* 统一全局上传 带桶
* @Return: java.lang.String
*/
public static String upload(MultipartFile file, String bizPath, String uploadType, String customBucket) {
String url = "";
try {
if (CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)) {
url = MinioUtil.upload(file, bizPath, customBucket);
} else {
url = OssBootUtil.upload(file, bizPath, customBucket);
}
} catch (Exception e) {
log.error(e.getMessage(),e);
}
return url;
}
/** 当前系统数据库类型 */
private static String DB_TYPE = "";
private static DbType dbTypeEnum = null;
/**
* 全局获取平台数据库类型(作废了)
* @return
*/
@Deprecated
public static String getDatabaseType() {
if(oConvertUtils.isNotEmpty(DB_TYPE)){
return DB_TYPE;
}
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
try {
return getDatabaseTypeByDataSource(dataSource);
} catch (SQLException e) {
//e.printStackTrace();
log.warn(e.getMessage(),e);
return "";
}
}
/**
* 全局获取平台数据库类型(对应mybaisPlus枚举)
* @return
*/
public static DbType getDatabaseTypeEnum() {
if (oConvertUtils.isNotEmpty(dbTypeEnum)) {
return dbTypeEnum;
}
try {
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
dbTypeEnum = JdbcUtils.getDbType(dataSource.getConnection().getMetaData().getURL());
return dbTypeEnum;
} catch (SQLException e) {
log.warn(e.getMessage(), e);
return null;
}
}
/**
* 根据数据源key获取DataSourceProperty
* @param sourceKey
* @return
*/
public static DataSourceProperty getDataSourceProperty(String sourceKey){
DynamicDataSourceProperties prop = SpringContextUtils.getApplicationContext().getBean(DynamicDataSourceProperties.class);
Map<String, DataSourceProperty> map = prop.getDatasource();
DataSourceProperty db = (DataSourceProperty)map.get(sourceKey);
return db;
}
/**
* 根据sourceKey 获取数据源连接
* @param sourceKey
* @return
* @throws SQLException
*/
public static Connection getDataSourceConnect(String sourceKey) throws SQLException {
if (oConvertUtils.isEmpty(sourceKey)) {
sourceKey = "master";
}
DynamicDataSourceProperties prop = SpringContextUtils.getApplicationContext().getBean(DynamicDataSourceProperties.class);
Map<String, DataSourceProperty> map = prop.getDatasource();
DataSourceProperty db = (DataSourceProperty)map.get(sourceKey);
if(db==null){
return null;
}
DriverManagerDataSource ds = new DriverManagerDataSource ();
ds.setDriverClassName(db.getDriverClassName());
ds.setUrl(db.getUrl());
ds.setUsername(db.getUsername());
ds.setPassword(db.getPassword());
return ds.getConnection();
}
/**
* 获取数据库类型
* @param dataSource
* @return
* @throws SQLException
*/
private static String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException{
if("".equals(DB_TYPE)) {
Connection connection = dataSource.getConnection();
try {
DatabaseMetaData md = connection.getMetaData();
String dbType = md.getDatabaseProductName().toUpperCase();
String sqlserver= "SQL SERVER";
if(dbType.indexOf(DataBaseConstant.DB_TYPE_MYSQL)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
}else if(dbType.indexOf(DataBaseConstant.DB_TYPE_ORACLE)>=0 ||dbType.indexOf(DataBaseConstant.DB_TYPE_DM)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
}else if(dbType.indexOf(DataBaseConstant.DB_TYPE_SQLSERVER)>=0||dbType.indexOf(sqlserver)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
}else if(dbType.indexOf(DataBaseConstant.DB_TYPE_POSTGRESQL)>=0 || dbType.indexOf(DataBaseConstant.DB_TYPE_KINGBASEES)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
}else if(dbType.indexOf(DataBaseConstant.DB_TYPE_MARIADB)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_MARIADB;
}else {
log.error("数据库类型:[" + dbType + "]不识别!");
//throw new JeecgBootException("数据库类型:["+dbType+"]不识别!");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}finally {
connection.close();
}
}
return DB_TYPE;
}
/**
* 获取服务器地址
*
* @param request
* @return
*/
public static String getBaseUrl(HttpServletRequest request) {
//1.【兼容】兼容微服务下的 base path-------
String xGatewayBasePath = request.getHeader(ServiceNameConstants.X_GATEWAY_BASE_PATH);
if(oConvertUtils.isNotEmpty(xGatewayBasePath)){
log.info("x_gateway_base_path = "+ xGatewayBasePath);
return xGatewayBasePath;
}
//2.【兼容】SSL认证之后,request.getScheme()获取不到https的问题
// https://blog.csdn.net/weixin_34376986/article/details/89767950
String scheme = request.getHeader(CommonConstant.X_FORWARDED_SCHEME);
if(oConvertUtils.isEmpty(scheme)){
scheme = request.getScheme();
}
//3.常规操作
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath();
//返回 host domain
String baseDomainPath = null;
//update-begin---author:wangshuai---date:2024-03-15---for:【QQYUN-8561】企业微信登陆请求接口设置上下文不一致,导致接口404---
int httpPort = 80;
int httpsPort = 443;
if(httpPort == serverPort || httpsPort == serverPort){
//update-end---author:wangshuai---date:2024-03-15---for:【QQYUN-8561】企业微信登陆请求接口设置上下文不一致,导致接口404---~
baseDomainPath = scheme + "://" + serverName + contextPath ;
}else{
baseDomainPath = scheme + "://" + serverName + ":" + serverPort + contextPath ;
}
log.debug("-----Common getBaseUrl----- : " + baseDomainPath);
return baseDomainPath;
}
/**
* 递归合并 fastJSON 对象
*
* @param target 目标对象
* @param sources 来源对象,允许多个,优先级从左到右,最右侧的优先级最高
*/
public static JSONObject mergeJSON(JSONObject target, JSONObject... sources) {
for (JSONObject source : sources) {
CommonUtils.mergeJSON(target, source);
}
return target;
}
/**
* 递归合并 fastJSON 对象
*
* @param target 目标对象
* @param source 来源对象
*/
public static JSONObject mergeJSON(JSONObject target, JSONObject source) {
for (String key : source.keySet()) {
Object sourceItem = source.get(key);
// 是否是 JSONObject
if (sourceItem instanceof Map) {
// target中存在此key
if (target.containsKey(key)) {
// 两个都是 JSONObject,继续合并
if (target.get(key) instanceof Map) {
CommonUtils.mergeJSON(target.getJSONObject(key), source.getJSONObject(key));
continue;
}
}
}
// target不存在此key,或不是 JSONObject,则覆盖
target.put(key, sourceItem);
}
return target;
}
/**
* 将list集合以分割符的方式进行分割
* @param list String类型的集合文本
* @param separator 分隔符
* @return
*/
public static String getSplitText(List<String> list, String separator) {
if (null != list && list.size() > 0) {
return StringUtils.join(list, separator);
}
return "";
}
/**
* 通过table的条件SQL
*
* @param tableSql sys_user where name = '1212'
* @return name = '1212'
*/
public static String getFilterSqlByTableSql(String tableSql) {
if(oConvertUtils.isEmpty(tableSql)){
return null;
}
if (tableSql.toLowerCase().indexOf(DataBaseConstant.SQL_WHERE) > 0) {
String[] arr = tableSql.split(" (?i)where ");
if (arr != null && oConvertUtils.isNotEmpty(arr[1])) {
return arr[1];
}
}
return "";
}
/**
* 通过table获取表名
*
* @param tableSql sys_user where name = '1212'
* @return sys_user
*/
public static String getTableNameByTableSql(String tableSql) {
if(oConvertUtils.isEmpty(tableSql)){
return null;
}
if (tableSql.toLowerCase().indexOf(DataBaseConstant.SQL_WHERE) > 0) {
String[] arr = tableSql.split(" (?i)where ");
return arr[0].trim();
} else {
return tableSql;
}
}
/**
* 判断两个数组是否存在交集
* @param set1
* @param arr2
* @return
*/
public static boolean hasIntersection(Set<String> set1, String[] arr2) {
if (set1 == null) {
return false;
}
if(set1.size()>0){
for (String str : arr2) {
if (set1.contains(str)) {
return true;
}
}
}
return false;
}
/**
* 输出info日志,会捕获异常,防止因为日志问题导致程序异常
*
* @param msg
* @param objects
*/
public static void logInfo(String msg, Object... objects) {
try {
log.info(msg, objects);
} catch (Exception e) {
log.warn("{} —— {}", msg, e.getMessage());
}
}
} | jeecgboot/jeecg-boot | jeecg-boot-base-core/src/main/java/org/jeecg/common/util/CommonUtils.java |
982 | package me.zhyd.oauth.request;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
import me.zhyd.oauth.enums.AuthToutiaoErrorCode;
import me.zhyd.oauth.enums.AuthUserGender;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.UrlBuilder;
/**
* 今日头条登录
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @since 1.6.0-beta
*/
public class AuthToutiaoRequest extends AuthDefaultRequest {
public AuthToutiaoRequest(AuthConfig config) {
super(config, AuthDefaultSource.TOUTIAO);
}
public AuthToutiaoRequest(AuthConfig config, AuthStateCache authStateCache) {
super(config, AuthDefaultSource.TOUTIAO, authStateCache);
}
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
String response = doGetAuthorizationCode(authCallback.getCode());
JSONObject accessTokenObject = JSONObject.parseObject(response);
this.checkResponse(accessTokenObject);
return AuthToken.builder()
.accessToken(accessTokenObject.getString("access_token"))
.expireIn(accessTokenObject.getIntValue("expires_in"))
.openId(accessTokenObject.getString("open_id"))
.build();
}
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
String userResponse = doGetUserInfo(authToken);
JSONObject userProfile = JSONObject.parseObject(userResponse);
this.checkResponse(userProfile);
JSONObject user = userProfile.getJSONObject("data");
boolean isAnonymousUser = user.getIntValue("uid_type") == 14;
String anonymousUserName = "匿名用户";
return AuthUser.builder()
.rawUserInfo(user)
.uuid(user.getString("uid"))
.username(isAnonymousUser ? anonymousUserName : user.getString("screen_name"))
.nickname(isAnonymousUser ? anonymousUserName : user.getString("screen_name"))
.avatar(user.getString("avatar_url"))
.remark(user.getString("description"))
.gender(AuthUserGender.getRealGender(user.getString("gender")))
.token(authToken)
.source(source.toString())
.build();
}
/**
* 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state}
*
* @param state state 验证授权流程的参数,可以防止csrf
* @return 返回授权地址
* @since 1.9.3
*/
@Override
public String authorize(String state) {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("response_type", "code")
.queryParam("client_key", config.getClientId())
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("auth_only", 1)
.queryParam("display", 0)
.queryParam("state", getRealState(state))
.build();
}
/**
* 返回获取accessToken的url
*
* @param code 授权码
* @return 返回获取accessToken的url
*/
@Override
protected String accessTokenUrl(String code) {
return UrlBuilder.fromBaseUrl(source.accessToken())
.queryParam("code", code)
.queryParam("client_key", config.getClientId())
.queryParam("client_secret", config.getClientSecret())
.queryParam("grant_type", "authorization_code")
.build();
}
/**
* 返回获取userInfo的url
*
* @param authToken 用户授权后的token
* @return 返回获取userInfo的url
*/
@Override
protected String userInfoUrl(AuthToken authToken) {
return UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("client_key", config.getClientId())
.queryParam("access_token", authToken.getAccessToken())
.build();
}
/**
* 检查响应内容是否正确
*
* @param object 请求响应内容
*/
private void checkResponse(JSONObject object) {
if (object.containsKey("error_code")) {
throw new AuthException(AuthToutiaoErrorCode.getErrorCode(object.getIntValue("error_code")).getDesc());
}
}
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/request/AuthToutiaoRequest.java |
983 | package me.zhyd.oauth.request;
import com.alibaba.fastjson.JSONObject;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.enums.AuthUserGender;
import me.zhyd.oauth.enums.scope.AuthJdScope;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.utils.AuthScopeUtils;
import me.zhyd.oauth.utils.GlobalAuthUtils;
import me.zhyd.oauth.utils.HttpUtils;
import me.zhyd.oauth.utils.UrlBuilder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
/**
* 京东登录
*
* @author harry.lee ([email protected])
* @since 1.15.0
*/
public class AuthJdRequest extends AuthDefaultRequest {
public AuthJdRequest(AuthConfig config) {
super(config, AuthDefaultSource.JD);
}
public AuthJdRequest(AuthConfig config, AuthStateCache authStateCache) {
super(config, AuthDefaultSource.JD, authStateCache);
}
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
Map<String, String> params = new HashMap<>(7);
params.put("app_key", config.getClientId());
params.put("app_secret", config.getClientSecret());
params.put("grant_type", "authorization_code");
params.put("code", authCallback.getCode());
String response = new HttpUtils(config.getHttpConfig()).post(source.accessToken(), params, false).getBody();
JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
return AuthToken.builder()
.accessToken(object.getString("access_token"))
.expireIn(object.getIntValue("expires_in"))
.refreshToken(object.getString("refresh_token"))
.scope(object.getString("scope"))
.openId(object.getString("open_id"))
.build();
}
@Override
protected AuthUser getUserInfo(AuthToken authToken) {
UrlBuilder urlBuilder = UrlBuilder.fromBaseUrl(source.userInfo())
.queryParam("access_token", authToken.getAccessToken())
.queryParam("app_key", config.getClientId())
.queryParam("method", "jingdong.user.getUserInfoByOpenId")
.queryParam("360buy_param_json", "{\"openId\":\"" + authToken.getOpenId() + "\"}")
.queryParam("timestamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
.queryParam("v", "2.0");
urlBuilder.queryParam("sign", GlobalAuthUtils.generateJdSignature(config.getClientSecret(), urlBuilder.getReadOnlyParams()));
String response = new HttpUtils(config.getHttpConfig()).post(urlBuilder.build(true)).getBody();
JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
JSONObject data = this.getUserDataJsonObject(object);
return AuthUser.builder()
.rawUserInfo(data)
.uuid(authToken.getOpenId())
.username(data.getString("nickName"))
.nickname(data.getString("nickName"))
.avatar(data.getString("imageUrl"))
.gender(AuthUserGender.getRealGender(data.getString("gendar")))
.token(authToken)
.source(source.toString())
.build();
}
/**
* 个人用户无法申请应用
* 暂时只能参考官网给出的返回结果解析
*
* @param object 请求返回结果
* @return data JSONObject
*/
private JSONObject getUserDataJsonObject(JSONObject object) {
return object.getJSONObject("jingdong_user_getUserInfoByOpenId_response")
.getJSONObject("getuserinfobyappidandopenid_result")
.getJSONObject("data");
}
@Override
public AuthResponse refresh(AuthToken oldToken) {
Map<String, String> params = new HashMap<>(7);
params.put("app_key", config.getClientId());
params.put("app_secret", config.getClientSecret());
params.put("grant_type", "refresh_token");
params.put("refresh_token", oldToken.getRefreshToken());
String response = new HttpUtils(config.getHttpConfig()).post(source.refresh(), params, false).getBody();
JSONObject object = JSONObject.parseObject(response);
this.checkResponse(object);
return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode())
.data(AuthToken.builder()
.accessToken(object.getString("access_token"))
.expireIn(object.getIntValue("expires_in"))
.refreshToken(object.getString("refresh_token"))
.scope(object.getString("scope"))
.openId(object.getString("open_id"))
.build())
.build();
}
private void checkResponse(JSONObject object) {
if (object.containsKey("error_response")) {
throw new AuthException(object.getJSONObject("error_response").getString("zh_desc"));
}
}
@Override
public String authorize(String state) {
return UrlBuilder.fromBaseUrl(source.authorize())
.queryParam("app_key", config.getClientId())
.queryParam("response_type", "code")
.queryParam("redirect_uri", config.getRedirectUri())
.queryParam("scope", this.getScopes(" ", true, AuthScopeUtils.getDefaultScopes(AuthJdScope.values())))
.queryParam("state", getRealState(state))
.build();
}
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/request/AuthJdRequest.java |
986 | package com.alibaba.otter.canal.sink.entry;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.EntryType;
import com.alibaba.otter.canal.protocol.position.LogIdentity;
import com.alibaba.otter.canal.sink.AbstractCanalEventSink;
import com.alibaba.otter.canal.sink.CanalEventDownStreamHandler;
import com.alibaba.otter.canal.sink.CanalEventSink;
import com.alibaba.otter.canal.sink.exception.CanalSinkException;
import com.alibaba.otter.canal.store.CanalEventStore;
import com.alibaba.otter.canal.store.memory.MemoryEventStoreWithBuffer;
import com.alibaba.otter.canal.store.model.Event;
/**
* mysql binlog数据对象输出
*
* @author jianghang 2012-7-4 下午03:23:16
* @version 1.0.0
*/
public class EntryEventSink extends AbstractCanalEventSink<List<CanalEntry.Entry>> implements CanalEventSink<List<CanalEntry.Entry>> {
private static final Logger logger = LoggerFactory.getLogger(EntryEventSink.class);
private static final int maxFullTimes = 10;
private CanalEventStore<Event> eventStore;
protected boolean filterTransactionEntry = false; // 是否需要尽可能过滤事务头/尾
protected boolean filterEmtryTransactionEntry = true; // 是否需要过滤空的事务头/尾
protected long emptyTransactionInterval = 5 * 1000; // 空的事务输出的频率
protected long emptyTransctionThresold = 8192; // 超过8192个事务头,输出一个
protected volatile long lastTransactionTimestamp = 0L;
protected AtomicLong lastTransactionCount = new AtomicLong(0L);
protected volatile long lastEmptyTransactionTimestamp = 0L;
protected AtomicLong lastEmptyTransactionCount = new AtomicLong(0L);
protected AtomicLong eventsSinkBlockingTime = new AtomicLong(0L);
protected boolean raw;
public EntryEventSink(){
addHandler(new HeartBeatEntryEventHandler());
}
public void start() {
super.start();
Assert.notNull(eventStore);
if (eventStore instanceof MemoryEventStoreWithBuffer) {
this.raw = ((MemoryEventStoreWithBuffer) eventStore).isRaw();
}
for (CanalEventDownStreamHandler handler : getHandlers()) {
if (!handler.isStart()) {
handler.start();
}
}
}
public void stop() {
super.stop();
for (CanalEventDownStreamHandler handler : getHandlers()) {
if (handler.isStart()) {
handler.stop();
}
}
}
public boolean filter(List<Entry> event, InetSocketAddress remoteAddress, String destination) {
return false;
}
public boolean sink(List<CanalEntry.Entry> entrys, InetSocketAddress remoteAddress, String destination)
throws CanalSinkException,
InterruptedException {
return sinkData(entrys, remoteAddress);
}
private boolean sinkData(List<CanalEntry.Entry> entrys, InetSocketAddress remoteAddress)
throws InterruptedException {
boolean hasRowData = false;
boolean hasHeartBeat = false;
List<Event> events = new ArrayList<>();
for (CanalEntry.Entry entry : entrys) {
if (!doFilter(entry)) {
continue;
}
if (filterTransactionEntry
&& (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND)) {
long currentTimestamp = entry.getHeader().getExecuteTime();
// 基于一定的策略控制,放过空的事务头和尾,便于及时更新数据库位点,表明工作正常
if (lastTransactionCount.incrementAndGet() <= emptyTransctionThresold
&& Math.abs(currentTimestamp - lastTransactionTimestamp) <= emptyTransactionInterval) {
continue;
} else {
// fixed issue https://github.com/alibaba/canal/issues/2616
// 主要原因在于空事务只发送了begin,没有同步发送commit信息,这里修改为只对commit事件做计数更新,确保begin/commit成对出现
if (entry.getEntryType() == EntryType.TRANSACTIONEND) {
lastTransactionCount.set(0L);
lastTransactionTimestamp = currentTimestamp;
}
}
}
hasRowData |= (entry.getEntryType() == EntryType.ROWDATA);
hasHeartBeat |= (entry.getEntryType() == EntryType.HEARTBEAT);
Event event = new Event(new LogIdentity(remoteAddress, -1L), entry, raw);
events.add(event);
}
if (hasRowData || hasHeartBeat) {
// 存在row记录 或者 存在heartbeat记录,直接跳给后续处理
return doSink(events);
} else {
// 需要过滤的数据
if (filterEmtryTransactionEntry && !CollectionUtils.isEmpty(events)) {
long currentTimestamp = events.get(0).getExecuteTime();
// 基于一定的策略控制,放过空的事务头和尾,便于及时更新数据库位点,表明工作正常
if (Math.abs(currentTimestamp - lastEmptyTransactionTimestamp) > emptyTransactionInterval
|| lastEmptyTransactionCount.incrementAndGet() > emptyTransctionThresold) {
lastEmptyTransactionCount.set(0L);
lastEmptyTransactionTimestamp = currentTimestamp;
return doSink(events);
}
}
// 直接返回true,忽略空的事务头和尾
return true;
}
}
protected boolean doFilter(CanalEntry.Entry entry) {
if (filter != null && entry.getEntryType() == EntryType.ROWDATA) {
String name = getSchemaNameAndTableName(entry);
boolean need = filter.filter(name);
if (!need) {
logger.debug("filter name[{}] entry : {}:{}",
name,
entry.getHeader().getLogfileName(),
entry.getHeader().getLogfileOffset());
}
return need;
} else {
return true;
}
}
protected boolean doSink(List<Event> events) {
for (CanalEventDownStreamHandler<List<Event>> handler : getHandlers()) {
events = handler.before(events);
}
long blockingStart = 0L;
int fullTimes = 0;
do {
if (eventStore.tryPut(events)) {
if (fullTimes > 0) {
eventsSinkBlockingTime.addAndGet(System.nanoTime() - blockingStart);
}
for (CanalEventDownStreamHandler<List<Event>> handler : getHandlers()) {
events = handler.after(events);
}
return true;
} else {
if (fullTimes == 0) {
blockingStart = System.nanoTime();
}
applyWait(++fullTimes);
if (fullTimes % 100 == 0) {
long nextStart = System.nanoTime();
eventsSinkBlockingTime.addAndGet(nextStart - blockingStart);
blockingStart = nextStart;
}
}
for (CanalEventDownStreamHandler<List<Event>> handler : getHandlers()) {
events = handler.retry(events);
}
} while (running && !Thread.interrupted());
return false;
}
// 处理无数据的情况,避免空循环挂死
private void applyWait(int fullTimes) {
int newFullTimes = fullTimes > maxFullTimes ? maxFullTimes : fullTimes;
if (fullTimes <= 3) { // 3次以内
Thread.yield();
} else { // 超过3次,最多只sleep 10ms
LockSupport.parkNanos(1000 * 1000L * newFullTimes);
}
}
private String getSchemaNameAndTableName(CanalEntry.Entry entry) {
return entry.getHeader().getSchemaName() + "." + entry.getHeader().getTableName();
}
public void setEventStore(CanalEventStore<Event> eventStore) {
this.eventStore = eventStore;
}
public void setFilterTransactionEntry(boolean filterTransactionEntry) {
this.filterTransactionEntry = filterTransactionEntry;
}
public void setFilterEmtryTransactionEntry(boolean filterEmtryTransactionEntry) {
this.filterEmtryTransactionEntry = filterEmtryTransactionEntry;
}
public void setEmptyTransactionInterval(long emptyTransactionInterval) {
this.emptyTransactionInterval = emptyTransactionInterval;
}
public void setEmptyTransctionThresold(long emptyTransctionThresold) {
this.emptyTransctionThresold = emptyTransctionThresold;
}
public AtomicLong getEventsSinkBlockingTime() {
return eventsSinkBlockingTime;
}
}
| alibaba/canal | sink/src/main/java/com/alibaba/otter/canal/sink/entry/EntryEventSink.java |
988 | package com.zheng.common.util;
import javax.servlet.http.HttpServletRequest;
/**
* 分页实体类
* @author shuzheng
* @date 2016年7月6日 下午6:05:00
*/
public class Paginator {
// 总记录数
private long total = 0L;
// 当前页数
private int page = 1;
// 总页数
private long totalPage = 1;
// 每页记录数
private int rows = 10;
// 最多显示分页页码数
private int step = 5;
// 分页参数名称,用于支持一个页面多个分页功能
private String param = "page";
// 项目路径
private String url = "";
// 当前页所有参数
private String query = "";
public Paginator() {
}
public Paginator(long total, int page, int rows, HttpServletRequest request) {
setTotal(total);
setPage(page);
setRows(rows);
setUrl(request.getRequestURI());
setQuery(request.getQueryString());
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
this.initTotalPage();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public long getTotalPage() {
return totalPage;
}
public void setTotalPage(long totalPage) {
this.totalPage = totalPage;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
// 设置个最大记录数,限制单页记录过多
if (rows > 10000) {
rows = 10000;
}
this.rows = rows;
this.initTotalPage();
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
/**
* 初始化分页信息
*/
public void initTotalPage() {
totalPage = (total % rows) == 0 ? (total / rows) : ((total / rows) + 1);
if (page > totalPage) {
page = (int) totalPage;
}
if (page < 1) {
page = 1;
}
}
/**
* 生成简单的分页页面内容
* @return
*/
public String getHtml() {
// 根据request获取当前url,包括参数,如果有已存在名称未paramname的参数,剔除掉,后面会追加新的参数
//String contextPath = request.getContextPath();
//String requestURI = request.getRequestURI();
//String url = contextPath + requestURI;
//String url = request.getRequestURI();
//String query = request.getQueryString();
if (query != null) {
String params = "";
String[] querys = query.split("&");
for (int i = 0; i < querys.length; i++) {
if (querys[i].startsWith(param)) {
continue;
}
if ("".equals(params)) {
params = querys[i];
} else {
params += "&" + querys[i];
}
}
if (!"".equals(params)) {
url += "?" + params;
}
}
// 结果html
String pages = "";
int pageCount = (int) Math.ceil((double) total / rows);// 求总页数
if (pageCount <= 1) {
return pages;
}
if (page > pageCount) {
page = pageCount;// 如果分页变量大总页数,则将分页变量设计为总页数
}
if (page <= 0) {
page = 1;// 如果分页变量小于1,则将分页变量设为1
}
// 显示上一页
if (page > 1) {
if (url.contains("?")) {
pages = pages.concat("<a class=\"prev\" href=\"" + url + "&" + param + "=" + (page - 1) + "\">上一页</a>\n");
} else {
pages = pages.concat("<a class=\"prev\" href=\"" + url + "?" + param + "=" + (page - 1) + "\">上一页</a>\n");
}
} else {
// 特定需求可隐藏
pages = pages.concat("<a class=\"prev\" href=\"javascript:;\" style=\"color:#ccc\">上一页</a>\n");
}
// 如果总页数大于要显示的个数,则拼接显示
if (pageCount > step) {
// 显示分页码
int listBegin = (page - (int) Math.floor((double) step / 2));// 从第几页开始显示分页信息
if (listBegin < 1) {
listBegin = 1;
}
// 显示第1页
if (listBegin >= 2) {
if (url.contains("?")) {
pages = pages.concat("<a href=\"" + url + "&" + param + "=1\">1</a> ... \n");
} else {
pages = pages.concat("<a href=\"" + url + "?" + param + "=1\">1</a> ... \n");
}
}
// 当前页数右侧还有未显示页码时
if (pageCount - page >= page - listBegin) {
for (int i = listBegin; i < (listBegin + step); i++) {
if (i != page) {
if (url.contains("?")) {
pages = pages.concat("<a href=\"" + url + "&" + param + "=" + i + "\">" + i + "</a>\n");
} else {
pages = pages.concat("<a href=\"" + url + "?" + param + "=" + i + "\">" + i + "</a>\n");
}
} else {
pages = pages.concat("<span class=\"current\">" + i + "</span>\n");
}
}
// 显示最后1页
if (listBegin + step <= pageCount) {
if (url.contains("?")) {
pages = pages.concat(" ... <a href=\"" + url + "&" + param + "=" + pageCount + "\">" + pageCount + "</a>\n");
} else {
pages = pages.concat(" ... <a href=\"" + url + "?" + param + "=" + pageCount + "\">" + pageCount + "</a>\n");
}
}
} else { // 显示最后剩余的几个页码
for (int i = (pageCount - step) + 1; i <= pageCount; i++) {
if (i != page) {
if (url.contains("?")) {
pages = pages.concat("<a href=\"" + url + "&" + param + "=" + i + "\">" + i + "</a>\n");
} else {
pages = pages.concat("<a href=\"" + url + "?" + param + "=" + i + "\">" + i + "</a>\n");
}
} else {
pages = pages.concat("<span class=\"current\">" + i + "</span>\n");
}
}
}
} else { // 总页数小于等于step时,直接显示
for (int i = 1; i <= pageCount; i++) {
if (i != page) {
if (url.contains("?")) {
pages = pages.concat("<a href=\"" + url + "&" + param + "=" + i + "\">" + i + "</a>\n");
} else {
pages = pages.concat("<a href=\"" + url + "?" + param + "=" + i + "\">" + i + "</a>\n");
}
} else {
pages = pages.concat("<span class=\"current\">" + i + "</span>\n");
}
}
}
// 显示下一页
if (page < pageCount) {
if (url.contains("?")) {
pages = pages.concat("<a class=\"next\" href=\"" + url + "&" + param + "=" + (page + 1) + "\">下一页</a>\n");
} else {
pages = pages.concat("<a class=\"next\" href=\"" + url + "?" + param + "=" + (page + 1) + "\">下一页</a>\n");
}
} else {
// 特定需求可隐藏
pages = pages.concat("<a class=\"next\" href=\"javascript:;\" style=\"color:#ccc\">下一页</a>\n");
}
return pages;
}
}
| shuzheng/zheng | zheng-common/src/main/java/com/zheng/common/util/Paginator.java |
990 | /**
* @author mcrwayfun
* @version v1.0
* @date Created in 2019/01/23
* @description
*/
public class Solution {
public int GetUglyNumber_Solution(int index) {
if (index <= 0)
return 0;
List<Integer> reList = new ArrayList<>();
// 第一个丑数为1
reList.add(1);
int i2 = 0, i3 = 0, i5 = 0;
while (reList.size() < index) {
int m2 = reList.get(i2) * 2;
int m3 = reList.get(i3) * 3;
int m5 = reList.get(i5) * 5;
// 求出m2、m3、m5中的最小值,该值为加入list的丑数
int min = Math.min(m2, Math.min(m3, m5));
if (m2 == min) {
i2++;
}
if (m3 == min) {
i3++;
}
if (m5 == min) {
i5++;
}
reList.add(min);
}
// O(1)
return reList.get(reList.size() - 1);
}
} | geekxh/hello-algorithm | 算法读物/剑指offer/49_UglyNumber/Solution.java |
992 | M
tags: Hash Table, Linked List
time: O(n)
space: O(n)
deep copy linked list. linked list 上有random pointer to other nodes.
#### HashMap, Linked List, time, space: O(n)
- Basic Implementation of copy linked list:
- use a iterator node to iterate over the list: 遍历head.next .... null.
- use a dummy node to hold reference to the iterator node.
- Map<original, new node>: 1. avoid creating same node; 2. return the new node if existing
- 每一步都check map里面有没有head. 没有? 加上
- 每一步都check map里面有没有head.random. 没有? 加上
- Note, there is a way to skip the extra map O(n): https://leetcode.com/problems/copy-list-with-random-pointer/discuss/43491/A-solution-with-constant-space-complexity-O(1)-and-linear-time-complexity-O(N)
- However, creating a deep clone of the list is already O(n) extra space, so it is NOT effectively O(1) w/o map
- It may be beneficial, if we can not hold all nodes in memory, then the approach w/o map is more applicable.
```
/*
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Input:
{
"$id":"1",
"next":{
"$id":"2",
"next":null,
"random":{"$ref":"2"},
"val":2
},
"random":{"$ref":"2"},
"val":1
}
Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.
*/
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
/*
Iterative through the list.
Use a dummyHead and return dummyHead.next at the end.
In each iteration, check if Head is already exist, or make a new one
* use HashMap<oldNode, newNode> to mark if a node has been visited.
deep copy the random node of head as well.
border case: if head == null, return null
*/
class Solution {
public Node copyRandomList(Node head) {
Node node = new Node(); //creat node, used to iterate over all nodes
Node dummy = node;
HashMap<Node, Node> map = new HashMap<>(); // <original, new>
while(head != null) {
// replicate head and head.random
replicateNode(map, head);
replicateNode(map, head.random);
node.next = map.get(head);
node.next.random = map.get(head.random);
node = node.next;
head = head.next;
}
return dummy.next;
}
private void replicateNode(HashMap<Node, Node> map, Node original) {
if (original == null) return;
if (!map.containsKey(original)) {
Node newNode = new Node();
newNode.val = original.val;
map.put(original, newNode);
}
}
}
/*
Thinking process:
1. Loop through the original list
2. Use a HashMap<old node, new node>. User the old node as a key and new node as value.
3. Doesn't matter of the order of node that being added into the hashMap.
For example, node1 is added.
node1.random, which is node 99, will be added into hashMap right after node1.
4. During the loop:
If head exist in hashmap, get it; if not existed, create new node using head, add into hashMap
If head.random exist, get it; if not, add a new node using head.random.
*/
public class Solution {
public Node copyRandomList(Node head) {
HashMap<Node, Node> map = new HashMap<>();
Node dummy = new Node();
Node pre = dummy;
Node newNode;
while (head != null) {
//Add new node
if (map.containsKey(head)) {
newNode = map.get(head);
} else {
newNode = new Node();
newNode.val = head.val;
map.put(head, newNode);
}
//Add new node's random node
if (head.random != null) {
if (map.containsKey(head.random)) {
newNode.random = map.get(head.random);
} else {
newNode.random = new Node(head.random.val);
map.put(head.random, newNode.random);
}
}
//append and shift
pre.next = newNode;
pre = newNode;
head = head.next;
}
return dummy.next;
}
}
``` | awangdev/leet-code | Java/138. Copy List with Random Pointer.java |
993 | /*
* Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.backend.datasource;
import io.mycat.MycatServer;
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import io.mycat.backend.BackendConnection;
import io.mycat.backend.mysql.nio.handler.ResponseHandler;
import io.mycat.route.RouteResultsetNode;
public class PhysicalDBNode {
protected static final Logger LOGGER = LoggerFactory
.getLogger(PhysicalDBNode.class);
protected final String name;
protected final String database;
protected final PhysicalDBPool dbPool;
public PhysicalDBNode(String hostName, String database,
PhysicalDBPool dbPool) {
this.name = hostName;
this.database = database;
this.dbPool = dbPool;
}
public String getName() {
return name;
}
public PhysicalDBPool getDbPool() {
return dbPool;
}
public String getDatabase() {
return database;
}
/**
* get connection from the same datasource
*
* @param exitsCon
* @throws Exception
*/
public void getConnectionFromSameSource(String schema,boolean autocommit,
BackendConnection exitsCon, ResponseHandler handler,
Object attachment) throws Exception {
PhysicalDatasource ds = this.dbPool.findDatasouce(exitsCon);
if (ds == null) {
throw new RuntimeException(
"can't find existing connection,maybe fininshed " + exitsCon);
} else {
ds.getConnection(schema,autocommit, handler, attachment);
}
}
private void checkRequest(String schema){
if (schema != null
&& !schema.equals(this.database)) {
throw new RuntimeException(
"invalid param ,connection request db is :"
+ schema + " and datanode db is "
+ this.database);
}
if (!dbPool.isInitSuccess()) {
dbPool.init(dbPool.activedIndex);
}
}
public void getConnection(String schema,boolean autoCommit, RouteResultsetNode rrs,
ResponseHandler handler, Object attachment) throws Exception {
checkRequest(schema);
boolean needMaster = !autoCommit && MycatServer.getInstance().getConfig().getSystem().isStrictTxIsolation();
if (needMaster && rrs.getRunOnSlave()==null){
rrs.setRunOnSlave(false);//#2305
}
if (dbPool.isInitSuccess()) {
LOGGER.debug("rrs.getRunOnSlave() " + rrs.getRunOnSlaveDebugInfo());
if(rrs.getRunOnSlave() != null){ // 带有 /*db_type=master/slave*/ 注解
// 强制走 slave
if(rrs.getRunOnSlave()){
LOGGER.debug("rrs.isHasBlanceFlag() " + rrs.isHasBlanceFlag());
if (rrs.isHasBlanceFlag()) { // 带有 /*balance*/ 注解(目前好像只支持一个注解...)
dbPool.getReadBanlanceCon(schema,autoCommit,handler, attachment, this.database);
}else{ // 没有 /*balance*/ 注解
LOGGER.debug("rrs.isHasBlanceFlag()" + rrs.isHasBlanceFlag());
if(!dbPool.getReadCon(schema, autoCommit, handler, attachment, this.database)){
LOGGER.warn("Do not have slave connection to use, use master connection instead.");
PhysicalDatasource writeSource=dbPool.getSource();
//记录写节点写负载值
writeSource.setWriteCount();
writeSource.getConnection(schema,
autoCommit, handler, attachment);
rrs.setRunOnSlave(false);
rrs.setCanRunInReadDB(false);
}
}
}else{ // 强制走 master
// 默认获得的是 writeSource,也就是 走master
LOGGER.debug("rrs.getRunOnSlave() " + rrs.getRunOnSlaveDebugInfo());
PhysicalDatasource writeSource=dbPool.getSource();
//记录写节点写负载值
writeSource.setWriteCount();
writeSource.getConnection(schema, autoCommit,
handler, attachment);
rrs.setCanRunInReadDB(false);
}
}else{ // 没有 /*db_type=master/slave*/ 注解,按照原来的处理方式
LOGGER.debug("rrs.getRunOnSlave() " + rrs.getRunOnSlaveDebugInfo()); // null
if (rrs.canRunnINReadDB(autoCommit)) {
dbPool.getRWBanlanceCon(schema,autoCommit, handler, attachment, this.database);
} else {
PhysicalDatasource writeSource =dbPool.getSource();
//记录写节点写负载值
writeSource.setWriteCount();
writeSource.getConnection(schema, autoCommit,
handler, attachment);
}
}
} else {
throw new IllegalArgumentException("Invalid DataSource:" + dbPool.getActivedIndex());
}
}
// public void getConnection(String schema,boolean autoCommit, RouteResultsetNode rrs,
// ResponseHandler handler, Object attachment) throws Exception {
// checkRequest(schema);
// if (dbPool.isInitSuccess()) {
// if (rrs.canRunnINReadDB(autoCommit)) {
// dbPool.getRWBanlanceCon(schema,autoCommit, handler, attachment,
// this.database);
// } else {
// dbPool.getSource().getConnection(schema,autoCommit, handler, attachment);
// }
//
// } else {
// throw new IllegalArgumentException("Invalid DataSource:"
// + dbPool.getActivedIndex());
// }
// }
} | MyCATApache/Mycat-Server | src/main/java/io/mycat/backend/datasource/PhysicalDBNode.java |
994 | /**
* Copyright (c) 2011-2023, 玛雅牛 (myaniu AT gmail.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jfinal.core.paragetter;
import com.jfinal.core.Action;
import com.jfinal.core.Controller;
/**
* 使用构建好的 IParaGetter 数组获取用于 action 方法实参的参数值
*/
public class ParaProcessor implements IParaGetter<Object[]> {
private int fileParaIndex = -1;
private IParaGetter<?>[] paraGetters;
public ParaProcessor(int paraCount) {
paraGetters = paraCount > 0 ? new IParaGetter<?>[paraCount] : null;
}
public void addParaGetter(int index, IParaGetter<?> paraGetter) {
// fileParaIndex 记录第一个 File、UploadFile 的数组下标
if ( fileParaIndex == -1 &&
(paraGetter instanceof FileGetter || paraGetter instanceof UploadFileGetter)) {
fileParaIndex = index;
}
paraGetters[index] = paraGetter;
}
@Override
public Object[] get(Action action, Controller c) {
int len = paraGetters.length;
Object[] ret = new Object[len];
// 没有 File、UploadFile 参数的 action
if (fileParaIndex == -1) {
for (int i=0; i<len; i++) {
ret[i] = paraGetters[i].get(action, c);
}
return ret;
}
// 有 File、UploadFile 参数的 action,优先获取 File、UploadFile 对象
Object fileRet = paraGetters[fileParaIndex].get(action, c);
for (int i=0; i<len; i++) {
if (i != fileParaIndex) {
ret[i] = paraGetters[i].get(action, c);
} else {
ret[i] = fileRet;
}
}
return ret;
}
}
| jfinal/jfinal | src/main/java/com/jfinal/core/paragetter/ParaProcessor.java |
995 | package com.vip.vjtools.vjkit.datamasking;
import com.alibaba.fastjson.serializer.BeanContext;
import com.alibaba.fastjson.serializer.ContextValueFilter;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
/**
* 对每个json字段进行脱敏处理
* 处理String,String[] Collection<String>
*/
public class DataMaskJsonFilter implements ContextValueFilter {
@Override
public Object process(BeanContext context, Object object, String name, Object value) {
if (null == value) {
return null;
}
try {
Field field = context.getField();
//处理字符串,只处理字符串相关类型的字段
if (field.getType() == String.class) {
if (((String) value).length() == 0) {
return value;
}
Sensitive sensitive = field.getAnnotation(Sensitive.class);
SensitiveType sensitiveType = getSensitiveType(field, sensitive);
return mask((String) value, sensitive, sensitiveType);
} else if (field.getType() == String[].class) {
//处理数组String[]
Sensitive sensitive = field.getAnnotation(Sensitive.class);
SensitiveType sensitiveType = getSensitiveType(field, sensitive);
if (sensitiveType == null) {
return value;
}
String[] strArr = (String[]) value;
for (int i = 0; i < strArr.length; i++) {
strArr[i] = mask(strArr[i], sensitive, sensitiveType);
}
return strArr;
} else if (Collection.class.isAssignableFrom(field.getType())) {
//处理Collection<String>
Sensitive sensitive = field.getAnnotation(Sensitive.class);
SensitiveType sensitiveType = getSensitiveType(field, sensitive);
if (sensitiveType == null) {
return value;
}
if(!isStringCollection(field)){
return value;
}
//没有set()的接口,重新构造一个
Collection<String> newValue = (Collection<String>) value.getClass().newInstance();
for (String item : (Collection<String>) value) {
newValue.add(mask(item, sensitive, sensitiveType));
}
return newValue;
} else {
return value;
}
} catch (Exception e) {
return value;
}
}
/**
* 是否Collection<String>
* @param field
* @return
*/
private boolean isStringCollection(Field field){
Type type = field.getGenericType();
if (!(type instanceof ParameterizedType)) {
return false;
}
Class parameterizedType = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
if (parameterizedType != String.class) {
return false;
}
return true;
}
/**
* 对字段进行mask
* @param value 值
* @return 脱敏后的值
*/
private String mask(String value, Sensitive sensitive, SensitiveType type) {
if (value == null || value.isEmpty()) {
return value;
}
if (sensitive == null) {
if (type != null) {
return DataMask.mask(value, type);
} else {
return value;
}
} else {
return sensitive.type().getStrategy().mask(value, sensitive.keepChars());
}
}
private SensitiveType getSensitiveType(Field field, Sensitive sensitive) {
SensitiveType type = null;
if (sensitive == null) {
String fieldName = field.getName();
//没有@Sensitive,但是有mapping命中
type = MaskMapping.getMaskTypeMapping(fieldName);
} else {
type = sensitive.type();
}
return type;
}
}
| vipshop/vjtools | vjkit/src/main/java/com/vip/vjtools/vjkit/datamasking/DataMaskJsonFilter.java |
999 | package com.macro.mall.tiny.strategy;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.macro.mall.tiny.anno.CustomMerge;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* 自定义单元格合并策略
*/
public class CustomMergeStrategy implements RowWriteHandler {
/**
* 主键下标
*/
private Integer pkIndex;
/**
* 需要合并的列的下标集合
*/
private List<Integer> needMergeColumnIndex = new ArrayList<>();
/**
* DTO数据类型
*/
private Class<?> elementType;
public CustomMergeStrategy(Class<?> elementType) {
this.elementType = elementType;
}
@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
// 如果是标题,则直接返回
if (isHead) {
return;
}
// 获取当前sheet
Sheet sheet = writeSheetHolder.getSheet();
// 获取标题行
Row titleRow = sheet.getRow(0);
if (null == pkIndex) {
this.lazyInit(writeSheetHolder);
}
// 判断是否需要和上一行进行合并
// 不能和标题合并,只能数据行之间合并
if (row.getRowNum() <= 1) {
return;
}
// 获取上一行数据
Row lastRow = sheet.getRow(row.getRowNum() - 1);
// 将本行和上一行是同一类型的数据(通过主键字段进行判断),则需要合并
if (lastRow.getCell(pkIndex).getStringCellValue().equalsIgnoreCase(row.getCell(pkIndex).getStringCellValue())) {
for (Integer needMerIndex : needMergeColumnIndex) {
CellRangeAddress cellRangeAddress = new CellRangeAddress(row.getRowNum() - 1, row.getRowNum(),
needMerIndex, needMerIndex);
sheet.addMergedRegionUnsafe(cellRangeAddress);
}
}
}
/**
* 初始化主键下标和需要合并字段的下标
*/
private void lazyInit(WriteSheetHolder writeSheetHolder) {
// 获取当前sheet
Sheet sheet = writeSheetHolder.getSheet();
// 获取标题行
Row titleRow = sheet.getRow(0);
// 获取DTO的类型
Class<?> eleType = this.elementType;
// 获取DTO所有的属性
Field[] fields = eleType.getDeclaredFields();
// 遍历所有的字段,因为是基于DTO的字段来构建excel,所以字段数 >= excel的列数
for (Field theField : fields) {
// 获取@ExcelProperty注解,用于获取该字段对应在excel中的列的下标
ExcelProperty easyExcelAnno = theField.getAnnotation(ExcelProperty.class);
// 为空,则表示该字段不需要导入到excel,直接处理下一个字段
if (null == easyExcelAnno) {
continue;
}
// 获取自定义的注解,用于合并单元格
CustomMerge customMerge = theField.getAnnotation(CustomMerge.class);
// 没有@CustomMerge注解的默认不合并
if (null == customMerge) {
continue;
}
for (int index = 0; index < fields.length; index++) {
Cell theCell = titleRow.getCell(index);
// 当配置为不需要导出时,返回的为null,这里作一下判断,防止NPE
if (null == theCell) {
continue;
}
// 将字段和excel的表头匹配上
if (easyExcelAnno.value()[0].equalsIgnoreCase(theCell.getStringCellValue())) {
if (customMerge.isPk()) {
pkIndex = index;
}
if (customMerge.needMerge()) {
needMergeColumnIndex.add(index);
}
}
}
}
// 没有指定主键,则异常
if (null == this.pkIndex) {
throw new IllegalStateException("使用@CustomMerge注解必须指定主键");
}
}
}
| macrozheng/mall-learning | mall-tiny-easyexcel/src/main/java/com/macro/mall/tiny/strategy/CustomMergeStrategy.java |
1,001 | package com.alibaba.otter.canal.connector.core.producer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.commons.lang.StringUtils;
import com.alibaba.otter.canal.common.utils.ExecutorTemplate;
import com.alibaba.otter.canal.connector.core.filter.AviaterRegexFilter;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;
import com.alibaba.otter.canal.protocol.FlatMessage;
import com.alibaba.otter.canal.protocol.Message;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import com.google.common.collect.MigrateMap;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
/**
* process MQ Message utils
*
* @author agapple 2019年9月29日 下午12:36:26
* @since 5.0.0
*/
public class MQMessageUtils {
private static Map<String, List<PartitionData>> partitionDatas = MigrateMap.makeComputingMap(CacheBuilder.newBuilder()
.softValues(),
pkHashConfigs -> {
List<PartitionData> datas = new ArrayList<>();
String[] pkHashConfigArray = StringUtils.split(StringUtils.replace(pkHashConfigs,
",",
";"),
";");
// schema.table:id^name
for (String pkHashConfig : pkHashConfigArray) {
PartitionData data = new PartitionData();
int i = pkHashConfig.lastIndexOf(":");
if (i > 0) {
String pkStr = pkHashConfig.substring(i + 1);
if (pkStr.equalsIgnoreCase("$pk$")) {
data.hashMode.autoPkHash = true;
} else {
data.hashMode.pkNames = Lists.newArrayList(StringUtils.split(pkStr,
'^'));
}
pkHashConfig = pkHashConfig.substring(0,
i);
} else {
data.hashMode.tableHash = true;
}
if (!isWildCard(pkHashConfig)) {
data.simpleName = pkHashConfig;
} else {
data.regexFilter = new AviaterRegexFilter(pkHashConfig);
}
datas.add(data);
}
return datas;
});
private static Map<String, List<DynamicTopicData>> dynamicTopicDatas = MigrateMap.makeComputingMap(CacheBuilder.newBuilder()
.softValues(),
pkHashConfigs -> {
List<DynamicTopicData> datas = new ArrayList<>();
String[] dynamicTopicArray = StringUtils.split(StringUtils.replace(pkHashConfigs,
",",
";"),
";");
// schema.table
for (String dynamicTopic : dynamicTopicArray) {
DynamicTopicData data = new DynamicTopicData();
if (!isWildCard(dynamicTopic)) {
data.simpleName = dynamicTopic;
} else {
if (dynamicTopic.contains("\\.")) {
data.tableRegexFilter = new AviaterRegexFilter(dynamicTopic);
} else {
data.schemaRegexFilter = new AviaterRegexFilter(dynamicTopic);
}
}
datas.add(data);
}
return datas;
});
private static Map<String, List<TopicPartitionData>> topicPartitionDatas = MigrateMap.makeComputingMap(CacheBuilder.newBuilder()
.softValues(),
tPConfigs -> {
List<TopicPartitionData> datas = new ArrayList<>();
String[] tPArray = StringUtils.split(StringUtils.replace(tPConfigs,
",",
";"),
";");
for (String tPConfig : tPArray) {
TopicPartitionData data = new TopicPartitionData();
int i = tPConfig.lastIndexOf(":");
if (i > 0) {
String tStr = tPConfig.substring(0, i);
String pStr = tPConfig.substring(i + 1);
if (!isWildCard(tStr)) {
data.simpleName = tStr;
} else {
data.regexFilter = new AviaterRegexFilter(tStr);
}
if (!StringUtils.isEmpty(pStr) && StringUtils.isNumeric(pStr)) {
data.partitionNum = Integer.valueOf(pStr);
}
datas.add(data);
}
}
return datas;
});
/**
* 按 schema 或者 schema+table 将 message 分配到对应topic
*
* @param message 原message
* @param defaultTopic 默认topic
* @param dynamicTopicConfigs 动态topic规则
* @return 分隔后的message map
*/
public static Map<String, Message> messageTopics(Message message, String defaultTopic, String dynamicTopicConfigs) {
List<CanalEntry.Entry> entries;
if (message.isRaw()) {
List<ByteString> rawEntries = message.getRawEntries();
entries = new ArrayList<>(rawEntries.size());
for (ByteString byteString : rawEntries) {
CanalEntry.Entry entry;
try {
entry = CanalEntry.Entry.parseFrom(byteString);
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
entries.add(entry);
}
} else {
entries = message.getEntries();
}
Map<String, Message> messages = new HashMap<>();
for (CanalEntry.Entry entry : entries) {
// 如果有topic路由,则忽略begin/end事件
if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN
|| entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
continue;
}
String schemaName = entry.getHeader().getSchemaName();
String tableName = entry.getHeader().getTableName();
if (StringUtils.isEmpty(schemaName) || StringUtils.isEmpty(tableName)) {
put2MapMessage(messages, message.getId(), defaultTopic, entry);
} else {
Set<String> topics = matchTopics(schemaName + "." + tableName, dynamicTopicConfigs);
if (topics != null) {
for (String topic : topics) {
put2MapMessage(messages, message.getId(), topic, entry);
}
} else {
topics = matchTopics(schemaName, dynamicTopicConfigs);
if (topics != null) {
for (String topic : topics) {
put2MapMessage(messages, message.getId(), topic, entry);
}
} else {
put2MapMessage(messages, message.getId(), defaultTopic, entry);
}
}
}
}
return messages;
}
/**
* 多线程构造message的rowChanged对象,比如为partition/flastMessage转化等处理 </br>
* 因为protobuf对象的序列化和反序列化是cpu密集型,串行执行会有代价
*/
public static EntryRowData[] buildMessageData(Message message, ThreadPoolExecutor executor) {
ExecutorTemplate template = new ExecutorTemplate(executor);
if (message.isRaw()) {
List<ByteString> rawEntries = message.getRawEntries();
final EntryRowData[] datas = new EntryRowData[rawEntries.size()];
int i = 0;
for (ByteString byteString : rawEntries) {
final int index = i;
template.submit(() -> {
try {
Entry entry = Entry.parseFrom(byteString);
RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
datas[index] = new EntryRowData();
datas[index].entry = entry;
datas[index].rowChange = rowChange;
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
});
i++;
}
template.waitForResult();
return datas;
} else {
final EntryRowData[] datas = new EntryRowData[message.getEntries().size()];
int i = 0;
for (Entry entry : message.getEntries()) {
final int index = i;
template.submit(() -> {
try {
RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
datas[index] = new EntryRowData();
datas[index].entry = entry;
datas[index].rowChange = rowChange;
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
});
i++;
}
template.waitForResult();
return datas;
}
}
/**
* 将 message 分区
*
* @param partitionsNum 分区数
* @param pkHashConfigs 分区库表主键正则表达式
* @param databaseHash 是否取消根据database进行hash
* @return 分区message数组
*/
@SuppressWarnings("unchecked")
public static Message[] messagePartition(EntryRowData[] datas, long id, Integer partitionsNum,
String pkHashConfigs, boolean databaseHash) {
if (partitionsNum == null) {
partitionsNum = 1;
}
Message[] partitionMessages = new Message[partitionsNum];
List<Entry>[] partitionEntries = new List[partitionsNum];
for (int i = 0; i < partitionsNum; i++) {
// 注意一下并发
partitionEntries[i] = Collections.synchronizedList(new ArrayList<>());
}
for (EntryRowData data : datas) {
CanalEntry.Entry entry = data.entry;
CanalEntry.RowChange rowChange = data.rowChange;
// 如果有分区路由,则忽略begin/end事件
if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN
|| entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
continue;
}
if (rowChange.getIsDdl()) {
partitionEntries[0].add(entry);
} else {
if (rowChange.getRowDatasList() != null && !rowChange.getRowDatasList().isEmpty()) {
String database = entry.getHeader().getSchemaName();
String table = entry.getHeader().getTableName();
HashMode hashMode = getPartitionHashColumns(database + "." + table, pkHashConfigs);
if (hashMode == null) {
// 如果都没有匹配,发送到第一个分区
partitionEntries[0].add(entry);
} else if (hashMode.tableHash) {
int hashCode = table.hashCode();
int pkHash = Math.abs(hashCode) % partitionsNum;
pkHash = Math.abs(pkHash);
// tableHash not need split entry message
partitionEntries[pkHash].add(entry);
} else {
// build new entry
Entry.Builder builder = Entry.newBuilder(entry);
RowChange.Builder rowChangeBuilder = RowChange.newBuilder(rowChange);
for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
int hashCode = 0;
if (databaseHash) {
hashCode = database.hashCode();
}
CanalEntry.EventType eventType = rowChange.getEventType();
List<CanalEntry.Column> columns = null;
if (eventType == CanalEntry.EventType.DELETE) {
columns = rowData.getBeforeColumnsList();
} else {
columns = rowData.getAfterColumnsList();
}
if (hashMode.autoPkHash) {
// isEmpty use default pkNames
for (CanalEntry.Column column : columns) {
if (column.getIsKey()) {
hashCode = hashCode ^ column.getValue().hashCode();
}
}
} else {
for (CanalEntry.Column column : columns) {
if (checkPkNamesHasContain(hashMode.pkNames, column.getName())) {
hashCode = hashCode ^ column.getValue().hashCode();
}
}
}
int pkHash = Math.abs(hashCode) % partitionsNum;
pkHash = Math.abs(pkHash);
// clear rowDatas
rowChangeBuilder.clearRowDatas();
rowChangeBuilder.addRowDatas(rowData);
builder.clearStoreValue();
builder.setStoreValue(rowChangeBuilder.build().toByteString());
partitionEntries[pkHash].add(builder.build());
}
}
} else {
// 针对stmt/mixed binlog格式的query事件
partitionEntries[0].add(entry);
}
}
}
for (int i = 0; i < partitionsNum; i++) {
List<Entry> entriesTmp = partitionEntries[i];
if (!entriesTmp.isEmpty()) {
partitionMessages[i] = new Message(id, entriesTmp);
}
}
return partitionMessages;
}
/**
* 将Message转换为FlatMessage
*
* @return FlatMessage列表
* @author agapple 2018年12月11日 下午1:28:32
*/
public static List<FlatMessage> messageConverter(EntryRowData[] datas, long id) {
List<FlatMessage> flatMessages = new ArrayList<>();
for (EntryRowData entryRowData : datas) {
CanalEntry.Entry entry = entryRowData.entry;
CanalEntry.RowChange rowChange = entryRowData.rowChange;
// 如果有分区路由,则忽略begin/end事件
if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN
|| entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
continue;
}
// build flatMessage
CanalEntry.EventType eventType = rowChange.getEventType();
FlatMessage flatMessage = new FlatMessage(id);
flatMessages.add(flatMessage);
flatMessage.setDatabase(entry.getHeader().getSchemaName());
flatMessage.setTable(entry.getHeader().getTableName());
flatMessage.setIsDdl(rowChange.getIsDdl());
flatMessage.setType(eventType.toString());
flatMessage.setEs(entry.getHeader().getExecuteTime());
flatMessage.setTs(System.currentTimeMillis());
flatMessage.setSql(rowChange.getSql());
flatMessage.setGtid(entry.getHeader().getGtid());
if (!rowChange.getIsDdl()) {
Map<String, Integer> sqlType = new LinkedHashMap<>();
Map<String, String> mysqlType = new LinkedHashMap<>();
List<Map<String, String>> data = new ArrayList<>();
List<Map<String, String>> old = new ArrayList<>();
Set<String> updateSet = new HashSet<>();
boolean hasInitPkNames = false;
for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
if (eventType != CanalEntry.EventType.INSERT && eventType != CanalEntry.EventType.UPDATE
&& eventType != CanalEntry.EventType.DELETE) {
continue;
}
Map<String, String> row = new LinkedHashMap<>();
List<CanalEntry.Column> columns;
if (eventType == CanalEntry.EventType.DELETE) {
columns = rowData.getBeforeColumnsList();
} else {
columns = rowData.getAfterColumnsList();
}
for (CanalEntry.Column column : columns) {
if (!hasInitPkNames && column.getIsKey()) {
flatMessage.addPkName(column.getName());
}
sqlType.put(column.getName(), column.getSqlType());
mysqlType.put(column.getName(), column.getMysqlType());
if (column.getIsNull()) {
row.put(column.getName(), null);
} else {
row.put(column.getName(), column.getValue());
}
// 获取update为true的字段
if (column.getUpdated()) {
updateSet.add(column.getName());
}
}
hasInitPkNames = true;
if (!row.isEmpty()) {
data.add(row);
}
if (eventType == CanalEntry.EventType.UPDATE) {
Map<String, String> rowOld = new LinkedHashMap<>();
for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
if (updateSet.contains(column.getName())) {
if (column.getIsNull()) {
rowOld.put(column.getName(), null);
} else {
rowOld.put(column.getName(), column.getValue());
}
}
}
// update操作将记录修改前的值
old.add(rowOld);
}
}
if (!sqlType.isEmpty()) {
flatMessage.setSqlType(sqlType);
}
if (!mysqlType.isEmpty()) {
flatMessage.setMysqlType(mysqlType);
}
if (!data.isEmpty()) {
flatMessage.setData(data);
}
if (!old.isEmpty()) {
flatMessage.setOld(old);
}
}
}
return flatMessages;
}
/**
* 将FlatMessage按指定的字段值hash拆分
*
* @param flatMessage flatMessage
* @param partitionsNum 分区数量
* @param pkHashConfigs hash映射
* @param databaseHash 是否取消根据database进行hash
* @return 拆分后的flatMessage数组
*/
public static FlatMessage[] messagePartition(FlatMessage flatMessage, Integer partitionsNum, String pkHashConfigs,
boolean databaseHash) {
if (partitionsNum == null) {
partitionsNum = 1;
}
FlatMessage[] partitionMessages = new FlatMessage[partitionsNum];
if (flatMessage.getIsDdl()) {
partitionMessages[0] = flatMessage;
} else {
if (flatMessage.getData() != null && !flatMessage.getData().isEmpty()) {
String database = flatMessage.getDatabase();
String table = flatMessage.getTable();
HashMode hashMode = getPartitionHashColumns(database + "." + table, pkHashConfigs);
if (hashMode == null) {
// 如果都没有匹配,发送到第一个分区
partitionMessages[0] = flatMessage;
} else if (hashMode.tableHash) {
int hashCode = table.hashCode();
int pkHash = Math.abs(hashCode) % partitionsNum;
// math.abs可能返回负值,这里再取反,把出现负值的数据还是写到固定的分区,仍然可以保证消费顺序
pkHash = Math.abs(pkHash);
partitionMessages[pkHash] = flatMessage;
} else {
List<String> pkNames = hashMode.pkNames;
if (hashMode.autoPkHash) {
pkNames = flatMessage.getPkNames();
}
int idx = 0;
for (Map<String, String> row : flatMessage.getData()) {
int hashCode = 0;
if (databaseHash) {
hashCode = database.hashCode();
}
if (pkNames != null) {
for (String pkName : pkNames) {
String value = row.get(pkName);
if (value == null) {
value = "";
}
hashCode = hashCode ^ value.hashCode();
}
}
int pkHash = Math.abs(hashCode) % partitionsNum;
// math.abs可能返回负值,这里再取反,把出现负值的数据还是写到固定的分区,仍然可以保证消费顺序
pkHash = Math.abs(pkHash);
FlatMessage flatMessageTmp = partitionMessages[pkHash];
if (flatMessageTmp == null) {
flatMessageTmp = new FlatMessage(flatMessage.getId());
partitionMessages[pkHash] = flatMessageTmp;
flatMessageTmp.setDatabase(flatMessage.getDatabase());
flatMessageTmp.setTable(flatMessage.getTable());
flatMessageTmp.setIsDdl(flatMessage.getIsDdl());
flatMessageTmp.setType(flatMessage.getType());
flatMessageTmp.setSql(flatMessage.getSql());
flatMessageTmp.setSqlType(flatMessage.getSqlType());
flatMessageTmp.setMysqlType(flatMessage.getMysqlType());
flatMessageTmp.setEs(flatMessage.getEs());
flatMessageTmp.setTs(flatMessage.getTs());
flatMessageTmp.setPkNames(flatMessage.getPkNames());
flatMessageTmp.setGtid(flatMessage.getGtid());
}
List<Map<String, String>> data = flatMessageTmp.getData();
if (data == null) {
data = new ArrayList<>();
flatMessageTmp.setData(data);
}
data.add(row);
if (flatMessage.getOld() != null && !flatMessage.getOld().isEmpty()) {
List<Map<String, String>> old = flatMessageTmp.getOld();
if (old == null) {
old = new ArrayList<>();
flatMessageTmp.setOld(old);
}
old.add(flatMessage.getOld().get(idx));
}
idx++;
}
}
} else {
// 针对stmt/mixed binlog格式的query事件
partitionMessages[0] = flatMessage;
}
}
return partitionMessages;
}
/**
* match return List , not match return null
*/
public static HashMode getPartitionHashColumns(String name, String pkHashConfigs) {
if (StringUtils.isEmpty(pkHashConfigs)) {
return null;
}
List<PartitionData> datas = partitionDatas.get(pkHashConfigs);
for (PartitionData data : datas) {
if (data.simpleName != null) {
if (data.simpleName.equalsIgnoreCase(name)) {
return data.hashMode;
}
} else {
if (data.regexFilter.filter(name)) {
return data.hashMode;
}
}
}
return null;
}
private static Set<String> matchTopics(String name, String dynamicTopicConfigs) {
String[] router = StringUtils.split(StringUtils.replace(dynamicTopicConfigs, ",", ";"), ";");
Set<String> topics = new HashSet<>();
for (String item : router) {
int i = item.indexOf(":");
if (i > -1) {
String topic = item.substring(0, i).trim();
String topicConfigs = item.substring(i + 1).trim();
if (matchDynamicTopic(name, topicConfigs)) {
topics.add(topic);
// 匹配了一个就退出
break;
}
} else if (matchDynamicTopic(name, item)) {
// 匹配了一个就退出
topics.add(name.toLowerCase());
break;
}
}
return topics.isEmpty() ? null : topics;
}
public static boolean matchDynamicTopic(String name, String dynamicTopicConfigs) {
if (StringUtils.isEmpty(dynamicTopicConfigs)) {
return false;
}
boolean res = false;
List<DynamicTopicData> datas = dynamicTopicDatas.get(dynamicTopicConfigs);
for (DynamicTopicData data : datas) {
if (data.simpleName != null) {
if (data.simpleName.equalsIgnoreCase(name)) {
res = true;
break;
}
} else if (name.contains(".")) {
if (data.tableRegexFilter != null && data.tableRegexFilter.filter(name)) {
res = true;
break;
}
} else {
if (data.schemaRegexFilter != null && data.schemaRegexFilter.filter(name)) {
res = true;
break;
}
}
}
return res;
}
public static boolean checkPkNamesHasContain(List<String> pkNames, String name) {
for (String pkName : pkNames) {
if (pkName.equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
public static Integer parseDynamicTopicPartition(String name, String tPConfigs) {
if (!StringUtils.isEmpty(tPConfigs)) {
List<TopicPartitionData> datas = topicPartitionDatas.get(tPConfigs);
for (TopicPartitionData data : datas) {
if (data.simpleName != null) {
if (data.simpleName.equalsIgnoreCase(name)) {
return data.partitionNum;
}
} else {
if (data.regexFilter.filter(name)) {
return data.partitionNum;
}
}
}
}
return null;
}
private static boolean isWildCard(String value) {
// not contaiins '.' ?
return StringUtils.containsAny(value, new char[] { '*', '?', '+', '|', '(', ')', '{', '}', '[', ']', '\\', '$',
'^' });
}
private static void put2MapMessage(Map<String, Message> messageMap, Long messageId, String topicName,
CanalEntry.Entry entry) {
Message message = messageMap.get(topicName);
if (message == null) {
message = new Message(messageId, new ArrayList<>());
messageMap.put(topicName, message);
}
message.getEntries().add(entry);
}
public static class PartitionData {
/**
* 当{schemaName.tableName}没有正则时,就匹配{schemaName.tableName}
*/
public String simpleName;
/**
* 当{schemaName.tableName}有正则时,匹配正则
*/
public AviaterRegexFilter regexFilter;
/**
* hash模式
*/
public HashMode hashMode = new HashMode();
}
public static class HashMode {
/**
* 当{schemaName.tableName}:$pk$时,使用自动主键hash
*/
public boolean autoPkHash = false;
/**
* 当表达式仅为{schemaName.tableName},没有:时,仅使用table hash
*/
public boolean tableHash = false;
/**
* 当表达式为{schemaName.tableName}:id^name^age时,pkNames为:id, name, age三个
*/
public List<String> pkNames = new ArrayList<>();
}
public static class DynamicTopicData {
public String simpleName;
public AviaterRegexFilter schemaRegexFilter;
public AviaterRegexFilter tableRegexFilter;
}
public static class TopicPartitionData {
public String simpleName;
public AviaterRegexFilter regexFilter;
public Integer partitionNum;
}
public static class EntryRowData {
public Entry entry;
public RowChange rowChange;
}
}
| alibaba/canal | connector/core/src/main/java/com/alibaba/otter/canal/connector/core/producer/MQMessageUtils.java |
1,003 | /**
* Copyright (c) 2012-2013, Michael Yang 杨福海 (www.yangfuhai.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.tsz.afinal;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import net.tsz.afinal.bitmap.core.BitmapCache;
import net.tsz.afinal.bitmap.core.BitmapDisplayConfig;
import net.tsz.afinal.bitmap.core.BitmapProcess;
import net.tsz.afinal.bitmap.display.Displayer;
import net.tsz.afinal.bitmap.display.SimpleDisplayer;
import net.tsz.afinal.bitmap.download.Downloader;
import net.tsz.afinal.bitmap.download.SimpleDownloader;
import net.tsz.afinal.core.AsyncTask;
import net.tsz.afinal.utils.Utils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
public class FinalBitmap {
private FinalBitmapConfig mConfig;
private BitmapCache mImageCache;
private BitmapProcess mBitmapProcess;
private boolean mExitTasksEarly = false;
private boolean mPauseWork = false;
private final Object mPauseWorkLock = new Object();
private Context mContext;
private boolean mInit = false ;
private ExecutorService bitmapLoadAndDisplayExecutor;
private static FinalBitmap mFinalBitmap;
////////////////////////// config method start////////////////////////////////////
private FinalBitmap(Context context) {
mContext = context;
mConfig = new FinalBitmapConfig(context);
configDiskCachePath(Utils.getDiskCacheDir(context, "afinalCache").getAbsolutePath());//配置缓存路径
configDisplayer(new SimpleDisplayer());//配置显示器
configDownlader(new SimpleDownloader());//配置下载器
}
/**
* 创建finalbitmap
* @param ctx
* @return
*/
public static synchronized FinalBitmap create(Context ctx){
if(mFinalBitmap == null){
mFinalBitmap = new FinalBitmap(ctx.getApplicationContext());
}
return mFinalBitmap;
}
/**
* 设置图片正在加载的时候显示的图片
* @param bitmap
*/
public FinalBitmap configLoadingImage(Bitmap bitmap) {
mConfig.defaultDisplayConfig.setLoadingBitmap(bitmap);
return this;
}
/**
* 设置图片正在加载的时候显示的图片
* @param bitmap
*/
public FinalBitmap configLoadingImage(int resId) {
mConfig.defaultDisplayConfig.setLoadingBitmap(BitmapFactory.decodeResource(mContext.getResources(), resId));
return this;
}
/**
* 设置图片加载失败时候显示的图片
* @param bitmap
*/
public FinalBitmap configLoadfailImage(Bitmap bitmap) {
mConfig.defaultDisplayConfig.setLoadfailBitmap(bitmap);
return this;
}
/**
* 设置图片加载失败时候显示的图片
* @param resId
*/
public FinalBitmap configLoadfailImage(int resId) {
mConfig.defaultDisplayConfig.setLoadfailBitmap(BitmapFactory.decodeResource(mContext.getResources(), resId));
return this;
}
/**
* 配置默认图片的小的高度
* @param bitmapHeight
*/
public FinalBitmap configBitmapMaxHeight(int bitmapHeight){
mConfig.defaultDisplayConfig.setBitmapHeight(bitmapHeight);
return this;
}
/**
* 配置默认图片的小的宽度
* @param bitmapHeight
*/
public FinalBitmap configBitmapMaxWidth(int bitmapWidth){
mConfig.defaultDisplayConfig.setBitmapWidth(bitmapWidth);
return this;
}
/**
* 设置下载器,比如通过ftp或者其他协议去网络读取图片的时候可以设置这项
* @param downlader
* @return
*/
public FinalBitmap configDownlader(Downloader downlader){
mConfig.downloader = downlader;
return this;
}
/**
* 设置显示器,比如在显示的过程中显示动画等
* @param displayer
* @return
*/
public FinalBitmap configDisplayer(Displayer displayer){
mConfig.displayer = displayer;
return this;
}
/**
* 配置磁盘缓存路径
* @param strPath
* @return
*/
public FinalBitmap configDiskCachePath(String strPath){
if(!TextUtils.isEmpty(strPath)){
mConfig.cachePath = strPath;
}
return this;
}
/**
* 配置内存缓存大小 大于2MB以上有效
* @param size 缓存大小
*/
public FinalBitmap configMemoryCacheSize(int size){
mConfig.memCacheSize = size;
return this;
}
/**
* 设置应缓存的在APK总内存的百分比,优先级大于configMemoryCacheSize
* @param percent 百分比,值的范围是在 0.05 到 0.8之间
*/
public FinalBitmap configMemoryCachePercent(float percent){
mConfig.memCacheSizePercent = percent;
return this;
}
/**
* 设置磁盘缓存大小 5MB 以上有效
* @param size
*/
public FinalBitmap configDiskCacheSize(int size){
mConfig.diskCacheSize = size;
return this;
}
/**
* 设置加载图片的线程并发数量
* @param size
*/
public FinalBitmap configBitmapLoadThreadSize(int size){
if(size >= 1)
mConfig.poolSize = size;
return this;
}
/**
* 配置是否立即回收图片资源
* @param recycleImmediately
* @return
*/
public FinalBitmap configRecycleImmediately(boolean recycleImmediately){
mConfig.recycleImmediately = recycleImmediately;
return this;
}
/**
* 初始化finalBitmap
* @return
*/
private FinalBitmap init(){
if( ! mInit ){
BitmapCache.ImageCacheParams imageCacheParams = new BitmapCache.ImageCacheParams(mConfig.cachePath);
if(mConfig.memCacheSizePercent>0.05 && mConfig.memCacheSizePercent<0.8){
imageCacheParams.setMemCacheSizePercent(mContext, mConfig.memCacheSizePercent);
}else{
if(mConfig.memCacheSize > 1024 * 1024 * 2){
imageCacheParams.setMemCacheSize(mConfig.memCacheSize);
}else{
//设置默认的内存缓存大小
imageCacheParams.setMemCacheSizePercent(mContext, 0.3f);
}
}
if(mConfig.diskCacheSize > 1024 * 1024 * 5)
imageCacheParams.setDiskCacheSize(mConfig.diskCacheSize);
imageCacheParams.setRecycleImmediately(mConfig.recycleImmediately);
//init Cache
mImageCache = new BitmapCache(imageCacheParams);
//init Executors
bitmapLoadAndDisplayExecutor = Executors.newFixedThreadPool(mConfig.poolSize,new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
// 设置线程的优先级别,让线程先后顺序执行(级别越高,抢到cpu执行的时间越多)
t.setPriority(Thread.NORM_PRIORITY - 1);
return t;
}
});
//init BitmapProcess
mBitmapProcess = new BitmapProcess(mConfig.downloader,mImageCache);
mInit = true ;
}
return this;
}
////////////////////////// config method end////////////////////////////////////
public void display(View imageView,String uri){
doDisplay(imageView,uri,null);
}
public void display(View imageView,String uri,int imageWidth,int imageHeight){
BitmapDisplayConfig displayConfig = configMap.get(imageWidth+"_"+imageHeight);
if(displayConfig==null){
displayConfig = getDisplayConfig();
displayConfig.setBitmapHeight(imageHeight);
displayConfig.setBitmapWidth(imageWidth);
configMap.put(imageWidth+"_"+imageHeight, displayConfig);
}
doDisplay(imageView,uri,displayConfig);
}
public void display(View imageView,String uri,Bitmap loadingBitmap){
BitmapDisplayConfig displayConfig = configMap.get(String.valueOf(loadingBitmap));
if(displayConfig==null){
displayConfig = getDisplayConfig();
displayConfig.setLoadingBitmap(loadingBitmap);
configMap.put(String.valueOf(loadingBitmap), displayConfig);
}
doDisplay(imageView,uri,displayConfig);
}
public void display(View imageView,String uri,Bitmap loadingBitmap,Bitmap laodfailBitmap){
BitmapDisplayConfig displayConfig = configMap.get(String.valueOf(loadingBitmap)+"_"+String.valueOf(laodfailBitmap));
if(displayConfig==null){
displayConfig = getDisplayConfig();
displayConfig.setLoadingBitmap(loadingBitmap);
displayConfig.setLoadfailBitmap(laodfailBitmap);
configMap.put(String.valueOf(loadingBitmap)+"_"+String.valueOf(laodfailBitmap), displayConfig);
}
doDisplay(imageView,uri,displayConfig);
}
public void display(View imageView,String uri,int imageWidth,int imageHeight,Bitmap loadingBitmap,Bitmap laodfailBitmap){
BitmapDisplayConfig displayConfig = configMap.get(imageWidth+"_"+imageHeight+"_"+String.valueOf(loadingBitmap)+"_"+String.valueOf(laodfailBitmap));
if(displayConfig==null){
displayConfig = getDisplayConfig();
displayConfig.setBitmapHeight(imageHeight);
displayConfig.setBitmapWidth(imageWidth);
displayConfig.setLoadingBitmap(loadingBitmap);
displayConfig.setLoadfailBitmap(laodfailBitmap);
configMap.put(imageWidth+"_"+imageHeight+"_"+String.valueOf(loadingBitmap)+"_"+String.valueOf(laodfailBitmap), displayConfig);
}
doDisplay(imageView,uri,displayConfig);
}
public void display(View imageView,String uri,BitmapDisplayConfig config){
doDisplay(imageView,uri,config);
}
private void doDisplay(View imageView, String uri, BitmapDisplayConfig displayConfig) {
if(!mInit ){
init();
}
if (TextUtils.isEmpty(uri) || imageView == null) {
return;
}
if(displayConfig == null)
displayConfig = mConfig.defaultDisplayConfig;
Bitmap bitmap = null;
if (mImageCache != null) {
bitmap = mImageCache.getBitmapFromMemoryCache(uri);
}
if (bitmap != null) {
if(imageView instanceof ImageView){
((ImageView)imageView).setImageBitmap(bitmap);
}else{
imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
}
}else if (checkImageTask(uri, imageView)) {
final BitmapLoadAndDisplayTask task = new BitmapLoadAndDisplayTask(imageView, displayConfig );
//设置默认图片
final AsyncDrawable asyncDrawable = new AsyncDrawable(mContext.getResources(), displayConfig.getLoadingBitmap(), task);
if(imageView instanceof ImageView){
((ImageView)imageView).setImageDrawable(asyncDrawable);
}else{
imageView.setBackgroundDrawable(asyncDrawable);
}
task.executeOnExecutor(bitmapLoadAndDisplayExecutor, uri);
}
}
private HashMap<String, BitmapDisplayConfig> configMap = new HashMap<String, BitmapDisplayConfig>();
private BitmapDisplayConfig getDisplayConfig(){
BitmapDisplayConfig config = new BitmapDisplayConfig();
config.setAnimation(mConfig.defaultDisplayConfig.getAnimation());
config.setAnimationType(mConfig.defaultDisplayConfig.getAnimationType());
config.setBitmapHeight(mConfig.defaultDisplayConfig.getBitmapHeight());
config.setBitmapWidth(mConfig.defaultDisplayConfig.getBitmapWidth());
config.setLoadfailBitmap(mConfig.defaultDisplayConfig.getLoadfailBitmap());
config.setLoadingBitmap(mConfig.defaultDisplayConfig.getLoadingBitmap());
return config;
}
private void clearCacheInternalInBackgroud() {
if (mImageCache != null) {
mImageCache.clearCache();
}
}
private void clearDiskCacheInBackgroud(){
if (mImageCache != null) {
mImageCache.clearDiskCache();
}
}
private void clearCacheInBackgroud(String key){
if (mImageCache != null) {
mImageCache.clearCache(key);
}
}
private void clearDiskCacheInBackgroud(String key){
if (mImageCache != null) {
mImageCache.clearDiskCache(key);
}
}
/**
* 执行过此方法后,FinalBitmap的缓存已经失效,建议通过FinalBitmap.create()获取新的实例
* @author fantouch
*/
private void closeCacheInternalInBackgroud() {
if (mImageCache != null) {
mImageCache.close();
mImageCache = null;
mFinalBitmap = null;
}
}
/**
* 网络加载bitmap
* @param data
* @return
*/
private Bitmap processBitmap(String uri,BitmapDisplayConfig config) {
if (mBitmapProcess != null) {
return mBitmapProcess.getBitmap(uri,config);
}
return null;
}
/**
* 从缓存(内存缓存和磁盘缓存)中直接获取bitmap,注意这里有io操作,最好不要放在ui线程执行
* @param key
* @return
*/
public Bitmap getBitmapFromCache(String key){
Bitmap bitmap = getBitmapFromMemoryCache(key);
if(bitmap == null)
bitmap = getBitmapFromDiskCache(key);
return bitmap;
}
/**
* 从内存缓存中获取bitmap
* @param key
* @return
*/
public Bitmap getBitmapFromMemoryCache(String key){
return mImageCache.getBitmapFromMemoryCache(key);
}
/**
* 从磁盘缓存中获取bitmap,,注意这里有io操作,最好不要放在ui线程执行
* @param key
* @return
*/
public Bitmap getBitmapFromDiskCache(String key){
return getBitmapFromDiskCache(key,null);
}
public Bitmap getBitmapFromDiskCache(String key,BitmapDisplayConfig config){
return mBitmapProcess.getFromDisk(key, config);
}
public void setExitTasksEarly(boolean exitTasksEarly) {
mExitTasksEarly = exitTasksEarly;
}
/**
* activity onResume的时候调用这个方法,让加载图片线程继续
*/
public void onResume(){
setExitTasksEarly(false);
}
/**
* activity onPause的时候调用这个方法,让线程暂停
*/
public void onPause() {
setExitTasksEarly(true);
}
/**
* activity onDestroy的时候调用这个方法,释放缓存
* 执行过此方法后,FinalBitmap的缓存已经失效,建议通过FinalBitmap.create()获取新的实例
*
* @author fantouch
*/
public void onDestroy() {
closeCache();
}
/**
* 清除所有缓存(磁盘和内存)
*/
public void clearCache() {
new CacheExecutecTask().execute(CacheExecutecTask.MESSAGE_CLEAR);
}
/**
* 根据key清除指定的内存缓存
* @param key
*/
public void clearCache(String key) {
new CacheExecutecTask().execute(CacheExecutecTask.MESSAGE_CLEAR_KEY,key);
}
/**
* 清除缓存
*/
public void clearMemoryCache() {
if(mImageCache!=null)
mImageCache.clearMemoryCache();
}
/**
* 根据key清除指定的内存缓存
* @param key
*/
public void clearMemoryCache(String key) {
if(mImageCache!=null)
mImageCache.clearMemoryCache(key);
}
/**
* 清除磁盘缓存
*/
public void clearDiskCache() {
new CacheExecutecTask().execute(CacheExecutecTask.MESSAGE_CLEAR_DISK);
}
/**
* 根据key清除指定的内存缓存
* @param key
*/
public void clearDiskCache(String key) {
new CacheExecutecTask().execute(CacheExecutecTask.MESSAGE_CLEAR_KEY_IN_DISK,key);
}
/**
* 关闭缓存
* 执行过此方法后,FinalBitmap的缓存已经失效,建议通过FinalBitmap.create()获取新的实例
* @author fantouch
*/
public void closeCache() {
new CacheExecutecTask().execute(CacheExecutecTask.MESSAGE_CLOSE);
}
/**
* 退出正在加载的线程,程序退出的时候调用词方法
* @param exitTasksEarly
*/
public void exitTasksEarly(boolean exitTasksEarly) {
mExitTasksEarly = exitTasksEarly;
if(exitTasksEarly)
pauseWork(false);//让暂停的线程结束
}
/**
* 暂停正在加载的线程,监听listview或者gridview正在滑动的时候条用词方法
* @param pauseWork true停止暂停线程,false继续线程
*/
public void pauseWork(boolean pauseWork) {
synchronized (mPauseWorkLock) {
mPauseWork = pauseWork;
if (!mPauseWork) {
mPauseWorkLock.notifyAll();
}
}
}
private static BitmapLoadAndDisplayTask getBitmapTaskFromImageView(View imageView) {
if (imageView != null) {
Drawable drawable = null;
if(imageView instanceof ImageView){
drawable = ((ImageView)imageView).getDrawable();
}else{
drawable = imageView.getBackground();
}
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkerTask();
}
}
return null;
}
/**
* 检测 imageView中是否已经有线程在运行
* @param data
* @param imageView
* @return true 没有 false 有线程在运行了
*/
public static boolean checkImageTask(Object data, View imageView) {
final BitmapLoadAndDisplayTask bitmapWorkerTask = getBitmapTaskFromImageView(imageView);
if (bitmapWorkerTask != null) {
final Object bitmapData = bitmapWorkerTask.data;
if (bitmapData == null || !bitmapData.equals(data)) {
bitmapWorkerTask.cancel(true);
} else {
// 同一个线程已经在执行
return false;
}
}
return true;
}
private static class AsyncDrawable extends BitmapDrawable {
private final WeakReference<BitmapLoadAndDisplayTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap,BitmapLoadAndDisplayTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference = new WeakReference<BitmapLoadAndDisplayTask>(
bitmapWorkerTask);
}
public BitmapLoadAndDisplayTask getBitmapWorkerTask() {
return bitmapWorkerTaskReference.get();
}
}
private class CacheExecutecTask extends AsyncTask<Object, Void, Void> {
public static final int MESSAGE_CLEAR = 1;
public static final int MESSAGE_CLOSE = 2;
public static final int MESSAGE_CLEAR_DISK = 3;
public static final int MESSAGE_CLEAR_KEY = 4;
public static final int MESSAGE_CLEAR_KEY_IN_DISK = 5;
@Override
protected Void doInBackground(Object... params) {
switch ((Integer) params[0]) {
case MESSAGE_CLEAR:
clearCacheInternalInBackgroud();
break;
case MESSAGE_CLOSE:
closeCacheInternalInBackgroud();
break;
case MESSAGE_CLEAR_DISK:
clearDiskCacheInBackgroud();
break;
case MESSAGE_CLEAR_KEY:
clearCacheInBackgroud(String.valueOf(params[1]));
break;
case MESSAGE_CLEAR_KEY_IN_DISK:
clearDiskCacheInBackgroud(String.valueOf(params[1]));
break;
}
return null;
}
}
/**
* bitmap下载显示的线程
* @author michael yang
*/
private class BitmapLoadAndDisplayTask extends AsyncTask<Object, Void, Bitmap> {
private Object data;
private final WeakReference<View> imageViewReference;
private final BitmapDisplayConfig displayConfig;
public BitmapLoadAndDisplayTask(View imageView,BitmapDisplayConfig config) {
imageViewReference = new WeakReference<View>(imageView);
displayConfig = config;
}
@Override
protected Bitmap doInBackground(Object... params) {
data = params[0];
final String dataString = String.valueOf(data);
Bitmap bitmap = null;
synchronized (mPauseWorkLock) {
while (mPauseWork && !isCancelled()) {
try {
mPauseWorkLock.wait();
} catch (InterruptedException e) {
}
}
}
if (bitmap == null && !isCancelled()&& getAttachedImageView() != null && !mExitTasksEarly) {
bitmap = processBitmap(dataString,displayConfig);
}
if(bitmap!=null){
mImageCache.addToMemoryCache(dataString, bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled() || mExitTasksEarly) {
bitmap = null;
}
// 判断线程和当前的imageview是否是匹配
final View imageView = getAttachedImageView();
if (bitmap != null && imageView != null) {
mConfig.displayer.loadCompletedisplay(imageView,bitmap,displayConfig);
}else if(bitmap == null && imageView!=null ){
mConfig.displayer.loadFailDisplay(imageView, displayConfig.getLoadfailBitmap());
}
}
@Override
protected void onCancelled(Bitmap bitmap) {
super.onCancelled(bitmap);
synchronized (mPauseWorkLock) {
mPauseWorkLock.notifyAll();
}
}
/**
* 获取线程匹配的imageView,防止出现闪动的现象
* @return
*/
private View getAttachedImageView() {
final View imageView = imageViewReference.get();
final BitmapLoadAndDisplayTask bitmapWorkerTask = getBitmapTaskFromImageView(imageView);
if (this == bitmapWorkerTask) {
return imageView;
}
return null;
}
}
/**
* @title 配置信息
* @description FinalBitmap的配置信息
* @company 探索者网络工作室(www.tsz.net)
* @author michael Young (www.YangFuhai.com)
* @version 1.0
* @created 2012-10-28
*/
private class FinalBitmapConfig {
public String cachePath;
public Displayer displayer;
public Downloader downloader;
public BitmapDisplayConfig defaultDisplayConfig;
public float memCacheSizePercent;//缓存百分比,android系统分配给每个apk内存的大小
public int memCacheSize;//内存缓存百分比
public int diskCacheSize;//磁盘百分比
public int poolSize = 3;//默认的线程池线程并发数量
public boolean recycleImmediately = true;//是否立即回收内存
public FinalBitmapConfig(Context context) {
defaultDisplayConfig = new BitmapDisplayConfig();
defaultDisplayConfig.setAnimation(null);
defaultDisplayConfig.setAnimationType(BitmapDisplayConfig.AnimationType.fadeIn);
//设置图片的显示最大尺寸(为屏幕的大小,默认为屏幕宽度的1/2)
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int defaultWidth = (int)Math.floor(displayMetrics.widthPixels/2);
defaultDisplayConfig.setBitmapHeight(defaultWidth);
defaultDisplayConfig.setBitmapWidth(defaultWidth);
}
}
}
| yangfuhai/afinal | src/net/tsz/afinal/FinalBitmap.java |
1,004 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package tk.mybatis.mapper.mapperhelper;
import tk.mybatis.mapper.LogicDeleteException;
import tk.mybatis.mapper.annotation.LogicDelete;
import tk.mybatis.mapper.annotation.Version;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.entity.IDynamicTableName;
import tk.mybatis.mapper.util.StringUtil;
import tk.mybatis.mapper.version.VersionException;
import java.util.Set;
/**
* 拼常用SQL的工具类
*
* @author liuzh
* @since 2015-11-03 22:40
*/
public class SqlHelper {
/**
* 获取表名 - 支持动态表名
*
* @param entityClass
* @param tableName
* @return
*/
public static String getDynamicTableName(Class<?> entityClass, String tableName) {
if (IDynamicTableName.class.isAssignableFrom(entityClass)) {
StringBuilder sql = new StringBuilder();
sql.append("<choose>");
sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@isDynamicParameter(_parameter) and dynamicTableName != null and dynamicTableName != ''\">");
sql.append("${dynamicTableName}\n");
sql.append("</when>");
//不支持指定列的时候查询全部列
sql.append("<otherwise>");
sql.append(tableName);
sql.append("</otherwise>");
sql.append("</choose>");
return sql.toString();
} else {
return tableName;
}
}
/**
* 获取表名 - 支持动态表名,该方法用于多个入参时,通过parameterName指定入参中实体类的@Param的注解值
*
* @param entityClass
* @param tableName
* @param parameterName
* @return
*/
public static String getDynamicTableName(Class<?> entityClass, String tableName, String parameterName) {
if (IDynamicTableName.class.isAssignableFrom(entityClass)) {
if (StringUtil.isNotEmpty(parameterName)) {
StringBuilder sql = new StringBuilder();
sql.append("<choose>");
sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@isDynamicParameter(" + parameterName + ") and " + parameterName + ".dynamicTableName != null and " + parameterName + ".dynamicTableName != ''\">");
sql.append("${" + parameterName + ".dynamicTableName}");
sql.append("</when>");
//不支持指定列的时候查询全部列
sql.append("<otherwise>");
sql.append(tableName);
sql.append("</otherwise>");
sql.append("</choose>");
return sql.toString();
} else {
return getDynamicTableName(entityClass, tableName);
}
} else {
return tableName;
}
}
/**
* <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
*
* @param column
* @return
*/
public static String getBindCache(EntityColumn column) {
StringBuilder sql = new StringBuilder();
sql.append("<bind name=\"");
sql.append(column.getProperty()).append("_cache\" ");
sql.append("value=\"").append(column.getProperty()).append("\"/>");
return sql.toString();
}
/**
* <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
*
* @param column
* @return
*/
public static String getBindValue(EntityColumn column, String value) {
StringBuilder sql = new StringBuilder();
sql.append("<bind name=\"");
sql.append(column.getProperty()).append("_bind\" ");
sql.append("value='").append(value).append("'/>");
return sql.toString();
}
/**
* <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
*
* @param column
* @return
*/
public static String getIfCacheNotNull(EntityColumn column, String contents) {
StringBuilder sql = new StringBuilder();
sql.append("<if test=\"").append(column.getProperty()).append("_cache != null\">");
sql.append(contents);
sql.append("</if>");
return sql.toString();
}
/**
* 如果_cache == null
*
* @param column
* @return
*/
public static String getIfCacheIsNull(EntityColumn column, String contents) {
StringBuilder sql = new StringBuilder();
sql.append("<if test=\"").append(column.getProperty()).append("_cache == null\">");
sql.append(contents);
sql.append("</if>");
return sql.toString();
}
/**
* 判断自动!=null的条件结构
*
* @param column
* @param contents
* @param empty
* @return
*/
public static String getIfNotNull(EntityColumn column, String contents, boolean empty) {
return getIfNotNull(null, column, contents, empty);
}
/**
* 判断自动==null的条件结构
*
* @param column
* @param contents
* @param empty
* @return
*/
public static String getIfIsNull(EntityColumn column, String contents, boolean empty) {
return getIfIsNull(null, column, contents, empty);
}
/**
* 判断自动!=null的条件结构
*
* @param entityName
* @param column
* @param contents
* @param empty
* @return
*/
public static String getIfNotNull(String entityName, EntityColumn column, String contents, boolean empty) {
StringBuilder sql = new StringBuilder();
sql.append("<if test=\"");
if (StringUtil.isNotEmpty(entityName)) {
sql.append(entityName).append(".");
}
sql.append(column.getProperty()).append(" != null");
if (empty && column.getJavaType().equals(String.class)) {
sql.append(" and ");
if (StringUtil.isNotEmpty(entityName)) {
sql.append(entityName).append(".");
}
sql.append(column.getProperty()).append(" != '' ");
}
sql.append("\">");
sql.append(contents);
sql.append("</if>");
return sql.toString();
}
/**
* 判断自动==null的条件结构
*
* @param entityName
* @param column
* @param contents
* @param empty
* @return
*/
public static String getIfIsNull(String entityName, EntityColumn column, String contents, boolean empty) {
StringBuilder sql = new StringBuilder();
sql.append("<if test=\"");
if (StringUtil.isNotEmpty(entityName)) {
sql.append(entityName).append(".");
}
sql.append(column.getProperty()).append(" == null");
if (empty && column.getJavaType().equals(String.class)) {
sql.append(" or ");
if (StringUtil.isNotEmpty(entityName)) {
sql.append(entityName).append(".");
}
sql.append(column.getProperty()).append(" == '' ");
}
sql.append("\">");
sql.append(contents);
sql.append("</if>");
return sql.toString();
}
/**
* 获取所有查询列,如id,name,code...
*
* @param entityClass
* @return
*/
public static String getAllColumns(Class<?> entityClass) {
Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
StringBuilder sql = new StringBuilder();
for (EntityColumn entityColumn : columnSet) {
sql.append(entityColumn.getColumn()).append(",");
}
return sql.substring(0, sql.length() - 1);
}
/**
* select xxx,xxx...
*
* @param entityClass
* @return
*/
public static String selectAllColumns(Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT ");
sql.append(getAllColumns(entityClass));
sql.append(" ");
return sql.toString();
}
/**
* select count(x)
*
* @param entityClass
* @return
*/
public static String selectCount(Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT ");
Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass);
if (pkColumns.size() == 1) {
sql.append("COUNT(").append(pkColumns.iterator().next().getColumn()).append(") ");
} else {
sql.append("COUNT(*) ");
}
return sql.toString();
}
/**
* select case when count(x) > 0 then 1 else 0 end
*
* @param entityClass
* @return
*/
public static String selectCountExists(Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT CASE WHEN ");
Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass);
if (pkColumns.size() == 1) {
sql.append("COUNT(").append(pkColumns.iterator().next().getColumn()).append(") ");
} else {
sql.append("COUNT(*) ");
}
sql.append(" > 0 THEN 1 ELSE 0 END AS result ");
return sql.toString();
}
/**
* from tableName - 动态表名
*
* @param entityClass
* @param defaultTableName
* @return
*/
public static String fromTable(Class<?> entityClass, String defaultTableName) {
StringBuilder sql = new StringBuilder();
sql.append(" FROM ");
sql.append(getDynamicTableName(entityClass, defaultTableName));
sql.append(" ");
return sql.toString();
}
/**
* update tableName - 动态表名
*
* @param entityClass
* @param defaultTableName
* @return
*/
public static String updateTable(Class<?> entityClass, String defaultTableName) {
return updateTable(entityClass, defaultTableName, null);
}
/**
* update tableName - 动态表名
*
* @param entityClass
* @param defaultTableName 默认表名
* @param entityName 别名
* @return
*/
public static String updateTable(Class<?> entityClass, String defaultTableName, String entityName) {
StringBuilder sql = new StringBuilder();
sql.append("UPDATE ");
sql.append(getDynamicTableName(entityClass, defaultTableName, entityName));
sql.append(" ");
return sql.toString();
}
/**
* delete tableName - 动态表名
*
* @param entityClass
* @param defaultTableName
* @return
*/
public static String deleteFromTable(Class<?> entityClass, String defaultTableName) {
StringBuilder sql = new StringBuilder();
sql.append("DELETE FROM ");
sql.append(getDynamicTableName(entityClass, defaultTableName));
sql.append(" ");
return sql.toString();
}
/**
* insert into tableName - 动态表名
*
* @param entityClass
* @param defaultTableName
* @return
*/
public static String insertIntoTable(Class<?> entityClass, String defaultTableName) {
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO ");
sql.append(getDynamicTableName(entityClass, defaultTableName));
sql.append(" ");
return sql.toString();
}
/**
* insert into tableName - 动态表名
*
* @param entityClass
* @param defaultTableName
* @param parameterName 动态表名的参数名
* @return
*/
public static String insertIntoTable(Class<?> entityClass, String defaultTableName, String parameterName) {
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO ");
sql.append(getDynamicTableName(entityClass, defaultTableName, parameterName));
sql.append(" ");
return sql.toString();
}
/**
* insert table()列
*
* @param entityClass
* @param skipId 是否从列中忽略id类型
* @param notNull 是否判断!=null
* @param notEmpty 是否判断String类型!=''
* @return
*/
public static String insertColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty) {
StringBuilder sql = new StringBuilder();
sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">");
//获取全部列
Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
//当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值
for (EntityColumn column : columnSet) {
if (!column.isInsertable()) {
continue;
}
if (skipId && column.isId()) {
continue;
}
if (notNull) {
sql.append(SqlHelper.getIfNotNull(column, column.getColumn() + ",", notEmpty));
} else {
sql.append(column.getColumn() + ",");
}
}
sql.append("</trim>");
return sql.toString();
}
/**
* insert-values()列
*
* @param entityClass
* @param skipId 是否从列中忽略id类型
* @param notNull 是否判断!=null
* @param notEmpty 是否判断String类型!=''
* @return
*/
public static String insertValuesColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty) {
StringBuilder sql = new StringBuilder();
sql.append("<trim prefix=\"VALUES (\" suffix=\")\" suffixOverrides=\",\">");
//获取全部列
Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
//当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值
for (EntityColumn column : columnSet) {
if (!column.isInsertable()) {
continue;
}
if (skipId && column.isId()) {
continue;
}
if (notNull) {
sql.append(SqlHelper.getIfNotNull(column, column.getColumnHolder() + ",", notEmpty));
} else {
sql.append(column.getColumnHolder() + ",");
}
}
sql.append("</trim>");
return sql.toString();
}
/**
* update set列
*
* @param entityClass 实体Class
* @param entityName 实体映射名
* @param notNull 是否判断!=null
* @param notEmpty 是否判断String类型!=''
* @return XML中的SET语句块
*/
public static String updateSetColumns(Class<?> entityClass, String entityName, boolean notNull, boolean notEmpty) {
StringBuilder sql = new StringBuilder();
sql.append("<set>");
//获取全部列
Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
//对乐观锁的支持
EntityColumn versionColumn = null;
// 逻辑删除列
EntityColumn logicDeleteColumn = null;
//当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值
for (EntityColumn column : columnSet) {
if (column.getEntityField().isAnnotationPresent(Version.class)) {
if (versionColumn != null) {
throw new VersionException(entityClass.getName() + " 中包含多个带有 @Version 注解的字段,一个类中只能存在一个带有 @Version 注解的字段!");
}
versionColumn = column;
}
if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) {
if (logicDeleteColumn != null) {
throw new LogicDeleteException(entityClass.getName() + " 中包含多个带有 @LogicDelete 注解的字段,一个类中只能存在一个带有 @LogicDelete 注解的字段!");
}
logicDeleteColumn = column;
}
if (!column.isId() && column.isUpdatable()) {
if (column == versionColumn) {
Version version = versionColumn.getEntityField().getAnnotation(Version.class);
String versionClass = version.nextVersion().getName();
sql.append("<bind name=\"").append(column.getProperty()).append("Version\" value=\"");
//version = ${@tk.mybatis.mapper.version@nextVersionClass("versionClass", version)}
sql.append("@tk.mybatis.mapper.version.VersionUtil@nextVersion(")
.append("@").append(versionClass).append("@class, ");
if (StringUtil.isNotEmpty(entityName)) {
sql.append(entityName).append(".");
}
sql.append(column.getProperty()).append(")\"/>");
sql.append(column.getColumn()).append(" = #{").append(column.getProperty()).append("Version},");
} else if (column == logicDeleteColumn) {
sql.append(logicDeleteColumnEqualsValue(column, false)).append(",");
} else if (notNull) {
sql.append(SqlHelper.getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + ",", notEmpty));
} else {
sql.append(column.getColumnEqualsHolder(entityName) + ",");
}
}
}
sql.append("</set>");
return sql.toString();
}
/**
* update set列,不考虑乐观锁注解 @Version
*
* @param entityClass
* @param entityName 实体映射名
* @param notNull 是否判断!=null
* @param notEmpty 是否判断String类型!=''
* @return
*/
public static String updateSetColumnsIgnoreVersion(Class<?> entityClass, String entityName, boolean notNull, boolean notEmpty) {
StringBuilder sql = new StringBuilder();
sql.append("<set>");
//获取全部列
Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
// 逻辑删除列
EntityColumn logicDeleteColumn = null;
//当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值
for (EntityColumn column : columnSet) {
if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) {
if (logicDeleteColumn != null) {
throw new LogicDeleteException(entityClass.getName() + " 中包含多个带有 @LogicDelete 注解的字段,一个类中只能存在一个带有 @LogicDelete 注解的字段!");
}
logicDeleteColumn = column;
}
if (!column.isId() && column.isUpdatable()) {
if (column.getEntityField().isAnnotationPresent(Version.class)) {
//ignore
} else if (column == logicDeleteColumn) {
sql.append(logicDeleteColumnEqualsValue(column, false)).append(",");
} else if (notNull) {
sql.append(SqlHelper.getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + ",", notEmpty));
} else {
sql.append(column.getColumnEqualsHolder(entityName)).append(",");
}
} else if (column.isId() && column.isUpdatable()) {
//set id = id,
sql.append(column.getColumn()).append(" = ").append(column.getColumn()).append(",");
}
}
sql.append("</set>");
return sql.toString();
}
/**
* 不是所有参数都是 null 的检查
*
* @param parameterName 参数名
* @param columnSet 需要检查的列
* @return
*/
public static String notAllNullParameterCheck(String parameterName, Set<EntityColumn> columnSet) {
StringBuilder sql = new StringBuilder();
sql.append("<bind name=\"notAllNullParameterCheck\" value=\"@tk.mybatis.mapper.util.OGNL@notAllNullParameterCheck(");
sql.append(parameterName).append(", '");
StringBuilder fields = new StringBuilder();
for (EntityColumn column : columnSet) {
if (fields.length() > 0) {
fields.append(",");
}
fields.append(column.getProperty());
}
sql.append(fields);
sql.append("')\"/>");
return sql.toString();
}
/**
* Example 中包含至少 1 个查询条件
*
* @param parameterName 参数名
* @return
*/
public static String exampleHasAtLeastOneCriteriaCheck(String parameterName) {
StringBuilder sql = new StringBuilder();
sql.append("<bind name=\"exampleHasAtLeastOneCriteriaCheck\" value=\"@tk.mybatis.mapper.util.OGNL@exampleHasAtLeastOneCriteriaCheck(");
sql.append(parameterName).append(")\"/>");
return sql.toString();
}
/**
* where主键条件
*
* @param entityClass
* @return
*/
public static String wherePKColumns(Class<?> entityClass) {
return wherePKColumns(entityClass, false);
}
/**
* where主键条件
*
* @param entityClass
* @param useVersion
* @return
*/
public static String wherePKColumns(Class<?> entityClass, boolean useVersion) {
return wherePKColumns(entityClass, null, useVersion);
}
/**
* where主键条件
*
* @param entityClass
* @param entityName
* @param useVersion
* @return
*/
public static String wherePKColumns(Class<?> entityClass, String entityName, boolean useVersion) {
StringBuilder sql = new StringBuilder();
boolean hasLogicDelete = hasLogicDeleteColumn(entityClass);
sql.append("<where>");
//获取全部列
Set<EntityColumn> columnSet = EntityHelper.getPKColumns(entityClass);
//当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值
for (EntityColumn column : columnSet) {
sql.append(" AND ").append(column.getColumnEqualsHolder(entityName));
}
if (useVersion) {
sql.append(whereVersion(entityClass));
}
if (hasLogicDelete) {
sql.append(whereLogicDelete(entityClass, false));
}
sql.append("</where>");
return sql.toString();
}
/**
* where所有列的条件,会判断是否!=null
*
* @param entityClass
* @param empty
* @return
*/
public static String whereAllIfColumns(Class<?> entityClass, boolean empty) {
return whereAllIfColumns(entityClass, empty, false);
}
/**
* where所有列的条件,会判断是否!=null
*
* @param entityClass
* @param empty
* @param useVersion
* @return
*/
public static String whereAllIfColumns(Class<?> entityClass, boolean empty, boolean useVersion) {
StringBuilder sql = new StringBuilder();
boolean hasLogicDelete = false;
sql.append("<where>");
//获取全部列
Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
EntityColumn logicDeleteColumn = SqlHelper.getLogicDeleteColumn(entityClass);
//当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值
for (EntityColumn column : columnSet) {
if (!useVersion || !column.getEntityField().isAnnotationPresent(Version.class)) {
// 逻辑删除,后面拼接逻辑删除字段的未删除条件
if (logicDeleteColumn != null && logicDeleteColumn == column) {
hasLogicDelete = true;
continue;
}
sql.append(getIfNotNull(column, " AND " + column.getColumnEqualsHolder(), empty));
}
}
if (useVersion) {
sql.append(whereVersion(entityClass));
}
if (hasLogicDelete) {
sql.append(whereLogicDelete(entityClass, false));
}
sql.append("</where>");
return sql.toString();
}
/**
* 乐观锁字段条件
*
* @param entityClass
* @return
*/
public static String whereVersion(Class<?> entityClass){
return whereVersion(entityClass,null);
}
/**
* 乐观锁字段条件
*
* @param entityClass
* @param entityName 实体名称
* @return
*/
public static String whereVersion(Class<?> entityClass,String entityName) {
Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
boolean hasVersion = false;
String result = "";
for (EntityColumn column : columnSet) {
if (column.getEntityField().isAnnotationPresent(Version.class)) {
if (hasVersion) {
throw new VersionException(entityClass.getName() + " 中包含多个带有 @Version 注解的字段,一个类中只能存在一个带有 @Version 注解的字段!");
}
hasVersion = true;
result = " AND " + column.getColumnEqualsHolder(entityName);
}
}
return result;
}
/**
* 逻辑删除的where条件,没有逻辑删除注解则返回空字符串
* <br>
* AND column = value
*
* @param entityClass
* @param isDeleted true:已经逻辑删除,false:未逻辑删除
* @return
*/
public static String whereLogicDelete(Class<?> entityClass, boolean isDeleted) {
String value = logicDeleteColumnEqualsValue(entityClass, isDeleted);
return "".equals(value) ? "" : " AND " + value;
}
/**
* 返回格式: column = value
* <br>
* 默认isDeletedValue = 1 notDeletedValue = 0
* <br>
* 则返回is_deleted = 1 或 is_deleted = 0
* <br>
* 若没有逻辑删除注解,则返回空字符串
*
* @param entityClass
* @param isDeleted true 已经逻辑删除 false 未逻辑删除
*/
public static String logicDeleteColumnEqualsValue(Class<?> entityClass, boolean isDeleted) {
EntityColumn logicDeleteColumn = SqlHelper.getLogicDeleteColumn(entityClass);
if (logicDeleteColumn != null) {
return logicDeleteColumnEqualsValue(logicDeleteColumn, isDeleted);
}
return "";
}
/**
* 返回格式: column = value
* <br>
* 默认isDeletedValue = 1 notDeletedValue = 0
* <br>
* 则返回is_deleted = 1 或 is_deleted = 0
* <br>
* 若没有逻辑删除注解,则返回空字符串
*
* @param column
* @param isDeleted true 已经逻辑删除 false 未逻辑删除
*/
public static String logicDeleteColumnEqualsValue(EntityColumn column, boolean isDeleted) {
String result = "";
if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) {
Integer logicDeletedValue = getLogicDeletedValue(column, isDeleted);
if(logicDeletedValue==null){
result = column.getColumn() + " is null ";
}else {
result = column.getColumn() + " = " + logicDeletedValue;
}
}
return result;
}
/**
* 获取逻辑删除注解的参数值
*
* @param column
* @param isDeleted true:逻辑删除的值,false:未逻辑删除的值
* @return
*/
public static Integer getLogicDeletedValue(EntityColumn column, boolean isDeleted) {
if (!column.getEntityField().isAnnotationPresent(LogicDelete.class)) {
throw new LogicDeleteException(column.getColumn() + " 没有 @LogicDelete 注解!");
}
LogicDelete logicDelete = column.getEntityField().getAnnotation(LogicDelete.class);
if (isDeleted) {
return logicDelete.isNullForDeletedValue()?null: logicDelete.isDeletedValue();
}
return logicDelete.isNullForNotDeletedValue()?null: logicDelete.notDeletedValue();
}
/**
* 是否有逻辑删除的注解
*
* @param entityClass
* @return
*/
public static boolean hasLogicDeleteColumn(Class<?> entityClass) {
return getLogicDeleteColumn(entityClass) != null;
}
/**
* 获取逻辑删除注解的列,若没有返回null
*
* @param entityClass
* @return
*/
public static EntityColumn getLogicDeleteColumn(Class<?> entityClass) {
EntityColumn logicDeleteColumn = null;
Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
boolean hasLogicDelete = false;
for (EntityColumn column : columnSet) {
if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) {
if (hasLogicDelete) {
throw new LogicDeleteException(entityClass.getName() + " 中包含多个带有 @LogicDelete 注解的字段,一个类中只能存在一个带有 @LogicDelete 注解的字段!");
}
hasLogicDelete = true;
logicDeleteColumn = column;
}
}
return logicDeleteColumn;
}
/**
* 获取默认的orderBy,通过注解设置的
*
* @param entityClass
* @return
*/
public static String orderByDefault(Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
String orderByClause = EntityHelper.getOrderByClause(entityClass);
if (orderByClause.length() > 0) {
sql.append(" ORDER BY ");
sql.append(orderByClause);
}
return sql.toString();
}
/**
* example支持查询指定列时
*
* @return
*/
public static String exampleSelectColumns(Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
sql.append("<choose>");
sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@hasSelectColumns(_parameter)\">");
sql.append("<foreach collection=\"_parameter.selectColumns\" item=\"selectColumn\" separator=\",\">");
sql.append("${selectColumn}");
sql.append("</foreach>");
sql.append("</when>");
//不支持指定列的时候查询全部列
sql.append("<otherwise>");
sql.append(getAllColumns(entityClass));
sql.append("</otherwise>");
sql.append("</choose>");
return sql.toString();
}
/**
* example支持查询指定列时
*
* @return
*/
public static String exampleCountColumn(Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
sql.append("<choose>");
sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@hasCountColumn(_parameter)\">");
sql.append("COUNT(<if test=\"distinct\">distinct </if>${countColumn})");
sql.append("</when>");
sql.append("<otherwise>");
sql.append("COUNT(*)");
sql.append("</otherwise>");
sql.append("</choose>");
return sql.toString();
}
/**
* example查询中的orderBy条件,会判断默认orderBy
*
* @return
*/
public static String exampleOrderBy(Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
sql.append("<if test=\"orderByClause != null\">");
sql.append("order by ${orderByClause}");
sql.append("</if>");
String orderByClause = EntityHelper.getOrderByClause(entityClass);
if (orderByClause.length() > 0) {
sql.append("<if test=\"orderByClause == null\">");
sql.append("ORDER BY " + orderByClause);
sql.append("</if>");
}
return sql.toString();
}
/**
* example查询中的orderBy条件,会判断默认orderBy
*
* @return
*/
public static String exampleOrderBy(String entityName, Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
sql.append("<if test=\"").append(entityName).append(".orderByClause != null\">");
sql.append("order by ${").append(entityName).append(".orderByClause}");
sql.append("</if>");
String orderByClause = EntityHelper.getOrderByClause(entityClass);
if (orderByClause.length() > 0) {
sql.append("<if test=\"").append(entityName).append(".orderByClause == null\">");
sql.append("ORDER BY " + orderByClause);
sql.append("</if>");
}
return sql.toString();
}
/**
* example 支持 for update
*
* @return
*/
public static String exampleForUpdate() {
StringBuilder sql = new StringBuilder();
sql.append("<if test=\"@tk.mybatis.mapper.util.OGNL@hasForUpdate(_parameter)\">");
sql.append("FOR UPDATE");
sql.append("</if>");
return sql.toString();
}
/**
* example 支持 for update
*
* @return
*/
public static String exampleCheck(Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
sql.append("<bind name=\"checkExampleEntityClass\" value=\"@tk.mybatis.mapper.util.OGNL@checkExampleEntityClass(_parameter, '");
sql.append(entityClass.getName());
sql.append("')\"/>");
return sql.toString();
}
/**
* Example查询中的where结构,用于只有一个Example参数时
*
* @return
*/
public static String exampleWhereClause() {
return "<if test=\"_parameter != null\">" +
"<where>\n" +
" ${@tk.mybatis.mapper.util.OGNL@andNotLogicDelete(_parameter)}" +
" <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" +
" <foreach collection=\"oredCriteria\" item=\"criteria\">\n" +
" <if test=\"criteria.valid\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criteria)}" +
" <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" +
" <foreach collection=\"criteria.criteria\" item=\"criterion\">\n" +
" <choose>\n" +
" <when test=\"criterion.noValue\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" +
" </when>\n" +
" <when test=\"criterion.singleValue\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value}\n" +
" </when>\n" +
" <when test=\"criterion.betweenValue\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value} and #{criterion.secondValue}\n" +
" </when>\n" +
" <when test=\"criterion.listValue\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" +
" <foreach close=\")\" collection=\"criterion.value\" item=\"listItem\" open=\"(\" separator=\",\">\n" +
" #{listItem}\n" +
" </foreach>\n" +
" </when>\n" +
" </choose>\n" +
" </foreach>\n" +
" </trim>\n" +
" </if>\n" +
" </foreach>\n" +
" </trim>\n" +
"</where>" +
"</if>";
}
/**
* Example-Update中的where结构,用于多个参数时,Example带@Param("example")注解时
*
* @return
*/
public static String updateByExampleWhereClause() {
return "<where>\n" +
" ${@tk.mybatis.mapper.util.OGNL@andNotLogicDelete(example)}" +
" <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" +
" <foreach collection=\"example.oredCriteria\" item=\"criteria\">\n" +
" <if test=\"criteria.valid\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criteria)}" +
" <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" +
" <foreach collection=\"criteria.criteria\" item=\"criterion\">\n" +
" <choose>\n" +
" <when test=\"criterion.noValue\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" +
" </when>\n" +
" <when test=\"criterion.singleValue\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value}\n" +
" </when>\n" +
" <when test=\"criterion.betweenValue\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value} and #{criterion.secondValue}\n" +
" </when>\n" +
" <when test=\"criterion.listValue\">\n" +
" ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" +
" <foreach close=\")\" collection=\"criterion.value\" item=\"listItem\" open=\"(\" separator=\",\">\n" +
" #{listItem}\n" +
" </foreach>\n" +
" </when>\n" +
" </choose>\n" +
" </foreach>\n" +
" </trim>\n" +
" </if>\n" +
" </foreach>\n" +
" </trim>\n" +
"</where>";
}
}
| abel533/Mapper | core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java |
1,006 | package cn.hutool.poi;
import cn.hutool.core.exceptions.DependencyException;
import cn.hutool.core.util.ClassLoaderUtil;
/**
* POI引入检查器
*
* @author looly
* @since 4.0.10
*/
public class PoiChecker {
/** 没有引入POI的错误消息 */
public static final String NO_POI_ERROR_MSG = "You need to add dependency of 'poi-ooxml' to your project, and version >= 4.1.2";
/**
* 检查POI包的引入情况
*/
public static void checkPoiImport() {
try {
Class.forName("org.apache.poi.ss.usermodel.Workbook", false, ClassLoaderUtil.getClassLoader());
} catch (ClassNotFoundException | NoClassDefFoundError | NoSuchMethodError e) {
throw new DependencyException(e, NO_POI_ERROR_MSG);
}
}
}
| dromara/hutool | hutool-poi/src/main/java/cn/hutool/poi/PoiChecker.java |
1,011 | /**
* @author Anonymous
* @since 2019/10/27
*/
public class Solution {
/**
* 不修改数组查找重复的元素,没有则返回-1
* @param numbers 数组
* @return 重复的元素
*/
public int getDuplication(int[] numbers) {
if (numbers == null || numbers.length < 1) {
return -1;
}
int start = 1;
int end = numbers.length - 1;
while (end >= start) {
int middle = start + ((end - start) >> 1);
// 调用 log n 次
int count = countRange(numbers, start, middle);
if (start == end) {
if (count > 1) {
return start;
}
break;
} else {
// 无法找出所有重复的数
if (count > (middle - start) + 1) {
end = middle;
} else {
start = middle + 1;
}
}
}
return -1;
}
/**
* 计算整个数组中有多少个数的取值在[start, end] 之间
* 时间复杂度 O(n)
* @param numbers 数组
* @param start 左边界
* @param end 右边界
* @return 数量
*/
private int countRange(int[] numbers, int start, int end) {
if (numbers == null) {
return 0;
}
int count = 0;
for(int e : numbers) {
if (e >= start && e <= end) {
++count;
}
}
return count;
}
} | geekxh/hello-algorithm | 算法读物/剑指offer/03_02_DuplicationInArrayNoEdit/Solution.java |
1,012 | package org.linlinjava.litemall.db.util;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import java.util.ArrayList;
import java.util.List;
/*
* 订单流程:下单成功-》支付订单-》发货-》收货
* 订单状态:
* 101 订单生成,未支付;102,下单未支付用户取消;103,下单未支付超期系统自动取消
* 201 支付完成,商家未发货;202,订单生产,已付款未发货,用户申请退款;203,管理员执行退款操作,确认退款成功;
* 301 商家发货,用户未确认;
* 401 用户确认收货,订单结束; 402 用户没有确认收货,但是快递反馈已收货后,超过一定时间,系统自动确认收货,订单结束。
*
* 当101用户未付款时,此时用户可以进行的操作是取消或者付款
* 当201支付完成而商家未发货时,此时用户可以退款
* 当301商家已发货时,此时用户可以有确认收货
* 当401用户确认收货以后,此时用户可以进行的操作是退货、删除、去评价或者再次购买
* 当402系统自动确认收货以后,此时用户可以删除、去评价、或者再次购买
*/
public class OrderUtil {
public static final Short STATUS_CREATE = 101;
public static final Short STATUS_PAY = 201;
public static final Short STATUS_SHIP = 301;
public static final Short STATUS_CONFIRM = 401;
public static final Short STATUS_CANCEL = 102;
public static final Short STATUS_AUTO_CANCEL = 103;
public static final Short STATUS_ADMIN_CANCEL = 104;
public static final Short STATUS_REFUND = 202;
public static final Short STATUS_REFUND_CONFIRM = 203;
public static final Short STATUS_AUTO_CONFIRM = 402;
public static String orderStatusText(LitemallOrder order) {
int status = order.getOrderStatus().intValue();
if (status == 101) {
return "未付款";
}
if (status == 102) {
return "已取消";
}
if (status == 103) {
return "已取消(系统)";
}
if (status == 201) {
return "已付款";
}
if (status == 202) {
return "订单取消,退款中";
}
if (status == 203) {
return "已退款";
}
if (status == 204) {
return "已超时团购";
}
if (status == 301) {
return "已发货";
}
if (status == 401) {
return "已收货";
}
if (status == 402) {
return "已收货(系统)";
}
throw new IllegalStateException("orderStatus不支持");
}
public static OrderHandleOption build(LitemallOrder order) {
int status = order.getOrderStatus().intValue();
OrderHandleOption handleOption = new OrderHandleOption();
if (status == 101) {
// 如果订单没有被取消,且没有支付,则可支付,可取消
handleOption.setCancel(true);
handleOption.setPay(true);
} else if (status == 102 || status == 103) {
// 如果订单已经取消或是已完成,则可删除
handleOption.setDelete(true);
} else if (status == 201) {
// 如果订单已付款,没有发货,则可退款
handleOption.setRefund(true);
} else if (status == 202 || status == 204) {
// 如果订单申请退款中,没有相关操作
} else if (status == 203) {
// 如果订单已经退款,则可删除
handleOption.setDelete(true);
} else if (status == 301) {
// 如果订单已经发货,没有收货,则可收货操作,
// 此时不能取消订单
handleOption.setConfirm(true);
} else if (status == 401 || status == 402) {
// 如果订单已经支付,且已经收货,则可删除、去评论、申请售后和再次购买
handleOption.setDelete(true);
handleOption.setComment(true);
handleOption.setRebuy(true);
handleOption.setAftersale(true);
} else {
throw new IllegalStateException("status不支持");
}
return handleOption;
}
public static List<Short> orderStatus(Integer showType) {
// 全部订单
if (showType == 0) {
return null;
}
List<Short> status = new ArrayList<Short>(2);
if (showType.equals(1)) {
// 待付款订单
status.add((short) 101);
} else if (showType.equals(2)) {
// 待发货订单
status.add((short) 201);
} else if (showType.equals(3)) {
// 待收货订单
status.add((short) 301);
} else if (showType.equals(4)) {
// 待评价订单
status.add((short) 401);
// 系统超时自动取消,此时应该不支持评价
// status.add((short)402);
} else {
return null;
}
return status;
}
public static boolean isCreateStatus(LitemallOrder litemallOrder) {
return OrderUtil.STATUS_CREATE == litemallOrder.getOrderStatus().shortValue();
}
public static boolean hasPayed(LitemallOrder order) {
return OrderUtil.STATUS_CREATE != order.getOrderStatus().shortValue()
&& OrderUtil.STATUS_CANCEL != order.getOrderStatus().shortValue()
&& OrderUtil.STATUS_AUTO_CANCEL != order.getOrderStatus().shortValue();
}
public static boolean isPayStatus(LitemallOrder litemallOrder) {
return OrderUtil.STATUS_PAY == litemallOrder.getOrderStatus().shortValue();
}
public static boolean isShipStatus(LitemallOrder litemallOrder) {
return OrderUtil.STATUS_SHIP == litemallOrder.getOrderStatus().shortValue();
}
public static boolean isConfirmStatus(LitemallOrder litemallOrder) {
return OrderUtil.STATUS_CONFIRM == litemallOrder.getOrderStatus().shortValue();
}
public static boolean isCancelStatus(LitemallOrder litemallOrder) {
return OrderUtil.STATUS_CANCEL == litemallOrder.getOrderStatus().shortValue();
}
public static boolean isAutoCancelStatus(LitemallOrder litemallOrder) {
return OrderUtil.STATUS_AUTO_CANCEL == litemallOrder.getOrderStatus().shortValue();
}
public static boolean isRefundStatus(LitemallOrder litemallOrder) {
return OrderUtil.STATUS_REFUND == litemallOrder.getOrderStatus().shortValue();
}
public static boolean isRefundConfirmStatus(LitemallOrder litemallOrder) {
return OrderUtil.STATUS_REFUND_CONFIRM == litemallOrder.getOrderStatus().shortValue();
}
public static boolean isAutoConfirmStatus(LitemallOrder litemallOrder) {
return OrderUtil.STATUS_AUTO_CONFIRM == litemallOrder.getOrderStatus().shortValue();
}
}
| linlinjava/litemall | litemall-db/src/main/java/org/linlinjava/litemall/db/util/OrderUtil.java |
1,013 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.okgo.callback;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.convert.Converter;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2016/1/14
* 描 述:抽象的回调接口
* 修订历史:
* ================================================
* <p>该类的回调具有如下顺序,虽然顺序写的很复杂,但是理解后,是很简单,并且合情合理的
* <p>1.无缓存模式{@link CacheMode#NO_CACHE}<br>
* ---网络请求成功 onStart -> convertResponse -> onSuccess -> onFinish<br>
* ---网络请求失败 onStart -> onError -> onFinish<br>
* <p>2.默认缓存模式,遵循304头{@link CacheMode#DEFAULT}<br>
* ---网络请求成功,服务端返回非304 onStart -> convertResponse -> onSuccess -> onFinish<br>
* ---网络请求成功服务端返回304 onStart -> onCacheSuccess -> onFinish<br>
* ---网络请求失败 onStart -> onError -> onFinish<br>
* <p>3.请求网络失败后读取缓存{@link CacheMode#REQUEST_FAILED_READ_CACHE}<br>
* ---网络请求成功,不读取缓存 onStart -> convertResponse -> onSuccess -> onFinish<br>
* ---网络请求失败,读取缓存成功 onStart -> onCacheSuccess -> onFinish<br>
* ---网络请求失败,读取缓存失败 onStart -> onError -> onFinish<br>
* <p>4.如果缓存不存在才请求网络,否则使用缓存{@link CacheMode#IF_NONE_CACHE_REQUEST}<br>
* ---已经有缓存,不请求网络 onStart -> onCacheSuccess -> onFinish<br>
* ---没有缓存请求网络成功 onStart -> convertResponse -> onSuccess -> onFinish<br>
* ---没有缓存请求网络失败 onStart -> onError -> onFinish<br>
* <p>5.先使用缓存,不管是否存在,仍然请求网络{@link CacheMode#FIRST_CACHE_THEN_REQUEST}<br>
* ---无缓存时,网络请求成功 onStart -> convertResponse -> onSuccess -> onFinish<br>
* ---无缓存时,网络请求失败 onStart -> onError -> onFinish<br>
* ---有缓存时,网络请求成功 onStart -> onCacheSuccess -> convertResponse -> onSuccess -> onFinish<br>
* ---有缓存时,网络请求失败 onStart -> onCacheSuccess -> onError -> onFinish<br>
*/
public interface Callback<T> extends Converter<T> {
/** 请求网络开始前,UI线程 */
void onStart(Request<T, ? extends Request> request);
/** 对返回数据进行操作的回调, UI线程 */
void onSuccess(Response<T> response);
/** 缓存成功的回调,UI线程 */
void onCacheSuccess(Response<T> response);
/** 请求失败,响应错误,数据解析错误等,都会回调该方法, UI线程 */
void onError(Response<T> response);
/** 请求网络结束后,UI线程 */
void onFinish();
/** 上传过程中的进度回调,get请求不回调,UI线程 */
void uploadProgress(Progress progress);
/** 下载过程中的进度回调,UI线程 */
void downloadProgress(Progress progress);
}
| jeasonlzy/okhttp-OkGo | okgo/src/main/java/com/lzy/okgo/callback/Callback.java |
1,014 | package me.zhyd.oauth.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 今日头条授权登录时的异常状态码
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @since 1.8
*/
@Getter
@AllArgsConstructor
public enum AuthToutiaoErrorCode {
/**
* 0:正常;
* other:调用异常,具体异常内容见{@code desc}
*/
EC0(0, "接口调用成功"),
EC1(1, "API配置错误,未传入Client Key"),
EC2(2, "API配置错误,Client Key错误,请检查是否和开放平台的ClientKey一致"),
EC3(3, "没有授权信息"),
EC4(4, "响应类型错误"),
EC5(5, "授权类型错误"),
EC6(6, "client_secret错误"),
EC7(7, "authorize_code过期"),
EC8(8, "指定url的scheme不是https"),
EC9(9, "接口内部错误,请联系头条技术"),
EC10(10, "access_token过期"),
EC11(11, "缺少access_token"),
EC12(12, "参数缺失"),
EC13(13, "url错误"),
EC21(21, "域名与登记域名不匹配"),
EC999(999, "未知错误,请联系头条技术"),
;
private int code;
private String desc;
public static AuthToutiaoErrorCode getErrorCode(int errorCode) {
AuthToutiaoErrorCode[] errorCodes = AuthToutiaoErrorCode.values();
for (AuthToutiaoErrorCode code : errorCodes) {
if (code.getCode() == errorCode) {
return code;
}
}
return EC999;
}
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/enums/AuthToutiaoErrorCode.java |
1,015 | package com.sohu.cache.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sohu.cache.server.data.OS;
import com.sohu.cache.server.data.OSInfo;
import com.sohu.cache.server.data.OSInfo.DistributionType;
import com.sohu.cache.server.data.OSInfo.DistributionVersion;
import com.sohu.cache.server.data.OSInfo.OSType;
import com.sohu.cache.server.data.OSInfo.ProcessorArchitecture;
/**
* 根据操作系统原生信息解析出OS
*/
public class OSFactory {
private static final Logger logger = LoggerFactory.getLogger(OSFactory.class);
//获取发行版本号的主版本和次版本
private static final Pattern VERSION_PATTERN = Pattern.compile("([1-9]+(\\.[0-9]+)?)");
public static OS getDefaultOS(OSInfo osInfo) {
String uname = osInfo.getUname();
//无法获取系统位数
if(uname == null) {
return null;
}
uname = uname.toLowerCase();
ProcessorArchitecture defaultArch = ProcessorArchitecture.X86_64;
//其次获取操作系统位数
if(!uname.contains(defaultArch.getValue())) {
defaultArch = ProcessorArchitecture.X86;
}
return new OS(OSType.LINUX, DistributionType.LINUX_OLD,
DistributionVersion.DEFAULT, defaultArch);
}
/**
* 采用uname -a信息和/etc/issue解析出目前能够支持的操作系统
* @param osInfo
* @return OS
*/
public static OS getOS(OSInfo osInfo) {
String uname = osInfo.getUname();
String issue = osInfo.getIssue();
OSType osType = OSType.LINUX;
ProcessorArchitecture defaultArch = ProcessorArchitecture.X86_64;
DistributionType defaultDist = DistributionType.LINUX_OLD;
DistributionVersion version = DistributionVersion.DEFAULT;
//无法获取系统类型,位数 版本,采用默认
if(uname == null || issue == null) {
OS os = new OS(osType, defaultDist, version, defaultArch);
return os;
}
uname = uname.toLowerCase();
//首先获取操作系统类型
if(!uname.contains(OSType.LINUX.getValue())) {
logger.error("os={} is temporarily not supported", uname);
return null;
}
//其次获取操作系统位数
if(!uname.contains(defaultArch.getValue())) {
defaultArch = ProcessorArchitecture.X86;
}
//再次解析操作系统发行版本
issue = issue.toLowerCase();
DistributionType findType = DistributionType.findByContains(issue);
//没有找到匹配的版本,使用默认
if(findType == null) {
logger.warn("dist cannot matched, {}", issue);
OS os = new OS(osType, defaultDist, version, defaultArch);
return os;
}
//最后解析版本号
Matcher matcher = VERSION_PATTERN.matcher(issue);
//没有版本好用默认的
if(!matcher.find()) {
logger.warn("version not matched, {}", issue);
OS os = new OS(osType, defaultDist, version, defaultArch);
return os;
}
String ver = matcher.group();
ver = ver.replaceAll("\\.", "");
logger.info("version matched, {} - {}", ver, issue);
DistributionVersion versionResult = findVersion(findType.getVersions(), ver);
//没有具体的版本能匹配上
if(versionResult == null) {
logger.info("version {} not found, {}", ver, issue);
OS os = new OS(osType, defaultDist, version, defaultArch);
return os;
}
OS os = new OS(osType, findType, versionResult, defaultArch);
logger.info("find OS={}", os);
return os;
}
private static DistributionVersion findVersion(DistributionVersion[] versions, String target) {
for(DistributionVersion dv : versions) {
if(dv.getValue().equals(target)){
return dv;
}
}
return null;
}
}
| sohutv/cachecloud | cachecloud-web/src/main/java/com/sohu/cache/util/OSFactory.java |
1,016 | package org.jeecg.modules.demo.gpt.service.impl;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.Message;
import com.unfbx.chatgpt.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.demo.gpt.cache.LocalCache;
import org.jeecg.modules.demo.gpt.listeners.OpenAISSEEventSourceListener;
import org.jeecg.modules.demo.gpt.service.ChatService;
import org.jeecg.modules.demo.gpt.vo.ChatHistoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
//update-begin---author:chenrui ---date:20240126 for:【QQYUN-7932】AI助手------------
/**
* AI助手聊天Service
* @author chenrui
* @date 2024/1/26 20:07
*/
@Service
@Slf4j
public class ChatServiceImpl implements ChatService {
//update-begin---author:chenrui ---date:20240223 for:[QQYUN-8225]聊天记录保存------------
private static final String CACHE_KEY_PREFIX = "ai:chart:";
/**
*
*/
private static final String CACHE_KEY_MSG_CONTEXT = "msg_content";
/**
*
*/
private static final String CACHE_KEY_MSG_HISTORY = "msg_history";
@Autowired
RedisTemplate redisTemplate;
//update-end---author:chenrui ---date:20240223 for:[QQYUN-8225]聊天记录保存------------
private OpenAiStreamClient openAiStreamClient = null;
//update-begin---author:chenrui ---date:20240131 for:[QQYUN-8212]fix 没有配置启动报错------------
public ChatServiceImpl() {
try {
this.openAiStreamClient = SpringContextUtils.getBean(OpenAiStreamClient.class);
} catch (Exception ignored) {
}
}
/**
* 防止client不能成功注入
* @return
* @author chenrui
* @date 2024/2/3 23:08
*/
private OpenAiStreamClient ensureClient(){
if(null == this.openAiStreamClient){
this.openAiStreamClient = SpringContextUtils.getBean(OpenAiStreamClient.class);
}
return this.openAiStreamClient;
}
//update-end---author:chenrui ---date:20240131 for:[QQYUN-8212]fix 没有配置启动报错------------
private String getUserId() {
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
return sysUser.getId();
}
@Override
public SseEmitter createChat() {
String uid = getUserId();
//默认30秒超时,设置为0L则永不超时
SseEmitter sseEmitter = new SseEmitter(-0L);
//完成后回调
sseEmitter.onCompletion(() -> {
log.info("[{}]结束连接...................",uid);
LocalCache.CACHE.remove(uid);
});
//超时回调
sseEmitter.onTimeout(() -> {
log.info("[{}]连接超时...................", uid);
});
//异常回调
sseEmitter.onError(
throwable -> {
try {
log.info("[{}]连接异常,{}", uid, throwable.toString());
sseEmitter.send(SseEmitter.event()
.id(uid)
.name("发生异常!")
.data(Message.builder().content("发生异常请重试!").build())
.reconnectTime(3000));
LocalCache.CACHE.put(uid, sseEmitter);
} catch (IOException e) {
log.error(e.getMessage(),e);
}
}
);
try {
sseEmitter.send(SseEmitter.event().reconnectTime(5000));
} catch (IOException e) {
log.error(e.getMessage(),e);
}
LocalCache.CACHE.put(uid, sseEmitter);
log.info("[{}]创建sse连接成功!", uid);
return sseEmitter;
}
@Override
public void closeChat() {
String uid = getUserId();
SseEmitter sse = (SseEmitter) LocalCache.CACHE.get(uid);
if (sse != null) {
sse.complete();
//移除
LocalCache.CACHE.remove(uid);
}
}
@Override
public void sendMessage(String topicId, String message) {
String uid = getUserId();
if (StrUtil.isBlank(message)) {
log.info("参数异常,message为null");
throw new BaseException("参数异常,message不能为空~");
}
if (StrUtil.isBlank(topicId)) {
topicId = UUIDGenerator.generate();
}
//update-begin---author:chenrui ---date:20240223 for:[QQYUN-8225]聊天记录保存------------
log.info("话题id:{}", topicId);
String cacheKey = CACHE_KEY_PREFIX + uid + "_" + topicId;
String messageContext = (String) redisTemplate.opsForHash().get(cacheKey, CACHE_KEY_MSG_CONTEXT);
List<Message> msgHistory = new ArrayList<>();
if (StrUtil.isNotBlank(messageContext)) {
List<Message> messages = JSONArray.parseArray(messageContext, Message.class);
msgHistory = messages == null ? new ArrayList<>() : messages;
}
Message currentMessage = Message.builder().content(message).role(Message.Role.USER).build();
msgHistory.add(currentMessage);
SseEmitter sseEmitter = (SseEmitter) LocalCache.CACHE.get(uid);
if (sseEmitter == null) {
log.info("聊天消息推送失败uid:[{}],没有创建连接,请重试。", uid);
throw new JeecgBootException("聊天消息推送失败uid:[{}],没有创建连接,请重试。~");
}
OpenAISSEEventSourceListener openAIEventSourceListener = new OpenAISSEEventSourceListener(topicId, sseEmitter);
ChatCompletion completion = ChatCompletion
.builder()
.messages(msgHistory)
.model(ChatCompletion.Model.GPT_3_5_TURBO.getName())
.build();
ensureClient().streamChatCompletion(completion, openAIEventSourceListener);
redisTemplate.opsForHash().put(cacheKey, CACHE_KEY_MSG_CONTEXT, JSONUtil.toJsonStr(msgHistory));
//update-end---author:chenrui ---date:20240223 for:[QQYUN-8225]聊天记录保存------------
Result.ok(completion.tokens());
}
//update-begin---author:chenrui ---date:20240223 for:[QQYUN-8225]聊天记录保存------------
@Override
public Result<?> saveHistory(ChatHistoryVO chatHistoryVO) {
String uid = getUserId();
String cacheKey = CACHE_KEY_PREFIX + CACHE_KEY_MSG_HISTORY + ":" + uid;
redisTemplate.opsForValue().set(cacheKey, chatHistoryVO.getContent());
return Result.OK("保存成功");
}
@Override
public Result<ChatHistoryVO> getHistoryByTopic() {
String uid = getUserId();
String cacheKey = CACHE_KEY_PREFIX + CACHE_KEY_MSG_HISTORY + ":" + uid;
String historyContent = (String) redisTemplate.opsForValue().get(cacheKey);
ChatHistoryVO chatHistoryVO = new ChatHistoryVO();
chatHistoryVO.setContent(historyContent);
return Result.OK(chatHistoryVO);
}
//update-end---author:chenrui ---date:20240223 for:[QQYUN-8225]聊天记录保存------------
}
//update-end---author:chenrui ---date:20240126 for:【QQYUN-7932】AI助手------------
| jeecgboot/jeecg-boot | jeecg-module-demo/src/main/java/org/jeecg/modules/demo/gpt/service/impl/ChatServiceImpl.java |
1,017 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.okgo.cache.policy;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.Response;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2017/5/25
* 描 述:
* 修订历史:
* ================================================
*/
public interface CachePolicy<T> {
/**
* 获取数据成功的回调
*
* @param success 获取的数据,可是是缓存或者网络
*/
void onSuccess(Response<T> success);
/**
* 获取数据失败的回调
*
* @param error 失败的信息,可是是缓存或者网络
*/
void onError(Response<T> error);
/**
* 控制是否执行后续的回调动作
*
* @param call 请求的对象
* @param response 响应的对象
* @return true,不执行回调, false 执行回调
*/
boolean onAnalysisResponse(okhttp3.Call call, okhttp3.Response response);
/**
* 构建缓存
*
* @return 获取的缓存
*/
CacheEntity<T> prepareCache();
/**
* 构建请求对象
*
* @return 准备请求的对象
*/
okhttp3.Call prepareRawCall() throws Throwable;
/**
* 同步请求获取数据
*
* @param cacheEntity 本地的缓存
* @return 从缓存或本地获取的数据
*/
Response<T> requestSync(CacheEntity<T> cacheEntity);
/**
* 异步请求获取数据
*
* @param cacheEntity 本地的缓存
* @param callback 异步回调
*/
void requestAsync(CacheEntity<T> cacheEntity, Callback<T> callback);
/**
* 当前请求是否已经执行
*
* @return true,已经执行, false,没有执行
*/
boolean isExecuted();
/**
* 取消请求
*/
void cancel();
/**
* 是否已经取消
*
* @return true,已经取消,false,没有取消
*/
boolean isCanceled();
}
| jeasonlzy/okhttp-OkGo | okgo/src/main/java/com/lzy/okgo/cache/policy/CachePolicy.java |
1,018 | package practice;
/**
* @program: leetcode
* @description:
* @author: [email protected]
* @create: 2022-06-30 22:33
**/
public class L0142 {
public ListNode detectCycle(ListNode head) {
// 异常处理
if (null==head || null==head.next) {
return null;
}
boolean hasCycle = false;
ListNode fast = head;
ListNode slow = head;
while (null!=fast && null!=fast.next) {
fast = fast.next.next;
slow = slow.next;
// 发现环,就退出while循环
if (fast==slow) {
hasCycle = true;
break;
}
}
// 没有环就立即返回null
if (!hasCycle) {
return null;
}
// 根据算式推导出:从相遇位置和定点同时出发,两个指针相遇地点就是环形入口处
while (head!=slow) {
head = head.next;
slow = slow.next;
}
return slow;
}
public static void main(String[] args) {
ListNode l0 = new ListNode(3);
ListNode l1 = new ListNode(2);
ListNode l2 = new ListNode(0);
ListNode l3 = new ListNode(-4);
l0.next = l1;
l1.next = l2;
l2.next = l3;
l3.next = l1;
ListNode rlt = new L0142().detectCycle(l0);
System.out.println(null==rlt ? null : rlt.val);
}
}
| zq2599/blog_demos | leetcode/src/practice/L0142.java |
1,019 | package practice;
import java.util.ArrayList;
import java.util.List;
/**
* @program: leetcode
* @description:
* @author: [email protected]
* @create: 2022-06-30 22:33
**/
public class L0448 {
/*
public List<Integer> findDisappearedNumbers(Integer[] nums) {
List<Integer> rlt = new ArrayList<>();
if (nums==null || nums.length<1) {
return rlt;
}
// 本题的关键:数组元素的每一个值,减一之后,一定是个索引位置
// 例如数组长度等于3,索引位置就是0,,1,,2
// 该数组中的元素值,减一后,一定是0,1,2三者之一,
// 所以,根据元素值,一定可以找到一个索引,例如元素值2,减一后就是1,一定有个索引等于1,
// 基于以上规律,读取每个元素值,给对应的索引打标,读到1就给nums[0]打标,读到2就给nums[1]打标,读到3就给nums[3]打标,
// 最后检查整个数组,没有打标的元素,一定是因为有个数字在数组中不存在,例如num[1]没打标,就表示数组中没有读到过2
int max = nums.length;
int index = 0;
for (int i=0;i<max;i++) {
// 题目中,元素值的大小不会超过数组长度,
// 所以,如果元素大小超过数组长度,就意味着刚才已经打标了
if(nums[i]>max) {
// 需要去掉标签才是该元素的原始值
index = nums[i]-max;
} else {
index = nums[i];
}
// 元素值一定对应着一个索引,
// 现在看这个索引位置的值是否已经打标,如果没有,就打标
if(nums[index-1]<=max) {
// 所谓打标,就是加上max
nums[index-1] += max;
}
}
for (int i=0;i<max;i++) {
if(nums[i]<=max) {
rlt.add(i+1);
}
}
return rlt;
}
*/
public List<Integer> findDisappearedNumbers(Integer[] nums) {
List<Integer> rlt = new ArrayList<>();
if (nums==null || nums.length<1) {
return rlt;
}
// 本题的关键:数组元素的每一个值,减一之后,一定是个索引位置
// 例如数组长度等于3,索引位置就是0,,1,,2
// 该数组中的元素值,减一后,一定是0,1,2三者之一,
// 所以,根据元素值,一定可以找到一个索引,例如元素值2,减一后就是1,一定有个索引等于1,
// 基于以上规律,读取每个元素值,给对应的索引打标,读到1就给nums[0]打标,读到2就给nums[1]打标,读到3就给nums[3]打标,
// 最后检查整个数组,没有打标的元素,一定是因为有个数字在数组中不存在,例如num[1]没打标,就表示数组中没有读到过2
int max = nums.length;
int index;
for (int i=0;i<max;i++) {
// 千万注意,这里要先减去1,再取模
// 如果先用nums[i]模max,再减一的话,当nums[i]等于max的时候,模完了就是0了,再减一的话结果等于-1,这是不符合要求的,
// 不论之前加过几次max,取模后都能还原成加max之前的状态
index = (nums[i] -1)%max;
// index就是数组元素的原始值,该值一定是个索引位置
nums[index] += max;
}
for (int i=0;i<max;i++) {
if(nums[i]<=max) {
rlt.add(i+1);
}
}
return rlt;
}
public static void main( String[] args ) {
System.out.println(new L0448().findDisappearedNumbers(new Integer[]{4,3,2,7,8,2,3,1}));
}
}
| zq2599/blog_demos | leetcode/src/practice/L0448.java |
1,020 | package practice;
/**
* @program: leetcode
* @description:
* @author: [email protected]
* @create: 2022-06-30 22:33
**/
public class L0123 {
// 0 : 第一次买入
// 1 : 第一次卖出
// 2 : 第二次买入
// 3 : 第二次卖出
/*
public int maxProfit(int[] prices) {
if (1==prices.length) {
return 0;
}
int[][] dp = new int[prices.length][4];
// 股票交易第一天结束
// 0 : 第一次买入
dp[0][0] = -prices[0];
// 1 : 第一次卖出
dp[0][1] = 0;
// 2 : 第二次买入
dp[0][2] = 0;
// 3 : 第二次卖出
dp[0][3] = 0;
// 股票交易第二天结束
// 0 : 第一次买入,前两天的最低股价
dp[1][0] = Math.max(dp[0][0], -prices[1]);
// 1 : 第一次卖出,只能是第0天买入,第1天卖出
dp[1][1] = prices[1]-prices[0];
// 2 : 第二次买入,股市总共才两天,不可能出现第二次买入
dp[1][2] = 0;
// 3 : 第二次卖出,股市总共才两天,不可能出现第二次卖出
dp[1][3] = 0;
// 股票交易第二天结束,只能有一次卖出
if(2==prices.length) {
return Math.max(0, dp[1][1]);
}
// 股票交易第三天结束
// 0 : 第一次买入,两种可能:之前第一次买入,当天第一次买入(一分钱没有,再减去当天股价)
dp[2][0] = Math.max(dp[1][0], -prices[2]);
// 1 : 第一次卖出,两种可能:之前第一次卖出,当天第一次卖出(之前第一次买入,再加上当天股价)
dp[2][1] = Math.max(dp[1][1], dp[1][0]+prices[2]);
// 2 : 第二次买入,股票交易第三天结束,只可能是第一天买->第二天卖->第三天买
dp[2][2] = -prices[0] + prices[1] - prices[2];
// 3 : 第二次卖出,股票交易第三天结束,不可能出现第二次卖出
dp[2][3] = 0;
// 股票交易第三天结束,只能有一次卖出
if(3==prices.length) {
return Math.max(0, dp[2][1]);
}
// 股票交易第四天结束
// 0 : 第一次买入,两种可能:之前第一次买入,当天第一次买入(一分钱没有,再减去当天股价)
dp[3][0] = Math.max(dp[2][0], -prices[3]);
// 1 : 第一次卖出,两种可能:之前第一次卖出,当天第一次卖出(之前第一次买入,再加上当天股价)
dp[3][1] = Math.max(dp[2][1], dp[2][0]+prices[3]);
// 2 : 第二次买入,两种可能:之前第二次买入,当天第二次买入(之前第一次卖出,再减去当天股价)
dp[3][2] = Math.max(dp[2][2], dp[2][1]-prices[3]);
// 3 : 第二次卖出,股票交易第四天结束,只可能是第一天买->第二天卖->第三天买->第四天卖
dp[3][3] = -prices[0] + prices[1] - prices[2] + prices[3];
// 股票交易第四天结束,一次或者两次卖出都有可能
if(4==prices.length) {
return Math.max(0, Math.max(dp[3][1], dp[3][3]));
}
// 注意审题,prices.length>=1
for (int i=4;i<prices.length;i++) {
// 0 : 第一次买入,两种可能:之前第一次买入,当天第一次买入(一分钱没有,再减去当天股价)
dp[i][0] = Math.max(dp[i-1][0], -prices[i]);
// 1 : 第一次卖出,两种可能:之前第一次卖出,当天第一次卖出(之前第一次买入,再加上当天股价)
dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0]+prices[i]);
// 2 : 第二次买入,两种可能:之前第二次买入,当天第二次买入(之前第一次卖出,再减去当天股价)
dp[i][2] = Math.max(dp[i-1][2], dp[i-1][1]-prices[i]);
// 3 : 第二次卖出,两种可能:之前第二次卖出,当天第二次卖出(之前第二次买入,再加上当天股价)
dp[i][3] = Math.max(dp[i-1][3], dp[i-1][2]+prices[i]);
}
// 注意,如果算出来是负数,就返回0,表示这些天未做交易
return Math.max(0, Math.max(dp[prices.length-1][1], dp[prices.length-1][3]));
}
*/
/*
public int maxProfit(int[] prices) {
if (1==prices.length) {
return 0;
}
int buy1 = 0;
int sell1 = 0;
int buy2 = 0;
int sell2 = 0;
// 股票交易第一天结束
// 0 : 第一次买入
buy1 = -prices[0];
// 1 : 第一次卖出,不可能发生
// 2 : 第二次买入,不可能发生
// 3 : 第二次卖出,不可能发生
// 股票交易第二天结束
// 0 : 第一次买入,前两天的最低股价
buy1 = Math.max(buy1, -prices[1]);
// 1 : 第一次卖出,只能是第0天买入,第1天卖出
sell1 = prices[1]-prices[0];
// 2 : 第二次买入,股市总共才两天,不可能出现第二次买入
// 3 : 第二次卖出,股市总共才两天,不可能出现第二次卖出
// 股票交易第二天结束,只能有一次卖出
if(2==prices.length) {
return Math.max(0, sell1);
}
// 股票交易第三天结束
// 0 : 第一次买入,两种可能:之前第一次买入,当天第一次买入(一分钱没有,再减去当天股价)
buy1 = Math.max(buy1, -prices[2]);
// 1 : 第一次卖出,两种可能:之前第一次卖出,当天第一次卖出(之前第一次买入,再加上当天股价)
sell1 = Math.max(sell1, buy1+prices[2]);
// 2 : 第二次买入,股票交易第三天结束,只可能是第一天买->第二天卖->第三天买
buy2 = -prices[0] + prices[1] - prices[2];
// 3 : 第二次卖出,股票交易第三天结束,不可能出现第二次卖出
// 股票交易第三天结束,只能有一次卖出
if(3==prices.length) {
return Math.max(0, sell1);
}
// 股票交易第四天结束
// 0 : 第一次买入,两种可能:之前第一次买入,当天第一次买入(一分钱没有,再减去当天股价)
buy1 = Math.max(buy1, -prices[3]);
// 1 : 第一次卖出,两种可能:之前第一次卖出,当天第一次卖出(之前第一次买入,再加上当天股价)
sell1 = Math.max(sell1, buy1+prices[3]);
// 2 : 第二次买入,两种可能:之前第二次买入,当天第二次买入(之前第一次卖出,再减去当天股价)
buy2 = Math.max(buy2, sell1-prices[3]);
// 3 : 第二次卖出,股票交易第四天结束,只可能是第一天买->第二天卖->第三天买->第四天卖
sell2 = -prices[0] + prices[1] - prices[2] + prices[3];
// 股票交易第四天结束,一次或者两次卖出都有可能
if(4==prices.length) {
return Math.max(0, Math.max(sell1, sell2));
}
// 注意审题,prices.length>=1
for (int i=4;i<prices.length;i++) {
// 0 : 第一次买入,两种可能:之前第一次买入,当天第一次买入(一分钱没有,再减去当天股价)
buy1 = Math.max(buy1, -prices[i]);
// 1 : 第一次卖出,两种可能:之前第一次卖出,当天第一次卖出(之前第一次买入,再加上当天股价)
sell1 = Math.max(sell1, buy1+prices[i]);
// 2 : 第二次买入,两种可能:之前第二次买入,当天第二次买入(之前第一次卖出,再减去当天股价)
buy2 = Math.max(buy2, sell1-prices[i]);
// 3 : 第二次卖出,两种可能:之前第二次卖出,当天第二次卖出(之前第二次买入,再加上当天股价)
sell2 = Math.max(sell2, buy2+prices[i]);
}
// 注意,如果算出来是负数,就返回0,表示这些天未做交易
return Math.max(0, Math.max(sell1, sell2));
}
*/
public int maxProfit(int[] prices) {
if (1==prices.length) {
return 0;
}
int buy1 = -prices[0];
int sell1 = 0;
// 注意,在计算过程中,如果buy2的默认值是0,当i小于4的时候,也就是第二次买卖还不存在的时候,让第二次买入状态的最大利润等于0,会影响后面sell2的计算,所以应该让其等于buy1才对
// 此时buy2是不存在的,如果给buy2默认值是0,就会导致所以""
int buy2 = -prices[0];
int sell2 = 0;
for (int i=1;i<prices.length;i++) {
// 0 : 第一次买入,两种可能:之前第一次买入,当天第一次买入(一分钱没有,再减去当天股价)
buy1 = Math.max(buy1, -prices[i]);
// 1 : 第一次卖出,两种可能:之前第一次卖出,当天第一次卖出(之前第一次买入,再加上当天股价)
sell1 = Math.max(sell1, buy1+prices[i]);
// 2 : 第二次买入,两种可能:之前第二次买入,当天第二次买入(之前第一次卖出,再减去当天股价)
buy2 = Math.max(buy2, sell1-prices[i]);
// 3 : 第二次卖出,两种可能:之前第二次卖出,当天第二次卖出(之前第二次买入,再加上当天股价)
sell2 = Math.max(sell2, buy2+prices[i]);
}
// 注意,如果算出来是负数,就返回0,表示这些天未做交易
return Math.max(0, Math.max(sell1, sell2));
}
public static void main(String[] args) {
System.out.println(new L0123().maxProfit(new int[]{3,3,5,0,0,3,1,4})); // 6
System.out.println(new L0123().maxProfit(new int[]{1,2,3,4,5})); // 4
System.out.println(new L0123().maxProfit(new int[]{7,6,4,3,1})); // 0
System.out.println(new L0123().maxProfit(new int[]{1})); // 0
System.out.println(new L0123().maxProfit(new int[]{2,1,4,5,2,9,7})); // 11
}
}
| zq2599/blog_demos | leetcode/src/practice/L0123.java |
1,021 | package practice;
/**
* @program: leetcode
* @description: 快排
* @author: [email protected]
* @create: 2022-06-30 22:33
**/
public class L0053 {
/*
public int maxSubArray(int[] nums) {
// 异常处理
if (nums.length<1) {
return 0;
}
// 以array=[-2,4,-3,-1]这样的数组为例,
// 从array[2]的视角去看,它只会关注连上array[1]之后,对array[1]这个位置的总和能不能带给它总和的增加,
// array[2]却不关注array[1]和array[0]到底连接了没有,
// 所以,假设dp[i]是i位置的最大总和,那么array[i+1]只关注dp[i]加上自己会不会更大,若会,就应该连上array[i],也就是dp[i+i]=dp[i]+array[i+1]
// 以array=[-2,4,-3,-1]为例,
// dp[0]=-2,
// dp[1]=4(不连前面),
// dp[2]=1(连前面),可见,array[1]和array[2]相连后,总和大于array[2]
// dp[3]=0(连前面),可见,尽管array[2]小鱼0,但是
int[] dp = new int[nums.length];
dp[0] = nums[0];
int max = dp[0];
for(int i=1;i<nums.length;i++) {
dp[i] = dp[i-1]<0 ? nums[i] : nums[i] + dp[i-1];
if(max<dp[i]) {
max = dp[i];
}
}
return max;
}
*/
public int maxSubArray(int[] nums) {
// 异常处理
if (nums.length<1) {
return 0;
}
// 以array=[-2,4,-3,-1]这样的数组为例,
// 从array[2]的视角去看,它只会关注连上array[1]之后,对array[1]这个位置的总和能不能带给它总和的增加,
// array[2]却不关注array[1]和array[0]到底连接了没有,
// 所以,假设dp[i]是i位置的最大总和,那么array[i+1]只关注dp[i]加上自己会不会更大,若会,就应该连上array[i],也就是dp[i+i]=dp[i]+array[i+1]
// 以array=[-2,4,-3,-1]为例,
// dp[0]=-2,
// dp[1]=4(不连前面),
// dp[2]=1(连前面),可见,array[1]和array[2]相连后,总和大于array[2]
// dp[3]=0(连前面),可见,尽管array[2]小鱼0,但是
int prevDp = nums[0];
int max = prevDp;
for(int i=1;i<nums.length;i++) {
// 其实括号左边是current的意思,不过这样写就把current变量省去了
prevDp = prevDp<0 ? nums[i] : nums[i] + prevDp;
// 找到更大的就更新了
if(max<prevDp) {
max = prevDp;
}
}
return max;
}
public static void main(String[] args) {
System.out.println(new L0053().maxSubArray(new int[] {5,4,-1,7,8}));
}
}
| zq2599/blog_demos | leetcode/src/practice/L0053.java |
1,024 | /**
* File: subset_sum_i.java
* Created Time: 2023-06-21
* Author: krahets ([email protected])
*/
package chapter_backtracking;
import java.util.*;
public class subset_sum_i {
/* 回溯算法:子集和 I */
static void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
// 子集和等于 target 时,记录解
if (target == 0) {
res.add(new ArrayList<>(state));
return;
}
// 遍历所有选择
// 剪枝二:从 start 开始遍历,避免生成重复子集
for (int i = start; i < choices.length; i++) {
// 剪枝一:若子集和超过 target ,则直接结束循环
// 这是因为数组已排序,后边元素更大,子集和一定超过 target
if (target - choices[i] < 0) {
break;
}
// 尝试:做出选择,更新 target, start
state.add(choices[i]);
// 进行下一轮选择
backtrack(state, target - choices[i], choices, i, res);
// 回退:撤销选择,恢复到之前的状态
state.remove(state.size() - 1);
}
}
/* 求解子集和 I */
static List<List<Integer>> subsetSumI(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // 状态(子集)
Arrays.sort(nums); // 对 nums 进行排序
int start = 0; // 遍历起始点
List<List<Integer>> res = new ArrayList<>(); // 结果列表(子集列表)
backtrack(state, target, nums, start, res);
return res;
}
public static void main(String[] args) {
int[] nums = { 3, 4, 5 };
int target = 9;
List<List<Integer>> res = subsetSumI(nums, target);
System.out.println("输入数组 nums = " + Arrays.toString(nums) + ", target = " + target);
System.out.println("所有和等于 " + target + " 的子集 res = " + res);
}
}
| krahets/hello-algo | codes/java/chapter_backtracking/subset_sum_i.java |
1,025 | package cn.hutool.db;
import cn.hutool.core.collection.ArrayIter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.handler.HandleHelper;
import cn.hutool.db.handler.RsHandler;
import cn.hutool.db.sql.NamedSql;
import cn.hutool.db.sql.SqlBuilder;
import cn.hutool.db.sql.SqlLog;
import cn.hutool.db.sql.SqlUtil;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Statement和PreparedStatement工具类
*
* @author looly
* @since 4.0.10
*/
public class StatementUtil {
/**
* 填充SQL的参数。
*
* @param ps PreparedStatement
* @param params SQL参数
* @return {@link PreparedStatement}
* @throws SQLException SQL执行异常
*/
public static PreparedStatement fillParams(PreparedStatement ps, Object... params) throws SQLException {
if (ArrayUtil.isEmpty(params)) {
return ps;
}
return fillParams(ps, new ArrayIter<>(params));
}
/**
* 填充SQL的参数。<br>
* 对于日期对象特殊处理:传入java.util.Date默认按照Timestamp处理
*
* @param ps PreparedStatement
* @param params SQL参数
* @return {@link PreparedStatement}
* @throws SQLException SQL执行异常
*/
public static PreparedStatement fillParams(PreparedStatement ps, Iterable<?> params) throws SQLException {
return fillParams(ps, params, null);
}
/**
* 填充SQL的参数。<br>
* 对于日期对象特殊处理:传入java.util.Date默认按照Timestamp处理
*
* @param ps PreparedStatement
* @param params SQL参数
* @param nullTypeCache null参数的类型缓存,避免循环中重复获取类型
* @return {@link PreparedStatement}
* @throws SQLException SQL执行异常
* @since 4.6.7
*/
public static PreparedStatement fillParams(PreparedStatement ps, Iterable<?> params, Map<Integer, Integer> nullTypeCache) throws SQLException {
if (null == params) {
return ps;// 无参数
}
int paramIndex = 1;//第一个参数从1计数
for (Object param : params) {
setParam(ps, paramIndex++, param, nullTypeCache);
}
return ps;
}
/**
* 创建{@link PreparedStatement}
*
* @param conn 数据库连接
* @param sqlBuilder {@link SqlBuilder}包括SQL语句和参数
* @return {@link PreparedStatement}
* @throws SQLException SQL异常
* @since 4.1.3
*/
public static PreparedStatement prepareStatement(Connection conn, SqlBuilder sqlBuilder) throws SQLException {
return prepareStatement(conn, sqlBuilder.build(), sqlBuilder.getParamValueArray());
}
/**
* 创建{@link PreparedStatement}
*
* @param conn 数据库连接
* @param sql SQL语句,使用"?"做为占位符
* @param params "?"对应参数列表
* @return {@link PreparedStatement}
* @throws SQLException SQL异常
* @since 3.2.3
*/
public static PreparedStatement prepareStatement(Connection conn, String sql, Collection<Object> params) throws SQLException {
return prepareStatement(conn, sql, params.toArray(new Object[0]));
}
/**
* 创建{@link PreparedStatement}
*
* @param conn 数据库连接
* @param sql SQL语句,使用"?"做为占位符
* @param params "?"对应参数列表
* @return {@link PreparedStatement}
* @throws SQLException SQL异常
* @since 3.2.3
*/
public static PreparedStatement prepareStatement(Connection conn, String sql, Object... params) throws SQLException {
return prepareStatement(GlobalDbConfig.returnGeneratedKey, conn, sql, params);
}
/**
* 创建{@link PreparedStatement}
*
* @param returnGeneratedKey 当为insert语句时,是否返回主键
* @param conn 数据库连接
* @param sql SQL语句,使用"?"做为占位符
* @param params "?"对应参数列表
* @return {@link PreparedStatement}
* @throws SQLException SQL异常
* @since 5.8.19
*/
public static PreparedStatement prepareStatement(boolean returnGeneratedKey, Connection conn, String sql, Object... params) throws SQLException {
Assert.notBlank(sql, "Sql String must be not blank!");
sql = sql.trim();
if(ArrayUtil.isNotEmpty(params) && 1 == params.length && params[0] instanceof Map){
// 检查参数是否为命名方式的参数
final NamedSql namedSql = new NamedSql(sql, Convert.toMap(String.class, Object.class, params[0]));
sql = namedSql.getSql();
params = namedSql.getParams();
}
SqlLog.INSTANCE.log(sql, ArrayUtil.isEmpty(params) ? null : params);
PreparedStatement ps;
if (returnGeneratedKey && StrUtil.startWithIgnoreCase(sql, "insert")) {
// 插入默认返回主键
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
} else {
ps = conn.prepareStatement(sql);
}
return fillParams(ps, params);
}
/**
* 创建批量操作的{@link PreparedStatement}
*
* @param conn 数据库连接
* @param sql SQL语句,使用"?"做为占位符
* @param paramsBatch "?"对应参数批次列表
* @return {@link PreparedStatement}
* @throws SQLException SQL异常
* @since 4.1.13
*/
public static PreparedStatement prepareStatementForBatch(Connection conn, String sql, Object[]... paramsBatch) throws SQLException {
return prepareStatementForBatch(conn, sql, new ArrayIter<>(paramsBatch));
}
/**
* 创建批量操作的{@link PreparedStatement}
*
* @param conn 数据库连接
* @param sql SQL语句,使用"?"做为占位符
* @param paramsBatch "?"对应参数批次列表
* @return {@link PreparedStatement}
* @throws SQLException SQL异常
* @since 4.1.13
*/
public static PreparedStatement prepareStatementForBatch(Connection conn, String sql, Iterable<Object[]> paramsBatch) throws SQLException {
Assert.notBlank(sql, "Sql String must be not blank!");
sql = sql.trim();
SqlLog.INSTANCE.log(sql, paramsBatch);
PreparedStatement ps = conn.prepareStatement(sql);
final Map<Integer, Integer> nullTypeMap = new HashMap<>();
for (Object[] params : paramsBatch) {
fillParams(ps, new ArrayIter<>(params), nullTypeMap);
ps.addBatch();
}
return ps;
}
/**
* 创建批量操作的{@link PreparedStatement}
*
* @param conn 数据库连接
* @param sql SQL语句,使用"?"做为占位符
* @param fields 字段列表,用于获取对应值
* @param entities "?"对应参数批次列表
* @return {@link PreparedStatement}
* @throws SQLException SQL异常
* @since 4.6.7
*/
public static PreparedStatement prepareStatementForBatch(Connection conn, String sql, Iterable<String> fields, Entity... entities) throws SQLException {
Assert.notBlank(sql, "Sql String must be not blank!");
sql = sql.trim();
SqlLog.INSTANCE.logForBatch(sql);
PreparedStatement ps = conn.prepareStatement(sql);
//null参数的类型缓存,避免循环中重复获取类型
final Map<Integer, Integer> nullTypeMap = new HashMap<>();
for (Entity entity : entities) {
fillParams(ps, CollUtil.valuesOfKeys(entity, fields), nullTypeMap);
ps.addBatch();
}
return ps;
}
/**
* 创建{@link CallableStatement}
*
* @param conn 数据库连接
* @param sql SQL语句,使用"?"做为占位符
* @param params "?"对应参数列表
* @return {@link CallableStatement}
* @throws SQLException SQL异常
* @since 4.1.13
*/
public static CallableStatement prepareCall(Connection conn, String sql, Object... params) throws SQLException {
Assert.notBlank(sql, "Sql String must be not blank!");
sql = sql.trim();
SqlLog.INSTANCE.log(sql, params);
final CallableStatement call = conn.prepareCall(sql);
fillParams(call, params);
return call;
}
/**
* 获得自增键的值<br>
* 此方法对于Oracle无效(返回null)
*
* @param ps PreparedStatement
* @return 自增键的值,不存在返回null
* @throws SQLException SQL执行异常
*/
public static Long getGeneratedKeyOfLong(Statement ps) throws SQLException {
return getGeneratedKeys(ps, (rs)->{
Long generatedKey = null;
if (rs != null && rs.next()) {
try {
generatedKey = rs.getLong(1);
} catch (SQLException e) {
// 自增主键不为数字或者为Oracle的rowid,跳过
}
}
return generatedKey;
});
}
/**
* 获得所有主键
*
* @param ps PreparedStatement
* @return 所有主键
* @throws SQLException SQL执行异常
*/
public static List<Object> getGeneratedKeys(Statement ps) throws SQLException {
return getGeneratedKeys(ps, HandleHelper::handleRowToList);
}
/**
* 获取主键,并使用{@link RsHandler} 处理后返回
* @param statement {@link Statement}
* @param rsHandler 主键结果集处理器
* @param <T> 自定义主键类型
* @return 主键
* @throws SQLException SQL执行异常
* @since 5.5.3
*/
public static <T> T getGeneratedKeys(Statement statement, RsHandler<T> rsHandler) throws SQLException {
try (final ResultSet rs = statement.getGeneratedKeys()) {
return rsHandler.handle(rs);
}
}
/**
* 获取null字段对应位置的数据类型<br>
* 有些数据库对于null字段必须指定类型,否则会插入报错,此方法用于获取其类型,如果获取失败,使用默认的{@link Types#VARCHAR}
*
* @param ps {@link Statement}
* @param paramIndex 参数位置,第一位从1开始
* @return 数据类型,默认{@link Types#VARCHAR}
* @since 4.6.7
*/
public static int getTypeOfNull(PreparedStatement ps, int paramIndex) {
int sqlType = Types.VARCHAR;
final ParameterMetaData pmd;
try {
pmd = ps.getParameterMetaData();
sqlType = pmd.getParameterType(paramIndex);
} catch (SQLException ignore) {
// ignore
// log.warn("Null param of index [{}] type get failed, by: {}", paramIndex, e.getMessage());
}
return sqlType;
}
/**
* 为{@link PreparedStatement} 设置单个参数
*
* @param ps {@link PreparedStatement}
* @param paramIndex 参数位置,从1开始
* @param param 参数
* @throws SQLException SQL异常
* @since 4.6.7
*/
public static void setParam(PreparedStatement ps, int paramIndex, Object param) throws SQLException {
setParam(ps, paramIndex, param, null);
}
//--------------------------------------------------------------------------------------------- Private method start
/**
* 为{@link PreparedStatement} 设置单个参数
*
* @param ps {@link PreparedStatement}
* @param paramIndex 参数位置,从1开始
* @param param 参数,不能为{@code null}
* @param nullTypeCache 用于缓存参数为null位置的类型,避免重复获取
* @throws SQLException SQL异常
* @since 4.6.7
*/
private static void setParam(PreparedStatement ps, int paramIndex, Object param, Map<Integer, Integer> nullTypeCache) throws SQLException {
if (null == param) {
Integer type = (null == nullTypeCache) ? null : nullTypeCache.get(paramIndex);
if (null == type) {
type = getTypeOfNull(ps, paramIndex);
if (null != nullTypeCache) {
nullTypeCache.put(paramIndex, type);
}
}
ps.setNull(paramIndex, type);
}
// 日期特殊处理,默认按照时间戳传入,避免毫秒丢失
if (param instanceof java.util.Date) {
if (param instanceof java.sql.Date) {
ps.setDate(paramIndex, (java.sql.Date) param);
} else if (param instanceof java.sql.Time) {
ps.setTime(paramIndex, (java.sql.Time) param);
} else {
ps.setTimestamp(paramIndex, SqlUtil.toSqlTimestamp((java.util.Date) param));
}
return;
}
// 针对大数字类型的特殊处理
if (param instanceof Number) {
if (param instanceof BigDecimal) {
// BigDecimal的转换交给JDBC驱动处理
ps.setBigDecimal(paramIndex, (BigDecimal) param);
return;
}
if (param instanceof BigInteger) {
// BigInteger转为BigDecimal
ps.setBigDecimal(paramIndex, new BigDecimal((BigInteger) param));
return;
}
// 忽略其它数字类型,按照默认类型传入
}
// 其它参数类型
ps.setObject(paramIndex, param);
}
//--------------------------------------------------------------------------------------------- Private method end
}
| dromara/hutool | hutool-db/src/main/java/cn/hutool/db/StatementUtil.java |
1,026 | package org.ansj.dic;
import org.ansj.app.crf.SplitWord;
import org.ansj.domain.Nature;
import org.ansj.domain.NewWord;
import org.ansj.domain.TermNatures;
import org.ansj.recognition.impl.NatureRecognition;
import org.ansj.util.Graph;
import org.nlpcn.commons.lang.tire.domain.Forest;
import org.nlpcn.commons.lang.tire.domain.SmartForest;
import org.nlpcn.commons.lang.util.CollectionUtil;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
/**
* 新词发现,这是个线程安全的.所以可以多个对象公用一个
*
* @author ansj
*
*/
public class LearnTool {
private SplitWord splitWord = null;
/**
* 是否开启学习机
*/
public boolean isAsianName = true;
public boolean isForeignName = true;
/**
* 告诉大家你学习了多少个词了
*/
public int count;
/**
* 新词发现的结果集.可以序列化到硬盘.然后可以当做训练集来做.
*/
private final SmartForest<NewWord> sf = new SmartForest<NewWord>();
/**
* 学习新词排除用户自定义词典那中的词语
*/
private Forest[] forests;
/**
* 公司名称学习.
*
* @param graph
*/
public void learn(Graph graph, SplitWord splitWord, Forest... forests) {
this.splitWord = splitWord;
this.forests = forests;
}
// 批量将新词加入到词典中
private void addListToTerm(List<NewWord> newWords) {
if (newWords.size() == 0) {
return;
}
for (NewWord newWord : newWords) {
TermNatures termNatures = new NatureRecognition(forests).getTermNatures(newWord.getName());
if (termNatures == TermNatures.NULL) {
addTerm(newWord);
}
}
}
/**
* 增加一个新词到树中
*
* @param newWord
*/
public void addTerm(NewWord newWord) {
NewWord temp = null;
SmartForest<NewWord> smartForest = null;
if ((smartForest = sf.getBranch(newWord.getName())) != null && smartForest.getParam() != null) {
temp = smartForest.getParam();
temp.update(newWord.getNature(), newWord.getAllFreq());
} else {
count++;
if (splitWord == null) {
newWord.setScore(-1);
} else {
newWord.setScore(-splitWord.cohesion(newWord.getName()));
}
synchronized (sf) {
sf.add(newWord.getName(), newWord);
}
}
}
public SmartForest<NewWord> getForest() {
return this.sf;
}
/**
* 返回学习到的新词.
*
* @param num 返回数目.0为全部返回
* @return
*/
public List<Entry<String, Double>> getTopTree(int num) {
return getTopTree(num, null);
}
public List<Entry<String, Double>> getTopTree(int num, Nature nature) {
if (sf.branches == null) {
return Collections.emptyList();
}
HashMap<String, Double> hm = new HashMap<String, Double>();
for (int i = 0; i < sf.branches.length; i++) {
valueResult(sf.branches[i], hm, nature);
}
List<Entry<String, Double>> sortMapByValue = CollectionUtil.sortMapByValue(hm, -1);
if (num == 0) {
return sortMapByValue;
} else {
num = Math.min(num, sortMapByValue.size());
return sortMapByValue.subList(0, num);
}
}
private void valueResult(SmartForest<NewWord> smartForest, HashMap<String, Double> hm, Nature nature) {
if (smartForest == null || smartForest.branches == null) {
return;
}
for (int i = 0; i < smartForest.branches.length; i++) {
NewWord param = smartForest.branches[i].getParam();
if (smartForest.branches[i].getStatus() == 3) {
if (param.isActive() && (nature == null || param.getNature().equals(nature))) {
hm.put(param.getName(), param.getScore());
}
} else if (smartForest.branches[i].getStatus() == 2) {
if (param.isActive() && (nature == null || param.getNature().equals(nature))) {
hm.put(param.getName(), param.getScore());
}
valueResult(smartForest.branches[i], hm, nature);
} else {
valueResult(smartForest.branches[i], hm, nature);
}
}
}
/**
* 尝试激活,新词
*
* @param name
*/
public void active(String name) {
SmartForest<NewWord> branch = sf.getBranch(name);
if (branch != null && branch.getParam() != null) {
branch.getParam().setActive(true);
}
}
}
| NLPchina/ansj_seg | src/main/java/org/ansj/dic/LearnTool.java |
1,030 | /*
* Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.sqlengine.mpp;
import io.mycat.MycatServer;
import io.mycat.memory.MyCatMemory;
import io.mycat.memory.unsafe.KVIterator;
import io.mycat.memory.unsafe.map.UnsafeFixedWidthAggregationMap;
import io.mycat.memory.unsafe.memory.mm.DataNodeMemoryManager;
import io.mycat.memory.unsafe.memory.mm.MemoryManager;
import io.mycat.memory.unsafe.row.BufferHolder;
import io.mycat.memory.unsafe.row.StructType;
import io.mycat.memory.unsafe.row.UnsafeRow;
import io.mycat.memory.unsafe.row.UnsafeRowWriter;
import io.mycat.memory.unsafe.utils.BytesTools;
import io.mycat.memory.unsafe.utils.MycatPropertyConf;
import io.mycat.memory.unsafe.utils.sort.UnsafeExternalRowSorter;
import io.mycat.util.ByteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by zagnix on 2016/6/26.
*
* implement group function select a,count(*),sum(*) from A group by a
*
*/
public class UnsafeRowGrouper {
private static final Logger logger = LoggerFactory.getLogger(UnsafeRowGrouper.class);
private UnsafeFixedWidthAggregationMap aggregationMap = null;
private final Map<String, ColMeta> columToIndx;
private final MergeCol[] mergCols;
private String[] sortColumnsByIndex = null;
private final String[] columns;
private boolean isMergAvg=false;
private HavingCols havingCols;
private UnsafeRow groupKey = null;
private UnsafeRow valueKey = null;
private BufferHolder bufferHolder = null;
private UnsafeRowWriter unsafeRowWriter = null;
private final int groupKeyfieldCount;
private final int valuefieldCount;
private StructType groupKeySchema ;
private StructType aggBufferSchema;
private UnsafeRow emptyAggregationBuffer;
private final MyCatMemory myCatMemory;
private final MemoryManager memoryManager;
private final MycatPropertyConf conf;
public UnsafeRowGrouper(Map<String,ColMeta> columToIndx,String[] columns, MergeCol[] mergCols, HavingCols havingCols) {
super();
assert columns!=null;
assert columToIndx!=null;
assert mergCols !=null;
this.columToIndx = columToIndx;
this.columns = columns;
this.mergCols = mergCols;
this.havingCols = havingCols;
this.sortColumnsByIndex = columns !=null ? toSortColumnsByIndex(columns,columToIndx):null;
this.groupKeyfieldCount = columns != null?columns.length:0;
this.valuefieldCount = columToIndx != null?columToIndx.size():0;
this.myCatMemory = MycatServer.getInstance().getMyCatMemory();
this.memoryManager = myCatMemory.getResultMergeMemoryManager();
this.conf = myCatMemory.getConf();
logger.debug("columToIndx :" + (columToIndx != null ? columToIndx.toString():"null"));
initGroupKey();
initEmptyValueKey();
DataNodeMemoryManager dataNodeMemoryManager =
new DataNodeMemoryManager(memoryManager,Thread.currentThread().getId());
aggregationMap = new UnsafeFixedWidthAggregationMap(
emptyAggregationBuffer,
aggBufferSchema,
groupKeySchema,
dataNodeMemoryManager,
1024,
conf.getSizeAsBytes("mycat.buffer.pageSize", "32k"),
false);
}
private String[] toSortColumnsByIndex(String[] columns, Map<String, ColMeta> columToIndx) {
Map<String,Integer> map = new HashMap<String,Integer>();
ColMeta curColMeta;
for (int i = 0; i < columns.length; i++) {
curColMeta = columToIndx.get(columns[i].toUpperCase());
if (curColMeta == null) {
throw new IllegalArgumentException(
"all columns in group by clause should be in the selected column list.!"
+ columns[i]);
}
map.put(columns[i],curColMeta.colIndex);
}
String[] sortColumnsByIndex = new String[map.size()];
List<Map.Entry<String, Integer>> entryList = new ArrayList<
Map.Entry<String, Integer>>(
map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
Map.Entry<String, Integer> tmpEntry = null;
int index = 0;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortColumnsByIndex[index++] = tmpEntry.getKey();
}
return sortColumnsByIndex;
}
private void initGroupKey(){
/**
* 构造groupKey
*/
Map<String,ColMeta> groupcolMetaMap = new HashMap<String,ColMeta>(this.groupKeyfieldCount);
groupKey = new UnsafeRow(this.groupKeyfieldCount);
bufferHolder = new BufferHolder(groupKey,0);
unsafeRowWriter = new UnsafeRowWriter(bufferHolder,this.groupKeyfieldCount);
bufferHolder.reset();
ColMeta curColMeta = null;
for (int i = 0; i < this.groupKeyfieldCount; i++) {
curColMeta = this.columToIndx.get(sortColumnsByIndex[i].toUpperCase());
groupcolMetaMap.put(sortColumnsByIndex[i],curColMeta);
switch (curColMeta.colType) {
case ColMeta.COL_TYPE_BIT:
groupKey.setByte(i, (byte) 0);
break;
case ColMeta.COL_TYPE_INT:
case ColMeta.COL_TYPE_INT24:
case ColMeta.COL_TYPE_LONG:
groupKey.setInt(i, 0);
break;
case ColMeta.COL_TYPE_SHORT:
groupKey.setShort(i, (short) 0);
break;
case ColMeta.COL_TYPE_FLOAT:
groupKey.setFloat(i, 0);
break;
case ColMeta.COL_TYPE_DOUBLE:
groupKey.setDouble(i, 0);
break;
case ColMeta.COL_TYPE_NEWDECIMAL:
// groupKey.setDouble(i, 0);
unsafeRowWriter.write(i, new BigDecimal(0L));
break;
case ColMeta.COL_TYPE_LONGLONG:
groupKey.setLong(i, 0);
break;
default:
unsafeRowWriter.write(i, "init".getBytes());
break;
}
}
groupKey.setTotalSize(bufferHolder.totalSize());
groupKeySchema = new StructType(groupcolMetaMap,this.groupKeyfieldCount);
groupKeySchema.setOrderCols(null);
}
private void initEmptyValueKey(){
/**
* 构造valuerow
*/
emptyAggregationBuffer = new UnsafeRow(this.valuefieldCount);
bufferHolder = new BufferHolder(emptyAggregationBuffer,0);
unsafeRowWriter = new UnsafeRowWriter(bufferHolder,this.valuefieldCount);
bufferHolder.reset();
ColMeta curColMeta = null;
for (Map.Entry<String, ColMeta> fieldEntry : columToIndx.entrySet()) {
curColMeta = fieldEntry.getValue();
switch (curColMeta.colType) {
case ColMeta.COL_TYPE_BIT:
emptyAggregationBuffer.setByte(curColMeta.colIndex, (byte) 0);
break;
case ColMeta.COL_TYPE_INT:
case ColMeta.COL_TYPE_INT24:
case ColMeta.COL_TYPE_LONG:
emptyAggregationBuffer.setInt(curColMeta.colIndex, 0);
break;
case ColMeta.COL_TYPE_SHORT:
emptyAggregationBuffer.setShort(curColMeta.colIndex, (short) 0);
break;
case ColMeta.COL_TYPE_LONGLONG:
emptyAggregationBuffer.setLong(curColMeta.colIndex, 0);
break;
case ColMeta.COL_TYPE_FLOAT:
emptyAggregationBuffer.setFloat(curColMeta.colIndex, 0);
break;
case ColMeta.COL_TYPE_DOUBLE:
emptyAggregationBuffer.setDouble(curColMeta.colIndex, 0);
break;
case ColMeta.COL_TYPE_NEWDECIMAL:
// emptyAggregationBuffer.setDouble(curColMeta.colIndex, 0);
unsafeRowWriter.write(curColMeta.colIndex, new BigDecimal(0L));
break;
default:
unsafeRowWriter.write(curColMeta.colIndex, "init".getBytes());
break;
}
}
emptyAggregationBuffer.setTotalSize(bufferHolder.totalSize());
aggBufferSchema = new StructType(columToIndx,this.valuefieldCount);
aggBufferSchema.setOrderCols(null);
}
public Iterator<UnsafeRow> getResult(@Nonnull UnsafeExternalRowSorter sorter) throws IOException {
KVIterator<UnsafeRow,UnsafeRow> iter = aggregationMap.iterator();
/**
* 求平均值
*/
if (isMergeAvg() && !isMergAvg){
try {
while (iter.next()){
mergAvg(iter.getValue());
}
} catch (IOException e) {
logger.error(e.getMessage());
}
isMergAvg = true;
processAvgFieldPrecision();
}
/**
* group having
*/
if (havingCols !=null){
filterHaving(sorter);
}else{
/**
* KVIterator<K,V> ==>Iterator<V>
*/
insertValue(sorter);
}
return sorter.sort();
}
/**
* 处理AVG列精度
*/
private void processAvgFieldPrecision() {
for (MergeCol mergCol : mergCols) {
if (mergCol.mergeType != MergeCol.MERGE_AVG) {
continue ;
}
for (String key : columToIndx.keySet()) {
ColMeta colMeta = columToIndx.get(key);
// AVG列的小数点精度默认取SUM小数点精度, 计算和返回的小数点精度应该扩展4
if (colMeta.colIndex == mergCol.colMeta.avgSumIndex) {
colMeta.decimals += 4;
break ;
}
}
}
}
/**
* 判断列是否为AVG列
* @param columnName
* @return
*/
private boolean isAvgField(String columnName) {
Pattern pattern = Pattern.compile("AVG([1-9]\\d*|0)SUM");
Matcher matcher = pattern.matcher(columnName);
return matcher.find();
}
public UnsafeRow getAllBinaryRow(UnsafeRow row) throws UnsupportedEncodingException {
UnsafeRow value = new UnsafeRow( this.valuefieldCount);
bufferHolder = new BufferHolder(value,0);
unsafeRowWriter = new UnsafeRowWriter(bufferHolder, this.valuefieldCount);
bufferHolder.reset();
ColMeta curColMeta = null;
for (Map.Entry<String, ColMeta> fieldEntry : columToIndx.entrySet()) {
curColMeta = fieldEntry.getValue();
if (!row.isNullAt(curColMeta.colIndex)) {
switch (curColMeta.colType) {
case ColMeta.COL_TYPE_BIT:
unsafeRowWriter.write(curColMeta.colIndex, row.getByte(curColMeta.colIndex));
break;
case ColMeta.COL_TYPE_INT:
case ColMeta.COL_TYPE_LONG:
case ColMeta.COL_TYPE_INT24:
unsafeRowWriter.write(curColMeta.colIndex,
BytesTools.int2Bytes(row.getInt(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_SHORT:
unsafeRowWriter.write(curColMeta.colIndex,
BytesTools.short2Bytes(row.getShort(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_LONGLONG:
unsafeRowWriter.write(curColMeta.colIndex,
BytesTools.long2Bytes(row.getLong(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_FLOAT:
unsafeRowWriter.write(curColMeta.colIndex,
BytesTools.float2Bytes(row.getFloat(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_DOUBLE:
unsafeRowWriter.write(curColMeta.colIndex,
BytesTools.double2Bytes(row.getDouble(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_NEWDECIMAL:
int scale = curColMeta.decimals;
BigDecimal decimalVal = row.getDecimal(curColMeta.colIndex, scale);
unsafeRowWriter.write(curColMeta.colIndex, decimalVal.toString().getBytes());
break;
default:
unsafeRowWriter.write(curColMeta.colIndex,
row.getBinary(curColMeta.colIndex));
break;
}
}else {
unsafeRowWriter.setNullAt(curColMeta.colIndex);
}
}
value.setTotalSize(bufferHolder.totalSize());
return value;
}
private void insertValue(@Nonnull UnsafeExternalRowSorter sorter){
KVIterator<UnsafeRow,UnsafeRow> it = aggregationMap.iterator();
try {
while (it.next()){
UnsafeRow row = getAllBinaryRow(it.getValue());
sorter.insertRow(row);
}
} catch (IOException e) {
logger.error("group insertValue err: " + e.getMessage());
free();
}
}
private void filterHaving(@Nonnull UnsafeExternalRowSorter sorter){
if (havingCols.getColMeta() == null || aggregationMap == null) {
return;
}
KVIterator<UnsafeRow,UnsafeRow> it = aggregationMap.iterator();
byte[] right = havingCols.getRight().getBytes(StandardCharsets.UTF_8);
int index = havingCols.getColMeta().getColIndex();
try {
while (it.next()){
UnsafeRow row = getAllBinaryRow(it.getValue());
switch (havingCols.getOperator()) {
case "=":
if (eq(row.getBinary(index),right)) {
sorter.insertRow(row);
}
break;
case ">":
if (gt(row.getBinary(index),right)) {
sorter.insertRow(row);
}
break;
case "<":
if (lt(row.getBinary(index),right)) {
sorter.insertRow(row);
}
break;
case ">=":
if (gt(row.getBinary(index),right) || eq(row.getBinary(index),right)) {
sorter.insertRow(row);
}
break;
case "<=":
if (lt(row.getBinary(index),right) || eq(row.getBinary(index),right)) {
sorter.insertRow(row);
}
break;
case "!=":
if (neq(row.getBinary(index),right)) {
sorter.insertRow(row);
}
break;
}
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
private boolean lt(byte[] l, byte[] r) {
return -1 >= ByteUtil.compareNumberByte(l, r);
}
private boolean gt(byte[] l, byte[] r) {
return 1 <= ByteUtil.compareNumberByte(l, r);
}
private boolean eq(byte[] l, byte[] r) {
return 0 == ByteUtil.compareNumberByte(l, r);
}
private boolean neq(byte[] l, byte[] r) {
return 0 != ByteUtil.compareNumberByte(l, r);
}
/**
* 构造groupKey
*/
private UnsafeRow getGroupKey(UnsafeRow row) throws UnsupportedEncodingException {
UnsafeRow key = null;
if(this.sortColumnsByIndex == null){
/**
* 针对没有group by关键字
* select count(*) from table;
*/
key = new UnsafeRow(this.groupKeyfieldCount+1);
bufferHolder = new BufferHolder(key,0);
unsafeRowWriter = new UnsafeRowWriter(bufferHolder,this.groupKeyfieldCount+1);
bufferHolder.reset();
unsafeRowWriter.write(0,"same".getBytes());
key.setTotalSize(bufferHolder.totalSize());
return key;
}
key = new UnsafeRow(this.groupKeyfieldCount);
bufferHolder = new BufferHolder(key,0);
unsafeRowWriter = new UnsafeRowWriter(bufferHolder,this.groupKeyfieldCount);
bufferHolder.reset();
ColMeta curColMeta = null;
for (int i = 0; i < this.groupKeyfieldCount;i++) {
curColMeta = this.columToIndx.get(sortColumnsByIndex[i].toUpperCase());
if(!row.isNullAt(curColMeta.colIndex)){
switch(curColMeta.colType){
case ColMeta.COL_TYPE_BIT:
key.setByte(i,row.getByte(curColMeta.colIndex));
case ColMeta.COL_TYPE_INT:
case ColMeta.COL_TYPE_LONG:
case ColMeta.COL_TYPE_INT24:
key.setInt(i,
BytesTools.getInt(row.getBinary(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_SHORT:
key.setShort(i,
BytesTools.getShort(row.getBinary(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_FLOAT:
key.setFloat(i,
BytesTools.getFloat(row.getBinary(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_DOUBLE:
key.setDouble(i,
BytesTools.getDouble(row.getBinary(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_NEWDECIMAL:
// key.setDouble(i,
// BytesTools.getDouble(row.getBinary(curColMeta.colIndex)));
unsafeRowWriter.write(i,
new BigDecimal(new String(row.getBinary(curColMeta.colIndex))));
break;
case ColMeta.COL_TYPE_LONGLONG:
key.setLong(i,
BytesTools.getLong(row.getBinary(curColMeta.colIndex)));
break;
default:
unsafeRowWriter.write(i,
row.getBinary(curColMeta.colIndex));
break;
}
}else {
key.setNullAt(i);
}
}
key.setTotalSize(bufferHolder.totalSize());
return key;
}
/**
* 构造value
*/
private UnsafeRow getValue(UnsafeRow row) throws UnsupportedEncodingException {
UnsafeRow value = new UnsafeRow(this.valuefieldCount);
bufferHolder = new BufferHolder(value,0);
unsafeRowWriter = new UnsafeRowWriter(bufferHolder,this.valuefieldCount);
bufferHolder.reset();
ColMeta curColMeta = null;
for (Map.Entry<String, ColMeta> fieldEntry : columToIndx.entrySet()) {
curColMeta = fieldEntry.getValue();
if(!row.isNullAt(curColMeta.colIndex)) {
switch (curColMeta.colType) {
case ColMeta.COL_TYPE_BIT:
value.setByte(curColMeta.colIndex, row.getByte(curColMeta.colIndex));
break;
case ColMeta.COL_TYPE_INT:
case ColMeta.COL_TYPE_LONG:
case ColMeta.COL_TYPE_INT24:
value.setInt(curColMeta.colIndex,
BytesTools.getInt(row.getBinary(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_SHORT:
value.setShort(curColMeta.colIndex,
BytesTools.getShort(row.getBinary(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_LONGLONG:
value.setLong(curColMeta.colIndex,
BytesTools.getLong(row.getBinary(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_FLOAT:
value.setFloat(curColMeta.colIndex,
BytesTools.getFloat(row.getBinary(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_DOUBLE:
value.setDouble(curColMeta.colIndex, BytesTools.getDouble(row.getBinary(curColMeta.colIndex)));
break;
case ColMeta.COL_TYPE_NEWDECIMAL:
// value.setDouble(curColMeta.colIndex, BytesTools.getDouble(row.getBinary(curColMeta.colIndex)));
unsafeRowWriter.write(curColMeta.colIndex,
new BigDecimal(new String(row.getBinary(curColMeta.colIndex))));
break;
default:
unsafeRowWriter.write(curColMeta.colIndex,
row.getBinary(curColMeta.colIndex));
break;
}
}else {
switch(curColMeta.colType) {
case ColMeta.COL_TYPE_NEWDECIMAL:
BigDecimal nullDecimal = null;
unsafeRowWriter.write(curColMeta.colIndex, nullDecimal);
break;
default:
value.setNullAt(curColMeta.colIndex);
break;
}
}
}
value.setTotalSize(bufferHolder.totalSize());
return value;
}
public void addRow(UnsafeRow rowDataPkg) throws UnsupportedEncodingException {
UnsafeRow key = getGroupKey(rowDataPkg);
UnsafeRow value = getValue(rowDataPkg);
if(aggregationMap.find(key)){
UnsafeRow rs = aggregationMap.getAggregationBuffer(key);
aggregateRow(key,rs,value);
}else {
aggregationMap.put(key,value);
}
return;
}
private boolean isMergeAvg(){
if (mergCols == null) {
return false;
}
for (MergeCol merg : mergCols) {
if(merg.mergeType == MergeCol.MERGE_AVG) {
return true;
}
}
return false;
}
private void aggregateRow(UnsafeRow key,UnsafeRow toRow, UnsafeRow newRow) throws UnsupportedEncodingException {
if (mergCols == null) {
return;
}
for (MergeCol merg : mergCols) {
if(merg.mergeType != MergeCol.MERGE_AVG && merg.colMeta !=null) {
byte[] result = null;
byte[] left = null;
byte[] right = null;
int type = merg.colMeta.colType;
int index = merg.colMeta.colIndex;
switch(type){
case ColMeta.COL_TYPE_INT:
case ColMeta.COL_TYPE_LONG:
case ColMeta.COL_TYPE_INT24:
if (!toRow.isNullAt(index)) {
left = BytesTools.int2Bytes(toRow.getInt(index));
}
if (!newRow.isNullAt(index)) {
right = BytesTools.int2Bytes(newRow.getInt(index));
}
break;
case ColMeta.COL_TYPE_SHORT:
left = BytesTools.short2Bytes(toRow.getShort(index));
right =BytesTools.short2Bytes(newRow.getShort(index));
break;
case ColMeta.COL_TYPE_LONGLONG:
left = BytesTools.long2Bytes(toRow.getLong(index));
right = BytesTools.long2Bytes(newRow.getLong(index));
break;
case ColMeta.COL_TYPE_FLOAT:
left = BytesTools.float2Bytes(toRow.getFloat(index));
right = BytesTools.float2Bytes(newRow.getFloat(index));
break;
case ColMeta.COL_TYPE_DOUBLE:
left = BytesTools.double2Bytes(toRow.getDouble(index));
right = BytesTools.double2Bytes(newRow.getDouble(index));
break;
case ColMeta.COL_TYPE_NEWDECIMAL:
// left = BytesTools.double2Bytes(toRow.getDouble(index));
// right = BytesTools.double2Bytes(newRow.getDouble(index));
int scale = merg.colMeta.decimals;
BigDecimal decimalLeft = toRow.getDecimal(index, scale);
BigDecimal decimalRight = newRow.getDecimal(index, scale);
left = decimalLeft == null ? null : decimalLeft.toString().getBytes();
right = decimalRight == null ? null : decimalRight.toString().getBytes();
break;
case ColMeta.COL_TYPE_DATE:
case ColMeta.COL_TYPE_TIMSTAMP:
case ColMeta.COL_TYPE_TIME:
case ColMeta.COL_TYPE_YEAR:
case ColMeta.COL_TYPE_DATETIME:
case ColMeta.COL_TYPE_NEWDATE:
case ColMeta.COL_TYPE_BIT:
case ColMeta.COL_TYPE_VAR_STRING:
case ColMeta.COL_TYPE_STRING:
case ColMeta.COL_TYPE_ENUM:
case ColMeta.COL_TYPE_SET:
left = toRow.getBinary(index);
right = newRow.getBinary(index);
break;
default:
break;
}
result = mertFields(left,right,type,merg.mergeType);
if (result != null) {
switch(type){
case ColMeta.COL_TYPE_BIT:
toRow.setByte(index,result[0]);
case ColMeta.COL_TYPE_INT:
case ColMeta.COL_TYPE_LONG:
case ColMeta.COL_TYPE_INT24:
toRow.setInt(index,BytesTools.getInt(result));
break;
case ColMeta.COL_TYPE_SHORT:
toRow.setShort(index,BytesTools.getShort(result));
break;
case ColMeta.COL_TYPE_LONGLONG:
toRow.setLong(index,BytesTools.getLong(result));
break;
case ColMeta.COL_TYPE_FLOAT:
toRow.setFloat(index,BytesTools.getFloat(result));
break;
case ColMeta.COL_TYPE_DOUBLE:
toRow.setDouble(index,BytesTools.getDouble(result));
break;
case ColMeta.COL_TYPE_NEWDECIMAL:
// toRow.setDouble(index,BytesTools.getDouble(result));
toRow.updateDecimal(index, new BigDecimal(new String(result)));
break;
/**
*TODO UnsafeFixedWidthAggregationMap 中存放
* UnsafeRow时,非数值类型的列不可更改其值,
* 为了统一处理聚合函数这块
* 做max或者min聚合时候,目前解决方法
* 先free原来 UnsafeFixedWidthAggregationMap对象。
* 然后重新创建一个UnsafeFixedWidthAggregationMap对象
* 然后存放最新的max或者min值作为下次比较。
**/
case ColMeta.COL_TYPE_DATE:
case ColMeta.COL_TYPE_TIMSTAMP:
case ColMeta.COL_TYPE_TIME:
case ColMeta.COL_TYPE_YEAR:
case ColMeta.COL_TYPE_DATETIME:
case ColMeta.COL_TYPE_NEWDATE:
case ColMeta.COL_TYPE_VAR_STRING:
case ColMeta.COL_TYPE_STRING:
case ColMeta.COL_TYPE_ENUM:
case ColMeta.COL_TYPE_SET:
aggregationMap.free();
DataNodeMemoryManager dataNodeMemoryManager =
new DataNodeMemoryManager(memoryManager,Thread.currentThread().getId());
aggregationMap = new UnsafeFixedWidthAggregationMap(
emptyAggregationBuffer,
aggBufferSchema,
groupKeySchema,
dataNodeMemoryManager,
1024,
conf.getSizeAsBytes("mycat.buffer.pageSize", "32k"),
false);
UnsafeRow unsafeRow = new UnsafeRow(toRow.numFields());
bufferHolder = new BufferHolder(unsafeRow, 0);
unsafeRowWriter = new UnsafeRowWriter(bufferHolder, toRow.numFields());
bufferHolder.reset();
for (int i = 0; i < toRow.numFields(); i++) {
if (i == index) {
unsafeRowWriter.write(i,result);
} else if (!toRow.isNullAt(i)) {
unsafeRowWriter.write(i, toRow.getBinary(i));
} else if (toRow.isNullAt(i)){
unsafeRow.setNullAt(i);
}
}
unsafeRow.setTotalSize(bufferHolder.totalSize());
aggregationMap.put(key, unsafeRow);
toRow = unsafeRow;
break;
default:
break;
}
}
}
}
}
private void mergAvg(UnsafeRow toRow) throws UnsupportedEncodingException {
if (mergCols == null) {
return;
}
for (MergeCol merg : mergCols) {
if(merg.mergeType==MergeCol.MERGE_AVG) {
byte[] result = null;
byte[] avgSum = null;
byte[] avgCount = null;
int type = merg.colMeta.colType;
int avgSumIndex = merg.colMeta.avgSumIndex;
int avgCountIndex = merg.colMeta.avgCountIndex;
switch(type){
case ColMeta.COL_TYPE_BIT:
avgSum = BytesTools.toBytes(toRow.getByte(avgSumIndex));
avgCount = BytesTools.toBytes(toRow.getLong(avgCountIndex));
break;
case ColMeta.COL_TYPE_INT:
case ColMeta.COL_TYPE_LONG:
case ColMeta.COL_TYPE_INT24:
avgSum = BytesTools.int2Bytes(toRow.getInt(avgSumIndex));
avgCount = BytesTools.long2Bytes(toRow.getLong(avgCountIndex));
break;
case ColMeta.COL_TYPE_SHORT:
avgSum =BytesTools.short2Bytes(toRow.getShort(avgSumIndex));
avgCount = BytesTools.long2Bytes(toRow.getLong(avgCountIndex));
break;
case ColMeta.COL_TYPE_LONGLONG:
avgSum = BytesTools.long2Bytes(toRow.getLong(avgSumIndex));
avgCount = BytesTools.long2Bytes(toRow.getLong(avgCountIndex));
break;
case ColMeta.COL_TYPE_FLOAT:
avgSum = BytesTools.float2Bytes(toRow.getFloat(avgSumIndex));
avgCount = BytesTools.long2Bytes(toRow.getLong(avgCountIndex));
break;
case ColMeta.COL_TYPE_DOUBLE:
avgSum = BytesTools.double2Bytes(toRow.getDouble(avgSumIndex));
avgCount = BytesTools.long2Bytes(toRow.getLong(avgCountIndex));
break;
case ColMeta.COL_TYPE_NEWDECIMAL:
// avgSum = BytesTools.double2Bytes(toRow.getDouble(avgSumIndex));
// avgCount = BytesTools.long2Bytes(toRow.getLong(avgCountIndex));
int scale = merg.colMeta.decimals;
BigDecimal sumDecimal = toRow.getDecimal(avgSumIndex, scale);
avgSum = sumDecimal == null ? null : sumDecimal.toString().getBytes();
avgCount = BytesTools.long2Bytes(toRow.getLong(avgCountIndex));
break;
default:
break;
}
result = mertFields(avgSum,avgCount,merg.colMeta.colType,merg.mergeType);
if (result != null) {
switch(type){
case ColMeta.COL_TYPE_BIT:
toRow.setByte(avgSumIndex,result[0]);
break;
case ColMeta.COL_TYPE_INT:
case ColMeta.COL_TYPE_LONG:
case ColMeta.COL_TYPE_INT24:
toRow.setInt(avgSumIndex,BytesTools.getInt(result));
break;
case ColMeta.COL_TYPE_SHORT:
toRow.setShort(avgSumIndex,BytesTools.getShort(result));
break;
case ColMeta.COL_TYPE_LONGLONG:
toRow.setLong(avgSumIndex,BytesTools.getLong(result));
break;
case ColMeta.COL_TYPE_FLOAT:
toRow.setFloat(avgSumIndex,BytesTools.getFloat(result));
break;
case ColMeta.COL_TYPE_DOUBLE:
toRow.setDouble(avgSumIndex,ByteUtil.getDouble(result));
break;
case ColMeta.COL_TYPE_NEWDECIMAL:
// toRow.setDouble(avgSumIndex,ByteUtil.getDouble(result));
toRow.updateDecimal(avgSumIndex, new BigDecimal(new String(result)));
break;
default:
break;
}
}
}
}
}
private byte[] mertFields(byte[] bs, byte[] bs2, int colType, int mergeType) throws UnsupportedEncodingException {
if(bs2==null || bs2.length==0) {
return bs;
}else if(bs==null || bs.length==0) {
return bs2;
}
switch (mergeType) {
case MergeCol.MERGE_SUM:
if (colType == ColMeta.COL_TYPE_DOUBLE
|| colType == ColMeta.COL_TYPE_FLOAT){
double value = BytesTools.getDouble(bs) +
BytesTools.getDouble(bs2);
return BytesTools.double2Bytes(value);
} else if(colType == ColMeta.COL_TYPE_NEWDECIMAL
|| colType == ColMeta.COL_TYPE_DECIMAL) {
BigDecimal decimal = new BigDecimal(new String(bs));
decimal = decimal.add(new BigDecimal(new String(bs2)));
return decimal.toString().getBytes();
}
case MergeCol.MERGE_COUNT: {
long s1 = BytesTools.getLong(bs);
long s2 = BytesTools.getLong(bs2);
long total = s1 + s2;
return BytesTools.long2Bytes(total);
}
case MergeCol.MERGE_MAX: {
int compare = ByteUtil.compareNumberByte(bs,bs2);
return (compare > 0) ? bs : bs2;
}
case MergeCol.MERGE_MIN: {
int compare = ByteUtil.compareNumberByte(bs,bs2);
return (compare > 0) ? bs2 : bs;
}
case MergeCol.MERGE_AVG: {
/**
* 元素总个数
*/
long count = BytesTools.getLong(bs2);
if (colType == ColMeta.COL_TYPE_DOUBLE
|| colType == ColMeta.COL_TYPE_FLOAT) {
/**
* 数值总和
*/
double sum = BytesTools.getDouble(bs);
double value = sum / count;
return BytesTools.double2Bytes(value);
} else if(colType == ColMeta.COL_TYPE_NEWDECIMAL
|| colType == ColMeta.COL_TYPE_DECIMAL){
BigDecimal sum = new BigDecimal(new String(bs));
// AVG计算时候小数点精度扩展4, 并且四舍五入
BigDecimal avg = sum.divide(new BigDecimal(count), sum.scale() + 4, RoundingMode.HALF_UP);
return avg.toString().getBytes();
}
}
default:
return null;
}
}
public void free(){
if(aggregationMap != null)
aggregationMap.free();
}
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/sqlengine/mpp/UnsafeRowGrouper.java |
1,032 | package com.alibaba.otter.canal.parse.inbound.mysql;
import static com.alibaba.otter.canal.parse.driver.mysql.utils.GtidUtil.parseGtidSet;
import static com.alibaba.otter.canal.parse.inbound.mysql.dbsync.DirectLogFetcher.MASTER_HEARTBEAT_PERIOD_SECONDS;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.otter.canal.parse.driver.mysql.MysqlConnector;
import com.alibaba.otter.canal.parse.driver.mysql.MysqlQueryExecutor;
import com.alibaba.otter.canal.parse.driver.mysql.MysqlUpdateExecutor;
import com.alibaba.otter.canal.parse.driver.mysql.packets.GTIDSet;
import com.alibaba.otter.canal.parse.driver.mysql.packets.HeaderPacket;
import com.alibaba.otter.canal.parse.driver.mysql.packets.client.BinlogDumpCommandPacket;
import com.alibaba.otter.canal.parse.driver.mysql.packets.client.BinlogDumpGTIDCommandPacket;
import com.alibaba.otter.canal.parse.driver.mysql.packets.client.RegisterSlaveCommandPacket;
import com.alibaba.otter.canal.parse.driver.mysql.packets.client.SemiAckCommandPacket;
import com.alibaba.otter.canal.parse.driver.mysql.packets.server.ErrorPacket;
import com.alibaba.otter.canal.parse.driver.mysql.packets.server.ResultSetPacket;
import com.alibaba.otter.canal.parse.driver.mysql.utils.PacketManager;
import com.alibaba.otter.canal.parse.exception.CanalParseException;
import com.alibaba.otter.canal.parse.inbound.ErosaConnection;
import com.alibaba.otter.canal.parse.inbound.MultiStageCoprocessor;
import com.alibaba.otter.canal.parse.inbound.SinkFunction;
import com.alibaba.otter.canal.parse.inbound.mysql.dbsync.DirectLogFetcher;
import com.alibaba.otter.canal.parse.support.AuthenticationInfo;
import com.taobao.tddl.dbsync.binlog.LogBuffer;
import com.taobao.tddl.dbsync.binlog.LogContext;
import com.taobao.tddl.dbsync.binlog.LogDecoder;
import com.taobao.tddl.dbsync.binlog.LogEvent;
import com.taobao.tddl.dbsync.binlog.event.FormatDescriptionLogEvent;
public class MysqlConnection implements ErosaConnection {
private static final Logger logger = LoggerFactory.getLogger(MysqlConnection.class);
private MysqlConnector connector;
private long slaveId;
private Charset charset = Charset.forName("UTF-8");
private BinlogFormat binlogFormat;
private BinlogImage binlogImage;
// tsdb releated
private AuthenticationInfo authInfo;
protected int connTimeout = 5 * 1000; // 5秒
protected int soTimeout = 60 * 60 * 1000; // 1小时
private int binlogChecksum = LogEvent.BINLOG_CHECKSUM_ALG_OFF;
// dump binlog bytes, 暂不包括meta与TSDB
private AtomicLong receivedBinlogBytes;
private boolean compatiablePercona = false;
public MysqlConnection(){
}
public MysqlConnection(InetSocketAddress address, String username, String password){
authInfo = new AuthenticationInfo();
authInfo.setAddress(address);
authInfo.setUsername(username);
authInfo.setPassword(password);
connector = new MysqlConnector(address, username, password);
// 将connection里面的参数透传下
connector.setSoTimeout(soTimeout);
connector.setConnTimeout(connTimeout);
}
public MysqlConnection(InetSocketAddress address, String username, String password, byte charsetNumber,
String defaultSchema){
authInfo = new AuthenticationInfo();
authInfo.setAddress(address);
authInfo.setUsername(username);
authInfo.setPassword(password);
authInfo.setDefaultDatabaseName(defaultSchema);
connector = new MysqlConnector(address, username, password, charsetNumber, defaultSchema);
// 将connection里面的参数透传下
connector.setSoTimeout(soTimeout);
connector.setConnTimeout(connTimeout);
}
public void connect() throws IOException {
connector.connect();
}
public void reconnect() throws IOException {
connector.reconnect();
}
public void disconnect() throws IOException {
connector.disconnect();
}
public boolean isConnected() {
return connector.isConnected();
}
public ResultSetPacket query(String cmd) throws IOException {
MysqlQueryExecutor exector = new MysqlQueryExecutor(connector);
return exector.query(cmd);
}
public List<ResultSetPacket> queryMulti(String cmd) throws IOException {
MysqlQueryExecutor exector = new MysqlQueryExecutor(connector);
return exector.queryMulti(cmd);
}
public void update(String cmd) throws IOException {
MysqlUpdateExecutor exector = new MysqlUpdateExecutor(connector);
exector.update(cmd);
}
/**
* 加速主备切换时的查找速度,做一些特殊优化,比如只解析事务头或者尾
*/
public void seek(String binlogfilename, Long binlogPosition, String gtid, SinkFunction func) throws IOException {
updateSettings();
loadBinlogChecksum();
loadVersionComment();
sendBinlogDump(binlogfilename, binlogPosition);
DirectLogFetcher fetcher = new DirectLogFetcher(connector.getReceiveBufferSize());
fetcher.start(connector.getChannel());
LogDecoder decoder = new LogDecoder();
decoder.handle(LogEvent.ROTATE_EVENT);
decoder.handle(LogEvent.FORMAT_DESCRIPTION_EVENT);
decoder.handle(LogEvent.QUERY_EVENT);
decoder.handle(LogEvent.XID_EVENT);
LogContext context = new LogContext();
// 若entry position存在gtid,则使用传入的gtid作为gtidSet
// 拼接的标准,否则同时开启gtid和tsdb时,会导致丢失gtid
// 而当源端数据库gtid 有purged时会有如下类似报错
// 'errno = 1236, sqlstate = HY000 errmsg = The slave is connecting
// using CHANGE MASTER TO MASTER_AUTO_POSITION = 1 ...
if (StringUtils.isNotEmpty(gtid)) {
GTIDSet gtidSet = parseGtidSet(gtid, isMariaDB());
if (isMariaDB()) {
decoder.handle(LogEvent.GTID_EVENT);
decoder.handle(LogEvent.GTID_LIST_EVENT);
} else {
decoder.handle(LogEvent.GTID_LOG_EVENT);
}
context.setGtidSet(gtidSet);
}
context.setCompatiablePercona(compatiablePercona);
context.setFormatDescription(new FormatDescriptionLogEvent(4, binlogChecksum));
while (fetcher.fetch()) {
accumulateReceivedBytes(fetcher.limit());
LogEvent event = null;
event = decoder.decode(fetcher, context);
if (event == null) {
throw new CanalParseException("parse failed");
}
if (!func.sink(event)) {
break;
}
}
}
public void dump(String binlogfilename, Long binlogPosition, SinkFunction func) throws IOException {
updateSettings();
loadBinlogChecksum();
loadVersionComment();
sendRegisterSlave();
sendBinlogDump(binlogfilename, binlogPosition);
DirectLogFetcher fetcher = new DirectLogFetcher(connector.getReceiveBufferSize());
fetcher.start(connector.getChannel());
LogDecoder decoder = new LogDecoder(LogEvent.UNKNOWN_EVENT, LogEvent.ENUM_END_EVENT);
LogContext context = new LogContext();
context.setCompatiablePercona(compatiablePercona);
context.setFormatDescription(new FormatDescriptionLogEvent(4, binlogChecksum));
while (fetcher.fetch()) {
accumulateReceivedBytes(fetcher.limit());
LogEvent event = null;
event = decoder.decode(fetcher, context);
if (event == null) {
throw new CanalParseException("parse failed");
}
if (!func.sink(event)) {
break;
}
if (event.getSemival() == 1) {
sendSemiAck(context.getLogPosition().getFileName(), context.getLogPosition().getPosition());
}
}
}
@Override
public void dump(GTIDSet gtidSet, SinkFunction func) throws IOException {
updateSettings();
loadBinlogChecksum();
loadVersionComment();
sendBinlogDumpGTID(gtidSet);
try (DirectLogFetcher fetcher = new DirectLogFetcher(connector.getReceiveBufferSize())) {
fetcher.start(connector.getChannel());
LogDecoder decoder = new LogDecoder(LogEvent.UNKNOWN_EVENT, LogEvent.ENUM_END_EVENT);
LogContext context = new LogContext();
context.setCompatiablePercona(compatiablePercona);
context.setFormatDescription(new FormatDescriptionLogEvent(4, binlogChecksum));
// fix bug: #890 将gtid传输至context中,供decode使用
context.setGtidSet(gtidSet);
while (fetcher.fetch()) {
accumulateReceivedBytes(fetcher.limit());
LogEvent event = null;
event = decoder.decode(fetcher, context);
if (event == null) {
throw new CanalParseException("parse failed");
}
List<LogEvent> iterateEvents = decoder.processIterateDecode(event, context);
if (!iterateEvents.isEmpty()) {
// 处理compress event
for (LogEvent itEvent : iterateEvents) {
if (!func.sink(event)) {
break;
}
}
} else {
if (!func.sink(event)) {
break;
}
}
}
}
}
public void dump(long timestamp, SinkFunction func) throws IOException {
throw new NullPointerException("Not implement yet");
}
@Override
public void dump(String binlogfilename, Long binlogPosition, MultiStageCoprocessor coprocessor) throws IOException {
updateSettings();
loadBinlogChecksum();
loadVersionComment();
sendRegisterSlave();
sendBinlogDump(binlogfilename, binlogPosition);
((MysqlMultiStageCoprocessor) coprocessor).setConnection(this);
((MysqlMultiStageCoprocessor) coprocessor).setBinlogChecksum(binlogChecksum);
((MysqlMultiStageCoprocessor) coprocessor).setCompatiablePercona(compatiablePercona);
try (DirectLogFetcher fetcher = new DirectLogFetcher(connector.getReceiveBufferSize())) {
fetcher.start(connector.getChannel());
while (fetcher.fetch()) {
accumulateReceivedBytes(fetcher.limit());
LogBuffer buffer = fetcher.duplicate();
fetcher.consume(fetcher.limit());
if (!coprocessor.publish(buffer)) {
break;
}
}
}
}
@Override
public void dump(long timestamp, MultiStageCoprocessor coprocessor) throws IOException {
throw new NullPointerException("Not implement yet");
}
@Override
public void dump(GTIDSet gtidSet, MultiStageCoprocessor coprocessor) throws IOException {
updateSettings();
loadBinlogChecksum();
loadVersionComment();
sendBinlogDumpGTID(gtidSet);
((MysqlMultiStageCoprocessor) coprocessor).setConnection(this);
((MysqlMultiStageCoprocessor) coprocessor).setBinlogChecksum(binlogChecksum);
((MysqlMultiStageCoprocessor) coprocessor).setCompatiablePercona(compatiablePercona);
try (DirectLogFetcher fetcher = new DirectLogFetcher(connector.getReceiveBufferSize())) {
fetcher.start(connector.getChannel());
while (fetcher.fetch()) {
accumulateReceivedBytes(fetcher.limit());
LogBuffer buffer = fetcher.duplicate();
fetcher.consume(fetcher.limit());
if (!coprocessor.publish(buffer)) {
break;
}
}
}
}
private void sendRegisterSlave() throws IOException {
RegisterSlaveCommandPacket cmd = new RegisterSlaveCommandPacket();
SocketAddress socketAddress = connector.getChannel().getLocalSocketAddress();
if (socketAddress == null || !(socketAddress instanceof InetSocketAddress)) {
return;
}
InetSocketAddress address = (InetSocketAddress) socketAddress;
String host = address.getHostString();
int port = address.getPort();
cmd.reportHost = host;
cmd.reportPort = port;
cmd.reportPasswd = authInfo.getPassword();
cmd.reportUser = authInfo.getUsername();
cmd.serverId = this.slaveId;
byte[] cmdBody = cmd.toBytes();
logger.info("Register slave {}", cmd);
HeaderPacket header = new HeaderPacket();
header.setPacketBodyLength(cmdBody.length);
header.setPacketSequenceNumber((byte) 0x00);
PacketManager.writePkg(connector.getChannel(), header.toBytes(), cmdBody);
header = PacketManager.readHeader(connector.getChannel(), 4);
byte[] body = PacketManager.readBytes(connector.getChannel(), header.getPacketBodyLength());
assert body != null;
if (body[0] < 0) {
if (body[0] == -1) {
ErrorPacket err = new ErrorPacket();
err.fromBytes(body);
throw new IOException("Error When doing Register slave:" + err.toString());
} else {
throw new IOException("Unexpected packet with field_count=" + body[0]);
}
}
}
private void sendBinlogDump(String binlogfilename, Long binlogPosition) throws IOException {
BinlogDumpCommandPacket binlogDumpCmd = new BinlogDumpCommandPacket();
binlogDumpCmd.binlogFileName = binlogfilename;
binlogDumpCmd.binlogPosition = binlogPosition;
binlogDumpCmd.slaveServerId = this.slaveId;
byte[] cmdBody = binlogDumpCmd.toBytes();
logger.info("COM_BINLOG_DUMP with position:{}", binlogDumpCmd);
HeaderPacket binlogDumpHeader = new HeaderPacket();
binlogDumpHeader.setPacketBodyLength(cmdBody.length);
binlogDumpHeader.setPacketSequenceNumber((byte) 0x00);
PacketManager.writePkg(connector.getChannel(), binlogDumpHeader.toBytes(), cmdBody);
connector.setDumping(true);
}
public void sendSemiAck(String binlogfilename, Long binlogPosition) throws IOException {
SemiAckCommandPacket semiAckCmd = new SemiAckCommandPacket();
semiAckCmd.binlogFileName = binlogfilename;
semiAckCmd.binlogPosition = binlogPosition;
byte[] cmdBody = semiAckCmd.toBytes();
logger.info("SEMI ACK with position:{}", semiAckCmd);
HeaderPacket semiAckHeader = new HeaderPacket();
semiAckHeader.setPacketBodyLength(cmdBody.length);
semiAckHeader.setPacketSequenceNumber((byte) 0x00);
PacketManager.writePkg(connector.getChannel(), semiAckHeader.toBytes(), cmdBody);
}
private void sendBinlogDumpGTID(GTIDSet gtidSet) throws IOException {
if (isMariaDB()) {
sendMariaBinlogDumpGTID(gtidSet);
} else {
sendMySQLBinlogDumpGTID(gtidSet);
}
}
private void sendMySQLBinlogDumpGTID(GTIDSet gtidSet) throws IOException {
BinlogDumpGTIDCommandPacket binlogDumpCmd = new BinlogDumpGTIDCommandPacket();
binlogDumpCmd.slaveServerId = this.slaveId;
binlogDumpCmd.gtidSet = gtidSet;
byte[] cmdBody = binlogDumpCmd.toBytes();
logger.info("COM_BINLOG_DUMP_GTID:{}", binlogDumpCmd);
HeaderPacket binlogDumpHeader = new HeaderPacket();
binlogDumpHeader.setPacketBodyLength(cmdBody.length);
binlogDumpHeader.setPacketSequenceNumber((byte) 0x00);
PacketManager.writePkg(connector.getChannel(), binlogDumpHeader.toBytes(), cmdBody);
connector.setDumping(true);
}
private void sendMariaBinlogDumpGTID(GTIDSet gtidSet) throws IOException {
update("SET @slave_connect_state = '" + new String(gtidSet.encode()) + "'");
update("SET @slave_gtid_strict_mode = 0");
update("SET @slave_gtid_ignore_duplicates = 0");
sendRegisterSlave();
sendBinlogDump("", 0L);
connector.setDumping(true);
}
public MysqlConnection fork() {
MysqlConnection connection = new MysqlConnection();
connection.setCharset(getCharset());
connection.setSlaveId(getSlaveId());
connection.setConnector(connector.fork());
// set authInfo
connection.setAuthInfo(authInfo);
return connection;
}
@Override
public long queryServerId() throws IOException {
ResultSetPacket resultSetPacket = query("show variables like 'server_id'");
List<String> fieldValues = resultSetPacket.getFieldValues();
if (fieldValues == null || fieldValues.size() != 2) {
return 0;
}
return NumberUtils.toLong(fieldValues.get(1));
}
// ====================== help method ====================
/**
* the settings that will need to be checked or set:<br>
* <ol>
* <li>wait_timeout</li>
* <li>net_write_timeout</li>
* <li>net_read_timeout</li>
* </ol>
*
* @throws IOException
*/
private void updateSettings() throws IOException {
try {
update("set wait_timeout=9999999");
} catch (Exception e) {
logger.warn("update wait_timeout failed", e);
}
try {
update("set net_write_timeout=7200");
} catch (Exception e) {
logger.warn("update net_write_timeout failed", e);
}
try {
update("set net_read_timeout=7200");
} catch (Exception e) {
logger.warn("update net_read_timeout failed", e);
}
try {
// 设置服务端返回结果时不做编码转化,直接按照数据库的二进制编码进行发送,由客户端自己根据需求进行编码转化
update("set names 'binary'");
} catch (Exception e) {
logger.warn("update names failed", e);
}
try {
// mysql5.6针对checksum支持需要设置session变量
// 如果不设置会出现错误: Slave can not handle replication events with the
// checksum that master is configured to log
// 但也不能乱设置,需要和mysql server的checksum配置一致,不然RotateLogEvent会出现乱码
// '@@global.binlog_checksum'需要去掉单引号,在mysql 5.6.29下导致master退出
update("set @master_binlog_checksum= @@global.binlog_checksum");
} catch (Exception e) {
if (!StringUtils.contains(e.getMessage(), "Unknown system variable")) {
logger.warn("update master_binlog_checksum failed", e);
}
}
try {
// 参考:https://github.com/alibaba/canal/issues/284
// mysql5.6需要设置slave_uuid避免被server kill链接
update("set @slave_uuid=uuid()");
} catch (Exception e) {
if (!StringUtils.contains(e.getMessage(), "Unknown system variable")
&& !StringUtils.contains(e.getMessage(), "slave_uuid can't be set")) {
logger.warn("update slave_uuid failed", e);
}
}
try {
// mariadb针对特殊的类型,需要设置session变量
update("SET @mariadb_slave_capability='" + LogEvent.MARIA_SLAVE_CAPABILITY_MINE + "'");
} catch (Exception e) {
if (!StringUtils.contains(e.getMessage(), "Unknown system variable")) {
logger.warn("update mariadb_slave_capability failed", e);
}
}
/**
* MASTER_HEARTBEAT_PERIOD sets the interval in seconds between replication
* heartbeats. Whenever the master's binary log is updated with an event, the
* waiting period for the next heartbeat is reset. interval is a decimal value
* having the range 0 to 4294967 seconds and a resolution in milliseconds; the
* smallest nonzero value is 0.001. Heartbeats are sent by the master only if
* there are no unsent events in the binary log file for a period longer than
* interval.
*/
try {
long periodNano = TimeUnit.SECONDS.toNanos(MASTER_HEARTBEAT_PERIOD_SECONDS);
update("SET @master_heartbeat_period=" + periodNano);
} catch (Exception e) {
logger.warn("update master_heartbeat_period failed", e);
}
}
/**
* 获取一下binlog format格式
*/
private void loadBinlogFormat() {
ResultSetPacket rs = null;
try {
rs = query("show variables like 'binlog_format'");
} catch (IOException e) {
throw new CanalParseException(e);
}
List<String> columnValues = rs.getFieldValues();
if (columnValues == null || columnValues.size() != 2) {
logger.warn(
"unexpected binlog format query result, this may cause unexpected result, so throw exception to request network to io shutdown.");
throw new IllegalStateException("unexpected binlog format query result:" + rs.getFieldValues());
}
binlogFormat = BinlogFormat.valuesOf(columnValues.get(1));
if (binlogFormat == null) {
throw new IllegalStateException("unexpected binlog format query result:" + rs.getFieldValues());
}
}
/**
* 获取一下binlog image格式
*/
private void loadBinlogImage() {
ResultSetPacket rs = null;
try {
rs = query("show variables like 'binlog_row_image'");
} catch (IOException e) {
throw new CanalParseException(e);
}
List<String> columnValues = rs.getFieldValues();
if (columnValues == null || columnValues.size() != 2) {
// 可能历时版本没有image特性
binlogImage = BinlogImage.FULL;
} else {
binlogImage = BinlogImage.valuesOf(columnValues.get(1));
}
if (binlogFormat == null) {
throw new IllegalStateException("unexpected binlog image query result:" + rs.getFieldValues());
}
}
/**
* 获取主库checksum信息
*
* <pre>
* mariadb区别于mysql会在binlog的第一个事件Rotate_Event里也会采用checksum逻辑,而mysql是在第二个binlog事件之后才感知是否需要处理checksum
* 导致maraidb只要是开启checksum就会出现binlog文件名解析乱码
* fixed issue : https://github.com/alibaba/canal/issues/1081
* </pre>
*/
private void loadBinlogChecksum() {
ResultSetPacket rs = null;
try {
rs = query("select @@global.binlog_checksum");
List<String> columnValues = rs.getFieldValues();
if (columnValues != null && columnValues.size() >= 1 && columnValues.get(0) != null
&& columnValues.get(0).toUpperCase().equals("CRC32")) {
binlogChecksum = LogEvent.BINLOG_CHECKSUM_ALG_CRC32;
} else {
binlogChecksum = LogEvent.BINLOG_CHECKSUM_ALG_OFF;
}
} catch (Throwable e) {
// logger.error("", e);
binlogChecksum = LogEvent.BINLOG_CHECKSUM_ALG_OFF;
}
}
/**
* 识别下mysql的几种生态版本 (percona / mariadb / mysql)
*/
private void loadVersionComment() {
ResultSetPacket rs = null;
try {
rs = query("select @@version_comment");
List<String> columnValues = rs.getFieldValues();
if (columnValues != null && columnValues.size() >= 1 && columnValues.get(0) != null) {
logger.warn("load MySQL @@version_comment : " + columnValues.get(0));
if (StringUtils.containsIgnoreCase(columnValues.get(0), "Percona")) {
compatiablePercona = true;
}
}
} catch (Throwable e) {
compatiablePercona = false;
}
}
private void accumulateReceivedBytes(long x) {
if (receivedBinlogBytes != null) {
receivedBinlogBytes.addAndGet(x);
}
}
public static enum BinlogFormat {
STATEMENT("STATEMENT"), ROW("ROW"), MIXED("MIXED");
public boolean isStatement() {
return this == STATEMENT;
}
public boolean isRow() {
return this == ROW;
}
public boolean isMixed() {
return this == MIXED;
}
private String value;
private BinlogFormat(String value){
this.value = value;
}
public static BinlogFormat valuesOf(String value) {
BinlogFormat[] formats = values();
for (BinlogFormat format : formats) {
if (format.value.equalsIgnoreCase(value)) {
return format;
}
}
return null;
}
}
/**
* http://dev.mysql.com/doc/refman/5.6/en/replication-options-binary-log.
* html#sysvar_binlog_row_image
*
* @author agapple 2015年6月29日 下午10:39:03
* @since 1.0.20
*/
public static enum BinlogImage {
FULL("FULL"), MINIMAL("MINIMAL"), NOBLOB("NOBLOB");
public boolean isFull() {
return this == FULL;
}
public boolean isMinimal() {
return this == MINIMAL;
}
public boolean isNoBlob() {
return this == NOBLOB;
}
private String value;
private BinlogImage(String value){
this.value = value;
}
public static BinlogImage valuesOf(String value) {
BinlogImage[] formats = values();
for (BinlogImage format : formats) {
if (format.value.equalsIgnoreCase(value)) {
return format;
}
}
return null;
}
}
// ================== setter / getter ===================
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public long getSlaveId() {
return slaveId;
}
public void setSlaveId(long slaveId) {
this.slaveId = slaveId;
}
public MysqlConnector getConnector() {
return connector;
}
public void setConnector(MysqlConnector connector) {
this.connector = connector;
}
public BinlogFormat getBinlogFormat() {
if (binlogFormat == null) {
synchronized (this) {
loadBinlogFormat();
}
}
return binlogFormat;
}
public BinlogImage getBinlogImage() {
if (binlogImage == null) {
synchronized (this) {
loadBinlogImage();
}
}
return binlogImage;
}
public InetSocketAddress getAddress() {
return authInfo.getAddress();
}
public void setConnTimeout(int connTimeout) {
this.connTimeout = connTimeout;
}
public void setSoTimeout(int soTimeout) {
this.soTimeout = soTimeout;
}
public AuthenticationInfo getAuthInfo() {
return authInfo;
}
public void setAuthInfo(AuthenticationInfo authInfo) {
this.authInfo = authInfo;
}
public void setReceivedBinlogBytes(AtomicLong receivedBinlogBytes) {
this.receivedBinlogBytes = receivedBinlogBytes;
}
public boolean isMariaDB() {
return connector.getServerVersion() != null && connector.getServerVersion().toLowerCase().contains("mariadb");
}
}
| alibaba/canal | parse/src/main/java/com/alibaba/otter/canal/parse/inbound/mysql/MysqlConnection.java |
1,034 | package org.nutz.el;
import org.nutz.el.parse.CharQueue;
/**
* 转换器接口.<br>
* 负责对字符队列进行转意,将其零散的字符转换成有具体意义的对象.
* @author juqkai([email protected])
*
*/
public interface Parse {
/**
* 空对象, 这样更好判断空值
*/
static final Object nullobj = new Object() {
public String toString() {return "/*nutz-el-nullobj*/";}
};
/**
* 提取队列顶部元素<br>
* 特别注意,实现本方法的子程序只应该读取自己要转换的数据,不是自己要使用的数据一律不做取操作.<br>
* 一句话,只读取自己能转换的,自己不能转换的一律不操作.
* @param exp 表达式
*/
Object fetchItem(CharQueue exp);
}
| nutzam/nutz | src/org/nutz/el/Parse.java |
1,035 | package com.didispace.async;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author 程序猿DD
* @version 1.0.0
* @date 16/5/16 下午12:58.
* @blog http://blog.didispace.com
*/
@Slf4j
@Component
public class Task {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Async("taskExecutor")
public void doTaskOne() throws Exception {
log.info("开始做任务一");
long start = System.currentTimeMillis();
log.info(stringRedisTemplate.randomKey());
long end = System.currentTimeMillis();
log.info("完成任务一,耗时:" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskTwo() throws Exception {
log.info("开始做任务二");
long start = System.currentTimeMillis();
log.info(stringRedisTemplate.randomKey());
long end = System.currentTimeMillis();
log.info("完成任务二,耗时:" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskThree() throws Exception {
log.info("开始做任务三");
long start = System.currentTimeMillis();
log.info(stringRedisTemplate.randomKey());
long end = System.currentTimeMillis();
log.info("完成任务三,耗时:" + (end - start) + "毫秒");
}
}
| dyc87112/SpringBoot-Learning | 1.x/Chapter4-1-4/src/main/java/com/didispace/async/Task.java |
1,037 | package com.example.gsyvideoplayer.utils;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.shuyu.gsyvideoplayer.utils.FileUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* Created by shuyu on 2016/11/11.
*/
public class CommonUtil {
public static void setViewHeight(View view, int width, int height) {
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
if (null == layoutParams)
return;
layoutParams.width = width;
layoutParams.height = height;
view.setLayoutParams(layoutParams);
}
public static void saveBitmap(Context context, Bitmap bitmap) throws FileNotFoundException {
if (bitmap != null) {
addPictureToAlbum(context, bitmap, "GSY-" + System.currentTimeMillis() + ".jpg");
bitmap.recycle();
}
}
/**
* 保存图片到picture 目录,Android Q适配,最简单的做法就是保存到公共目录,不用SAF存储
*
* @param context
* @param bitmap
* @param fileName
*/
public static boolean addPictureToAlbum(Context context, Bitmap bitmap, String fileName) {
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.Images.Media.DESCRIPTION, fileName);
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream outputStream = null;
try {
outputStream = context.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
| CarGuo/GSYVideoPlayer | app/src/main/java/com/example/gsyvideoplayer/utils/CommonUtil.java |
1,041 | /**
* File: permutations_i.java
* Created Time: 2023-04-24
* Author: krahets ([email protected])
*/
package chapter_backtracking;
import java.util.*;
public class permutations_i {
/* 回溯算法:全排列 I */
public static void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// 遍历所有选择
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state.add(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.remove(state.size() - 1);
}
}
}
/* 全排列 I */
static List<List<Integer>> permutationsI(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
return res;
}
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
List<List<Integer>> res = permutationsI(nums);
System.out.println("输入数组 nums = " + Arrays.toString(nums));
System.out.println("所有排列 res = " + res);
}
}
| krahets/hello-algo | codes/java/chapter_backtracking/permutations_i.java |
1,046 | M
1528088505
tags: Hash Table
给一个Hash Table, 是用 linked list 做的. 问题是: capacity太小, collision太多的情况下, 需要double capacity 然后rehash.
#### Hash Table
- 明白hashCode() function的意义: 拿到hashKey的时候, 用hashKey%capacity 来做hash code
- hashcode就是hash map里面的index
- 明白collision handling 的方式, 和如何double capacity而rehashing
- 都是基本操作, 概念实现
```
/*
The size of the hash table is not determinate at the very beginning.
If the total size of keys is too large (e.g. size >= capacity / 10),
we should double the size of the hash table and rehash every keys.
Say you have a hash table looks like below:
size=3, capacity=4
[null, 21, 14, null]
↓ ↓
9 null
↓
null
The hash function is:
int hashcode(int key, int capacity) {
return key % capacity;
}
here we have three numbers, 9, 14 and 21, where 21 and 9 share the same position
as they all have the same hashcode 1 (21 % 4 = 9 % 4 = 1).
We store them in the hash table by linked list.
rehashing this hash table, double the capacity, you will get:
size=3, capacity=8
index: 0 1 2 3 4 5 6 7
hash : [null, 9, null, null, null, 21, 14, null]
Given the original hash table, return the new hash table after rehashing .
Example
Given [null, 21->9->null, 14->null, null],
return [null, 9->null, null, null, null, 21->null, 14->null, null]
Note
For negative integer in hash table, the position can be calculated as follow:
C++/Java: if you directly calculate -4 % 3 you will get -1.
You can use function: a % b = (a % b + b) % b to make it is a non negative integer.
Python: you can directly use -1 % 3, you will get 2 automatically.
Tags Expand
LintCode Copyright Hash Table
Thoughts:
1. Loop through the hashtable[] and find longest, calcualte new capacity
2. rehash
*/
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param hashTable: A list of The first node of linked list
* @return: A list of The first node of linked list which have twice size
*/
public ListNode[] rehashing(ListNode[] hashTable) {
if (hashTable == null || hashTable.length == 0) {
return hashTable;
}
//Calculate new capacity, double the hashtable size
int capacity = hashTable.length * 2;
ListNode[] rst = new ListNode[capacity];
for (int i = 0; i < hashTable.length; i++) {
ListNode node = hashTable[i]; // process one hashkey (a linked list)
while (node != null) {
ListNode newNode = new ListNode(node.val);
int hCode = hashcode(newNode.val, capacity);
if (rst[hCode] == null) {
rst[hCode] = newNode;
} else {
ListNode collisionNode = rst[hCode];
while (collisionNode.next != null) {
collisionNode = collisionNode.next;
}
collisionNode.next = newNode;
}
node = node.next;
}
}
return rst;
}
public int hashcode(int key, int capacity) {
if (key < 0) {
return (key % capacity + capacity) % capacity;
} else {
return key % capacity;
}
}
};
``` | awangdev/leet-code | Java/Rehashing.java |
1,048 | package cn.hutool.crypto.asymmetric;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.SecureUtil;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Set;
/**
* 签名包装,{@link Signature} 包装类
*
* @author looly
* @since 3.3.0
*/
public class Sign extends BaseAsymmetric<Sign> {
private static final long serialVersionUID = 1L;
/** 签名,用于签名和验证 */
protected Signature signature;
// ------------------------------------------------------------------ Constructor start
/**
* 构造,创建新的私钥公钥对
*
* @param algorithm {@link SignAlgorithm}
*/
public Sign(SignAlgorithm algorithm) {
this(algorithm, null, (byte[]) null);
}
/**
* 构造,创建新的私钥公钥对
*
* @param algorithm 算法
*/
public Sign(String algorithm) {
this(algorithm, null, (byte[]) null);
}
/**
* 构造 私钥和公钥同时为空时生成一对新的私钥和公钥<br>
* 私钥和公钥可以单独传入一个,如此则只能使用此钥匙来做签名或验证
*
* @param algorithm {@link SignAlgorithm}
* @param privateKeyStr 私钥Hex或Base64表示
* @param publicKeyStr 公钥Hex或Base64表示
*/
public Sign(SignAlgorithm algorithm, String privateKeyStr, String publicKeyStr) {
this(algorithm.getValue(), SecureUtil.decode(privateKeyStr), SecureUtil.decode(publicKeyStr));
}
/**
* 构造 私钥和公钥同时为空时生成一对新的私钥和公钥<br>
* 私钥和公钥可以单独传入一个,如此则只能使用此钥匙来做签名或验证
*
* @param algorithm {@link SignAlgorithm}
* @param privateKey 私钥
* @param publicKey 公钥
*/
public Sign(SignAlgorithm algorithm, byte[] privateKey, byte[] publicKey) {
this(algorithm.getValue(), privateKey, publicKey);
}
/**
* 构造 私钥和公钥同时为空时生成一对新的私钥和公钥<br>
* 私钥和公钥可以单独传入一个,如此则只能使用此钥匙来做签名或验证
*
* @param algorithm {@link SignAlgorithm}
* @param keyPair 密钥对(包括公钥和私钥)
*/
public Sign(SignAlgorithm algorithm, KeyPair keyPair) {
this(algorithm.getValue(), keyPair);
}
/**
* 构造 私钥和公钥同时为空时生成一对新的私钥和公钥<br>
* 私钥和公钥可以单独传入一个,如此则只能使用此钥匙来做签名或验证
*
* @param algorithm {@link SignAlgorithm}
* @param privateKey 私钥
* @param publicKey 公钥
*/
public Sign(SignAlgorithm algorithm, PrivateKey privateKey, PublicKey publicKey) {
this(algorithm.getValue(), privateKey, publicKey);
}
/**
* 构造 私钥和公钥同时为空时生成一对新的私钥和公钥<br>
* 私钥和公钥可以单独传入一个,如此则只能使用此钥匙来做签名或验证
*
* @param algorithm 非对称加密算法
* @param privateKeyBase64 私钥Base64
* @param publicKeyBase64 公钥Base64
*/
public Sign(String algorithm, String privateKeyBase64, String publicKeyBase64) {
this(algorithm, Base64.decode(privateKeyBase64), Base64.decode(publicKeyBase64));
}
/**
* 构造
*
* 私钥和公钥同时为空时生成一对新的私钥和公钥<br>
* 私钥和公钥可以单独传入一个,如此则只能使用此钥匙来做签名或验证
*
* @param algorithm 算法
* @param privateKey 私钥
* @param publicKey 公钥
*/
public Sign(String algorithm, byte[] privateKey, byte[] publicKey) {
this(algorithm, //
SecureUtil.generatePrivateKey(algorithm, privateKey), //
SecureUtil.generatePublicKey(algorithm, publicKey)//
);
}
/**
* 构造 私钥和公钥同时为空时生成一对新的私钥和公钥<br>
* 私钥和公钥可以单独传入一个,如此则只能使用此钥匙来做签名或验证
*
* @param algorithm 算法,见{@link SignAlgorithm}
* @param keyPair 密钥对(包括公钥和私钥)
*/
public Sign(String algorithm, KeyPair keyPair) {
this(algorithm, keyPair.getPrivate(), keyPair.getPublic());
}
/**
* 构造
*
* 私钥和公钥同时为空时生成一对新的私钥和公钥<br>
* 私钥和公钥可以单独传入一个,如此则只能使用此钥匙来做签名或验证
*
* @param algorithm 算法
* @param privateKey 私钥
* @param publicKey 公钥
*/
public Sign(String algorithm, PrivateKey privateKey, PublicKey publicKey) {
super(algorithm, privateKey, publicKey);
}
// ------------------------------------------------------------------ Constructor end
/**
* 初始化
*
* @param algorithm 算法
* @param privateKey 私钥
* @param publicKey 公钥
* @return this
*/
@Override
public Sign init(String algorithm, PrivateKey privateKey, PublicKey publicKey) {
signature = SecureUtil.createSignature(algorithm);
super.init(algorithm, privateKey, publicKey);
return this;
}
/**
* 设置签名的参数
*
* @param params {@link AlgorithmParameterSpec}
* @return this
* @since 4.6.5
*/
public Sign setParameter(AlgorithmParameterSpec params) {
try {
this.signature.setParameter(params);
} catch (InvalidAlgorithmParameterException e) {
throw new CryptoException(e);
}
return this;
}
// --------------------------------------------------------------------------------- Sign and Verify
/**
* 生成文件签名
*
* @param data 被签名数据
* @param charset 编码
* @return 签名
* @since 5.7.0
*/
public byte[] sign(String data, Charset charset) {
return sign(StrUtil.bytes(data, charset));
}
/**
* 生成文件签名
*
* @param data 被签名数据
* @return 签名
* @since 5.7.0
*/
public byte[] sign(String data) {
return sign(data, CharsetUtil.CHARSET_UTF_8);
}
/**
* 生成文件签名,并转为16进制字符串
*
* @param data 被签名数据
* @param charset 编码
* @return 签名
* @since 5.7.0
*/
public String signHex(String data, Charset charset) {
return HexUtil.encodeHexStr(sign(data, charset));
}
/**
* 生成文件签名
*
* @param data 被签名数据
* @return 签名
* @since 5.7.0
*/
public String signHex(String data) {
return signHex(data, CharsetUtil.CHARSET_UTF_8);
}
/**
* 用私钥对信息生成数字签名
*
* @param data 加密数据
* @return 签名
*/
public byte[] sign(byte[] data) {
return sign(new ByteArrayInputStream(data), -1);
}
/**
* 生成签名,并转为16进制字符串<br>
*
* @param data 被签名数据
* @return 签名
* @since 5.7.0
*/
public String signHex(byte[] data) {
return HexUtil.encodeHexStr(sign(data));
}
/**
* 生成签名,并转为16进制字符串<br>
* 使用默认缓存大小,见 {@link IoUtil#DEFAULT_BUFFER_SIZE}
*
* @param data 被签名数据
* @return 签名
* @since 5.7.0
*/
public String signHex(InputStream data) {
return HexUtil.encodeHexStr(sign(data));
}
/**
* 生成签名,使用默认缓存大小,见 {@link IoUtil#DEFAULT_BUFFER_SIZE}
*
* @param data {@link InputStream} 数据流
* @return 签名bytes
* @since 5.7.0
*/
public byte[] sign(InputStream data) {
return sign(data, IoUtil.DEFAULT_BUFFER_SIZE);
}
/**
* 生成签名,并转为16进制字符串<br>
* 使用默认缓存大小,见 {@link IoUtil#DEFAULT_BUFFER_SIZE}
*
* @param data 被签名数据
* @param bufferLength 缓存长度,不足1使用 {@link IoUtil#DEFAULT_BUFFER_SIZE} 做为默认值
* @return 签名
* @since 5.7.0
*/
public String digestHex(InputStream data, int bufferLength) {
return HexUtil.encodeHexStr(sign(data, bufferLength));
}
/**
* 生成签名
*
* @param data {@link InputStream} 数据流
* @param bufferLength 缓存长度,不足1使用 {@link IoUtil#DEFAULT_BUFFER_SIZE} 做为默认值
* @return 签名bytes
* @since 5.7.0
*/
public byte[] sign(InputStream data, int bufferLength){
if (bufferLength < 1) {
bufferLength = IoUtil.DEFAULT_BUFFER_SIZE;
}
final byte[] buffer = new byte[bufferLength];
lock.lock();
try {
signature.initSign(this.privateKey);
byte[] result;
try {
int read = data.read(buffer, 0, bufferLength);
while (read > -1) {
signature.update(buffer, 0, read);
read = data.read(buffer, 0, bufferLength);
}
result = signature.sign();
} catch (Exception e) {
throw new CryptoException(e);
}
return result;
} catch (Exception e) {
throw new CryptoException(e);
} finally {
lock.unlock();
}
}
/**
* 用公钥检验数字签名的合法性
*
* @param data 数据
* @param sign 签名
* @return 是否验证通过
*/
public boolean verify(byte[] data, byte[] sign) {
lock.lock();
try {
signature.initVerify(this.publicKey);
signature.update(data);
return signature.verify(sign);
} catch (Exception e) {
throw new CryptoException(e);
} finally {
lock.unlock();
}
}
/**
* 获得签名对象
*
* @return {@link Signature}
*/
public Signature getSignature() {
return signature;
}
/**
* 设置签名
*
* @param signature 签名对象 {@link Signature}
* @return 自身 {@link AsymmetricCrypto}
*/
public Sign setSignature(Signature signature) {
this.signature = signature;
return this;
}
/**
* 设置{@link Certificate} 为PublicKey<br>
* 如果Certificate是X509Certificate,我们需要检查是否有密钥扩展
*
* @param certificate {@link Certificate}
* @return this
*/
public Sign setCertificate(Certificate certificate) {
// If the certificate is of type X509Certificate,
// we should check whether it has a Key Usage
// extension marked as critical.
if (certificate instanceof X509Certificate) {
// Check whether the cert has a key usage extension
// marked as a critical extension.
// The OID for KeyUsage extension is 2.5.29.15.
final X509Certificate cert = (X509Certificate) certificate;
final Set<String> critSet = cert.getCriticalExtensionOIDs();
if (CollUtil.isNotEmpty(critSet) && critSet.contains("2.5.29.15")) {
final boolean[] keyUsageInfo = cert.getKeyUsage();
// keyUsageInfo[0] is for digitalSignature.
if ((keyUsageInfo != null) && (keyUsageInfo[0] == false)) {
throw new CryptoException("Wrong key usage");
}
}
}
this.publicKey = certificate.getPublicKey();
return this;
}
}
| dromara/hutool | hutool-crypto/src/main/java/cn/hutool/crypto/asymmetric/Sign.java |
1,049 | package com.taobao.arthas.core.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import static com.taobao.arthas.core.util.ArthasCheckUtils.isEquals;
import static com.taobao.arthas.core.util.ArthasCheckUtils.isIn;
import static com.taobao.arthas.core.util.StringUtils.isBlank;
/**
* Feature编解器(线程安全)<br/>
* <p/>
* 用于封装系统内部features/attribute等扩展字段的管理
* Created by dukun on 15/3/31.
*/
public class FeatureCodec {
// 对象的编码解码器
public final static FeatureCodec DEFAULT_COMMANDLINE_CODEC = new FeatureCodec(';', '=');
/**
* KV片段分割符<br/>
* KV片段定义为一个完整的KV对,例如字符串<span>;k1=v1;k2=v2;</span>
* 其中<b>;</b>即为KV片段分隔符
*/
private final char kvSegmentSeparator;
/**
* KV分割符<br/>
* KV定义为一个KV对区分K和V的分割符号,例如字符串<span>k1=v1</span>
* 其中<b>=</b>即为KV分隔符
*/
private final char kvSeparator;
/**
* 转义前缀符
*/
private static final char ESCAPE_PREFIX_CHAR = '\\';
/**
* 使用指定的KV分割符构造FeatureParser<br/>
*
* @param kvSegmentSeparator KV对之间的分隔符
* @param kvSeparator K与V之间的分隔符
*/
public FeatureCodec(final char kvSegmentSeparator, final char kvSeparator) {
// 分隔符禁止与转义前缀符相等
if (isIn(ESCAPE_PREFIX_CHAR, kvSegmentSeparator, kvSeparator)) {
throw new IllegalArgumentException("separator can not init to '" + ESCAPE_PREFIX_CHAR + "'.");
}
this.kvSegmentSeparator = kvSegmentSeparator;
this.kvSeparator = kvSeparator;
}
/**
* map集合转换到feature字符串
*
* @param map map集合
* @return feature字符串
*/
public String toString(final Map<String, String> map) {
final StringBuilder featureSB = new StringBuilder().append(kvSegmentSeparator);
if (null == map
|| map.isEmpty()) {
return featureSB.toString();
}
for (Map.Entry<String, String> entry : map.entrySet()) {
featureSB
.append(escapeEncode(entry.getKey()))
.append(kvSeparator)
.append(escapeEncode(entry.getValue()))
.append(kvSegmentSeparator)
;
}
return featureSB.toString();
}
/**
* feature字符串转换到map集合
*
* @param featureString the feature string
* @return the map
*/
public Map<String, String> toMap(final String featureString) {
final Map<String, String> map = new HashMap<String, String>();
if (isBlank(featureString)) {
return map;
}
for (String kv : escapeSplit(featureString, kvSegmentSeparator)) {
if (isBlank(kv)) {
// 过滤掉为空的字符串片段
continue;
}
final String[] ar = escapeSplit(kv, kvSeparator);
if (ar.length != 2) {
// 过滤掉不符合K:V单目的情况
continue;
}
final String k = ar[0];
final String v = ar[1];
if (!isBlank(k)
&& !isBlank(v)) {
map.put(escapeDecode(k), escapeDecode(v));
}
}
return map;
}
/**
* 转义编码
*
* @param string 原始字符串
* @return 转义编码后的字符串
*/
private String escapeEncode(final String string) {
final StringBuilder returnSB = new StringBuilder();
for (final char c : string.toCharArray()) {
if (isIn(c, kvSegmentSeparator, kvSeparator, ESCAPE_PREFIX_CHAR)) {
returnSB.append(ESCAPE_PREFIX_CHAR);
}
returnSB.append(c);
}
return returnSB.toString();
}
/**
* 转义解码
*
* @param string 编码字符串
* @return 转义解码后的字符串
*/
private String escapeDecode(String string) {
final StringBuilder segmentSB = new StringBuilder();
final int stringLength = string.length();
for (int index = 0; index < stringLength; index++) {
final char c = string.charAt(index);
if (isEquals(c, ESCAPE_PREFIX_CHAR)
&& index < stringLength - 1) {
final char nextChar = string.charAt(++index);
// 下一个字符是转义符
if (isIn(nextChar, kvSegmentSeparator, kvSeparator, ESCAPE_PREFIX_CHAR)) {
segmentSB.append(nextChar);
}
// 如果不是转义字符,则需要两个都放入
else {
segmentSB.append(c);
segmentSB.append(nextChar);
}
} else {
segmentSB.append(c);
}
}
return segmentSB.toString();
}
/**
* 编码字符串拆分
*
* @param string 编码字符串
* @param splitEscapeChar 分割符
* @return 拆分后的字符串数组
*/
private String[] escapeSplit(String string, char splitEscapeChar) {
final ArrayList<String> segmentArrayList = new ArrayList<String>();
final Stack<Character> decodeStack = new Stack<Character>();
final int stringLength = string.length();
for (int index = 0; index < stringLength; index++) {
boolean isArchive = false;
final char c = string.charAt(index);
// 匹配到转义前缀符
if (isEquals(c, ESCAPE_PREFIX_CHAR)) {
decodeStack.push(c);
if (index < stringLength - 1) {
final char nextChar = string.charAt(++index);
decodeStack.push(nextChar);
}
}
// 匹配到分割符
else if (isEquals(c, splitEscapeChar)) {
isArchive = true;
}
// 匹配到其他字符
else {
decodeStack.push(c);
}
if (isArchive
|| index == stringLength - 1) {
final StringBuilder segmentSB = new StringBuilder(decodeStack.size());
while (!decodeStack.isEmpty()) {
segmentSB.append(decodeStack.pop());
}
segmentArrayList.add(
segmentSB
.reverse() // 因为堆栈中是逆序的,所以需要对逆序的字符串再次逆序
.toString() // toString
.trim() // 考虑到字符串片段可能会出现首尾空格的场景,这里做一个过滤
);
}
}
return segmentArrayList.toArray(new String[0]);
}
} | alibaba/arthas | core/src/main/java/com/taobao/arthas/core/config/FeatureCodec.java |
1,053 | M
1528086917
tags: Linked List, Two Pointers
#### Linked List
- linked list 不能像partitioin array一样从两边遍历
- 把小于value的加在前半段, 把 >= value的加在后半段
- 做法很普通: 建造两个list, midTail pointer, post pointer
- 把满足条件(<x, >=x)的数字分别放到两个list里面
- 记得用dummyNode track head.
- 最终midTail.next = post链接起来。
```
/*
33% Accepted
Given a linked list and a value x,
partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2->null and x = 3,
return 1->2->2->4->3->5->null.
Example
Tags Expand
Linked List Two Pointers
*/
/*
Thinking process:
0. dummyPre, dummyPost to store the head of the 2 list
1. Append node.val < x to listPre
2. Append node.val >= x to listPost
3. Link them togeter
4. return dummyPre.next
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(0);
ListNode dummyPost = new ListNode(0);
ListNode midTail = dummy;
ListNode post = dummyPost;
while (head != null) {
if (head.val < x) {
midTail.next = head;
midTail = midTail.next;
} else {
post.next = head;
post = post.next;
}
head = head.next;
}
post.next = null;
midTail.next = dummyPost.next;
return dummy.next;
}
}
``` | awangdev/leet-code | Java/Partition List.java |
1,054 | package com.alibaba.otter.canal.parse.driver.mysql.packets;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import com.alibaba.otter.canal.parse.driver.mysql.utils.ByteHelper;
/**
* Created by hiwjd on 2018/4/23. [email protected]
*/
public class UUIDSet {
public UUID SID;
public List<Interval> intervals;
public byte[] encode() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(SID.getMostSignificantBits());
bb.putLong(SID.getLeastSignificantBits());
out.write(bb.array());
ByteHelper.writeUnsignedInt64LittleEndian(intervals.size(), out);
for (Interval interval : intervals) {
ByteHelper.writeUnsignedInt64LittleEndian(interval.start, out);
ByteHelper.writeUnsignedInt64LittleEndian(interval.stop, out);
}
return out.toByteArray();
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (this == o) return true;
UUIDSet us = (UUIDSet) o;
Collections.sort(intervals);
Collections.sort(us.intervals);
if (SID.equals(us.SID) && intervals.equals(us.intervals)) {
return true;
}
return false;
}
public static class Interval implements Comparable<Interval> {
public long start;
public long stop;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Interval interval = (Interval) o;
if (start != interval.start) return false;
return stop == interval.stop;
}
@Override
public int hashCode() {
int result = (int) (start ^ (start >>> 32));
result = 31 * result + (int) (stop ^ (stop >>> 32));
return result;
}
@Override
public int compareTo(Interval o) {
if (equals(o)) {
return 1;
}
return Long.compare(start, o.start);
}
}
/**
* 解析如下格式字符串为UUIDSet: 726757ad-4455-11e8-ae04-0242ac110002:1 => UUIDSet{SID:
* 726757ad-4455-11e8-ae04-0242ac110002, intervals: [{start:1, stop:2}]}
* 726757ad-4455-11e8-ae04-0242ac110002:1-3 => UUIDSet{SID:
* 726757ad-4455-11e8-ae04-0242ac110002, intervals: [{start:1, stop:4}]}
* 726757ad-4455-11e8-ae04-0242ac110002:1-3:4 UUIDSet{SID:
* 726757ad-4455-11e8-ae04-0242ac110002, intervals: [{start:1, stop:5}]}
* 726757ad-4455-11e8-ae04-0242ac110002:1-3:7-9 UUIDSet{SID:
* 726757ad-4455-11e8-ae04-0242ac110002, intervals: [{start:1, stop:4},
* {start:7, stop:10}]}
*
* @param str
* @return
*/
public static UUIDSet parse(String str) {
String[] ss = str.split(":");
if (ss.length < 2) {
throw new RuntimeException(String.format("parseUUIDSet failed due to wrong format: %s", str));
}
List<Interval> intervals = new ArrayList<>();
for (int i = 1; i < ss.length; i++) {
intervals.add(parseInterval(ss[i]));
}
UUIDSet uuidSet = new UUIDSet();
uuidSet.SID = UUID.fromString(ss[0]);
uuidSet.intervals = combine(intervals);
return uuidSet;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(SID.toString());
for (Interval interval : intervals) {
if (interval.start == interval.stop - 1) {
sb.append(":");
sb.append(interval.start);
} else {
sb.append(":");
sb.append(interval.start);
sb.append("-");
sb.append(interval.stop - 1);
}
}
return sb.toString();
}
/**
* 解析如下格式字符串为Interval: 1 => Interval{start:1, stop:2} 1-3 =>
* Interval{start:1, stop:4} 注意!字符串格式表达时[n,m]是两侧都包含的,Interval表达时[n,m)右侧开
*
* @param str
* @return
*/
public static Interval parseInterval(String str) {
String[] ss = str.split("-");
Interval interval = new Interval();
switch (ss.length) {
case 1:
interval.start = Long.parseLong(ss[0]);
interval.stop = interval.start + 1;
break;
case 2:
interval.start = Long.parseLong(ss[0]);
interval.stop = Long.parseLong(ss[1]) + 1;
break;
default:
throw new RuntimeException(String.format("parseInterval failed due to wrong format: %s", str));
}
return interval;
}
/**
* 把{start,stop}连续的合并掉: [{start:1, stop:4},{start:4, stop:5}] => [{start:1,
* stop:5}]
*
* @param intervals
* @return
*/
public static List<Interval> combine(List<Interval> intervals) {
List<Interval> combined = new ArrayList<>();
Collections.sort(intervals);
int len = intervals.size();
for (int i = 0; i < len; i++) {
combined.add(intervals.get(i));
int j;
for (j = i + 1; j < len; j++) {
if (intervals.get(i).stop >= intervals.get(j).start) {
intervals.get(i).stop = intervals.get(j).stop;
} else {
break;
}
}
i = j - 1;
}
return combined;
}
}
| alibaba/canal | driver/src/main/java/com/alibaba/otter/canal/parse/driver/mysql/packets/UUIDSet.java |
1,056 | /**
* File: array.java
* Created Time: 2022-11-25
* Author: krahets ([email protected])
*/
package chapter_array_and_linkedlist;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class array {
/* 随机访问元素 */
static int randomAccess(int[] nums) {
// 在区间 [0, nums.length) 中随机抽取一个数字
int randomIndex = ThreadLocalRandom.current().nextInt(0, nums.length);
// 获取并返回随机元素
int randomNum = nums[randomIndex];
return randomNum;
}
/* 扩展数组长度 */
static int[] extend(int[] nums, int enlarge) {
// 初始化一个扩展长度后的数组
int[] res = new int[nums.length + enlarge];
// 将原数组中的所有元素复制到新数组
for (int i = 0; i < nums.length; i++) {
res[i] = nums[i];
}
// 返回扩展后的新数组
return res;
}
/* 在数组的索引 index 处插入元素 num */
static void insert(int[] nums, int num, int index) {
// 把索引 index 以及之后的所有元素向后移动一位
for (int i = nums.length - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// 将 num 赋给 index 处的元素
nums[index] = num;
}
/* 删除索引 index 处的元素 */
static void remove(int[] nums, int index) {
// 把索引 index 之后的所有元素向前移动一位
for (int i = index; i < nums.length - 1; i++) {
nums[i] = nums[i + 1];
}
}
/* 遍历数组 */
static void traverse(int[] nums) {
int count = 0;
// 通过索引遍历数组
for (int i = 0; i < nums.length; i++) {
count += nums[i];
}
// 直接遍历数组元素
for (int num : nums) {
count += num;
}
}
/* 在数组中查找指定元素 */
static int find(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target)
return i;
}
return -1;
}
/* Driver Code */
public static void main(String[] args) {
/* 初始化数组 */
int[] arr = new int[5];
System.out.println("数组 arr = " + Arrays.toString(arr));
int[] nums = { 1, 3, 2, 5, 4 };
System.out.println("数组 nums = " + Arrays.toString(nums));
/* 随机访问 */
int randomNum = randomAccess(nums);
System.out.println("在 nums 中获取随机元素 " + randomNum);
/* 长度扩展 */
nums = extend(nums, 3);
System.out.println("将数组长度扩展至 8 ,得到 nums = " + Arrays.toString(nums));
/* 插入元素 */
insert(nums, 6, 3);
System.out.println("在索引 3 处插入数字 6 ,得到 nums = " + Arrays.toString(nums));
/* 删除元素 */
remove(nums, 2);
System.out.println("删除索引 2 处的元素,得到 nums = " + Arrays.toString(nums));
/* 遍历数组 */
traverse(nums);
/* 查找元素 */
int index = find(nums, 3);
System.out.println("在 nums 中查找元素 3 ,得到索引 = " + index);
}
}
| krahets/hello-algo | codes/java/chapter_array_and_linkedlist/array.java |
1,057 | package com.xkcoding.ldap.util;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* LdapUtils
*
* @author fxbin
* @version v1.0
* @since 2019-08-26 1:03
*/
public class LdapUtils {
/**
* 校验密码
*
* @param ldapPassword ldap 加密密码
* @param inputPassword 用户输入
* @return boolean
* @throws NoSuchAlgorithmException 加解密异常
*/
public static boolean verify(String ldapPassword, String inputPassword) throws NoSuchAlgorithmException {
// MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能,这里LDAP使用的是SHA-1
MessageDigest md = MessageDigest.getInstance("SHA-1");
// 取出加密字符
if (ldapPassword.startsWith("{SSHA}")) {
ldapPassword = ldapPassword.substring(6);
} else if (ldapPassword.startsWith("{SHA}")) {
ldapPassword = ldapPassword.substring(5);
}
// 解码BASE64
byte[] ldapPasswordByte = Base64.decode(ldapPassword);
byte[] shaCode;
byte[] salt;
// 前20位是SHA-1加密段,20位后是最初加密时的随机明文
if (ldapPasswordByte.length <= 20) {
shaCode = ldapPasswordByte;
salt = new byte[0];
} else {
shaCode = new byte[20];
salt = new byte[ldapPasswordByte.length - 20];
System.arraycopy(ldapPasswordByte, 0, shaCode, 0, 20);
System.arraycopy(ldapPasswordByte, 20, salt, 0, salt.length);
}
// 把用户输入的密码添加到摘要计算信息
md.update(inputPassword.getBytes());
// 把随机明文添加到摘要计算信息
md.update(salt);
// 按SSHA把当前用户密码进行计算
byte[] inputPasswordByte = md.digest();
// 返回校验结果
return MessageDigest.isEqual(shaCode, inputPasswordByte);
}
/**
* Ascii转换为字符串
*
* @param value Ascii串
* @return 字符串
*/
public static String asciiToString(String value) {
StringBuilder sbu = new StringBuilder();
String[] chars = value.split(",");
for (String aChar : chars) {
sbu.append((char) Integer.parseInt(aChar));
}
return sbu.toString();
}
}
| xkcoding/spring-boot-demo | demo-ldap/src/main/java/com/xkcoding/ldap/util/LdapUtils.java |
1,059 | package com.taobao.arthas.core.util.reflect;
import com.taobao.arthas.core.util.ArthasCheckUtils;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* 反射工具类 Created by vlinux on 15/5/18.
*/
public class ArthasReflectUtils {
/**
* 从包package中获取所有的Class
*
* @param packname 包名称
* @return 包路径下所有类集合
* <p>
* 代码摘抄自 http://www.oschina.net/code/snippet_129830_8767</p>
*/
public static Set<Class<?>> getClasses(final ClassLoader loader, final String packname) {
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
// 是否循环迭代
// 获取包的名字 并进行替换
String packageName = packname;
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try {
// dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
dirs = loader.getResources(packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
// System.err.println("file类型的扫描");
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath,
true, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
// System.err.println("jar类型的扫描");
JarFile jar;
try {
// 获取jar
jar = ((JarURLConnection) url.openConnection())
.getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx)
.replace('/', '.');
}
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class") && !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(
packageName.length() + 1,
name.length() - 6);
try {
// 添加到classes
classes.add(Class
.forName(packageName + '.'
+ className));
} catch (ClassNotFoundException e) {
// log
// .error("添加用户自定义视图类错误 找不到此类的.class文件");
// e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// log.error("在扫描用户定义视图时从jar包获取文件出错");
// e.printStackTrace();
}
}
}
} catch (IOException e) {
// e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
* <p/>
* <p>
* 代码摘抄自 http://www.oschina.net/code/snippet_129830_8767</p>
*/
private static void findAndAddClassesInPackageByFile(String packageName,
String packagePath, final boolean recursive, Set<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
@Override
public boolean accept(File file) {
return (recursive && file.isDirectory())
|| (file.getName().endsWith(".class"));
}
});
if (dirfiles != null) {
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(
packageName + "." + file.getName(),
file.getAbsolutePath(), recursive, classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0,
file.getName().length() - 6);
try {
// 添加到集合中去
// classes.add(Class.forName(packageName + '.' +
// className));
// 经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净
classes.add(Thread.currentThread().getContextClassLoader()
.loadClass(packageName + '.' + className));
} catch (ClassNotFoundException e) {
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
// e.printStackTrace();
}
}
}
}
}
/**
* 设置对象某个成员的值
*
* @param field 属性对象
* @param value 属性值
* @param target 目标对象
* @throws IllegalArgumentException 非法参数
* @throws IllegalAccessException 非法进入
*/
public static void set(Field field, Object value, Object target) throws IllegalArgumentException, IllegalAccessException {
final boolean isAccessible = field.isAccessible();
try {
field.setAccessible(true);
field.set(target, value);
} finally {
field.setAccessible(isAccessible);
}
}
/**
* 获取一个类下的所有成员(包括父类、私有成员)
*
* @param clazz 目标类
* @return 类下所有属性
*/
public static Set<Field> getFields(Class<?> clazz) {
final Set<Field> fields = new LinkedHashSet<Field>();
final Class<?> parentClazz = clazz.getSuperclass();
Collections.addAll(fields, clazz.getDeclaredFields());
if (null != parentClazz) {
fields.addAll(getFields(parentClazz));
}
return fields;
}
/**
* 获取一个类下的指定成员
*
* @param clazz 目标类
* @param name 属性名
* @return 属性
*/
public static Field getField(Class<?> clazz, String name) {
for (Field field : getFields(clazz)) {
if (ArthasCheckUtils.isEquals(field.getName(), name)) {
return field;
}
}//for
return null;
}
/**
* 获取对象某个成员的值
*
* @param <T>
* @param target 目标对象
* @param field 目标属性
* @return 目标属性值
* @throws IllegalArgumentException 非法参数
* @throws IllegalAccessException 非法进入
*/
public static <T> T getFieldValueByField(Object target, Field field) throws IllegalArgumentException, IllegalAccessException {
final boolean isAccessible = field.isAccessible();
try {
field.setAccessible(true);
//noinspection unchecked
return (T) field.get(target);
} finally {
field.setAccessible(isAccessible);
}
}
/**
* 将字符串转换为指定类型,目前只支持9种类型:8种基本类型(包括其包装类)以及字符串
*
* @param t 目标对象类型
* @param value 目标值
* @return 类型转换后的值
*/
@SuppressWarnings("unchecked")
public static <T> T valueOf(Class<T> t, String value) {
if (ArthasCheckUtils.isIn(t, int.class, Integer.class)) {
return (T) Integer.valueOf(value);
} else if (ArthasCheckUtils.isIn(t, long.class, Long.class)) {
return (T) Long.valueOf(value);
} else if (ArthasCheckUtils.isIn(t, double.class, Double.class)) {
return (T) Double.valueOf(value);
} else if (ArthasCheckUtils.isIn(t, float.class, Float.class)) {
return (T) Float.valueOf(value);
} else if (ArthasCheckUtils.isIn(t, char.class, Character.class)) {
return (T) Character.valueOf(value.charAt(0));
} else if (ArthasCheckUtils.isIn(t, byte.class, Byte.class)) {
return (T) Byte.valueOf(value);
} else if (ArthasCheckUtils.isIn(t, boolean.class, Boolean.class)) {
return (T) Boolean.valueOf(value);
} else if (ArthasCheckUtils.isIn(t, short.class, Short.class)) {
return (T) Short.valueOf(value);
} else if (ArthasCheckUtils.isIn(t, String.class)) {
return (T) value;
} else {
return null;
}
}
/**
* 定义类
*
* @param targetClassLoader 目标classloader
* @param className 类名称
* @param classByteArray 类字节码数组
* @return 定义的类
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static Class<?> defineClass(
final ClassLoader targetClassLoader,
final String className,
final byte[] classByteArray) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
final Method defineClassMethod = ClassLoader.class.getDeclaredMethod(
"defineClass",
String.class,
byte[].class,
int.class,
int.class
);
synchronized (defineClassMethod) {
final boolean acc = defineClassMethod.isAccessible();
try {
defineClassMethod.setAccessible(true);
return (Class<?>) defineClassMethod.invoke(
targetClassLoader,
className,
classByteArray,
0,
classByteArray.length
);
} finally {
defineClassMethod.setAccessible(acc);
}
}
}
}
| alibaba/arthas | core/src/main/java/com/taobao/arthas/core/util/reflect/ArthasReflectUtils.java |
1,060 | package cn.hutool.core.util;
/**
* 进制转换工具类,可以转换为任意进制
* <p>
* 把一个十进制整数根据自己定义的进制规则进行转换<br>
* from:https://gitee.com/loolly/hutool/pulls/260
* <p>
* 主要应用一下情况:
* <ul>
* <li>根据ID生成邀请码,并且尽可能的缩短。并且不希望直接猜测出和ID的关联</li>
* <li>短连接的生成,根据ID转成短连接,同样不希望被猜测到</li>
* <li>数字加密,通过两次不同进制的转换,让有规律的数字看起来没有任何规律</li>
* <li>....</li>
* </ul>
*
* @author [email protected]
* @since 5.5.8
*/
public class RadixUtil {
/**
* 34进制字符串,不包含 IO 字符
* 对于需要补齐的,自己可以随机填充IO字符
* 26个字母:abcdefghijklmnopqrstuvwxyz
*/
public final static String RADIXS_34 = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
/**
* 打乱后的34进制
*/
public final static String RADIXS_SHUFFLE_34 = "H3UM16TDFPSBZJ90CW28QYRE45AXKNGV7L";
/**
* 59进制字符串,不包含 IOl 字符
*/
public final static String RADIXS_59 = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
/**
* 打乱后的59进制
*/
public final static String RADIXS_SHUFFLE_59 = "vh9wGkfK8YmqbsoENP3764SeCX0dVzrgy1HRtpnTaLjJW2xQiZAcBMUFDu5";
/**
* 把一个整型数值转换成自己定义的进制
* 长度即进制<br>
* <ul>
* <li>encode("AB",10) 51转换成2进制,A=0;B=1 。 二进制1010,结果 BABA</li>
* <li>encode("VIP",21) 21转换成3进制,V=0;I=1;P=2 ,三进制210 ,得到结果PIV </li>
* </ul>
*
* @param radixs 自定进制,不要重复,否则转不回来的。
* @param num 要转换的数值
* @return 自定义进制字符串
*/
public static String encode(String radixs, int num) {
//考虑到负数问题
long tmpNum = (num >= 0 ? num : (0x100000000L - (~num + 1)));
return encode(radixs, tmpNum, 32);
}
/**
* 把一个长整型数值转换成自己定义的进制
*
* @param radixs 自定进制,不要重复,否则转不回来的。
* @param num 要转换的数值
* @return 自定义进制字符串
*/
public static String encode(String radixs, long num) {
if (num < 0) {
throw new RuntimeException("暂不支持负数!");
}
return encode(radixs, num, 64);
}
/**
* 把转换后的进制字符还原成int 值
*
* @param radixs 自定进制,需要和encode的保持一致
* @param encodeStr 需要转换成十进制的字符串
* @return int
*/
public static int decodeToInt(String radixs, String encodeStr) {
//还原负数
return (int) decode(radixs, encodeStr);
}
/**
* 把转换后进制的字符还原成long 值
*
* @param radixs 自定进制,需要和encode的保持一致
* @param encodeStr 需要转换成十进制的字符串
* @return long
*/
public static long decode(String radixs, String encodeStr) {
//目标是多少进制
int rl = radixs.length();
long res = 0L;
for (char c : encodeStr.toCharArray()) {
res = res * rl + radixs.indexOf(c);
}
return res;
}
// -------------------------------------------------------------------------------- Private methods
private static String encode(String radixs, long num, int maxLength) {
if (radixs.length() < 2) {
throw new RuntimeException("自定义进制最少两个字符哦!");
}
//目标是多少进制
int rl = radixs.length();
//考虑到负数问题
long tmpNum = num;
//进制的结果,二进制最小进制转换结果是32个字符
//StringBuilder 比较耗时
char[] aa = new char[maxLength];
//因为反需字符串比较耗时
int i = aa.length;
do {
aa[--i] = radixs.charAt((int) (tmpNum % rl));
tmpNum /= rl;
} while (tmpNum > 0);
//去掉前面的字符串,trim比较耗时
return new String(aa, i, aa.length - i);
}
}
| dromara/hutool | hutool-core/src/main/java/cn/hutool/core/util/RadixUtil.java |
1,062 | /*
* Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.net.mysql;
import java.nio.ByteBuffer;
import io.mycat.net.BackendAIOConnection;
import io.mycat.net.FrontendConnection;
/**
* @author mycat
*/
public abstract class MySQLPacket {
/**
* none, this is an internal thread state
*/
public static final byte COM_SLEEP = 0;
/**
* mysql_close
*/
public static final byte COM_QUIT = 1;
/**
* mysql_select_db
*/
public static final byte COM_INIT_DB = 2;
/**
* mysql_real_query
*/
public static final byte COM_QUERY = 3;
/**
* mysql_list_fields
*/
public static final byte COM_FIELD_LIST = 4;
/**
* mysql_create_db (deprecated)
*/
public static final byte COM_CREATE_DB = 5;
/**
* mysql_drop_db (deprecated)
*/
public static final byte COM_DROP_DB = 6;
/**
* mysql_refresh
*/
public static final byte COM_REFRESH = 7;
/**
* mysql_shutdown
*/
public static final byte COM_SHUTDOWN = 8;
/**
* mysql_stat
*/
public static final byte COM_STATISTICS = 9;
/**
* mysql_list_processes
*/
public static final byte COM_PROCESS_INFO = 10;
/**
* none, this is an internal thread state
*/
public static final byte COM_CONNECT = 11;
/**
* mysql_kill
*/
public static final byte COM_PROCESS_KILL = 12;
/**
* mysql_dump_debug_info
*/
public static final byte COM_DEBUG = 13;
/**
* mysql_ping
*/
public static final byte COM_PING = 14;
/**
* none, this is an internal thread state
*/
public static final byte COM_TIME = 15;
/**
* none, this is an internal thread state
*/
public static final byte COM_DELAYED_INSERT = 16;
/**
* mysql_change_user
*/
public static final byte COM_CHANGE_USER = 17;
/**
* used by slave server mysqlbinlog
*/
public static final byte COM_BINLOG_DUMP = 18;
/**
* used by slave server to get master table
*/
public static final byte COM_TABLE_DUMP = 19;
/**
* used by slave to log connection to master
*/
public static final byte COM_CONNECT_OUT = 20;
/**
* used by slave to register to master
*/
public static final byte COM_REGISTER_SLAVE = 21;
/**
* mysql_stmt_prepare
*/
public static final byte COM_STMT_PREPARE = 22;
/**
* mysql_stmt_execute
*/
public static final byte COM_STMT_EXECUTE = 23;
/**
* mysql_stmt_send_long_data
*/
public static final byte COM_STMT_SEND_LONG_DATA = 24;
/**
* mysql_stmt_close
*/
public static final byte COM_STMT_CLOSE = 25;
/**
* mysql_stmt_reset
*/
public static final byte COM_STMT_RESET = 26;
/**
* mysql_set_server_option
*/
public static final byte COM_SET_OPTION = 27;
/**
* mysql_stmt_fetch
*/
public static final byte COM_STMT_FETCH = 28;
/**
* mysql_reset_connection
*/
public static final byte COM_RESET_CONNECTION = 31;
/**
* Mycat heartbeat
*/
public static final byte COM_HEARTBEAT = 64;
//包头大小
public static final int packetHeaderSize = 4;
public int packetLength;
public byte packetId;
/**
* 把数据包写到buffer中,如果buffer满了就把buffer通过前端连接写出 (writeSocketIfFull=true)。
*/
public ByteBuffer write(ByteBuffer buffer, FrontendConnection c,boolean writeSocketIfFull) {
throw new UnsupportedOperationException();
}
/**
* 把数据包通过后端连接写出,一般使用buffer机制来提高写的吞吐量。
*/
public void write(BackendAIOConnection c) {
throw new UnsupportedOperationException();
}
/**
* 计算数据包大小,不包含包头长度。
*/
public abstract int calcPacketSize();
/**
* 取得数据包信息
*/
protected abstract String getPacketInfo();
@Override
public String toString() {
return new StringBuilder().append(getPacketInfo()).append("{length=").append(packetLength).append(",id=")
.append(packetId).append('}').toString();
}
} | MyCATApache/Mycat-Server | src/main/java/io/mycat/net/mysql/MySQLPacket.java |
1,064 | import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author Anonymous
* @since 2019/11/23
*/
/*
* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right =
* null;
*
* public TreeNode(int val) { this.val = val;
*
* }
*
* }
*/
public class Solution {
/**
* 把二叉树打印成多行
*
* @param pRoot 二叉树根节点
* @return 结果list
*/
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
if (pRoot == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(pRoot);
int cnt = 1;
while (cnt > 0) {
int num = cnt;
cnt = 0;
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < num; ++i) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
++cnt;
}
if (node.right != null) {
queue.offer(node.right);
++cnt;
}
res.add(node.val);
}
list.add(res);
}
return list;
}
} | geekxh/hello-algorithm | 算法读物/剑指offer/32_02_PrintTreesInLines/Solution.java |
1,066 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cn.itcast_01;
/**
*
* @author fqy
*/
public class OperatorJFrame extends javax.swing.JFrame {
/**
* Creates new form OperatorJFrame
*/
public OperatorJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
firstNumber = new javax.swing.JTextField();
choiceOperator = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
secondNumber = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
resultNumber = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jiSuanButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("第一个操作数");
choiceOperator.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "+", "-", "*", "/" }));
jLabel2.setText("第二个操作数");
jLabel3.setText("=");
jLabel4.setText("结果");
jiSuanButton.setText("计算");
jiSuanButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jiSuanButtonMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(firstNumber))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(choiceOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(secondNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jiSuanButton)
.addComponent(resultNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(firstNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(choiceOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(secondNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(resultNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jiSuanButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jiSuanButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jiSuanButtonMouseClicked
/*
思路:
1:获取操作数和运算符
2:根据运算符,进行相应的运算
3:把运算的结果赋值给最后一个文本框
*/
String firstNumberString = this.firstNumber.getText();
String operatorString = String.valueOf(this.choiceOperator.getSelectedItem());
String secondNumberString = this.secondNumber.getText();
// System.out.println("firstNumberString:" + firstNumberString);
// System.out.println("operatorString:" + operatorString);
// System.out.println("secondNumberString:" + secondNumberString);
//把字符串转换为数据类型
int firstNumber = Integer.parseInt(firstNumberString);
int secondNumber = Integer.parseInt(secondNumberString);
//定义变量,用于保存运算的结果
int result = 0;
switch (operatorString) {
case "+":
result = firstNumber + secondNumber;
break;
case "-":
result = firstNumber - secondNumber;
break;
case "*":
result = firstNumber * secondNumber;
break;
case "/":
result = firstNumber / secondNumber;
break;
}
//把运算的结果赋值给最后一个文本框
this.resultNumber.setText(String.valueOf(result));
}//GEN-LAST:event_jiSuanButtonMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OperatorJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OperatorJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox choiceOperator;
private javax.swing.JTextField firstNumber;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JButton jiSuanButton;
private javax.swing.JTextField resultNumber;
private javax.swing.JTextField secondNumber;
// End of variables declaration//GEN-END:variables
}
| DuGuQiuBai/Java | day25/code/四则运算/src/cn/itcast_01/OperatorJFrame.java |
1,067 | /**
* IK 中文分词 版本 5.0
* IK Analyzer release 5.0
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 源代码由林良益([email protected])提供
* 版权声明 2012,乌龙茶工作室
* provided by Linliangyi and copyright 2012 by Oolong studio
*
*/
package org.wltea.analyzer.core;
import java.util.Stack;
import java.util.TreeSet;
/**
* IK分词歧义裁决器
*/
class IKArbitrator {
IKArbitrator(){
}
/**
* 分词歧义处理
// * @param orgLexemes
* @param useSmart
*/
void process(AnalyzeContext context , boolean useSmart){
QuickSortSet orgLexemes = context.getOrgLexemes();
Lexeme orgLexeme = orgLexemes.pollFirst();
LexemePath crossPath = new LexemePath();
while(orgLexeme != null){
if(!crossPath.addCrossLexeme(orgLexeme)){
//找到与crossPath不相交的下一个crossPath
if(crossPath.size() == 1 || !useSmart){
//crossPath没有歧义 或者 不做歧义处理
//直接输出当前crossPath
context.addLexemePath(crossPath);
}else{
//对当前的crossPath进行歧义处理
QuickSortSet.Cell headCell = crossPath.getHead();
LexemePath judgeResult = this.judge(headCell, crossPath.getPathLength());
//输出歧义处理结果judgeResult
context.addLexemePath(judgeResult);
}
//把orgLexeme加入新的crossPath中
crossPath = new LexemePath();
crossPath.addCrossLexeme(orgLexeme);
}
orgLexeme = orgLexemes.pollFirst();
}
//处理最后的path
if(crossPath.size() == 1 || !useSmart){
//crossPath没有歧义 或者 不做歧义处理
//直接输出当前crossPath
context.addLexemePath(crossPath);
}else{
//对当前的crossPath进行歧义处理
QuickSortSet.Cell headCell = crossPath.getHead();
LexemePath judgeResult = this.judge(headCell, crossPath.getPathLength());
//输出歧义处理结果judgeResult
context.addLexemePath(judgeResult);
}
}
/**
* 歧义识别
* @param lexemeCell 歧义路径链表头
* @param fullTextLength 歧义路径文本长度
* @return
*/
private LexemePath judge(QuickSortSet.Cell lexemeCell , int fullTextLength){
//候选路径集合
TreeSet<LexemePath> pathOptions = new TreeSet<LexemePath>();
//候选结果路径
LexemePath option = new LexemePath();
//对crossPath进行一次遍历,同时返回本次遍历中有冲突的Lexeme栈
Stack<QuickSortSet.Cell> lexemeStack = this.forwardPath(lexemeCell , option);
//当前词元链并非最理想的,加入候选路径集合
pathOptions.add(option.copy());
//存在歧义词,处理
QuickSortSet.Cell c = null;
while(!lexemeStack.isEmpty()){
c = lexemeStack.pop();
//回滚词元链
this.backPath(c.getLexeme() , option);
//从歧义词位置开始,递归,生成可选方案
this.forwardPath(c , option);
pathOptions.add(option.copy());
}
//返回集合中的最优方案
return pathOptions.first();
}
/**
* 向前遍历,添加词元,构造一个无歧义词元组合
// * @param LexemePath path
* @return
*/
private Stack<QuickSortSet.Cell> forwardPath(QuickSortSet.Cell lexemeCell , LexemePath option){
//发生冲突的Lexeme栈
Stack<QuickSortSet.Cell> conflictStack = new Stack<QuickSortSet.Cell>();
QuickSortSet.Cell c = lexemeCell;
//迭代遍历Lexeme链表
while(c != null && c.getLexeme() != null){
if(!option.addNotCrossLexeme(c.getLexeme())){
//词元交叉,添加失败则加入lexemeStack栈
conflictStack.push(c);
}
c = c.getNext();
}
return conflictStack;
}
/**
* 回滚词元链,直到它能够接受指定的词元
// * @param lexeme
* @param l
*/
private void backPath(Lexeme l , LexemePath option){
while(option.checkCross(l)){
option.removeTail();
}
}
}
| infinilabs/analysis-ik | core/src/main/java/org/wltea/analyzer/core/IKArbitrator.java |
1,068 | package me.zhyd.oauth.utils;
import com.alibaba.fastjson.JSON;
import me.zhyd.oauth.exception.AuthException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* 全局的工具类
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @since 1.0.0
*/
public class GlobalAuthUtils {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
private static final String HMAC_SHA1 = "HmacSHA1";
private static final String HMAC_SHA_256 = "HmacSHA256";
/**
* 生成钉钉请求的Signature
*
* @param secretKey 平台应用的授权密钥
* @param timestamp 时间戳
* @return Signature
*/
public static String generateDingTalkSignature(String secretKey, String timestamp) {
byte[] signData = sign(secretKey.getBytes(DEFAULT_ENCODING), timestamp.getBytes(DEFAULT_ENCODING), HMAC_SHA_256);
return urlEncode(new String(Base64Utils.encode(signData, false)));
}
/**
* 签名
*
* @param key key
* @param data data
* @param algorithm algorithm
* @return byte[]
*/
private static byte[] sign(byte[] key, byte[] data, String algorithm) {
try {
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(key, algorithm));
return mac.doFinal(data);
} catch (NoSuchAlgorithmException ex) {
throw new AuthException("Unsupported algorithm: " + algorithm, ex);
} catch (InvalidKeyException ex) {
throw new AuthException("Invalid key: " + Arrays.toString(key), ex);
}
}
/**
* 编码
*
* @param value str
* @return encode str
*/
public static String urlEncode(String value) {
if (value == null) {
return "";
}
try {
String encoded = URLEncoder.encode(value, GlobalAuthUtils.DEFAULT_ENCODING.displayName());
return encoded.replace("+", "%20").replace("*", "%2A").replace("~", "%7E").replace("/", "%2F");
} catch (UnsupportedEncodingException e) {
throw new AuthException("Failed To Encode Uri", e);
}
}
/**
* 解码
*
* @param value str
* @return decode str
*/
public static String urlDecode(String value) {
if (value == null) {
return "";
}
try {
return URLDecoder.decode(value, GlobalAuthUtils.DEFAULT_ENCODING.displayName());
} catch (UnsupportedEncodingException e) {
throw new AuthException("Failed To Decode Uri", e);
}
}
/**
* string字符串转map,str格式为 {@code xxx=xxx&xxx=xxx}
*
* @param accessTokenStr 待转换的字符串
* @return map
*/
public static Map<String, String> parseStringToMap(String accessTokenStr) {
Map<String, String> res = null;
if (accessTokenStr.contains("&")) {
String[] fields = accessTokenStr.split("&");
res = new HashMap<>((int) (fields.length / 0.75 + 1));
for (String field : fields) {
if (field.contains("=")) {
String[] keyValue = field.split("=");
res.put(GlobalAuthUtils.urlDecode(keyValue[0]), keyValue.length == 2 ? GlobalAuthUtils.urlDecode(keyValue[1]) : null);
}
}
} else {
res = new HashMap<>(0);
}
return res;
}
/**
* map转字符串,转换后的字符串格式为 {@code xxx=xxx&xxx=xxx}
*
* @param params 待转换的map
* @param encode 是否转码
* @return str
*/
public static String parseMapToString(Map<String, String> params, boolean encode) {
if (null == params || params.isEmpty()) {
return "";
}
List<String> paramList = new ArrayList<>();
params.forEach((k, v) -> {
if (null == v) {
paramList.add(k + "=");
} else {
paramList.add(k + "=" + (encode ? urlEncode(v) : v));
}
});
return String.join("&", paramList);
}
/**
* 是否为http协议
*
* @param url 待验证的url
* @return true: http协议, false: 非http协议
*/
public static boolean isHttpProtocol(String url) {
if (StringUtils.isEmpty(url)) {
return false;
}
return url.startsWith("http://") || url.startsWith("http%3A%2F%2F");
}
/**
* 是否为https协议
*
* @param url 待验证的url
* @return true: https协议, false: 非https协议
*/
public static boolean isHttpsProtocol(String url) {
if (StringUtils.isEmpty(url)) {
return false;
}
return url.startsWith("https://") || url.startsWith("https%3A%2F%2F");
}
/**
* 是否为本地主机(域名)
*
* @param url 待验证的url
* @return true: 本地主机(域名), false: 非本地主机(域名)
*/
public static boolean isLocalHost(String url) {
return StringUtils.isEmpty(url) || url.contains("127.0.0.1") || url.contains("localhost");
}
/**
* 是否为https协议或本地主机(域名)
*
* @param url 待验证的url
* @return true: https协议或本地主机 false: 非https协议或本机主机
*/
public static boolean isHttpsProtocolOrLocalHost(String url) {
if (StringUtils.isEmpty(url)) {
return false;
}
return isHttpsProtocol(url) || isLocalHost(url);
}
/**
* Generate nonce with given length
*
* @param len length
* @return nonce string
*/
public static String generateNonce(int len) {
String s = "0123456789QWERTYUIOPLKJHGFDSAZXCVBNMqwertyuioplkjhgfdsazxcvbnm";
Random rng = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
int index = rng.nextInt(62);
sb.append(s, index, index + 1);
}
return sb.toString();
}
/**
* Get current timestamp
*
* @return timestamp string
*/
public static String getTimestamp() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
/**
* Generate Twitter signature
* https://developer.twitter.com/en/docs/basics/authentication/guides/creating-a-signature
*
* @param params parameters including: oauth headers, query params, body params
* @param method HTTP method
* @param baseUrl base url
* @param apiSecret api key secret can be found in the developer portal by viewing the app details page
* @param tokenSecret oauth token secret
* @return BASE64 encoded signature string
*/
public static String generateTwitterSignature(Map<String, String> params, String method, String baseUrl, String apiSecret, String tokenSecret) {
TreeMap<String, String> map = new TreeMap<>(params);
String str = parseMapToString(map, true);
String baseStr = method.toUpperCase() + "&" + urlEncode(baseUrl) + "&" + urlEncode(str);
String signKey = apiSecret + "&" + (StringUtils.isEmpty(tokenSecret) ? "" : tokenSecret);
byte[] signature = sign(signKey.getBytes(DEFAULT_ENCODING), baseStr.getBytes(DEFAULT_ENCODING), HMAC_SHA1);
return new String(Base64Utils.encode(signature, false));
}
/**
* 喜马拉雅签名算法
* {@code https://open.ximalaya.com/doc/detailApi?categoryId=6&articleId=69}
*
* @param params 加密参数
* @param clientSecret 平台应用的授权key
* @return Signature
* @since 1.15.9
*/
public static String generateXmlySignature(Map<String, String> params, String clientSecret) {
TreeMap<String, String> map = new TreeMap<>(params);
String baseStr = Base64Utils.encode(parseMapToString(map, false));
byte[] sign = sign(clientSecret.getBytes(DEFAULT_ENCODING), baseStr.getBytes(DEFAULT_ENCODING), HMAC_SHA1);
MessageDigest md5 = null;
StringBuilder builder = null;
try {
builder = new StringBuilder();
md5 = MessageDigest.getInstance("MD5");
md5.update(sign);
byte[] byteData = md5.digest();
for (byte byteDatum : byteData) {
builder.append(Integer.toString((byteDatum & 0xff) + 0x100, 16).substring(1));
}
} catch (Exception ignored) {
}
return null == builder ? "" : builder.toString();
}
/**
* 生成饿了么请求的Signature
* <p>
* 代码copy并修改自:https://coding.net/u/napos_openapi/p/eleme-openapi-java-sdk/git/blob/master/src/main/java/eleme/openapi/sdk/utils/SignatureUtil.java
*
* @param appKey 平台应用的授权key
* @param secret 平台应用的授权密钥
* @param timestamp 时间戳,单位秒。API服务端允许客户端请求最大时间误差为正负5分钟。
* @param action 饿了么请求的api方法
* @param token 用户授权的token
* @param parameters 加密参数
* @return Signature
*/
public static String generateElemeSignature(String appKey, String secret, long timestamp, String action, String token, Map<String, Object> parameters) {
final Map<String, Object> sorted = new TreeMap<>(parameters);
sorted.put("app_key", appKey);
sorted.put("timestamp", timestamp);
StringBuffer string = new StringBuffer();
for (Map.Entry<String, Object> entry : sorted.entrySet()) {
string.append(entry.getKey()).append("=").append(JSON.toJSONString(entry.getValue()));
}
String splice = String.format("%s%s%s%s", action, token, string, secret);
String calculatedSignature = md5(splice);
return calculatedSignature.toUpperCase();
}
/**
* MD5加密
* <p>
* 代码copy并修改自:https://coding.net/u/napos_openapi/p/eleme-openapi-java-sdk/git/blob/master/src/main/java/eleme/openapi/sdk/utils/SignatureUtil.java
*
* @param str 待加密的字符串
* @return md5 str
*/
public static String md5(String str) {
MessageDigest md = null;
StringBuilder buffer = null;
try {
md = MessageDigest.getInstance("MD5");
md.update(str.getBytes(StandardCharsets.UTF_8));
byte[] byteData = md.digest();
buffer = new StringBuilder();
for (byte byteDatum : byteData) {
buffer.append(Integer.toString((byteDatum & 0xff) + 0x100, 16).substring(1));
}
} catch (Exception ignored) {
}
return null == buffer ? "" : buffer.toString();
}
/**
* 生成京东宙斯平台的签名字符串
* 宙斯签名规则过程如下:
* 将所有请求参数按照字母先后顺序排列,例如将access_token,app_key,method,timestamp,v 排序为access_token,app_key,method,timestamp,v
* 1.把所有参数名和参数值进行拼接,例如:access_tokenxxxapp_keyxxxmethodxxxxxxtimestampxxxxxxvx
* 2.把appSecret夹在字符串的两端,例如:appSecret+XXXX+appSecret
* 3.使用MD5进行加密,再转化成大写
* link: http://open.jd.com/home/home#/doc/common?listId=890
* link: https://github.com/pingjiang/jd-open-api-sdk-src/blob/master/src/main/java/com/jd/open/api/sdk/DefaultJdClient.java
*
* @param appSecret 京东应用密钥
* @param params 签名参数
* @return 签名后的字符串
* @since 1.15.0
*/
public static String generateJdSignature(String appSecret, Map<String, Object> params) {
Map<String, Object> treeMap = new TreeMap<>(params);
StringBuilder signBuilder = new StringBuilder(appSecret);
for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
String name = entry.getKey();
String value = String.valueOf(entry.getValue());
if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(value)) {
signBuilder.append(name).append(value);
}
}
signBuilder.append(appSecret);
return md5(signBuilder.toString()).toUpperCase();
}
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/utils/GlobalAuthUtils.java |
1,069 | package org.nutz.lang;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.nutz.lang.util.Regex;
/**
* 一些时间相关的帮助函数
*
* @author zozoh([email protected])
*/
public abstract class Times {
private static final Pattern _p_tm = Pattern.compile("^([0-9]{1,2}):([0-9]{1,2})(:([0-9]{1,2})([.,]([0-9]{1,3}))?)?$");
/**
* 判断一年是否为闰年,如果给定年份小于1全部为 false
*
* @param year
* 年份,比如 2012 就是二零一二年
* @return 给定年份是否是闰年
*/
public static boolean leapYear(int year) {
if (year < 4) {
return false;
}
return (year % 400 == 0) || (year % 100 != 0 && year % 4 == 0);
}
/**
* 判断某年(不包括自己)之前有多少个闰年
*
* @param year
* 年份,比如 2012 就是二零一二年
* @return 闰年的个数
*/
public static int countLeapYear(int year) {
// 因为要计算年份到公元元年(0001年)的年份跨度,所以减去1
int span = year - 1;
return (span / 4) - (span / 100) + (span / 400);
}
/**
* 将一个秒数(天中),转换成一个如下格式的数组:
*
* <pre>
* [0-23][0-59[-059]
* </pre>
*
* @param sec
* 秒数
* @return 时分秒的数组
*/
public static int[] T(int sec) {
TmInfo ti = Ti(sec);
return Nums.array(ti.hour, ti.minute, ti.second);
}
/**
* 将一个时间字符串,转换成一个一天中的绝对秒数
*
* @param ts
* 时间字符串,符合格式 "HH:mm:ss" 或者 "HH:mm"
* @return 一天中的绝对秒数
*/
public static int T(String ts) {
return Ti(ts).value;
}
/**
* 将一个秒数(天中),转换成一个时间对象:
*
* @param sec
* 秒数
* @return 时间对象
*/
public static TmInfo Ti(int sec) {
TmInfo ti = new TmInfo();
ti.valueInMillisecond = sec * 1000;
ti.__recound_by_valueInMilliSecond();
return ti;
}
/**
* 将一个毫秒数(天中),转换成一个时间对象:
*
* @param ams
* 毫秒数
* @return 时间对象
*/
public static TmInfo Tims(long ams) {
TmInfo ti = new TmInfo();
ti.valueInMillisecond = (int) ams;
ti.__recound_by_valueInMilliSecond();
return ti;
}
/**
* 将一个时间字符串,转换成一个一天中的绝对时间对象
*
* @param ts
* 时间字符串,符合格式
* <ul>
* <li>"HH:mm:ss"
* <li>"HH:mm"
* <li>"HH:mm:ss.SSS"
* <li>"HH:mm:ss,SSS"
* </ul>
* @return 时间对象
*/
public static TmInfo Ti(String ts) {
Matcher m = _p_tm.matcher(ts);
if (m.find()) {
TmInfo ti = new TmInfo();
// 仅仅到分钟
if (null == m.group(3)) {
ti.hour = Integer.parseInt(m.group(1));
ti.minute = Integer.parseInt(m.group(2));
ti.second = 0;
ti.millisecond = 0;
}
// 到秒
else if (null == m.group(5)) {
ti.hour = Integer.parseInt(m.group(1));
ti.minute = Integer.parseInt(m.group(2));
ti.second = Integer.parseInt(m.group(4));
ti.millisecond = 0;
}
// 到毫秒
else {
ti.hour = Integer.parseInt(m.group(1));
ti.minute = Integer.parseInt(m.group(2));
ti.second = Integer.parseInt(m.group(4));
ti.millisecond = Integer.parseInt(m.group(6));
}
// 计算其他的值
ti.value = ti.hour * 3600 + ti.minute * 60 + ti.second;
ti.valueInMillisecond = ti.value * 1000 + ti.millisecond;
// 返回
return ti;
}
throw Lang.makeThrow("Wrong format of time string '%s'", ts);
}
/**
* 描述了一个时间(一天内)的结构信息
*/
public static class TmInfo {
public int value;
public int valueInMillisecond;
public int hour;
public int minute;
public int second;
public int millisecond;
public void offset(int sec) {
this.valueInMillisecond += sec * 1000;
this.__recound_by_valueInMilliSecond();
}
public void offsetInMillisecond(int ms) {
this.valueInMillisecond += ms;
this.__recound_by_valueInMilliSecond();
}
private void __recound_by_valueInMilliSecond() {
// 确保毫秒数在一天之内,即 [0, 86399000]
if (this.valueInMillisecond >= 86400000) {
this.valueInMillisecond = this.valueInMillisecond % 86400000;
}
// 负数表示后退
else if (this.valueInMillisecond < 0) {
this.valueInMillisecond = this.valueInMillisecond % 86400000;
if (this.valueInMillisecond < 0) {
this.valueInMillisecond = 86400000 + this.valueInMillisecond;
}
}
// 计算其他值
this.value = this.valueInMillisecond / 1000;
this.millisecond = this.valueInMillisecond - this.value * 1000;
this.hour = Math.min(23, this.value / 3600);
this.minute = Math.min(59, (this.value - (this.hour * 3600)) / 60);
this.second = Math.min(59, this.value - (this.hour * 3600) - (this.minute * 60));
}
@Override
public String toString() {
String fmt = "HH:mm";
// 到毫秒
if (0 != this.millisecond) {
fmt += ":ss.SSS";
}
// 到秒
else if (0 != this.second) {
fmt += ":ss";
}
return toString(fmt);
}
private static Pattern _p_tmfmt = Pattern.compile("a|[HhKkms]{1,2}|S(SS)?");
/**
* <pre>
* a Am/pm marker (AM/PM)
* H Hour in day (0-23)
* k Hour in day (1-24)
* K Hour in am/pm (0-11)
* h Hour in am/pm (1-12)
* m Minute in hour
* s Second in minute
* S Millisecond Number
* HH 补零的小时(0-23)
* kk 补零的小时(1-24)
* KK 补零的半天小时(0-11)
* hh 补零的半天小时(1-12)
* mm 补零的分钟
* ss 补零的秒
* SSS 补零的毫秒
* </pre>
*
* @param fmt
* 格式化字符串类似 <code>"HH:mm:ss,SSS"</code>
* @return 格式化后的时间
*/
public String toString(String fmt) {
StringBuilder sb = new StringBuilder();
fmt = Strings.sBlank(fmt, "HH:mm:ss");
Matcher m = _p_tmfmt.matcher(fmt);
int pos = 0;
while (m.find()) {
int l = m.start();
// 记录之前
if (l > pos) {
sb.append(fmt.substring(pos, l));
}
// 偏移
pos = m.end();
// 替换
String s = m.group(0);
if ("a".equals(s)) {
sb.append(this.value > 43200 ? "PM" : "AM");
}
// H Hour in day (0-23)
else if ("H".equals(s)) {
sb.append(this.hour);
}
// k Hour in day (1-24)
else if ("k".equals(s)) {
sb.append(this.hour + 1);
}
// K Hour in am/pm (0-11)
else if ("K".equals(s)) {
sb.append(this.hour % 12);
}
// h Hour in am/pm (1-12)
else if ("h".equals(s)) {
sb.append((this.hour % 12) + 1);
}
// m Minute in hour
else if ("m".equals(s)) {
sb.append(this.minute);
}
// s Second in minute
else if ("s".equals(s)) {
sb.append(this.second);
}
// S Millisecond Number
else if ("S".equals(s)) {
sb.append(this.millisecond);
}
// HH 补零的小时(0-23)
else if ("HH".equals(s)) {
sb.append(String.format("%02d", this.hour));
}
// kk 补零的小时(1-24)
else if ("kk".equals(s)) {
sb.append(String.format("%02d", this.hour + 1));
}
// KK 补零的半天小时(0-11)
else if ("KK".equals(s)) {
sb.append(String.format("%02d", this.hour % 12));
}
// hh 补零的半天小时(1-12)
else if ("hh".equals(s)) {
sb.append(String.format("%02d", (this.hour % 12) + 1));
}
// mm 补零的分钟
else if ("mm".equals(s)) {
sb.append(String.format("%02d", this.minute));
}
// ss 补零的秒
else if ("ss".equals(s)) {
sb.append(String.format("%02d", this.second));
}
// SSS 补零的毫秒
else if ("SSS".equals(s)) {
sb.append(String.format("%03d", this.millisecond));
}
// 不认识
else {
sb.append(s);
}
}
// 结尾
if (pos < fmt.length()) {
sb.append(fmt.substring(pos));
}
// 返回
return sb.toString();
}
}
/**
* 返回服务器当前时间
*
* @return 服务器当前时间
*/
public static Date now() {
return new Date(System.currentTimeMillis());
}
private static Pattern _P_TIME = Pattern.compile("^((\\d{2,4})([/\\\\-])?(\\d{1,2})([/\\\\-])?(\\d{1,2}))?"
+ "(([ T])?"
+ "(\\d{1,2})(:)(\\d{1,2})((:)(\\d{1,2}))?"
+ "(([.])"
+ "(\\d{1,}))?)?"
+ "(([+-])(\\d{1,2})(:\\d{1,2})?)?"
+ "$");
private static Pattern _P_TIME_LONG = Pattern.compile("^[0-9]+(L)?$");
/**
* 根据默认时区计算时间字符串的绝对毫秒数
*
* @param ds
* 时间字符串
* @return 绝对毫秒数
*
* @see #ams(String, TimeZone)
*/
public static long ams(String ds) {
return ams(ds, null);
}
/**
* 根据字符串得到相对于 "UTC 1970-01-01 00:00:00" 的绝对毫秒数。
* 本函数假想给定的时间字符串是本地时间。所以计算出来结果后,还需要减去时差
*
* 支持的时间格式字符串为:
*
* <pre>
* yyyy-MM-dd HH:mm:ss
* yyyy-MM-dd HH:mm:ss.SSS
* yy-MM-dd HH:mm:ss;
* yy-MM-dd HH:mm:ss.SSS;
* yyyy-MM-dd;
* yy-MM-dd;
* HH:mm:ss;
* HH:mm:ss.SSS;
* </pre>
*
* 时间字符串后面可以跟 +8 或者 +8:00 表示 GMT+8:00 时区。 同理 -9 或者 -9:00 表示 GMT-9:00 时区
*
* @param ds
* 时间字符串
* @param tz
* 你给定的时间字符串是属于哪个时区的
* @return 时间
* @see #_P_TIME
*/
public static long ams(String ds, TimeZone tz) {
Matcher m = _P_TIME.matcher(ds);
if (m.find()) {
int yy = _int(m, 2, 1970);
int MM = _int(m, 4, 1);
int dd = _int(m, 6, 1);
int HH = _int(m, 9, 0);
int mm = _int(m, 11, 0);
int ss = _int(m, 14, 0);
int ms = _int(m, 17, 0);
/*
* zozoh: 先干掉,还是用 SimpleDateFormat 吧,"1980-05-01 15:17:23" 之前的日子
* 得出的时间竟然总是多 30 分钟 long day = (long) D1970(yy, MM, dd); long MS =
* day * 86400000L; MS += (((long) HH) * 3600L + ((long) mm) * 60L +
* ss) * 1000L; MS += (long) ms;
*
* // 如果没有指定时区 ... if (null == tz) { // 那么用字符串中带有的时区信息, if
* (!Strings.isBlank(m.group(17))) { tz =
* TimeZone.getTimeZone(String.format("GMT%s%s:00", m.group(18),
* m.group(19))); // tzOffset = Long.parseLong(m.group(19)) // *
* 3600000L // * (m.group(18).charAt(0) == '-' ? -1 : 1);
*
* } // 如果依然木有,则用系统默认时区 else { tz = TimeZone.getDefault(); } }
*
* // 计算 return MS - tz.getRawOffset() - tz.getDSTSavings();
*/
String str = String.format("%04d-%02d-%02d %02d:%02d:%02d.%03d",
yy,
MM,
dd,
HH,
mm,
ss,
ms);
SimpleDateFormat df = (SimpleDateFormat) DF_DATE_TIME_MS4.clone();
// 那么用字符串中带有的时区信息 ...
if (null == tz && !Strings.isBlank(m.group(18))) {
tz = TimeZone.getTimeZone(String.format("GMT%s%s:00", m.group(19), m.group(20)));
}
// 指定时区 ...
if (null != tz) {
df.setTimeZone(tz);
}
// 解析返回
try {
return df.parse(str).getTime();
}
catch (ParseException e) {
throw Lang.wrapThrow(e);
}
} else if (_P_TIME_LONG.matcher(ds).find()) {
if (ds.endsWith("L")) {
ds.substring(0, ds.length() - 1);
}
return Long.parseLong(ds);
}
throw Lang.makeThrow("Unexpect date format '%s'", ds);
}
/**
* 这个接口函数是 1.b.49 提供了,下一版本将改名为 ams,预计在版本 1.b.51 之后被移除
*
* @deprecated since 1.b.49 util 1.b.51
*/
@Deprecated
public static long ms(String ds, TimeZone tz) {
return ams(ds, tz);
}
/**
* 返回时间对象在一天中的毫秒数
*
* @param d
* 时间对象
*
* @return 时间对象在一天中的毫秒数
*/
public static long ms(Date d) {
return ms(C(d));
}
/**
* 返回时间对象在一天中的毫秒数
*
* @param c
* 时间对象
*
* @return 时间对象在一天中的毫秒数
*/
public static int ms(Calendar c) {
int ms = c.get(Calendar.HOUR_OF_DAY) * 3600000;
ms += c.get(Calendar.MINUTE) * 60000;
ms += c.get(Calendar.SECOND) * 1000;
ms += c.get(Calendar.MILLISECOND);
return ms;
}
/**
* 返回当前时间在一天中的毫秒数
*
* @return 当前时间在一天中的毫秒数
*/
public static int ms() {
return ms(Calendar.getInstance());
}
/**
* 返回当前时间在一天中的毫秒数
*
* @param str
* 时间字符串
*
* @return 当前时间在一天中的毫秒数
*/
public static int ms(String str) {
return Ti(str).valueInMillisecond;
}
/**
* 根据一个当天的绝对毫秒数,得到一个时间字符串,格式为 "HH:mm:ss.EEE"
*
* @param ms
* 当天的绝对毫秒数
* @return 时间字符串
*/
public static String mss(int ms) {
int sec = ms / 1000;
ms = ms - sec * 1000;
return secs(sec) + "." + Strings.alignRight(ms, 3, '0');
}
/**
* 根据一个当天的绝对秒数,得到一个时间字符串,格式为 "HH:mm:ss"
*
* @param sec
* 当天的绝对秒数
* @return 时间字符串
*/
public static String secs(int sec) {
int hh = sec / 3600;
sec -= hh * 3600;
int mm = sec / 60;
sec -= mm * 60;
return Strings.alignRight(hh, 2, '0')
+ ":"
+ Strings.alignRight(mm, 2, '0')
+ ":"
+ Strings.alignRight(sec, 2, '0');
}
/**
* 返回时间对象在一天中的秒数
*
* @param d
* 时间对象
*
* @return 时间对象在一天中的秒数
*/
public static int sec(Date d) {
Calendar c = C(d);
int sec = c.get(Calendar.HOUR_OF_DAY) * 3600;
sec += c.get(Calendar.MINUTE) * 60;
sec += c.get(Calendar.SECOND);
return sec;
}
/**
* 返回当前时间在一天中的秒数
*
* @return 当前时间在一天中的秒数
*/
public static int sec() {
return sec(now());
}
/**
* 根据字符串得到时间对象
*
* @param ds
* 时间字符串
* @return 时间
*
* @see #ams(String)
*/
public static Date D(String ds) {
return D(ams(ds));
}
private static int _int(Matcher m, int index, int dft) {
String s = m.group(index);
if (Strings.isBlank(s)) {
return dft;
}
return Integer.parseInt(s);
}
// 常量数组,一年每个月多少天
private static final int[] _MDs = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/**
* 计算一个给定日期,距离 1970 年 1 月 1 日有多少天
*
* @param yy
* 年,比如 1999,或者 43
* @param MM
* 月,一月为 1,十二月为 12
* @param dd
* 日,每月一号为 1
* @return 距离 1970 年 1 月 1 日的天数
*/
public static int D1970(int yy, int MM, int dd) {
// 转换成相对公元元年的年份
// 如果给的年份小于 100,那么就认为是从 1970 开始算的年份
int year = (yy < 100 ? yy + 1970 : yy);
// 得到今年之前的基本天数
int day = (year - 1970) * 365;
// 补上闰年天数
day += countLeapYear(year) - countLeapYear(1970);
// 计算今年本月之前的月份
int mi = Math.min(MM - 1, 11);
boolean isLeapYear = leapYear(yy);
for (int i = 0; i < mi; i++) {
day += _MDs[i];
}
// 考虑今年是闰年的情况
if (isLeapYear && MM > 2) {
day++;
}
// 最后加上天数
day += Math.min(dd, _MDs[mi]) - 1;
// 如果是闰年且本月是 2 月
if (isLeapYear && dd == 29) {
day++;
}
// 如果是闰年并且过了二月
return day;
}
/**
* 根据毫秒数得到时间
*
* @param ms
* 时间的毫秒数
* @return 时间
*/
public static Date D(long ms) {
return new Date(ms);
}
/**
* 根据字符串得到时间
*
* <pre>
* 如果你输入了格式为 "yyyy-MM-dd HH:mm:ss"
* 那么会匹配到秒
*
* 如果你输入格式为 "yyyy-MM-dd"
* 相当于你输入了 "yyyy-MM-dd 00:00:00"
* </pre>
*
* @param ds
* 时间字符串
* @return 时间
*/
public static Calendar C(String ds) {
return C(D(ds));
}
/**
* 根据日期对象得到时间
*
* @param d
* 时间对象
* @return 时间
*/
public static Calendar C(Date d) {
return C(d.getTime());
}
/**
* 根据毫秒数得到时间
*
* @param ms
* 时间的毫秒数
* @return 时间
*/
public static Calendar C(long ms) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(ms);
return c;
}
/**
* 把时间转换成格式为 y-M-d H:m:s.S 的字符串
*
* @param d
* 时间对象
* @return 该时间的字符串形式 , 格式为 y-M-d H:m:s.S
*/
public static String sDTms(Date d) {
return format(DF_DATE_TIME_MS, d);
}
/**
* 把时间转换成格式为 yy-MM-dd HH:mm:ss.SSS 的字符串
*
* @param d
* 时间对象
* @return 该时间的字符串形式 , 格式为 yy-MM-dd HH:mm:ss.SSS
*/
public static String sDTms2(Date d) {
return format(DF_DATE_TIME_MS2, d);
}
/**
* 把时间转换成格式为 yyyy-MM-dd HH:mm:ss.SSS 的字符串
*
* @param d
* 时间对象
* @return 该时间的字符串形式 , 格式为 yyyy-MM-dd HH:mm:ss.SSS
*/
public static String sDTms4(Date d) {
return format(DF_DATE_TIME_MS4, d);
}
/**
* 把时间转换成格式为 yyyy-MM-dd HH:mm:ss 的字符串
*
* @param d
* 时间对象
* @return 该时间的字符串形式 , 格式为 yyyy-MM-dd HH:mm:ss
*/
public static String sDT(Date d) {
return format(DF_DATE_TIME, d);
}
/**
* 把时间转换成格式为 yyyy-MM-dd 的字符串
*
* @param d
* 时间对象
* @return 该时间的字符串形式 , 格式为 yyyy-MM-dd
*/
public static String sD(Date d) {
return format(DF_DATE, d);
}
/**
* 将一个秒数(天中),转换成一个格式为 HH:mm:ss 的字符串
*
* @param sec
* 秒数
* @return 格式为 HH:mm:ss 的字符串
*/
public static String sT(int sec) {
int[] ss = T(sec);
return Strings.alignRight(ss[0], 2, '0')
+ ":"
+ Strings.alignRight(ss[1], 2, '0')
+ ":"
+ Strings.alignRight(ss[2], 2, '0');
}
/**
* 将一个秒数(天中),转换成一个格式为 HH:mm 的字符串(精确到分钟)
*
* @param sec
* 秒数
* @return 格式为 HH:mm 的字符串
*/
public static String sTmin(int sec) {
int[] ss = T(sec);
return Strings.alignRight(ss[0], 2, '0') + ":" + Strings.alignRight(ss[1], 2, '0');
}
/**
* 将一个毫秒秒数(天中),转换成一个格式为 HH:mm:ss,SSS 的字符串(精确到毫秒)
*
* @param ams
* 当天毫秒数
* @return 格式为 HH:mm:ss,SSS 的字符串
*/
public static String sTms(long ams) {
return Tims(ams).toString("HH:mm:ss,SSS");
}
/**
* 以本周为基础获得某一周的时间范围
*
* @param off
* 从本周偏移几周, 0 表示本周,-1 表示上一周,1 表示下一周
*
* @return 时间范围(毫秒级别)
*
* @see org.nutz.lang.Times#weeks(long, int, int)
*/
public static Date[] week(int off) {
return week(System.currentTimeMillis(), off);
}
/**
* 以某周为基础获得某一周的时间范围
*
* @param base
* 基础时间,毫秒
* @param off
* 从本周偏移几周, 0 表示本周,-1 表示上一周,1 表示下一周
*
* @return 时间范围(毫秒级别)
*
* @see org.nutz.lang.Times#weeks(long, int, int)
*/
public static Date[] week(long base, int off) {
return weeks(base, off, off);
}
/**
* 以本周为基础获得时间范围
*
* @param offL
* 从本周偏移几周, 0 表示本周,-1 表示上一周,1 表示下一周
* @param offR
* 从本周偏移几周, 0 表示本周,-1 表示上一周,1 表示下一周
*
* @return 时间范围(毫秒级别)
*
* @see org.nutz.lang.Times#weeks(long, int, int)
*/
public static Date[] weeks(int offL, int offR) {
return weeks(System.currentTimeMillis(), offL, offR);
}
/**
* 按周获得某几周周一 00:00:00 到周六 的时间范围
* <p>
* 它会根据给定的 offL 和 offR 得到一个时间范围
* <p>
* 对本函数来说 week(-3,-5) 和 week(-5,-3) 是一个意思
*
* @param base
* 基础时间,毫秒
* @param offL
* 从本周偏移几周, 0 表示本周,-1 表示上一周,1 表示下一周
* @param offR
* 从本周偏移几周, 0 表示本周,-1 表示上一周,1 表示下一周
*
* @return 时间范围(毫秒级别)
*/
public static Date[] weeks(long base, int offL, int offR) {
int from = Math.min(offL, offR);
int len = Math.abs(offL - offR);
// 现在
Calendar c = Calendar.getInstance();
c.setTimeInMillis(base);
Date[] re = new Date[2];
// 计算开始
c.add(Calendar.DAY_OF_YEAR, 7 * from);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
re[0] = c.getTime();
// 计算结束
c.add(Calendar.DAY_OF_YEAR, 7 * (len + 1));
c.add(Calendar.MILLISECOND, -1);
re[1] = c.getTime();
// 返回
return re;
}
private static final String[] _MMM = new String[]{"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"};
/**
* 将一个时间格式化成容易被人类阅读的格式
*
* <pre>
* 如果 1 分钟内,打印 Just Now
* 如果 1 小时内,打印多少分钟
* 如果 1 天之内,打印多少小时之前
* 如果是今年之内,打印月份和日期
* 否则打印月份和年
* </pre>
*
* @param d
* @return 日期字符串
*/
public static String formatForRead(Date d) {
long ms = System.currentTimeMillis() - d.getTime();
// 如果 1 分钟内,打印 Just Now
if (ms < (60000)) {
return "Just Now";
}
// 如果 1 小时内,打印多少分钟
if (ms < (60 * 60000)) {
return "" + (ms / 60000) + "Min.";
}
// 如果 1 天之内,打印多少小时之前
if (ms < (24 * 3600 * 1000)) {
return "" + (ms / 3600000) + "hr.";
}
// 如果一周之内,打印多少天之前
if (ms < (7 * 24 * 3600 * 1000)) {
return "" + (ms / (24 * 3600000)) + "Day";
}
// 如果是今年之内,打印月份和日期
Calendar c = Calendar.getInstance();
int thisYear = c.get(Calendar.YEAR);
c.setTime(d);
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH);
if (thisYear == yy) {
int dd = c.get(Calendar.DAY_OF_MONTH);
return String.format("%s %d", _MMM[mm], dd);
}
// 否则打印月份和年
return String.format("%s %d", _MMM[mm], yy);
}
/**
* 以给定的时间格式来安全的对时间进行格式化,并返回格式化后所对应的字符串
*
* @param fmt
* 时间格式
* @param d
* 时间对象
* @return 格式化后的字符串
*/
public static String format(DateFormat fmt, Date d) {
return ((DateFormat) fmt.clone()).format(d);
}
/**
* 以给定的时间格式来安全的对时间进行格式化,并返回格式化后所对应的字符串
*
* @param fmt
* 时间格式
* @param d
* 时间对象
* @return 格式化后的字符串
*/
public static String format(String fmt, Date d) {
return new SimpleDateFormat(fmt, Locale.ENGLISH).format(d);
}
/**
* 以给定的时间格式来安全的解析时间字符串,并返回解析后所对应的时间对象(包裹RuntimeException)
*
* @param fmt
* 时间格式
* @param s
* 时间字符串
* @return 该时间字符串对应的时间对象
*/
public static Date parseq(DateFormat fmt, String s) {
try {
return parse(fmt, s);
}
catch (ParseException e) {
throw Lang.wrapThrow(e);
}
}
/**
* 以给定的时间格式来安全的解析时间字符串,并返回解析后所对应的时间对象(包裹RuntimeException)
*
* @param fmt
* 时间格式
* @param s
* 时间字符串
* @return 该时间字符串对应的时间对象
*/
public static Date parseq(String fmt, String s) {
try {
return parse(fmt, s);
}
catch (ParseException e) {
throw Lang.wrapThrow(e);
}
}
/**
* 以给定的时间格式来安全的解析时间字符串,并返回解析后所对应的时间对象
*
* @param fmt
* 时间格式
* @param s
* 日期时间字符串
* @return 该时间字符串对应的时间对象
*/
public static Date parse(DateFormat fmt, String s) throws ParseException {
return ((DateFormat) fmt.clone()).parse(s);
}
/**
* 以给定的时间格式来安全的解析时间字符串,并返回解析后所对应的时间对象
*
* @param fmt
* 时间格式
* @param s
* 日期时间字符串
* @return 该时间字符串对应的时间对象
*/
public static Date parse(String fmt, String s) throws ParseException {
return new SimpleDateFormat(fmt).parse(s);
}
private static final DateFormat DF_DATE_TIME_MS = new SimpleDateFormat("y-M-d H:m:s.S");
private static final DateFormat DF_DATE_TIME_MS2 = new SimpleDateFormat("yy-MM-dd HH:mm:ss.SSS");
private static final DateFormat DF_DATE_TIME_MS4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private static final DateFormat DF_DATE_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final DateFormat DF_DATE = new SimpleDateFormat("yyyy-MM-dd");
// private static final DateFormat DF_MONTH = new
// SimpleDateFormat("yyyy-MM");
public static final long T_1S = 1000;
public static final long T_1M = 60 * 1000;
public static final long T_1H = 60 * 60 * 1000;
public static final long T_1D = 24 * 60 * 60 * 1000;
/**
* 方便的把时间换算成毫秒数
*
* 支持几个单位, s(秒), m(分钟), h(小时), d(天)
*
* 比如:
*
* 100s -> 100000 <br>
* 2m -> 120000 <br>
* 3h -> 10800000 <br>
*
* @param tstr
* 时间字符串
* @return 毫秒数
*/
public static long toMillis(String tstr) {
if (Strings.isBlank(tstr)) {
return 0;
}
tstr = tstr.toLowerCase();
// FIXME 稍后改成正则判断
String tl = tstr.substring(0, tstr.length() - 1);
String tu = tstr.substring(tstr.length() - 1);
if (TIME_S_EN.equals(tu)) {
return T_1S * Long.valueOf(tl);
}
if (TIME_M_EN.equals(tu)) {
return T_1M * Long.valueOf(tl);
}
if (TIME_H_EN.equals(tu)) {
return T_1H * Long.valueOf(tl);
}
if (TIME_D_EN.equals(tu)) {
return T_1D * Long.valueOf(tl);
}
return Long.valueOf(tstr);
}
private static String TIME_S_EN = "s";
private static String TIME_M_EN = "m";
private static String TIME_H_EN = "h";
private static String TIME_D_EN = "d";
private static String TIME_S_CN = "秒";
private static String TIME_M_CN = "分";
private static String TIME_H_CN = "时";
private static String TIME_D_CN = "天";
/**
* 一段时间长度的毫秒数转换为一个时间长度的字符串
*
* 1000 -> 1S
*
* 120000 - 2M
*
* @param mi
* 毫秒数
* @return 可读的文字
*/
public static String fromMillis(long mi) {
return _fromMillis(mi, true);
}
/**
* fromMillis的中文版本
*
* 1000 -> 1秒
*
* 120000 - 2分
*
* @param mi
* 毫秒数
* @return 可读的文字
*/
public static String fromMillisCN(long mi) {
return _fromMillis(mi, false);
}
private static String _fromMillis(long mi, boolean useEnglish) {
if (mi <= T_1S) {
return "1" + (useEnglish ? TIME_S_EN : TIME_S_CN);
}
if (mi < T_1M && mi > T_1S) {
return (int) (mi / T_1S) + (useEnglish ? TIME_S_EN : TIME_S_CN);
}
if (mi >= T_1M && mi < T_1H) {
int m = (int) (mi / T_1M);
return m
+ (useEnglish ? TIME_M_EN : TIME_M_CN)
+ _fromMillis(mi - m * T_1M, useEnglish);
}
if (mi >= T_1H && mi < T_1D) {
int h = (int) (mi / T_1H);
return h
+ (useEnglish ? TIME_H_EN : TIME_H_CN)
+ _fromMillis(mi - h * T_1H, useEnglish);
}
// if (mi >= T_1D) {
int d = (int) (mi / T_1D);
return d + (useEnglish ? TIME_D_EN : TIME_D_CN) + _fromMillis(mi - d * T_1D, useEnglish);
// }
// WTF ?
// throw Lang.impossible();
}
/**
* 比较2个字符串格式时间yyyy-MM-dd hh:mm:ss大小 2017-2-8 17:14:14
*
* @param t1
* 第一个时间
* @param t2
* 第二个时间
* @return true,如果相等
*/
public static boolean sDTcompare(String t1, String t2) {
// 将字符串形式的时间转化为Date类型的时间
Date d1 = parseq(DF_DATE_TIME, t1);
Date d2 = parseq(DF_DATE_TIME, t2);
// Date类的一个方法,如果a早于b返回true,否则返回false
if (d1.before(d2)) {
return true;
} else {
return false;
}
}
/**
* Unix时间戳转String日期
*
* @param timestamp
* 时间戳
* @param sf
* 日期格式
* @return 日期字符串
*/
public static String ts2S(long timestamp, String sf) {
DateFormat format = new SimpleDateFormat(sf);
return format.format(new Date(Long.parseLong(timestamp * 1000 + "")));
}
/**
* 取Unix时间戳
*
* @return 时间戳
*/
public static long getTS() {
return System.currentTimeMillis() / 1000;
}
/**
* 字符串yyyy-MM-dd HH:mm:ss时间转化成Unix时间戳
*
* @param str
* 日期,符合yyyy-MM-dd HH:mm:ss
* @return timestamp 时间戳字符串
*/
public static String sDT2TS(String str, DateFormat df) {
try {
return "" + (df.parse(str).getTime() / 1000);
}
catch (Exception e) {
e.printStackTrace();
}
return "0";
}
/**
* 取当前时间的字符串形式 , 格式为 yyyy-MM-dd HH:mm:ss
*
* @return 时间字符串
*/
public static String getNowSDT() {
return sDT(now());
}
/**
* 获得某月的天数
*
* @param year
* 年
* @param month
* 月
* @return int 指定年月的天数
*/
public static int getDaysOfMonth(String year, String month) {
int days = 0;
if ("1".equals(month)
|| "3".equals(month)
|| "5".equals(month)
|| "7".equals(month)
|| "8".equals(month)
|| "10".equals(month)
|| "12".equals(month)) {
days = 31;
} else if ("4".equals(month)
|| "6".equals(month)
|| "9".equals(month)
|| "11".equals(month)) {
days = 30;
} else {
if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
|| Integer.parseInt(year) % 400 == 0) {
days = 29;
} else {
days = 28;
}
}
return days;
}
/**
* 获取某年某月的天数
*
* @param year
* int 年
* @param month
* int 月份[1-12] 月
* @return int 指定年月的天数
*/
public static int getDaysOfMonth(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 获得当前日期
*
* @return 当前日期,按月算,即DAY_OF_MONTH
*/
public static int getToday() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.DATE);
}
/**
* 获得当前月份
*
* @return 当前月份,1开始算
*/
public static int getToMonth() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 获得当前年份
*
* @return 当前年份
*/
public static int getToYear() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.YEAR);
}
/**
* 返回日期的天
*
* @param date
* 指定的Date
* @return 指定时间所在月的DAY_OF_MONTH
*/
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DATE);
}
/**
* 返回日期的年
*
* @param date
* 指定的Date
* @return 指定时间的年份
*/
public static int getYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
/**
* 返回日期的月份,1-12
*
* @param date
* 指定的Date
* @return 指定时间的月份
*/
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 计算两个日期相差的天数,如果date2 > date1 返回正数,否则返回负数
*
* @param date1
* Date
* @param date2
* Date
* @return long
*/
public static long dayDiff(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / 86400000;
}
/**
* 比较两个日期的年差
*
* @param before
* 前一个日期,格式yyyy-MM-dd
* @param after
* 后一个日期,格式yyyy-MM-dd
* @return 年份差值
*/
public static int yearDiff(String before, String after) {
Date beforeDay = parseq(DF_DATE, before);
Date afterDay = parseq(DF_DATE, after);
return getYear(afterDay) - getYear(beforeDay);
}
/**
* 比较指定日期与当前日期的年差
*
* @param after
* 指定的后一个日期,格式yyyy-MM-dd
* @return 年份差值
*/
public static int yearDiffCurr(String after) {
Date beforeDay = new Date();
Date afterDay = parseq(DF_DATE, after);
return getYear(beforeDay) - getYear(afterDay);
}
/**
* 比较指定日期与当前日期的天差
*
* @param before
* 指定的前应日期,格式yyyy-MM-dd
* @return 天差
*/
public static long dayDiffCurr(String before) {
Date currDate = parseq(DF_DATE, sD(now()));
Date beforeDate = parseq(DF_DATE, before);
return (currDate.getTime() - beforeDate.getTime()) / 86400000;
}
/**
* 根据生日获取星座
*
* @param birth
* 日期格式为YYYY-mm-dd
* @return 星座,单一字符
*/
public static String getAstro(String birth) {
if (!isDate(birth)) {
birth = "2000" + birth;
}
if (!isDate(birth)) {
return "";
}
int month = Integer.parseInt(birth.substring(birth.indexOf("-") + 1,
birth.lastIndexOf("-")));
int day = Integer.parseInt(birth.substring(birth.lastIndexOf("-") + 1));
String s = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
int[] arr = {20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};
int start = month * 2 - (day < arr[month - 1] ? 2 : 0);
return s.substring(start, start + 2) + "座";
}
/**
* 判断日期是否有效,包括闰年的情况
*
* @param date
* 日期格式YYYY-mm-dd
* @return true,如果合法
*/
public static boolean isDate(String date) {
StringBuffer reg = new StringBuffer("^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
Pattern p = Regex.getPattern(reg.toString());
return p.matcher(date).matches();
}
/**
* 取得指定日期过 years 年后的日期 (当 years 为负数表示指定年之前);
*
* @param date
* 日期 为null时表示当天
* @param years
* 相加(相减)的年数
*/
public static Date nextYear(Date date, int years) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.YEAR, years);
return cal.getTime();
}
/**
* 取得指定日期过 months 月后的日期 (当 months 为负数表示指定月之前);
*
* @param date
* 日期 为null时表示当天
* @param months
* 相加(相减)的月数
*/
public static Date nextMonth(Date date, int months) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.MONTH, months);
return cal.getTime();
}
/**
* 取得指定日期过 day 周后的日期 (当 day 为负数表示指定月之前)
*
* @param date
* 日期 为null时表示当天
*/
public static Date nextWeek(Date date, int week) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.WEEK_OF_MONTH, week);
return cal.getTime();
}
/**
* 取得指定日期过 day 天后的日期 (当 day 为负数表示指日期之前);
*
* @param date
* 日期 为null时表示当天
* @param day
* 相加(相减)的月数
*/
public static Date nextDay(Date date, int day) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.DAY_OF_MONTH, day);
return cal.getTime();
}
/**
* 取得当前时间距离1900/1/1的天数
*
* @return 天数
*/
public static int getDayNum() {
int daynum = 0;
GregorianCalendar gd = new GregorianCalendar();
Date dt = gd.getTime();
GregorianCalendar gd1 = new GregorianCalendar(1900, 1, 1);
Date dt1 = gd1.getTime();
daynum = (int) ((dt.getTime() - dt1.getTime()) / (24 * 60 * 60 * 1000));
return daynum;
}
/**
* getDayNum的逆方法(用于处理Excel取出的日期格式数据等)
*
* @param day
* 天数
* @return 反推出的时间
*/
public static Date getDateByNum(int day) {
GregorianCalendar gd = new GregorianCalendar(1900, 1, 1);
Date date = gd.getTime();
date = nextDay(date, day);
return date;
}
/**
* 取得距离今天 day 日的日期
*
* @param day
* 天数
* @return 日期字符串
*/
public static String nextDay(int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(now());
cal.add(Calendar.DAY_OF_MONTH, day);
return format(DF_DATE, cal.getTime());
}
/**
* 获取明天的日期
*
* return 明天的日期
*/
public static String afterDay() {
return nextDay(1);
}
/**
* 获取昨天的日期
*
* @return 昨天的日期
*/
public static String befoDay() {
return nextDay(-1);
}
/**
* 获取本月最后一天
*
* @return 本月最后一天
*/
public static String getLastDayOfMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 1);
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DATE, -1);
return format(DF_DATE, cal.getTime());
}
/**
* 获取本月第一天
*
* @return 本月第一天
*/
public static String getFirstDayOfMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 1);
return format(DF_DATE, cal.getTime());
}
public static final long T_1MS = 1;
public static final long T_1W = 7 * 24 * 60 * 60 * 1000;
/**
* 判断两个日期相差的时长
*
* @param s
* 起始日期
* @param e
* 结束日期
* @param unit
* 相差的单位 T_1MS 毫秒 T_1S 秒 T_1M 分 T_1H 时 T_1D 天 T_1W 周
* @return 相差的数量
*/
public static long between(Date s, Date e, long unit) {
Date start;
Date end;
if (s.before(e)) {
start = s;
end = e;
} else {
start = e;
end = s;
}
long diff = end.getTime() - start.getTime();
return diff / unit;
}
/**
* 取得指定日期过 minute 分钟后的日期 (当 minute 为负数表示指定分钟之前)
*
* @param date
* 日期 为null时表示当天
*/
public static Date nextMinute(Date date, int minute) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.MINUTE, minute);
return cal.getTime();
}
/**
* 取得指定日期过 second 秒后的日期 (当 second 为负数表示指定秒之前)
*
* @param date
* 日期 为null时表示当天
*/
public static Date nextSecond(Date date, int second) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.SECOND, second);
return cal.getTime();
}
/**
* 取得指定日期过 hour 小时后的日期 (当 hour 为负数表示指定小时之前)
*
* @param date
* 日期 为null时表示当天
*/
public static Date nextHour(Date date, int hour) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.HOUR, hour);
return cal.getTime();
}
/**
* Unix时间戳转Date日期
*
* @param timestamp
* 时间戳
* @return 日期
*/
public static Date ts2D(long timestamp) {
return new Date(Long.parseLong(timestamp * 1000 + ""));
}
/**
* Date日期转Unix时间戳
*
* @param date 日期
* @return 时间戳
*/
public static long d2TS(Date date) {
if (Lang.isEmpty(date)) {
return getTS();
} else {
return date.getTime() / 1000;
}
}
}
| nutzam/nutz | src/org/nutz/lang/Times.java |
1,070 | package com.taobao.rigel.rap.common.utils;
import com.taobao.rigel.rap.common.config.Patterns;
import com.taobao.rigel.rap.common.config.SystemConstant;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 为FE提供各类过滤字符串的接口
*
* @author Junquan 2010.01.20
*/
public class StringUtils {
public static final String NAME_FORMAT_WARN_MSG = "名字必须由数字/字母/汉子/空格/下划线组成,长度" + SystemConstant.NAME_LENGTH_MIN + "-" + SystemConstant.NAME_LENGTH_MAX + ".";
public static final String ACCOUNT_FORMAT_WARN_MSG = "账户必须由数字/字母/下划线组成,长度" + SystemConstant.ACCOUNT_LENGTH_MIN + "-" + SystemConstant.ACCOUNT_LENGTH_MAX + ".";
/**
* 默认编码 utf8
*/
public static String DEFAULT_CHARSET = "utf8";
/**
* 在html标签或属性中A: 左尖括号:< 转成 < 右尖括号:> 转成 > 单引号:' 转成 ' 双引号:" 转成
* "
*/
public static String escapeInH(String str) {
if (str == null || ("").equals(str.trim())) {
return "";
}
StringBuffer sb = new StringBuffer();
int lth = str.length();
for (int i = 0; i < lth; i++) {
char c = str.charAt(i);
switch (c) {
case 60: // <
sb.append("<");
break;
case 62: // >
sb.append(">");
break;
case 39: // '
sb.append("'");
break;
case 34: // "
sb.append(""");
break;
default:
sb.append(c);
break;
}
}
return new String(sb.toString());
}
public static String escapeInH(Number num) {
String str = null;
if (num != null) {
str = num.toString();
}
return escapeInH(str);
}
/**
* 在html标签或属性中A - 逆
*/
public static String UnEscapeInH(String str) {
// TODO
return str;
}
/**
* 在html标签或属性中B: 左尖括号:< 转成 < 右尖括号:> 转成 > 单引号:' 转成 ' 双引号:" 转成
* " &符号:& 转成&
*/
public static String escapeInX(String str) {
if (str == null || ("").equals(str.trim())) {
return "";
}
StringBuffer sb = new StringBuffer();
int lth = str.length();
for (int i = 0; i < lth; i++) {
char c = str.charAt(i);
switch (c) {
case 60: // <
sb.append("<");
break;
case 62: // >
sb.append(">");
break;
case 39: // '
sb.append("'");
break;
case 34: // "
sb.append(""");
break;
case 38: // &
sb.append("&");
break;
default:
sb.append(c);
break;
}
}
return new String(sb.toString());
}
public static String escapeInX(Number num) {
String str = null;
if (num != null) {
str = num.toString();
}
return escapeInX(str);
}
/**
* 在html标签或属性中B - 逆
*/
public static String UnEscapeInX(String str) {
// TODO
return str;
}
/**
* 在普通JS环境: 单引号:' 转成 \' 双引号:" 转成 \" 反斜杠:\ 转成 \\ 正斜杠:/ 转成 \/ 换行符 转成 \n 回车符 转成
* \r
*/
public static String escapeInJ(String str) {
if (str == null || ("").equals(str.trim())) {
return "";
}
StringBuffer sb = new StringBuffer();
int lth = str.length();
for (int i = 0; i < lth; i++) {
char c = str.charAt(i);
switch (c) {
case 39: // '
sb.append("\\'");
break;
case 34: // "
sb.append("\\\"");
break;
case 47: // /
sb.append("\\/");
break;
case 92: // \
sb.append("\\\\");
break;
case 13: // 回车 \r
sb.append("\\r");
break;
case 10: // 换行 \n
sb.append("\\n");
break;
default:
sb.append(c);
break;
}
}
return new String(sb.toString());
}
public static String escapeInJ(Number num) {
String str = null;
if (num != null) {
str = num.toString();
}
return escapeInJ(str);
}
/**
* 在普通JS环境 - 逆
*/
public static String UnEscapeInJ(String str) {
// TODO
return str;
}
/**
* 在JS环境的innerHTML: 左尖括号:< 转成 < 右尖括号:> 转成 > 单引号:' 转成 \' 双引号:" 转成 \"
* 反斜杠:\ 转成 \\ 正斜杠:/ 转成 \/ 换行符 转成 \n 回车符 转成 \r
*/
public static String escapeInJH(String str) {
if (str == null || ("").equals(str.trim())) {
return "";
}
StringBuffer sb = new StringBuffer();
int lth = str.length();
for (int i = 0; i < lth; i++) {
char c = str.charAt(i);
switch (c) {
case 60: // <
sb.append("<");
break;
case 62: // >
sb.append(">");
break;
case 39: // '
sb.append("\\'");
break;
case 34: // "
sb.append("\\\"");
break;
case 47: // /
sb.append("\\/");
break;
case 92: // \
sb.append("\\\\");
break;
case 13: // 回车 \r
sb.append("\\r");
break;
case 10: // 换行 \n
sb.append("\\n");
break;
default:
sb.append(c);
break;
}
}
return new String(sb.toString());
}
public static String escapeInJH(Number num) {
String str = null;
if (num != null) {
str = num.toString();
}
return escapeInJH(str);
}
/**
* 在JS环境的innerHTML - 逆
*/
public static String UnEscapeInJH(String str) {
// TODO
return str;
}
/**
* 在标签onclick等事件函数参数中: 左尖括号:< 转成 < 右尖括号:> 转成 > &符号:& 转成& 单引号:' 转成
* \' 双引号:" 转成 \" 反斜杠:\ 转成 \\ 正斜杠:/ 转成 \/ 换行符 转成 \n 回车符 转成 \r
*/
public static String escapeInHJ(String str) {
if (str == null || ("").equals(str.trim())) {
return "";
}
StringBuffer sb = new StringBuffer();
int lth = str.length();
for (int i = 0; i < lth; i++) {
char c = str.charAt(i);
switch (c) {
case 60: // <
sb.append("<");
break;
case 62: // >
sb.append(">");
break;
case 39: // '
sb.append("\\'");
break;
case 34: // "
sb.append("\\"");
break;
case 38: // &
sb.append("&");
break;
case 47: // /
sb.append("\\/");
break;
case 92: // \
sb.append("\\\\");
break;
case 13: // 回车 \r
sb.append("\\r");
break;
case 10: // 换行 \n
sb.append("\\n");
break;
default:
sb.append(c);
break;
}
}
return new String(sb.toString());
}
public static String escapeInHJ(Number num) {
String str = null;
if (num != null) {
str = num.toString();
}
return escapeInHJ(str);
}
/**
* 在标签onclick等事件函数参数中 - 逆
*/
public static String UnEscapeInHJ(String str) {
// TODO
return str;
}
/**
* 在URL参数中: 对非字母、数字字符进行转码(%加字符的ASCII格式)
*
* @throws UnsupportedEncodingException
*/
public static String escapeInU(String str)
throws UnsupportedEncodingException {
if (str == null || ("").equals(str.trim())) {
return "";
}
return URLEncoder.encode(str, DEFAULT_CHARSET);
}
/**
* 在URL参数中 - 逆
*
* @throws UnsupportedEncodingException
*/
public static String UnEscapeInU(String str)
throws UnsupportedEncodingException {
if (str == null || ("").equals(str.trim())) {
return "";
}
return URLDecoder.decode(str, DEFAULT_CHARSET);
}
public static String getMD5(String src) {
byte[] defaultBytes = src.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(defaultBytes);
byte messageDigest[] = algorithm.digest();
for (int i = 0; i < messageDigest.length; i++) {
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hexString.toString();
}
public static String getMD5(byte[] source) {
String s = null;
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};// 用来将字节转换成16进制表示的字符
try {
java.security.MessageDigest md = java.security.MessageDigest
.getInstance("MD5");
md.update(source);
byte tmp[] = md.digest();// MD5 的计算结果是一个 128 位的长整数,
// 用字节表示就是 16 个字节
char str[] = new char[16 * 2];// 每个字节用 16 进制表示的话,使用两个字符, 所以表示成 16
// 进制需要 32 个字符
int k = 0;// 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) {// 从第一个字节开始,对 MD5 的每一个字节// 转换成 16
// 进制字符的转换
byte byte0 = tmp[i];// 取第 i 个字节
str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 取字节中高 4 位的数字转换,// >>>
// 为逻辑右移,将符号位一起右移
str[k++] = hexDigits[byte0 & 0xf];// 取字节中低 4 位的数字转换
}
s = new String(str);// 换后的结果转换为字符串
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return s;
}
public static String getDoubleMD5(String src) {
if (src != null) {
src = getMD5(src);
src = getMD5(src);
}
return src;
}
/**
* 把中文转成Unicode码
*
* @param str
* @return
*/
public static String chineseToUnicode(String str) {
if (str == null) {
str = "";
}
String result = "";
for (int i = 0; i < str.length(); i++) {
int chr1 = (char) str.charAt(i);
if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
result += "\\u" + Integer.toHexString(chr1);
} else {
result += str.charAt(i);
}
}
return result;
}
/**
* 判断是否为中文字符
*
* @param c
* @return
*/
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}
/**
* 中文算2个,字母算1个
*
* @param str
* @return
*/
public static int getLengthOfStringChinese(String str) {
int length = 0;
for (char c : str.toCharArray()) {
if (isChinese(c)) length += 2;
else length++;
}
return length;
}
/**
* 中文算2个,字母算1个
*
* @param str
* @param startIndex
* @param endIndex
* @return
*/
public static String subStringChinese(String str, int startIndex, int endIndex) {
int length = 0;
int size = endIndex - startIndex;
List<Character> charList = new ArrayList<Character>();
for (char c : str.toCharArray()) {
if (isChinese(c)) length += 2;
else length++;
charList.add(c);
if (length >= size) break;
}
StringBuilder builder = new StringBuilder();
for (Character c : charList) {
builder.append(c);
}
return builder.toString();
}
/**
* regular expression matcher helper
*
* @param pattern regular expression
* @param str string to be matched
* @return
*/
public static boolean regMatch(String pattern, String str) {
Pattern p = Pattern.compile(pattern);
Matcher matcher = p.matcher(str);
return matcher.matches();
}
/**
* remove all characters except [0-9a-zA-Z_] and blank space
*
* @param o
* @return
*/
public static String removeIllegalCharacters(String o) {
return o.replaceAll(Patterns.ILLEGAL_NAME_CHAR, "");
}
public static boolean validateAccount(String str) {
if (str == null) return false;
if (str.length() < SystemConstant.ACCOUNT_LENGTH_MIN || str.length() > SystemConstant.ACCOUNT_LENGTH_MAX) {
return false;
}
return str.matches(Patterns.LEGAL_ACCOUNT_CHAR + "*");
}
public static boolean validateName(String str) {
if (str == null) return false;
if (str.length() < SystemConstant.NAME_LENGTH_MIN || str.length() > SystemConstant.NAME_LENGTH_MAX) {
return false;
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!isChinese(c) && !String.valueOf(c).matches(Patterns.LEGAL_NAME_CHAR)) {
return false;
}
}
return true;
}
/**
* similar to JavaScript's String.prototype.join
*
* @param strs
* @param seperator
* @return
*/
public static String join(String [] strs, String seperator) {
String rv = "";
for (int i = 0; i < strs.length; i++) {
rv += (i == 0) ? strs[i] : seperator + strs[i];
}
return rv;
}
}
| thx/RAP | src/main/java/com/taobao/rigel/rap/common/utils/StringUtils.java |
1,071 | E
把#of occurrences 存进HashMap, 第一个string 做加法,第二个string做减法。最后看是否有不等于0的作判断。
```
public class Solution {
/*
* @param A: a string
* @param B: a string
* @return: a boolean
*/
public boolean Permutation(String A, String B) {
if (A == null || B == null || A.length() != B.length()) {
return false;
}
final Map<Character, Integer> strMap = new HashMap<>();
for (int i = 0; i < A.length(); i++) {
final char charA = A.charAt(i);
final char charB = B.charAt(i);
if (!strMap.containsKey(charA)) {
strMap.put(charA, 0);
}
strMap.put(charA, strMap.get(charA) + 1);
if (!strMap.containsKey(charB)) {
strMap.put(charB, 0);
}
strMap.put(charB, strMap.get(charB) - 1);
}
for (Map.Entry<Character, Integer> entry : strMap.entrySet()) {
if (entry.getValue() != 0) {
return false;
}
}
return true;
}
}
```
| awangdev/leet-code | Java/String Permutation.java |
1,074 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.demo.utils;
import java.io.File;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2015/10/11
* 描 述:MD5加密工具类
* 修订历史:
* ================================================
*/
public class MD5Utils {
private MD5Utils() {
}
/**
* 获取字符串的 MD5
*/
public static String encode(String str) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(str.getBytes("UTF-8"));
byte messageDigest[] = md5.digest();
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
hexString.append(String.format("%02X", b));
}
return hexString.toString().toLowerCase();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获取文件的 MD5
*/
public static String encode(File file) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
FileInputStream inputStream = new FileInputStream(file);
DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);
//必须把文件读取完毕才能拿到md5
byte[] buffer = new byte[4096];
while (digestInputStream.read(buffer) > -1) {
}
MessageDigest digest = digestInputStream.getMessageDigest();
digestInputStream.close();
byte[] md5 = digest.digest();
StringBuilder sb = new StringBuilder();
for (byte b : md5) {
sb.append(String.format("%02X", b));
}
return sb.toString().toLowerCase();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| jeasonlzy/okhttp-OkGo | demo/src/main/java/com/lzy/demo/utils/MD5Utils.java |