mirror of
https://github.com/alibaba/canal.git
synced 2026-11-04 00:30:15 +08:00
Compare commits
1 Commits
canal-1.1.
...
bugfix_end
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ac605242e |
@@ -14,7 +14,7 @@ cache:
|
|||||||
install: true
|
install: true
|
||||||
|
|
||||||
script:
|
script:
|
||||||
- travis_wait 30 ./mvnw -T 1C clean install -DskipTests=false -Dcheckstyle.skip=true -Dmaven.javadoc.skip=true
|
- travis_wait 30 ./mvnw clean install -DskipTests=false -Dcheckstyle.skip=true -Dmaven.javadoc.skip=true
|
||||||
|
|
||||||
after_success:
|
after_success:
|
||||||
- bash <(curl -s https://codecov.io/bash)
|
- bash <(curl -s https://codecov.io/bash)
|
||||||
|
|||||||
@@ -85,19 +85,15 @@ canal 特别设计了 client-server 模式,交互协议使用 protobuf 3.0 , c
|
|||||||
- canal php客户端: [https://github.com/xingwenge/canal-php](https://github.com/xingwenge/canal-php)
|
- canal php客户端: [https://github.com/xingwenge/canal-php](https://github.com/xingwenge/canal-php)
|
||||||
- canal Python客户端:[https://github.com/haozi3156666/canal-python](https://github.com/haozi3156666/canal-python)
|
- canal Python客户端:[https://github.com/haozi3156666/canal-python](https://github.com/haozi3156666/canal-python)
|
||||||
- canal Rust客户端:[https://github.com/laohanlinux/canal-rs](https://github.com/laohanlinux/canal-rs)
|
- canal Rust客户端:[https://github.com/laohanlinux/canal-rs](https://github.com/laohanlinux/canal-rs)
|
||||||
- canal Nodejs客户端:[https://github.com/marmot-z/canal-nodejs](https://github.com/marmot-z/canal-nodejs)
|
|
||||||
|
|
||||||
canal 作为 MySQL binlog 增量获取和解析工具,可将变更记录投递到 MQ 系统中,比如 Kafka/RocketMQ,可以借助于 MQ 的多语言能力
|
canal 作为 MySQL binlog 增量获取和解析工具,可将变更记录投递到 MQ 系统中,比如 Kafka/RocketMQ,可以借助于 MQ 的多语言能力
|
||||||
|
|
||||||
- 参考文档: [Canal Kafka/RocketMQ QuickStart](https://github.com/alibaba/canal/wiki/Canal-Kafka-RocketMQ-QuickStart)
|
- 参考文档: [Canal Kafka/RocketMQ QuickStart](https://github.com/alibaba/canal/wiki/Canal-Kafka-RocketMQ-QuickStart)
|
||||||
|
|
||||||
## 相关开源&产品
|
## 相关开源
|
||||||
|
|
||||||
- [canal 消费端开源项目: Otter](http://github.com/alibaba/otter)
|
- [canal 消费端开源项目: Otter](http://github.com/alibaba/otter)
|
||||||
- [阿里巴巴去 Oracle 数据迁移同步工具: yugong](http://github.com/alibaba/yugong)
|
- [阿里巴巴去 Oracle 数据迁移同步工具: yugong](http://github.com/alibaba/yugong)
|
||||||
- [阿里巴巴离线同步开源项目 DataX](https://github.com/alibaba/datax)
|
|
||||||
- [阿里巴巴数据库连接池开源项目 Druid](https://github.com/alibaba/druid)
|
|
||||||
- [阿里巴巴实时数据同步工具 DTS](https://www.aliyun.com/product/dts)
|
|
||||||
|
|
||||||
## 问题反馈
|
## 问题反馈
|
||||||
- 报告 issue: [github issues](https://github.com/alibaba/canal/issues)
|
- 报告 issue: [github issues](https://github.com/alibaba/canal/issues)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.admin</artifactId>
|
<artifactId>canal.admin</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.7-SNAPSHOT</version>
|
<version>1.1.5-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ export default {
|
|||||||
canalInstanceDetail(this.$route.query.id).then(response => {
|
canalInstanceDetail(this.$route.query.id).then(response => {
|
||||||
const data = response.data
|
const data = response.data
|
||||||
this.form.id = data.id
|
this.form.id = data.id
|
||||||
this.form.name = data.name + '/instance.properties'
|
this.form.name = data.name + '/instance.propertios'
|
||||||
this.form.content = data.content
|
this.form.content = data.content
|
||||||
this.form.clusterServerId = data.clusterServerId
|
this.form.clusterServerId = data.clusterServerId
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.admin</artifactId>
|
<artifactId>canal.admin</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.7-SNAPSHOT</version>
|
<version>1.1.5-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>canal.admin-web</artifactId>
|
<artifactId>canal.admin-web</artifactId>
|
||||||
|
|||||||
@@ -1,13 +1,5 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
case $(uname) in
|
sh stop.sh
|
||||||
Linux)
|
|
||||||
bin_abs_path=$(readlink -f $(dirname $0))
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
bin_abs_path=$(cd $(dirname $0) ||exit ; pwd)
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
sh "$bin_abs_path"/stop.sh
|
sh startup.sh
|
||||||
sh "$bin_abs_path"/startup.sh
|
|
||||||
|
|||||||
@@ -56,29 +56,14 @@ in
|
|||||||
exit;;
|
exit;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
JavaVersion=`$JAVA -version 2>&1 |awk 'NR==1{ gsub(/"/,""); print $3 }' | awk -F '.' '{print $1}'`
|
|
||||||
str=`file -L $JAVA | grep 64-bit`
|
str=`file -L $JAVA | grep 64-bit`
|
||||||
|
|
||||||
JAVA_OPTS="$JAVA_OPTS -Xss256k -XX:+AggressiveOpts -XX:-UseBiasedLocking -XX:-OmitStackTraceInFastThrow -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$base/logs"
|
|
||||||
if [ $JavaVersion -ge 11 ] ; then
|
|
||||||
#JAVA_OPTS="$JAVA_OPTS -Xlog:gc*:$base_log/gc.log:time "
|
|
||||||
JAVA_OPTS="$JAVA_OPTS"
|
|
||||||
else
|
|
||||||
#JAVA_OPTS="$JAVA_OPTS -Xloggc:$base/logs/canal/gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCApplicationStoppedTime"
|
|
||||||
JAVA_OPTS="$JAVA_OPTS -XX:+UseFastAccessorMethods -XX:+PrintAdaptiveSizePolicy -XX:+PrintTenuringDistribution"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -n "$str" ]; then
|
if [ -n "$str" ]; then
|
||||||
if [ $JavaVersion -ge 11 ] ; then
|
JAVA_OPTS="-server -Xms2048m -Xmx3072m"
|
||||||
# For G1
|
|
||||||
JAVA_OPTS="-server -Xms2g -Xmx3g -XX:+UseG1GC -XX:MaxGCPauseMillis=250 -XX:+UseGCOverheadLimit -XX:+ExplicitGCInvokesConcurrent $JAVA_OPTS"
|
|
||||||
else
|
|
||||||
JAVA_OPTS="-server -Xms2g -Xmx3g -Xmn1g -XX:SurvivorRatio=2 -XX:PermSize=96m -XX:MaxPermSize=256m -XX:MaxTenuringThreshold=15 -XX:+DisableExplicitGC $JAVA_OPTS"
|
|
||||||
fi
|
|
||||||
else
|
else
|
||||||
JAVA_OPTS="-server -Xms1024m -Xmx1024m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:MaxPermSize=128m $JAVA_OPTS"
|
JAVA_OPTS="-server -Xms1024m -Xmx1024m"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
JAVA_OPTS="$JAVA_OPTS -XX:+UseG1GC -XX:MaxGCPauseMillis=250 -XX:+UseGCOverheadLimit -XX:+ExplicitGCInvokesConcurrent -XX:+PrintAdaptiveSizePolicy -XX:+PrintTenuringDistribution"
|
||||||
JAVA_OPTS=" $JAVA_OPTS -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Dfile.encoding=UTF-8"
|
JAVA_OPTS=" $JAVA_OPTS -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Dfile.encoding=UTF-8"
|
||||||
CANAL_OPTS="-DappName=canal-admin"
|
CANAL_OPTS="-DappName=canal-admin"
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,6 @@ public class Threads {
|
|||||||
pool,
|
pool,
|
||||||
0L,
|
0L,
|
||||||
TimeUnit.MILLISECONDS,
|
TimeUnit.MILLISECONDS,
|
||||||
new ArrayBlockingQueue<>(pool * 20),
|
new ArrayBlockingQueue<Runnable>(pool * 20),
|
||||||
DaemonThreadFactory.daemonThreadFactory);
|
DaemonThreadFactory.daemonThreadFactory);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,5 @@
|
|||||||
package com.alibaba.otter.canal.admin.config;
|
package com.alibaba.otter.canal.admin.config;
|
||||||
|
|
||||||
import io.ebean.EbeanServer;
|
|
||||||
import io.ebean.EbeanServerFactory;
|
|
||||||
import io.ebean.config.ServerConfig;
|
|
||||||
import io.ebean.config.UnderscoreNamingConvention;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -13,6 +8,11 @@ import javax.sql.DataSource;
|
|||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import io.ebean.EbeanServer;
|
||||||
|
import io.ebean.EbeanServerFactory;
|
||||||
|
import io.ebean.config.ServerConfig;
|
||||||
|
import io.ebean.config.UnderscoreNamingConvention;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ebean 配置
|
* Ebean 配置
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -84,9 +84,7 @@ public class WebConfig implements WebMvcConfigurer {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
.addPathPatterns("/api/**")
|
.addPathPatterns("/api/**")
|
||||||
.excludePathPatterns("/api/**/config/server_polling")
|
.excludePathPatterns("/api/**/config/**")
|
||||||
.excludePathPatterns("/api/**/config/instances_polling")
|
|
||||||
.excludePathPatterns("/api/**/config/instance_polling/**")
|
|
||||||
.excludePathPatterns("/api/**/user/login")
|
.excludePathPatterns("/api/**/user/login")
|
||||||
.excludePathPatterns("/api/**/user/logout")
|
.excludePathPatterns("/api/**/user/logout")
|
||||||
.excludePathPatterns("/api/**/user/info");
|
.excludePathPatterns("/api/**/user/info");
|
||||||
|
|||||||
@@ -108,7 +108,9 @@ public class SimpleAdminConnector implements AdminConnector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
connected = true;
|
connected = true;
|
||||||
} catch (IOException | NoSuchAlgorithmException e) {
|
} catch (IOException e) {
|
||||||
|
throw new ServiceException(e);
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
throw new ServiceException(e);
|
throw new ServiceException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,11 @@ package com.alibaba.otter.canal.admin.connector;
|
|||||||
|
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
|
|
||||||
import org.assertj.core.util.Strings;
|
import com.alibaba.otter.canal.admin.config.SpringContext;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.core.env.Environment;
|
import org.springframework.core.env.Environment;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.admin.config.SpringContext;
|
|
||||||
|
|
||||||
public class SimpleAdminConnectors {
|
public class SimpleAdminConnectors {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(SimpleAdminConnectors.class);
|
private static final Logger logger = LoggerFactory.getLogger(SimpleAdminConnectors.class);
|
||||||
@@ -27,8 +25,7 @@ public class SimpleAdminConnectors {
|
|||||||
connector.connect();
|
connector.connect();
|
||||||
return function.apply(connector);
|
return function.apply(connector);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("connect to ip:{},port:{},user:{},password:{}, failed",
|
logger.error("connect to ip:{},port:{},user:{},password:{}, failed", ip, port, user,passwd);
|
||||||
ip, port, user, getDesensitizationPassword(passwd));
|
|
||||||
logger.error(e.getMessage());
|
logger.error(e.getMessage());
|
||||||
} finally {
|
} finally {
|
||||||
connector.disconnect();
|
connector.disconnect();
|
||||||
@@ -36,14 +33,4 @@ public class SimpleAdminConnectors {
|
|||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String getDesensitizationPassword(String password) {
|
|
||||||
String defaultPassword = "******";
|
|
||||||
|
|
||||||
if (Strings.isNullOrEmpty(password) || password.length() < 6) {
|
|
||||||
return defaultPassword;
|
|
||||||
} else {
|
|
||||||
return String.format("%s******", password.substring(0, 3));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,17 +4,10 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
import com.alibaba.fastjson2.JSONArray;
|
import com.alibaba.fastjson.JSONArray;
|
||||||
import com.alibaba.fastjson2.JSONObject;
|
import com.alibaba.fastjson.JSONObject;
|
||||||
import com.alibaba.otter.canal.admin.model.BaseModel;
|
import com.alibaba.otter.canal.admin.model.BaseModel;
|
||||||
import com.alibaba.otter.canal.admin.model.CanalCluster;
|
import com.alibaba.otter.canal.admin.model.CanalCluster;
|
||||||
import com.alibaba.otter.canal.admin.model.NodeServer;
|
import com.alibaba.otter.canal.admin.model.NodeServer;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.admin.controller;
|
package com.alibaba.otter.canal.admin.controller;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.admin.common.TemplateConfigLoader;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
@@ -8,7 +9,6 @@ import org.springframework.web.bind.annotation.RequestBody;
|
|||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.admin.common.TemplateConfigLoader;
|
|
||||||
import com.alibaba.otter.canal.admin.model.BaseModel;
|
import com.alibaba.otter.canal.admin.model.BaseModel;
|
||||||
import com.alibaba.otter.canal.admin.model.CanalConfig;
|
import com.alibaba.otter.canal.admin.model.CanalConfig;
|
||||||
import com.alibaba.otter.canal.admin.service.CanalConfigService;
|
import com.alibaba.otter.canal.admin.service.CanalConfigService;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.alibaba.otter.canal.admin.controller;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.admin.common.TemplateConfigLoader;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
@@ -14,7 +15,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
|||||||
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.admin.common.TemplateConfigLoader;
|
|
||||||
import com.alibaba.otter.canal.admin.model.BaseModel;
|
import com.alibaba.otter.canal.admin.model.BaseModel;
|
||||||
import com.alibaba.otter.canal.admin.model.CanalInstanceConfig;
|
import com.alibaba.otter.canal.admin.model.CanalInstanceConfig;
|
||||||
import com.alibaba.otter.canal.admin.model.Pager;
|
import com.alibaba.otter.canal.admin.model.Pager;
|
||||||
@@ -143,7 +143,8 @@ public class CanalInstanceController {
|
|||||||
* @return 是否成功
|
* @return 是否成功
|
||||||
*/
|
*/
|
||||||
@PutMapping(value = "/instance/status/{id}")
|
@PutMapping(value = "/instance/status/{id}")
|
||||||
public BaseModel<Boolean> instanceStart(@PathVariable Long id, @RequestParam String option, @PathVariable String env) {
|
public BaseModel<Boolean> instanceStart(@PathVariable Long id, @RequestParam String option,
|
||||||
|
@PathVariable String env) {
|
||||||
return BaseModel.getInstance(canalInstanceConfigService.instanceOperation(id, option));
|
return BaseModel.getInstance(canalInstanceConfigService.instanceOperation(id, option));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -46,15 +46,14 @@ public class PollingConfigController {
|
|||||||
public BaseModel<CanalConfig> canalConfigPoll(@RequestHeader String user, @RequestHeader String passwd,
|
public BaseModel<CanalConfig> canalConfigPoll(@RequestHeader String user, @RequestHeader String passwd,
|
||||||
@RequestParam String ip, @RequestParam Integer port,
|
@RequestParam String ip, @RequestParam Integer port,
|
||||||
@RequestParam String md5, @RequestParam boolean register,
|
@RequestParam String md5, @RequestParam boolean register,
|
||||||
@RequestParam String cluster, @RequestParam String name,
|
@RequestParam String cluster, @PathVariable String env) {
|
||||||
@PathVariable String env) {
|
|
||||||
if (!auth(user, passwd)) {
|
if (!auth(user, passwd)) {
|
||||||
throw new RuntimeException("auth :" + user + " is failed");
|
throw new RuntimeException("auth :" + user + " is failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (StringUtils.isEmpty(md5) && register) {
|
if (StringUtils.isEmpty(md5) && register) {
|
||||||
// do something
|
// do something
|
||||||
pollingConfigService.autoRegister(ip, port, cluster, StringUtils.trimToNull(name));
|
pollingConfigService.autoRegister(ip, port, cluster);
|
||||||
}
|
}
|
||||||
|
|
||||||
CanalConfig canalConfig = pollingConfigService.getChangedConfig(ip, port, md5);
|
CanalConfig canalConfig = pollingConfigService.getChangedConfig(ip, port, md5);
|
||||||
|
|||||||
@@ -1,28 +1,20 @@
|
|||||||
package com.alibaba.otter.canal.admin.controller;
|
package com.alibaba.otter.canal.admin.controller;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.admin.service.UserService;
|
||||||
|
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||||
|
import com.github.benmanes.caffeine.cache.LoadingCache;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.admin.model.BaseModel;
|
||||||
|
import com.alibaba.otter.canal.admin.model.User;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestParam;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.admin.model.BaseModel;
|
|
||||||
import com.alibaba.otter.canal.admin.model.User;
|
|
||||||
import com.alibaba.otter.canal.admin.service.UserService;
|
|
||||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
|
||||||
import com.github.benmanes.caffeine.cache.LoadingCache;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户管理控制层
|
* 用户管理控制层
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package com.alibaba.otter.canal.admin.handler;
|
package com.alibaba.otter.canal.admin.handler;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.admin.common.exception.ServiceException;
|
||||||
|
import com.alibaba.otter.canal.admin.model.BaseModel;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
@@ -8,9 +10,6 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
|
|||||||
import org.springframework.web.bind.annotation.ResponseBody;
|
import org.springframework.web.bind.annotation.ResponseBody;
|
||||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.admin.common.exception.ServiceException;
|
|
||||||
import com.alibaba.otter.canal.admin.model.BaseModel;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MVC异常拦截器
|
* MVC异常拦截器
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -3,11 +3,10 @@ package com.alibaba.otter.canal.admin.model;
|
|||||||
import io.ebean.Finder;
|
import io.ebean.Finder;
|
||||||
import io.ebean.annotation.WhenModified;
|
import io.ebean.annotation.WhenModified;
|
||||||
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import javax.persistence.Entity;
|
||||||
import javax.persistence.Id;
|
import javax.persistence.Id;
|
||||||
import javax.persistence.Table;
|
import javax.persistence.Table;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Canal集群信息实体类
|
* Canal集群信息实体类
|
||||||
|
|||||||
@@ -1,17 +1,11 @@
|
|||||||
package com.alibaba.otter.canal.admin.model;
|
package com.alibaba.otter.canal.admin.model;
|
||||||
|
|
||||||
import io.ebean.Finder;
|
|
||||||
import io.ebean.annotation.WhenModified;
|
|
||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
import javax.persistence.Column;
|
import javax.persistence.*;
|
||||||
import javax.persistence.Entity;
|
|
||||||
import javax.persistence.FetchType;
|
import io.ebean.Finder;
|
||||||
import javax.persistence.Id;
|
import io.ebean.annotation.WhenModified;
|
||||||
import javax.persistence.JoinColumn;
|
|
||||||
import javax.persistence.ManyToOne;
|
|
||||||
import javax.persistence.Transient;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Canal实例配置信息实体类
|
* Canal实例配置信息实体类
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
package com.alibaba.otter.canal.admin.model;
|
package com.alibaba.otter.canal.admin.model;
|
||||||
|
|
||||||
import io.ebean.Ebean;
|
|
||||||
import io.ebean.EbeanServer;
|
|
||||||
|
|
||||||
import javax.persistence.MappedSuperclass;
|
import javax.persistence.MappedSuperclass;
|
||||||
import javax.persistence.OptimisticLockException;
|
import javax.persistence.OptimisticLockException;
|
||||||
|
|
||||||
import org.apache.commons.beanutils.PropertyUtils;
|
import org.apache.commons.beanutils.PropertyUtils;
|
||||||
|
|
||||||
|
import io.ebean.Ebean;
|
||||||
|
import io.ebean.EbeanServer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* EBean Model扩展类
|
* EBean Model扩展类
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -5,13 +5,7 @@ import io.ebean.annotation.WhenModified;
|
|||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
import javax.persistence.Column;
|
import javax.persistence.*;
|
||||||
import javax.persistence.Entity;
|
|
||||||
import javax.persistence.FetchType;
|
|
||||||
import javax.persistence.Id;
|
|
||||||
import javax.persistence.JoinColumn;
|
|
||||||
import javax.persistence.ManyToOne;
|
|
||||||
import javax.persistence.Table;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 节点信息实体类
|
* 节点信息实体类
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ public class Pager<T> implements Serializable {
|
|||||||
private static final long serialVersionUID = -986577815091763517L;
|
private static final long serialVersionUID = -986577815091763517L;
|
||||||
|
|
||||||
private Long count = 0L;
|
private Long count = 0L;
|
||||||
private List<T> items = new ArrayList<>();
|
private List<T> items = new ArrayList<T>();
|
||||||
private Integer page = 1;
|
private Integer page = 1;
|
||||||
private Integer size = 20;
|
private Integer size = 20;
|
||||||
private Long offset = 0L;
|
private Long offset = 0L;
|
||||||
|
|||||||
@@ -3,12 +3,11 @@ package com.alibaba.otter.canal.admin.model;
|
|||||||
import io.ebean.Finder;
|
import io.ebean.Finder;
|
||||||
import io.ebean.annotation.WhenCreated;
|
import io.ebean.annotation.WhenCreated;
|
||||||
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
import javax.persistence.Entity;
|
||||||
import javax.persistence.Id;
|
import javax.persistence.Id;
|
||||||
import javax.persistence.Table;
|
import javax.persistence.Table;
|
||||||
import javax.persistence.Transient;
|
import javax.persistence.Transient;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户信息实体类
|
* 用户信息实体类
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
package com.alibaba.otter.canal.admin.service;
|
package com.alibaba.otter.canal.admin.service;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.admin.model.NodeServer;
|
import com.alibaba.otter.canal.admin.model.NodeServer;
|
||||||
import com.alibaba.otter.canal.admin.model.Pager;
|
import com.alibaba.otter.canal.admin.model.Pager;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
public interface NodeServerService {
|
public interface NodeServerService {
|
||||||
|
|
||||||
void save(NodeServer nodeServer);
|
void save(NodeServer nodeServer);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import com.alibaba.otter.canal.admin.model.CanalInstanceConfig;
|
|||||||
|
|
||||||
public interface PollingConfigService {
|
public interface PollingConfigService {
|
||||||
|
|
||||||
public boolean autoRegister(String ip, Integer adminPort, String cluster, String name);
|
public boolean autoRegister(String ip, Integer adminPort, String cluster);
|
||||||
|
|
||||||
CanalConfig getChangedConfig(String ip, Integer port, String md5);
|
CanalConfig getChangedConfig(String ip, Integer port, String md5);
|
||||||
|
|
||||||
|
|||||||
@@ -109,12 +109,12 @@ public class CanalInstanceServiceImpl implements CanalInstanceService {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Future<Void> f : futures) {
|
for (Future<Void> f :futures){
|
||||||
try {
|
try {
|
||||||
f.get(3, TimeUnit.SECONDS);
|
f.get(3, TimeUnit.SECONDS);
|
||||||
} catch (InterruptedException | ExecutionException e) {
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
// ignore
|
// ignore
|
||||||
} catch (TimeoutException e) {
|
} catch (TimeoutException e){
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -154,12 +154,12 @@ public class NodeServerServiceImpl implements NodeServerService {
|
|||||||
return !status;
|
return !status;
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
for (Future<Boolean> f : futures) {
|
for (Future<Boolean> f :futures){
|
||||||
try {
|
try {
|
||||||
f.get(3, TimeUnit.SECONDS);
|
f.get(3, TimeUnit.SECONDS);
|
||||||
} catch (InterruptedException | ExecutionException e) {
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
// ignore
|
// ignore
|
||||||
} catch (TimeoutException e) {
|
} catch (TimeoutException e){
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package com.alibaba.otter.canal.admin.service.impl;
|
|||||||
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
import java.security.NoSuchAlgorithmException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
import org.apache.commons.lang.StringUtils;
|
||||||
@@ -29,11 +28,11 @@ public class PollingConfigServiceImpl implements PollingConfigService {
|
|||||||
@Autowired
|
@Autowired
|
||||||
CanalClusterService canalClusterService;
|
CanalClusterService canalClusterService;
|
||||||
|
|
||||||
public boolean autoRegister(String ip, Integer adminPort, String cluster, String name) {
|
public boolean autoRegister(String ip, Integer adminPort, String cluster) {
|
||||||
NodeServer server = NodeServer.find.query().where().eq("ip", ip).eq("adminPort", adminPort).findOne();
|
NodeServer server = NodeServer.find.query().where().eq("ip", ip).eq("adminPort", adminPort).findOne();
|
||||||
if (server == null) {
|
if (server == null) {
|
||||||
server = new NodeServer();
|
server = new NodeServer();
|
||||||
server.setName(Optional.ofNullable(name).orElse(ip));
|
server.setName(ip);
|
||||||
server.setIp(ip);
|
server.setIp(ip);
|
||||||
server.setAdminPort(adminPort);
|
server.setAdminPort(adminPort);
|
||||||
server.setTcpPort(adminPort + 1);
|
server.setTcpPort(adminPort + 1);
|
||||||
|
|||||||
@@ -21,8 +21,6 @@ public class UserServiceImpl implements UserService {
|
|||||||
|
|
||||||
private static byte[] seeds = "canal is best!".getBytes();
|
private static byte[] seeds = "canal is best!".getBytes();
|
||||||
|
|
||||||
private static final Integer PASSWORD_LENGTH = 6;
|
|
||||||
|
|
||||||
public User find4Login(String username, String password) {
|
public User find4Login(String username, String password) {
|
||||||
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
|
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
|
||||||
return null;
|
return null;
|
||||||
@@ -45,9 +43,6 @@ public class UserServiceImpl implements UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void update(User user) {
|
public void update(User user) {
|
||||||
if (user.getPassword().length() < PASSWORD_LENGTH) {
|
|
||||||
throw new ServiceException("The new password is too short,must more than 6 digits");
|
|
||||||
}
|
|
||||||
User userTmp = User.find.query().where().eq("username", user.getUsername()).findOne();
|
User userTmp = User.find.query().where().eq("username", user.getUsername()).findOne();
|
||||||
if (userTmp == null) {
|
if (userTmp == null) {
|
||||||
throw new ServiceException();
|
throw new ServiceException();
|
||||||
|
|||||||
@@ -8,24 +8,20 @@ canal.register.ip =
|
|||||||
canal.port = 11111
|
canal.port = 11111
|
||||||
canal.metrics.pull.port = 11112
|
canal.metrics.pull.port = 11112
|
||||||
# canal instance user/passwd
|
# canal instance user/passwd
|
||||||
# canal.user = canal
|
canal.user = canal
|
||||||
# canal.passwd = E3619321C1A937C46A0D8BD1DAC39F93B27D4458
|
canal.passwd = E3619321C1A937C46A0D8BD1DAC39F93B27D4458
|
||||||
|
|
||||||
# canal admin config
|
# canal admin config
|
||||||
#canal.admin.manager = 127.0.0.1:8089
|
canal.admin.manager = 127.0.0.1:8089
|
||||||
canal.admin.port = 11110
|
canal.admin.port = 11110
|
||||||
canal.admin.user = admin
|
canal.admin.user = admin
|
||||||
canal.admin.passwd = 4ACFE3202A5FF5CF467898FC58AAB1D615029441
|
canal.admin.passwd = 4ACFE3202A5FF5CF467898FC58AAB1D615029441
|
||||||
# admin auto register
|
|
||||||
#canal.admin.register.auto = true
|
|
||||||
#canal.admin.register.cluster =
|
|
||||||
#canal.admin.register.name =
|
|
||||||
|
|
||||||
canal.zkServers =
|
canal.zkServers =
|
||||||
# flush data to zk
|
# flush data to zk
|
||||||
canal.zookeeper.flush.period = 1000
|
canal.zookeeper.flush.period = 1000
|
||||||
canal.withoutNetty = false
|
canal.withoutNetty = false
|
||||||
# tcp, kafka, rocketMQ, rabbitMQ, pulsarMQ
|
# tcp, kafka, RocketMQ
|
||||||
canal.serverMode = tcp
|
canal.serverMode = tcp
|
||||||
# flush meta cursor/parse position to file
|
# flush meta cursor/parse position to file
|
||||||
canal.file.data.dir = ${canal.conf.dir}
|
canal.file.data.dir = ${canal.conf.dir}
|
||||||
@@ -64,9 +60,6 @@ canal.instance.filter.query.ddl = false
|
|||||||
canal.instance.filter.table.error = false
|
canal.instance.filter.table.error = false
|
||||||
canal.instance.filter.rows = false
|
canal.instance.filter.rows = false
|
||||||
canal.instance.filter.transaction.entry = false
|
canal.instance.filter.transaction.entry = false
|
||||||
canal.instance.filter.dml.insert = false
|
|
||||||
canal.instance.filter.dml.update = false
|
|
||||||
canal.instance.filter.dml.delete = false
|
|
||||||
|
|
||||||
# binlog format/image check
|
# binlog format/image check
|
||||||
canal.instance.binlog.format = ROW,STATEMENT,MIXED
|
canal.instance.binlog.format = ROW,STATEMENT,MIXED
|
||||||
@@ -93,6 +86,10 @@ canal.instance.tsdb.snapshot.interval = 24
|
|||||||
# purge snapshot expire , default 360 hour(15 days)
|
# purge snapshot expire , default 360 hour(15 days)
|
||||||
canal.instance.tsdb.snapshot.expire = 360
|
canal.instance.tsdb.snapshot.expire = 360
|
||||||
|
|
||||||
|
# aliyun ak/sk , support rds/mq
|
||||||
|
canal.aliyun.accessKey =
|
||||||
|
canal.aliyun.secretKey =
|
||||||
|
|
||||||
#################################################
|
#################################################
|
||||||
######### destinations #############
|
######### destinations #############
|
||||||
#################################################
|
#################################################
|
||||||
@@ -102,9 +99,6 @@ canal.conf.dir = ../conf
|
|||||||
# auto scan instance dir add/remove and start/stop instance
|
# auto scan instance dir add/remove and start/stop instance
|
||||||
canal.auto.scan = true
|
canal.auto.scan = true
|
||||||
canal.auto.scan.interval = 5
|
canal.auto.scan.interval = 5
|
||||||
# set this value to 'true' means that when binlog pos not found, skip to latest.
|
|
||||||
# WARN: pls keep 'false' in production env, or if you know what you want.
|
|
||||||
canal.auto.reset.latest.pos.mode = false
|
|
||||||
|
|
||||||
canal.instance.tsdb.spring.xml = classpath:spring/tsdb/h2-tsdb.xml
|
canal.instance.tsdb.spring.xml = classpath:spring/tsdb/h2-tsdb.xml
|
||||||
#canal.instance.tsdb.spring.xml = classpath:spring/tsdb/mysql-tsdb.xml
|
#canal.instance.tsdb.spring.xml = classpath:spring/tsdb/mysql-tsdb.xml
|
||||||
@@ -117,71 +111,29 @@ canal.instance.global.spring.xml = classpath:spring/file-instance.xml
|
|||||||
#canal.instance.global.spring.xml = classpath:spring/default-instance.xml
|
#canal.instance.global.spring.xml = classpath:spring/default-instance.xml
|
||||||
|
|
||||||
##################################################
|
##################################################
|
||||||
######### MQ Properties #############
|
######### MQ #############
|
||||||
##################################################
|
##################################################
|
||||||
# aliyun ak/sk , support rds/mq
|
canal.mq.servers = 127.0.0.1:6667
|
||||||
canal.aliyun.accessKey =
|
canal.mq.retries = 0
|
||||||
canal.aliyun.secretKey =
|
canal.mq.batchSize = 16384
|
||||||
canal.aliyun.uid=
|
canal.mq.maxRequestSize = 1048576
|
||||||
|
canal.mq.lingerMs = 100
|
||||||
canal.mq.flatMessage = true
|
canal.mq.bufferMemory = 33554432
|
||||||
canal.mq.canalBatchSize = 50
|
canal.mq.canalBatchSize = 50
|
||||||
canal.mq.canalGetTimeout = 100
|
canal.mq.canalGetTimeout = 100
|
||||||
|
canal.mq.flatMessage = true
|
||||||
|
canal.mq.compressionType = none
|
||||||
|
canal.mq.acks = all
|
||||||
|
#canal.mq.properties. =
|
||||||
|
canal.mq.producerGroup = test
|
||||||
# Set this value to "cloud", if you want open message trace feature in aliyun.
|
# Set this value to "cloud", if you want open message trace feature in aliyun.
|
||||||
canal.mq.accessChannel = local
|
canal.mq.accessChannel = local
|
||||||
|
# aliyun mq namespace
|
||||||
canal.mq.database.hash = true
|
#canal.mq.namespace =
|
||||||
canal.mq.send.thread.size = 30
|
|
||||||
canal.mq.build.thread.size = 8
|
|
||||||
|
|
||||||
##################################################
|
##################################################
|
||||||
######### Kafka #############
|
######### Kafka Kerberos Info #############
|
||||||
##################################################
|
##################################################
|
||||||
kafka.bootstrap.servers = 127.0.0.1:6667
|
canal.mq.kafka.kerberos.enable = false
|
||||||
kafka.acks = all
|
canal.mq.kafka.kerberos.krb5FilePath = "../conf/kerberos/krb5.conf"
|
||||||
kafka.compression.type = none
|
canal.mq.kafka.kerberos.jaasFilePath = "../conf/kerberos/jaas.conf"
|
||||||
kafka.batch.size = 16384
|
|
||||||
kafka.linger.ms = 1
|
|
||||||
kafka.max.request.size = 1048576
|
|
||||||
kafka.buffer.memory = 33554432
|
|
||||||
kafka.max.in.flight.requests.per.connection = 1
|
|
||||||
kafka.retries = 0
|
|
||||||
|
|
||||||
kafka.kerberos.enable = false
|
|
||||||
kafka.kerberos.krb5.file = ../conf/kerberos/krb5.conf
|
|
||||||
kafka.kerberos.jaas.file = ../conf/kerberos/jaas.conf
|
|
||||||
|
|
||||||
# sasl demo
|
|
||||||
# kafka.sasl.jaas.config = org.apache.kafka.common.security.scram.ScramLoginModule required \\n username=\"alice\" \\npassword="alice-secret\";
|
|
||||||
# kafka.sasl.mechanism = SCRAM-SHA-512
|
|
||||||
# kafka.security.protocol = SASL_PLAINTEXT
|
|
||||||
|
|
||||||
##################################################
|
|
||||||
######### RocketMQ #############
|
|
||||||
##################################################
|
|
||||||
rocketmq.producer.group = test
|
|
||||||
rocketmq.enable.message.trace = false
|
|
||||||
rocketmq.customized.trace.topic =
|
|
||||||
rocketmq.namespace =
|
|
||||||
rocketmq.namesrv.addr = 127.0.0.1:9876
|
|
||||||
rocketmq.retry.times.when.send.failed = 0
|
|
||||||
rocketmq.vip.channel.enabled = false
|
|
||||||
rocketmq.tag =
|
|
||||||
|
|
||||||
##################################################
|
|
||||||
######### RabbitMQ #############
|
|
||||||
##################################################
|
|
||||||
rabbitmq.host =
|
|
||||||
rabbitmq.virtual.host =
|
|
||||||
rabbitmq.exchange =
|
|
||||||
rabbitmq.username =
|
|
||||||
rabbitmq.password =
|
|
||||||
rabbitmq.deliveryMode =
|
|
||||||
|
|
||||||
|
|
||||||
##################################################
|
|
||||||
######### Pulsar #############
|
|
||||||
##################################################
|
|
||||||
pulsarmq.serverUrl =
|
|
||||||
pulsarmq.roleToken =
|
|
||||||
pulsarmq.topicTenantPrefix =
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<artifactId>canal.admin</artifactId>
|
<artifactId>canal.admin</artifactId>
|
||||||
<version>1.1.7-SNAPSHOT</version>
|
<version>1.1.5-SNAPSHOT</version>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
<name>canal admin module for otter ${project.version}</name>
|
<name>canal admin module for otter ${project.version}</name>
|
||||||
<modules>
|
<modules>
|
||||||
@@ -18,7 +18,6 @@
|
|||||||
<java_source_version>1.8</java_source_version>
|
<java_source_version>1.8</java_source_version>
|
||||||
<java_target_version>1.8</java_target_version>
|
<java_target_version>1.8</java_target_version>
|
||||||
<file_encoding>UTF-8</file_encoding>
|
<file_encoding>UTF-8</file_encoding>
|
||||||
<log4j_version>2.17.0</log4j_version>
|
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
@@ -70,7 +69,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>mysql</groupId>
|
<groupId>mysql</groupId>
|
||||||
<artifactId>mysql-connector-java</artifactId>
|
<artifactId>mysql-connector-java</artifactId>
|
||||||
<version>5.1.48</version>
|
<version>8.0.17</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||||
@@ -92,21 +91,6 @@
|
|||||||
<artifactId>ebean</artifactId>
|
<artifactId>ebean</artifactId>
|
||||||
<version>11.41.1</version>
|
<version>11.41.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-core</artifactId>
|
|
||||||
<version>${log4j_version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-api</artifactId>
|
|
||||||
<version>${log4j_version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-to-slf4j</artifactId>
|
|
||||||
<version>${log4j_version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</dependencyManagement>
|
</dependencyManagement>
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.client-adapter</artifactId>
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.7-SNAPSHOT</version>
|
<version>1.1.5-SNAPSHOT</version>
|
||||||
<relativePath>../pom.xml</relativePath>
|
<relativePath>../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
@@ -18,13 +18,29 @@
|
|||||||
<version>${project.version}</version>
|
<version>${project.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>connector.core</artifactId>
|
<artifactId>spring-core</artifactId>
|
||||||
<version>${project.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-boot</artifactId>
|
<artifactId>spring-aop</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-context</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-jdbc</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-orm</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>joda-time</groupId>
|
<groupId>joda-time</groupId>
|
||||||
@@ -34,6 +50,10 @@
|
|||||||
<groupId>com.alibaba</groupId>
|
<groupId>com.alibaba</groupId>
|
||||||
<artifactId>druid</artifactId>
|
<artifactId>druid</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.yaml</groupId>
|
||||||
|
<artifactId>snakeyaml</artifactId>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.powermock</groupId>
|
<groupId>org.powermock</groupId>
|
||||||
<artifactId>powermock-api-mockito</artifactId>
|
<artifactId>powermock-api-mockito</artifactId>
|
||||||
|
|||||||
@@ -1,87 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.Dml;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
public class ProxyOuterAdapter implements OuterAdapter {
|
|
||||||
|
|
||||||
private OuterAdapter outerAdapter;
|
|
||||||
|
|
||||||
public ProxyOuterAdapter(OuterAdapter outerAdapter) {
|
|
||||||
this.outerAdapter = outerAdapter;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ClassLoader changeCL() {
|
|
||||||
ClassLoader cl = Thread.currentThread().getContextClassLoader();
|
|
||||||
Thread.currentThread().setContextClassLoader(outerAdapter.getClass().getClassLoader());
|
|
||||||
return cl;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void revertCL(ClassLoader cl) {
|
|
||||||
Thread.currentThread().setContextClassLoader(cl);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void init(OuterAdapterConfig configuration, Properties envProperties) {
|
|
||||||
ClassLoader cl = changeCL();
|
|
||||||
try {
|
|
||||||
outerAdapter.init(configuration, envProperties);
|
|
||||||
} finally {
|
|
||||||
revertCL(cl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void sync(List<Dml> dmls) {
|
|
||||||
ClassLoader cl = changeCL();
|
|
||||||
try {
|
|
||||||
outerAdapter.sync(dmls);
|
|
||||||
} finally {
|
|
||||||
revertCL(cl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void destroy() {
|
|
||||||
ClassLoader cl = changeCL();
|
|
||||||
try {
|
|
||||||
outerAdapter.destroy();
|
|
||||||
} finally {
|
|
||||||
revertCL(cl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public EtlResult etl(String task, List<String> params) {
|
|
||||||
ClassLoader cl = changeCL();
|
|
||||||
try {
|
|
||||||
return OuterAdapter.super.etl(task, params);
|
|
||||||
} finally {
|
|
||||||
revertCL(cl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Map<String, Object> count(String task) {
|
|
||||||
ClassLoader cl = changeCL();
|
|
||||||
try {
|
|
||||||
return OuterAdapter.super.count(task);
|
|
||||||
} finally {
|
|
||||||
revertCL(cl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getDestination(String task) {
|
|
||||||
ClassLoader cl = changeCL();
|
|
||||||
try {
|
|
||||||
return OuterAdapter.super.getDestination(task);
|
|
||||||
} finally {
|
|
||||||
revertCL(cl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import org.springframework.util.PropertyPlaceholderHelper;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.bind.PropertiesConfigurationFactory;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将yaml内容绑定到指定对象, 遵循spring yml的绑定规范
|
||||||
|
*
|
||||||
|
* @author reweerma 2019-2-1 上午9:14:02
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class YmlConfigBinder {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将当前内容绑定到指定对象
|
||||||
|
*
|
||||||
|
* @param content yml内容
|
||||||
|
* @param clazz 指定对象类型
|
||||||
|
* @return 对象
|
||||||
|
*/
|
||||||
|
public static <T> T bindYmlToObj(String content, Class<T> clazz) {
|
||||||
|
return bindYmlToObj(null, content, clazz, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将当前内容绑定到指定对象并指定内容编码格式
|
||||||
|
*
|
||||||
|
* @param content yml内容
|
||||||
|
* @param clazz 指定对象类型
|
||||||
|
* @param charset yml内容编码格式
|
||||||
|
* @return 对象
|
||||||
|
*/
|
||||||
|
public static <T> T bindYmlToObj(String content, Class<T> clazz, String charset) {
|
||||||
|
return bindYmlToObj(null, content, clazz, charset);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将当前内容指定前缀部分绑定到指定对象
|
||||||
|
*
|
||||||
|
* @param prefix 指定前缀
|
||||||
|
* @param content yml内容
|
||||||
|
* @param clazz 指定对象类型
|
||||||
|
* @return 对象
|
||||||
|
*/
|
||||||
|
public static <T> T bindYmlToObj(String prefix, String content, Class<T> clazz) {
|
||||||
|
return bindYmlToObj(prefix, content, clazz, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将当前内容指定前缀部分绑定到指定对象并指定内容编码格式
|
||||||
|
*
|
||||||
|
* @param prefix 指定前缀
|
||||||
|
* @param content yml内容
|
||||||
|
* @param clazz 指定对象类型
|
||||||
|
* @param charset yml内容编码格式
|
||||||
|
* @return 对象
|
||||||
|
*/
|
||||||
|
public static <T> T bindYmlToObj(String prefix, String content, Class<T> clazz, String charset) {
|
||||||
|
return bindYmlToObj(prefix, content, clazz, charset, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将当前内容指定前缀部分绑定到指定对象并用环境变量中的属性替换占位符, 例: 当前内容有属性 zkServers: ${zookeeper.servers}
|
||||||
|
* 在envProperties中有属性 zookeeper.servers:
|
||||||
|
* 192.168.0.1:2181,192.168.0.1:2181,192.168.0.1:2181 则当前内容 zkServers 会被替换为
|
||||||
|
* zkServers: 192.168.0.1:2181,192.168.0.1:2181,192.168.0.1:2181 注: 假设绑定的类中
|
||||||
|
* zkServers 属性是 List<String> 对象, 则会自动映射成List
|
||||||
|
*
|
||||||
|
* @param prefix 指定前缀
|
||||||
|
* @param content yml内容
|
||||||
|
* @param clazz 指定对象类型
|
||||||
|
* @param charset yml内容编码格式
|
||||||
|
* @return 对象
|
||||||
|
*/
|
||||||
|
public static <T> T bindYmlToObj(String prefix, String content, Class<T> clazz, String charset,
|
||||||
|
Properties baseProperties) {
|
||||||
|
try {
|
||||||
|
byte[] contentBytes;
|
||||||
|
if (charset == null) {
|
||||||
|
contentBytes = content.getBytes("UTF-8");
|
||||||
|
} else {
|
||||||
|
contentBytes = content.getBytes(charset);
|
||||||
|
}
|
||||||
|
YamlPropertySourceLoader propertySourceLoader = new YamlPropertySourceLoader();
|
||||||
|
Resource configResource = new ByteArrayResource(contentBytes);
|
||||||
|
PropertySource<?> propertySource = propertySourceLoader.load("manualBindConfig", configResource, null);
|
||||||
|
|
||||||
|
if (propertySource == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Properties properties = new Properties();
|
||||||
|
Map<String, Object> propertiesRes = new LinkedHashMap<>();
|
||||||
|
if (!StringUtils.isEmpty(prefix) && !prefix.endsWith(".")) {
|
||||||
|
prefix = prefix + ".";
|
||||||
|
}
|
||||||
|
|
||||||
|
properties.putAll((Map<?, ?>) propertySource.getSource());
|
||||||
|
|
||||||
|
if (baseProperties != null) {
|
||||||
|
baseProperties.putAll(properties);
|
||||||
|
properties = baseProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Map.Entry<?, ?> entry : ((Map<?, ?>) propertySource.getSource()).entrySet()) {
|
||||||
|
String key = (String) entry.getKey();
|
||||||
|
Object value = entry.getValue();
|
||||||
|
|
||||||
|
if (prefix != null) {
|
||||||
|
if (key != null && key.startsWith(prefix)) {
|
||||||
|
key = key.substring(prefix.length());
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value instanceof String && ((String) value).contains("${") && ((String) value).contains("}")) {
|
||||||
|
PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");
|
||||||
|
value = propertyPlaceholderHelper.replacePlaceholders((String) value, properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
propertiesRes.put(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (propertiesRes.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
propertySource = new MapPropertySource(propertySource.getName(), propertiesRes);
|
||||||
|
|
||||||
|
T target = clazz.newInstance();
|
||||||
|
|
||||||
|
MutablePropertySources propertySources = new MutablePropertySources();
|
||||||
|
propertySources.addFirst(propertySource);
|
||||||
|
|
||||||
|
PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>(target);
|
||||||
|
factory.setPropertySources(propertySources);
|
||||||
|
factory.setIgnoreInvalidFields(true);
|
||||||
|
factory.setIgnoreUnknownFields(true);
|
||||||
|
|
||||||
|
factory.bindPropertiesToTarget();
|
||||||
|
|
||||||
|
return target;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link PropertyNamePatternsMatcher} that matches when a property name exactly
|
||||||
|
* matches one of the given names, or starts with one of the given names
|
||||||
|
* followed by a delimiter. This implementation is optimized for frequent calls.
|
||||||
|
*
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @since 1.2.0
|
||||||
|
*/
|
||||||
|
class DefaultPropertyNamePatternsMatcher implements PropertyNamePatternsMatcher {
|
||||||
|
|
||||||
|
private final char[] delimiters;
|
||||||
|
|
||||||
|
private final boolean ignoreCase;
|
||||||
|
|
||||||
|
private final String[] names;
|
||||||
|
|
||||||
|
protected DefaultPropertyNamePatternsMatcher(char[] delimiters, String... names){
|
||||||
|
this(delimiters, false, names);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected DefaultPropertyNamePatternsMatcher(char[] delimiters, boolean ignoreCase, String... names){
|
||||||
|
this(delimiters, ignoreCase, new HashSet<String>(Arrays.asList(names)));
|
||||||
|
}
|
||||||
|
|
||||||
|
DefaultPropertyNamePatternsMatcher(char[] delimiters, boolean ignoreCase, Set<String> names){
|
||||||
|
this.delimiters = delimiters;
|
||||||
|
this.ignoreCase = ignoreCase;
|
||||||
|
this.names = names.toArray(new String[names.size()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(String propertyName) {
|
||||||
|
char[] propertyNameChars = propertyName.toCharArray();
|
||||||
|
boolean[] match = new boolean[this.names.length];
|
||||||
|
boolean noneMatched = true;
|
||||||
|
for (int i = 0; i < this.names.length; i++) {
|
||||||
|
if (this.names[i].length() <= propertyNameChars.length) {
|
||||||
|
match[i] = true;
|
||||||
|
noneMatched = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (noneMatched) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (int charIndex = 0; charIndex < propertyNameChars.length; charIndex++) {
|
||||||
|
for (int nameIndex = 0; nameIndex < this.names.length; nameIndex++) {
|
||||||
|
if (match[nameIndex]) {
|
||||||
|
match[nameIndex] = false;
|
||||||
|
if (charIndex < this.names[nameIndex].length()) {
|
||||||
|
if (isCharMatch(this.names[nameIndex].charAt(charIndex), propertyNameChars[charIndex])) {
|
||||||
|
match[nameIndex] = true;
|
||||||
|
noneMatched = false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
char charAfter = propertyNameChars[this.names[nameIndex].length()];
|
||||||
|
if (isDelimiter(charAfter)) {
|
||||||
|
match[nameIndex] = true;
|
||||||
|
noneMatched = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (noneMatched) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < match.length; i++) {
|
||||||
|
if (match[i]) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isCharMatch(char c1, char c2) {
|
||||||
|
if (this.ignoreCase) {
|
||||||
|
return Character.toLowerCase(c1) == Character.toLowerCase(c2);
|
||||||
|
}
|
||||||
|
return c1 == c2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isDelimiter(char c) {
|
||||||
|
for (char delimiter : this.delimiters) {
|
||||||
|
if (c == delimiter) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import java.beans.PropertyEditorSupport;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link PropertyNamePatternsMatcher} that matches when a property name exactly
|
||||||
|
* matches one of the given names, or starts with one of the given names
|
||||||
|
* followed by a delimiter. This implementation is optimized for frequent calls.
|
||||||
|
*
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @since 1.2.0
|
||||||
|
*/
|
||||||
|
class InetAddressEditor extends PropertyEditorSupport {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getAsText() {
|
||||||
|
return ((InetAddress) getValue()).getHostAddress();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setAsText(String text) throws IllegalArgumentException {
|
||||||
|
try {
|
||||||
|
setValue(InetAddress.getByName(text));
|
||||||
|
} catch (UnknownHostException ex) {
|
||||||
|
throw new IllegalArgumentException("Cannot locate host", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import org.springframework.beans.PropertyValue;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.PropertySource;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A {@link PropertyValue} that can provide information about its origin.
|
||||||
|
*
|
||||||
|
* @author Andy Wilkinson
|
||||||
|
*/
|
||||||
|
class OriginCapablePropertyValue extends PropertyValue {
|
||||||
|
|
||||||
|
private static final String ATTRIBUTE_PROPERTY_ORIGIN = "propertyOrigin";
|
||||||
|
|
||||||
|
private final PropertyOrigin origin;
|
||||||
|
|
||||||
|
OriginCapablePropertyValue(PropertyValue propertyValue){
|
||||||
|
this(propertyValue.getName(),
|
||||||
|
propertyValue.getValue(),
|
||||||
|
(PropertyOrigin) propertyValue.getAttribute(ATTRIBUTE_PROPERTY_ORIGIN));
|
||||||
|
}
|
||||||
|
|
||||||
|
OriginCapablePropertyValue(String name, Object value, String originName, PropertySource<?> originSource){
|
||||||
|
this(name, value, new PropertyOrigin(originSource, originName));
|
||||||
|
}
|
||||||
|
|
||||||
|
OriginCapablePropertyValue(String name, Object value, PropertyOrigin origin){
|
||||||
|
super(name, value);
|
||||||
|
this.origin = origin;
|
||||||
|
setAttribute(ATTRIBUTE_PROPERTY_ORIGIN, origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
public PropertyOrigin getOrigin() {
|
||||||
|
return this.origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
String name = (this.origin != null ? this.origin.getName() : this.getName());
|
||||||
|
String source = (this.origin.getSource() != null ? this.origin.getSource().getName() : "unknown");
|
||||||
|
return "'" + name + "' from '" + source + "'";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PropertyOrigin getOrigin(PropertyValue propertyValue) {
|
||||||
|
if (propertyValue instanceof OriginCapablePropertyValue) {
|
||||||
|
return ((OriginCapablePropertyValue) propertyValue).getOrigin();
|
||||||
|
}
|
||||||
|
return new OriginCapablePropertyValue(propertyValue).getOrigin();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import org.springframework.util.PatternMatchUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link PropertyNamePatternsMatcher} that delegates to
|
||||||
|
* {@link PatternMatchUtils#simpleMatch(String[], String)}.
|
||||||
|
*
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @since 1.2.0
|
||||||
|
*/
|
||||||
|
class PatternPropertyNamePatternsMatcher implements PropertyNamePatternsMatcher {
|
||||||
|
|
||||||
|
private final String[] patterns;
|
||||||
|
|
||||||
|
PatternPropertyNamePatternsMatcher(Collection<String> patterns){
|
||||||
|
this.patterns = (patterns != null ? patterns.toArray(new String[patterns.size()]) : new String[] {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(String propertyName) {
|
||||||
|
return PatternMatchUtils.simpleMatch(this.patterns, propertyName);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,356 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import java.beans.PropertyDescriptor;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.springframework.beans.BeanUtils;
|
||||||
|
import org.springframework.beans.PropertyValues;
|
||||||
|
import org.springframework.beans.factory.FactoryBean;
|
||||||
|
import org.springframework.beans.factory.InitializingBean;
|
||||||
|
import org.springframework.beans.support.ResourceEditorRegistrar;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.context.ApplicationContextAware;
|
||||||
|
import org.springframework.context.MessageSource;
|
||||||
|
import org.springframework.context.MessageSourceAware;
|
||||||
|
import org.springframework.core.convert.ConversionService;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.validation.*;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.PropertySources;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate some {@link Properties} (or optionally
|
||||||
|
* {@link org.springframework.core.env.PropertySources}) by binding them to an
|
||||||
|
* object of a specified type and then optionally running a {@link Validator}
|
||||||
|
* over it.
|
||||||
|
*
|
||||||
|
* @param <T> the target type
|
||||||
|
* @author Dave Syer
|
||||||
|
*/
|
||||||
|
public class PropertiesConfigurationFactory<T> implements FactoryBean<T>, ApplicationContextAware, MessageSourceAware, InitializingBean {
|
||||||
|
|
||||||
|
private static final char[] EXACT_DELIMITERS = { '_', '.', '[' };
|
||||||
|
|
||||||
|
private static final char[] TARGET_NAME_DELIMITERS = { '_', '.' };
|
||||||
|
|
||||||
|
private static final Log logger = LogFactory.getLog(PropertiesConfigurationFactory.class);
|
||||||
|
|
||||||
|
private boolean ignoreUnknownFields = true;
|
||||||
|
|
||||||
|
private boolean ignoreInvalidFields;
|
||||||
|
|
||||||
|
private boolean exceptionIfInvalid = true;
|
||||||
|
|
||||||
|
private PropertySources propertySources;
|
||||||
|
|
||||||
|
private final T target;
|
||||||
|
|
||||||
|
private Validator validator;
|
||||||
|
|
||||||
|
private ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
private MessageSource messageSource;
|
||||||
|
|
||||||
|
private boolean hasBeenBound = false;
|
||||||
|
|
||||||
|
private boolean ignoreNestedProperties = false;
|
||||||
|
|
||||||
|
private String targetName;
|
||||||
|
|
||||||
|
private ConversionService conversionService;
|
||||||
|
|
||||||
|
private boolean resolvePlaceholders = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@link PropertiesConfigurationFactory} instance.
|
||||||
|
*
|
||||||
|
* @param target the target object to bind too
|
||||||
|
* @see #PropertiesConfigurationFactory(Class)
|
||||||
|
*/
|
||||||
|
public PropertiesConfigurationFactory(T target){
|
||||||
|
Assert.notNull(target, "target must not be null");
|
||||||
|
this.target = target;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@link PropertiesConfigurationFactory} instance.
|
||||||
|
*
|
||||||
|
* @param type the target type
|
||||||
|
* @see #PropertiesConfigurationFactory(Class)
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public PropertiesConfigurationFactory(Class<?> type){
|
||||||
|
Assert.notNull(type, "type must not be null");
|
||||||
|
this.target = (T) BeanUtils.instantiate(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flag to disable binding of nested properties (i.e. those with period
|
||||||
|
* separators in their paths). Can be useful to disable this if the name prefix
|
||||||
|
* is empty and you don't want to ignore unknown fields.
|
||||||
|
*
|
||||||
|
* @param ignoreNestedProperties the flag to set (default false)
|
||||||
|
*/
|
||||||
|
public void setIgnoreNestedProperties(boolean ignoreNestedProperties) {
|
||||||
|
this.ignoreNestedProperties = ignoreNestedProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set whether to ignore unknown fields, that is, whether to ignore bind
|
||||||
|
* parameters that do not have corresponding fields in the target object.
|
||||||
|
* <p>
|
||||||
|
* Default is "true". Turn this off to enforce that all bind parameters must
|
||||||
|
* have a matching field in the target object.
|
||||||
|
*
|
||||||
|
* @param ignoreUnknownFields if unknown fields should be ignored
|
||||||
|
*/
|
||||||
|
public void setIgnoreUnknownFields(boolean ignoreUnknownFields) {
|
||||||
|
this.ignoreUnknownFields = ignoreUnknownFields;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set whether to ignore invalid fields, that is, whether to ignore bind
|
||||||
|
* parameters that have corresponding fields in the target object which are not
|
||||||
|
* accessible (for example because of null values in the nested path).
|
||||||
|
* <p>
|
||||||
|
* Default is "false". Turn this on to ignore bind parameters for nested objects
|
||||||
|
* in non-existing parts of the target object graph.
|
||||||
|
*
|
||||||
|
* @param ignoreInvalidFields if invalid fields should be ignored
|
||||||
|
*/
|
||||||
|
public void setIgnoreInvalidFields(boolean ignoreInvalidFields) {
|
||||||
|
this.ignoreInvalidFields = ignoreInvalidFields;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the target name.
|
||||||
|
*
|
||||||
|
* @param targetName the target name
|
||||||
|
*/
|
||||||
|
public void setTargetName(String targetName) {
|
||||||
|
this.targetName = targetName;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setApplicationContext(ApplicationContext applicationContext) {
|
||||||
|
this.applicationContext = applicationContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the message source.
|
||||||
|
*
|
||||||
|
* @param messageSource the message source
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void setMessageSource(MessageSource messageSource) {
|
||||||
|
this.messageSource = messageSource;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the property sources.
|
||||||
|
*
|
||||||
|
* @param propertySources the property sources
|
||||||
|
*/
|
||||||
|
public void setPropertySources(PropertySources propertySources) {
|
||||||
|
this.propertySources = propertySources;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the conversion service.
|
||||||
|
*
|
||||||
|
* @param conversionService the conversion service
|
||||||
|
*/
|
||||||
|
public void setConversionService(ConversionService conversionService) {
|
||||||
|
this.conversionService = conversionService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the validator.
|
||||||
|
*
|
||||||
|
* @param validator the validator
|
||||||
|
*/
|
||||||
|
public void setValidator(Validator validator) {
|
||||||
|
this.validator = validator;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set a flag to indicate that an exception should be raised if a Validator is
|
||||||
|
* available and validation fails.
|
||||||
|
*
|
||||||
|
* @param exceptionIfInvalid the flag to set
|
||||||
|
* @deprecated as of 1.5, do not specify a {@link Validator} if validation
|
||||||
|
* should not occur
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public void setExceptionIfInvalid(boolean exceptionIfInvalid) {
|
||||||
|
this.exceptionIfInvalid = exceptionIfInvalid;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flag to indicate that placeholders should be replaced during binding. Default
|
||||||
|
* is true.
|
||||||
|
*
|
||||||
|
* @param resolvePlaceholders flag value
|
||||||
|
*/
|
||||||
|
public void setResolvePlaceholders(boolean resolvePlaceholders) {
|
||||||
|
this.resolvePlaceholders = resolvePlaceholders;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterPropertiesSet() throws Exception {
|
||||||
|
bindPropertiesToTarget();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Class<?> getObjectType() {
|
||||||
|
if (this.target == null) {
|
||||||
|
return Object.class;
|
||||||
|
}
|
||||||
|
return this.target.getClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isSingleton() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public T getObject() throws Exception {
|
||||||
|
if (!this.hasBeenBound) {
|
||||||
|
bindPropertiesToTarget();
|
||||||
|
}
|
||||||
|
return this.target;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void bindPropertiesToTarget() throws BindException {
|
||||||
|
Assert.state(this.propertySources != null, "PropertySources should not be null");
|
||||||
|
try {
|
||||||
|
if (logger.isTraceEnabled()) {
|
||||||
|
logger.trace("Property Sources: " + this.propertySources);
|
||||||
|
|
||||||
|
}
|
||||||
|
this.hasBeenBound = true;
|
||||||
|
doBindPropertiesToTarget();
|
||||||
|
} catch (BindException ex) {
|
||||||
|
if (this.exceptionIfInvalid) {
|
||||||
|
throw ex;
|
||||||
|
}
|
||||||
|
logger.error("Failed to load Properties validation bean. " + "Your Properties may be invalid.", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void doBindPropertiesToTarget() throws BindException {
|
||||||
|
RelaxedDataBinder dataBinder = (this.targetName != null ? new RelaxedDataBinder(this.target,
|
||||||
|
this.targetName) : new RelaxedDataBinder(this.target));
|
||||||
|
if (this.validator != null && this.validator.supports(dataBinder.getTarget().getClass())) {
|
||||||
|
dataBinder.setValidator(this.validator);
|
||||||
|
}
|
||||||
|
if (this.conversionService != null) {
|
||||||
|
dataBinder.setConversionService(this.conversionService);
|
||||||
|
}
|
||||||
|
dataBinder.setAutoGrowCollectionLimit(Integer.MAX_VALUE);
|
||||||
|
dataBinder.setIgnoreNestedProperties(this.ignoreNestedProperties);
|
||||||
|
dataBinder.setIgnoreInvalidFields(this.ignoreInvalidFields);
|
||||||
|
dataBinder.setIgnoreUnknownFields(this.ignoreUnknownFields);
|
||||||
|
customizeBinder(dataBinder);
|
||||||
|
if (this.applicationContext != null) {
|
||||||
|
ResourceEditorRegistrar resourceEditorRegistrar = new ResourceEditorRegistrar(this.applicationContext,
|
||||||
|
this.applicationContext.getEnvironment());
|
||||||
|
resourceEditorRegistrar.registerCustomEditors(dataBinder);
|
||||||
|
}
|
||||||
|
Iterable<String> relaxedTargetNames = getRelaxedTargetNames();
|
||||||
|
Set<String> names = getNames(relaxedTargetNames);
|
||||||
|
PropertyValues propertyValues = getPropertySourcesPropertyValues(names, relaxedTargetNames);
|
||||||
|
dataBinder.bind(propertyValues);
|
||||||
|
if (this.validator != null) {
|
||||||
|
dataBinder.validate();
|
||||||
|
}
|
||||||
|
checkForBindingErrors(dataBinder);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Iterable<String> getRelaxedTargetNames() {
|
||||||
|
return (this.target != null
|
||||||
|
&& StringUtils.hasLength(this.targetName) ? new RelaxedNames(this.targetName) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> getNames(Iterable<String> prefixes) {
|
||||||
|
Set<String> names = new LinkedHashSet<String>();
|
||||||
|
if (this.target != null) {
|
||||||
|
PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(this.target.getClass());
|
||||||
|
for (PropertyDescriptor descriptor : descriptors) {
|
||||||
|
String name = descriptor.getName();
|
||||||
|
if (!name.equals("class")) {
|
||||||
|
RelaxedNames relaxedNames = RelaxedNames.forCamelCase(name);
|
||||||
|
if (prefixes == null) {
|
||||||
|
for (String relaxedName : relaxedNames) {
|
||||||
|
names.add(relaxedName);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (String prefix : prefixes) {
|
||||||
|
for (String relaxedName : relaxedNames) {
|
||||||
|
names.add(prefix + "." + relaxedName);
|
||||||
|
names.add(prefix + "_" + relaxedName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
private PropertyValues getPropertySourcesPropertyValues(Set<String> names, Iterable<String> relaxedTargetNames) {
|
||||||
|
PropertyNamePatternsMatcher includes = getPropertyNamePatternsMatcher(names, relaxedTargetNames);
|
||||||
|
return new PropertySourcesPropertyValues(this.propertySources, names, includes, this.resolvePlaceholders);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PropertyNamePatternsMatcher getPropertyNamePatternsMatcher(Set<String> names,
|
||||||
|
Iterable<String> relaxedTargetNames) {
|
||||||
|
if (this.ignoreUnknownFields && !isMapTarget()) {
|
||||||
|
// Since unknown fields are ignored we can filter them out early to save
|
||||||
|
// unnecessary calls to the PropertySource.
|
||||||
|
return new DefaultPropertyNamePatternsMatcher(EXACT_DELIMITERS, true, names);
|
||||||
|
}
|
||||||
|
if (relaxedTargetNames != null) {
|
||||||
|
// We can filter properties to those starting with the target name, but
|
||||||
|
// we can't do a complete filter since we need to trigger the
|
||||||
|
// unknown fields check
|
||||||
|
Set<String> relaxedNames = new HashSet<String>();
|
||||||
|
for (String relaxedTargetName : relaxedTargetNames) {
|
||||||
|
relaxedNames.add(relaxedTargetName);
|
||||||
|
}
|
||||||
|
return new DefaultPropertyNamePatternsMatcher(TARGET_NAME_DELIMITERS, true, relaxedNames);
|
||||||
|
}
|
||||||
|
// Not ideal, we basically can't filter anything
|
||||||
|
return PropertyNamePatternsMatcher.ALL;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isMapTarget() {
|
||||||
|
return this.target != null && Map.class.isAssignableFrom(this.target.getClass());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkForBindingErrors(RelaxedDataBinder dataBinder) throws BindException {
|
||||||
|
BindingResult errors = dataBinder.getBindingResult();
|
||||||
|
if (errors.hasErrors()) {
|
||||||
|
logger.error("Properties configuration failed validation");
|
||||||
|
for (ObjectError error : errors.getAllErrors()) {
|
||||||
|
logger.error(this.messageSource != null ? this.messageSource.getMessage(error, Locale.getDefault())
|
||||||
|
+ " (" + error + ")" : error);
|
||||||
|
}
|
||||||
|
if (this.exceptionIfInvalid) {
|
||||||
|
throw new BindException(errors);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Customize the data binder.
|
||||||
|
*
|
||||||
|
* @param dataBinder the data binder that will be used to bind and validate
|
||||||
|
*/
|
||||||
|
protected void customizeBinder(DataBinder dataBinder) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strategy interface used to check if a property name matches specific
|
||||||
|
* criteria.
|
||||||
|
*
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @since 1.2.0
|
||||||
|
*/
|
||||||
|
interface PropertyNamePatternsMatcher {
|
||||||
|
|
||||||
|
PropertyNamePatternsMatcher ALL = new PropertyNamePatternsMatcher() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(String propertyName) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
PropertyNamePatternsMatcher NONE = new PropertyNamePatternsMatcher() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(String propertyName) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return {@code true} of the property name matches.
|
||||||
|
*
|
||||||
|
* @param propertyName the property name
|
||||||
|
* @return {@code true} if the property name matches
|
||||||
|
*/
|
||||||
|
boolean matches(String propertyName);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.PropertySource;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The origin of a property, specifically its source and its name before any
|
||||||
|
* prefix was removed.
|
||||||
|
*
|
||||||
|
* @author Andy Wilkinson
|
||||||
|
* @since 1.3.0
|
||||||
|
*/
|
||||||
|
public class PropertyOrigin {
|
||||||
|
|
||||||
|
private final PropertySource<?> source;
|
||||||
|
|
||||||
|
private final String name;
|
||||||
|
|
||||||
|
PropertyOrigin(PropertySource<?> source, String name){
|
||||||
|
this.name = name;
|
||||||
|
this.source = source;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PropertySource<?> getSource() {
|
||||||
|
return this.source;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import org.springframework.core.convert.ConversionException;
|
||||||
|
import org.springframework.core.env.AbstractEnvironment;
|
||||||
|
import org.springframework.core.env.AbstractPropertyResolver;
|
||||||
|
import org.springframework.core.env.PropertyResolver;
|
||||||
|
import org.springframework.util.ClassUtils;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.PropertySource;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.PropertySources;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link PropertyResolver} implementation that resolves property values against
|
||||||
|
* an underlying set of {@link PropertySources}.
|
||||||
|
*
|
||||||
|
* @author Chris Beams
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @see PropertySource
|
||||||
|
* @see PropertySources
|
||||||
|
* @see AbstractEnvironment
|
||||||
|
* @since 3.1
|
||||||
|
*/
|
||||||
|
public class PropertySourcesPropertyResolver extends AbstractPropertyResolver {
|
||||||
|
|
||||||
|
private final PropertySources propertySources;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new resolver against the given property sources.
|
||||||
|
*
|
||||||
|
* @param propertySources the set of {@link PropertySource} objects to use
|
||||||
|
*/
|
||||||
|
public PropertySourcesPropertyResolver(PropertySources propertySources){
|
||||||
|
this.propertySources = propertySources;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean containsProperty(String key) {
|
||||||
|
if (this.propertySources != null) {
|
||||||
|
for (PropertySource<?> propertySource : this.propertySources) {
|
||||||
|
if (propertySource.containsProperty(key)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getProperty(String key) {
|
||||||
|
return getProperty(key, String.class, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> T getProperty(String key, Class<T> targetValueType) {
|
||||||
|
return getProperty(key, targetValueType, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String getPropertyAsRawString(String key) {
|
||||||
|
return getProperty(key, String.class, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected <T> T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) {
|
||||||
|
if (this.propertySources != null) {
|
||||||
|
for (PropertySource<?> propertySource : this.propertySources) {
|
||||||
|
if (logger.isTraceEnabled()) {
|
||||||
|
logger
|
||||||
|
.trace("Searching for key '" + key + "' in PropertySource '" + propertySource.getName() + "'");
|
||||||
|
}
|
||||||
|
Object value = propertySource.getProperty(key);
|
||||||
|
if (value != null) {
|
||||||
|
if (resolveNestedPlaceholders && value instanceof String) {
|
||||||
|
value = resolveNestedPlaceholders((String) value);
|
||||||
|
}
|
||||||
|
logKeyFound(key, propertySource, value);
|
||||||
|
return convertValueIfNecessary(value, targetValueType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Could not find key '" + key + "' in any property source");
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated
|
||||||
|
public <T> Class<T> getPropertyAsClass(String key, Class<T> targetValueType) {
|
||||||
|
if (this.propertySources != null) {
|
||||||
|
for (PropertySource<?> propertySource : this.propertySources) {
|
||||||
|
if (logger.isTraceEnabled()) {
|
||||||
|
logger.trace(String.format("Searching for key '%s' in [%s]", key, propertySource.getName()));
|
||||||
|
}
|
||||||
|
Object value = propertySource.getProperty(key);
|
||||||
|
if (value != null) {
|
||||||
|
logKeyFound(key, propertySource, value);
|
||||||
|
Class<?> clazz;
|
||||||
|
if (value instanceof String) {
|
||||||
|
try {
|
||||||
|
clazz = ClassUtils.forName((String) value, null);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new PropertySourcesPropertyResolver.ClassConversionException((String) value,
|
||||||
|
targetValueType,
|
||||||
|
ex);
|
||||||
|
}
|
||||||
|
} else if (value instanceof Class) {
|
||||||
|
clazz = (Class<?>) value;
|
||||||
|
} else {
|
||||||
|
clazz = value.getClass();
|
||||||
|
}
|
||||||
|
if (!targetValueType.isAssignableFrom(clazz)) {
|
||||||
|
throw new PropertySourcesPropertyResolver.ClassConversionException(clazz, targetValueType);
|
||||||
|
}
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Class<T> targetClass = (Class<T>) clazz;
|
||||||
|
return targetClass;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug(String.format("Could not find key '%s' in any property source", key));
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log the given key as found in the given {@link PropertySource}, resulting in
|
||||||
|
* the given value.
|
||||||
|
* <p>
|
||||||
|
* The default implementation writes a debug log message with key and source. As
|
||||||
|
* of 4.3.3, this does not log the value anymore in order to avoid accidental
|
||||||
|
* logging of sensitive settings. Subclasses may override this method to change
|
||||||
|
* the log level and/or log message, including the property's value if desired.
|
||||||
|
*
|
||||||
|
* @param key the key found
|
||||||
|
* @param propertySource the {@code PropertySource} that the key has been found
|
||||||
|
* in
|
||||||
|
* @param value the corresponding value
|
||||||
|
* @since 4.3.1
|
||||||
|
*/
|
||||||
|
protected void logKeyFound(String key, PropertySource<?> propertySource, Object value) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Found key '" + key + "' in PropertySource '" + propertySource.getName()
|
||||||
|
+ "' with value of type " + value.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
@Deprecated
|
||||||
|
private static class ClassConversionException extends ConversionException {
|
||||||
|
|
||||||
|
public ClassConversionException(Class<?> actual, Class<?> expected){
|
||||||
|
super(String
|
||||||
|
.format("Actual type %s is not assignable to expected type %s", actual.getName(), expected.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public ClassConversionException(String actual, Class<?> expected, Exception ex){
|
||||||
|
super(
|
||||||
|
String
|
||||||
|
.format("Could not find/load class %s during attempt to convert to %s", actual, expected.getName()),
|
||||||
|
ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.springframework.beans.MutablePropertyValues;
|
||||||
|
import org.springframework.beans.PropertyValue;
|
||||||
|
import org.springframework.beans.PropertyValues;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
import org.springframework.validation.DataBinder;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.CompositePropertySource;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.EnumerablePropertySource;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.PropertySource;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.common.PropertySources;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A {@link PropertyValues} implementation backed by a {@link PropertySources},
|
||||||
|
* bridging the two abstractions and allowing (for instance) a regular
|
||||||
|
* {@link DataBinder} to be used with the latter.
|
||||||
|
*
|
||||||
|
* @author Dave Syer
|
||||||
|
* @author Phillip Webb
|
||||||
|
*/
|
||||||
|
public class PropertySourcesPropertyValues implements PropertyValues {
|
||||||
|
|
||||||
|
private static final Pattern COLLECTION_PROPERTY = Pattern
|
||||||
|
.compile("\\[(\\d+)\\](\\.\\S+)?");
|
||||||
|
|
||||||
|
private final PropertySources propertySources;
|
||||||
|
|
||||||
|
private final Collection<String> nonEnumerableFallbackNames;
|
||||||
|
|
||||||
|
private final PropertyNamePatternsMatcher includes;
|
||||||
|
|
||||||
|
private final Map<String, PropertyValue> propertyValues = new LinkedHashMap<String, PropertyValue>();
|
||||||
|
|
||||||
|
private final ConcurrentHashMap<String, PropertySource<?>> collectionOwners = new ConcurrentHashMap<String, PropertySource<?>>();
|
||||||
|
|
||||||
|
private final boolean resolvePlaceholders;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new PropertyValues from the given PropertySources.
|
||||||
|
*
|
||||||
|
* @param propertySources a PropertySources instance
|
||||||
|
*/
|
||||||
|
public PropertySourcesPropertyValues(PropertySources propertySources){
|
||||||
|
this(propertySources, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new PropertyValues from the given PropertySources that will
|
||||||
|
* optionally resolve placeholders.
|
||||||
|
*
|
||||||
|
* @param propertySources a PropertySources instance
|
||||||
|
* @param resolvePlaceholders {@code true} if placeholders should be resolved.
|
||||||
|
* @since 1.5.2
|
||||||
|
*/
|
||||||
|
public PropertySourcesPropertyValues(PropertySources propertySources, boolean resolvePlaceholders){
|
||||||
|
this(propertySources, (Collection<String>) null, PropertyNamePatternsMatcher.ALL, resolvePlaceholders);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new PropertyValues from the given PropertySources.
|
||||||
|
*
|
||||||
|
* @param propertySources a PropertySources instance
|
||||||
|
* @param includePatterns property name patterns to include from system
|
||||||
|
* properties and environment variables
|
||||||
|
* @param nonEnumerableFallbackNames the property names to try in lieu of an
|
||||||
|
* {@link EnumerablePropertySource}.
|
||||||
|
*/
|
||||||
|
public PropertySourcesPropertyValues(PropertySources propertySources, Collection<String> includePatterns,
|
||||||
|
Collection<String> nonEnumerableFallbackNames){
|
||||||
|
this(propertySources,
|
||||||
|
nonEnumerableFallbackNames,
|
||||||
|
new PatternPropertyNamePatternsMatcher(includePatterns),
|
||||||
|
true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new PropertyValues from the given PropertySources.
|
||||||
|
*
|
||||||
|
* @param propertySources a PropertySources instance
|
||||||
|
* @param nonEnumerableFallbackNames the property names to try in lieu of an
|
||||||
|
* {@link EnumerablePropertySource}.
|
||||||
|
* @param includes the property name patterns to include
|
||||||
|
* @param resolvePlaceholders flag to indicate the placeholders should be
|
||||||
|
* resolved
|
||||||
|
*/
|
||||||
|
PropertySourcesPropertyValues(PropertySources propertySources, Collection<String> nonEnumerableFallbackNames,
|
||||||
|
PropertyNamePatternsMatcher includes, boolean resolvePlaceholders){
|
||||||
|
Assert.notNull(propertySources, "PropertySources must not be null");
|
||||||
|
Assert.notNull(includes, "Includes must not be null");
|
||||||
|
this.propertySources = propertySources;
|
||||||
|
this.nonEnumerableFallbackNames = nonEnumerableFallbackNames;
|
||||||
|
this.includes = includes;
|
||||||
|
this.resolvePlaceholders = resolvePlaceholders;
|
||||||
|
PropertySourcesPropertyResolver resolver = new PropertySourcesPropertyResolver(propertySources);
|
||||||
|
for (PropertySource<?> source : propertySources) {
|
||||||
|
processPropertySource(source, resolver);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void processPropertySource(PropertySource<?> source, PropertySourcesPropertyResolver resolver) {
|
||||||
|
if (source instanceof CompositePropertySource) {
|
||||||
|
processCompositePropertySource((CompositePropertySource) source, resolver);
|
||||||
|
} else if (source instanceof EnumerablePropertySource) {
|
||||||
|
processEnumerablePropertySource((EnumerablePropertySource<?>) source, resolver, this.includes);
|
||||||
|
} else {
|
||||||
|
processNonEnumerablePropertySource(source, resolver);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void processCompositePropertySource(CompositePropertySource source,
|
||||||
|
PropertySourcesPropertyResolver resolver) {
|
||||||
|
for (PropertySource<?> nested : source.getPropertySources()) {
|
||||||
|
processPropertySource(nested, resolver);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void processEnumerablePropertySource(EnumerablePropertySource<?> source,
|
||||||
|
PropertySourcesPropertyResolver resolver,
|
||||||
|
PropertyNamePatternsMatcher includes) {
|
||||||
|
if (source.getPropertyNames().length > 0) {
|
||||||
|
for (String propertyName : source.getPropertyNames()) {
|
||||||
|
if (includes.matches(propertyName)) {
|
||||||
|
Object value = getEnumerableProperty(source, resolver, propertyName);
|
||||||
|
putIfAbsent(propertyName, value, source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object getEnumerableProperty(EnumerablePropertySource<?> source, PropertySourcesPropertyResolver resolver,
|
||||||
|
String propertyName) {
|
||||||
|
try {
|
||||||
|
if (this.resolvePlaceholders) {
|
||||||
|
return resolver.getProperty(propertyName, Object.class);
|
||||||
|
}
|
||||||
|
} catch (RuntimeException ex) {
|
||||||
|
// Probably could not resolve placeholders, ignore it here
|
||||||
|
}
|
||||||
|
return source.getProperty(propertyName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void processNonEnumerablePropertySource(PropertySource<?> source,
|
||||||
|
PropertySourcesPropertyResolver resolver) {
|
||||||
|
// We can only do exact matches for non-enumerable property names, but
|
||||||
|
// that's better than nothing...
|
||||||
|
if (this.nonEnumerableFallbackNames == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (String propertyName : this.nonEnumerableFallbackNames) {
|
||||||
|
if (!source.containsProperty(propertyName)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Object value = null;
|
||||||
|
try {
|
||||||
|
value = resolver.getProperty(propertyName, Object.class);
|
||||||
|
} catch (RuntimeException ex) {
|
||||||
|
// Probably could not convert to Object, weird, but ignorable
|
||||||
|
}
|
||||||
|
if (value == null) {
|
||||||
|
value = source.getProperty(propertyName.toUpperCase(Locale.ENGLISH));
|
||||||
|
}
|
||||||
|
putIfAbsent(propertyName, value, source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PropertyValue[] getPropertyValues() {
|
||||||
|
Collection<PropertyValue> values = this.propertyValues.values();
|
||||||
|
return values.toArray(new PropertyValue[values.size()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PropertyValue getPropertyValue(String propertyName) {
|
||||||
|
PropertyValue propertyValue = this.propertyValues.get(propertyName);
|
||||||
|
if (propertyValue != null) {
|
||||||
|
return propertyValue;
|
||||||
|
}
|
||||||
|
for (PropertySource<?> source : this.propertySources) {
|
||||||
|
Object value = source.getProperty(propertyName);
|
||||||
|
propertyValue = putIfAbsent(propertyName, value, source);
|
||||||
|
if (propertyValue != null) {
|
||||||
|
return propertyValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private PropertyValue putIfAbsent(String propertyName, Object value, PropertySource<?> source) {
|
||||||
|
if (value != null && !this.propertyValues.containsKey(propertyName)) {
|
||||||
|
PropertySource<?> collectionOwner = this.collectionOwners
|
||||||
|
.putIfAbsent(COLLECTION_PROPERTY.matcher(propertyName).replaceAll("[]"), source);
|
||||||
|
if (collectionOwner == null || collectionOwner == source) {
|
||||||
|
PropertyValue propertyValue = new OriginCapablePropertyValue(propertyName, value, propertyName, source);
|
||||||
|
this.propertyValues.put(propertyName, propertyValue);
|
||||||
|
return propertyValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PropertyValues changesSince(PropertyValues old) {
|
||||||
|
MutablePropertyValues changes = new MutablePropertyValues();
|
||||||
|
// for each property value in the new set
|
||||||
|
for (PropertyValue newValue : getPropertyValues()) {
|
||||||
|
// if there wasn't an old one, add it
|
||||||
|
PropertyValue oldValue = old.getPropertyValue(newValue.getName());
|
||||||
|
if (oldValue == null || !oldValue.equals(newValue)) {
|
||||||
|
changes.addPropertyValue(newValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changes;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean contains(String propertyName) {
|
||||||
|
return getPropertyValue(propertyName) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return this.propertyValues.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import java.util.EnumSet;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.springframework.core.convert.ConversionFailedException;
|
||||||
|
import org.springframework.core.convert.ConversionService;
|
||||||
|
import org.springframework.core.convert.TypeDescriptor;
|
||||||
|
import org.springframework.core.convert.converter.Converter;
|
||||||
|
import org.springframework.core.convert.converter.ConverterFactory;
|
||||||
|
import org.springframework.core.convert.support.DefaultConversionService;
|
||||||
|
import org.springframework.core.convert.support.GenericConversionService;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal {@link ConversionService} used by {@link RelaxedDataBinder} to
|
||||||
|
* support additional relaxed conversion.
|
||||||
|
*
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @author Stephane Nicoll
|
||||||
|
* @since 1.1.0
|
||||||
|
*/
|
||||||
|
class RelaxedConversionService implements ConversionService {
|
||||||
|
|
||||||
|
private final ConversionService conversionService;
|
||||||
|
|
||||||
|
private final GenericConversionService additionalConverters;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@link RelaxedConversionService} instance.
|
||||||
|
*
|
||||||
|
* @param conversionService and option root conversion service
|
||||||
|
*/
|
||||||
|
RelaxedConversionService(ConversionService conversionService){
|
||||||
|
this.conversionService = conversionService;
|
||||||
|
this.additionalConverters = new GenericConversionService();
|
||||||
|
DefaultConversionService.addCollectionConverters(this.additionalConverters);
|
||||||
|
this.additionalConverters
|
||||||
|
.addConverterFactory(new RelaxedConversionService.StringToEnumIgnoringCaseConverterFactory());
|
||||||
|
this.additionalConverters.addConverter(new StringToCharArrayConverter());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean canConvert(Class<?> sourceType, Class<?> targetType) {
|
||||||
|
return (this.conversionService != null && this.conversionService.canConvert(sourceType, targetType))
|
||||||
|
|| this.additionalConverters.canConvert(sourceType, targetType);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
|
||||||
|
return (this.conversionService != null && this.conversionService.canConvert(sourceType, targetType))
|
||||||
|
|| this.additionalConverters.canConvert(sourceType, targetType);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public <T> T convert(Object source, Class<T> targetType) {
|
||||||
|
Assert.notNull(targetType, "The targetType to convert to cannot be null");
|
||||||
|
return (T) convert(source, TypeDescriptor.forObject(source), TypeDescriptor.valueOf(targetType));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
|
||||||
|
if (this.conversionService != null) {
|
||||||
|
try {
|
||||||
|
return this.conversionService.convert(source, sourceType, targetType);
|
||||||
|
} catch (ConversionFailedException ex) {
|
||||||
|
// Ignore and try the additional converters
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.additionalConverters.convert(source, sourceType, targetType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clone of Spring's package private StringToEnumConverterFactory, but ignoring
|
||||||
|
* the case of the source.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||||
|
private static class StringToEnumIgnoringCaseConverterFactory implements ConverterFactory<String, Enum> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
|
||||||
|
Class<?> enumType = targetType;
|
||||||
|
while (enumType != null && !enumType.isEnum()) {
|
||||||
|
enumType = enumType.getSuperclass();
|
||||||
|
}
|
||||||
|
Assert.notNull(enumType, "The target type " + targetType.getName() + " does not refer to an enum");
|
||||||
|
return new RelaxedConversionService.StringToEnumIgnoringCaseConverterFactory.StringToEnum(enumType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class StringToEnum<T extends Enum> implements Converter<String, T> {
|
||||||
|
|
||||||
|
private final Class<T> enumType;
|
||||||
|
|
||||||
|
StringToEnum(Class<T> enumType){
|
||||||
|
this.enumType = enumType;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public T convert(String source) {
|
||||||
|
if (source.isEmpty()) {
|
||||||
|
// It's an empty enum identifier: reset the enum value to null.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
source = source.trim();
|
||||||
|
for (T candidate : (Set<T>) EnumSet.allOf(this.enumType)) {
|
||||||
|
RelaxedNames names = new RelaxedNames(
|
||||||
|
candidate.name().replace('_', '-').toLowerCase(Locale.ENGLISH));
|
||||||
|
for (String name : names) {
|
||||||
|
if (name.equals(source)) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (candidate.name().equalsIgnoreCase(source)) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"No enum constant " + this.enumType.getCanonicalName() + "." + source);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,729 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import java.beans.PropertyEditor;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import org.springframework.beans.*;
|
||||||
|
import org.springframework.beans.propertyeditors.FileEditor;
|
||||||
|
import org.springframework.core.convert.ConversionService;
|
||||||
|
import org.springframework.core.convert.TypeDescriptor;
|
||||||
|
import org.springframework.core.env.StandardEnvironment;
|
||||||
|
import org.springframework.util.LinkedMultiValueMap;
|
||||||
|
import org.springframework.util.MultiValueMap;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.validation.AbstractPropertyBindingResult;
|
||||||
|
import org.springframework.validation.BeanPropertyBindingResult;
|
||||||
|
import org.springframework.validation.DataBinder;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Binder implementation that allows caller to bind to maps and also allows
|
||||||
|
* property names to match a bit loosely (if underscores or dashes are removed
|
||||||
|
* and replaced with camel case for example).
|
||||||
|
*
|
||||||
|
* @author Dave Syer
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @author Stephane Nicoll
|
||||||
|
* @author Andy Wilkinson
|
||||||
|
* @see RelaxedNames
|
||||||
|
*/
|
||||||
|
public class RelaxedDataBinder extends DataBinder {
|
||||||
|
|
||||||
|
private static final Set<Class<?>> EXCLUDED_EDITORS;
|
||||||
|
|
||||||
|
static {
|
||||||
|
Set<Class<?>> excluded = new HashSet<Class<?>>();
|
||||||
|
excluded.add(FileEditor.class);
|
||||||
|
EXCLUDED_EDITORS = Collections.unmodifiableSet(excluded);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final Object BLANK = new Object();
|
||||||
|
|
||||||
|
private String namePrefix;
|
||||||
|
|
||||||
|
private boolean ignoreNestedProperties;
|
||||||
|
|
||||||
|
private MultiValueMap<String, String> nameAliases = new LinkedMultiValueMap<String, String>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@link RelaxedDataBinder} instance.
|
||||||
|
*
|
||||||
|
* @param target the target into which properties are bound
|
||||||
|
*/
|
||||||
|
public RelaxedDataBinder(Object target){
|
||||||
|
super(wrapTarget(target));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@link RelaxedDataBinder} instance.
|
||||||
|
*
|
||||||
|
* @param target the target into which properties are bound
|
||||||
|
* @param namePrefix An optional prefix to be used when reading properties
|
||||||
|
*/
|
||||||
|
public RelaxedDataBinder(Object target, String namePrefix){
|
||||||
|
super(wrapTarget(target), (StringUtils.hasLength(namePrefix) ? namePrefix : DEFAULT_OBJECT_NAME));
|
||||||
|
this.namePrefix = cleanNamePrefix(namePrefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String cleanNamePrefix(String namePrefix) {
|
||||||
|
if (!StringUtils.hasLength(namePrefix)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (namePrefix.endsWith(".") ? namePrefix : namePrefix + ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flag to disable binding of nested properties (i.e. those with period
|
||||||
|
* separators in their paths). Can be useful to disable this if the name prefix
|
||||||
|
* is empty and you don't want to ignore unknown fields.
|
||||||
|
*
|
||||||
|
* @param ignoreNestedProperties the flag to set (default false)
|
||||||
|
*/
|
||||||
|
public void setIgnoreNestedProperties(boolean ignoreNestedProperties) {
|
||||||
|
this.ignoreNestedProperties = ignoreNestedProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set name aliases.
|
||||||
|
*
|
||||||
|
* @param aliases a map of property name to aliases
|
||||||
|
*/
|
||||||
|
public void setNameAliases(Map<String, List<String>> aliases) {
|
||||||
|
this.nameAliases = new LinkedMultiValueMap<String, String>(aliases);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add aliases to the {@link DataBinder}.
|
||||||
|
*
|
||||||
|
* @param name the property name to alias
|
||||||
|
* @param alias aliases for the property names
|
||||||
|
* @return this instance
|
||||||
|
*/
|
||||||
|
public RelaxedDataBinder withAlias(String name, String... alias) {
|
||||||
|
for (String value : alias) {
|
||||||
|
this.nameAliases.add(name, value);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doBind(MutablePropertyValues propertyValues) {
|
||||||
|
super.doBind(modifyProperties(propertyValues, getTarget()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Modify the property values so that period separated property paths are valid
|
||||||
|
* for map keys. Also creates new maps for properties of map type that are null
|
||||||
|
* (assuming all maps are potentially nested). The standard bracket {@code[...]}
|
||||||
|
* dereferencing is also accepted.
|
||||||
|
*
|
||||||
|
* @param propertyValues the property values
|
||||||
|
* @param target the target object
|
||||||
|
* @return modified property values
|
||||||
|
*/
|
||||||
|
private MutablePropertyValues modifyProperties(MutablePropertyValues propertyValues, Object target) {
|
||||||
|
propertyValues = getPropertyValuesForNamePrefix(propertyValues);
|
||||||
|
if (target instanceof RelaxedDataBinder.MapHolder) {
|
||||||
|
propertyValues = addMapPrefix(propertyValues);
|
||||||
|
}
|
||||||
|
BeanWrapper wrapper = new BeanWrapperImpl(target);
|
||||||
|
wrapper.setConversionService(new RelaxedConversionService(getConversionService()));
|
||||||
|
wrapper.setAutoGrowNestedPaths(true);
|
||||||
|
List<PropertyValue> sortedValues = new ArrayList<PropertyValue>();
|
||||||
|
Set<String> modifiedNames = new HashSet<String>();
|
||||||
|
List<String> sortedNames = getSortedPropertyNames(propertyValues);
|
||||||
|
for (String name : sortedNames) {
|
||||||
|
PropertyValue propertyValue = propertyValues.getPropertyValue(name);
|
||||||
|
PropertyValue modifiedProperty = modifyProperty(wrapper, propertyValue);
|
||||||
|
if (modifiedNames.add(modifiedProperty.getName())) {
|
||||||
|
sortedValues.add(modifiedProperty);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new MutablePropertyValues(sortedValues);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> getSortedPropertyNames(MutablePropertyValues propertyValues) {
|
||||||
|
List<String> names = new LinkedList<String>();
|
||||||
|
for (PropertyValue propertyValue : propertyValues.getPropertyValueList()) {
|
||||||
|
names.add(propertyValue.getName());
|
||||||
|
}
|
||||||
|
sortPropertyNames(names);
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort by name so that parent properties get processed first (e.g. 'foo.bar'
|
||||||
|
* before 'foo.bar.spam'). Don't use Collections.sort() because the order might
|
||||||
|
* be significant for other property names (it shouldn't be but who knows what
|
||||||
|
* people might be relying on, e.g. HSQL has a JDBCXADataSource where
|
||||||
|
* "databaseName" is a synonym for "url").
|
||||||
|
*
|
||||||
|
* @param names the names to sort
|
||||||
|
*/
|
||||||
|
private void sortPropertyNames(List<String> names) {
|
||||||
|
for (String name : new ArrayList<String>(names)) {
|
||||||
|
int propertyIndex = names.indexOf(name);
|
||||||
|
RelaxedDataBinder.BeanPath path = new RelaxedDataBinder.BeanPath(name);
|
||||||
|
for (String prefix : path.prefixes()) {
|
||||||
|
int prefixIndex = names.indexOf(prefix);
|
||||||
|
if (prefixIndex >= propertyIndex) {
|
||||||
|
// The child property has a parent in the list in the wrong order
|
||||||
|
names.remove(name);
|
||||||
|
names.add(prefixIndex, name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private MutablePropertyValues addMapPrefix(MutablePropertyValues propertyValues) {
|
||||||
|
MutablePropertyValues rtn = new MutablePropertyValues();
|
||||||
|
for (PropertyValue pv : propertyValues.getPropertyValues()) {
|
||||||
|
rtn.add("map." + pv.getName(), pv.getValue());
|
||||||
|
}
|
||||||
|
return rtn;
|
||||||
|
}
|
||||||
|
|
||||||
|
private MutablePropertyValues getPropertyValuesForNamePrefix(MutablePropertyValues propertyValues) {
|
||||||
|
if (!StringUtils.hasText(this.namePrefix) && !this.ignoreNestedProperties) {
|
||||||
|
return propertyValues;
|
||||||
|
}
|
||||||
|
MutablePropertyValues rtn = new MutablePropertyValues();
|
||||||
|
for (PropertyValue value : propertyValues.getPropertyValues()) {
|
||||||
|
String name = value.getName();
|
||||||
|
for (String prefix : new RelaxedNames(stripLastDot(this.namePrefix))) {
|
||||||
|
for (String separator : new String[] { ".", "_" }) {
|
||||||
|
String candidate = (StringUtils.hasLength(prefix) ? prefix + separator : prefix);
|
||||||
|
if (name.startsWith(candidate)) {
|
||||||
|
name = name.substring(candidate.length());
|
||||||
|
if (!(this.ignoreNestedProperties && name.contains("."))) {
|
||||||
|
PropertyOrigin propertyOrigin = OriginCapablePropertyValue.getOrigin(value);
|
||||||
|
rtn.addPropertyValue(
|
||||||
|
new OriginCapablePropertyValue(name, value.getValue(), propertyOrigin));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rtn;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String stripLastDot(String string) {
|
||||||
|
if (StringUtils.hasLength(string) && string.endsWith(".")) {
|
||||||
|
string = string.substring(0, string.length() - 1);
|
||||||
|
}
|
||||||
|
return string;
|
||||||
|
}
|
||||||
|
|
||||||
|
private PropertyValue modifyProperty(BeanWrapper target, PropertyValue propertyValue) {
|
||||||
|
String name = propertyValue.getName();
|
||||||
|
String normalizedName = normalizePath(target, name);
|
||||||
|
if (!normalizedName.equals(name)) {
|
||||||
|
return new PropertyValue(normalizedName, propertyValue.getValue());
|
||||||
|
}
|
||||||
|
return propertyValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize a bean property path to a format understood by a BeanWrapper. This
|
||||||
|
* is used so that
|
||||||
|
* <ul>
|
||||||
|
* <li>Fuzzy matching can be employed for bean property names</li>
|
||||||
|
* <li>Period separators can be used instead of indexing ([...]) for map
|
||||||
|
* keys</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* @param wrapper a bean wrapper for the object to bind
|
||||||
|
* @param path the bean path to bind
|
||||||
|
* @return a transformed path with correct bean wrapper syntax
|
||||||
|
*/
|
||||||
|
protected String normalizePath(BeanWrapper wrapper, String path) {
|
||||||
|
return initializePath(wrapper, new RelaxedDataBinder.BeanPath(path), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected AbstractPropertyBindingResult createBeanPropertyBindingResult() {
|
||||||
|
return new RelaxedDataBinder.RelaxedBeanPropertyBindingResult(getTarget(),
|
||||||
|
getObjectName(),
|
||||||
|
isAutoGrowNestedPaths(),
|
||||||
|
getAutoGrowCollectionLimit(),
|
||||||
|
getConversionService());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String initializePath(BeanWrapper wrapper, RelaxedDataBinder.BeanPath path, int index) {
|
||||||
|
String prefix = path.prefix(index);
|
||||||
|
String key = path.name(index);
|
||||||
|
if (path.isProperty(index)) {
|
||||||
|
key = getActualPropertyName(wrapper, prefix, key);
|
||||||
|
path.rename(index, key);
|
||||||
|
}
|
||||||
|
if (path.name(++index) == null) {
|
||||||
|
return path.toString();
|
||||||
|
}
|
||||||
|
String name = path.prefix(index);
|
||||||
|
TypeDescriptor descriptor = wrapper.getPropertyTypeDescriptor(name);
|
||||||
|
if (descriptor == null || descriptor.isMap()) {
|
||||||
|
if (isMapValueStringType(descriptor) || isBlanked(wrapper, name, path.name(index))) {
|
||||||
|
path.collapseKeys(index);
|
||||||
|
}
|
||||||
|
path.mapIndex(index);
|
||||||
|
extendMapIfNecessary(wrapper, path, index);
|
||||||
|
} else if (descriptor.isCollection()) {
|
||||||
|
extendCollectionIfNecessary(wrapper, path, index);
|
||||||
|
} else if (descriptor.getType().equals(Object.class)) {
|
||||||
|
if (isBlanked(wrapper, name, path.name(index))) {
|
||||||
|
path.collapseKeys(index);
|
||||||
|
}
|
||||||
|
path.mapIndex(index);
|
||||||
|
if (path.isLastNode(index)) {
|
||||||
|
wrapper.setPropertyValue(path.toString(), BLANK);
|
||||||
|
} else {
|
||||||
|
String next = path.prefix(index + 1);
|
||||||
|
if (wrapper.getPropertyValue(next) == null) {
|
||||||
|
wrapper.setPropertyValue(next, new LinkedHashMap<String, Object>());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return initializePath(wrapper, path, index);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isMapValueStringType(TypeDescriptor descriptor) {
|
||||||
|
if (descriptor == null || descriptor.getMapValueTypeDescriptor() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (Properties.class.isAssignableFrom(descriptor.getObjectType())) {
|
||||||
|
// Properties is declared as Map<Object,Object> but we know it's really
|
||||||
|
// Map<String,String>
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
Class<?> valueType = descriptor.getMapValueTypeDescriptor().getObjectType();
|
||||||
|
return (valueType != null && CharSequence.class.isAssignableFrom(valueType));
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("rawtypes")
|
||||||
|
private boolean isBlanked(BeanWrapper wrapper, String propertyName, String key) {
|
||||||
|
Object value = (wrapper.isReadableProperty(propertyName) ? wrapper.getPropertyValue(propertyName) : null);
|
||||||
|
if (value instanceof Map) {
|
||||||
|
if (((Map) value).get(key) == BLANK) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void extendCollectionIfNecessary(BeanWrapper wrapper, RelaxedDataBinder.BeanPath path, int index) {
|
||||||
|
String name = path.prefix(index);
|
||||||
|
TypeDescriptor elementDescriptor = wrapper.getPropertyTypeDescriptor(name).getElementTypeDescriptor();
|
||||||
|
if (!elementDescriptor.isMap() && !elementDescriptor.isCollection()
|
||||||
|
&& !elementDescriptor.getType().equals(Object.class)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Object extend = new LinkedHashMap<String, Object>();
|
||||||
|
if (!elementDescriptor.isMap() && path.isArrayIndex(index)) {
|
||||||
|
extend = new ArrayList<Object>();
|
||||||
|
}
|
||||||
|
wrapper.setPropertyValue(path.prefix(index + 1), extend);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void extendMapIfNecessary(BeanWrapper wrapper, RelaxedDataBinder.BeanPath path, int index) {
|
||||||
|
String name = path.prefix(index);
|
||||||
|
TypeDescriptor parent = wrapper.getPropertyTypeDescriptor(name);
|
||||||
|
if (parent == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
TypeDescriptor descriptor = parent.getMapValueTypeDescriptor();
|
||||||
|
if (descriptor == null) {
|
||||||
|
descriptor = TypeDescriptor.valueOf(Object.class);
|
||||||
|
}
|
||||||
|
if (!descriptor.isMap() && !descriptor.isCollection() && !descriptor.getType().equals(Object.class)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String extensionName = path.prefix(index + 1);
|
||||||
|
if (wrapper.isReadableProperty(extensionName)) {
|
||||||
|
Object currentValue = wrapper.getPropertyValue(extensionName);
|
||||||
|
if ((descriptor.isCollection() && currentValue instanceof Collection)
|
||||||
|
|| (!descriptor.isCollection() && currentValue instanceof Map)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Object extend = new LinkedHashMap<String, Object>();
|
||||||
|
if (descriptor.isCollection()) {
|
||||||
|
extend = new ArrayList<Object>();
|
||||||
|
}
|
||||||
|
if (descriptor.getType().equals(Object.class) && path.isLastNode(index)) {
|
||||||
|
extend = BLANK;
|
||||||
|
}
|
||||||
|
wrapper.setPropertyValue(extensionName, extend);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getActualPropertyName(BeanWrapper target, String prefix, String name) {
|
||||||
|
String propertyName = resolvePropertyName(target, prefix, name);
|
||||||
|
if (propertyName == null) {
|
||||||
|
propertyName = resolveNestedPropertyName(target, prefix, name);
|
||||||
|
}
|
||||||
|
return (propertyName != null ? propertyName : name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveNestedPropertyName(BeanWrapper target, String prefix, String name) {
|
||||||
|
StringBuilder candidate = new StringBuilder();
|
||||||
|
for (String field : name.split("[_\\-\\.]")) {
|
||||||
|
candidate.append(candidate.length() > 0 ? "." : "");
|
||||||
|
candidate.append(field);
|
||||||
|
String nested = resolvePropertyName(target, prefix, candidate.toString());
|
||||||
|
if (nested != null) {
|
||||||
|
Class<?> type = target.getPropertyType(nested);
|
||||||
|
if ((type != null) && Map.class.isAssignableFrom(type)) {
|
||||||
|
// Special case for map property (gh-3836).
|
||||||
|
return nested + "[" + name.substring(candidate.length() + 1) + "]";
|
||||||
|
}
|
||||||
|
String propertyName = resolvePropertyName(target,
|
||||||
|
joinString(prefix, nested),
|
||||||
|
name.substring(candidate.length() + 1));
|
||||||
|
if (propertyName != null) {
|
||||||
|
return joinString(nested, propertyName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolvePropertyName(BeanWrapper target, String prefix, String name) {
|
||||||
|
Iterable<String> names = getNameAndAliases(name);
|
||||||
|
for (String nameOrAlias : names) {
|
||||||
|
for (String candidate : new RelaxedNames(nameOrAlias)) {
|
||||||
|
try {
|
||||||
|
if (target.getPropertyType(joinString(prefix, candidate)) != null) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
} catch (InvalidPropertyException ex) {
|
||||||
|
// swallow and continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String joinString(String prefix, String name) {
|
||||||
|
return (StringUtils.hasLength(prefix) ? prefix + "." + name : name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Iterable<String> getNameAndAliases(String name) {
|
||||||
|
List<String> aliases = this.nameAliases.get(name);
|
||||||
|
if (aliases == null) {
|
||||||
|
return Collections.singleton(name);
|
||||||
|
}
|
||||||
|
List<String> nameAndAliases = new ArrayList<String>(aliases.size() + 1);
|
||||||
|
nameAndAliases.add(name);
|
||||||
|
nameAndAliases.addAll(aliases);
|
||||||
|
return nameAndAliases;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object wrapTarget(Object target) {
|
||||||
|
if (target instanceof Map) {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> map = (Map<String, Object>) target;
|
||||||
|
target = new RelaxedDataBinder.MapHolder(map);
|
||||||
|
}
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {
|
||||||
|
if (propertyEditor == null || !EXCLUDED_EDITORS.contains(propertyEditor.getClass())) {
|
||||||
|
super.registerCustomEditor(requiredType, propertyEditor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void registerCustomEditor(Class<?> requiredType, String field, PropertyEditor propertyEditor) {
|
||||||
|
if (propertyEditor == null || !EXCLUDED_EDITORS.contains(propertyEditor.getClass())) {
|
||||||
|
super.registerCustomEditor(requiredType, field, propertyEditor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holder to allow Map targets to be bound.
|
||||||
|
*/
|
||||||
|
static class MapHolder {
|
||||||
|
|
||||||
|
private Map<String, Object> map;
|
||||||
|
|
||||||
|
MapHolder(Map<String, Object> map){
|
||||||
|
this.map = map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMap(Map<String, Object> map) {
|
||||||
|
this.map = map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> getMap() {
|
||||||
|
return this.map;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A path though properties of a bean.
|
||||||
|
*/
|
||||||
|
private static class BeanPath {
|
||||||
|
|
||||||
|
private List<PathNode> nodes;
|
||||||
|
|
||||||
|
BeanPath(String path){
|
||||||
|
this.nodes = splitPath(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> prefixes() {
|
||||||
|
List<String> prefixes = new ArrayList<String>();
|
||||||
|
for (int index = 1; index < this.nodes.size(); index++) {
|
||||||
|
prefixes.add(prefix(index));
|
||||||
|
}
|
||||||
|
return prefixes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isLastNode(int index) {
|
||||||
|
return index >= this.nodes.size() - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<PathNode> splitPath(String path) {
|
||||||
|
List<PathNode> nodes = new ArrayList<PathNode>();
|
||||||
|
String current = extractIndexedPaths(path, nodes);
|
||||||
|
for (String name : StringUtils.delimitedListToStringArray(current, ".")) {
|
||||||
|
if (StringUtils.hasText(name)) {
|
||||||
|
nodes.add(new RelaxedDataBinder.BeanPath.PropertyNode(name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nodes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String extractIndexedPaths(String path, List<PathNode> nodes) {
|
||||||
|
int startRef = path.indexOf("[");
|
||||||
|
String current = path;
|
||||||
|
while (startRef >= 0) {
|
||||||
|
if (startRef > 0) {
|
||||||
|
nodes.addAll(splitPath(current.substring(0, startRef)));
|
||||||
|
}
|
||||||
|
int endRef = current.indexOf("]", startRef);
|
||||||
|
if (endRef > 0) {
|
||||||
|
String sub = current.substring(startRef + 1, endRef);
|
||||||
|
if (sub.matches("[0-9]+")) {
|
||||||
|
nodes.add(new RelaxedDataBinder.BeanPath.ArrayIndexNode(sub));
|
||||||
|
} else {
|
||||||
|
nodes.add(new RelaxedDataBinder.BeanPath.MapIndexNode(sub));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
current = current.substring(endRef + 1);
|
||||||
|
startRef = current.indexOf("[");
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void collapseKeys(int index) {
|
||||||
|
List<PathNode> revised = new ArrayList<PathNode>();
|
||||||
|
for (int i = 0; i < index; i++) {
|
||||||
|
revised.add(this.nodes.get(i));
|
||||||
|
}
|
||||||
|
StringBuilder builder = new StringBuilder();
|
||||||
|
for (int i = index; i < this.nodes.size(); i++) {
|
||||||
|
if (i > index) {
|
||||||
|
builder.append(".");
|
||||||
|
}
|
||||||
|
builder.append(this.nodes.get(i).name);
|
||||||
|
}
|
||||||
|
revised.add(new RelaxedDataBinder.BeanPath.PropertyNode(builder.toString()));
|
||||||
|
this.nodes = revised;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void mapIndex(int index) {
|
||||||
|
RelaxedDataBinder.BeanPath.PathNode node = this.nodes.get(index);
|
||||||
|
if (node instanceof RelaxedDataBinder.BeanPath.PropertyNode) {
|
||||||
|
node = ((RelaxedDataBinder.BeanPath.PropertyNode) node).mapIndex();
|
||||||
|
}
|
||||||
|
this.nodes.set(index, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String prefix(int index) {
|
||||||
|
return range(0, index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void rename(int index, String name) {
|
||||||
|
this.nodes.get(index).name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String name(int index) {
|
||||||
|
if (index < this.nodes.size()) {
|
||||||
|
return this.nodes.get(index).name;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String range(int start, int end) {
|
||||||
|
StringBuilder builder = new StringBuilder();
|
||||||
|
for (int i = start; i < end; i++) {
|
||||||
|
RelaxedDataBinder.BeanPath.PathNode node = this.nodes.get(i);
|
||||||
|
builder.append(node);
|
||||||
|
}
|
||||||
|
if (builder.toString().startsWith(("."))) {
|
||||||
|
builder.replace(0, 1, "");
|
||||||
|
}
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isArrayIndex(int index) {
|
||||||
|
return this.nodes.get(index) instanceof RelaxedDataBinder.BeanPath.ArrayIndexNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isProperty(int index) {
|
||||||
|
return this.nodes.get(index) instanceof RelaxedDataBinder.BeanPath.PropertyNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return prefix(this.nodes.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class PathNode {
|
||||||
|
|
||||||
|
protected String name;
|
||||||
|
|
||||||
|
PathNode(String name){
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class ArrayIndexNode extends RelaxedDataBinder.BeanPath.PathNode {
|
||||||
|
|
||||||
|
ArrayIndexNode(String name){
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "[" + this.name + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class MapIndexNode extends RelaxedDataBinder.BeanPath.PathNode {
|
||||||
|
|
||||||
|
MapIndexNode(String name){
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "[" + this.name + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class PropertyNode extends RelaxedDataBinder.BeanPath.PathNode {
|
||||||
|
|
||||||
|
PropertyNode(String name){
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RelaxedDataBinder.BeanPath.MapIndexNode mapIndex() {
|
||||||
|
return new RelaxedDataBinder.BeanPath.MapIndexNode(this.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "." + this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extended version of {@link BeanPropertyBindingResult} to support relaxed
|
||||||
|
* binding.
|
||||||
|
*/
|
||||||
|
private static class RelaxedBeanPropertyBindingResult extends BeanPropertyBindingResult {
|
||||||
|
|
||||||
|
private RelaxedConversionService conversionService;
|
||||||
|
|
||||||
|
RelaxedBeanPropertyBindingResult(Object target, String objectName, boolean autoGrowNestedPaths,
|
||||||
|
int autoGrowCollectionLimit, ConversionService conversionService){
|
||||||
|
super(target, objectName, autoGrowNestedPaths, autoGrowCollectionLimit);
|
||||||
|
this.conversionService = new RelaxedConversionService(conversionService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected BeanWrapper createBeanWrapper() {
|
||||||
|
BeanWrapper beanWrapper = new RelaxedDataBinder.RelaxedBeanWrapper(getTarget());
|
||||||
|
beanWrapper.setConversionService(this.conversionService);
|
||||||
|
beanWrapper.registerCustomEditor(InetAddress.class, new InetAddressEditor());
|
||||||
|
return beanWrapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extended version of {@link BeanWrapperImpl} to support relaxed binding.
|
||||||
|
*/
|
||||||
|
private static class RelaxedBeanWrapper extends BeanWrapperImpl {
|
||||||
|
|
||||||
|
private static final Set<String> BENIGN_PROPERTY_SOURCE_NAMES;
|
||||||
|
|
||||||
|
static {
|
||||||
|
Set<String> names = new HashSet<String>();
|
||||||
|
names.add(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
|
||||||
|
names.add(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
|
||||||
|
BENIGN_PROPERTY_SOURCE_NAMES = Collections.unmodifiableSet(names);
|
||||||
|
}
|
||||||
|
|
||||||
|
RelaxedBeanWrapper(Object target){
|
||||||
|
super(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setPropertyValue(PropertyValue pv) throws BeansException {
|
||||||
|
try {
|
||||||
|
super.setPropertyValue(pv);
|
||||||
|
} catch (NotWritablePropertyException ex) {
|
||||||
|
PropertyOrigin origin = OriginCapablePropertyValue.getOrigin(pv);
|
||||||
|
if (isBenign(origin)) {
|
||||||
|
logger.debug("Ignoring benign property binding failure", ex);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (origin == null) {
|
||||||
|
throw ex;
|
||||||
|
}
|
||||||
|
throw new RelaxedBindingNotWritablePropertyException(ex, origin);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isBenign(PropertyOrigin origin) {
|
||||||
|
String name = (origin != null ? origin.getSource().getName() : null);
|
||||||
|
return BENIGN_PROPERTY_SOURCE_NAMES.contains(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class RelaxedBindingNotWritablePropertyException extends NotWritablePropertyException {
|
||||||
|
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
private final PropertyOrigin propertyOrigin;
|
||||||
|
|
||||||
|
RelaxedBindingNotWritablePropertyException(NotWritablePropertyException ex, PropertyOrigin propertyOrigin){
|
||||||
|
super(ex.getBeanClass(), ex.getPropertyName());
|
||||||
|
this.propertyOrigin = propertyOrigin;
|
||||||
|
this.message = "Failed to bind '" + propertyOrigin.getName() + "' from '"
|
||||||
|
+ propertyOrigin.getSource().getName() + "' to '" + ex.getPropertyName() + "' property on '"
|
||||||
|
+ ex.getBeanClass().getName() + "'";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getMessage() {
|
||||||
|
return this.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PropertyOrigin getPropertyOrigin() {
|
||||||
|
return this.propertyOrigin;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates relaxed name variations from a given source.
|
||||||
|
*
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @author Dave Syer
|
||||||
|
* @see RelaxedDataBinder
|
||||||
|
*/
|
||||||
|
public final class RelaxedNames implements Iterable<String> {
|
||||||
|
|
||||||
|
private static final Pattern CAMEL_CASE_PATTERN = Pattern.compile("([^A-Z-])([A-Z])");
|
||||||
|
|
||||||
|
private static final Pattern SEPARATED_TO_CAMEL_CASE_PATTERN = Pattern.compile("[_\\-.]");
|
||||||
|
|
||||||
|
private final String name;
|
||||||
|
|
||||||
|
private final Set<String> values = new LinkedHashSet<String>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@link RelaxedNames} instance.
|
||||||
|
*
|
||||||
|
* @param name the source name. For the maximum number of variations specify the
|
||||||
|
* name using dashed notation (e.g. {@literal my-property-name}
|
||||||
|
*/
|
||||||
|
public RelaxedNames(String name){
|
||||||
|
this.name = (name != null ? name : "");
|
||||||
|
initialize(RelaxedNames.this.name, this.values);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Iterator<String> iterator() {
|
||||||
|
return this.values.iterator();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initialize(String name, Set<String> values) {
|
||||||
|
if (values.contains(name)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (RelaxedNames.Variation variation : RelaxedNames.Variation.values()) {
|
||||||
|
for (RelaxedNames.Manipulation manipulation : RelaxedNames.Manipulation.values()) {
|
||||||
|
String result = name;
|
||||||
|
result = manipulation.apply(result);
|
||||||
|
result = variation.apply(result);
|
||||||
|
values.add(result);
|
||||||
|
initialize(result, values);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Name variations.
|
||||||
|
*/
|
||||||
|
enum Variation {
|
||||||
|
|
||||||
|
NONE {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
LOWERCASE {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
return (value.isEmpty() ? value : value.toLowerCase(Locale.ENGLISH));
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
UPPERCASE {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
return (value.isEmpty() ? value : value.toUpperCase(Locale.ENGLISH));
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
public abstract String apply(String value);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Name manipulations.
|
||||||
|
*/
|
||||||
|
enum Manipulation {
|
||||||
|
|
||||||
|
NONE {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
HYPHEN_TO_UNDERSCORE {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
return (value.indexOf('-') != -1 ? value.replace('-', '_') : value);
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
UNDERSCORE_TO_PERIOD {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
return (value.indexOf('_') != -1 ? value.replace('_', '.') : value);
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
PERIOD_TO_UNDERSCORE {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
return (value.indexOf('.') != -1 ? value.replace('.', '_') : value);
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
CAMELCASE_TO_UNDERSCORE {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
if (value.isEmpty()) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
Matcher matcher = CAMEL_CASE_PATTERN.matcher(value);
|
||||||
|
if (!matcher.find()) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
matcher = matcher.reset();
|
||||||
|
StringBuffer result = new StringBuffer();
|
||||||
|
while (matcher.find()) {
|
||||||
|
matcher.appendReplacement(result,
|
||||||
|
matcher.group(1) + '_' + StringUtils.uncapitalize(matcher.group(2)));
|
||||||
|
}
|
||||||
|
matcher.appendTail(result);
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
CAMELCASE_TO_HYPHEN {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
if (value.isEmpty()) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
Matcher matcher = CAMEL_CASE_PATTERN.matcher(value);
|
||||||
|
if (!matcher.find()) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
matcher = matcher.reset();
|
||||||
|
StringBuffer result = new StringBuffer();
|
||||||
|
while (matcher.find()) {
|
||||||
|
matcher.appendReplacement(result,
|
||||||
|
matcher.group(1) + '-' + StringUtils.uncapitalize(matcher.group(2)));
|
||||||
|
}
|
||||||
|
matcher.appendTail(result);
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
SEPARATED_TO_CAMELCASE {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
return separatedToCamelCase(value, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
CASE_INSENSITIVE_SEPARATED_TO_CAMELCASE {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(String value) {
|
||||||
|
return separatedToCamelCase(value, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
private static final char[] SUFFIXES = new char[] { '_', '-', '.' };
|
||||||
|
|
||||||
|
public abstract String apply(String value);
|
||||||
|
|
||||||
|
private static String separatedToCamelCase(String value, boolean caseInsensitive) {
|
||||||
|
if (value.isEmpty()) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
StringBuilder builder = new StringBuilder();
|
||||||
|
for (String field : SEPARATED_TO_CAMEL_CASE_PATTERN.split(value)) {
|
||||||
|
field = (caseInsensitive ? field.toLowerCase(Locale.ENGLISH) : field);
|
||||||
|
builder.append(builder.length() != 0 ? StringUtils.capitalize(field) : field);
|
||||||
|
}
|
||||||
|
char lastChar = value.charAt(value.length() - 1);
|
||||||
|
for (char suffix : SUFFIXES) {
|
||||||
|
if (lastChar == suffix) {
|
||||||
|
builder.append(suffix);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a {@link RelaxedNames} for the given source camelCase source name.
|
||||||
|
*
|
||||||
|
* @param name the source name in camelCase
|
||||||
|
* @return the relaxed names
|
||||||
|
*/
|
||||||
|
public static RelaxedNames forCamelCase(String name) {
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
for (char c : name.toCharArray()) {
|
||||||
|
result.append(Character.isUpperCase(c) && result.length() > 0
|
||||||
|
&& result.charAt(result.length() - 1) != '-' ? "-" + Character.toLowerCase(c) : c);
|
||||||
|
}
|
||||||
|
return new RelaxedNames(result.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.bind;
|
||||||
|
|
||||||
|
import org.springframework.core.convert.converter.Converter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a String to a Char Array.
|
||||||
|
*
|
||||||
|
* @author Phillip Webb
|
||||||
|
*/
|
||||||
|
class StringToCharArrayConverter implements Converter<String, char[]> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public char[] convert(String source) {
|
||||||
|
return source.toCharArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
import org.springframework.util.ResourceUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convenience base class for {@link Resource} implementations, pre-implementing
|
||||||
|
* typical behavior.
|
||||||
|
* <p>
|
||||||
|
* The "exists" method will check whether a File or InputStream can be opened;
|
||||||
|
* "isOpen" will always return false; "getURL" and "getFile" throw an exception;
|
||||||
|
* and "toString" will return the description.
|
||||||
|
*
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @since 28.12.2003
|
||||||
|
*/
|
||||||
|
public abstract class AbstractResource implements Resource {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation checks whether a File can be opened, falling back to
|
||||||
|
* whether an InputStream can be opened. This will cover both directories and
|
||||||
|
* content resources.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean exists() {
|
||||||
|
// Try file existence: can we find the file in the file system?
|
||||||
|
try {
|
||||||
|
return getFile().exists();
|
||||||
|
} catch (IOException ex) {
|
||||||
|
// Fall back to stream existence: can we open the stream?
|
||||||
|
try {
|
||||||
|
InputStream is = getInputStream();
|
||||||
|
is.close();
|
||||||
|
return true;
|
||||||
|
} catch (Throwable isEx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation always returns {@code true}.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean isReadable() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation always returns {@code false}.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean isOpen() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation throws a FileNotFoundException, assuming that the
|
||||||
|
* resource cannot be resolved to a URL.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public URL getURL() throws IOException {
|
||||||
|
throw new FileNotFoundException(getDescription() + " cannot be resolved to URL");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation builds a URI based on the URL returned by
|
||||||
|
* {@link #getURL()}.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public URI getURI() throws IOException {
|
||||||
|
URL url = getURL();
|
||||||
|
try {
|
||||||
|
return ResourceUtils.toURI(url);
|
||||||
|
} catch (URISyntaxException ex) {
|
||||||
|
throw new RuntimeException("Invalid URI [" + url + "]", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation throws a FileNotFoundException, assuming that the
|
||||||
|
* resource cannot be resolved to an absolute file path.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public File getFile() throws IOException {
|
||||||
|
throw new FileNotFoundException(getDescription() + " cannot be resolved to absolute file path");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation reads the entire InputStream to calculate the content
|
||||||
|
* length. Subclasses will almost always be able to provide a more optimal
|
||||||
|
* version of this, e.g. checking a File length.
|
||||||
|
*
|
||||||
|
* @see #getInputStream()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public long contentLength() throws IOException {
|
||||||
|
InputStream is = getInputStream();
|
||||||
|
Assert.state(is != null, "Resource InputStream must not be null");
|
||||||
|
try {
|
||||||
|
long size = 0;
|
||||||
|
byte[] buf = new byte[255];
|
||||||
|
int read;
|
||||||
|
while ((read = is.read(buf)) != -1) {
|
||||||
|
size += read;
|
||||||
|
}
|
||||||
|
return size;
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
is.close();
|
||||||
|
} catch (IOException ex) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation checks the timestamp of the underlying File, if
|
||||||
|
* available.
|
||||||
|
*
|
||||||
|
* @see #getFileForLastModifiedCheck()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public long lastModified() throws IOException {
|
||||||
|
long lastModified = getFileForLastModifiedCheck().lastModified();
|
||||||
|
if (lastModified == 0L) {
|
||||||
|
throw new FileNotFoundException(
|
||||||
|
getDescription() + " cannot be resolved in the file system for resolving its last-modified timestamp");
|
||||||
|
}
|
||||||
|
return lastModified;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine the File to use for timestamp checking.
|
||||||
|
* <p>
|
||||||
|
* The default implementation delegates to {@link #getFile()}.
|
||||||
|
*
|
||||||
|
* @return the File to use for timestamp checking (never {@code null})
|
||||||
|
* @throws FileNotFoundException if the resource cannot be resolved as an
|
||||||
|
* absolute file path, i.e. is not available in a file system
|
||||||
|
* @throws IOException in case of general resolution/reading failures
|
||||||
|
*/
|
||||||
|
protected File getFileForLastModifiedCheck() throws IOException {
|
||||||
|
return getFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation throws a FileNotFoundException, assuming that relative
|
||||||
|
* resources cannot be created for this resource.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public org.springframework.core.io.Resource createRelative(String relativePath) throws IOException {
|
||||||
|
throw new FileNotFoundException("Cannot create a relative resource for " + getDescription());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation always returns {@code null}, assuming that this resource
|
||||||
|
* type does not have a filename.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public String getFilename() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation returns the description of this resource.
|
||||||
|
*
|
||||||
|
* @see #getDescription()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return getDescription();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation compares description strings.
|
||||||
|
*
|
||||||
|
* @see #getDescription()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
return (obj == this
|
||||||
|
|| (obj instanceof org.springframework.core.io.Resource
|
||||||
|
&& ((org.springframework.core.io.Resource) obj).getDescription().equals(getDescription())));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation returns the description's hash code.
|
||||||
|
*
|
||||||
|
* @see #getDescription()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return getDescription().hashCode();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
import org.springframework.core.io.InputStreamResource;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link Resource} implementation for a given byte array.
|
||||||
|
* <p>
|
||||||
|
* Creates a {@link ByteArrayInputStream} for the given byte array.
|
||||||
|
* <p>
|
||||||
|
* Useful for loading content from any given byte array, without having to
|
||||||
|
* resort to a single-use {@link InputStreamResource}. Particularly useful for
|
||||||
|
* creating mail attachments from local content, where JavaMail needs to be able
|
||||||
|
* to read the stream multiple times.
|
||||||
|
*
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @author Sam Brannen
|
||||||
|
* @see ByteArrayInputStream
|
||||||
|
* @see InputStreamResource
|
||||||
|
* @since 1.2.3
|
||||||
|
*/
|
||||||
|
public class ByteArrayResource extends AbstractResource {
|
||||||
|
|
||||||
|
private final byte[] byteArray;
|
||||||
|
|
||||||
|
private final String description;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@code ByteArrayResource}.
|
||||||
|
*
|
||||||
|
* @param byteArray the byte array to wrap
|
||||||
|
*/
|
||||||
|
public ByteArrayResource(byte[] byteArray){
|
||||||
|
this(byteArray, "resource loaded from byte array");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@code ByteArrayResource} with a description.
|
||||||
|
*
|
||||||
|
* @param byteArray the byte array to wrap
|
||||||
|
* @param description where the byte array comes from
|
||||||
|
*/
|
||||||
|
public ByteArrayResource(byte[] byteArray, String description){
|
||||||
|
Assert.notNull(byteArray, "Byte array must not be null");
|
||||||
|
this.byteArray = byteArray;
|
||||||
|
this.description = (description != null ? description : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the underlying byte array.
|
||||||
|
*/
|
||||||
|
public final byte[] getByteArray() {
|
||||||
|
return this.byteArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation always returns {@code true}.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean exists() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation returns the length of the underlying byte array.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public long contentLength() {
|
||||||
|
return this.byteArray.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation returns a ByteArrayInputStream for the underlying byte
|
||||||
|
* array.
|
||||||
|
*
|
||||||
|
* @see ByteArrayInputStream
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public InputStream getInputStream() throws IOException {
|
||||||
|
return new ByteArrayInputStream(this.byteArray);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation returns a description that includes the passed-in
|
||||||
|
* {@code description}, if any.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public String getDescription() {
|
||||||
|
return "Byte array resource [" + this.description + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation compares the underlying byte array.
|
||||||
|
*
|
||||||
|
* @see Arrays#equals(byte[], byte[])
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
return (obj == this || (obj instanceof org.springframework.core.io.ByteArrayResource
|
||||||
|
&& Arrays.equals(((ByteArrayResource) obj).byteArray, this.byteArray)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This implementation returns the hash code based on the underlying byte array.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return (byte[].class.hashCode() * 29 * this.byteArray.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Composite {@link PropertySource} implementation that iterates over a set of
|
||||||
|
* {@link PropertySource} instances. Necessary in cases where multiple property
|
||||||
|
* sources share the same name, e.g. when multiple values are supplied to
|
||||||
|
* {@code @PropertySource}.
|
||||||
|
* <p>
|
||||||
|
* As of Spring 4.1.2, this class extends {@link EnumerablePropertySource}
|
||||||
|
* instead of plain {@link PropertySource}, exposing {@link #getPropertyNames()}
|
||||||
|
* based on the accumulated property names from all contained sources (as far as
|
||||||
|
* possible).
|
||||||
|
*
|
||||||
|
* @author Chris Beams
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @since 3.1.1
|
||||||
|
*/
|
||||||
|
public class CompositePropertySource extends EnumerablePropertySource<Object> {
|
||||||
|
|
||||||
|
private final Set<PropertySource<?>> propertySources = new LinkedHashSet<PropertySource<?>>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@code CompositePropertySource}.
|
||||||
|
*
|
||||||
|
* @param name the name of the property source
|
||||||
|
*/
|
||||||
|
public CompositePropertySource(String name){
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getProperty(String name) {
|
||||||
|
for (PropertySource<?> propertySource : this.propertySources) {
|
||||||
|
Object candidate = propertySource.getProperty(name);
|
||||||
|
if (candidate != null) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean containsProperty(String name) {
|
||||||
|
for (PropertySource<?> propertySource : this.propertySources) {
|
||||||
|
if (propertySource.containsProperty(name)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String[] getPropertyNames() {
|
||||||
|
Set<String> names = new LinkedHashSet<String>();
|
||||||
|
for (PropertySource<?> propertySource : this.propertySources) {
|
||||||
|
if (!(propertySource instanceof EnumerablePropertySource)) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"Failed to enumerate property names due to non-enumerable property source: " + propertySource);
|
||||||
|
}
|
||||||
|
names.addAll(Arrays.asList(((EnumerablePropertySource<?>) propertySource).getPropertyNames()));
|
||||||
|
}
|
||||||
|
return StringUtils.toStringArray(names);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the given {@link PropertySource} to the end of the chain.
|
||||||
|
*
|
||||||
|
* @param propertySource the PropertySource to add
|
||||||
|
*/
|
||||||
|
public void addPropertySource(PropertySource<?> propertySource) {
|
||||||
|
this.propertySources.add(propertySource);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the given {@link PropertySource} to the start of the chain.
|
||||||
|
*
|
||||||
|
* @param propertySource the PropertySource to add
|
||||||
|
* @since 4.1
|
||||||
|
*/
|
||||||
|
public void addFirstPropertySource(PropertySource<?> propertySource) {
|
||||||
|
List<PropertySource<?>> existing = new ArrayList<PropertySource<?>>(this.propertySources);
|
||||||
|
this.propertySources.clear();
|
||||||
|
this.propertySources.add(propertySource);
|
||||||
|
this.propertySources.addAll(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return all property sources that this composite source holds.
|
||||||
|
*
|
||||||
|
* @since 4.1.1
|
||||||
|
*/
|
||||||
|
public Collection<PropertySource<?>> getPropertySources() {
|
||||||
|
return this.propertySources;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return String
|
||||||
|
.format("%s [name='%s', propertySources=%s]", getClass().getSimpleName(), this.name, this.propertySources);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import org.springframework.util.ObjectUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A {@link PropertySource} implementation capable of interrogating its
|
||||||
|
* underlying source object to enumerate all possible property name/value pairs.
|
||||||
|
* Exposes the {@link #getPropertyNames()} method to allow callers to introspect
|
||||||
|
* available properties without having to access the underlying source object.
|
||||||
|
* This also facilitates a more efficient implementation of
|
||||||
|
* {@link #containsProperty(String)}, in that it can call
|
||||||
|
* {@link #getPropertyNames()} and iterate through the returned array rather
|
||||||
|
* than attempting a call to {@link #getProperty(String)} which may be more
|
||||||
|
* expensive. Implementations may consider caching the result of
|
||||||
|
* {@link #getPropertyNames()} to fully exploit this performance opportunity.
|
||||||
|
* <p>
|
||||||
|
* Most framework-provided {@code PropertySource} implementations are
|
||||||
|
* enumerable; a counter-example would be {@code JndiPropertySource} where, due
|
||||||
|
* to the nature of JNDI it is not possible to determine all possible property
|
||||||
|
* names at any given time; rather it is only possible to try to access a
|
||||||
|
* property (via {@link #getProperty(String)}) in order to evaluate whether it
|
||||||
|
* is present or not.
|
||||||
|
*
|
||||||
|
* @author Chris Beams
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @since 3.1
|
||||||
|
*/
|
||||||
|
public abstract class EnumerablePropertySource<T> extends PropertySource<T> {
|
||||||
|
|
||||||
|
public EnumerablePropertySource(String name, T source){
|
||||||
|
super(name, source);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected EnumerablePropertySource(String name){
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return whether this {@code PropertySource} contains a property with the given
|
||||||
|
* name.
|
||||||
|
* <p>
|
||||||
|
* This implementation checks for the presence of the given name within the
|
||||||
|
* {@link #getPropertyNames()} array.
|
||||||
|
*
|
||||||
|
* @param name the name of the property to find
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean containsProperty(String name) {
|
||||||
|
return ObjectUtils.containsElement(getPropertyNames(), name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the names of all properties contained by the {@linkplain #getSource()
|
||||||
|
* source} object (never {@code null}).
|
||||||
|
*/
|
||||||
|
public abstract String[] getPropertyNames();
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.core.env.PropertiesPropertySource;
|
||||||
|
import org.springframework.core.env.PropertySource;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link PropertySource} that reads keys and values from a {@code Map} object.
|
||||||
|
*
|
||||||
|
* @author Chris Beams
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @since 3.1
|
||||||
|
* @see PropertiesPropertySource
|
||||||
|
*/
|
||||||
|
public class MapPropertySource extends EnumerablePropertySource<Map<String, Object>> {
|
||||||
|
|
||||||
|
public MapPropertySource(String name, Map<String, Object> source){
|
||||||
|
super(name, source);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getProperty(String name) {
|
||||||
|
return this.source.get(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean containsProperty(String name) {
|
||||||
|
return this.source.containsKey(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String[] getPropertyNames() {
|
||||||
|
return StringUtils.toStringArray(this.source.keySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.springframework.core.env.PropertyResolver;
|
||||||
|
import org.springframework.core.env.PropertySourcesPropertyResolver;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default implementation of the {@link PropertySources} interface. Allows
|
||||||
|
* manipulation of contained property sources and provides a constructor for
|
||||||
|
* copying an existing {@code PropertySources} instance.
|
||||||
|
* <p>
|
||||||
|
* Where <em>precedence</em> is mentioned in methods such as {@link #addFirst}
|
||||||
|
* and {@link #addLast}, this is with regard to the order in which property
|
||||||
|
* sources will be searched when resolving a given property with a
|
||||||
|
* {@link PropertyResolver}.
|
||||||
|
*
|
||||||
|
* @author Chris Beams
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @see PropertySourcesPropertyResolver
|
||||||
|
* @since 3.1
|
||||||
|
*/
|
||||||
|
public class MutablePropertySources implements PropertySources {
|
||||||
|
|
||||||
|
private final Log logger;
|
||||||
|
|
||||||
|
private final List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<PropertySource<?>>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@link MutablePropertySources}
|
||||||
|
* object.
|
||||||
|
*/
|
||||||
|
public MutablePropertySources(){
|
||||||
|
this.logger = LogFactory.getLog(getClass());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@code MutablePropertySources} from the given propertySources
|
||||||
|
* object, preserving the original order of contained {@code PropertySource}
|
||||||
|
* objects.
|
||||||
|
*/
|
||||||
|
public MutablePropertySources(PropertySources propertySources){
|
||||||
|
this();
|
||||||
|
for (PropertySource<?> propertySource : propertySources) {
|
||||||
|
addLast(propertySource);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@link MutablePropertySources}
|
||||||
|
* object and inherit the given logger, usually from an enclosing
|
||||||
|
* {@link Environment}.
|
||||||
|
*/
|
||||||
|
MutablePropertySources(Log logger){
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean contains(String name) {
|
||||||
|
return this.propertySourceList.contains(PropertySource.named(name));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PropertySource<?> get(String name) {
|
||||||
|
int index = this.propertySourceList.indexOf(PropertySource.named(name));
|
||||||
|
return (index != -1 ? this.propertySourceList.get(index) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Iterator<PropertySource<?>> iterator() {
|
||||||
|
return this.propertySourceList.iterator();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the given property source object with highest precedence.
|
||||||
|
*/
|
||||||
|
public void addFirst(PropertySource<?> propertySource) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Adding PropertySource '" + propertySource.getName() + "' with highest search precedence");
|
||||||
|
}
|
||||||
|
removeIfPresent(propertySource);
|
||||||
|
this.propertySourceList.add(0, propertySource);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the given property source object with lowest precedence.
|
||||||
|
*/
|
||||||
|
public void addLast(PropertySource<?> propertySource) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Adding PropertySource '" + propertySource.getName() + "' with lowest search precedence");
|
||||||
|
}
|
||||||
|
removeIfPresent(propertySource);
|
||||||
|
this.propertySourceList.add(propertySource);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the given property source object with precedence immediately higher than
|
||||||
|
* the named relative property source.
|
||||||
|
*/
|
||||||
|
public void addBefore(String relativePropertySourceName, PropertySource<?> propertySource) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Adding PropertySource '" + propertySource.getName()
|
||||||
|
+ "' with search precedence immediately higher than '" + relativePropertySourceName + "'");
|
||||||
|
}
|
||||||
|
assertLegalRelativeAddition(relativePropertySourceName, propertySource);
|
||||||
|
removeIfPresent(propertySource);
|
||||||
|
int index = assertPresentAndGetIndex(relativePropertySourceName);
|
||||||
|
addAtIndex(index, propertySource);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the given property source object with precedence immediately lower than
|
||||||
|
* the named relative property source.
|
||||||
|
*/
|
||||||
|
public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Adding PropertySource '" + propertySource.getName()
|
||||||
|
+ "' with search precedence immediately lower than '" + relativePropertySourceName + "'");
|
||||||
|
}
|
||||||
|
assertLegalRelativeAddition(relativePropertySourceName, propertySource);
|
||||||
|
removeIfPresent(propertySource);
|
||||||
|
int index = assertPresentAndGetIndex(relativePropertySourceName);
|
||||||
|
addAtIndex(index + 1, propertySource);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the precedence of the given property source, {@code -1} if not found.
|
||||||
|
*/
|
||||||
|
public int precedenceOf(PropertySource<?> propertySource) {
|
||||||
|
return this.propertySourceList.indexOf(propertySource);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove and return the property source with the given name, {@code null} if
|
||||||
|
* not found.
|
||||||
|
*
|
||||||
|
* @param name the name of the property source to find and remove
|
||||||
|
*/
|
||||||
|
public PropertySource<?> remove(String name) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Removing PropertySource '" + name + "'");
|
||||||
|
}
|
||||||
|
int index = this.propertySourceList.indexOf(PropertySource.named(name));
|
||||||
|
return (index != -1 ? this.propertySourceList.remove(index) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace the property source with the given name with the given property
|
||||||
|
* source object.
|
||||||
|
*
|
||||||
|
* @param name the name of the property source to find and replace
|
||||||
|
* @param propertySource the replacement property source
|
||||||
|
* @throws IllegalArgumentException if no property source with the given name is
|
||||||
|
* present
|
||||||
|
* @see #contains
|
||||||
|
*/
|
||||||
|
public void replace(String name, PropertySource<?> propertySource) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Replacing PropertySource '" + name + "' with '" + propertySource.getName() + "'");
|
||||||
|
}
|
||||||
|
int index = assertPresentAndGetIndex(name);
|
||||||
|
this.propertySourceList.set(index, propertySource);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the number of {@link PropertySource} objects contained.
|
||||||
|
*/
|
||||||
|
public int size() {
|
||||||
|
return this.propertySourceList.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.propertySourceList.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure that the given property source is not being added relative to itself.
|
||||||
|
*/
|
||||||
|
protected void assertLegalRelativeAddition(String relativePropertySourceName, PropertySource<?> propertySource) {
|
||||||
|
String newPropertySourceName = propertySource.getName();
|
||||||
|
if (relativePropertySourceName.equals(newPropertySourceName)) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"PropertySource named '" + newPropertySourceName + "' cannot be added relative to itself");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the given property source if it is present.
|
||||||
|
*/
|
||||||
|
protected void removeIfPresent(PropertySource<?> propertySource) {
|
||||||
|
this.propertySourceList.remove(propertySource);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add the given property source at a particular index in the list.
|
||||||
|
*/
|
||||||
|
private void addAtIndex(int index, PropertySource<?> propertySource) {
|
||||||
|
removeIfPresent(propertySource);
|
||||||
|
this.propertySourceList.add(index, propertySource);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Assert that the named property source is present and return its index.
|
||||||
|
*
|
||||||
|
* @param name {@linkplain PropertySource#getName() name of the property source}
|
||||||
|
* to find
|
||||||
|
* @throws IllegalArgumentException if the named property source is not present
|
||||||
|
*/
|
||||||
|
private int assertPresentAndGetIndex(String name) {
|
||||||
|
int index = this.propertySourceList.indexOf(PropertySource.named(name));
|
||||||
|
if (index == -1) {
|
||||||
|
throw new IllegalArgumentException("PropertySource named '" + name + "' does not exist");
|
||||||
|
}
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import org.springframework.core.env.PropertySource;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link PropertySource} implementation that extracts properties from a
|
||||||
|
* {@link Properties} object.
|
||||||
|
* <p>
|
||||||
|
* Note that because a {@code Properties} object is technically an
|
||||||
|
* {@code <Object, Object>} {@link java.util.Hashtable Hashtable}, one may
|
||||||
|
* contain non-{@code String} keys or values. This implementation, however is
|
||||||
|
* restricted to accessing only {@code String}-based keys and values, in the
|
||||||
|
* same fashion as {@link Properties#getProperty} and
|
||||||
|
* {@link Properties#setProperty}.
|
||||||
|
*
|
||||||
|
* @author Chris Beams
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @since 3.1
|
||||||
|
*/
|
||||||
|
public class PropertiesPropertySource extends MapPropertySource {
|
||||||
|
|
||||||
|
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||||
|
public PropertiesPropertySource(String name, Properties source){
|
||||||
|
super(name, (Map) source);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected PropertiesPropertySource(String name, Map<String, Object> source){
|
||||||
|
super(name, source);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
import org.springframework.util.ObjectUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abstract base class representing a source of name/value property pairs. The
|
||||||
|
* underlying {@linkplain #getSource() source object} may be of any type
|
||||||
|
* {@code T} that encapsulates properties. Examples include
|
||||||
|
* {@link java.util.Properties} objects, {@link java.util.Map} objects,
|
||||||
|
* {@code ServletContext} and {@code ServletConfig} objects (for access to init
|
||||||
|
* parameters). Explore the {@code PropertySource} type hierarchy to see
|
||||||
|
* provided implementations.
|
||||||
|
* <p>
|
||||||
|
* {@code PropertySource} objects are not typically used in isolation, but
|
||||||
|
* rather through a {@link PropertySources} object, which aggregates property
|
||||||
|
* sources and in conjunction with a {@link PropertyResolver} implementation
|
||||||
|
* that can perform precedence-based searches across the set of
|
||||||
|
* {@code PropertySources}.
|
||||||
|
* <p>
|
||||||
|
* {@code PropertySource} identity is determined not based on the content of
|
||||||
|
* encapsulated properties, but rather based on the {@link #getName() name} of
|
||||||
|
* the {@code PropertySource} alone. This is useful for manipulating
|
||||||
|
* {@code PropertySource} objects when in collection contexts. See operations in
|
||||||
|
* {@link MutablePropertySources} as well as the {@link #named(String)} and
|
||||||
|
* {@link #toString()} methods for details.
|
||||||
|
* <p>
|
||||||
|
* Note that when working
|
||||||
|
* with @{@link org.springframework.context.annotation.Configuration
|
||||||
|
* Configuration} classes that the @{@link PropertySource PropertySource}
|
||||||
|
* annotation provides a convenient and declarative way of adding property
|
||||||
|
* sources to the enclosing {@code Environment}.
|
||||||
|
*
|
||||||
|
* @author Chris Beams
|
||||||
|
* @since 3.1
|
||||||
|
* @see PropertySources
|
||||||
|
* @see MutablePropertySources
|
||||||
|
* @see PropertySource
|
||||||
|
*/
|
||||||
|
public abstract class PropertySource<T> {
|
||||||
|
|
||||||
|
protected final Log logger = LogFactory.getLog(getClass());
|
||||||
|
|
||||||
|
protected final String name;
|
||||||
|
|
||||||
|
protected final T source;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@code PropertySource} with the given name and source object.
|
||||||
|
*/
|
||||||
|
public PropertySource(String name, T source){
|
||||||
|
Assert.hasText(name, "Property source name must contain at least one character");
|
||||||
|
Assert.notNull(source, "Property source must not be null");
|
||||||
|
this.name = name;
|
||||||
|
this.source = source;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new {@code PropertySource} with the given name and with a new
|
||||||
|
* {@code Object} instance as the underlying source.
|
||||||
|
* <p>
|
||||||
|
* Often useful in testing scenarios when creating anonymous implementations
|
||||||
|
* that never query an actual source but rather return hard-coded values.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public PropertySource(String name){
|
||||||
|
this(name, (T) new Object());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the name of this {@code PropertySource}
|
||||||
|
*/
|
||||||
|
public String getName() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the underlying source object for this {@code PropertySource}.
|
||||||
|
*/
|
||||||
|
public T getSource() {
|
||||||
|
return this.source;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return whether this {@code PropertySource} contains the given name.
|
||||||
|
* <p>
|
||||||
|
* This implementation simply checks for a {@code null} return value from
|
||||||
|
* {@link #getProperty(String)}. Subclasses may wish to implement a more
|
||||||
|
* efficient algorithm if possible.
|
||||||
|
*
|
||||||
|
* @param name the property name to find
|
||||||
|
*/
|
||||||
|
public boolean containsProperty(String name) {
|
||||||
|
return (getProperty(name) != null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the value associated with the given name, or {@code null} if not
|
||||||
|
* found.
|
||||||
|
*
|
||||||
|
* @param name the property to find
|
||||||
|
*/
|
||||||
|
public abstract Object getProperty(String name);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This {@code PropertySource} object is equal to the given object if:
|
||||||
|
* <ul>
|
||||||
|
* <li>they are the same instance
|
||||||
|
* <li>the {@code name} properties for both objects are equal
|
||||||
|
* </ul>
|
||||||
|
* <p>
|
||||||
|
* No properties other than {@code name} are evaluated.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
return (this == obj || (obj instanceof PropertySource
|
||||||
|
&& ObjectUtils.nullSafeEquals(this.name, ((PropertySource<?>) obj).name)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a hash code derived from the {@code name} property of this
|
||||||
|
* {@code PropertySource} object.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return ObjectUtils.nullSafeHashCode(this.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Produce concise output (type and name) if the current log level does not
|
||||||
|
* include debug. If debug is enabled, produce verbose output including the hash
|
||||||
|
* code of the PropertySource instance and every name/value property pair.
|
||||||
|
* <p>
|
||||||
|
* This variable verbosity is useful as a property source such as system
|
||||||
|
* properties or environment variables may contain an arbitrary number of
|
||||||
|
* property pairs, potentially leading to difficult to read exception and log
|
||||||
|
* messages.
|
||||||
|
*
|
||||||
|
* @see Log#isDebugEnabled()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
return getClass().getSimpleName() + "@" + System.identityHashCode(this) + " {name='" + this.name
|
||||||
|
+ "', properties=" + this.source + "}";
|
||||||
|
} else {
|
||||||
|
return getClass().getSimpleName() + " {name='" + this.name + "'}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a {@code PropertySource} implementation intended for collection
|
||||||
|
* comparison purposes only.
|
||||||
|
* <p>
|
||||||
|
* Primarily for internal use, but given a collection of {@code PropertySource}
|
||||||
|
* objects, may be used as follows:
|
||||||
|
*
|
||||||
|
* <pre class="code">
|
||||||
|
*
|
||||||
|
* {
|
||||||
|
* @code
|
||||||
|
* List<PropertySource<?>> sources = new ArrayList<PropertySource<?>>();
|
||||||
|
* sources.add(new MapPropertySource("sourceA", mapA));
|
||||||
|
* sources.add(new MapPropertySource("sourceB", mapB));
|
||||||
|
* assert sources.contains(PropertySource.named("sourceA"));
|
||||||
|
* assert sources.contains(PropertySource.named("sourceB"));
|
||||||
|
* assert !sources.contains(PropertySource.named("sourceC"));
|
||||||
|
* }
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* The returned {@code PropertySource} will throw
|
||||||
|
* {@code UnsupportedOperationException} if any methods other than
|
||||||
|
* {@code equals(Object)}, {@code hashCode()}, and {@code toString()} are
|
||||||
|
* called.
|
||||||
|
*
|
||||||
|
* @param name the name of the comparison {@code PropertySource} to be created
|
||||||
|
* and returned.
|
||||||
|
*/
|
||||||
|
public static PropertySource<?> named(String name) {
|
||||||
|
return new ComparisonPropertySource(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code PropertySource} to be used as a placeholder in cases where an actual
|
||||||
|
* property source cannot be eagerly initialized at application context creation
|
||||||
|
* time. For example, a {@code ServletContext}-based property source must wait
|
||||||
|
* until the {@code ServletContext} object is available to its enclosing
|
||||||
|
* {@code ApplicationContext}. In such cases, a stub should be used to hold the
|
||||||
|
* intended default position/order of the property source, then be replaced
|
||||||
|
* during context refresh.
|
||||||
|
*
|
||||||
|
* @see org.springframework.web.context.support.StandardServletEnvironment
|
||||||
|
* @see org.springframework.web.context.support.ServletContextPropertySource
|
||||||
|
*/
|
||||||
|
public static class StubPropertySource extends PropertySource<Object> {
|
||||||
|
|
||||||
|
public StubPropertySource(String name){
|
||||||
|
super(name, new Object());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Always returns {@code null}.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public String getProperty(String name) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @see PropertySource#named(String)
|
||||||
|
*/
|
||||||
|
static class ComparisonPropertySource extends StubPropertySource {
|
||||||
|
|
||||||
|
private static final String USAGE_ERROR = "ComparisonPropertySource instances are for use with collection comparison only";
|
||||||
|
|
||||||
|
public ComparisonPropertySource(String name){
|
||||||
|
super(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getSource() {
|
||||||
|
throw new UnsupportedOperationException(USAGE_ERROR);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean containsProperty(String name) {
|
||||||
|
throw new UnsupportedOperationException(USAGE_ERROR);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getProperty(String name) {
|
||||||
|
throw new UnsupportedOperationException(USAGE_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.springframework.core.io.support.SpringFactoriesLoader;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strategy interface located via {@link SpringFactoriesLoader} and used to load
|
||||||
|
* a {@link PropertySource}.
|
||||||
|
*
|
||||||
|
* @author Dave Syer
|
||||||
|
* @author Phillip Webb
|
||||||
|
*/
|
||||||
|
public interface PropertySourceLoader {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the file extensions that the loader supports (excluding the '.').
|
||||||
|
*
|
||||||
|
* @return the file extensions
|
||||||
|
*/
|
||||||
|
String[] getFileExtensions();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the resource into a property source.
|
||||||
|
*
|
||||||
|
* @param name the name of the property source
|
||||||
|
* @param resource the resource to load
|
||||||
|
* @param profile the name of the profile to load or {@code null}. The profile
|
||||||
|
* can be used to load multi-document files (such as YAML). Simple property
|
||||||
|
* formats should {@code null} when asked to load a profile.
|
||||||
|
* @return a property source or {@code null}
|
||||||
|
* @throws IOException if the source cannot be loaded
|
||||||
|
*/
|
||||||
|
PropertySource<?> load(String name, Resource resource, String profile) throws IOException;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holder containing one or more {@link PropertySource} objects.
|
||||||
|
*
|
||||||
|
* @author Chris Beams
|
||||||
|
* @since 3.1
|
||||||
|
*/
|
||||||
|
public interface PropertySources extends Iterable<PropertySource<?>> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return whether a property source with the given name is contained.
|
||||||
|
*
|
||||||
|
* @param name the {@linkplain PropertySource#getName() name of the property source} to find
|
||||||
|
*/
|
||||||
|
boolean contains(String name);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the property source with the given name, {@code null} if not found.
|
||||||
|
*
|
||||||
|
* @param name the {@linkplain PropertySource#getName() name of the property source} to find
|
||||||
|
*/
|
||||||
|
PropertySource<?> get(String name);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import org.springframework.core.io.*;
|
||||||
|
import org.springframework.core.io.ByteArrayResource;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for a resource descriptor that abstracts from the actual type of
|
||||||
|
* underlying resource, such as a file or class path resource.
|
||||||
|
* <p>
|
||||||
|
* An InputStream can be opened for every resource if it exists in physical
|
||||||
|
* form, but a URL or File handle can just be returned for certain resources.
|
||||||
|
* The actual behavior is implementation-specific.
|
||||||
|
*
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @since 28.12.2003
|
||||||
|
* @see #getInputStream()
|
||||||
|
* @see #getURL()
|
||||||
|
* @see #getURI()
|
||||||
|
* @see #getFile()
|
||||||
|
* @see WritableResource
|
||||||
|
* @see ContextResource
|
||||||
|
* @see UrlResource
|
||||||
|
* @see ClassPathResource
|
||||||
|
* @see FileSystemResource
|
||||||
|
* @see PathResource
|
||||||
|
* @see ByteArrayResource
|
||||||
|
* @see InputStreamResource
|
||||||
|
*/
|
||||||
|
public interface Resource extends InputStreamSource {
|
||||||
|
|
||||||
|
boolean exists();
|
||||||
|
|
||||||
|
boolean isReadable();
|
||||||
|
|
||||||
|
boolean isOpen();
|
||||||
|
|
||||||
|
URL getURL() throws IOException;
|
||||||
|
|
||||||
|
URI getURI() throws IOException;
|
||||||
|
|
||||||
|
File getFile() throws IOException;
|
||||||
|
|
||||||
|
long contentLength() throws IOException;
|
||||||
|
|
||||||
|
long lastModified() throws IOException;
|
||||||
|
|
||||||
|
org.springframework.core.io.Resource createRelative(String var1) throws IOException;
|
||||||
|
|
||||||
|
String getFilename();
|
||||||
|
|
||||||
|
String getDescription();
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import org.springframework.core.env.Environment;
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link YamlProcessor.DocumentMatcher} backed by
|
||||||
|
* {@link Environment#getActiveProfiles()}. A YAML document may define a
|
||||||
|
* "spring.profiles" element as a comma-separated list of Spring profile names,
|
||||||
|
* optionally negated using the {@code !} character. If both negated and
|
||||||
|
* non-negated profiles are specified for a single document, at least one
|
||||||
|
* non-negated profile must match and no negated profiles may match.
|
||||||
|
*
|
||||||
|
* @author Dave Syer
|
||||||
|
* @author Matt Benson
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @author Andy Wilkinson
|
||||||
|
*/
|
||||||
|
public class SpringProfileDocumentMatcher implements YamlProcessor.DocumentMatcher {
|
||||||
|
|
||||||
|
private String[] activeProfiles = new String[0];
|
||||||
|
|
||||||
|
public SpringProfileDocumentMatcher(){
|
||||||
|
}
|
||||||
|
|
||||||
|
public SpringProfileDocumentMatcher(String... profiles){
|
||||||
|
addActiveProfiles(profiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addActiveProfiles(String... profiles) {
|
||||||
|
LinkedHashSet<String> set = new LinkedHashSet<String>(Arrays.asList(this.activeProfiles));
|
||||||
|
Collections.addAll(set, profiles);
|
||||||
|
this.activeProfiles = set.toArray(new String[set.size()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public YamlProcessor.MatchStatus matches(Properties properties) {
|
||||||
|
List<String> profiles = extractSpringProfiles(properties);
|
||||||
|
ProfilesMatcher profilesMatcher = getProfilesMatcher();
|
||||||
|
Set<String> negative = extractProfiles(profiles, ProfileType.NEGATIVE);
|
||||||
|
Set<String> positive = extractProfiles(profiles, ProfileType.POSITIVE);
|
||||||
|
if (!CollectionUtils.isEmpty(negative)) {
|
||||||
|
if (profilesMatcher.matches(negative) == YamlProcessor.MatchStatus.FOUND) {
|
||||||
|
return YamlProcessor.MatchStatus.NOT_FOUND;
|
||||||
|
}
|
||||||
|
if (CollectionUtils.isEmpty(positive)) {
|
||||||
|
return YamlProcessor.MatchStatus.FOUND;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return profilesMatcher.matches(positive);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> extractSpringProfiles(Properties properties) {
|
||||||
|
SpringProperties springProperties = new SpringProperties();
|
||||||
|
MutablePropertySources propertySources = new MutablePropertySources();
|
||||||
|
propertySources.addFirst(new PropertiesPropertySource("profiles", properties));
|
||||||
|
// PropertyValues propertyValues = new PropertySourcesPropertyValues(
|
||||||
|
// propertySources);
|
||||||
|
// new RelaxedDataBinder(springProperties, "spring").bind(propertyValues);
|
||||||
|
// TODO
|
||||||
|
List<String> profiles = springProperties.getProfiles();
|
||||||
|
return profiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ProfilesMatcher getProfilesMatcher() {
|
||||||
|
return (this.activeProfiles.length != 0 ? new ActiveProfilesMatcher(
|
||||||
|
new HashSet<String>(Arrays.asList(this.activeProfiles))) : new EmptyProfilesMatcher());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<String> extractProfiles(List<String> profiles, ProfileType type) {
|
||||||
|
if (CollectionUtils.isEmpty(profiles)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Set<String> extractedProfiles = new HashSet<String>();
|
||||||
|
for (String candidate : profiles) {
|
||||||
|
ProfileType candidateType = ProfileType.POSITIVE;
|
||||||
|
if (candidate.startsWith("!")) {
|
||||||
|
candidateType = ProfileType.NEGATIVE;
|
||||||
|
}
|
||||||
|
if (candidateType == type) {
|
||||||
|
extractedProfiles.add(type != ProfileType.POSITIVE ? candidate.substring(1) : candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return extractedProfiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Profile match types.
|
||||||
|
*/
|
||||||
|
enum ProfileType {
|
||||||
|
|
||||||
|
POSITIVE, NEGATIVE
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for profile matchers.
|
||||||
|
*/
|
||||||
|
private abstract static class ProfilesMatcher {
|
||||||
|
|
||||||
|
public final YamlProcessor.MatchStatus matches(Set<String> profiles) {
|
||||||
|
if (CollectionUtils.isEmpty(profiles)) {
|
||||||
|
return YamlProcessor.MatchStatus.ABSTAIN;
|
||||||
|
}
|
||||||
|
return doMatches(profiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract YamlProcessor.MatchStatus doMatches(Set<String> profiles);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link ProfilesMatcher} that matches when a value in {@code spring.profiles}
|
||||||
|
* is also in {@code spring.profiles.active}.
|
||||||
|
*/
|
||||||
|
private static class ActiveProfilesMatcher extends ProfilesMatcher {
|
||||||
|
|
||||||
|
private final Set<String> activeProfiles;
|
||||||
|
|
||||||
|
ActiveProfilesMatcher(Set<String> activeProfiles){
|
||||||
|
this.activeProfiles = activeProfiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected YamlProcessor.MatchStatus doMatches(Set<String> profiles) {
|
||||||
|
if (profiles.isEmpty()) {
|
||||||
|
return YamlProcessor.MatchStatus.NOT_FOUND;
|
||||||
|
}
|
||||||
|
for (String activeProfile : this.activeProfiles) {
|
||||||
|
if (profiles.contains(activeProfile)) {
|
||||||
|
return YamlProcessor.MatchStatus.FOUND;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return YamlProcessor.MatchStatus.NOT_FOUND;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link ProfilesMatcher} that matches when {@code
|
||||||
|
* spring.profiles} is empty or contains a value with no text.
|
||||||
|
*
|
||||||
|
* @see StringUtils#hasText(String)
|
||||||
|
*/
|
||||||
|
private static class EmptyProfilesMatcher extends ProfilesMatcher {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public YamlProcessor.MatchStatus doMatches(Set<String> springProfiles) {
|
||||||
|
if (springProfiles.isEmpty()) {
|
||||||
|
return YamlProcessor.MatchStatus.FOUND;
|
||||||
|
}
|
||||||
|
for (String profile : springProfiles) {
|
||||||
|
if (!StringUtils.hasText(profile)) {
|
||||||
|
return YamlProcessor.MatchStatus.FOUND;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return YamlProcessor.MatchStatus.NOT_FOUND;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class for binding {@code spring.profiles} property.
|
||||||
|
*/
|
||||||
|
static class SpringProperties {
|
||||||
|
|
||||||
|
private List<String> profiles = new ArrayList<String>();
|
||||||
|
|
||||||
|
public List<String> getProfiles() {
|
||||||
|
return this.profiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setProfiles(List<String> profiles) {
|
||||||
|
this.profiles = profiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.Reader;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
import org.yaml.snakeyaml.Yaml;
|
||||||
|
import org.yaml.snakeyaml.constructor.Constructor;
|
||||||
|
import org.yaml.snakeyaml.nodes.MappingNode;
|
||||||
|
import org.yaml.snakeyaml.parser.ParserException;
|
||||||
|
import org.yaml.snakeyaml.reader.UnicodeReader;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for YAML factories.
|
||||||
|
*
|
||||||
|
* @author Dave Syer
|
||||||
|
* @author Juergen Hoeller
|
||||||
|
* @since 4.1
|
||||||
|
*/
|
||||||
|
public abstract class YamlProcessor {
|
||||||
|
|
||||||
|
private final Log logger = LogFactory.getLog(getClass());
|
||||||
|
|
||||||
|
private ResolutionMethod resolutionMethod = ResolutionMethod.OVERRIDE;
|
||||||
|
|
||||||
|
private Resource[] resources = new Resource[0];
|
||||||
|
|
||||||
|
private List<DocumentMatcher> documentMatchers = Collections.emptyList();
|
||||||
|
|
||||||
|
private boolean matchDefault = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A map of document matchers allowing callers to selectively use only some of
|
||||||
|
* the documents in a YAML resource. In YAML documents are separated by
|
||||||
|
* <code>---<code> lines, and each document is converted to properties before
|
||||||
|
* the match is made. E.g.
|
||||||
|
*
|
||||||
|
* <pre class="code">
|
||||||
|
* environment: dev
|
||||||
|
* url: http://dev.bar.com
|
||||||
|
* name: Developer Setup
|
||||||
|
* ---
|
||||||
|
* environment: prod
|
||||||
|
* url:http://foo.bar.com
|
||||||
|
* name: My Cool App
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* when mapped with
|
||||||
|
*
|
||||||
|
* <pre class="code">
|
||||||
|
* setDocumentMatchers(properties -> ("prod"
|
||||||
|
* .equals(properties.getProperty("environment")) ? MatchStatus.FOUND : MatchStatus.NOT_FOUND));
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* would end up as
|
||||||
|
*
|
||||||
|
* <pre class="code">
|
||||||
|
* environment=prod
|
||||||
|
* url=http://foo.bar.com
|
||||||
|
* name=My Cool App
|
||||||
|
* </pre>
|
||||||
|
*/
|
||||||
|
public void setDocumentMatchers(DocumentMatcher... matchers) {
|
||||||
|
this.documentMatchers = Arrays.asList(matchers);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flag indicating that a document for which all the
|
||||||
|
* {@link #setDocumentMatchers(DocumentMatcher...) document matchers} abstain
|
||||||
|
* will nevertheless match. Default is {@code true}.
|
||||||
|
*/
|
||||||
|
public void setMatchDefault(boolean matchDefault) {
|
||||||
|
this.matchDefault = matchDefault;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to use for resolving resources. Each resource will be converted to a
|
||||||
|
* Map, so this property is used to decide which map entries to keep in the
|
||||||
|
* final output from this factory. Default is {@link ResolutionMethod#OVERRIDE}.
|
||||||
|
*/
|
||||||
|
public void setResolutionMethod(ResolutionMethod resolutionMethod) {
|
||||||
|
Assert.notNull(resolutionMethod, "ResolutionMethod must not be null");
|
||||||
|
this.resolutionMethod = resolutionMethod;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set locations of YAML {@link Resource resources} to be loaded.
|
||||||
|
*
|
||||||
|
* @see ResolutionMethod
|
||||||
|
*/
|
||||||
|
public void setResources(Resource... resources) {
|
||||||
|
this.resources = resources;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provide an opportunity for subclasses to process the Yaml parsed from the
|
||||||
|
* supplied resources. Each resource is parsed in turn and the documents inside
|
||||||
|
* checked against the {@link #setDocumentMatchers(DocumentMatcher...)
|
||||||
|
* matchers}. If a document matches it is passed into the callback, along with
|
||||||
|
* its representation as Properties. Depending on the
|
||||||
|
* {@link #setResolutionMethod(ResolutionMethod)} not all of the documents will
|
||||||
|
* be parsed.
|
||||||
|
*
|
||||||
|
* @param callback a callback to delegate to once matching documents are found
|
||||||
|
* @see #createYaml()
|
||||||
|
*/
|
||||||
|
protected void process(MatchCallback callback) {
|
||||||
|
Yaml yaml = createYaml();
|
||||||
|
for (Resource resource : this.resources) {
|
||||||
|
boolean found = process(callback, yaml, resource);
|
||||||
|
if (this.resolutionMethod == ResolutionMethod.FIRST_FOUND && found) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create the {@link Yaml} instance to use.
|
||||||
|
*/
|
||||||
|
protected Yaml createYaml() {
|
||||||
|
return new Yaml(new StrictMapAppenderConstructor());
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean process(MatchCallback callback, Yaml yaml, Resource resource) {
|
||||||
|
int count = 0;
|
||||||
|
try {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Loading from YAML: " + resource);
|
||||||
|
}
|
||||||
|
Reader reader = new UnicodeReader(resource.getInputStream());
|
||||||
|
try {
|
||||||
|
for (Object object : yaml.loadAll(reader)) {
|
||||||
|
if (object != null && process(asMap(object), callback)) {
|
||||||
|
count++;
|
||||||
|
if (this.resolutionMethod == ResolutionMethod.FIRST_FOUND) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug(
|
||||||
|
"Loaded " + count + " document" + (count > 1 ? "s" : "") + " from YAML resource: " + resource);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
reader.close();
|
||||||
|
}
|
||||||
|
} catch (IOException ex) {
|
||||||
|
handleProcessError(resource, ex);
|
||||||
|
}
|
||||||
|
return (count > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleProcessError(Resource resource, IOException ex) {
|
||||||
|
if (this.resolutionMethod != ResolutionMethod.FIRST_FOUND
|
||||||
|
&& this.resolutionMethod != ResolutionMethod.OVERRIDE_AND_IGNORE) {
|
||||||
|
throw new IllegalStateException(ex);
|
||||||
|
}
|
||||||
|
if (logger.isWarnEnabled()) {
|
||||||
|
logger.warn("Could not load map from " + resource + ": " + ex.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> asMap(Object object) {
|
||||||
|
// YAML can have numbers as keys
|
||||||
|
Map<String, Object> result = new LinkedHashMap<String, Object>();
|
||||||
|
if (!(object instanceof Map)) {
|
||||||
|
// A document can be a text literal
|
||||||
|
result.put("document", object);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<Object, Object> map = (Map<Object, Object>) object;
|
||||||
|
for (Map.Entry<Object, Object> entry : map.entrySet()) {
|
||||||
|
Object value = entry.getValue();
|
||||||
|
if (value instanceof Map) {
|
||||||
|
value = asMap(value);
|
||||||
|
}
|
||||||
|
Object key = entry.getKey();
|
||||||
|
if (key instanceof CharSequence) {
|
||||||
|
result.put(key.toString(), value);
|
||||||
|
} else {
|
||||||
|
// It has to be a map key in this case
|
||||||
|
result.put("[" + key.toString() + "]", value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean process(Map<String, Object> map, MatchCallback callback) {
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
Properties properties = new Properties() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getProperty(String key) {
|
||||||
|
Object value = get(key);
|
||||||
|
return (value != null ? value.toString() : null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
properties.putAll(getFlattenedMap(map));
|
||||||
|
|
||||||
|
if (this.documentMatchers.isEmpty()) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Merging document (no matchers set): " + map);
|
||||||
|
}
|
||||||
|
callback.process(properties, map);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
MatchStatus result = MatchStatus.ABSTAIN;
|
||||||
|
for (DocumentMatcher matcher : this.documentMatchers) {
|
||||||
|
MatchStatus match = matcher.matches(properties);
|
||||||
|
result = MatchStatus.getMostSpecific(match, result);
|
||||||
|
if (match == MatchStatus.FOUND) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Matched document with document matcher: " + properties);
|
||||||
|
}
|
||||||
|
callback.process(properties, map);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result == MatchStatus.ABSTAIN && this.matchDefault) {
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Matched document with default matcher: " + map);
|
||||||
|
}
|
||||||
|
callback.process(properties, map);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Unmatched document: " + map);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a flattened version of the given map, recursively following any nested
|
||||||
|
* Map or Collection values. Entries from the resulting map retain the same
|
||||||
|
* order as the source. When called with the Map from a {@link MatchCallback}
|
||||||
|
* the result will contain the same values as the {@link MatchCallback}
|
||||||
|
* Properties.
|
||||||
|
*
|
||||||
|
* @param source the source map
|
||||||
|
* @return a flattened map
|
||||||
|
* @since 4.1.3
|
||||||
|
*/
|
||||||
|
protected final Map<String, Object> getFlattenedMap(Map<String, Object> source) {
|
||||||
|
Map<String, Object> result = new LinkedHashMap<String, Object>();
|
||||||
|
buildFlattenedMap(result, source, null);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean containsText(CharSequence str) {
|
||||||
|
int strLen = str.length();
|
||||||
|
for (int i = 0; i < strLen; i++) {
|
||||||
|
if (!Character.isWhitespace(str.charAt(i))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void buildFlattenedMap(Map<String, Object> result, Map<String, Object> source, String path) {
|
||||||
|
for (Map.Entry<String, Object> entry : source.entrySet()) {
|
||||||
|
String key = entry.getKey();
|
||||||
|
if (path != null && !path.isEmpty() && containsText(path)) {
|
||||||
|
if (key.startsWith("[")) {
|
||||||
|
key = path + key;
|
||||||
|
} else {
|
||||||
|
key = path + '.' + key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Object value = entry.getValue();
|
||||||
|
if (value instanceof String) {
|
||||||
|
result.put(key, value);
|
||||||
|
} else if (value instanceof Map) {
|
||||||
|
// Need a compound key
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> map = (Map<String, Object>) value;
|
||||||
|
buildFlattenedMap(result, map, key);
|
||||||
|
} else if (value instanceof Collection) {
|
||||||
|
// Need a compound key
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Collection<Object> collection = (Collection<Object>) value;
|
||||||
|
int count = 0;
|
||||||
|
for (Object object : collection) {
|
||||||
|
buildFlattenedMap(result, Collections.singletonMap("[" + (count++) + "]", object), key);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result.put(key, (value != null ? value : ""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Callback interface used to process the YAML parsing results.
|
||||||
|
*/
|
||||||
|
public interface MatchCallback {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process the given representation of the parsing results.
|
||||||
|
*
|
||||||
|
* @param properties the properties to process (as a flattened representation
|
||||||
|
* with indexed keys in case of a collection or map)
|
||||||
|
* @param map the result map (preserving the original value structure in the
|
||||||
|
* YAML document)
|
||||||
|
*/
|
||||||
|
void process(Properties properties, Map<String, Object> map);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strategy interface used to test if properties match.
|
||||||
|
*/
|
||||||
|
public interface DocumentMatcher {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test if the given properties match.
|
||||||
|
*
|
||||||
|
* @param properties the properties to test
|
||||||
|
* @return the status of the match
|
||||||
|
*/
|
||||||
|
MatchStatus matches(Properties properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Status returned from {@link DocumentMatcher#matches(Properties)}
|
||||||
|
*/
|
||||||
|
public enum MatchStatus {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A match was found.
|
||||||
|
*/
|
||||||
|
FOUND,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* No match was found.
|
||||||
|
*/
|
||||||
|
NOT_FOUND,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The matcher should not be considered.
|
||||||
|
*/
|
||||||
|
ABSTAIN;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compare two {@link MatchStatus} items, returning the most specific status.
|
||||||
|
*/
|
||||||
|
public static MatchStatus getMostSpecific(MatchStatus a, MatchStatus b) {
|
||||||
|
return (a.ordinal() < b.ordinal() ? a : b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to use for resolving resources.
|
||||||
|
*/
|
||||||
|
public enum ResolutionMethod {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace values from earlier in the list.
|
||||||
|
*/
|
||||||
|
OVERRIDE,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace values from earlier in the list, ignoring any failures.
|
||||||
|
*/
|
||||||
|
OVERRIDE_AND_IGNORE,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Take the first resource in the list that exists and use just that.
|
||||||
|
*/
|
||||||
|
FIRST_FOUND
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A specialized {@link Constructor} that checks for duplicate keys.
|
||||||
|
*/
|
||||||
|
protected static class StrictMapAppenderConstructor extends Constructor {
|
||||||
|
|
||||||
|
// Declared as public for use in subclasses
|
||||||
|
public StrictMapAppenderConstructor(){
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Map<Object, Object> constructMapping(MappingNode node) {
|
||||||
|
try {
|
||||||
|
return super.constructMapping(node);
|
||||||
|
} catch (IllegalStateException ex) {
|
||||||
|
throw new ParserException("while parsing MappingNode",
|
||||||
|
node.getStartMark(),
|
||||||
|
ex.getMessage(),
|
||||||
|
node.getEndMark());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Map<Object, Object> createDefaultMap() {
|
||||||
|
final Map<Object, Object> delegate = super.createDefaultMap();
|
||||||
|
return new AbstractMap<Object, Object>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object put(Object key, Object value) {
|
||||||
|
if (delegate.containsKey(key)) {
|
||||||
|
throw new IllegalStateException("Duplicate key: " + key);
|
||||||
|
}
|
||||||
|
return delegate.put(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<Entry<Object, Object>> entrySet() {
|
||||||
|
return delegate.entrySet();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.config.common;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.springframework.util.ClassUtils;
|
||||||
|
import org.yaml.snakeyaml.DumperOptions;
|
||||||
|
import org.yaml.snakeyaml.Yaml;
|
||||||
|
import org.yaml.snakeyaml.nodes.Tag;
|
||||||
|
import org.yaml.snakeyaml.representer.Representer;
|
||||||
|
import org.yaml.snakeyaml.resolver.Resolver;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strategy to load '.yml' (or '.yaml') files into a {@link PropertySource}.
|
||||||
|
*
|
||||||
|
* @author Dave Syer
|
||||||
|
* @author Phillip Webb
|
||||||
|
* @author Andy Wilkinson
|
||||||
|
*/
|
||||||
|
public class YamlPropertySourceLoader implements PropertySourceLoader {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String[] getFileExtensions() {
|
||||||
|
return new String[] { "yml", "yaml" };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {
|
||||||
|
if (ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", null)) {
|
||||||
|
Processor processor = new Processor(resource, profile);
|
||||||
|
Map<String, Object> source = processor.process();
|
||||||
|
if (!source.isEmpty()) {
|
||||||
|
return new MapPropertySource(name, source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link YamlProcessor} to create a {@link Map} containing the property values.
|
||||||
|
* Similar to {@link YamlPropertiesFactoryBean} but retains the order of
|
||||||
|
* entries.
|
||||||
|
*/
|
||||||
|
private static class Processor extends YamlProcessor {
|
||||||
|
|
||||||
|
Processor(Resource resource, String profile){
|
||||||
|
if (profile == null) {
|
||||||
|
setMatchDefault(true);
|
||||||
|
setDocumentMatchers(new SpringProfileDocumentMatcher());
|
||||||
|
} else {
|
||||||
|
setMatchDefault(false);
|
||||||
|
setDocumentMatchers(new SpringProfileDocumentMatcher(profile));
|
||||||
|
}
|
||||||
|
setResources(resource);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Yaml createYaml() {
|
||||||
|
return new Yaml(new StrictMapAppenderConstructor(), new Representer(), new DumperOptions(), new Resolver() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addImplicitResolver(Tag tag, Pattern regexp, String first) {
|
||||||
|
if (tag == Tag.TIMESTAMP) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.addImplicitResolver(tag, regexp, first);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> process() {
|
||||||
|
final Map<String, Object> result = new LinkedHashMap<String, Object>();
|
||||||
|
process(new MatchCallback() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void process(Properties properties, Map<String, Object> map) {
|
||||||
|
result.putAll(getFlattenedMap(map));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@ package com.alibaba.otter.canal.client.adapter.support;
|
|||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 配置信息类
|
* 配置信息类
|
||||||
@@ -28,7 +27,7 @@ public class CanalClientConfig {
|
|||||||
// 重试次数
|
// 重试次数
|
||||||
private Integer retries;
|
private Integer retries;
|
||||||
// 消费超时时间
|
// 消费超时时间
|
||||||
private Long timeout = 500L;
|
private Long timeout;
|
||||||
// 模式 tcp kafka rocketMQ
|
// 模式 tcp kafka rocketMQ
|
||||||
private String mode = "tcp";
|
private String mode = "tcp";
|
||||||
// aliyun ak/sk
|
// aliyun ak/sk
|
||||||
@@ -40,8 +39,6 @@ public class CanalClientConfig {
|
|||||||
// rabbitmq vhost
|
// rabbitmq vhost
|
||||||
private String vhost = "/";
|
private String vhost = "/";
|
||||||
|
|
||||||
private Properties consumerProperties;
|
|
||||||
|
|
||||||
private Long resourceOwnerId;
|
private Long resourceOwnerId;
|
||||||
// 是否启用消息轨迹
|
// 是否启用消息轨迹
|
||||||
private boolean enableMessageTrace;
|
private boolean enableMessageTrace;
|
||||||
@@ -54,8 +51,6 @@ public class CanalClientConfig {
|
|||||||
// canal adapters 配置
|
// canal adapters 配置
|
||||||
private List<CanalAdapter> canalAdapters;
|
private List<CanalAdapter> canalAdapters;
|
||||||
|
|
||||||
private Boolean terminateOnException = false;
|
|
||||||
|
|
||||||
public String getCanalServerHost() {
|
public String getCanalServerHost() {
|
||||||
return canalServerHost;
|
return canalServerHost;
|
||||||
}
|
}
|
||||||
@@ -168,14 +163,6 @@ public class CanalClientConfig {
|
|||||||
this.vhost = vhost;
|
this.vhost = vhost;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Properties getConsumerProperties() {
|
|
||||||
return consumerProperties;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setConsumerProperties(Properties consumerProperties) {
|
|
||||||
this.consumerProperties = consumerProperties;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getResourceOwnerId() {
|
public Long getResourceOwnerId() {
|
||||||
return resourceOwnerId;
|
return resourceOwnerId;
|
||||||
}
|
}
|
||||||
@@ -224,14 +211,6 @@ public class CanalClientConfig {
|
|||||||
this.namespace = namespace;
|
this.namespace = namespace;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Boolean getTerminateOnException() {
|
|
||||||
return terminateOnException;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTerminateOnException(Boolean terminateOnException) {
|
|
||||||
this.terminateOnException = terminateOnException;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class CanalAdapter {
|
public static class CanalAdapter {
|
||||||
|
|
||||||
private String instance; // 实例名
|
private String instance; // 实例名
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import java.io.InputStreamReader;
|
|||||||
import java.net.MalformedURLException;
|
import java.net.MalformedURLException;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.net.URLClassLoader;
|
import java.net.URLClassLoader;
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
@@ -260,7 +259,7 @@ public class ExtensionLoader<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Class<?>> extensionClasses = new HashMap<>();
|
Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
|
||||||
|
|
||||||
// 1. plugin folder,customized extension classLoader (jar_dir/plugin)
|
// 1. plugin folder,customized extension classLoader (jar_dir/plugin)
|
||||||
String dir = File.separator + this.getJarDirectoryPath() + File.separator + "plugin";
|
String dir = File.separator + this.getJarDirectoryPath() + File.separator + "plugin";
|
||||||
@@ -318,8 +317,10 @@ public class ExtensionLoader<T> {
|
|||||||
while (urls.hasMoreElements()) {
|
while (urls.hasMoreElements()) {
|
||||||
URL url = urls.nextElement();
|
URL url = urls.nextElement();
|
||||||
try {
|
try {
|
||||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
|
BufferedReader reader = null;
|
||||||
String line;
|
try {
|
||||||
|
reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
|
||||||
|
String line = null;
|
||||||
while ((line = reader.readLine()) != null) {
|
while ((line = reader.readLine()) != null) {
|
||||||
final int ci = line.indexOf('#');
|
final int ci = line.indexOf('#');
|
||||||
if (ci >= 0) line = line.substring(0, ci);
|
if (ci >= 0) line = line.substring(0, ci);
|
||||||
@@ -381,6 +382,10 @@ public class ExtensionLoader<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} // end of while read lines
|
} // end of while read lines
|
||||||
|
} finally {
|
||||||
|
if (reader != null) {
|
||||||
|
reader.close();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
logger.error("Exception when load extension class(interface: " + type + ", class file: " + url
|
logger.error("Exception when load extension class(interface: " + type + ", class file: " + url
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.support;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Created by @author zhuchao on @date 2021/11/11.
|
|
||||||
*/
|
|
||||||
public class FileName2KeyMapping {
|
|
||||||
|
|
||||||
private static Map<String, String> MAP = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
public static void register(String type, String fileName, String key) {
|
|
||||||
MAP.putIfAbsent(join(type, fileName), key);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void unregister(String type, String fileName) {
|
|
||||||
MAP.remove(join(type, fileName));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String getKey(String type, String fileName) {
|
|
||||||
return MAP.get(join(type, fileName));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String join(String type, String fileName) {
|
|
||||||
return type + "|" + fileName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -55,7 +55,7 @@ public class MappingConfigsLoader {
|
|||||||
}
|
}
|
||||||
if (filePath.exists()) {
|
if (filePath.exists()) {
|
||||||
String fileName = filePath.getName();
|
String fileName = filePath.getName();
|
||||||
if (!(fileName.endsWith(".yml") || fileName.endsWith(".yaml"))) {
|
if (!fileName.endsWith(".yml")) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
try (InputStream in = new FileInputStream(filePath)) {
|
try (InputStream in = new FileInputStream(filePath)) {
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ package com.alibaba.otter.canal.client.adapter.support;
|
|||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.connector.core.consumer.CommonMessage;
|
|
||||||
import com.alibaba.otter.canal.protocol.CanalEntry;
|
import com.alibaba.otter.canal.protocol.CanalEntry;
|
||||||
|
import com.alibaba.otter.canal.protocol.FlatMessage;
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -19,7 +19,7 @@ public class MessageUtil {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
List<CanalEntry.Entry> entries = message.getEntries();
|
List<CanalEntry.Entry> entries = message.getEntries();
|
||||||
List<Dml> dmls = new ArrayList<>(entries.size());
|
List<Dml> dmls = new ArrayList<Dml>(entries.size());
|
||||||
for (CanalEntry.Entry entry : entries) {
|
for (CanalEntry.Entry entry : entries) {
|
||||||
if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN
|
if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN
|
||||||
|| entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
|
|| entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
|
||||||
@@ -131,13 +131,10 @@ public class MessageUtil {
|
|||||||
return dmls;
|
return dmls;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<Dml> flatMessage2Dml(String destination, String groupId, List<CommonMessage> commonMessages) {
|
public static List<Dml> flatMessage2Dml(String destination, String groupId, List<FlatMessage> flatMessages) {
|
||||||
if (commonMessages == null) {
|
List<Dml> dmls = new ArrayList<Dml>(flatMessages.size());
|
||||||
return new ArrayList<>();
|
for (FlatMessage flatMessage : flatMessages) {
|
||||||
}
|
Dml dml = flatMessage2Dml(destination, groupId, flatMessage);
|
||||||
List<Dml> dmls = new ArrayList<>(commonMessages.size());
|
|
||||||
for (CommonMessage commonMessage : commonMessages) {
|
|
||||||
Dml dml = flatMessage2Dml(destination, groupId, commonMessage);
|
|
||||||
if (dml != null) {
|
if (dml != null) {
|
||||||
dmls.add(dml);
|
dmls.add(dml);
|
||||||
}
|
}
|
||||||
@@ -146,31 +143,31 @@ public class MessageUtil {
|
|||||||
return dmls;
|
return dmls;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Dml flatMessage2Dml(String destination, String groupId, CommonMessage commonMessage) {
|
public static Dml flatMessage2Dml(String destination, String groupId, FlatMessage flatMessage) {
|
||||||
if (commonMessage == null) {
|
if (flatMessage == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
Dml dml = new Dml();
|
Dml dml = new Dml();
|
||||||
dml.setDestination(destination);
|
dml.setDestination(destination);
|
||||||
dml.setGroupId(groupId);
|
dml.setGroupId(groupId);
|
||||||
dml.setDatabase(commonMessage.getDatabase());
|
dml.setDatabase(flatMessage.getDatabase());
|
||||||
dml.setTable(commonMessage.getTable());
|
dml.setTable(flatMessage.getTable());
|
||||||
dml.setPkNames(commonMessage.getPkNames());
|
dml.setPkNames(flatMessage.getPkNames());
|
||||||
dml.setIsDdl(commonMessage.getIsDdl());
|
dml.setIsDdl(flatMessage.getIsDdl());
|
||||||
dml.setType(commonMessage.getType());
|
dml.setType(flatMessage.getType());
|
||||||
dml.setTs(commonMessage.getTs());
|
dml.setTs(flatMessage.getTs());
|
||||||
dml.setEs(commonMessage.getEs());
|
dml.setEs(flatMessage.getEs());
|
||||||
dml.setSql(commonMessage.getSql());
|
dml.setSql(flatMessage.getSql());
|
||||||
// if (flatMessage.getSqlType() == null || flatMessage.getMysqlType() == null) {
|
// if (flatMessage.getSqlType() == null || flatMessage.getMysqlType() == null) {
|
||||||
// throw new RuntimeException("SqlType or mysqlType is null");
|
// throw new RuntimeException("SqlType or mysqlType is null");
|
||||||
// }
|
// }
|
||||||
List<Map<String, Object>> data = commonMessage.getData();
|
List<Map<String, String>> data = flatMessage.getData();
|
||||||
if (data != null) {
|
if (data != null) {
|
||||||
dml.setData(data);
|
dml.setData(changeRows(dml.getTable(), data, flatMessage.getSqlType(), flatMessage.getMysqlType()));
|
||||||
}
|
}
|
||||||
List<Map<String, Object>> old = commonMessage.getOld();
|
List<Map<String, String>> old = flatMessage.getOld();
|
||||||
if (old != null) {
|
if (old != null) {
|
||||||
dml.setOld(old);
|
dml.setOld(changeRows(dml.getTable(), old, flatMessage.getSqlType(), flatMessage.getMysqlType()));
|
||||||
}
|
}
|
||||||
return dml;
|
return dml;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,7 @@ import java.util.Enumeration;
|
|||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
|
|
||||||
public class URLClassExtensionLoader extends URLClassLoader {
|
public class URLClassExtensionLoader extends URLClassLoader {
|
||||||
|
public URLClassExtensionLoader(URL[] urls) {
|
||||||
public URLClassExtensionLoader(URL[] urls){
|
|
||||||
super(urls);
|
super(urls);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -19,11 +18,9 @@ public class URLClassExtensionLoader extends URLClassLoader {
|
|||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (name.startsWith("java.") || name.startsWith("org.slf4j.") || name.startsWith("org.apache.logging")
|
if (name.startsWith("java.") || name.startsWith("org.slf4j.")
|
||||||
|| name.startsWith("org.apache.zookeeper.") || name.startsWith("org.I0Itec.zkclient.")
|
|| name.startsWith("org.apache.logging")
|
||||||
|| name.startsWith("org.apache.commons.logging.")
|
|| name.startsWith("org.apache.commons.logging.")) {
|
||||||
|| name.startsWith("com.alibaba.druid")
|
|
||||||
) {
|
|
||||||
// || name.startsWith("org.apache.hadoop."))
|
// || name.startsWith("org.apache.hadoop."))
|
||||||
// {
|
// {
|
||||||
c = super.loadClass(name);
|
c = super.loadClass(name);
|
||||||
|
|||||||
@@ -30,8 +30,6 @@ public class Util {
|
|||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(Util.class);
|
private static final Logger logger = LoggerFactory.getLogger(Util.class);
|
||||||
|
|
||||||
public static final String AUTO_GENERATED_PREFIX = "AUTO_GENERATED_";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 通过DS执行sql
|
* 通过DS执行sql
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.support;
|
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
|
||||||
import org.springframework.boot.context.properties.bind.Bindable;
|
|
||||||
import org.springframework.boot.context.properties.bind.Binder;
|
|
||||||
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
|
|
||||||
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
|
|
||||||
import org.springframework.boot.env.YamlPropertySourceLoader;
|
|
||||||
import org.springframework.boot.origin.OriginTrackedValue;
|
|
||||||
import org.springframework.core.env.PropertySource;
|
|
||||||
import org.springframework.core.io.ByteArrayResource;
|
|
||||||
import org.springframework.core.io.ClassPathResource;
|
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
|
|
||||||
public class YamlUtils {
|
|
||||||
|
|
||||||
public static <T> T resourceYmlToObj(String resource, String prefix, Class<T> clazz) {
|
|
||||||
ClassPathResource classPathResource = new ClassPathResource(resource);
|
|
||||||
|
|
||||||
String content;
|
|
||||||
try (InputStream inputStream = classPathResource.getInputStream()) {
|
|
||||||
|
|
||||||
ByteArrayOutputStream result = new ByteArrayOutputStream();
|
|
||||||
byte[] buffer = new byte[1024];
|
|
||||||
int length;
|
|
||||||
while ((length = inputStream.read(buffer)) != -1) {
|
|
||||||
result.write(buffer, 0, length);
|
|
||||||
}
|
|
||||||
content = result.toString("UTF-8");
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
return ymlToObj(prefix, content, clazz);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static <T> T ymlToObj(String content, Class<T> clazz) {
|
|
||||||
return ymlToObj("", content, clazz, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static <T> T ymlToObj(String prefix, String content, Class<T> clazz) {
|
|
||||||
return ymlToObj(prefix, content, clazz, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static <T> T ymlToObj(String prefix, String content, Class<T> clazz, String charset) {
|
|
||||||
return ymlToObj(prefix, content, clazz, charset, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static <T> T ymlToObj(String prefix, String content, Class<T> clazz, String charset,
|
|
||||||
Properties baseProperties) {
|
|
||||||
try {
|
|
||||||
prefix = StringUtils.trimToEmpty(prefix);
|
|
||||||
byte[] contentBytes;
|
|
||||||
if (charset == null) {
|
|
||||||
contentBytes = content.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} else {
|
|
||||||
contentBytes = content.getBytes(charset);
|
|
||||||
}
|
|
||||||
YamlPropertySourceLoader propertySourceLoader = new YamlPropertySourceLoader();
|
|
||||||
Resource configResource = new ByteArrayResource(contentBytes);
|
|
||||||
List<PropertySource<?>> propertySources = propertySourceLoader.load("manualBindConfig", configResource);
|
|
||||||
|
|
||||||
if (propertySources == null || propertySources.isEmpty()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
PropertySource<?> propertySource = propertySources.get(0);
|
|
||||||
|
|
||||||
Properties properties = new Properties();
|
|
||||||
|
|
||||||
properties.putAll((Map<?, ?>) propertySource.getSource());
|
|
||||||
|
|
||||||
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
|
|
||||||
Object value = entry.getValue();
|
|
||||||
if (value instanceof OriginTrackedValue) {
|
|
||||||
entry.setValue(((OriginTrackedValue) value).getValue());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (baseProperties != null) {
|
|
||||||
baseProperties.putAll(properties);
|
|
||||||
properties = baseProperties;
|
|
||||||
}
|
|
||||||
|
|
||||||
ConfigurationPropertySource sources = new MapConfigurationPropertySource(properties);
|
|
||||||
Binder binder = new Binder(sources);
|
|
||||||
return binder.bind(prefix, Bindable.of(clazz)).get();
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,24 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.support;
|
package com.alibaba.otter.canal.client.adapter.support;
|
||||||
|
|
||||||
|
import static org.mockito.AdditionalMatchers.or;
|
||||||
|
import static org.mockito.Matchers.isA;
|
||||||
|
import static org.mockito.Matchers.isNull;
|
||||||
|
import static org.powermock.api.mockito.PowerMockito.mockStatic;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.JdbcTypeUtil;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.Util;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Rule;
|
import org.junit.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.rules.ExpectedException;
|
import org.junit.rules.ExpectedException;
|
||||||
import org.junit.rules.Timeout;
|
import org.junit.rules.Timeout;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
|
import org.powermock.api.mockito.PowerMockito;
|
||||||
|
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||||
import org.powermock.modules.junit4.PowerMockRunner;
|
import org.powermock.modules.junit4.PowerMockRunner;
|
||||||
|
|
||||||
|
import java.lang.reflect.Array;
|
||||||
|
|
||||||
@RunWith(PowerMockRunner.class)
|
@RunWith(PowerMockRunner.class)
|
||||||
public class JdbcTypeUtilTest {
|
public class JdbcTypeUtilTest {
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package com.alibaba.otter.canal.client.adapter.support;
|
|||||||
import static org.mockito.AdditionalMatchers.or;
|
import static org.mockito.AdditionalMatchers.or;
|
||||||
import static org.mockito.Matchers.isA;
|
import static org.mockito.Matchers.isA;
|
||||||
import static org.mockito.Matchers.isNull;
|
import static org.mockito.Matchers.isNull;
|
||||||
|
import static org.powermock.api.mockito.PowerMockito.mockStatic;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.Util;
|
||||||
import com.diffblue.deeptestutils.mock.DTUMemberMatcher;
|
import com.diffblue.deeptestutils.mock.DTUMemberMatcher;
|
||||||
import org.apache.commons.lang.StringUtils;
|
import org.apache.commons.lang.StringUtils;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
|
|||||||
@@ -1,229 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.support;
|
|
||||||
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class YamlUtilsTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testLoadConfigToYml() {
|
|
||||||
String configStr="dataSourceKey: defaultDS\n"
|
|
||||||
+ "destination: example\n"
|
|
||||||
+ "groupId: g1\n"
|
|
||||||
+ "outerAdapterKey: mysql1\n"
|
|
||||||
+ "concurrent: true\n"
|
|
||||||
+ "dbMapping:\n"
|
|
||||||
+ " database: mytest\n"
|
|
||||||
+ " table: user\n"
|
|
||||||
+ " targetTable: mytest2.user\n"
|
|
||||||
+ " targetPk:\n"
|
|
||||||
+ " id: id\n"
|
|
||||||
+ "# mapAll: true\n"
|
|
||||||
+ " targetColumns:\n"
|
|
||||||
+ " id:\n"
|
|
||||||
+ " name:\n"
|
|
||||||
+ " role_id:\n"
|
|
||||||
+ " c_time:\n"
|
|
||||||
+ " test1:\n"
|
|
||||||
+ " etlCondition: \"where c_time>={}\"\n"
|
|
||||||
+ " commitBatch: 3000 # 批量提交的大小";
|
|
||||||
|
|
||||||
MappingConfig config = YamlUtils.ymlToObj(null, configStr, MappingConfig.class, null, new Properties());
|
|
||||||
|
|
||||||
Assert.assertNotNull(config);
|
|
||||||
Assert.assertEquals(config.getDestination(), "example");
|
|
||||||
Assert.assertEquals(config.getOuterAdapterKey(), "mysql1");
|
|
||||||
Assert.assertEquals(config.getDbMapping().getDatabase(), "mytest");
|
|
||||||
Assert.assertEquals(config.getDbMapping().getTargetColumns().size(), 5);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static class MappingConfig {
|
|
||||||
private String dataSourceKey;
|
|
||||||
|
|
||||||
private String destination;
|
|
||||||
|
|
||||||
private String groupId;
|
|
||||||
|
|
||||||
private String outerAdapterKey;
|
|
||||||
|
|
||||||
private boolean concurrent = false;
|
|
||||||
|
|
||||||
private DbMapping dbMapping;
|
|
||||||
|
|
||||||
public String getDataSourceKey() {
|
|
||||||
return dataSourceKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDataSourceKey(String dataSourceKey) {
|
|
||||||
this.dataSourceKey = dataSourceKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDestination() {
|
|
||||||
return destination;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDestination(String destination) {
|
|
||||||
this.destination = destination;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getGroupId() {
|
|
||||||
return groupId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setGroupId(String groupId) {
|
|
||||||
this.groupId = groupId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getOuterAdapterKey() {
|
|
||||||
return outerAdapterKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setOuterAdapterKey(String outerAdapterKey) {
|
|
||||||
this.outerAdapterKey = outerAdapterKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isConcurrent() {
|
|
||||||
return concurrent;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setConcurrent(boolean concurrent) {
|
|
||||||
this.concurrent = concurrent;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DbMapping getDbMapping() {
|
|
||||||
return dbMapping;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDbMapping(DbMapping dbMapping) {
|
|
||||||
this.dbMapping = dbMapping;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static class DbMapping {
|
|
||||||
private boolean mirrorDb = false; // 是否镜像库
|
|
||||||
private String database; // 数据库名或schema名
|
|
||||||
private String table; // 表名
|
|
||||||
private Map<String, String> targetPk = new LinkedHashMap<>(); // 目标表主键字段
|
|
||||||
private boolean mapAll = false; // 映射所有字段
|
|
||||||
private String targetDb; // 目标库名
|
|
||||||
private String targetTable; // 目标表名
|
|
||||||
private Map<String, String> targetColumns; // 目标表字段映射
|
|
||||||
|
|
||||||
private boolean caseInsensitive = false; // 目标表不区分大小写,默认是否
|
|
||||||
|
|
||||||
private String etlCondition; // etl条件sql
|
|
||||||
|
|
||||||
private int readBatch = 5000;
|
|
||||||
private int commitBatch = 5000; // etl等批量提交大小
|
|
||||||
|
|
||||||
private Map<String, String> allMapColumns;
|
|
||||||
|
|
||||||
public boolean isMirrorDb() {
|
|
||||||
return mirrorDb;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMirrorDb(boolean mirrorDb) {
|
|
||||||
this.mirrorDb = mirrorDb;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDatabase() {
|
|
||||||
return database;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDatabase(String database) {
|
|
||||||
this.database = database;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTable() {
|
|
||||||
return table;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTable(String table) {
|
|
||||||
this.table = table;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getTargetPk() {
|
|
||||||
return targetPk;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTargetPk(Map<String, String> targetPk) {
|
|
||||||
this.targetPk = targetPk;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isMapAll() {
|
|
||||||
return mapAll;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMapAll(boolean mapAll) {
|
|
||||||
this.mapAll = mapAll;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTargetDb() {
|
|
||||||
return targetDb;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTargetDb(String targetDb) {
|
|
||||||
this.targetDb = targetDb;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTargetTable() {
|
|
||||||
return targetTable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTargetTable(String targetTable) {
|
|
||||||
this.targetTable = targetTable;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getTargetColumns() {
|
|
||||||
return targetColumns;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTargetColumns(Map<String, String> targetColumns) {
|
|
||||||
this.targetColumns = targetColumns;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isCaseInsensitive() {
|
|
||||||
return caseInsensitive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCaseInsensitive(boolean caseInsensitive) {
|
|
||||||
this.caseInsensitive = caseInsensitive;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEtlCondition() {
|
|
||||||
return etlCondition;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setEtlCondition(String etlCondition) {
|
|
||||||
this.etlCondition = etlCondition;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getReadBatch() {
|
|
||||||
return readBatch;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setReadBatch(int readBatch) {
|
|
||||||
this.readBatch = readBatch;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getCommitBatch() {
|
|
||||||
return commitBatch;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCommitBatch(int commitBatch) {
|
|
||||||
this.commitBatch = commitBatch;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getAllMapColumns() {
|
|
||||||
return allMapColumns;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAllMapColumns(Map<String, String> allMapColumns) {
|
|
||||||
this.allMapColumns = allMapColumns;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.client-adapter</artifactId>
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.7-SNAPSHOT</version>
|
<version>1.1.5-SNAPSHOT</version>
|
||||||
<relativePath>../pom.xml</relativePath>
|
<relativePath>../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
@@ -27,22 +29,22 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.elasticsearch</groupId>
|
<groupId>org.elasticsearch</groupId>
|
||||||
<artifactId>elasticsearch</artifactId>
|
<artifactId>elasticsearch</artifactId>
|
||||||
<version>6.8.22</version>
|
<version>6.4.3</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.elasticsearch.client</groupId>
|
<groupId>org.elasticsearch.client</groupId>
|
||||||
<artifactId>transport</artifactId>
|
<artifactId>transport</artifactId>
|
||||||
<version>6.8.22</version>
|
<version>6.4.3</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.elasticsearch.client</groupId>
|
<groupId>org.elasticsearch.client</groupId>
|
||||||
<artifactId>elasticsearch-rest-client</artifactId>
|
<artifactId>elasticsearch-rest-client</artifactId>
|
||||||
<version>6.8.22</version>
|
<version>6.4.3</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.elasticsearch.client</groupId>
|
<groupId>org.elasticsearch.client</groupId>
|
||||||
<artifactId>elasticsearch-rest-high-level-client</artifactId>
|
<artifactId>elasticsearch-rest-high-level-client</artifactId>
|
||||||
<version>6.8.22</version>
|
<version>6.4.3</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|||||||
@@ -5,10 +5,6 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
|
||||||
|
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.ESAdapter;
|
import com.alibaba.otter.canal.client.adapter.es.core.ESAdapter;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.es6x.etl.ESEtlService;
|
import com.alibaba.otter.canal.client.adapter.es6x.etl.ESEtlService;
|
||||||
@@ -18,6 +14,9 @@ import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
|
|||||||
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
||||||
|
import org.elasticsearch.action.search.SearchResponse;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ES 6.x 外部适配器
|
* ES 6.x 外部适配器
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import java.util.concurrent.atomic.AtomicLong;
|
|||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
import org.apache.commons.lang.StringUtils;
|
||||||
|
import org.elasticsearch.action.bulk.BulkResponse;
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
import org.elasticsearch.action.search.SearchResponse;
|
||||||
import org.elasticsearch.index.query.QueryBuilders;
|
import org.elasticsearch.index.query.QueryBuilders;
|
||||||
import org.elasticsearch.search.SearchHit;
|
import org.elasticsearch.search.SearchHit;
|
||||||
@@ -117,7 +118,8 @@ public class ESEtlService extends AbstractEtlService {
|
|||||||
if (idVal != null) {
|
if (idVal != null) {
|
||||||
String parentVal = (String) esFieldData.remove("$parent_routing");
|
String parentVal = (String) esFieldData.remove("$parent_routing");
|
||||||
if (mapping.isUpsert()) {
|
if (mapping.isUpsert()) {
|
||||||
ESUpdateRequest esUpdateRequest = this.esConnection.new ES6xUpdateRequest(mapping.get_index(),
|
ESUpdateRequest esUpdateRequest = this.esConnection.new ES6xUpdateRequest(
|
||||||
|
mapping.get_index(),
|
||||||
mapping.get_type(),
|
mapping.get_type(),
|
||||||
idVal.toString()).setDoc(esFieldData).setDocAsUpsert(true);
|
idVal.toString()).setDoc(esFieldData).setDocAsUpsert(true);
|
||||||
|
|
||||||
@@ -127,9 +129,8 @@ public class ESEtlService extends AbstractEtlService {
|
|||||||
|
|
||||||
esBulkRequest.add(esUpdateRequest);
|
esBulkRequest.add(esUpdateRequest);
|
||||||
} else {
|
} else {
|
||||||
ESIndexRequest esIndexRequest = this.esConnection.new ES6xIndexRequest(mapping.get_index(),
|
ESIndexRequest esIndexRequest = this.esConnection.new ES6xIndexRequest(mapping
|
||||||
mapping.get_type(),
|
.get_index(), mapping.get_type(), idVal.toString()).setSource(esFieldData);
|
||||||
idVal.toString()).setSource(esFieldData);
|
|
||||||
if (StringUtils.isNotEmpty(parentVal)) {
|
if (StringUtils.isNotEmpty(parentVal)) {
|
||||||
esIndexRequest.setRouting(parentVal);
|
esIndexRequest.setRouting(parentVal);
|
||||||
}
|
}
|
||||||
@@ -138,17 +139,18 @@ public class ESEtlService extends AbstractEtlService {
|
|||||||
} else {
|
} else {
|
||||||
idVal = esFieldData.get(mapping.getPk());
|
idVal = esFieldData.get(mapping.getPk());
|
||||||
ESSearchRequest esSearchRequest = this.esConnection.new ESSearchRequest(mapping.get_index(),
|
ESSearchRequest esSearchRequest = this.esConnection.new ESSearchRequest(mapping.get_index(),
|
||||||
mapping.get_type()).setQuery(QueryBuilders.termQuery(mapping.getPk(), idVal)).size(10000);
|
mapping.get_type()).setQuery(QueryBuilders.termQuery(mapping.getPk(), idVal))
|
||||||
|
.size(10000);
|
||||||
SearchResponse response = esSearchRequest.getResponse();
|
SearchResponse response = esSearchRequest.getResponse();
|
||||||
for (SearchHit hit : response.getHits()) {
|
for (SearchHit hit : response.getHits()) {
|
||||||
ESUpdateRequest esUpdateRequest = this.esConnection.new ES6xUpdateRequest(mapping.get_index(),
|
ESUpdateRequest esUpdateRequest = this.esConnection.new ES6xUpdateRequest(mapping
|
||||||
mapping.get_type(),
|
.get_index(), mapping.get_type(), hit.getId()).setDoc(esFieldData);
|
||||||
hit.getId()).setDoc(esFieldData);
|
|
||||||
esBulkRequest.add(esUpdateRequest);
|
esBulkRequest.add(esUpdateRequest);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (esBulkRequest.numberOfActions() % mapping.getCommitBatch() == 0 && esBulkRequest.numberOfActions() > 0) {
|
if (esBulkRequest.numberOfActions() % mapping.getCommitBatch() == 0
|
||||||
|
&& esBulkRequest.numberOfActions() > 0) {
|
||||||
long esBatchBegin = System.currentTimeMillis();
|
long esBatchBegin = System.currentTimeMillis();
|
||||||
ESBulkResponse rp = esBulkRequest.bulk();
|
ESBulkResponse rp = esBulkRequest.bulk();
|
||||||
if (rp.hasFailures()) {
|
if (rp.hasFailures()) {
|
||||||
@@ -189,7 +191,7 @@ public class ESEtlService extends AbstractEtlService {
|
|||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
return count;
|
return count;
|
||||||
} );
|
});
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|||||||
@@ -2,11 +2,7 @@ package com.alibaba.otter.canal.client.adapter.es6x.support;
|
|||||||
|
|
||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.ConcurrentMap;
|
import java.util.concurrent.ConcurrentMap;
|
||||||
|
|
||||||
@@ -24,8 +20,8 @@ import org.slf4j.LoggerFactory;
|
|||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig.ESMapping;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig.ESMapping;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.ColumnItem;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.FieldItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.FieldItem;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.ColumnItem;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.support.ESBulkRequest;
|
import com.alibaba.otter.canal.client.adapter.es.core.support.ESBulkRequest;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.support.ESBulkRequest.ESBulkResponse;
|
import com.alibaba.otter.canal.client.adapter.es.core.support.ESBulkRequest.ESBulkResponse;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.support.ESBulkRequest.ESDeleteRequest;
|
import com.alibaba.otter.canal.client.adapter.es.core.support.ESBulkRequest.ESDeleteRequest;
|
||||||
@@ -316,17 +312,13 @@ public class ES6xTemplate implements ESTemplate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object getESDataFromDmlData(ESSyncConfig.ESMapping mapping,String owner, Map<String, Object> dmlData,
|
public Object getESDataFromDmlData(ESSyncConfig.ESMapping mapping, Map<String, Object> dmlData,
|
||||||
Map<String, Object> dmlOld, Map<String, Object> esFieldData) {
|
Map<String, Object> dmlOld, Map<String, Object> esFieldData) {
|
||||||
SchemaItem schemaItem = mapping.getSchemaItem();
|
SchemaItem schemaItem = mapping.getSchemaItem();
|
||||||
String idFieldName = mapping.get_id() == null ? mapping.getPk() : mapping.get_id();
|
String idFieldName = mapping.get_id() == null ? mapping.getPk() : mapping.get_id();
|
||||||
Object resultIdVal = null;
|
Object resultIdVal = null;
|
||||||
for (FieldItem fieldItem : schemaItem.getSelectFields().values()) {
|
for (FieldItem fieldItem : schemaItem.getSelectFields().values()) {
|
||||||
ColumnItem columnItem = fieldItem.getColumnItems().iterator().next();
|
String columnName = fieldItem.getColumnItems().iterator().next().getColumnName();
|
||||||
if (!columnItem.getOwner().equals(owner)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String columnName = columnItem.getColumnName();
|
|
||||||
|
|
||||||
if (fieldItem.getFieldName().equals(idFieldName)) {
|
if (fieldItem.getFieldName().equals(idFieldName)) {
|
||||||
resultIdVal = getValFromData(mapping, dmlData, fieldItem.getFieldName(), columnName);
|
resultIdVal = getValFromData(mapping, dmlData, fieldItem.getFieldName(), columnName);
|
||||||
|
|||||||
@@ -2,12 +2,10 @@ package com.alibaba.otter.canal.client.adapter.es6x.support;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URISyntaxException;
|
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.es.core.support.ESBulkRequest;
|
||||||
import org.apache.commons.lang.StringUtils;
|
import org.apache.commons.lang.StringUtils;
|
||||||
import org.apache.http.HttpHost;
|
import org.apache.http.HttpHost;
|
||||||
import org.apache.http.auth.AuthScope;
|
import org.apache.http.auth.AuthScope;
|
||||||
@@ -29,11 +27,7 @@ import org.elasticsearch.action.search.SearchRequestBuilder;
|
|||||||
import org.elasticsearch.action.search.SearchResponse;
|
import org.elasticsearch.action.search.SearchResponse;
|
||||||
import org.elasticsearch.action.update.UpdateRequest;
|
import org.elasticsearch.action.update.UpdateRequest;
|
||||||
import org.elasticsearch.action.update.UpdateRequestBuilder;
|
import org.elasticsearch.action.update.UpdateRequestBuilder;
|
||||||
import org.elasticsearch.client.RequestOptions;
|
import org.elasticsearch.client.*;
|
||||||
import org.elasticsearch.client.RestClient;
|
|
||||||
import org.elasticsearch.client.RestClientBuilder;
|
|
||||||
import org.elasticsearch.client.RestHighLevelClient;
|
|
||||||
import org.elasticsearch.client.RestHighLevelClientExt;
|
|
||||||
import org.elasticsearch.client.transport.TransportClient;
|
import org.elasticsearch.client.transport.TransportClient;
|
||||||
import org.elasticsearch.cluster.metadata.MappingMetaData;
|
import org.elasticsearch.cluster.metadata.MappingMetaData;
|
||||||
import org.elasticsearch.common.collect.ImmutableOpenMap;
|
import org.elasticsearch.common.collect.ImmutableOpenMap;
|
||||||
@@ -46,8 +40,6 @@ import org.elasticsearch.transport.client.PreBuiltTransportClient;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.support.ESBulkRequest;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ES 连接器, Transport Rest 两种方式
|
* ES 连接器, Transport Rest 两种方式
|
||||||
*
|
*
|
||||||
@@ -81,15 +73,23 @@ public class ESConnection {
|
|||||||
Integer.parseInt(host.substring(i + 1))));
|
Integer.parseInt(host.substring(i + 1))));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
HttpHost[] httpHosts = Arrays.stream(hosts).map(this::createHttpHost).toArray(HttpHost[]::new);
|
HttpHost[] httpHosts = new HttpHost[hosts.length];
|
||||||
|
for (int i = 0; i < hosts.length; i++) {
|
||||||
|
String host = hosts[i];
|
||||||
|
int j = host.indexOf(":");
|
||||||
|
HttpHost httpHost = new HttpHost(InetAddress.getByName(host.substring(0, j)),
|
||||||
|
Integer.parseInt(host.substring(j + 1)));
|
||||||
|
httpHosts[i] = httpHost;
|
||||||
|
}
|
||||||
RestClientBuilder restClientBuilder = RestClient.builder(httpHosts);
|
RestClientBuilder restClientBuilder = RestClient.builder(httpHosts);
|
||||||
String nameAndPwd = properties.get("security.auth");
|
String nameAndPwd = properties.get("security.auth");
|
||||||
if (StringUtils.isNotEmpty(nameAndPwd) && nameAndPwd.contains(":")) {
|
if (StringUtils.isNotEmpty(nameAndPwd) && nameAndPwd.contains(":")) {
|
||||||
String[] nameAndPwdArr = nameAndPwd.split(":");
|
String[] nameAndPwdArr = nameAndPwd.split(":");
|
||||||
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
|
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
|
||||||
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(nameAndPwdArr[0],
|
credentialsProvider.setCredentials(AuthScope.ANY,
|
||||||
nameAndPwdArr[1]));
|
new UsernamePasswordCredentials(nameAndPwdArr[0], nameAndPwdArr[1]));
|
||||||
restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
|
restClientBuilder.setHttpClientConfigCallback(
|
||||||
|
httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
|
||||||
}
|
}
|
||||||
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
|
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
|
||||||
}
|
}
|
||||||
@@ -150,13 +150,7 @@ public class ESConnection {
|
|||||||
logger.error(e.getMessage(), e);
|
logger.error(e.getMessage(), e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
mappingMetaData = mappings.get(index).get(type);
|
||||||
//通过别名查询mapping返回的是真实索引名称,mappings.get(index)返回null,为兼容别名情况修改如下:
|
|
||||||
ImmutableOpenMap<String, MappingMetaData> esIndex = mappings.get(index);
|
|
||||||
if(esIndex == null){
|
|
||||||
esIndex = mappings.valuesIt().next();
|
|
||||||
}
|
|
||||||
mappingMetaData = esIndex.get(type);
|
|
||||||
}
|
}
|
||||||
return mappingMetaData;
|
return mappingMetaData;
|
||||||
}
|
}
|
||||||
@@ -424,7 +418,6 @@ public class ESConnection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
|
||||||
public ESBulkResponse bulk() {
|
public ESBulkResponse bulk() {
|
||||||
if (mode == ESClientMode.TRANSPORT) {
|
if (mode == ESClientMode.TRANSPORT) {
|
||||||
BulkResponse responses = bulkRequestBuilder.execute().actionGet();
|
BulkResponse responses = bulkRequestBuilder.execute().actionGet();
|
||||||
@@ -509,17 +502,4 @@ public class ESConnection {
|
|||||||
public void setRestHighLevelClient(RestHighLevelClient restHighLevelClient) {
|
public void setRestHighLevelClient(RestHighLevelClient restHighLevelClient) {
|
||||||
this.restHighLevelClient = restHighLevelClient;
|
this.restHighLevelClient = restHighLevelClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
private HttpHost createHttpHost(String uriStr) {
|
|
||||||
URI uri = URI.create(uriStr);
|
|
||||||
if (!org.springframework.util.StringUtils.hasLength(uri.getUserInfo())) {
|
|
||||||
return HttpHost.create(uri.toString());
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return HttpHost.create(new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(),
|
|
||||||
uri.getQuery(), uri.getFragment()).toString());
|
|
||||||
} catch (URISyntaxException ex) {
|
|
||||||
throw new IllegalStateException(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Date;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Date;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Date;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Date;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Date;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
package com.alibaba.otter.canal.client.adapter.es6x.test.sync;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Date;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.elasticsearch.action.get.GetResponse;
|
import org.elasticsearch.action.get.GetResponse;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.client-adapter</artifactId>
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.7-SNAPSHOT</version>
|
<version>1.1.5-SNAPSHOT</version>
|
||||||
<relativePath>../pom.xml</relativePath>
|
<relativePath>../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|||||||
@@ -5,20 +5,20 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import com.alibaba.otter.canal.client.adapter.es7x.etl.ESEtlService;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
|
||||||
import org.elasticsearch.action.search.SearchResponse;
|
import org.elasticsearch.action.search.SearchResponse;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.ESAdapter;
|
import com.alibaba.otter.canal.client.adapter.es.core.ESAdapter;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.es7x.etl.ESEtlService;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es7x.support.ES7xTemplate;
|
import com.alibaba.otter.canal.client.adapter.es7x.support.ES7xTemplate;
|
||||||
import com.alibaba.otter.canal.client.adapter.es7x.support.ESConnection;
|
import com.alibaba.otter.canal.client.adapter.es7x.support.ESConnection;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ES 7.x 外部适配器
|
* ES 7.x 外部适配器
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -2,11 +2,7 @@ package com.alibaba.otter.canal.client.adapter.es7x.support;
|
|||||||
|
|
||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.ConcurrentMap;
|
import java.util.concurrent.ConcurrentMap;
|
||||||
|
|
||||||
@@ -287,7 +283,8 @@ public class ES7xTemplate implements ESTemplate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object getESDataFromDmlData(ESMapping mapping, Map<String, Object> dmlData, Map<String, Object> esFieldData) {
|
public Object getESDataFromDmlData(ESMapping mapping, Map<String, Object> dmlData,
|
||||||
|
Map<String, Object> esFieldData) {
|
||||||
SchemaItem schemaItem = mapping.getSchemaItem();
|
SchemaItem schemaItem = mapping.getSchemaItem();
|
||||||
String idFieldName = mapping.get_id() == null ? mapping.getPk() : mapping.get_id();
|
String idFieldName = mapping.get_id() == null ? mapping.getPk() : mapping.get_id();
|
||||||
Object resultIdVal = null;
|
Object resultIdVal = null;
|
||||||
@@ -311,17 +308,13 @@ public class ES7xTemplate implements ESTemplate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object getESDataFromDmlData(ESMapping mapping,String owner, Map<String, Object> dmlData, Map<String, Object> dmlOld,
|
public Object getESDataFromDmlData(ESMapping mapping, Map<String, Object> dmlData, Map<String, Object> dmlOld,
|
||||||
Map<String, Object> esFieldData) {
|
Map<String, Object> esFieldData) {
|
||||||
SchemaItem schemaItem = mapping.getSchemaItem();
|
SchemaItem schemaItem = mapping.getSchemaItem();
|
||||||
String idFieldName = mapping.get_id() == null ? mapping.getPk() : mapping.get_id();
|
String idFieldName = mapping.get_id() == null ? mapping.getPk() : mapping.get_id();
|
||||||
Object resultIdVal = null;
|
Object resultIdVal = null;
|
||||||
for (FieldItem fieldItem : schemaItem.getSelectFields().values()) {
|
for (FieldItem fieldItem : schemaItem.getSelectFields().values()) {
|
||||||
ColumnItem columnItem = fieldItem.getColumnItems().iterator().next();
|
String columnName = fieldItem.getColumnItems().iterator().next().getColumnName();
|
||||||
if (!columnItem.getOwner().equals(owner)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
String columnName = columnItem.getColumnName();
|
|
||||||
|
|
||||||
if (fieldItem.getFieldName().equals(idFieldName)) {
|
if (fieldItem.getFieldName().equals(idFieldName)) {
|
||||||
resultIdVal = getValFromData(mapping, dmlData, fieldItem.getFieldName(), columnName);
|
resultIdVal = getValFromData(mapping, dmlData, fieldItem.getFieldName(), columnName);
|
||||||
|
|||||||
@@ -2,10 +2,7 @@ package com.alibaba.otter.canal.client.adapter.es7x.support;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URISyntaxException;
|
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
import org.apache.commons.lang.StringUtils;
|
||||||
@@ -62,7 +59,6 @@ public class ESConnection {
|
|||||||
|
|
||||||
private ESClientMode mode;
|
private ESClientMode mode;
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
|
||||||
private TransportClient transportClient;
|
private TransportClient transportClient;
|
||||||
|
|
||||||
private RestHighLevelClient restHighLevelClient;
|
private RestHighLevelClient restHighLevelClient;
|
||||||
@@ -80,15 +76,23 @@ public class ESConnection {
|
|||||||
Integer.parseInt(host.substring(i + 1))));
|
Integer.parseInt(host.substring(i + 1))));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
HttpHost[] httpHosts = Arrays.stream(hosts).map(this::createHttpHost).toArray(HttpHost[]::new);
|
HttpHost[] httpHosts = new HttpHost[hosts.length];
|
||||||
|
for (int i = 0; i < hosts.length; i++) {
|
||||||
|
String host = hosts[i];
|
||||||
|
int j = host.indexOf(":");
|
||||||
|
HttpHost httpHost = new HttpHost(InetAddress.getByName(host.substring(0, j)),
|
||||||
|
Integer.parseInt(host.substring(j + 1)));
|
||||||
|
httpHosts[i] = httpHost;
|
||||||
|
}
|
||||||
RestClientBuilder restClientBuilder = RestClient.builder(httpHosts);
|
RestClientBuilder restClientBuilder = RestClient.builder(httpHosts);
|
||||||
String nameAndPwd = properties.get("security.auth");
|
String nameAndPwd = properties.get("security.auth");
|
||||||
if (StringUtils.isNotEmpty(nameAndPwd) && nameAndPwd.contains(":")) {
|
if (StringUtils.isNotEmpty(nameAndPwd) && nameAndPwd.contains(":")) {
|
||||||
String[] nameAndPwdArr = nameAndPwd.split(":");
|
String[] nameAndPwdArr = nameAndPwd.split(":");
|
||||||
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
|
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
|
||||||
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(nameAndPwdArr[0],
|
credentialsProvider.setCredentials(AuthScope.ANY,
|
||||||
nameAndPwdArr[1]));
|
new UsernamePasswordCredentials(nameAndPwdArr[0], nameAndPwdArr[1]));
|
||||||
restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
|
restClientBuilder.setHttpClientConfigCallback(
|
||||||
|
httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
|
||||||
}
|
}
|
||||||
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
|
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
|
||||||
}
|
}
|
||||||
@@ -497,17 +501,4 @@ public class ESConnection {
|
|||||||
public void setRestHighLevelClient(RestHighLevelClient restHighLevelClient) {
|
public void setRestHighLevelClient(RestHighLevelClient restHighLevelClient) {
|
||||||
this.restHighLevelClient = restHighLevelClient;
|
this.restHighLevelClient = restHighLevelClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
private HttpHost createHttpHost(String uriStr) {
|
|
||||||
URI uri = URI.create(uriStr);
|
|
||||||
if (!org.springframework.util.StringUtils.hasLength(uri.getUserInfo())) {
|
|
||||||
return HttpHost.create(uri.toString());
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return HttpHost.create(new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(),
|
|
||||||
uri.getQuery(), uri.getFragment()).toString());
|
|
||||||
} catch (URISyntaxException ex) {
|
|
||||||
throw new IllegalStateException(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ import org.junit.Test;
|
|||||||
@Ignore
|
@Ignore
|
||||||
public class ES7xTest {
|
public class ES7xTest {
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
|
||||||
private TransportClient transportClient;
|
private TransportClient transportClient;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
@@ -66,9 +65,8 @@ public class ES7xTest {
|
|||||||
relations.put("parent", "2");
|
relations.put("parent", "2");
|
||||||
|
|
||||||
BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
|
BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
|
||||||
bulkRequestBuilder.add(transportClient.prepareIndex("test", "osm", "2_4")
|
bulkRequestBuilder
|
||||||
.setRouting("2")
|
.add(transportClient.prepareIndex("test", "osm", "2_4").setRouting("2").setSource(esFieldData));
|
||||||
.setSource(esFieldData));
|
|
||||||
commit(bulkRequestBuilder);
|
commit(bulkRequestBuilder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import org.elasticsearch.cluster.metadata.MappingMetaData;
|
|||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Ignore;
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.springframework.util.Assert;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es7x.support.ESConnection;
|
import com.alibaba.otter.canal.client.adapter.es7x.support.ESConnection;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
@Ignore
|
@Ignore
|
||||||
public class ESConnectionTest {
|
public class ESConnectionTest {
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.client-adapter</artifactId>
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.7-SNAPSHOT</version>
|
<version>1.1.5-SNAPSHOT</version>
|
||||||
<relativePath>../pom.xml</relativePath>
|
<relativePath>../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
@@ -20,9 +22,8 @@
|
|||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.alibaba</groupId>
|
<groupId>com.alibaba.fastsql</groupId>
|
||||||
<artifactId>druid</artifactId>
|
<artifactId>fastsql</artifactId>
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es.core;
|
package com.alibaba.otter.canal.client.adapter.es.core;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
@@ -7,6 +8,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.es.core.support.ESTemplate;
|
||||||
import org.apache.commons.lang.StringUtils;
|
import org.apache.commons.lang.StringUtils;
|
||||||
|
|
||||||
import com.alibaba.druid.pool.DruidDataSource;
|
import com.alibaba.druid.pool.DruidDataSource;
|
||||||
@@ -17,8 +19,10 @@ import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem;
|
|||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SqlParser;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SqlParser;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.monitor.ESConfigMonitor;
|
import com.alibaba.otter.canal.client.adapter.es.core.monitor.ESConfigMonitor;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.service.ESSyncService;
|
import com.alibaba.otter.canal.client.adapter.es.core.service.ESSyncService;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.support.ESTemplate;
|
import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.*;
|
import com.alibaba.otter.canal.client.adapter.support.Dml;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ES外部适配器
|
* ES外部适配器
|
||||||
@@ -39,8 +43,6 @@ public abstract class ESAdapter implements OuterAdapter {
|
|||||||
|
|
||||||
protected Properties envProperties;
|
protected Properties envProperties;
|
||||||
|
|
||||||
protected OuterAdapterConfig configuration;
|
|
||||||
|
|
||||||
public ESSyncService getEsSyncService() {
|
public ESSyncService getEsSyncService() {
|
||||||
return esSyncService;
|
return esSyncService;
|
||||||
}
|
}
|
||||||
@@ -57,13 +59,23 @@ public abstract class ESAdapter implements OuterAdapter {
|
|||||||
public void init(OuterAdapterConfig configuration, Properties envProperties) {
|
public void init(OuterAdapterConfig configuration, Properties envProperties) {
|
||||||
try {
|
try {
|
||||||
this.envProperties = envProperties;
|
this.envProperties = envProperties;
|
||||||
this.configuration = configuration;
|
|
||||||
Map<String, ESSyncConfig> esSyncConfigTmp = ESSyncConfigLoader.load(envProperties);
|
Map<String, ESSyncConfig> esSyncConfigTmp = ESSyncConfigLoader.load(envProperties);
|
||||||
// 过滤不匹配的key的配置
|
// 过滤不匹配的key的配置
|
||||||
esSyncConfigTmp.forEach((key, config) -> {
|
esSyncConfigTmp.forEach((key, config) -> {
|
||||||
addConfig(key, config);
|
if ((config.getOuterAdapterKey() == null && configuration.getKey() == null)
|
||||||
|
|| (config.getOuterAdapterKey() != null
|
||||||
|
&& config.getOuterAdapterKey().equalsIgnoreCase(configuration.getKey()))) {
|
||||||
|
esSyncConfig.put(key, config);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
for (Map.Entry<String, ESSyncConfig> entry : esSyncConfig.entrySet()) {
|
||||||
|
String configName = entry.getKey();
|
||||||
|
ESSyncConfig config = entry.getValue();
|
||||||
|
|
||||||
|
addSyncConfigToCache(configName, config);
|
||||||
|
}
|
||||||
|
|
||||||
esSyncService = new ESSyncService(esTemplate);
|
esSyncService = new ESSyncService(esTemplate);
|
||||||
|
|
||||||
esConfigMonitor = new ESConfigMonitor();
|
esConfigMonitor = new ESConfigMonitor();
|
||||||
@@ -127,7 +139,7 @@ public abstract class ESAdapter implements OuterAdapter {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addSyncConfigToCache(String configName, ESSyncConfig config) {
|
public void addSyncConfigToCache(String configName, ESSyncConfig config) {
|
||||||
Properties envProperties = this.envProperties;
|
Properties envProperties = this.envProperties;
|
||||||
SchemaItem schemaItem = SqlParser.parse(config.getEsMapping().getSql());
|
SchemaItem schemaItem = SqlParser.parse(config.getEsMapping().getSql());
|
||||||
config.getEsMapping().setSchemaItem(schemaItem);
|
config.getEsMapping().setSchemaItem(schemaItem);
|
||||||
@@ -142,60 +154,24 @@ public abstract class ESAdapter implements OuterAdapter {
|
|||||||
throw new RuntimeException("Not found the schema of jdbc-url: " + config.getDataSourceKey());
|
throw new RuntimeException("Not found the schema of jdbc-url: " + config.getDataSourceKey());
|
||||||
}
|
}
|
||||||
String schema = matcher.group(2);
|
String schema = matcher.group(2);
|
||||||
|
|
||||||
schemaItem.getAliasTableItems().values().forEach(tableItem -> {
|
schemaItem.getAliasTableItems().values().forEach(tableItem -> {
|
||||||
Map<String, ESSyncConfig> esSyncConfigMap;
|
Map<String, ESSyncConfig> esSyncConfigMap;
|
||||||
String schemaKey = tableItem.getSchema() == null ? schema : tableItem.getSchema();
|
if (envProperties != null
|
||||||
if (envProperties != null && !"tcp".equalsIgnoreCase(envProperties.getProperty("canal.conf.mode"))) {
|
&& !"tcp".equalsIgnoreCase(envProperties.getProperty("canal.conf.mode"))) {
|
||||||
esSyncConfigMap = dbTableEsSyncConfig
|
esSyncConfigMap = dbTableEsSyncConfig
|
||||||
.computeIfAbsent(StringUtils.trimToEmpty(config.getDestination()) + "-"
|
.computeIfAbsent(StringUtils.trimToEmpty(config.getDestination()) + "-"
|
||||||
+ StringUtils.trimToEmpty(config.getGroupId()) + "_" + schemaKey + "-"
|
+ StringUtils.trimToEmpty(config.getGroupId()) + "_" + schema + "-"
|
||||||
+ tableItem.getTableName(),
|
+ tableItem.getTableName(),
|
||||||
k -> new ConcurrentHashMap<>());
|
k -> new ConcurrentHashMap<>());
|
||||||
} else {
|
} else {
|
||||||
esSyncConfigMap = dbTableEsSyncConfig.computeIfAbsent(
|
esSyncConfigMap = dbTableEsSyncConfig
|
||||||
StringUtils.trimToEmpty(config.getDestination()) + "_" + schemaKey + "-" + tableItem.getTableName(),
|
.computeIfAbsent(StringUtils.trimToEmpty(config.getDestination()) + "_" + schema + "-"
|
||||||
|
+ tableItem.getTableName(),
|
||||||
k -> new ConcurrentHashMap<>());
|
k -> new ConcurrentHashMap<>());
|
||||||
}
|
}
|
||||||
|
|
||||||
esSyncConfigMap.put(configName, config);
|
esSyncConfigMap.put(configName, config);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean addConfig(String fileName, ESSyncConfig config) {
|
|
||||||
if (match(config)) {
|
|
||||||
esSyncConfig.put(fileName, config);
|
|
||||||
addSyncConfigToCache(fileName, config);
|
|
||||||
FileName2KeyMapping.register(getClass().getAnnotation(SPI.class).value(), fileName, configuration.getKey());
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateConfig(String fileName, ESSyncConfig config) {
|
|
||||||
if (config.getOuterAdapterKey() != null && !config.getOuterAdapterKey().equals(configuration.getKey())) {
|
|
||||||
// 理论上不允许改这个 因为本身就是通过这个关联起Adapter和Config的
|
|
||||||
throw new RuntimeException("not allow to change outAdapterKey");
|
|
||||||
}
|
|
||||||
esSyncConfig.put(fileName, config);
|
|
||||||
addSyncConfigToCache(fileName, config);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void deleteConfig(String fileName) {
|
|
||||||
esSyncConfig.remove(fileName);
|
|
||||||
for (Map<String, ESSyncConfig> configMap : dbTableEsSyncConfig.values()) {
|
|
||||||
if (configMap != null) {
|
|
||||||
configMap.remove(fileName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
FileName2KeyMapping.unregister(getClass().getAnnotation(SPI.class).value(), fileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean match(ESSyncConfig config) {
|
|
||||||
boolean sameMatch = config.getOuterAdapterKey() != null
|
|
||||||
&& config.getOuterAdapterKey().equalsIgnoreCase(configuration.getKey());
|
|
||||||
boolean prefixMatch = config.getOuterAdapterKey() == null && configuration.getKey()
|
|
||||||
.startsWith(StringUtils
|
|
||||||
.join(new String[] { Util.AUTO_GENERATED_PREFIX, config.getDestination(), config.getGroupId() }, '-'));
|
|
||||||
return sameMatch || prefixMatch;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es.core.config;
|
package com.alibaba.otter.canal.client.adapter.es.core.config;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.YamlUtils;
|
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
@@ -8,6 +7,7 @@ import java.util.Properties;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.YmlConfigBinder;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.MappingConfigsLoader;
|
import com.alibaba.otter.canal.client.adapter.support.MappingConfigsLoader;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -28,7 +28,7 @@ public class ESSyncConfigLoader {
|
|||||||
String esv = envProperties.getProperty("es.version");
|
String esv = envProperties.getProperty("es.version");
|
||||||
Map<String, String> configContentMap = MappingConfigsLoader.loadConfigs(esv);
|
Map<String, String> configContentMap = MappingConfigsLoader.loadConfigs(esv);
|
||||||
configContentMap.forEach((fileName, content) -> {
|
configContentMap.forEach((fileName, content) -> {
|
||||||
ESSyncConfig config = YamlUtils.ymlToObj(null, content, ESSyncConfig.class, null, envProperties);
|
ESSyncConfig config = YmlConfigBinder.bindYmlToObj(null, content, ESSyncConfig.class, null, envProperties);
|
||||||
if (config == null) {
|
if (config == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,20 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es.core.config;
|
package com.alibaba.otter.canal.client.adapter.es.core.config;
|
||||||
|
|
||||||
import static com.alibaba.druid.sql.ast.expr.SQLBinaryOperator.BooleanAnd;
|
import static com.alibaba.fastsql.sql.ast.expr.SQLBinaryOperator.BooleanAnd;
|
||||||
import static com.alibaba.druid.sql.ast.expr.SQLBinaryOperator.Equality;
|
import static com.alibaba.fastsql.sql.ast.expr.SQLBinaryOperator.Equality;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import com.alibaba.druid.sql.SQLUtils;
|
import com.alibaba.fastsql.sql.SQLUtils;
|
||||||
import com.alibaba.druid.sql.ast.SQLExpr;
|
import com.alibaba.fastsql.sql.ast.SQLExpr;
|
||||||
import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr;
|
import com.alibaba.fastsql.sql.ast.expr.*;
|
||||||
import com.alibaba.druid.sql.ast.expr.SQLCaseExpr;
|
import com.alibaba.fastsql.sql.ast.statement.*;
|
||||||
import com.alibaba.druid.sql.ast.expr.SQLCharExpr;
|
import com.alibaba.fastsql.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;
|
||||||
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
|
import com.alibaba.fastsql.sql.dialect.mysql.parser.MySqlStatementParser;
|
||||||
import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
|
import com.alibaba.fastsql.sql.parser.ParserException;
|
||||||
import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
|
import com.alibaba.fastsql.sql.parser.SQLStatementParser;
|
||||||
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
|
|
||||||
import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource;
|
|
||||||
import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause;
|
|
||||||
import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
|
|
||||||
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
|
|
||||||
import com.alibaba.druid.sql.ast.statement.SQLSubqueryTableSource;
|
|
||||||
import com.alibaba.druid.sql.ast.statement.SQLTableSource;
|
|
||||||
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;
|
|
||||||
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
|
|
||||||
import com.alibaba.druid.sql.parser.ParserException;
|
|
||||||
import com.alibaba.druid.sql.parser.SQLStatementParser;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.ColumnItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.ColumnItem;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.FieldItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.FieldItem;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.RelationFieldsPair;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.RelationFieldsPair;
|
||||||
@@ -230,7 +219,8 @@ public class SqlParser {
|
|||||||
}
|
}
|
||||||
FieldItem rightFieldItem = new FieldItem();
|
FieldItem rightFieldItem = new FieldItem();
|
||||||
visitColumn(sqlBinaryOpExpr.getRight(), rightFieldItem);
|
visitColumn(sqlBinaryOpExpr.getRight(), rightFieldItem);
|
||||||
if (rightFieldItem.getColumnItems().size() != 1 || rightFieldItem.isMethod() || rightFieldItem.isBinaryOp()) {
|
if (rightFieldItem.getColumnItems().size() != 1 || rightFieldItem.isMethod()
|
||||||
|
|| rightFieldItem.isBinaryOp()) {
|
||||||
throw new UnsupportedOperationException("Unsupported for complex of on-condition");
|
throw new UnsupportedOperationException("Unsupported for complex of on-condition");
|
||||||
}
|
}
|
||||||
tableItem.getRelationFields().add(new RelationFieldsPair(leftFieldItem, rightFieldItem));
|
tableItem.getRelationFields().add(new RelationFieldsPair(leftFieldItem, rightFieldItem));
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.es.core.monitor;
|
package com.alibaba.otter.canal.client.adapter.es.core.monitor;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.es.core.ESAdapter;
|
||||||
import org.apache.commons.io.filefilter.FileFilterUtils;
|
import org.apache.commons.io.filefilter.FileFilterUtils;
|
||||||
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
|
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
|
||||||
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
||||||
@@ -10,13 +15,14 @@ import org.apache.commons.io.monitor.FileAlterationObserver;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.ESAdapter;
|
import com.alibaba.druid.pool.DruidDataSource;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.config.YmlConfigBinder;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SqlParser;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.MappingConfigsLoader;
|
import com.alibaba.otter.canal.client.adapter.support.MappingConfigsLoader;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.Util;
|
import com.alibaba.otter.canal.client.adapter.support.Util;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.YamlUtils;
|
|
||||||
|
|
||||||
;
|
|
||||||
|
|
||||||
public class ESConfigMonitor {
|
public class ESConfigMonitor {
|
||||||
|
|
||||||
@@ -64,20 +70,12 @@ public class ESConfigMonitor {
|
|||||||
try {
|
try {
|
||||||
// 加载新增的配置文件
|
// 加载新增的配置文件
|
||||||
String configContent = MappingConfigsLoader.loadConfig(adapterName + File.separator + file.getName());
|
String configContent = MappingConfigsLoader.loadConfig(adapterName + File.separator + file.getName());
|
||||||
ESSyncConfig config = YamlUtils.ymlToObj(null,
|
ESSyncConfig config = YmlConfigBinder
|
||||||
configContent,
|
.bindYmlToObj(null, configContent, ESSyncConfig.class, null, envProperties);
|
||||||
ESSyncConfig.class,
|
|
||||||
null,
|
|
||||||
envProperties);
|
|
||||||
if (config != null) {
|
if (config != null) {
|
||||||
// 这里要记得设置esVersion bugfix
|
|
||||||
config.setEsVersion(adapterName);
|
|
||||||
config.validate();
|
config.validate();
|
||||||
boolean result = esAdapter.addConfig(file.getName(), config);
|
addConfigToCache(file, config);
|
||||||
if (result) {
|
logger.info("Add a new es mapping config: {} to canal adapter", file.getName());
|
||||||
logger.info("Add a new es mapping config: {} to canal adapter",
|
|
||||||
file.getName());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error(e.getMessage(), e);
|
logger.error(e.getMessage(), e);
|
||||||
@@ -91,24 +89,23 @@ public class ESConfigMonitor {
|
|||||||
try {
|
try {
|
||||||
if (esAdapter.getEsSyncConfig().containsKey(file.getName())) {
|
if (esAdapter.getEsSyncConfig().containsKey(file.getName())) {
|
||||||
// 加载配置文件
|
// 加载配置文件
|
||||||
String configContent = MappingConfigsLoader.loadConfig(adapterName + File.separator
|
String configContent = MappingConfigsLoader
|
||||||
+ file.getName());
|
.loadConfig(adapterName + File.separator + file.getName());
|
||||||
if (configContent == null) {
|
if (configContent == null) {
|
||||||
onFileDelete(file);
|
onFileDelete(file);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ESSyncConfig config = YamlUtils.ymlToObj(null,
|
ESSyncConfig config = YmlConfigBinder
|
||||||
configContent,
|
.bindYmlToObj(null, configContent, ESSyncConfig.class, null, envProperties);
|
||||||
ESSyncConfig.class,
|
|
||||||
null,
|
|
||||||
envProperties);
|
|
||||||
if (config == null) {
|
if (config == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 这里要记得设置esVersion bugfix
|
|
||||||
config.setEsVersion(adapterName);
|
|
||||||
config.validate();
|
config.validate();
|
||||||
esAdapter.updateConfig(file.getName(), config);
|
if (esAdapter.getEsSyncConfig().containsKey(file.getName())) {
|
||||||
|
deleteConfigFromCache(file);
|
||||||
|
}
|
||||||
|
addConfigToCache(file, config);
|
||||||
|
|
||||||
logger.info("Change a es mapping config: {} of canal adapter", file.getName());
|
logger.info("Change a es mapping config: {} of canal adapter", file.getName());
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -122,12 +119,29 @@ public class ESConfigMonitor {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (esAdapter.getEsSyncConfig().containsKey(file.getName())) {
|
if (esAdapter.getEsSyncConfig().containsKey(file.getName())) {
|
||||||
esAdapter.deleteConfig(file.getName());
|
deleteConfigFromCache(file);
|
||||||
|
|
||||||
logger.info("Delete a es mapping config: {} of canal adapter", file.getName());
|
logger.info("Delete a es mapping config: {} of canal adapter", file.getName());
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error(e.getMessage(), e);
|
logger.error(e.getMessage(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void addConfigToCache(File file, ESSyncConfig config) {
|
||||||
|
esAdapter.getEsSyncConfig().put(file.getName(), config);
|
||||||
|
|
||||||
|
esAdapter.addSyncConfigToCache(file.getName(), config);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void deleteConfigFromCache(File file) {
|
||||||
|
esAdapter.getEsSyncConfig().remove(file.getName());
|
||||||
|
for (Map<String, ESSyncConfig> configMap : esAdapter.getDbTableEsSyncConfig().values()) {
|
||||||
|
if (configMap != null) {
|
||||||
|
configMap.remove(file.getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,19 +4,19 @@ import java.util.*;
|
|||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
import com.alibaba.fastsql.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SqlParser;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;
|
import com.alibaba.fastjson.JSON;
|
||||||
import com.alibaba.fastjson2.JSON;
|
import com.alibaba.fastjson.serializer.SerializerFeature;
|
||||||
import com.alibaba.fastjson2.JSONWriter;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig.ESMapping;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig.ESMapping;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.ColumnItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.ColumnItem;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.FieldItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.FieldItem;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.TableItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.TableItem;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SqlParser;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.support.ESSyncUtil;
|
import com.alibaba.otter.canal.client.adapter.es.core.support.ESSyncUtil;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.support.ESTemplate;
|
import com.alibaba.otter.canal.client.adapter.es.core.support.ESTemplate;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
|
import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
|
||||||
@@ -75,7 +75,7 @@ public class ESSyncService {
|
|||||||
esSyncConfigs
|
esSyncConfigs
|
||||||
.forEach(esSyncConfig -> configIndexes.append(esSyncConfig.getEsMapping().get_index()).append(" "));
|
.forEach(esSyncConfig -> configIndexes.append(esSyncConfig.getEsMapping().get_index()).append(" "));
|
||||||
logger.debug("DML: {} \nAffected indexes: {}",
|
logger.debug("DML: {} \nAffected indexes: {}",
|
||||||
JSON.toJSONString(dml, JSONWriter.Feature.WriteNulls),
|
JSON.toJSONString(dml, SerializerFeature.WriteMapNullValue),
|
||||||
configIndexes.toString());
|
configIndexes.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -205,7 +205,7 @@ public class ESSyncService {
|
|||||||
|
|
||||||
if (schemaItem.getAliasTableItems().size() == 1 && schemaItem.isAllFieldsSimple()) {
|
if (schemaItem.getAliasTableItems().size() == 1 && schemaItem.isAllFieldsSimple()) {
|
||||||
// ------单表 & 所有字段都为简单字段------
|
// ------单表 & 所有字段都为简单字段------
|
||||||
singleTableSimpleFiledUpdate(config, schemaItem.getMainTable().getAlias(), dml, data, old);
|
singleTableSimpleFiledUpdate(config, dml, data, old);
|
||||||
} else {
|
} else {
|
||||||
// ------主表 查询sql来更新------
|
// ------主表 查询sql来更新------
|
||||||
if (schemaItem.getMainTable().getTableName().equalsIgnoreCase(dml.getTable())) {
|
if (schemaItem.getMainTable().getTableName().equalsIgnoreCase(dml.getTable())) {
|
||||||
@@ -259,7 +259,7 @@ public class ESSyncService {
|
|||||||
|
|
||||||
// 判断主键和所更新的字段是否全为简单字段
|
// 判断主键和所更新的字段是否全为简单字段
|
||||||
if (idFieldSimple && allUpdateFieldSimple && !fkChanged) {
|
if (idFieldSimple && allUpdateFieldSimple && !fkChanged) {
|
||||||
singleTableSimpleFiledUpdate(config, schemaItem.getMainTable().getAlias(), dml, data, old);
|
singleTableSimpleFiledUpdate(config, dml, data, old);
|
||||||
} else {
|
} else {
|
||||||
mainTableUpdate(config, dml, data, old);
|
mainTableUpdate(config, dml, data, old);
|
||||||
}
|
}
|
||||||
@@ -806,12 +806,12 @@ public class ESSyncService {
|
|||||||
* @param data 单行data数据
|
* @param data 单行data数据
|
||||||
* @param old 单行old数据
|
* @param old 单行old数据
|
||||||
*/
|
*/
|
||||||
private void singleTableSimpleFiledUpdate(ESSyncConfig config, String owner, Dml dml, Map<String, Object> data,
|
private void singleTableSimpleFiledUpdate(ESSyncConfig config, Dml dml, Map<String, Object> data,
|
||||||
Map<String, Object> old) {
|
Map<String, Object> old) {
|
||||||
ESMapping mapping = config.getEsMapping();
|
ESMapping mapping = config.getEsMapping();
|
||||||
Map<String, Object> esFieldData = new LinkedHashMap<>();
|
Map<String, Object> esFieldData = new LinkedHashMap<>();
|
||||||
|
|
||||||
Object idVal = esTemplate.getESDataFromDmlData(mapping, owner, data, old, esFieldData);
|
Object idVal = esTemplate.getESDataFromDmlData(mapping, data, old, esFieldData);
|
||||||
|
|
||||||
if (logger.isTraceEnabled()) {
|
if (logger.isTraceEnabled()) {
|
||||||
logger.trace("Main table update to es index, destination:{}, table: {}, index: {}, id: {}",
|
logger.trace("Main table update to es index, destination:{}, table: {}, index: {}, id: {}",
|
||||||
|
|||||||
@@ -5,20 +5,14 @@ import java.io.InputStream;
|
|||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.sql.Blob;
|
import java.sql.Blob;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.LinkedHashSet;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.apache.commons.codec.binary.Base64;
|
import org.apache.commons.codec.binary.Base64;
|
||||||
import org.joda.time.DateTime;
|
import org.joda.time.DateTime;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.alibaba.fastjson2.JSON;
|
import com.alibaba.fastjson.JSON;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig.ESMapping;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.ESSyncConfig.ESMapping;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem;
|
||||||
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.ColumnItem;
|
import com.alibaba.otter.canal.client.adapter.es.core.config.SchemaItem.ColumnItem;
|
||||||
@@ -63,52 +57,43 @@ public class ESSyncUtil {
|
|||||||
return val;
|
return val;
|
||||||
}
|
}
|
||||||
Object res = null;
|
Object res = null;
|
||||||
switch (esType) {
|
if ("integer".equals(esType)) {
|
||||||
case "integer":
|
|
||||||
if (val instanceof Number) {
|
if (val instanceof Number) {
|
||||||
res = ((Number) val).intValue();
|
res = ((Number) val).intValue();
|
||||||
} else {
|
} else {
|
||||||
res = Integer.parseInt(val.toString());
|
res = Integer.parseInt(val.toString());
|
||||||
}
|
}
|
||||||
break;
|
} else if ("long".equals(esType)) {
|
||||||
case "long":
|
|
||||||
if (val instanceof Number) {
|
if (val instanceof Number) {
|
||||||
res = ((Number) val).longValue();
|
res = ((Number) val).longValue();
|
||||||
} else {
|
} else {
|
||||||
res = Long.parseLong(val.toString());
|
res = Long.parseLong(val.toString());
|
||||||
}
|
}
|
||||||
break;
|
} else if ("short".equals(esType)) {
|
||||||
case "short":
|
|
||||||
if (val instanceof Number) {
|
if (val instanceof Number) {
|
||||||
res = ((Number) val).shortValue();
|
res = ((Number) val).shortValue();
|
||||||
} else {
|
} else {
|
||||||
res = Short.parseShort(val.toString());
|
res = Short.parseShort(val.toString());
|
||||||
}
|
}
|
||||||
break;
|
} else if ("byte".equals(esType)) {
|
||||||
case "byte":
|
|
||||||
if (val instanceof Number) {
|
if (val instanceof Number) {
|
||||||
res = ((Number) val).byteValue();
|
res = ((Number) val).byteValue();
|
||||||
} else {
|
} else {
|
||||||
res = Byte.parseByte(val.toString());
|
res = Byte.parseByte(val.toString());
|
||||||
}
|
}
|
||||||
break;
|
} else if ("double".equals(esType)) {
|
||||||
case "double":
|
|
||||||
if (val instanceof Number) {
|
if (val instanceof Number) {
|
||||||
res = ((Number) val).doubleValue();
|
res = ((Number) val).doubleValue();
|
||||||
} else {
|
} else {
|
||||||
res = Double.parseDouble(val.toString());
|
res = Double.parseDouble(val.toString());
|
||||||
}
|
}
|
||||||
break;
|
} else if ("float".equals(esType) || "half_float".equals(esType) || "scaled_float".equals(esType)) {
|
||||||
case "float":
|
|
||||||
case "half_float":
|
|
||||||
case "scaled_float":
|
|
||||||
if (val instanceof Number) {
|
if (val instanceof Number) {
|
||||||
res = ((Number) val).floatValue();
|
res = ((Number) val).floatValue();
|
||||||
} else {
|
} else {
|
||||||
res = Float.parseFloat(val.toString());
|
res = Float.parseFloat(val.toString());
|
||||||
}
|
}
|
||||||
break;
|
} else if ("boolean".equals(esType)) {
|
||||||
case "boolean":
|
|
||||||
if (val instanceof Boolean) {
|
if (val instanceof Boolean) {
|
||||||
res = val;
|
res = val;
|
||||||
} else if (val instanceof Number) {
|
} else if (val instanceof Number) {
|
||||||
@@ -117,8 +102,7 @@ public class ESSyncUtil {
|
|||||||
} else {
|
} else {
|
||||||
res = Boolean.parseBoolean(val.toString());
|
res = Boolean.parseBoolean(val.toString());
|
||||||
}
|
}
|
||||||
break;
|
} else if ("date".equals(esType)) {
|
||||||
case "date":
|
|
||||||
if (val instanceof java.sql.Time) {
|
if (val instanceof java.sql.Time) {
|
||||||
DateTime dateTime = new DateTime(((java.sql.Time) val).getTime());
|
DateTime dateTime = new DateTime(((java.sql.Time) val).getTime());
|
||||||
if (dateTime.getMillisOfSecond() != 0) {
|
if (dateTime.getMillisOfSecond() != 0) {
|
||||||
@@ -182,8 +166,7 @@ public class ESSyncUtil {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
} else if ("binary".equals(esType)) {
|
||||||
case "binary":
|
|
||||||
if (val instanceof byte[]) {
|
if (val instanceof byte[]) {
|
||||||
Base64 base64 = new Base64();
|
Base64 base64 = new Base64();
|
||||||
res = base64.encodeAsString((byte[]) val);
|
res = base64.encodeAsString((byte[]) val);
|
||||||
@@ -197,8 +180,7 @@ public class ESSyncUtil {
|
|||||||
Base64 base64 = new Base64();
|
Base64 base64 = new Base64();
|
||||||
res = base64.encodeAsString(b);
|
res = base64.encodeAsString(b);
|
||||||
}
|
}
|
||||||
break;
|
} else if ("geo_point".equals(esType)) {
|
||||||
case "geo_point":
|
|
||||||
if (!(val instanceof String)) {
|
if (!(val instanceof String)) {
|
||||||
logger.error("es type is geo_point, but source type is not String");
|
logger.error("es type is geo_point, but source type is not String");
|
||||||
return val;
|
return val;
|
||||||
@@ -214,7 +196,7 @@ public class ESSyncUtil {
|
|||||||
location.put("lat", Double.valueOf(point[0].trim()));
|
location.put("lat", Double.valueOf(point[0].trim()));
|
||||||
location.put("lon", Double.valueOf(point[1].trim()));
|
location.put("lon", Double.valueOf(point[1].trim()));
|
||||||
return location;
|
return location;
|
||||||
case "array":
|
} else if ("array".equals(esType)) {
|
||||||
if ("".equals(val.toString().trim())) {
|
if ("".equals(val.toString().trim())) {
|
||||||
res = new ArrayList<>();
|
res = new ArrayList<>();
|
||||||
} else {
|
} else {
|
||||||
@@ -232,18 +214,15 @@ public class ESSyncUtil {
|
|||||||
String[] values = value.split(separator);
|
String[] values = value.split(separator);
|
||||||
return Arrays.asList(values);
|
return Arrays.asList(values);
|
||||||
}
|
}
|
||||||
break;
|
} else if ("object".equals(esType)) {
|
||||||
case "object":
|
|
||||||
if ("".equals(val.toString().trim())) {
|
if ("".equals(val.toString().trim())) {
|
||||||
res = new HashMap<>();
|
res = new HashMap<>();
|
||||||
} else {
|
} else {
|
||||||
res = JSON.parseObject(val.toString(), Map.class);
|
res = JSON.parseObject(val.toString(), Map.class);
|
||||||
}
|
}
|
||||||
break;
|
} else {
|
||||||
default:
|
|
||||||
// 其他类全以字符串处理
|
// 其他类全以字符串处理
|
||||||
res = val.toString();
|
res = val.toString();
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
|
|||||||
@@ -57,11 +57,13 @@ public interface ESTemplate {
|
|||||||
|
|
||||||
Object getIdValFromRS(ESMapping mapping, ResultSet resultSet) throws SQLException;
|
Object getIdValFromRS(ESMapping mapping, ResultSet resultSet) throws SQLException;
|
||||||
|
|
||||||
Object getESDataFromRS(ESMapping mapping, ResultSet resultSet, Map<String, Object> dmlOld, Map<String, Object> esFieldData) throws SQLException;
|
Object getESDataFromRS(ESMapping mapping, ResultSet resultSet, Map<String, Object> dmlOld,
|
||||||
|
Map<String, Object> esFieldData) throws SQLException;
|
||||||
|
|
||||||
Object getValFromData(ESMapping mapping, Map<String, Object> dmlData, String fieldName, String columnName);
|
Object getValFromData(ESMapping mapping, Map<String, Object> dmlData, String fieldName, String columnName);
|
||||||
|
|
||||||
Object getESDataFromDmlData(ESMapping mapping, Map<String, Object> dmlData, Map<String, Object> esFieldData);
|
Object getESDataFromDmlData(ESMapping mapping, Map<String, Object> dmlData, Map<String, Object> esFieldData);
|
||||||
|
|
||||||
Object getESDataFromDmlData(ESMapping mapping,String owner, Map<String, Object> dmlData, Map<String, Object> dmlOld, Map<String, Object> esFieldData);
|
Object getESDataFromDmlData(ESMapping mapping, Map<String, Object> dmlData, Map<String, Object> dmlOld,
|
||||||
|
Map<String, Object> esFieldData);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.client-adapter</artifactId>
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.7-SNAPSHOT</version>
|
<version>1.1.5-SNAPSHOT</version>
|
||||||
<relativePath>../pom.xml</relativePath>
|
<relativePath>../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.hbase</groupId>
|
<groupId>org.apache.hbase</groupId>
|
||||||
<artifactId>hbase-shaded-client</artifactId>
|
<artifactId>hbase-client</artifactId>
|
||||||
<version>1.1.2</version>
|
<version>1.1.2</version>
|
||||||
<exclusions>
|
<exclusions>
|
||||||
<exclusion>
|
<exclusion>
|
||||||
|
|||||||
@@ -1,25 +1,9 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.hbase;
|
package com.alibaba.otter.canal.client.adapter.hbase;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfig;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfigLoader;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.hbase.monitor.HbaseConfigMonitor;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.hbase.service.HbaseEtlService;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.hbase.service.HbaseSyncService;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.hbase.support.HbaseTemplate;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.Dml;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.FileName2KeyMapping;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.Util;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.*;
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
import org.apache.commons.lang.StringUtils;
|
||||||
import org.apache.hadoop.conf.Configuration;
|
import org.apache.hadoop.conf.Configuration;
|
||||||
import org.apache.hadoop.hbase.HBaseConfiguration;
|
import org.apache.hadoop.hbase.HBaseConfiguration;
|
||||||
@@ -32,6 +16,18 @@ import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfig;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfigLoader;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.hbase.monitor.HbaseConfigMonitor;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.hbase.service.HbaseEtlService;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.hbase.service.HbaseSyncService;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.hbase.support.HbaseTemplate;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.Dml;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HBase外部适配器
|
* HBase外部适配器
|
||||||
*
|
*
|
||||||
@@ -53,8 +49,6 @@ public class HbaseAdapter implements OuterAdapter {
|
|||||||
|
|
||||||
private Properties envProperties;
|
private Properties envProperties;
|
||||||
|
|
||||||
private OuterAdapterConfig configuration;
|
|
||||||
|
|
||||||
public Map<String, MappingConfig> getHbaseMapping() {
|
public Map<String, MappingConfig> getHbaseMapping() {
|
||||||
return hbaseMapping;
|
return hbaseMapping;
|
||||||
}
|
}
|
||||||
@@ -67,12 +61,33 @@ public class HbaseAdapter implements OuterAdapter {
|
|||||||
public void init(OuterAdapterConfig configuration, Properties envProperties) {
|
public void init(OuterAdapterConfig configuration, Properties envProperties) {
|
||||||
try {
|
try {
|
||||||
this.envProperties = envProperties;
|
this.envProperties = envProperties;
|
||||||
this.configuration = configuration;
|
|
||||||
Map<String, MappingConfig> hbaseMappingTmp = MappingConfigLoader.load(envProperties);
|
Map<String, MappingConfig> hbaseMappingTmp = MappingConfigLoader.load(envProperties);
|
||||||
// 过滤不匹配的key的配置
|
// 过滤不匹配的key的配置
|
||||||
hbaseMappingTmp.forEach((key, config) -> {
|
hbaseMappingTmp.forEach((key, mappingConfig) -> {
|
||||||
addConfig(key, config);
|
if ((mappingConfig.getOuterAdapterKey() == null && configuration.getKey() == null)
|
||||||
|
|| (mappingConfig.getOuterAdapterKey() != null
|
||||||
|
&& mappingConfig.getOuterAdapterKey().equalsIgnoreCase(configuration.getKey()))) {
|
||||||
|
hbaseMapping.put(key, mappingConfig);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
for (Map.Entry<String, MappingConfig> entry : hbaseMapping.entrySet()) {
|
||||||
|
String configName = entry.getKey();
|
||||||
|
MappingConfig mappingConfig = entry.getValue();
|
||||||
|
String k;
|
||||||
|
if (envProperties != null && !"tcp".equalsIgnoreCase(envProperties.getProperty("canal.conf.mode"))) {
|
||||||
|
k = StringUtils.trimToEmpty(mappingConfig.getDestination()) + "-"
|
||||||
|
+ StringUtils.trimToEmpty(mappingConfig.getGroupId()) + "_"
|
||||||
|
+ mappingConfig.getHbaseMapping().getDatabase() + "-"
|
||||||
|
+ mappingConfig.getHbaseMapping().getTable();
|
||||||
|
} else {
|
||||||
|
k = StringUtils.trimToEmpty(mappingConfig.getDestination()) + "_"
|
||||||
|
+ mappingConfig.getHbaseMapping().getDatabase() + "-"
|
||||||
|
+ mappingConfig.getHbaseMapping().getTable();
|
||||||
|
}
|
||||||
|
Map<String, MappingConfig> configMap = mappingConfigCache.computeIfAbsent(k,
|
||||||
|
k1 -> new ConcurrentHashMap<>());
|
||||||
|
configMap.put(configName, mappingConfig);
|
||||||
|
}
|
||||||
|
|
||||||
Map<String, String> properties = configuration.getProperties();
|
Map<String, String> properties = configuration.getProperties();
|
||||||
|
|
||||||
@@ -208,62 +223,4 @@ public class HbaseAdapter implements OuterAdapter {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addSyncConfigToCache(String configName, MappingConfig mappingConfig) {
|
|
||||||
String k;
|
|
||||||
if (envProperties != null && !"tcp"
|
|
||||||
.equalsIgnoreCase(envProperties.getProperty("canal.conf.mode"))) {
|
|
||||||
k = StringUtils.trimToEmpty(mappingConfig.getDestination()) + "-" + StringUtils
|
|
||||||
.trimToEmpty(mappingConfig.getGroupId()) + "_" + mappingConfig.getHbaseMapping()
|
|
||||||
.getDatabase() + "-" + mappingConfig.getHbaseMapping().getTable();
|
|
||||||
} else {
|
|
||||||
k = StringUtils.trimToEmpty(mappingConfig.getDestination()) + "_" + mappingConfig
|
|
||||||
.getHbaseMapping().getDatabase() + "-" + mappingConfig.getHbaseMapping()
|
|
||||||
.getTable();
|
|
||||||
}
|
|
||||||
Map<String, MappingConfig> configMap = mappingConfigCache
|
|
||||||
.computeIfAbsent(k, k1 -> new ConcurrentHashMap<>());
|
|
||||||
configMap.put(configName, mappingConfig);
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean addConfig(String fileName, MappingConfig config) {
|
|
||||||
if (match(config)) {
|
|
||||||
hbaseMapping.put(fileName, config);
|
|
||||||
addSyncConfigToCache(fileName, config);
|
|
||||||
FileName2KeyMapping.register(getClass().getAnnotation(SPI.class).value(), fileName,
|
|
||||||
configuration.getKey());
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateConfig(String fileName, MappingConfig config) {
|
|
||||||
if (config.getOuterAdapterKey() != null && !config.getOuterAdapterKey()
|
|
||||||
.equals(configuration.getKey())) {
|
|
||||||
// 理论上不允许改这个 因为本身就是通过这个关联起Adapter和Config的
|
|
||||||
throw new RuntimeException("not allow to change outAdapterKey");
|
|
||||||
}
|
|
||||||
hbaseMapping.put(fileName, config);
|
|
||||||
addSyncConfigToCache(fileName, config);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void deleteConfig(String fileName) {
|
|
||||||
hbaseMapping.remove(fileName);
|
|
||||||
for (Map<String, MappingConfig> configMap : mappingConfigCache.values()) {
|
|
||||||
if (configMap != null) {
|
|
||||||
configMap.remove(fileName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
FileName2KeyMapping.unregister(getClass().getAnnotation(SPI.class).value(), fileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean match(MappingConfig config) {
|
|
||||||
boolean sameMatch = config.getOuterAdapterKey() != null && config.getOuterAdapterKey()
|
|
||||||
.equalsIgnoreCase(configuration.getKey());
|
|
||||||
boolean prefixMatch = config.getOuterAdapterKey() == null && configuration.getKey()
|
|
||||||
.startsWith(StringUtils
|
|
||||||
.join(new String[]{Util.AUTO_GENERATED_PREFIX, config.getDestination(),
|
|
||||||
config.getGroupId()}, '-'));
|
|
||||||
return sameMatch || prefixMatch;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user