index
int64 0
36.5k
| proj_name
stringclasses 162
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
51
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.61k
| len_func_body
int64 1
5.26k
| len_input
int64 27
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
|
---|---|---|---|---|---|---|---|---|---|---|
481 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ReflectionUtil.java | ReflectionUtil | invoke | class ReflectionUtil {
private static Map<String, Method> methodCache = new ConcurrentHashMap<String, Method>();
private static Map<String, Field> fieldCache = new ConcurrentHashMap<String, Field>();
public static Object invoke(Class<?> clazz, Object instance, String name, Class<?>[] parameterTypes, Object[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {<FILL_FUNCTION_BODY>}
public static Object getValue(Class<?> clazz, Object instance, String name) throws NoSuchFieldException, IllegalAccessException {
String key = clazz.getName() + name;
Field field = fieldCache.get(key);
if (field == null) {
field = clazz.getDeclaredField(name);
field.setAccessible(true);
fieldCache.put(key, field);
}
return field.get(instance);
}
} |
String key = clazz.getName() + name;
Method method = methodCache.get(key);
if (method == null) {
method = clazz.getMethod(name, parameterTypes);
methodCache.put(key, method);
}
return method.invoke(instance, args);
| 87 | 241 | 80 | 321 |
482 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ResponseUtil.java | ResponseUtil | getFailureMessage | class ResponseUtil {
public static <T> ResponseEntity<T> getSuccessResponse(T result) {
return ResponseEntity.ok().body(result);
}
public static <T> ResponseEntity<T> getFailureResponse(T result) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
public static ResponseEntity<String> getFailureResponse(Exception e) {
String message = getFailureMessage(e);
return getFailureResponse(message);
}
public static String getFailureMessage(Exception e) {
return getFailureMessage(e, false);
}
public static String getFailureMessage(Exception e, boolean detailed) {<FILL_FUNCTION_BODY>}
} |
String message = null;
if (detailed) {
message = ExceptionUtils.getStackTrace(e);
} else {
message = e.getMessage();
}
// message = "An internal error occurred while processing your request\n" + message;
return message;
| 101 | 188 | 74 | 262 |
483 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/RestUtil.java | RestUtil | processParameter | class RestUtil {
public static HttpHeaders processHeader(HttpHeaders httpHeaders, Map<String, String> headerMap) {
if (MapUtils.isNotEmpty(headerMap)) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
httpHeaders.add(key, value);
}
}
return httpHeaders;
}
public static String processParameter(String url, Map<String, String> parameterMap) {<FILL_FUNCTION_BODY>}
public static HttpHeaders processCookie(HttpHeaders httpHeaders, Map<String, String> cookieMap) {
if (MapUtils.isNotEmpty(cookieMap)) {
List<String> cookieList = new ArrayList<String>();
for (Map.Entry<String, String> entry : cookieMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
cookieList.add(key + DiscoveryConstant.EQUALS + value);
}
httpHeaders.put(DiscoveryConstant.COOKIE_TYPE, cookieList);
}
return httpHeaders;
}
public static <T> T fromJson(RestTemplate restTemplate, String result, TypeReference<T> typeReference) {
try {
return JsonUtil.fromJson(result, typeReference);
} catch (Exception e) {
String error = getError(restTemplate);
if (StringUtils.isNotEmpty(error)) {
throw new IllegalArgumentException(error);
}
throw e;
}
}
public static String getError(RestTemplate restTemplate) {
ResponseErrorHandler responseErrorHandler = restTemplate.getErrorHandler();
if (responseErrorHandler instanceof DiscoveryResponseErrorHandler) {
DiscoveryResponseErrorHandler discoveryResponseErrorHandler = (DiscoveryResponseErrorHandler) responseErrorHandler;
return discoveryResponseErrorHandler.getError();
}
return null;
}
} |
if (MapUtils.isNotEmpty(parameterMap)) {
StringBuilder parameterStringBuilder = new StringBuilder();
int index = 0;
for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
parameterStringBuilder.append(key + DiscoveryConstant.EQUALS + value);
if (index < parameterMap.size() - 1) {
parameterStringBuilder.append("&");
}
index++;
}
String parameter = parameterStringBuilder.toString();
parameter = StringUtils.isNotEmpty(parameter) ? "?" + parameter : "";
url += parameter;
}
return url;
| 274 | 500 | 186 | 686 |
484 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/StringUtil.java | StringUtil | splitToComplexMap | class StringUtil {
public static List<String> splitToList(String value) {
return splitToList(value, DiscoveryConstant.SEPARATE);
}
public static List<String> splitToList(String value, String separate) {
if (StringUtils.isEmpty(value)) {
return null;
}
String[] valueArray = StringUtils.splitByWholeSeparator(value, separate);
return Arrays.asList(valueArray);
}
public static String convertToString(List<String> list) {
return convertToString(list, DiscoveryConstant.SEPARATE);
}
public static String convertToString(List<String> list, String separate) {
if (CollectionUtils.isEmpty(list)) {
return null;
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
String value = list.get(i);
stringBuilder.append(value);
if (i < list.size() - 1) {
stringBuilder.append(separate);
}
}
return stringBuilder.toString();
}
public static Map<String, String> splitToMap(String value) {
return splitToMap(value, DiscoveryConstant.EQUALS, DiscoveryConstant.SEPARATE);
}
public static Map<String, String> splitToMap(String value, String equals, String separate) {
if (StringUtils.isEmpty(value)) {
return null;
}
Map<String, String> map = new LinkedHashMap<String, String>();
String[] separateArray = StringUtils.splitByWholeSeparator(value, separate);
for (String separateValue : separateArray) {
String[] equalsArray = StringUtils.splitByWholeSeparator(separateValue, equals);
map.put(equalsArray[0].trim(), equalsArray[1].trim());
}
return map;
}
public static Map<String, List<String>> splitToComplexMap(String value) {
return splitToComplexMap(value, DiscoveryConstant.SEPARATE);
}
// Json {"a":"1;2", "b":"3;4"} -> Map {a=[1, 2], b=[3, 4]}
// String "1;2;3;4"-> Map {undefined=[1, 2, 3, 4]}
@SuppressWarnings("unchecked")
public static Map<String, List<String>> splitToComplexMap(String value, String separate) {<FILL_FUNCTION_BODY>}
public static String convertToString(Map<String, ?> map) {
return convertToString(map, DiscoveryConstant.EQUALS, DiscoveryConstant.SEPARATE);
}
public static String convertToString(Map<String, ?> map, String equals, String separate) {
if (MapUtils.isEmpty(map)) {
return null;
}
StringBuilder stringBuilder = new StringBuilder();
int index = 0;
for (Map.Entry<String, ?> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
stringBuilder.append(key + equals + value);
if (index < map.size() - 1) {
stringBuilder.append(separate);
}
index++;
}
return stringBuilder.toString();
}
public static String convertToComplexString(Map<String, List<String>> map) {
return convertToComplexString(map, DiscoveryConstant.SEPARATE);
}
// Map {a=[1, 2], b=[3, 4]} -> Json {"a":"1;2", "b":"3;4"}
// Map {undefined=[1, 2, 3, 4]} -> String "1;2;3;4"
public static String convertToComplexString(Map<String, List<String>> map, String separate) {
if (MapUtils.isEmpty(map)) {
return null;
}
if (map.size() == 1 && map.containsKey(DiscoveryConstant.UNDEFINED)) {
List<String> value = map.get(DiscoveryConstant.UNDEFINED);
return convertToString(value);
} else {
Map<String, String> jsonMap = new LinkedHashMap<String, String>();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> value = entry.getValue();
jsonMap.put(key, convertToString(value));
}
return JsonUtil.toJson(jsonMap);
}
}
public static Map<String, String> convertToMap(List<String> list) {
return convertToMap(list, DiscoveryConstant.EQUALS);
}
public static Map<String, String> convertToMap(List<String> list, String separate) {
if (list == null) {
return null;
}
Map<String, String> map = new LinkedHashMap<String, String>();
for (String value : list) {
String[] valueArray = StringUtils.splitByWholeSeparator(value, separate);
map.put(valueArray[0], valueArray[1]);
}
return map;
}
public static String firstToUpperCase(String value) {
return StringUtils.capitalize(value);
}
public static String firstToLowerCase(String value) {
return StringUtils.uncapitalize(value);
}
public static String simulateText(String value, int size, String padValue) {
return StringUtils.rightPad(value, size, padValue);
}
public static String simulateText(int size) {
return simulateText("10", size, "10");
}
public static String toDisplaySize(String value) {
return FileUtils.byteCountToDisplaySize(value.length());
}
public static int count(String text, String keyText) {
if (StringUtils.isEmpty(text) || StringUtils.isEmpty(keyText)) {
return -1;
}
int count = 0;
while (text.indexOf(keyText) != -1) {
text = text.substring(text.indexOf(keyText) + 1, text.length());
count++;
}
return count;
}
} |
if (StringUtils.isEmpty(value)) {
return null;
}
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
try {
Map<String, String> jsonMap = JsonUtil.fromJson(value, Map.class);
for (Map.Entry<String, String> entry : jsonMap.entrySet()) {
String key = entry.getKey();
String list = entry.getValue();
map.put(key, StringUtil.splitToList(list, separate));
}
} catch (Exception e) {
List<String> valueList = StringUtil.splitToList(value, separate);
map.put(DiscoveryConstant.UNDEFINED, valueList);
}
return map;
| 220 | 1,630 | 195 | 1,825 |
485 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/UrlUtil.java | UrlUtil | formatContextPath | class UrlUtil {
public static String formatUrl(String url) {
if (!url.endsWith("/")) {
url = url + "/";
}
return url;
}
public static String formatContextPath(String contextPath) {<FILL_FUNCTION_BODY>}
} |
if (StringUtils.isEmpty(contextPath)) {
return "/";
} else {
if (!contextPath.startsWith("/")) {
contextPath = "/" + contextPath;
}
if (!contextPath.endsWith("/")) {
contextPath = contextPath + "/";
}
}
return contextPath;
| 147 | 78 | 88 | 166 |
486 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/UuidUtil.java | UuidUtil | getTimeUUID | class UuidUtil {
public static final String DATE_FORMAT = "yyyyMMdd-HHmmss-SSS";
public static final String SEPARATOR = "-";
public static final String RANDOMS_EPARATOR = "-";
public static final int[] RANDOM_ARRAY = { 9999, 999, 999 };
public static String getTimeUUID() {
return getTimeUUID(null);
}
public static String getTimeUUID(String prefix) {
return getTimeUUID(prefix, RANDOM_ARRAY);
}
public static String getTimeUUID(String prefix, int[] randomArray) {
return getTimeUUID(prefix, DATE_FORMAT, randomArray, SEPARATOR, RANDOMS_EPARATOR);
}
public static String getTimeUUID(String prefix, String dataFormat) {
return getTimeUUID(prefix, dataFormat, RANDOM_ARRAY, SEPARATOR, RANDOMS_EPARATOR);
}
/**
* 获取日期时间戳和随机数混合的全局唯一ID
* @param prefix 前缀
* @param dataFormat 日期时间戳格式
* @param randomArray 随机数数组,数组元素个数即随机数个数。例如,{ 9, 99, 999 },第一个随机数是0 ~ 9,第二个随机数是0 ~ 99,第三个随机数是0 ~ 999
* @param separator 日期时间戳和随机数分隔符
* @param randomSeparator 随机数之间的分隔符号
* @return 字符串格式的全局唯一ID
*/
public static String getTimeUUID(String prefix, String dataFormat, int[] randomArray, String separator, String randomSeparator) {<FILL_FUNCTION_BODY>}
public static String random(int random) {
return random(random, String.valueOf(random).length());
}
/**
* 获取随机数。例如,输入999, 5, 在0 ~ 999产生随机数,由于要求是随机数位数为5,那么产生的值前面由0补齐
* @param random 随机数最大值
* @param padSize 随机数位数
* @return 随机数
*/
public static String random(int random, int padSize) {
return StringUtils.leftPad(String.valueOf(RandomUtils.nextInt(0, random)), padSize, "0");
}
public static String getUUID() {
return UUID.randomUUID().toString();
}
} |
if (dataFormat == null) {
throw new IllegalArgumentException("dataFormat can't be null");
}
if (randomArray == null) {
throw new IllegalArgumentException("randomArray can't be null");
}
StringBuilder stringBuilder = new StringBuilder();
if (StringUtils.isNotEmpty(prefix)) {
stringBuilder.append(prefix).append(separator);
}
stringBuilder.append(new SimpleDateFormat(dataFormat).format(new Date())).append(separator);
for (int random : randomArray) {
String result = random(random);
stringBuilder.append(result).append(randomSeparator);
}
if (stringBuilder.length() > 0) {
stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());
}
return stringBuilder.toString();
| 223 | 671 | 217 | 888 |
487 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/VersionSortUtil.java | VersionSortUtil | getVersionList | class VersionSortUtil {
public static List<String> assembleVersionList(List<InstanceEntity> instanceEntityList, VersionSortType versionSortType) {
if (CollectionUtils.isEmpty(instanceEntityList)) {
return null;
}
List<VersionSortEntity> versionSortEntityList = new ArrayList<VersionSortEntity>();
for (InstanceEntity instanceEntity : instanceEntityList) {
String version = instanceEntity.getVersion();
String serviceUUId = instanceEntity.getServiceUUId();
VersionSortEntity versionSortEntity = new VersionSortEntity();
versionSortEntity.setVersion(version);
versionSortEntity.setServiceUUId(serviceUUId);
versionSortEntityList.add(versionSortEntity);
}
List<String> versionList = VersionSortUtil.getVersionList(versionSortEntityList, versionSortType);
// 当服务未接入本框架或者版本号未设置(表现出来的值为DiscoveryConstant.DEFAULT),被认为是老版本
String defaultVersion = DiscoveryConstant.DEFAULT;
if (versionList.contains(defaultVersion)) {
versionList.remove(defaultVersion);
versionList.add(0, defaultVersion);
}
return versionList;
}
public static List<String> getVersionList(List<VersionSortEntity> versionSortEntityList, VersionSortType versionSortType) {<FILL_FUNCTION_BODY>}
} |
List<String> versionList = new ArrayList<String>();
Collections.sort(versionSortEntityList, new Comparator<VersionSortEntity>() {
public int compare(VersionSortEntity versionSortEntity1, VersionSortEntity versionSortEntity2) {
if (versionSortType == VersionSortType.VERSION) {
String version1 = versionSortEntity1.getVersion();
String version2 = versionSortEntity2.getVersion();
return version1.compareTo(version2);
} else {
String serviceUUId1 = versionSortEntity1.getServiceUUId();
String serviceUUId2 = versionSortEntity2.getServiceUUId();
return serviceUUId1.compareTo(serviceUUId2);
}
}
});
for (VersionSortEntity versionSortEntity : versionSortEntityList) {
String version = versionSortEntity.getVersion();
if (!versionList.contains(version)) {
versionList.add(version);
}
}
return versionList;
| 341 | 352 | 258 | 610 |
488 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/XmlUtil.java | XmlUtil | isXmlFormat | class XmlUtil {
public static boolean isXmlFormat(String xml) {<FILL_FUNCTION_BODY>}
} |
try {
Dom4JReader.getDocument(xml);
return true;
} catch (Exception e) {
return false;
}
| 72 | 33 | 42 | 75 |
489 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/YamlUtil.java | YamlUtil | isYamlFormat | class YamlUtil {
private static DumperOptions dumperOptions = new DumperOptions();
static {
dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK);
}
public static boolean isYamlFormat(String yaml) {<FILL_FUNCTION_BODY>}
public static <T> String toYaml(T object) {
// 非线程安全
Yaml snakeYaml = new Yaml(dumperOptions);
return snakeYaml.dump(object);
}
public static <T> T fromYaml(String yaml, Class<T> clazz) {
// 非线程安全
Yaml snakeYaml = new Yaml();
return snakeYaml.loadAs(yaml, clazz);
}
public static boolean isYamlFormat(SafeConstructor safeConstructor, String yaml) {
if (StringUtils.isBlank(yaml)) {
return false;
}
// 非线程安全
Yaml snakeYaml = new Yaml(safeConstructor);
try {
snakeYaml.load(yaml);
return true;
} catch (Exception e) {
return false;
}
}
public static <T> String toYaml(SafeConstructor safeConstructor, T object) {
// 非线程安全
Yaml snakeYaml = new Yaml(safeConstructor, new Representer(), dumperOptions);
return snakeYaml.dump(object);
}
public static <T> T fromYaml(SafeConstructor safeConstructor, String yaml, Class<T> clazz) {
// 非线程安全
Yaml snakeYaml = new Yaml(safeConstructor);
return snakeYaml.loadAs(yaml, clazz);
}
} |
if (StringUtils.isBlank(yaml)) {
return false;
}
// 非线程安全
Yaml snakeYaml = new Yaml();
try {
snakeYaml.load(yaml);
return true;
} catch (Exception e) {
return false;
}
| 124 | 457 | 87 | 544 |
490 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/adapter/ApolloConfigAdapter.java | ApolloConfigAdapter | updateConfig | class ApolloConfigAdapter implements ConfigAdapter {
@Autowired
private Environment environment;
@Autowired
private ApolloOpenApiClient apolloOpenApiClient;
@Override
public boolean updateConfig(String group, String serviceId, String config) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public boolean clearConfig(String group, String serviceId) throws Exception {
String appId = environment.getProperty(ApolloConstant.APOLLO_APP_ID);
if (StringUtils.isEmpty(appId)) {
throw new DiscoveryException(ApolloConstant.APOLLO_APP_ID + " can't be null or empty");
}
String env = environment.getProperty(ApolloConstant.APOLLO_ENV);
if (StringUtils.isEmpty(env)) {
throw new DiscoveryException(ApolloConstant.APOLLO_ENV + " can't be null or empty");
}
String operator = environment.getProperty(ApolloConstant.APOLLO_OPERATOR);
if (StringUtils.isEmpty(operator)) {
throw new DiscoveryException(ApolloConstant.APOLLO_OPERATOR + " can't be null or empty");
}
String cluster = environment.getProperty(ApolloConstant.APOLLO_CLUSTER, String.class, ApolloConstant.APOLLO_DEFAULT_CLUSTER);
String namespace = environment.getProperty(ApolloConstant.APOLLO_NAMESPACE, String.class, ApolloConstant.APOLLO_DEFAULT_NAMESPACE);
apolloOpenApiClient.removeItem(appId, env, cluster, namespace, group + "-" + serviceId, operator);
Date now = new Date();
NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO();
namespaceReleaseDTO.setReleaseTitle(new SimpleDateFormat("yyyyMMddHHmmss").format(now) + "-release");
namespaceReleaseDTO.setReleasedBy(operator);
namespaceReleaseDTO.setReleaseComment("Deleted by Nepxion Discovery Console");
namespaceReleaseDTO.setEmergencyPublish(true);
apolloOpenApiClient.publishNamespace(appId, env, cluster, namespace, namespaceReleaseDTO);
return true;
}
@Override
public String getConfig(String group, String serviceId) throws Exception {
String appId = environment.getProperty(ApolloConstant.APOLLO_APP_ID);
if (StringUtils.isEmpty(appId)) {
throw new DiscoveryException(ApolloConstant.APOLLO_APP_ID + " can't be null or empty");
}
String env = environment.getProperty(ApolloConstant.APOLLO_ENV);
if (StringUtils.isEmpty(env)) {
throw new DiscoveryException(ApolloConstant.APOLLO_ENV + " can't be null or empty");
}
String cluster = environment.getProperty(ApolloConstant.APOLLO_CLUSTER, String.class, ApolloConstant.APOLLO_DEFAULT_CLUSTER);
String namespace = environment.getProperty(ApolloConstant.APOLLO_NAMESPACE, String.class, ApolloConstant.APOLLO_DEFAULT_NAMESPACE);
return apolloOpenApiClient.getLatestActiveRelease(appId, env, cluster, namespace).getConfigurations().get(group + "-" + serviceId);
}
@Override
public ConfigType getConfigType() {
return ConfigType.APOLLO;
}
} |
String appId = environment.getProperty(ApolloConstant.APOLLO_APP_ID);
if (StringUtils.isEmpty(appId)) {
throw new DiscoveryException(ApolloConstant.APOLLO_APP_ID + " can't be null or empty");
}
String env = environment.getProperty(ApolloConstant.APOLLO_ENV);
if (StringUtils.isEmpty(env)) {
throw new DiscoveryException(ApolloConstant.APOLLO_ENV + " can't be null or empty");
}
String operator = environment.getProperty(ApolloConstant.APOLLO_OPERATOR);
if (StringUtils.isEmpty(operator)) {
throw new DiscoveryException(ApolloConstant.APOLLO_OPERATOR + " can't be null or empty");
}
String cluster = environment.getProperty(ApolloConstant.APOLLO_CLUSTER, String.class, ApolloConstant.APOLLO_DEFAULT_CLUSTER);
String namespace = environment.getProperty(ApolloConstant.APOLLO_NAMESPACE, String.class, ApolloConstant.APOLLO_DEFAULT_NAMESPACE);
Date now = new Date();
OpenItemDTO openItemDTO = new OpenItemDTO();
openItemDTO.setKey(group + "-" + serviceId);
openItemDTO.setValue(config);
openItemDTO.setComment("Operated by Nepxion Discovery Console");
openItemDTO.setDataChangeCreatedBy(operator);
openItemDTO.setDataChangeLastModifiedBy(operator);
openItemDTO.setDataChangeCreatedTime(now);
openItemDTO.setDataChangeLastModifiedTime(now);
apolloOpenApiClient.createOrUpdateItem(appId, env, cluster, namespace, openItemDTO);
NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO();
namespaceReleaseDTO.setReleaseTitle(new SimpleDateFormat("yyyyMMddHHmmss").format(now) + "-release");
namespaceReleaseDTO.setReleasedBy(operator);
namespaceReleaseDTO.setReleaseComment("Released by Nepxion Discovery Console");
namespaceReleaseDTO.setEmergencyPublish(true);
apolloOpenApiClient.publishNamespace(appId, env, cluster, namespace, namespaceReleaseDTO);
return true;
| 353 | 891 | 601 | 1,492 |
491 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter-apollo/src/main/java/com/nepxion/discovery/console/apollo/configuration/ApolloConfigAutoConfiguration.java | ApolloConfigAutoConfiguration | openApiClient | class ApolloConfigAutoConfiguration {
static {
/*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true");
if (Boolean.valueOf(bannerShown)) {
System.out.println("");
System.out.println("╔═══╗ ╔╗╔╗");
System.out.println("║╔═╗║ ║║║║");
System.out.println("║║ ║╠══╦══╣║║║╔══╗");
System.out.println("║╚═╝║╔╗║╔╗║║║║║╔╗║");
System.out.println("║╔═╗║╚╝║╚╝║╚╣╚╣╚╝║");
System.out.println("╚╝ ╚╣╔═╩══╩═╩═╩══╝");
System.out.println(" ║║");
System.out.println(" ╚╝");
System.out.println(ApolloConstant.TYPE + " Config");
System.out.println("");
}*/
LogoBanner logoBanner = new LogoBanner(ApolloConfigAutoConfiguration.class, "/com/nepxion/apollo/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true);
NepxionBanner.show(logoBanner, new Description("Config:", ConfigType.APOLLO.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1));
}
@Autowired
private Environment environment;
@Bean
public ApolloOpenApiClient openApiClient() {<FILL_FUNCTION_BODY>}
@Bean
public ConfigAdapter configAdapter() {
return new ApolloConfigAdapter();
}
} |
String portalUrl = environment.getProperty(ApolloConstant.APOLLO_PORTAL_URL);
if (StringUtils.isEmpty(portalUrl)) {
throw new DiscoveryException(ApolloConstant.APOLLO_PORTAL_URL + " can't be null or empty");
}
String token = environment.getProperty(ApolloConstant.APOLLO_TOKEN);
if (StringUtils.isEmpty(token)) {
throw new DiscoveryException(ApolloConstant.APOLLO_TOKEN + " can't be null or empty");
}
int connectTimeout = environment.getProperty(ApolloConstant.APOLLO_CONNECT_TIMEOUT, Integer.class, ApolloConstant.DEFAULT_CONNECT_TIMEOUT);
int readTimeout = environment.getProperty(ApolloConstant.APOLLO_READ_TIMEOUT, Integer.class, ApolloConstant.DEFAULT_READ_TIMEOUT);
return ApolloOpenApiClient.newBuilder().withPortalUrl(portalUrl).withToken(token).withConnectTimeout(connectTimeout).withReadTimeout(readTimeout).build();
| 140 | 544 | 273 | 817 |
492 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/ConsoleAutoConfiguration.java | RestTemplateEndpointConfiguration | consoleRestTemplate | class RestTemplateEndpointConfiguration {
@Bean
public RestTemplate consoleRestTemplate() {<FILL_FUNCTION_BODY>}
@Bean
@LoadBalanced
public RestTemplate loadBalancedRestTemplate() {
return new RestTemplate();
}
} |
RestTemplate consoleRestTemplate = new RestTemplate();
consoleRestTemplate.setErrorHandler(new DiscoveryResponseErrorHandler());
return consoleRestTemplate;
| 51 | 69 | 40 | 109 |
493 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/SwaggerConfiguration.java | SwaggerConfiguration | handlerPackage | class SwaggerConfiguration {
private String discoveryGroup = DiscoverySwaggerConstant.SWAGGER_DEFAULT_GROUP_VALUE;
private String discoveryPackages = "com.nepxion.discovery.console.endpoint";
private String discoveryDescription = "Console Restful APIs";
private String discoveryVersion = DiscoverySwaggerConstant.SWAGGER_DEFAULT_VERSION_VALUE;
private String discoveryLicenseName = DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_NAME_VALUE;
private String discoveryLicenseUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_URL_VALUE;
private String discoveryContactName = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_NAME_VALUE;
private String discoveryContactUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_URL_VALUE;
private String discoveryContactEmail = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_EMAIL_VALUE;
private String discoveryTermsOfServiceUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_TERMSOFSERVICE_URL_VALUE;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_GROUP + ":}")
private String serviceGroup;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_PACKAGES + ":}")
private String servicePackages;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_DESCRIPTION + ":}")
private String serviceDescription;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_VERSION + ":}")
private String serviceVersion;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_LICENSE_NAME + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_NAME_VALUE + "}")
private String serviceLicenseName;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_LICENSE_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_URL_VALUE + "}")
private String serviceLicenseUrl;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_NAME + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_NAME_VALUE + "}")
private String serviceContactName;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_URL_VALUE + "}")
private String serviceContactUrl;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_EMAIL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_EMAIL_VALUE + "}")
private String serviceContactEmail;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_TERMSOFSERVICE_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_TERMSOFSERVICE_URL_VALUE + "}")
private String serviceTermsOfServiceUrl;
@Value("${" + DiscoveryConstant.SPRING_APPLICATION_NAME + "}")
private String serviceName;
@Autowired(required = false)
private List<Parameter> swaggerHeaderParameters;
@Autowired(required = false)
private List<SecurityScheme> swaggerSecuritySchemes;
@Autowired(required = false)
private List<SecurityContext> swaggerSecurityContexts;
@Bean("discoveryDocket")
public Docket discoveryDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName(discoveryGroup)
.apiInfo(apiInfo(discoveryDescription,
discoveryVersion,
discoveryLicenseName,
discoveryLicenseUrl,
discoveryContactName,
discoveryContactUrl,
discoveryContactEmail,
discoveryTermsOfServiceUrl))
.select()
.apis(SwaggerConfiguration.basePackage(discoveryPackages)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())
.build()
.globalOperationParameters(swaggerHeaderParameters)
.securitySchemes(swaggerSecuritySchemes)
.securityContexts(swaggerSecurityContexts != null ? swaggerSecurityContexts : Collections.emptyList());
}
@Bean("serviceDocket")
@ConditionalOnProperty(name = DiscoverySwaggerConstant.SWAGGER_SERVICE_GROUP)
public Docket serviceDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName(serviceGroup)
.apiInfo(apiInfo(serviceDescription,
serviceVersion,
serviceLicenseName,
serviceLicenseUrl,
serviceContactName,
serviceContactUrl,
serviceContactEmail,
serviceTermsOfServiceUrl))
.select()
.apis(SwaggerConfiguration.basePackage(servicePackages)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())
.build()
.globalOperationParameters(swaggerHeaderParameters)
.securitySchemes(swaggerSecuritySchemes)
.securityContexts(swaggerSecurityContexts != null ? swaggerSecurityContexts : Collections.emptyList());
}
private ApiInfo apiInfo(String description,
String version,
String licenseName,
String licenseUrl,
String contactName,
String contactUrl,
String contactEmail,
String termsOfServiceUrl) {
return new ApiInfoBuilder()
.title(serviceName)
.description(description)
.version(version)
.license(licenseName)
.licenseUrl(licenseUrl)
.contact(new Contact(contactName, contactUrl, contactEmail))
.termsOfServiceUrl(termsOfServiceUrl)
.build();
}
public static Predicate<RequestHandler> basePackage(String basePackage) {
return new Predicate<RequestHandler>() {
@Override
public boolean apply(RequestHandler input) {
return declaringClass(input).transform(handlerPackage(basePackage)).or(true);
}
};
}
private static Function<Class<?>, Boolean> handlerPackage(String basePackage) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("deprecation")
private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
return Optional.fromNullable(input.declaringClass());
}
} |
return new Function<Class<?>, Boolean>() {
@Override
public Boolean apply(Class<?> input) {
String[] subPackages = basePackage.split(DiscoveryConstant.SEPARATE);
for (String subPackage : subPackages) {
boolean matched = input.getPackage().getName().startsWith(subPackage.trim());
if (matched) {
return true;
}
}
return false;
}
};
| 228 | 1,676 | 121 | 1,797 |
494 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/context/ConsoleApplicationContextInitializer.java | ConsoleApplicationContextInitializer | initialize | class ConsoleApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {<FILL_FUNCTION_BODY>}
} |
if (!(applicationContext instanceof AnnotationConfigApplicationContext)) {
/*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true");
if (Boolean.valueOf(bannerShown)) {
System.out.println("");
System.out.println("╔═══╗");
System.out.println("╚╗╔╗║");
System.out.println(" ║║║╠╦══╦══╦══╦╗╔╦══╦═╦╗ ╔╗");
System.out.println(" ║║║╠╣══╣╔═╣╔╗║╚╝║║═╣╔╣║ ║║");
System.out.println("╔╝╚╝║╠══║╚═╣╚╝╠╗╔╣║═╣║║╚═╝║");
System.out.println("╚═══╩╩══╩══╩══╝╚╝╚══╩╝╚═╗╔╝");
System.out.println(" ╔═╝║");
System.out.println(" ╚══╝");
System.out.println("Nepxion Discovery - Console v" + DiscoveryConstant.DISCOVERY_VERSION);
System.out.println("");
}*/
LogoBanner logoBanner = new LogoBanner(ConsoleApplicationContextInitializer.class, "/com/nepxion/discovery/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true);
NepxionBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", DiscoveryConstant.DISCOVERY_VERSION, 0, 1), new Description(BannerConstant.PLUGIN + ":", "Console", 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1));
}
| 369 | 51 | 582 | 633 |
495 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/delegate/ConsoleResourceDelegateImpl.java | ConsoleResourceDelegateImpl | getRemoteRuleEntity | class ConsoleResourceDelegateImpl implements ConsoleResourceDelegate {
private static final Logger LOG = LoggerFactory.getLogger(ConsoleResourceDelegateImpl.class);
@Autowired
private ConfigResource configResource;
@Override
public RuleEntity getRemoteRuleEntity(String group, String serviceId) {<FILL_FUNCTION_BODY>}
@Override
public boolean updateRemoteRuleEntity(String group, String serviceId, RuleEntity ruleEntity) {
String subscriptionServiceId = StringUtils.isEmpty(serviceId) ? group : serviceId;
try {
return configResource.updateRemoteRuleEntity(group, subscriptionServiceId, ruleEntity);
} catch (Exception e) {
throw new DiscoveryException("Update remote RuleEntity failed, group=" + group + ", serviceId=" + subscriptionServiceId, e);
}
}
} |
String subscriptionServiceId = StringUtils.isEmpty(serviceId) ? group : serviceId;
RuleEntity ruleEntity = null;
try {
ruleEntity = configResource.getRemoteRuleEntity(group, subscriptionServiceId);
} catch (Exception e) {
ruleEntity = new RuleEntity();
LOG.warn("Get remote RuleEntity failed, group={}, serviceId={}", group, subscriptionServiceId, e);
}
return ruleEntity;
| 119 | 206 | 115 | 321 |
496 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/AuthenticationEndpoint.java | AuthenticationEndpoint | doAuthenticate | class AuthenticationEndpoint {
@Autowired
private AuthenticationResource authenticationResource;
@RequestMapping(path = "/authenticate", method = RequestMethod.POST)
@ApiOperation(value = "登录认证", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> authenticate(@RequestBody @ApiParam(value = "UserEntity实例", required = true) UserEntity userEntity) {
return doAuthenticate(userEntity);
}
private ResponseEntity<?> doAuthenticate(UserEntity userEntity) {<FILL_FUNCTION_BODY>}
} |
try {
AuthenticationEntity authenticationEntity = authenticationResource.authenticate(userEntity);
return ResponseUtil.getSuccessResponse(authenticationEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 159 | 64 | 223 |
499 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/FailoverEndpoint.java | FailoverEndpoint | doCreateFailover | class FailoverEndpoint {
@Autowired
private FailoverResource failoverResource;
@RequestMapping(path = "/create/{failoverType}/{group}", method = RequestMethod.POST)
@ApiOperation(value = "全局订阅方式,创建故障转移", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> createFailover(@PathVariable(value = "failoverType") @ApiParam(value = "故障转移类型。取值:version-prefer | version-failover | region-transfer | region-failover | env-failover | zone-failover | address-failover", defaultValue = "version-failover", required = true) String failoverType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @RequestBody @ApiParam(value = "故障转移值,Json格式或者非Json格式", required = true) String failoverValue) {
return doCreateFailover(failoverType, group, failoverValue);
}
@RequestMapping(path = "/clear/{failoverType}/{group}", method = RequestMethod.POST)
@ApiOperation(value = "全局订阅方式,清除故障转移", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> clearFailover(@PathVariable(value = "failoverType") @ApiParam(value = "故障转移类型。取值:version-prefer | version-failover | region-transfer | region-failover | env-failover | zone-failover | address-failover", defaultValue = "version-failover", required = true) String failoverType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group) {
return doClearFailover(failoverType, group);
}
@RequestMapping(path = "/create/{failoverType}/{group}/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "局部订阅方式,创建故障转移", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> createFailover(@PathVariable(value = "failoverType") @ApiParam(value = "故障转移类型。取值:version-prefer | version-failover | region-transfer | region-failover | env-failover | zone-failover | address-failover", defaultValue = "version-failover", required = true) String failoverType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "故障转移值,Json格式或者非Json格式", required = true) String failoverValue) {
return doCreateFailover(failoverType, group, serviceId, failoverValue);
}
@RequestMapping(path = "/clear/{failoverType}/{group}/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "局部订阅方式,清除故障转移", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> clearFailover(@PathVariable(value = "failoverType") @ApiParam(value = "故障转移类型。取值:version-prefer | version-failover | region-transfer | region-failover | env-failover | zone-failover | address-failover", defaultValue = "version-failover", required = true) String failoverType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) {
return doClearFailover(failoverType, group, serviceId);
}
private ResponseEntity<?> doCreateFailover(String failoverType, String group, String failoverValue) {
try {
String result = failoverResource.createFailover(FailoverType.fromString(failoverType), group, failoverValue);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClearFailover(String failoverType, String group) {
try {
String result = failoverResource.clearFailover(FailoverType.fromString(failoverType), group);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doCreateFailover(String failoverType, String group, String serviceId, String failoverValue) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doClearFailover(String failoverType, String group, String serviceId) {
try {
String result = failoverResource.clearFailover(FailoverType.fromString(failoverType), group, serviceId);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
String result = failoverResource.createFailover(FailoverType.fromString(failoverType), group, serviceId, failoverValue);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 78 | 1,323 | 77 | 1,400 |
500 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/InspectorEndpoint.java | InspectorEndpoint | doInspectToList | class InspectorEndpoint {
@Autowired
private InspectorResource inspectorResource;
@RequestMapping(path = "/inspect", method = RequestMethod.POST)
@ApiOperation(value = "侦测调试全链路路由,返回字符串格式", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> inspect(@RequestBody @ApiParam(value = "侦测调试对象", required = true) InspectorDebugEntity inspectorDebugEntity) {
return doInspect(inspectorDebugEntity);
}
@RequestMapping(path = "/inspect-to-list", method = RequestMethod.POST)
@ApiOperation(value = "侦测调试全链路路由,返回结构化格式", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> inspectToList(@RequestBody @ApiParam(value = "侦测调试对象", required = true) InspectorDebugEntity inspectorDebugEntity) {
return doInspectToList(inspectorDebugEntity);
}
private ResponseEntity<?> doInspect(InspectorDebugEntity inspectorDebugEntity) {
try {
String result = inspectorResource.inspect(inspectorDebugEntity.getProtocol(), inspectorDebugEntity.getPortal(), inspectorDebugEntity.getPath(), inspectorDebugEntity.getService(), inspectorDebugEntity.getHeader(), inspectorDebugEntity.getFilter());
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doInspectToList(InspectorDebugEntity inspectorDebugEntity) {<FILL_FUNCTION_BODY>}
} |
try {
List<Map<String, String>> result = inspectorResource.inspectToList(inspectorDebugEntity.getProtocol(), inspectorDebugEntity.getPortal(), inspectorDebugEntity.getPath(), inspectorDebugEntity.getService(), inspectorDebugEntity.getHeader(), inspectorDebugEntity.getFilter());
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 81 | 440 | 114 | 554 |
502 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/SentinelEndpoint.java | SentinelEndpoint | doRemoteSentinelUpdate | class SentinelEndpoint {
@Autowired
private SentinelResource sentinelResource;
@RequestMapping(path = "/remote/update/{ruleType}/{group}/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "更新哨兵规则到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> remoteSentinelUpdate(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "哨兵规则内容,Json格式", required = true) String rule) {
return doRemoteSentinelUpdate(ruleType, group, serviceId, rule);
}
@RequestMapping(path = "/remote/clear/{ruleType}/{group}/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "清除哨兵规则到远程配置中心", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> remoteSentinelClear(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) {
return doRemoteSentinelClear(ruleType, group, serviceId);
}
@RequestMapping(path = "/remote/view/{ruleType}/{group}/{serviceId}", method = RequestMethod.GET)
@ApiOperation(value = "查看远程配置中心的哨兵规则", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> remoteSentinelView(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "group") @ApiParam(value = "组名", required = true) String group, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) {
return doRemoteSentinelView(ruleType, group, serviceId);
}
@RequestMapping(path = "/update/{ruleType}/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "批量更新哨兵规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> sentinelUpdate(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "哨兵规则内容,Json格式", required = true) String rule) {
return doSentinelUpdate(ruleType, serviceId, rule);
}
@RequestMapping(path = "/clear/{ruleType}/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "批量清除哨兵规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> sentinelClear(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) {
return doSentinelClear(ruleType, serviceId);
}
@RequestMapping(path = "/view/{ruleType}/{serviceId}", method = RequestMethod.GET)
@ApiOperation(value = "批量查看哨兵规则列表", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> sentinelView(@PathVariable(value = "ruleType") @ApiParam(value = "哨兵规则类型。取值: flow | degrade | authority | system | param-flow", defaultValue = "flow", required = true) String ruleType, @PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) {
return doSentinelView(ruleType, serviceId);
}
private ResponseEntity<?> doRemoteSentinelUpdate(String ruleType, String group, String serviceId, String rule) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doRemoteSentinelClear(String ruleType, String group, String serviceId) {
try {
boolean result = sentinelResource.clearRemoteSentinel(SentinelRuleType.fromString(ruleType), group, serviceId);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doRemoteSentinelView(String ruleType, String group, String serviceId) {
try {
String result = sentinelResource.getRemoteSentinel(SentinelRuleType.fromString(ruleType), group, serviceId);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doSentinelUpdate(String ruleType, String serviceId, String rule) {
try {
List<ResultEntity> resultEntityList = sentinelResource.updateSentinel(SentinelRuleType.fromString(ruleType), serviceId, rule);
return ResponseUtil.getSuccessResponse(resultEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doSentinelClear(String ruleType, String serviceId) {
try {
List<ResultEntity> resultEntityList = sentinelResource.clearSentinel(SentinelRuleType.fromString(ruleType), serviceId);
return ResponseUtil.getSuccessResponse(resultEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doSentinelView(String ruleType, String serviceId) {
try {
List<ResultEntity> resultEntityList = sentinelResource.viewSentinel(SentinelRuleType.fromString(ruleType), serviceId);
return ResponseUtil.getSuccessResponse(resultEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
boolean result = sentinelResource.updateRemoteSentinel(SentinelRuleType.fromString(ruleType), group, serviceId, rule);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 78 | 1,851 | 79 | 1,930 |
505 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/VersionEndpoint.java | VersionEndpoint | doVersionUpdate | class VersionEndpoint {
@Autowired
private VersionResource versionResource;
@RequestMapping(path = "/update-async/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "批量异步更新动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> versionUpdateAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "版本号,格式为${dynamicVersion}或者${dynamicVersion};${localVersion}", required = true) String version) {
return doVersionUpdate(serviceId, version, true);
}
@RequestMapping(path = "/update-sync/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "批量同步更新动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> versionUpdateSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody @ApiParam(value = "版本号,格式为${dynamicVersion}或者${dynamicVersion};${localVersion}", required = true) String version) {
return doVersionUpdate(serviceId, version, false);
}
@RequestMapping(path = "/clear-async/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "批量异步清除动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> versionClearAsync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) {
return doVersionClear(serviceId, version, true);
}
@RequestMapping(path = "/clear-sync/{serviceId}", method = RequestMethod.POST)
@ApiOperation(value = "批量同步清除动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> versionClearSync(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId, @RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) {
return doVersionClear(serviceId, version, false);
}
@RequestMapping(path = "/view/{serviceId}", method = RequestMethod.GET)
@ApiOperation(value = "批量查看版本", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> versionView(@PathVariable(value = "serviceId") @ApiParam(value = "服务名", required = true) String serviceId) {
return doVersionView(serviceId);
}
private ResponseEntity<?> doVersionUpdate(String serviceId, String version, boolean async) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doVersionClear(String serviceId, String version, boolean async) {
try {
List<ResultEntity> resultEntityList = versionResource.clearVersion(serviceId, version, async);
return ResponseUtil.getSuccessResponse(resultEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doVersionView(String serviceId) {
try {
List<ResultEntity> resultEntityList = versionResource.viewVersion(serviceId);
return ResponseUtil.getSuccessResponse(resultEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
List<ResultEntity> resultEntityList = versionResource.updateVersion(serviceId, version, async);
return ResponseUtil.getSuccessResponse(resultEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 77 | 1,149 | 70 | 1,219 |
506 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/AuthenticationResourceImpl.java | AuthenticationResourceImpl | authenticate | class AuthenticationResourceImpl implements AuthenticationResource {
@Autowired
private Environment environment;
@Override
public AuthenticationEntity authenticate(UserEntity userEntity) {<FILL_FUNCTION_BODY>}
} |
AuthenticationEntity authenticationEntity = new AuthenticationEntity();
String userId = userEntity.getUserId().trim();
String password = userEntity.getPassword().trim();
String passwordValue = environment.getProperty(userId);
if (StringUtils.isNotEmpty(passwordValue)) {
if (StringUtils.equals(password, passwordValue)) {
authenticationEntity.setPassed(true);
} else {
authenticationEntity.setError("Password is mismatched");
}
} else {
authenticationEntity.setError("Account doesn't exist");
}
return authenticationEntity;
| 176 | 57 | 152 | 209 |
508 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ConfigResourceImpl.java | ConfigResourceImpl | fromRuleEntity | class ConfigResourceImpl implements ConfigResource {
private static final Logger LOG = LoggerFactory.getLogger(ConfigResourceImpl.class);
@Autowired(required = false)
private ConfigAdapter configAdapter;
@Autowired
private ServiceResource serviceResource;
@Autowired
private RestTemplate consoleRestTemplate;
@Autowired
private PluginConfigParser pluginConfigParser;
@Autowired
private PluginConfigDeparser pluginConfigDeparser;
@Autowired
private Environment environment;
@Override
public ConfigType getConfigType() {
if (configAdapter == null) {
LOG.error("Remote config adapter isn't provided");
throw new DiscoveryException("Remote config adapter isn't provided");
}
return configAdapter.getConfigType();
}
@Override
public boolean updateRemoteConfig(String group, String serviceId, String config) throws Exception {
if (configAdapter == null) {
LOG.error("Remote config adapter isn't provided");
throw new DiscoveryException("Remote config adapter isn't provided");
}
return configAdapter.updateConfig(group, serviceId, config);
}
@Override
public boolean updateRemoteConfig(String group, String serviceId, String config, FormatType formatType) throws Exception {
if (configAdapter == null) {
LOG.error("Remote config adapter isn't provided");
throw new DiscoveryException("Remote config adapter isn't provided");
}
return configAdapter.updateConfig(group, serviceId, config, formatType);
}
@Override
public boolean updateRemoteRuleEntity(String group, String serviceId, RuleEntity ruleEntity) throws Exception {
String config = fromRuleEntity(ruleEntity);
String configFormat = environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT);
FormatType formatType = FormatType.fromString(configFormat);
return updateRemoteConfig(group, serviceId, config, formatType);
}
@Override
public boolean clearRemoteConfig(String group, String serviceId) throws Exception {
if (configAdapter == null) {
LOG.error("Remote config adapter isn't provided");
throw new DiscoveryException("Remote config adapter isn't provided");
}
return configAdapter.clearConfig(group, serviceId);
}
@Override
public String getRemoteConfig(String group, String serviceId) throws Exception {
if (configAdapter == null) {
LOG.error("Remote config adapter isn't provided");
throw new DiscoveryException("Remote config adapter isn't provided");
}
return configAdapter.getConfig(group, serviceId);
}
@Override
public RuleEntity getRemoteRuleEntity(String group, String serviceId) throws Exception {
String config = getRemoteConfig(group, serviceId);
return toRuleEntity(config);
}
@Override
public List<ResultEntity> updateConfig(String serviceId, String config, boolean async) {
ConfigUpdateRestInvoker configUpdateRestInvoker = new ConfigUpdateRestInvoker(serviceResource, serviceId, consoleRestTemplate, async, config);
return configUpdateRestInvoker.invoke();
}
@Override
public List<ResultEntity> updateRuleEntity(String serviceId, RuleEntity ruleEntity, boolean async) {
String config = fromRuleEntity(ruleEntity);
return updateConfig(serviceId, config, async);
}
@Override
public List<ResultEntity> clearConfig(String serviceId, boolean async) {
ConfigClearRestInvoker configClearRestInvoker = new ConfigClearRestInvoker(serviceResource, serviceId, consoleRestTemplate, async);
return configClearRestInvoker.invoke();
}
@Override
public List<ResultEntity> viewConfig(String serviceId) {
ConfigViewRestInvoker configViewRestInvoker = new ConfigViewRestInvoker(serviceResource, serviceId, consoleRestTemplate);
return configViewRestInvoker.invoke();
}
@Override
public RuleEntity toRuleEntity(String config) {
return StringUtils.isNotEmpty(config) ? parse(config) : new RuleEntity();
}
@Override
public String fromRuleEntity(RuleEntity ruleEntity) {<FILL_FUNCTION_BODY>}
@Override
public RuleEntity parse(String config) {
return pluginConfigParser.parse(config);
}
@Override
public String deparse(RuleEntity ruleEntity) {
return pluginConfigDeparser.deparse(ruleEntity);
}
} |
if (ruleEntity != null) {
return deparse(ruleEntity);
}
String configFormat = environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT);
ConfigFormatType configFormatType = ConfigFormatType.fromString(configFormat);
switch (configFormatType) {
case XML_FORMAT:
return DiscoveryConstant.EMPTY_XML_RULE;
case JSON_FORMAT:
return DiscoveryConstant.EMPTY_JSON_RULE_SINGLE;
}
return StringUtils.EMPTY;
| 149 | 1,146 | 158 | 1,304 |
509 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/FailoverResourceImpl.java | FailoverResourceImpl | setFailover | class FailoverResourceImpl extends ConsoleResourceDelegateImpl implements FailoverResource {
@Autowired
private ConfigResource configResource;
@Override
public String createFailover(FailoverType failoverType, String group, String failoverValue) {
return createFailover(failoverType, group, null, failoverValue);
}
@Override
public String clearFailover(FailoverType failoverType, String group) {
return clearFailover(failoverType, group, null);
}
@Override
public String createFailover(FailoverType failoverType, String group, String serviceId, String failoverValue) {
RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId);
createFailover(failoverType, ruleEntity, failoverValue);
updateRemoteRuleEntity(group, serviceId, ruleEntity);
return configResource.fromRuleEntity(ruleEntity);
}
@Override
public String clearFailover(FailoverType failoverType, String group, String serviceId) {
RuleEntity ruleEntity = getRemoteRuleEntity(group, serviceId);
clearFailover(failoverType, ruleEntity);
updateRemoteRuleEntity(group, serviceId, ruleEntity);
return configResource.fromRuleEntity(ruleEntity);
}
private void createFailover(FailoverType failoverType, RuleEntity ruleEntity, String failoverValue) {
StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity();
if (strategyFailoverEntity == null) {
strategyFailoverEntity = new StrategyFailoverEntity();
ruleEntity.setStrategyFailoverEntity(strategyFailoverEntity);
}
setFailover(failoverType, strategyFailoverEntity, failoverValue);
}
private void clearFailover(FailoverType failoverType, RuleEntity ruleEntity) {
StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity();
if (strategyFailoverEntity != null) {
setFailover(failoverType, strategyFailoverEntity, null);
}
}
private void setFailover(FailoverType failoverType, StrategyFailoverEntity strategyFailoverEntity, String failoverValue) {<FILL_FUNCTION_BODY>}
} |
switch (failoverType) {
case VERSION_PREFER:
strategyFailoverEntity.setVersionPreferValue(failoverValue);
break;
case VERSION_FAILOVER:
strategyFailoverEntity.setVersionFailoverValue(failoverValue);
break;
case REGION_TRANSFER:
strategyFailoverEntity.setRegionTransferValue(failoverValue);
break;
case REGION_FAILOVER:
strategyFailoverEntity.setRegionFailoverValue(failoverValue);
break;
case ENVIRONMENT_FAILOVER:
strategyFailoverEntity.setEnvironmentFailoverValue(failoverValue);
break;
case ZONE_FAILOVER:
strategyFailoverEntity.setZoneFailoverValue(failoverValue);
break;
case ADDRESS_FAILOVER:
strategyFailoverEntity.setAddressFailoverValue(failoverValue);
break;
}
| 338 | 562 | 244 | 806 |
510 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/InspectorResourceImpl.java | InspectorResourceImpl | inspect | class InspectorResourceImpl implements InspectorResource {
@Autowired
private RestTemplate loadBalancedRestTemplate;
@Override
public String inspect(String protocol, String portal, String path, List<String> service, Map<String, String> header, List<String> filter) {<FILL_FUNCTION_BODY>}
@Override
public List<Map<String, String>> inspectToList(String protocol, String portal, String path, List<String> service, Map<String, String> header, List<String> filter) {
String result = inspect(protocol, portal, path, service, header, filter);
return PluginInfoUtil.assembleAll(result, filter);
}
} |
String url = protocol + "://" + portal + UrlUtil.formatContextPath(path) + DiscoveryConstant.INSPECTOR_ENDPOINT_URL;
InspectorEntity inspectorEntity = new InspectorEntity();
inspectorEntity.setServiceIdList(service);
if (MapUtils.isNotEmpty(header)) {
HttpHeaders headers = new HttpHeaders();
for (Map.Entry<String, String> entry : header.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
HttpEntity<InspectorEntity> requestEntity = new HttpEntity<InspectorEntity>(inspectorEntity, headers);
String result = loadBalancedRestTemplate.exchange(url, HttpMethod.POST, requestEntity, InspectorEntity.class, new HashMap<String, String>()).getBody().getResult();
return PluginInfoUtil.extractAll(result, filter);
}
String result = loadBalancedRestTemplate.postForEntity(url, inspectorEntity, InspectorEntity.class).getBody().getResult();
return PluginInfoUtil.extractAll(result, filter);
| 200 | 172 | 277 | 449 |
511 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/RouteResourceImpl.java | RouteResourceImpl | updateRemoteRoute | class RouteResourceImpl implements RouteResource {
@Autowired
private ServiceResource serviceResource;
@Autowired
private ConfigResource configResource;
@Autowired
private RestTemplate consoleRestTemplate;
@Override
public boolean updateRemoteRoute(GatewayType gatewayType, String group, String serviceId, String route) {<FILL_FUNCTION_BODY>}
@Override
public boolean clearRemoteRoute(GatewayType gatewayType, String group, String serviceId) {
try {
return configResource.updateRemoteConfig(group, serviceId + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY, DiscoveryConstant.EMPTY_JSON_RULE_MULTIPLE, FormatType.JSON_FORMAT);
} catch (Exception e) {
throw new DiscoveryException("Clear remote " + gatewayType.getName() + " dynamic route failed, group={}, serviceId={}", e);
}
}
@Override
public String getRemoteRoute(GatewayType gatewayType, String group, String serviceId) {
try {
return configResource.getRemoteConfig(group, serviceId + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY);
} catch (Exception e) {
throw new DiscoveryException("Get remote " + gatewayType.getName() + " dynamic route failed, group={}, serviceId={}", e);
}
}
@Override
public List<ResultEntity> addRoute(GatewayType gatewayType, String serviceId, String route) {
RouteAddRestInvoker routeAddRestInvoker = new RouteAddRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType, route);
return routeAddRestInvoker.invoke();
}
@Override
public List<ResultEntity> modifyRoute(GatewayType gatewayType, String serviceId, String route) {
RouteModifyRestInvoker routeModifyRestInvoker = new RouteModifyRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType, route);
return routeModifyRestInvoker.invoke();
}
@Override
public List<ResultEntity> deleteRoute(GatewayType gatewayType, String serviceId, String routeId) {
RouteDeleteRestInvoker routeDeleteRestInvoker = new RouteDeleteRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType, routeId);
return routeDeleteRestInvoker.invoke();
}
@Override
public List<ResultEntity> updateAllRoute(GatewayType gatewayType, String serviceId, String route) {
RouteUpdateAllRestInvoker routeUpdateAllRestInvoker = new RouteUpdateAllRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType, route);
return routeUpdateAllRestInvoker.invoke();
}
@Override
public List<ResultEntity> viewAllRoute(GatewayType gatewayType, String serviceId) {
RouteViewAllRestInvoker routeViewAllRestInvoker = new RouteViewAllRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType);
return routeViewAllRestInvoker.invoke();
}
} |
try {
return configResource.updateRemoteConfig(group, serviceId + "-" + DiscoveryConstant.DYNAMIC_ROUTE_KEY, route, FormatType.JSON_FORMAT);
} catch (Exception e) {
throw new DiscoveryException("Update remote " + gatewayType.getName() + " dynamic route failed, group={}, serviceId={}", e);
}
| 80 | 768 | 95 | 863 |
512 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/SentinelResourceImpl.java | SentinelResourceImpl | updateRemoteSentinel | class SentinelResourceImpl implements SentinelResource {
@Autowired
private ServiceResource serviceResource;
@Autowired
private ConfigResource configResource;
@Autowired
private RestTemplate consoleRestTemplate;
@Override
public boolean updateRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId, String rule) {<FILL_FUNCTION_BODY>}
@Override
public boolean clearRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId) {
try {
return configResource.updateRemoteConfig(group, serviceId + "-" + ruleType.getKey(), DiscoveryConstant.EMPTY_JSON_RULE_MULTIPLE, FormatType.JSON_FORMAT);
} catch (Exception e) {
throw new DiscoveryException("Clear remote " + ruleType.getDescription() + " failed, group={}, serviceId={}", e);
}
}
@Override
public String getRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId) {
try {
return configResource.getRemoteConfig(group, serviceId + "-" + ruleType.getKey());
} catch (Exception e) {
throw new DiscoveryException("Get remote " + ruleType.getDescription() + " failed, group={}, serviceId={}", e);
}
}
@Override
public List<ResultEntity> updateSentinel(SentinelRuleType ruleType, String serviceId, String rule) {
SentinelUpdateRestInvoker sentinelUpdateRestInvoker = new SentinelUpdateRestInvoker(serviceResource, serviceId, consoleRestTemplate, ruleType, rule);
return sentinelUpdateRestInvoker.invoke();
}
@Override
public List<ResultEntity> clearSentinel(SentinelRuleType ruleType, String serviceId) {
SentinelClearRestInvoker sentinelClearRestInvoker = new SentinelClearRestInvoker(serviceResource, serviceId, consoleRestTemplate, ruleType);
return sentinelClearRestInvoker.invoke();
}
@Override
public List<ResultEntity> viewSentinel(SentinelRuleType ruleType, String serviceId) {
SentinelViewRestInvoker sentinelViewRestInvoker = new SentinelViewRestInvoker(serviceResource, serviceId, consoleRestTemplate, ruleType);
return sentinelViewRestInvoker.invoke();
}
} |
try {
return configResource.updateRemoteConfig(group, serviceId + "-" + ruleType.getKey(), rule, FormatType.JSON_FORMAT);
} catch (Exception e) {
throw new DiscoveryException("Update remote " + ruleType.getDescription() + " failed, group={}, serviceId={}", e);
}
| 78 | 611 | 85 | 696 |
515 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/VersionResourceImpl.java | VersionResourceImpl | updateVersion | class VersionResourceImpl implements VersionResource {
@Autowired
private ServiceResource serviceResource;
@Autowired
private RestTemplate consoleRestTemplate;
@Override
public List<ResultEntity> updateVersion(String serviceId, String version, boolean async) {<FILL_FUNCTION_BODY>}
@Override
public List<ResultEntity> clearVersion(String serviceId, String version, boolean async) {
VersionClearRestInvoker versionClearRestInvoker = new VersionClearRestInvoker(serviceResource, serviceId, consoleRestTemplate, async, version);
return versionClearRestInvoker.invoke();
}
@Override
public List<ResultEntity> viewVersion(String serviceId) {
VersionViewRestInvoker versionViewRestInvoker = new VersionViewRestInvoker(serviceResource, serviceId, consoleRestTemplate);
return versionViewRestInvoker.invoke();
}
} |
VersionUpdateRestInvoker versionUpdateRestInvoker = new VersionUpdateRestInvoker(serviceResource, serviceId, consoleRestTemplate, async, version);
return versionUpdateRestInvoker.invoke();
| 30 | 222 | 49 | 271 |
516 | Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/AbstractRestInvoker.java | AbstractRestInvoker | invoke | class AbstractRestInvoker {
private static final Logger LOG = LoggerFactory.getLogger(AbstractRestInvoker.class);
protected ServiceResource serviceResource;
protected String serviceId;
protected RestTemplate restTemplate;
protected boolean async;
public AbstractRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate) {
this(serviceResource, serviceId, restTemplate, false);
}
public AbstractRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, boolean async) {
this.serviceResource = serviceResource;
this.serviceId = serviceId;
this.restTemplate = restTemplate;
this.async = async;
}
public List<ResultEntity> invoke() {<FILL_FUNCTION_BODY>}
protected String getInvokeType() {
return async ? DiscoveryConstant.ASYNC : DiscoveryConstant.SYNC;
}
protected HttpHeaders getInvokeHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
return headers;
}
protected HttpEntity<String> getInvokeEntity(String content) {
HttpHeaders headers = getInvokeHeaders();
return new HttpEntity<String>(content, headers);
}
protected abstract String getDescription();
protected abstract String getSuffixPath();
protected abstract String doRest(String url);
} |
List<ServiceInstance> instances = serviceResource.getInstances(serviceId);
if (CollectionUtils.isEmpty(instances)) {
LOG.warn("No service instances found");
throw new DiscoveryException("No service instances found");
}
List<ResultEntity> resultEntityList = new ArrayList<ResultEntity>();
for (ServiceInstance instance : instances) {
Map<String, String> metadata = instance.getMetadata();
String host = instance.getHost();
int port = instance.getPort();
String protocol = InstanceEntityWrapper.getProtocol(metadata);
String contextPath = InstanceEntityWrapper.getFormatContextPath(metadata);
String url = protocol + "://" + host + ":" + port + contextPath + getSuffixPath();
String result = null;
try {
result = doRest(url);
String error = RestUtil.getError(restTemplate);
if (StringUtils.isNotEmpty(error)) {
result = error;
}
} catch (Exception e) {
result = ResponseUtil.getFailureMessage(e);
}
ResultEntity resultEntity = new ResultEntity();
resultEntity.setServiceId(serviceId);
resultEntity.setHost(host);
resultEntity.setPort(port);
resultEntity.setUrl(url);
resultEntity.setResult(result);
resultEntityList.add(resultEntity);
}
String description = getDescription();
LOG.info(description + " results=\n{}", resultEntityList);
return resultEntityList;
| 489 | 361 | 389 | 750 |
517 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/configuration/SwaggerConfiguration.java | SwaggerConfiguration | handlerPackage | class SwaggerConfiguration {
private String discoveryGroup = DiscoverySwaggerConstant.SWAGGER_DEFAULT_GROUP_VALUE;
private String discoveryPackages = "com.nepxion.discovery.plugin.admincenter.endpoint";
private String discoveryDescription = "Admin Center Restful APIs";
private String discoveryVersion = DiscoverySwaggerConstant.SWAGGER_DEFAULT_VERSION_VALUE;
private String discoveryLicenseName = DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_NAME_VALUE;
private String discoveryLicenseUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_URL_VALUE;
private String discoveryContactName = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_NAME_VALUE;
private String discoveryContactUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_URL_VALUE;
private String discoveryContactEmail = DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_EMAIL_VALUE;
private String discoveryTermsOfServiceUrl = DiscoverySwaggerConstant.SWAGGER_DEFAULT_TERMSOFSERVICE_URL_VALUE;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_GROUP + ":}")
private String serviceGroup;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_PACKAGES + ":}")
private String servicePackages;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_DESCRIPTION + ":}")
private String serviceDescription;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_VERSION + ":}")
private String serviceVersion;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_LICENSE_NAME + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_NAME_VALUE + "}")
private String serviceLicenseName;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_LICENSE_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_LICENSE_URL_VALUE + "}")
private String serviceLicenseUrl;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_NAME + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_NAME_VALUE + "}")
private String serviceContactName;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_URL_VALUE + "}")
private String serviceContactUrl;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_CONTACT_EMAIL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_CONTACT_EMAIL_VALUE + "}")
private String serviceContactEmail;
@Value("${" + DiscoverySwaggerConstant.SWAGGER_SERVICE_TERMSOFSERVICE_URL + ":" + DiscoverySwaggerConstant.SWAGGER_DEFAULT_TERMSOFSERVICE_URL_VALUE + "}")
private String serviceTermsOfServiceUrl;
@Value("${" + DiscoveryConstant.SPRING_APPLICATION_NAME + "}")
private String serviceName;
@Autowired(required = false)
private List<Parameter> swaggerHeaderParameters;
@Autowired(required = false)
private List<SecurityScheme> swaggerSecuritySchemes;
@Autowired(required = false)
private List<SecurityContext> swaggerSecurityContexts;
@Bean("discoveryDocket")
public Docket discoveryDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName(discoveryGroup)
.apiInfo(apiInfo(discoveryDescription,
discoveryVersion,
discoveryLicenseName,
discoveryLicenseUrl,
discoveryContactName,
discoveryContactUrl,
discoveryContactEmail,
discoveryTermsOfServiceUrl))
.select()
.apis(SwaggerConfiguration.basePackage(discoveryPackages)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())
.build()
.globalOperationParameters(swaggerHeaderParameters)
.securitySchemes(swaggerSecuritySchemes)
.securityContexts(swaggerSecurityContexts != null ? swaggerSecurityContexts : Collections.emptyList());
}
@Bean("serviceDocket")
@ConditionalOnProperty(name = DiscoverySwaggerConstant.SWAGGER_SERVICE_GROUP)
public Docket serviceDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName(serviceGroup)
.apiInfo(apiInfo(serviceDescription,
serviceVersion,
serviceLicenseName,
serviceLicenseUrl,
serviceContactName,
serviceContactUrl,
serviceContactEmail,
serviceTermsOfServiceUrl))
.select()
.apis(SwaggerConfiguration.basePackage(servicePackages)) // 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())
.build()
.globalOperationParameters(swaggerHeaderParameters)
.securitySchemes(swaggerSecuritySchemes)
.securityContexts(swaggerSecurityContexts != null ? swaggerSecurityContexts : Collections.emptyList());
}
private ApiInfo apiInfo(String description,
String version,
String licenseName,
String licenseUrl,
String contactName,
String contactUrl,
String contactEmail,
String termsOfServiceUrl) {
return new ApiInfoBuilder()
.title(serviceName)
.description(description)
.version(version)
.license(licenseName)
.licenseUrl(licenseUrl)
.contact(new Contact(contactName, contactUrl, contactEmail))
.termsOfServiceUrl(termsOfServiceUrl)
.build();
}
public static Predicate<RequestHandler> basePackage(String basePackage) {
return new Predicate<RequestHandler>() {
@Override
public boolean apply(RequestHandler input) {
return declaringClass(input).transform(handlerPackage(basePackage)).or(true);
}
};
}
private static Function<Class<?>, Boolean> handlerPackage(String basePackage) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("deprecation")
private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
return Optional.fromNullable(input.declaringClass());
}
} |
return new Function<Class<?>, Boolean>() {
@Override
public Boolean apply(Class<?> input) {
String[] subPackages = basePackage.split(DiscoveryConstant.SEPARATE);
for (String subPackage : subPackages) {
boolean matched = input.getPackage().getName().startsWith(subPackage.trim());
if (matched) {
return true;
}
}
return false;
}
};
| 228 | 1,680 | 121 | 1,801 |
518 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java | ConfigEndpoint | doConfigType | class ConfigEndpoint {
@Autowired
private ConfigResource configResource;
@RequestMapping(path = "/config-type", method = RequestMethod.GET)
@ApiOperation(value = "获取配置中心类型", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> configType() {
return doConfigType();
}
@RequestMapping(path = "/update-async", method = RequestMethod.POST)
@ApiOperation(value = "异步更新规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> updateAsync(@RequestBody @ApiParam(value = "规则配置内容", required = true) String config) {
return doUpdate(config, true);
}
@RequestMapping(path = "/update-sync", method = RequestMethod.POST)
@ApiOperation(value = "同步更新规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> updateSync(@RequestBody @ApiParam(value = "规则配置内容", required = true) String config) {
return doUpdate(config, false);
}
@RequestMapping(path = "/clear-async", method = RequestMethod.POST)
@ApiOperation(value = "异步清除规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> clearAsync() {
return doClear(true);
}
@RequestMapping(path = "/clear-sync", method = RequestMethod.POST)
@ApiOperation(value = "同步清除规则配置", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> clearSync() {
return doClear(false);
}
@RequestMapping(path = "/view", method = RequestMethod.GET)
@ApiOperation(value = "查看本地和更新的规则配置", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> view() {
return doView();
}
private ResponseEntity<?> doConfigType() {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doUpdate(String config, boolean async) {
try {
configResource.update(config, async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClear(boolean async) {
try {
configResource.clear(async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doView() {
try {
List<String> ruleList = configResource.view();
return ResponseUtil.getSuccessResponse(ruleList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
String configType = configResource.getConfigType().toString();
return ResponseUtil.getSuccessResponse(configType);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 784 | 60 | 844 |
519 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GatewayStrategyRouteEndpoint.java | GatewayStrategyRouteEndpoint | doView | class GatewayStrategyRouteEndpoint {
@Autowired
private GatewayStrategyRouteResource gatewayStrategyRouteResource;
@RequestMapping(path = "/add", method = RequestMethod.POST)
@ApiOperation(value = "增加网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> add(@RequestBody @ApiParam(value = "网关路由对象", required = true) GatewayStrategyRouteEntity gatewayStrategyRouteEntity) {
return doAdd(gatewayStrategyRouteEntity);
}
@RequestMapping(path = "/modify", method = RequestMethod.POST)
@ApiOperation(value = "修改网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> modify(@RequestBody @ApiParam(value = "网关路由对象", required = true) GatewayStrategyRouteEntity gatewayStrategyRouteEntity) {
return doModify(gatewayStrategyRouteEntity);
}
@RequestMapping(path = "/delete/{routeId}", method = RequestMethod.DELETE)
@ApiOperation(value = "删除网关路由", notes = "", response = ResponseEntity.class, httpMethod = "DELETE")
@ResponseBody
public ResponseEntity<?> delete(@PathVariable(value = "routeId") @ApiParam(value = "路由Id", required = true) String routeId) {
return doDelete(routeId);
}
@RequestMapping(path = "/update-all", method = RequestMethod.POST)
@ApiOperation(value = "更新全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> updateAll(@RequestBody @ApiParam(value = "网关路由对象列表", required = true) List<GatewayStrategyRouteEntity> gatewayStrategyRouteEntityList) {
return doUpdateAll(gatewayStrategyRouteEntityList);
}
@RequestMapping(path = "/view/{routeId}", method = RequestMethod.GET)
@ApiOperation(value = "根据路由Id查看网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> view(@PathVariable(value = "routeId") @ApiParam(value = "路由Id", required = true) String routeId) {
return doView(routeId);
}
@RequestMapping(path = "/view-all", method = RequestMethod.GET)
@ApiOperation(value = "查看全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> viewAll() {
return doViewAll();
}
private ResponseEntity<?> doAdd(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) {
try {
gatewayStrategyRouteResource.add(gatewayStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doModify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) {
try {
gatewayStrategyRouteResource.modify(gatewayStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doDelete(String routeId) {
try {
gatewayStrategyRouteResource.delete(routeId);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doUpdateAll(List<GatewayStrategyRouteEntity> gatewayStrategyRouteEntityList) {
try {
gatewayStrategyRouteResource.updateAll(gatewayStrategyRouteEntityList);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doView(String routeId) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doViewAll() {
try {
List<GatewayStrategyRouteEntity> gatewayStrategyRouteEntityList = gatewayStrategyRouteResource.viewAll();
return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
GatewayStrategyRouteEntity gatewayStrategyRouteEntity = gatewayStrategyRouteResource.view(routeId);
return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 1,130 | 70 | 1,200 |
520 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GitEndpoint.java | GitEndpoint | doMap | class GitEndpoint {
@Autowired
private GitResource gitResource;
@RequestMapping(path = "/map", method = RequestMethod.GET)
@ApiOperation(value = "获取Git信息的Map格式", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> map() {
return doMap();
}
@RequestMapping(path = "/text", method = RequestMethod.GET)
@ApiOperation(value = "获取Git信息的文本格式", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> text() {
return doText();
}
private ResponseEntity<?> doMap() {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doText() {
try {
String text = gitResource.text();
return ResponseUtil.getSuccessResponse(text);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
Map<String, String> map = gitResource.map();
return ResponseUtil.getSuccessResponse(map);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 76 | 270 | 59 | 329 |
521 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/InspectorEndpoint.java | InspectorEndpoint | doInspect | class InspectorEndpoint {
@Autowired
private InspectorResource inspectorResource;
@RequestMapping(path = "/inspect", method = RequestMethod.POST)
@ApiOperation(value = "侦测全链路路由", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> inspect(@RequestBody @ApiParam(value = "侦测对象", required = true) InspectorEntity inspectorEntity) {
return doInspect(inspectorEntity);
}
@RequestMapping(path = "/inspect-service", method = RequestMethod.POST)
@ApiOperation(value = "侦测全链路路由", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> inspect(@RequestBody @ApiParam(value = "侦测服务列表", required = true) List<String> service) {
return doInspect(service);
}
private ResponseEntity<?> doInspect(InspectorEntity inspectorEntity) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doInspect(List<String> service) {
try {
String result = inspectorResource.inspect(service);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
InspectorEntity result = inspectorResource.inspect(inspectorEntity);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 350 | 62 | 412 |
522 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java | RouterEndpoint | doRemoteRoute | class RouterEndpoint {
@Autowired
private RouterResource routerResource;
@RequestMapping(path = "/info", method = RequestMethod.GET)
@ApiOperation(value = "获取本地节点信息", notes = "获取当前节点的简单信息", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> info() {
return doInfo();
}
@RequestMapping(path = "/route/{routeServiceId}", method = RequestMethod.GET)
@ApiOperation(value = "获取本地节点可访问其他节点的路由信息列表", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> route(@PathVariable(value = "routeServiceId") @ApiParam(value = "目标服务名", required = true) String routeServiceId) {
return doNativeRoute(routeServiceId);
}
@RequestMapping(path = "/route/{routeServiceId}/{routeProtocol}/{routeHost}/{routePort}/{routeContextPath}", method = RequestMethod.GET)
@ApiOperation(value = "获取指定节点可访问其他节点的路由信息列表", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> route(@PathVariable(value = "routeServiceId") @ApiParam(value = "目标服务名", required = true) String routeServiceId, @PathVariable(value = "routeProtocol") @ApiParam(value = "目标服务采用的协议。取值: http | https", defaultValue = "http", required = true) String routeProtocol, @PathVariable(value = "routeHost") @ApiParam(value = "目标服务所在机器的IP地址", required = true) String routeHost, @PathVariable(value = "routePort") @ApiParam(value = "目标服务所在机器的端口号", required = true) int routePort, @PathVariable(value = "routeContextPath") @ApiParam(value = "目标服务的调用路径前缀", defaultValue = "/", required = true) String routeContextPath) {
return doRemoteRoute(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath);
}
@RequestMapping(path = "/routes", method = RequestMethod.POST)
@ApiOperation(value = "获取全路径的路由信息树", notes = "参数按调用服务名的前后次序排列,起始节点的服务名不能加上去。如果多个用“;”分隔,不允许出现空格", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> routes(@RequestBody @ApiParam(value = "格式示例:service-a;service-b", required = true) String routeServiceIds) {
return doRoutes(routeServiceIds);
}
private ResponseEntity<?> doInfo() {
try {
RouterEntity routerEntity = routerResource.getRouterEntity();
return ResponseUtil.getSuccessResponse(routerEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doNativeRoute(String routeServiceId) {
try {
List<RouterEntity> routerEntityList = routerResource.getRouterEntityList(routeServiceId);
return ResponseUtil.getSuccessResponse(routerEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doRemoteRoute(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doRoutes(String routeServiceIds) {
try {
RouterEntity routerEntity = routerResource.routeTree(routeServiceIds);
return ResponseUtil.getSuccessResponse(routerEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
List<RouterEntity> routerEntityList = routerResource.getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath);
return ResponseUtil.getSuccessResponse(routerEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 79 | 994 | 84 | 1,078 |
524 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelParamEndpoint.java | SentinelParamEndpoint | doViewParamFlowRules | class SentinelParamEndpoint {
@Autowired
private SentinelParamResource sentinelParamResource;
@RequestMapping(path = "/update-param-flow-rules", method = RequestMethod.POST)
@ApiOperation(value = "更新热点参数流控规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> updateParamFlowRules(@RequestBody @ApiParam(value = "热点参数流控规则内容,Json格式", required = true) String rule) {
return doUpdateParamFlowRules(rule);
}
@RequestMapping(path = "/clear-param-flow-rules", method = RequestMethod.POST)
@ApiOperation(value = "清除热点参数流控规则列表", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> clearParamFlowRules() {
return doClearParamFlowRules();
}
@RequestMapping(path = "/view-param-flow-rules", method = RequestMethod.GET)
@ApiOperation(value = "查看热点参数流控规则列表", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> viewParamFlowRules() {
return doViewParamFlowRules();
}
private ResponseEntity<?> doUpdateParamFlowRules(String rule) {
try {
sentinelParamResource.updateParamFlowRules(rule);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClearParamFlowRules() {
try {
sentinelParamResource.clearParamFlowRules();
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewParamFlowRules() {<FILL_FUNCTION_BODY>}
} |
try {
List<ParamFlowRule> paramFlowRules = sentinelParamResource.viewParamFlowRules();
return ResponseUtil.getSuccessResponse(paramFlowRules);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 524 | 72 | 596 |
526 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/StrategyEndpoint.java | StrategyEndpoint | doValidateExpression | class StrategyEndpoint {
@Autowired
private StrategyResource strategyResource;
@RequestMapping(path = "/validate-expression", method = RequestMethod.GET)
@ApiOperation(value = "校验策略的条件表达式", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> validateExpression(@RequestParam @ApiParam(value = "条件表达式,格式示例:#H['a'] == '1' && #H['b'] != '2'。注意,引号是否为中文格式", defaultValue = "#H['a'] == '1' && #H['b'] != '2'", required = true) String expression, @RequestParam(defaultValue = "", required = false) @ApiParam(value = "校验参数,格式示例:a=1;b=1。如果多个用“;”分隔,不允许出现空格。允许为空", defaultValue = "a=1;b=1") String validation) {
return doValidateExpression(expression, validation);
}
@RequestMapping(path = "/validate-route", method = RequestMethod.GET)
@ApiOperation(value = "校验策略的全链路路由", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> validateRoute(@RequestParam @ApiParam(value = "路由策略类型。取值:version | region | address | version-weight | region-weight | id-blacklist | address-blacklist", defaultValue = "version", required = true) String routeType, @RequestParam(defaultValue = "", required = false) @ApiParam(value = "校验参数,格式示例:a=1;b=1。如果多个用“;”分隔,不允许出现空格,允许为空。如果选择最后两项策略类型,则不需要校验参数", defaultValue = "a=1;b=1") String validation) {
return doValidateRoute(routeType, validation);
}
private ResponseEntity<?> doValidateExpression(String expression, String validation) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doValidateRoute(String routeType, String validation) {
try {
String route = strategyResource.validateRoute(routeType, validation);
return ResponseUtil.getSuccessResponse(route);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
boolean result = strategyResource.validateExpression(expression, validation);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 76 | 607 | 59 | 666 |
527 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java | VersionEndpoint | doView | class VersionEndpoint {
@Autowired
private VersionResource versionResource;
@RequestMapping(path = "/update-async", method = RequestMethod.POST)
@ApiOperation(value = "异步更新动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> updateAsync(@RequestBody @ApiParam(value = "版本号,格式为${dynamicVersion}或者${dynamicVersion};${localVersion}", required = true) String version) {
return doUpdate(version, true);
}
@RequestMapping(path = "/update-sync", method = RequestMethod.POST)
@ApiOperation(value = "同步更新动态版本", notes = "根据指定的localVersion更新服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接更新服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> updateSync(@RequestBody @ApiParam(value = "版本号,格式为${dynamicVersion}或者${dynamicVersion};${localVersion}", required = true) String version) {
return doUpdate(version, false);
}
@RequestMapping(path = "/clear-async", method = RequestMethod.POST)
@ApiOperation(value = "异步清除动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> clearAsync(@RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) {
return doClear(version, true);
}
@RequestMapping(path = "/clear-sync", method = RequestMethod.POST)
@ApiOperation(value = "同步清除动态版本", notes = "根据指定的localVersion清除服务的dynamicVersion。如果输入的localVersion不匹配服务的localVersion,则忽略;如果如果输入的localVersion为空,则直接清除服务的dynamicVersion", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> clearSync(@RequestBody(required = false) @ApiParam(value = "版本号,指localVersion,可以为空") String version) {
return doClear(version, false);
}
@RequestMapping(path = "/view", method = RequestMethod.GET)
@ApiOperation(value = "查看本地版本和动态版本", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> view() {
return doView();
}
private ResponseEntity<?> doUpdate(String version, boolean async) {
try {
versionResource.update(version, async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClear(String version, boolean async) {
try {
versionResource.clear(version, async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doView() {<FILL_FUNCTION_BODY>}
} |
try {
List<String> versionList = versionResource.view();
return ResponseUtil.getSuccessResponse(versionList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 919 | 59 | 978 |
528 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ZuulStrategyRouteEndpoint.java | ZuulStrategyRouteEndpoint | doView | class ZuulStrategyRouteEndpoint {
@Autowired
private ZuulStrategyRouteResource zuulStrategyRouteResource;
@RequestMapping(path = "/add", method = RequestMethod.POST)
@ApiOperation(value = "增加网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> add(@RequestBody @ApiParam(value = "网关路由对象", required = true) ZuulStrategyRouteEntity zuulStrategyRouteEntity) {
return doAdd(zuulStrategyRouteEntity);
}
@RequestMapping(path = "/modify", method = RequestMethod.POST)
@ApiOperation(value = "修改网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> modify(@RequestBody @ApiParam(value = "网关路由对象", required = true) ZuulStrategyRouteEntity zuulStrategyRouteEntity) {
return doModify(zuulStrategyRouteEntity);
}
@RequestMapping(path = "/delete/{routeId}", method = RequestMethod.DELETE)
@ApiOperation(value = "删除网关路由", notes = "", response = ResponseEntity.class, httpMethod = "DELETE")
@ResponseBody
public ResponseEntity<?> delete(@PathVariable(value = "routeId") @ApiParam(value = "路由Id", required = true) String routeId) {
return doDelete(routeId);
}
@RequestMapping(path = "/update-all", method = RequestMethod.POST)
@ApiOperation(value = "更新全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "POST")
@ResponseBody
public ResponseEntity<?> updateAll(@RequestBody @ApiParam(value = "网关路由对象列表", required = true) List<ZuulStrategyRouteEntity> zuulStrategyRouteEntityList) {
return doUpdateAll(zuulStrategyRouteEntityList);
}
@RequestMapping(path = "/view/{routeId}", method = RequestMethod.GET)
@ApiOperation(value = "根据路由Id查看网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> view(@PathVariable(value = "routeId") @ApiParam(value = "路由Id", required = true) String routeId) {
return doView(routeId);
}
@RequestMapping(path = "/view-all", method = RequestMethod.GET)
@ApiOperation(value = "查看全部网关路由", notes = "", response = ResponseEntity.class, httpMethod = "GET")
@ResponseBody
public ResponseEntity<?> viewAll() {
return doViewAll();
}
private ResponseEntity<?> doAdd(ZuulStrategyRouteEntity zuulStrategyRouteEntity) {
try {
zuulStrategyRouteResource.add(zuulStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doModify(ZuulStrategyRouteEntity zuulStrategyRouteEntity) {
try {
zuulStrategyRouteResource.modify(zuulStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doDelete(String routeId) {
try {
zuulStrategyRouteResource.delete(routeId);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doUpdateAll(List<ZuulStrategyRouteEntity> zuulStrategyRouteEntityList) {
try {
zuulStrategyRouteResource.updateAll(zuulStrategyRouteEntityList);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doView(String routeId) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doViewAll() {
try {
List<ZuulStrategyRouteEntity> zuulStrategyRouteEntityList = zuulStrategyRouteResource.viewAll();
return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
ZuulStrategyRouteEntity zuulStrategyRouteEntity = zuulStrategyRouteResource.view(routeId);
return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 1,167 | 76 | 1,243 |
529 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResourceImpl.java | ConfigResourceImpl | view | class ConfigResourceImpl implements ConfigResource {
private static final Logger LOG = LoggerFactory.getLogger(ConfigResourceImpl.class);
@Autowired
private PluginAdapter pluginAdapter;
@Autowired(required = false)
private PluginConfigAdapter pluginConfigAdapter;
@Autowired
private PluginEventWapper pluginEventWapper;
@Override
public ConfigType getConfigType() {
if (pluginConfigAdapter == null) {
LOG.error("Remote config adapter isn't provided");
throw new DiscoveryException("Remote config adapter isn't provided");
}
return pluginConfigAdapter.getConfigType();
}
@Override
public void update(String config, boolean async) {
pluginEventWapper.fireRuleUpdated(new RuleUpdatedEvent(SubscriptionType.PARTIAL, config), async);
}
@Override
public void clear(boolean async) {
pluginEventWapper.fireRuleCleared(new RuleClearedEvent(SubscriptionType.PARTIAL), async);
}
@Override
public List<String> view() {<FILL_FUNCTION_BODY>}
} |
List<String> ruleList = new ArrayList<String>(3);
String localRuleContent = StringUtils.EMPTY;
RuleEntity localRuleEntity = pluginAdapter.getLocalRule();
if (localRuleEntity != null && StringUtils.isNotEmpty(localRuleEntity.getContent())) {
localRuleContent = localRuleEntity.getContent();
}
String dynamicGlobalRuleContent = StringUtils.EMPTY;
RuleEntity dynamicGlobalRuleEntity = pluginAdapter.getDynamicGlobalRule();
if (dynamicGlobalRuleEntity != null && StringUtils.isNotEmpty(dynamicGlobalRuleEntity.getContent())) {
dynamicGlobalRuleContent = dynamicGlobalRuleEntity.getContent();
}
String dynamicPartialRuleContent = StringUtils.EMPTY;
RuleEntity dynamicPartialRuleEntity = pluginAdapter.getDynamicPartialRule();
if (dynamicPartialRuleEntity != null && StringUtils.isNotEmpty(dynamicPartialRuleEntity.getContent())) {
dynamicPartialRuleContent = dynamicPartialRuleEntity.getContent();
}
ruleList.add(localRuleContent);
ruleList.add(dynamicGlobalRuleContent);
ruleList.add(dynamicPartialRuleContent);
return ruleList;
| 224 | 291 | 301 | 592 |
530 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResourceImpl.java | InspectorResourceImpl | inspect | class InspectorResourceImpl implements InspectorResource {
private static final Logger LOG = LoggerFactory.getLogger(InspectorResourceImpl.class);
@Autowired
private RestTemplate pluginRestTemplate;
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private DiscoveryClient discoveryClient;
@Autowired(required = false)
private PluginContextHolder pluginContextHolder;
@Override
public InspectorEntity inspect(InspectorEntity inspectorEntity) {<FILL_FUNCTION_BODY>}
@Override
public String inspect(List<String> service) {
InspectorEntity inspectorEntity = new InspectorEntity();
inspectorEntity.setServiceIdList(service);
return inspect(inspectorEntity).getResult();
}
private ServiceInstance getInstance(String serviceId) {
List<ServiceInstance> instances = null;
try {
instances = discoveryClient.getInstances(serviceId);
} catch (Exception e) {
throw new DiscoveryException("Failed to get instance list, serviceId=" + serviceId, e);
}
if (CollectionUtils.isEmpty(instances)) {
throw new DiscoveryException("Instance list is empty, serviceId=" + serviceId);
}
return instances.get(0);
}
} |
List<String> serviceIdList = inspectorEntity.getServiceIdList();
String result = inspectorEntity.getResult();
// 第一个侦测节点,不会产生侦测信息,需要通过Header方式埋入
if (StringUtils.isEmpty(result) && pluginContextHolder != null) {
result = pluginContextHolder.getContext(DiscoveryConstant.INSPECTOR_ENDPOINT_HEADER);
}
String pluginInfo = pluginAdapter.getPluginInfo(result);
inspectorEntity.setResult(pluginInfo);
if (CollectionUtils.isNotEmpty(serviceIdList)) {
// 获取侦测列表中的第一个服务,作为下一个侦测中继节点
String nextServiceId = serviceIdList.get(0);
// 删除侦测列表中的第一个服务
serviceIdList.remove(0);
String url = null;
try {
ServiceInstance nextInstance = getInstance(nextServiceId);
String protocol = pluginAdapter.getInstanceProtocol(nextInstance);
String contextPath = pluginAdapter.getInstanceFormatContextPath(nextInstance);
url = protocol + "://" + nextServiceId + contextPath + DiscoveryConstant.INSPECTOR_ENDPOINT_URL;
// 直调方式需要走负载均衡模式下的RestTemplate
return pluginRestTemplate.postForEntity(url, inspectorEntity, InspectorEntity.class).getBody();
} catch (Exception e) {
String exceptionMessage = "Failed to inspect, current serviceId=" + pluginAdapter.getServiceId() + ", next serviceId=" + nextServiceId + ", url=" + url;
LOG.error(exceptionMessage, e);
throw new DiscoveryException(exceptionMessage, e);
}
} else {
return inspectorEntity;
}
| 433 | 332 | 443 | 775 |
531 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResourceImpl.java | RouterResourceImpl | routeTree | class RouterResourceImpl implements RouterResource {
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private ServiceResource serviceResource;
private RestTemplate routerRestTemplate;
public RouterResourceImpl() {
routerRestTemplate = new RestTemplate();
}
@Override
public RouterEntity getRouterEntity() {
String serviceType = pluginAdapter.getServiceType();
String serviceId = pluginAdapter.getServiceId();
String version = pluginAdapter.getVersion();
String region = pluginAdapter.getRegion();
String environment = pluginAdapter.getEnvironment();
String zone = pluginAdapter.getZone();
String host = pluginAdapter.getHost();
int port = pluginAdapter.getPort();
int weight = -1;
String protocol = pluginAdapter.getProtocol();
String contextPath = pluginAdapter.getFormatContextPath();
RouterEntity routerEntity = new RouterEntity();
routerEntity.setServiceType(serviceType);
routerEntity.setServiceId(serviceId);
routerEntity.setVersion(version);
routerEntity.setRegion(region);
routerEntity.setEnvironment(environment);
routerEntity.setZone(zone);
routerEntity.setHost(host);
routerEntity.setPort(port);
routerEntity.setWeight(weight);
routerEntity.setProtocol(protocol);
routerEntity.setContextPath(contextPath);
return routerEntity;
}
@Override
public List<RouterEntity> getRouterEntityList(String routeServiceId) {
List<ServiceInstance> instanceList = null;
try {
instanceList = serviceResource.getInstances(routeServiceId);
} catch (Exception e) {
throw new DiscoveryException("Get instance list for route serviceId=" + routeServiceId + " failed", e);
}
if (CollectionUtils.isEmpty(instanceList)) {
return null;
}
List<RouterEntity> routerEntityList = new ArrayList<RouterEntity>();
for (ServiceInstance instance : instanceList) {
String serviceId = pluginAdapter.getInstanceServiceId(instance);
String serviceType = pluginAdapter.getInstanceServiceType(instance);
String version = pluginAdapter.getInstanceVersion(instance);
String region = pluginAdapter.getInstanceRegion(instance);
String environment = pluginAdapter.getInstanceEnvironment(instance);
String zone = pluginAdapter.getInstanceZone(instance);
String host = instance.getHost();
int port = instance.getPort();
int weight = getWeight(routeServiceId, version, region);
String protocol = pluginAdapter.getInstanceProtocol(instance);
String contextPath = pluginAdapter.getInstanceFormatContextPath(instance);
RouterEntity routerEntity = new RouterEntity();
routerEntity.setServiceType(serviceType);
routerEntity.setServiceId(serviceId);
routerEntity.setVersion(version);
routerEntity.setRegion(region);
routerEntity.setEnvironment(environment);
routerEntity.setZone(zone);
routerEntity.setHost(host);
routerEntity.setPort(port);
routerEntity.setWeight(weight);
routerEntity.setProtocol(protocol);
routerEntity.setContextPath(contextPath);
routerEntityList.add(routerEntity);
}
return routerEntityList;
}
@Override
public List<RouterEntity> getRouterEntityList(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) {
String url = routeProtocol + "://" + routeHost + ":" + routePort + routeContextPath + "router/route/" + routeServiceId;
String result = null;
try {
result = routerRestTemplate.getForEntity(url, String.class).getBody();
} catch (RestClientException e) {
throw new DiscoveryException("Failed to execute to route, serviceId=" + routeServiceId + ", url=" + url, e);
}
if (StringUtils.isEmpty(result)) {
return null;
}
List<RouterEntity> routerEntityList = JsonUtil.fromJson(result, new TypeReference<List<RouterEntity>>() {
});
return routerEntityList;
}
@Override
public RouterEntity routeTree(String routeServiceIds) {<FILL_FUNCTION_BODY>}
private void routeFirst(RouterEntity routerEntity, String routeServiceId) {
List<RouterEntity> routerEntityList = getRouterEntityList(routeServiceId);
if (CollectionUtils.isNotEmpty(routerEntityList)) {
routerEntity.getNexts().addAll(routerEntityList);
}
}
private void route(RouterEntity routerEntity, String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) {
List<RouterEntity> routerEntityList = getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath);
if (CollectionUtils.isNotEmpty(routerEntityList)) {
routerEntity.getNexts().addAll(routerEntityList);
}
}
private List<RouterEntity> retrieveRouterEntityList(HashMap<Integer, List<RouterEntity>> routerEntityMap, int routerDepth) {
List<RouterEntity> routerEntityList = routerEntityMap.get(routerDepth);
if (routerEntityList == null) {
routerEntityList = new ArrayList<RouterEntity>();
routerEntityMap.put(routerDepth, routerEntityList);
}
return routerEntityList;
}
private int getWeight(String providerServiceId, String providerVersion, String providerRegion) {
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return -1;
}
DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return -1;
}
WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity();
if (weightFilterEntity == null || !weightFilterEntity.hasWeight()) {
return -1;
}
String serviceId = pluginAdapter.getServiceId();
return WeightEntityWrapper.getWeight(weightFilterEntity, providerServiceId, providerVersion, providerRegion, serviceId);
}
} |
if (StringUtils.isEmpty(routeServiceIds)) {
throw new DiscoveryException("Route serviceIds is empty");
}
String[] serviceIdArray = null;
try {
serviceIdArray = StringUtils.split(routeServiceIds, DiscoveryConstant.SEPARATE);
} catch (Exception e) {
throw new DiscoveryException("Route serviceIds must be separated with '" + DiscoveryConstant.SEPARATE + "'", e);
}
RouterEntity firstRouterEntity = getRouterEntity();
// 路由深度为Key
HashMap<Integer, List<RouterEntity>> routerEntityMap = new HashMap<Integer, List<RouterEntity>>();
int routerDepth = 0;
for (String serviceId : serviceIdArray) {
serviceId = serviceId.toLowerCase().trim();
if (routerDepth == 0) {
routeFirst(firstRouterEntity, serviceId);
retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(firstRouterEntity.getNexts());
} else {
List<RouterEntity> routerEntityList = retrieveRouterEntityList(routerEntityMap, routerDepth - 1);
for (RouterEntity routerEntity : routerEntityList) {
String routeHost = routerEntity.getHost();
int routePort = routerEntity.getPort();
String routeProtocol = routerEntity.getProtocol();
String routeContextPath = routerEntity.getContextPath();
route(routerEntity, serviceId, routeProtocol, routeHost, routePort, routeContextPath);
retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(routerEntity.getNexts());
}
}
routerDepth++;
}
return firstRouterEntity;
| 494 | 1,553 | 428 | 1,981 |
533 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResourceImpl.java | StrategyResourceImpl | validateRoute | class StrategyResourceImpl implements StrategyResource {
@Autowired
private StrategyCondition strategyCondition;
@Autowired
private StrategyWrapper strategyWrapper;
@Value("${" + AdminConstant.SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_VALIDATE_EXPRESSION_ENABLED + ":true}")
private Boolean validateExpressionEnabled;
@Override
public boolean validateExpression(String expression, String validation) {
if (!validateExpressionEnabled) {
throw new DiscoveryException("Strategy endpoint for validate-expression is disabled");
}
StrategyConditionEntity strategyConditionEntity = new StrategyConditionEntity();
strategyConditionEntity.setExpression(expression);
Map<String, String> map = null;
try {
map = StringUtil.splitToMap(validation);
} catch (Exception e) {
throw new DiscoveryException("Invalid format for validation input");
}
return strategyCondition.isTriggered(strategyConditionEntity, map);
}
@Override
public String validateRoute(String routeType, String validation) {<FILL_FUNCTION_BODY>}
} |
StrategyRouteType strategyRouteType = StrategyRouteType.fromString(routeType);
Map<String, String> map = null;
try {
map = StringUtil.splitToMap(validation);
} catch (Exception e) {
throw new DiscoveryException("Invalid format for validation input");
}
String route = null;
switch (strategyRouteType) {
case VERSION:
route = strategyWrapper.getRouteVersion(map);
break;
case REGION:
route = strategyWrapper.getRouteRegion(map);
break;
case ADDRESS:
route = strategyWrapper.getRouteAddress(map);
break;
case VERSION_WEIGHT:
route = strategyWrapper.getRouteVersionWeight(map);
break;
case REGION_WEIGHT:
route = strategyWrapper.getRouteRegionWeight(map);
break;
case ID_BLACKLIST:
route = strategyWrapper.getRouteIdBlacklist();
break;
case ADDRESS_BLACKLIST:
route = strategyWrapper.getRouteAddressBlacklist();
break;
}
if (StringUtils.isEmpty(route)) {
throw new DiscoveryException("Not found any " + routeType + " routes");
}
return route;
| 496 | 286 | 322 | 608 |
534 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter-swagger/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResourceImpl.java | VersionResourceImpl | update | class VersionResourceImpl implements VersionResource {
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private PluginEventWapper pluginEventWapper;
@Override
public void update(String version, boolean async) {<FILL_FUNCTION_BODY>}
@Override
public void clear(String version, boolean async) {
// 修复Swagger的一个Bug,当在Swagger界面不输入版本号的时候,传到后端变成了“{}”
if (StringUtils.isNotEmpty(version) && StringUtils.equals(version.trim(), "{}")) {
version = null;
}
pluginEventWapper.fireVersionCleared(new VersionClearedEvent(version), async);
}
@Override
public List<String> view() {
List<String> versionList = new ArrayList<String>(2);
String localVersion = pluginAdapter.getLocalVersion();
String dynamicVersion = pluginAdapter.getDynamicVersion();
versionList.add(StringUtils.isNotEmpty(localVersion) ? localVersion : StringUtils.EMPTY);
versionList.add(StringUtils.isNotEmpty(dynamicVersion) ? dynamicVersion : StringUtils.EMPTY);
return versionList;
}
} |
if (StringUtils.isEmpty(version)) {
throw new DiscoveryException("Version can't be null or empty");
}
String dynamicVersion = null;
String localVersion = null;
String[] versionArray = StringUtils.split(version, DiscoveryConstant.SEPARATE);
if (versionArray.length == 2) {
dynamicVersion = versionArray[0];
localVersion = versionArray[1];
} else if (versionArray.length == 1) {
dynamicVersion = versionArray[0];
} else {
throw new DiscoveryException("Invalid version format, it must be '${dynamicVersion}' or '${dynamicVersion};${localVersion}'");
}
pluginEventWapper.fireVersionUpdated(new VersionUpdatedEvent(dynamicVersion, localVersion), async);
| 195 | 316 | 198 | 514 |
535 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java | ConfigEndpoint | doConfigType | class ConfigEndpoint {
@Autowired
private ConfigResource configResource;
@RequestMapping(path = "/config-type", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> configType() {
return doConfigType();
}
@RequestMapping(path = "/update-async", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateAsync(@RequestBody String config) {
return doUpdate(config, true);
}
@RequestMapping(path = "/update-sync", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateSync(@RequestBody String config) {
return doUpdate(config, false);
}
@RequestMapping(path = "/clear-async", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearAsync() {
return doClear(true);
}
@RequestMapping(path = "/clear-sync", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearSync() {
return doClear(false);
}
@RequestMapping(path = "/view", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> view() {
return doView();
}
private ResponseEntity<?> doConfigType() {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doUpdate(String config, boolean async) {
try {
configResource.update(config, async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClear(boolean async) {
try {
configResource.clear(async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doView() {
try {
List<String> ruleList = configResource.view();
return ResponseUtil.getSuccessResponse(ruleList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
String configType = configResource.getConfigType().toString();
return ResponseUtil.getSuccessResponse(configType);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 564 | 60 | 624 |
536 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GatewayStrategyRouteEndpoint.java | GatewayStrategyRouteEndpoint | doView | class GatewayStrategyRouteEndpoint {
@Autowired
private GatewayStrategyRouteResource gatewayStrategyRouteResource;
@RequestMapping(path = "/add", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> add(@RequestBody GatewayStrategyRouteEntity gatewayStrategyRouteEntity) {
return doAdd(gatewayStrategyRouteEntity);
}
@RequestMapping(path = "/modify", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> modify(@RequestBody GatewayStrategyRouteEntity gatewayStrategyRouteEntity) {
return doModify(gatewayStrategyRouteEntity);
}
@RequestMapping(path = "/delete/{routeId}", method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<?> delete(@PathVariable(value = "routeId") String routeId) {
return doDelete(routeId);
}
@RequestMapping(path = "/update-all", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateAll(@RequestBody List<GatewayStrategyRouteEntity> gatewayStrategyRouteEntityList) {
return doUpdateAll(gatewayStrategyRouteEntityList);
}
@RequestMapping(path = "/view/{routeId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> view(@PathVariable(value = "routeId") String routeId) {
return doView(routeId);
}
@RequestMapping(path = "/view-all", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> viewAll() {
return doViewAll();
}
private ResponseEntity<?> doAdd(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) {
try {
gatewayStrategyRouteResource.add(gatewayStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doModify(GatewayStrategyRouteEntity gatewayStrategyRouteEntity) {
try {
gatewayStrategyRouteResource.modify(gatewayStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doDelete(String routeId) {
try {
gatewayStrategyRouteResource.delete(routeId);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doUpdateAll(List<GatewayStrategyRouteEntity> gatewayStrategyRouteEntityList) {
try {
gatewayStrategyRouteResource.updateAll(gatewayStrategyRouteEntityList);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doView(String routeId) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doViewAll() {
try {
List<GatewayStrategyRouteEntity> gatewayStrategyRouteEntityList = gatewayStrategyRouteResource.viewAll();
return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
GatewayStrategyRouteEntity gatewayStrategyRouteEntity = gatewayStrategyRouteResource.view(routeId);
return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 852 | 70 | 922 |
537 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GitEndpoint.java | GitEndpoint | doMap | class GitEndpoint {
@Autowired
private GitResource gitResource;
@RequestMapping(path = "/map", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> map() {
return doMap();
}
@RequestMapping(path = "/text", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> text() {
return doText();
}
private ResponseEntity<?> doMap() {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doText() {
try {
String text = gitResource.text();
return ResponseUtil.getSuccessResponse(text);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
Map<String, String> map = gitResource.map();
return ResponseUtil.getSuccessResponse(map);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 76 | 201 | 59 | 260 |
538 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/InspectorEndpoint.java | InspectorEndpoint | doInspect | class InspectorEndpoint {
@Autowired
private InspectorResource inspectorResource;
@RequestMapping(path = "/inspect", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> inspect(@RequestBody InspectorEntity inspectorEntity) {
return doInspect(inspectorEntity);
}
@RequestMapping(path = "/inspect-service", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> inspect(@RequestBody List<String> service) {
return doInspect(service);
}
private ResponseEntity<?> doInspect(InspectorEntity inspectorEntity) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doInspect(List<String> service) {
try {
String result = inspectorResource.inspect(service);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
InspectorEntity result = inspectorResource.inspect(inspectorEntity);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 252 | 62 | 314 |
539 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java | RouterEndpoint | doRemoteRoute | class RouterEndpoint {
@Autowired
private RouterResource routerResource;
@RequestMapping(path = "/info", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> info() {
return doInfo();
}
@RequestMapping(path = "/route/{routeServiceId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> route(@PathVariable(value = "routeServiceId") String routeServiceId) {
return doNativeRoute(routeServiceId);
}
@RequestMapping(path = "/route/{routeServiceId}/{routeProtocol}/{routeHost}/{routePort}/{routeContextPath}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> route(@PathVariable(value = "routeServiceId") String routeServiceId, @PathVariable(value = "routeProtocol") String routeProtocol, @PathVariable(value = "routeHost") String routeHost, @PathVariable(value = "routePort") int routePort, @PathVariable(value = "routeContextPath") String routeContextPath) {
return doRemoteRoute(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath);
}
@RequestMapping(path = "/routes", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> routes(@RequestBody String routeServiceIds) {
return doRoutes(routeServiceIds);
}
private ResponseEntity<?> doInfo() {
try {
RouterEntity routerEntity = routerResource.getRouterEntity();
return ResponseUtil.getSuccessResponse(routerEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doNativeRoute(String routeServiceId) {
try {
List<RouterEntity> routerEntityList = routerResource.getRouterEntityList(routeServiceId);
return ResponseUtil.getSuccessResponse(routerEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doRemoteRoute(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doRoutes(String routeServiceIds) {
try {
RouterEntity routerEntity = routerResource.routeTree(routeServiceIds);
return ResponseUtil.getSuccessResponse(routerEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
List<RouterEntity> routerEntityList = routerResource.getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath);
return ResponseUtil.getSuccessResponse(routerEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 79 | 646 | 84 | 730 |
540 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelCoreEndpoint.java | SentinelCoreEndpoint | doViewFlowRules | class SentinelCoreEndpoint {
@Autowired
private SentinelCoreResource sentinelCoreResource;
@RequestMapping(path = "/update-flow-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateFlowRules(@RequestBody String rule) {
return doUpdateFlowRules(rule);
}
@RequestMapping(path = "/clear-flow-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearFlowRules() {
return doClearFlowRules();
}
@RequestMapping(path = "/view-flow-rules", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> viewFlowRules() {
return doViewFlowRules();
}
@RequestMapping(path = "/update-degrade-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateDegradeRules(@RequestBody String rule) {
return doUpdateDegradeRules(rule);
}
@RequestMapping(path = "/clear-degrade-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearDegradeRules() {
return doClearDegradeRules();
}
@RequestMapping(path = "/view-degrade-rules", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> viewDegradeRules() {
return doViewDegradeRules();
}
@RequestMapping(path = "/update-authority-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateAuthorityRules(@RequestBody String rule) {
return doUpdateAuthorityRules(rule);
}
@RequestMapping(path = "/clear-authority-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearAuthorityRules() {
return doClearAuthorityRules();
}
@RequestMapping(path = "/view-authority-rules", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> viewAuthorityRules() {
return doViewAuthorityRules();
}
@RequestMapping(path = "/update-system-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateSystemRules(@RequestBody String rule) {
return doUpdateSystemRules(rule);
}
@RequestMapping(path = "/clear-system-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearSystemRules() {
return doClearSystemRules();
}
@RequestMapping(path = "/view-system-rules", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> viewSystemRules() {
return doViewSystemRules();
}
private ResponseEntity<?> doUpdateFlowRules(String rule) {
try {
sentinelCoreResource.updateFlowRules(rule);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClearFlowRules() {
try {
sentinelCoreResource.clearFlowRules();
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewFlowRules() {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doUpdateDegradeRules(String rule) {
try {
sentinelCoreResource.updateDegradeRules(rule);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClearDegradeRules() {
try {
sentinelCoreResource.clearDegradeRules();
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewDegradeRules() {
try {
List<DegradeRule> degradeRules = sentinelCoreResource.viewDegradeRules();
return ResponseUtil.getSuccessResponse(degradeRules);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doUpdateAuthorityRules(String rule) {
try {
sentinelCoreResource.updateAuthorityRules(rule);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClearAuthorityRules() {
try {
sentinelCoreResource.clearAuthorityRules();
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewAuthorityRules() {
try {
List<AuthorityRule> authorityRules = sentinelCoreResource.viewAuthorityRules();
return ResponseUtil.getSuccessResponse(authorityRules);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doUpdateSystemRules(String rule) {
try {
sentinelCoreResource.updateSystemRules(rule);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClearSystemRules() {
try {
sentinelCoreResource.clearSystemRules();
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewSystemRules() {
try {
List<SystemRule> systemRules = sentinelCoreResource.viewSystemRules();
return ResponseUtil.getSuccessResponse(systemRules);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
List<FlowRule> flowRules = sentinelCoreResource.viewFlowRules();
return ResponseUtil.getSuccessResponse(flowRules);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 1,638 | 68 | 1,706 |
541 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelParamEndpoint.java | SentinelParamEndpoint | doViewParamFlowRules | class SentinelParamEndpoint {
@Autowired
private SentinelParamResource sentinelParamResource;
@RequestMapping(path = "/update-param-flow-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateParamFlowRules(@RequestBody String rule) {
return doUpdateParamFlowRules(rule);
}
@RequestMapping(path = "/clear-param-flow-rules", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearParamFlowRules() {
return doClearParamFlowRules();
}
@RequestMapping(path = "/view-param-flow-rules", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> viewParamFlowRules() {
return doViewParamFlowRules();
}
private ResponseEntity<?> doUpdateParamFlowRules(String rule) {
try {
sentinelParamResource.updateParamFlowRules(rule);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClearParamFlowRules() {
try {
sentinelParamResource.clearParamFlowRules();
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewParamFlowRules() {<FILL_FUNCTION_BODY>}
} |
try {
List<ParamFlowRule> paramFlowRules = sentinelParamResource.viewParamFlowRules();
return ResponseUtil.getSuccessResponse(paramFlowRules);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 395 | 72 | 467 |
542 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ServiceEndpoint.java | ServiceEndpoint | doServiceList | class ServiceEndpoint {
@Autowired
private ServiceResource serviceResource;
@RequestMapping(path = "/discovery-type", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> discoveryType() {
return doDiscoveryType();
}
@RequestMapping(path = "/groups", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> groups() {
return doGroups();
}
@RequestMapping(path = "/group/{serviceId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> group(@PathVariable(value = "serviceId") String serviceId) {
return doGroup(serviceId);
}
@RequestMapping(path = "/services", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> services() {
return doServices();
}
@RequestMapping(path = "/service-list", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> serviceList(@RequestBody List<String> serviceTypes) {
return doServiceList(serviceTypes);
}
@RequestMapping(path = "/service-list/{group}", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> serviceList(@PathVariable(value = "group") String group, @RequestBody List<String> serviceTypes) {
return doServiceList(group, serviceTypes);
}
@RequestMapping(path = "/gateways", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> gateways() {
return doGateways();
}
@RequestMapping(path = "/gateway-list", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> gatewayList(@RequestBody List<String> gatewayTypes) {
return doGatewayList(gatewayTypes);
}
@RequestMapping(path = "/instances/{serviceId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> instances(@PathVariable(value = "serviceId") String serviceId) {
return doInstances(serviceId);
}
@RequestMapping(path = "/instance-list/{serviceId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> instanceList(@PathVariable(value = "serviceId") String serviceId) {
return doInstanceList(serviceId);
}
@RequestMapping(path = "/instance-map", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> instanceMap(@RequestBody List<String> groups) {
return doInstanceMap(groups);
}
private ResponseEntity<?> doDiscoveryType() {
try {
String discoveryType = serviceResource.getDiscoveryType().toString();
return ResponseUtil.getSuccessResponse(discoveryType);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doGroups() {
try {
List<String> groups = serviceResource.getGroups();
return ResponseUtil.getSuccessResponse(groups);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doGroup(String serviceId) {
try {
String group = serviceResource.getGroup(serviceId);
return ResponseUtil.getSuccessResponse(group);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doServices() {
try {
List<String> services = serviceResource.getServices();
return ResponseUtil.getSuccessResponse(services);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doServiceList(List<String> serviceTypes) {
try {
List<ServiceType> types = new ArrayList<ServiceType>();
for (String serviceType : serviceTypes) {
types.add(ServiceType.fromString(serviceType));
}
List<String> services = serviceResource.getServiceList(types);
return ResponseUtil.getSuccessResponse(services);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doServiceList(String group, List<String> serviceTypes) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doGateways() {
try {
List<String> gateways = serviceResource.getGateways();
return ResponseUtil.getSuccessResponse(gateways);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doGatewayList(List<String> gatewayTypes) {
try {
List<GatewayType> types = new ArrayList<GatewayType>();
for (String gatewayType : gatewayTypes) {
types.add(GatewayType.fromString(gatewayType));
}
List<String> gatewayList = serviceResource.getGatewayList(types);
return ResponseUtil.getSuccessResponse(gatewayList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doInstances(String serviceId) {
try {
List<ServiceInstance> instances = serviceResource.getInstances(serviceId);
return ResponseUtil.getSuccessResponse(instances);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doInstanceList(String serviceId) {
try {
List<InstanceEntity> instanceList = serviceResource.getInstanceList(serviceId);
return ResponseUtil.getSuccessResponse(instanceList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doInstanceMap(List<String> groups) {
try {
Map<String, List<InstanceEntity>> instanceMaps = serviceResource.getInstanceMap(groups);
return ResponseUtil.getSuccessResponse(instanceMaps);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
List<ServiceType> types = new ArrayList<ServiceType>();
for (String serviceType : serviceTypes) {
types.add(ServiceType.fromString(serviceType));
}
List<String> services = serviceResource.getServiceList(group, types);
return ResponseUtil.getSuccessResponse(services);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 137 | 1,596 | 110 | 1,706 |
543 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/StrategyEndpoint.java | StrategyEndpoint | doValidateExpression | class StrategyEndpoint {
@Autowired
private StrategyResource strategyResource;
@RequestMapping(path = "/validate-expression", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> validateExpression(@RequestParam String expression, @RequestParam(defaultValue = "", required = false) String validation) {
return doValidateExpression(expression, validation);
}
@RequestMapping(path = "/validate-route", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> validateRoute(@RequestParam String routeType, @RequestParam(defaultValue = "", required = false) String validation) {
return doValidateRoute(routeType, validation);
}
private ResponseEntity<?> doValidateExpression(String expression, String validation) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doValidateRoute(String routeType, String validation) {
try {
String route = strategyResource.validateRoute(routeType, validation);
return ResponseUtil.getSuccessResponse(route);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
boolean result = strategyResource.validateExpression(expression, validation);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 76 | 286 | 59 | 345 |
544 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/VersionEndpoint.java | VersionEndpoint | doView | class VersionEndpoint {
@Autowired
private VersionResource versionResource;
@RequestMapping(path = "/update-async", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateAsync(@RequestBody String version) {
return doUpdate(version, true);
}
@RequestMapping(path = "/update-sync", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateSync(@RequestBody String version) {
return doUpdate(version, false);
}
@RequestMapping(path = "/clear-async", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearAsync(@RequestBody(required = false) String version) {
return doClear(version, true);
}
@RequestMapping(path = "/clear-sync", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> clearSync(@RequestBody(required = false) String version) {
return doClear(version, false);
}
@RequestMapping(path = "/view", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> view() {
return doView();
}
private ResponseEntity<?> doUpdate(String version, boolean async) {
try {
versionResource.update(version, async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClear(String version, boolean async) {
try {
versionResource.clear(version, async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doView() {<FILL_FUNCTION_BODY>}
} |
try {
List<String> versionList = versionResource.view();
return ResponseUtil.getSuccessResponse(versionList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 472 | 59 | 531 |
545 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ZuulStrategyRouteEndpoint.java | ZuulStrategyRouteEndpoint | doView | class ZuulStrategyRouteEndpoint {
@Autowired
private ZuulStrategyRouteResource zuulStrategyRouteResource;
@RequestMapping(path = "/add", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> add(@RequestBody ZuulStrategyRouteEntity zuulStrategyRouteEntity) {
return doAdd(zuulStrategyRouteEntity);
}
@RequestMapping(path = "/modify", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> modify(@RequestBody ZuulStrategyRouteEntity zuulStrategyRouteEntity) {
return doModify(zuulStrategyRouteEntity);
}
@RequestMapping(path = "/delete/{routeId}", method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<?> delete(@PathVariable(value = "routeId") String routeId) {
return doDelete(routeId);
}
@RequestMapping(path = "/update-all", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> updateAll(@RequestBody List<ZuulStrategyRouteEntity> zuulStrategyRouteEntityList) {
return doUpdateAll(zuulStrategyRouteEntityList);
}
@RequestMapping(path = "/view/{routeId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> view(@PathVariable(value = "routeId") String routeId) {
return doView(routeId);
}
@RequestMapping(path = "/view-all", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> viewAll() {
return doViewAll();
}
private ResponseEntity<?> doAdd(ZuulStrategyRouteEntity zuulStrategyRouteEntity) {
try {
zuulStrategyRouteResource.add(zuulStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doModify(ZuulStrategyRouteEntity zuulStrategyRouteEntity) {
try {
zuulStrategyRouteResource.modify(zuulStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doDelete(String routeId) {
try {
zuulStrategyRouteResource.delete(routeId);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doUpdateAll(List<ZuulStrategyRouteEntity> zuulStrategyRouteEntityList) {
try {
zuulStrategyRouteResource.updateAll(zuulStrategyRouteEntityList);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doView(String routeId) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doViewAll() {
try {
List<ZuulStrategyRouteEntity> zuulStrategyRouteEntityList = zuulStrategyRouteResource.viewAll();
return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
ZuulStrategyRouteEntity zuulStrategyRouteEntity = zuulStrategyRouteResource.view(routeId);
return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 75 | 889 | 76 | 965 |
546 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/ConfigResourceImpl.java | ConfigResourceImpl | view | class ConfigResourceImpl implements ConfigResource {
private static final Logger LOG = LoggerFactory.getLogger(ConfigResourceImpl.class);
@Autowired
private PluginAdapter pluginAdapter;
@Autowired(required = false)
private PluginConfigAdapter pluginConfigAdapter;
@Autowired
private PluginEventWapper pluginEventWapper;
@Override
public ConfigType getConfigType() {
if (pluginConfigAdapter == null) {
LOG.error("Remote config adapter isn't provided");
throw new DiscoveryException("Remote config adapter isn't provided");
}
return pluginConfigAdapter.getConfigType();
}
@Override
public void update(String config, boolean async) {
pluginEventWapper.fireRuleUpdated(new RuleUpdatedEvent(SubscriptionType.PARTIAL, config), async);
}
@Override
public void clear(boolean async) {
pluginEventWapper.fireRuleCleared(new RuleClearedEvent(SubscriptionType.PARTIAL), async);
}
@Override
public List<String> view() {<FILL_FUNCTION_BODY>}
} |
List<String> ruleList = new ArrayList<String>(3);
String localRuleContent = StringUtils.EMPTY;
RuleEntity localRuleEntity = pluginAdapter.getLocalRule();
if (localRuleEntity != null && StringUtils.isNotEmpty(localRuleEntity.getContent())) {
localRuleContent = localRuleEntity.getContent();
}
String dynamicGlobalRuleContent = StringUtils.EMPTY;
RuleEntity dynamicGlobalRuleEntity = pluginAdapter.getDynamicGlobalRule();
if (dynamicGlobalRuleEntity != null && StringUtils.isNotEmpty(dynamicGlobalRuleEntity.getContent())) {
dynamicGlobalRuleContent = dynamicGlobalRuleEntity.getContent();
}
String dynamicPartialRuleContent = StringUtils.EMPTY;
RuleEntity dynamicPartialRuleEntity = pluginAdapter.getDynamicPartialRule();
if (dynamicPartialRuleEntity != null && StringUtils.isNotEmpty(dynamicPartialRuleEntity.getContent())) {
dynamicPartialRuleContent = dynamicPartialRuleEntity.getContent();
}
ruleList.add(localRuleContent);
ruleList.add(dynamicGlobalRuleContent);
ruleList.add(dynamicPartialRuleContent);
return ruleList;
| 224 | 291 | 301 | 592 |
547 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResourceImpl.java | InspectorResourceImpl | inspect | class InspectorResourceImpl implements InspectorResource {
private static final Logger LOG = LoggerFactory.getLogger(InspectorResourceImpl.class);
@Autowired
private RestTemplate pluginRestTemplate;
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private DiscoveryClient discoveryClient;
@Autowired(required = false)
private PluginContextHolder pluginContextHolder;
@Override
public InspectorEntity inspect(InspectorEntity inspectorEntity) {<FILL_FUNCTION_BODY>}
@Override
public String inspect(List<String> service) {
InspectorEntity inspectorEntity = new InspectorEntity();
inspectorEntity.setServiceIdList(service);
return inspect(inspectorEntity).getResult();
}
private ServiceInstance getInstance(String serviceId) {
List<ServiceInstance> instances = null;
try {
instances = discoveryClient.getInstances(serviceId);
} catch (Exception e) {
throw new DiscoveryException("Failed to get instance list, serviceId=" + serviceId, e);
}
if (CollectionUtils.isEmpty(instances)) {
throw new DiscoveryException("Instance list is empty, serviceId=" + serviceId);
}
return instances.get(0);
}
} |
List<String> serviceIdList = inspectorEntity.getServiceIdList();
String result = inspectorEntity.getResult();
// 第一个侦测节点,不会产生侦测信息,需要通过Header方式埋入
if (StringUtils.isEmpty(result) && pluginContextHolder != null) {
result = pluginContextHolder.getContext(DiscoveryConstant.INSPECTOR_ENDPOINT_HEADER);
}
String pluginInfo = pluginAdapter.getPluginInfo(result);
inspectorEntity.setResult(pluginInfo);
if (CollectionUtils.isNotEmpty(serviceIdList)) {
// 获取侦测列表中的第一个服务,作为下一个侦测中继节点
String nextServiceId = serviceIdList.get(0);
// 删除侦测列表中的第一个服务
serviceIdList.remove(0);
String url = null;
try {
ServiceInstance nextInstance = getInstance(nextServiceId);
String protocol = pluginAdapter.getInstanceProtocol(nextInstance);
String contextPath = pluginAdapter.getInstanceFormatContextPath(nextInstance);
url = protocol + "://" + nextServiceId + contextPath + DiscoveryConstant.INSPECTOR_ENDPOINT_URL;
// 直调方式需要走负载均衡模式下的RestTemplate
return pluginRestTemplate.postForEntity(url, inspectorEntity, InspectorEntity.class).getBody();
} catch (Exception e) {
String exceptionMessage = "Failed to inspect, current serviceId=" + pluginAdapter.getServiceId() + ", next serviceId=" + nextServiceId + ", url=" + url;
LOG.error(exceptionMessage, e);
throw new DiscoveryException(exceptionMessage, e);
}
} else {
return inspectorEntity;
}
| 433 | 332 | 443 | 775 |
548 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResourceImpl.java | RouterResourceImpl | routeTree | class RouterResourceImpl implements RouterResource {
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private ServiceResource serviceResource;
private RestTemplate routerRestTemplate;
public RouterResourceImpl() {
routerRestTemplate = new RestTemplate();
}
@Override
public RouterEntity getRouterEntity() {
String serviceType = pluginAdapter.getServiceType();
String serviceId = pluginAdapter.getServiceId();
String version = pluginAdapter.getVersion();
String region = pluginAdapter.getRegion();
String environment = pluginAdapter.getEnvironment();
String zone = pluginAdapter.getZone();
String host = pluginAdapter.getHost();
int port = pluginAdapter.getPort();
int weight = -1;
String protocol = pluginAdapter.getProtocol();
String contextPath = pluginAdapter.getFormatContextPath();
RouterEntity routerEntity = new RouterEntity();
routerEntity.setServiceType(serviceType);
routerEntity.setServiceId(serviceId);
routerEntity.setVersion(version);
routerEntity.setRegion(region);
routerEntity.setEnvironment(environment);
routerEntity.setZone(zone);
routerEntity.setHost(host);
routerEntity.setPort(port);
routerEntity.setWeight(weight);
routerEntity.setProtocol(protocol);
routerEntity.setContextPath(contextPath);
return routerEntity;
}
@Override
public List<RouterEntity> getRouterEntityList(String routeServiceId) {
List<ServiceInstance> instanceList = null;
try {
instanceList = serviceResource.getInstances(routeServiceId);
} catch (Exception e) {
throw new DiscoveryException("Get instance list for route serviceId=" + routeServiceId + " failed", e);
}
if (CollectionUtils.isEmpty(instanceList)) {
return null;
}
List<RouterEntity> routerEntityList = new ArrayList<RouterEntity>();
for (ServiceInstance instance : instanceList) {
String serviceId = pluginAdapter.getInstanceServiceId(instance);
String serviceType = pluginAdapter.getInstanceServiceType(instance);
String version = pluginAdapter.getInstanceVersion(instance);
String region = pluginAdapter.getInstanceRegion(instance);
String environment = pluginAdapter.getInstanceEnvironment(instance);
String zone = pluginAdapter.getInstanceZone(instance);
String host = instance.getHost();
int port = instance.getPort();
int weight = getWeight(routeServiceId, version, region);
String protocol = pluginAdapter.getInstanceProtocol(instance);
String contextPath = pluginAdapter.getInstanceFormatContextPath(instance);
RouterEntity routerEntity = new RouterEntity();
routerEntity.setServiceType(serviceType);
routerEntity.setServiceId(serviceId);
routerEntity.setVersion(version);
routerEntity.setRegion(region);
routerEntity.setEnvironment(environment);
routerEntity.setZone(zone);
routerEntity.setHost(host);
routerEntity.setPort(port);
routerEntity.setWeight(weight);
routerEntity.setProtocol(protocol);
routerEntity.setContextPath(contextPath);
routerEntityList.add(routerEntity);
}
return routerEntityList;
}
@Override
public List<RouterEntity> getRouterEntityList(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) {
String url = routeProtocol + "://" + routeHost + ":" + routePort + routeContextPath + "router/route/" + routeServiceId;
String result = null;
try {
result = routerRestTemplate.getForEntity(url, String.class).getBody();
} catch (RestClientException e) {
throw new DiscoveryException("Failed to execute to route, serviceId=" + routeServiceId + ", url=" + url, e);
}
if (StringUtils.isEmpty(result)) {
return null;
}
List<RouterEntity> routerEntityList = JsonUtil.fromJson(result, new TypeReference<List<RouterEntity>>() {
});
return routerEntityList;
}
@Override
public RouterEntity routeTree(String routeServiceIds) {<FILL_FUNCTION_BODY>}
private void routeFirst(RouterEntity routerEntity, String routeServiceId) {
List<RouterEntity> routerEntityList = getRouterEntityList(routeServiceId);
if (CollectionUtils.isNotEmpty(routerEntityList)) {
routerEntity.getNexts().addAll(routerEntityList);
}
}
private void route(RouterEntity routerEntity, String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) {
List<RouterEntity> routerEntityList = getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath);
if (CollectionUtils.isNotEmpty(routerEntityList)) {
routerEntity.getNexts().addAll(routerEntityList);
}
}
private List<RouterEntity> retrieveRouterEntityList(HashMap<Integer, List<RouterEntity>> routerEntityMap, int routerDepth) {
List<RouterEntity> routerEntityList = routerEntityMap.get(routerDepth);
if (routerEntityList == null) {
routerEntityList = new ArrayList<RouterEntity>();
routerEntityMap.put(routerDepth, routerEntityList);
}
return routerEntityList;
}
private int getWeight(String providerServiceId, String providerVersion, String providerRegion) {
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return -1;
}
DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return -1;
}
WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity();
if (weightFilterEntity == null || !weightFilterEntity.hasWeight()) {
return -1;
}
String serviceId = pluginAdapter.getServiceId();
return WeightEntityWrapper.getWeight(weightFilterEntity, providerServiceId, providerVersion, providerRegion, serviceId);
}
} |
if (StringUtils.isEmpty(routeServiceIds)) {
throw new DiscoveryException("Route serviceIds is empty");
}
String[] serviceIdArray = null;
try {
serviceIdArray = StringUtils.split(routeServiceIds, DiscoveryConstant.SEPARATE);
} catch (Exception e) {
throw new DiscoveryException("Route serviceIds must be separated with '" + DiscoveryConstant.SEPARATE + "'", e);
}
RouterEntity firstRouterEntity = getRouterEntity();
// 路由深度为Key
HashMap<Integer, List<RouterEntity>> routerEntityMap = new HashMap<Integer, List<RouterEntity>>();
int routerDepth = 0;
for (String serviceId : serviceIdArray) {
serviceId = serviceId.toLowerCase().trim();
if (routerDepth == 0) {
routeFirst(firstRouterEntity, serviceId);
retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(firstRouterEntity.getNexts());
} else {
List<RouterEntity> routerEntityList = retrieveRouterEntityList(routerEntityMap, routerDepth - 1);
for (RouterEntity routerEntity : routerEntityList) {
String routeHost = routerEntity.getHost();
int routePort = routerEntity.getPort();
String routeProtocol = routerEntity.getProtocol();
String routeContextPath = routerEntity.getContextPath();
route(routerEntity, serviceId, routeProtocol, routeHost, routePort, routeContextPath);
retrieveRouterEntityList(routerEntityMap, routerDepth).addAll(routerEntity.getNexts());
}
}
routerDepth++;
}
return firstRouterEntity;
| 494 | 1,553 | 428 | 1,981 |
550 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/StrategyResourceImpl.java | StrategyResourceImpl | validateRoute | class StrategyResourceImpl implements StrategyResource {
@Autowired
private StrategyCondition strategyCondition;
@Autowired
private StrategyWrapper strategyWrapper;
@Value("${" + AdminConstant.SPRING_APPLICATION_ADMIN_STRATEGY_ENDPOINT_VALIDATE_EXPRESSION_ENABLED + ":true}")
private Boolean validateExpressionEnabled;
@Override
public boolean validateExpression(String expression, String validation) {
if (!validateExpressionEnabled) {
throw new DiscoveryException("Strategy endpoint for validate-expression is disabled");
}
StrategyConditionEntity strategyConditionEntity = new StrategyConditionEntity();
strategyConditionEntity.setExpression(expression);
Map<String, String> map = null;
try {
map = StringUtil.splitToMap(validation);
} catch (Exception e) {
throw new DiscoveryException("Invalid format for validation input");
}
return strategyCondition.isTriggered(strategyConditionEntity, map);
}
@Override
public String validateRoute(String routeType, String validation) {<FILL_FUNCTION_BODY>}
} |
StrategyRouteType strategyRouteType = StrategyRouteType.fromString(routeType);
Map<String, String> map = null;
try {
map = StringUtil.splitToMap(validation);
} catch (Exception e) {
throw new DiscoveryException("Invalid format for validation input");
}
String route = null;
switch (strategyRouteType) {
case VERSION:
route = strategyWrapper.getRouteVersion(map);
break;
case REGION:
route = strategyWrapper.getRouteRegion(map);
break;
case ADDRESS:
route = strategyWrapper.getRouteAddress(map);
break;
case VERSION_WEIGHT:
route = strategyWrapper.getRouteVersionWeight(map);
break;
case REGION_WEIGHT:
route = strategyWrapper.getRouteRegionWeight(map);
break;
case ID_BLACKLIST:
route = strategyWrapper.getRouteIdBlacklist();
break;
case ADDRESS_BLACKLIST:
route = strategyWrapper.getRouteAddressBlacklist();
break;
}
if (StringUtils.isEmpty(route)) {
throw new DiscoveryException("Not found any " + routeType + " routes");
}
return route;
| 496 | 286 | 322 | 608 |
551 | Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResourceImpl.java | VersionResourceImpl | update | class VersionResourceImpl implements VersionResource {
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private PluginEventWapper pluginEventWapper;
@Override
public void update(String version, boolean async) {<FILL_FUNCTION_BODY>}
@Override
public void clear(String version, boolean async) {
// 修复Swagger的一个Bug,当在Swagger界面不输入版本号的时候,传到后端变成了“{}”
if (StringUtils.isNotEmpty(version) && StringUtils.equals(version.trim(), "{}")) {
version = null;
}
pluginEventWapper.fireVersionCleared(new VersionClearedEvent(version), async);
}
@Override
public List<String> view() {
List<String> versionList = new ArrayList<String>(2);
String localVersion = pluginAdapter.getLocalVersion();
String dynamicVersion = pluginAdapter.getDynamicVersion();
versionList.add(StringUtils.isNotEmpty(localVersion) ? localVersion : StringUtils.EMPTY);
versionList.add(StringUtils.isNotEmpty(dynamicVersion) ? dynamicVersion : StringUtils.EMPTY);
return versionList;
}
} |
if (StringUtils.isEmpty(version)) {
throw new DiscoveryException("Version can't be null or empty");
}
String dynamicVersion = null;
String localVersion = null;
String[] versionArray = StringUtils.split(version, DiscoveryConstant.SEPARATE);
if (versionArray.length == 2) {
dynamicVersion = versionArray[0];
localVersion = versionArray[1];
} else if (versionArray.length == 1) {
dynamicVersion = versionArray[0];
} else {
throw new DiscoveryException("Invalid version format, it must be '${dynamicVersion}' or '${dynamicVersion};${localVersion}'");
}
pluginEventWapper.fireVersionUpdated(new VersionUpdatedEvent(dynamicVersion, localVersion), async);
| 195 | 316 | 198 | 514 |
552 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter-apollo/src/main/java/com/nepxion/discovery/plugin/configcenter/apollo/adapter/ApolloConfigAdapter.java | ApolloConfigAdapter | subscribeConfig | class ApolloConfigAdapter extends ConfigAdapter {
@Autowired
private ApolloOperation apolloOperation;
private ConfigChangeListener partialConfigChangeListener;
private ConfigChangeListener globalConfigChangeListener;
@Override
public String getConfig(String group, String dataId) throws Exception {
return apolloOperation.getConfig(group, dataId);
}
@PostConstruct
@Override
public void subscribeConfig() {
partialConfigChangeListener = subscribeConfig(false);
globalConfigChangeListener = subscribeConfig(true);
}
private ConfigChangeListener subscribeConfig(boolean globalConfig) {<FILL_FUNCTION_BODY>}
@Override
public void unsubscribeConfig() {
unsubscribeConfig(partialConfigChangeListener, false);
unsubscribeConfig(globalConfigChangeListener, true);
}
private void unsubscribeConfig(ConfigChangeListener configChangeListener, boolean globalConfig) {
if (configChangeListener == null) {
return;
}
String group = getGroup();
String dataId = getDataId(globalConfig);
logUnsubscribeStarted(globalConfig);
try {
apolloOperation.unsubscribeConfig(group, dataId, configChangeListener);
} catch (Exception e) {
logUnsubscribeFailed(e, globalConfig);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.APOLLO;
}
} |
String group = getGroup();
String dataId = getDataId(globalConfig);
logSubscribeStarted(globalConfig);
try {
return apolloOperation.subscribeConfig(group, dataId, new ApolloSubscribeCallback() {
@Override
public void callback(String config) {
callbackConfig(config, globalConfig);
}
});
} catch (Exception e) {
logSubscribeFailed(e, globalConfig);
}
return null;
| 188 | 359 | 124 | 483 |
553 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/configcenter/consul/adapter/ConsulConfigAdapter.java | ConsulConfigAdapter | subscribeConfig | class ConsulConfigAdapter extends ConfigAdapter {
private ExecutorService executorService = DiscoveryThreadPoolFactory.getExecutorService("consul-config");
@Autowired
private ConsulOperation consulOperation;
private ConsulListener partialConsulListener;
private ConsulListener globalConsulListener;
@Override
public String getConfig(String group, String dataId) throws Exception {
return consulOperation.getConfig(group, dataId);
}
@PostConstruct
@Override
public void subscribeConfig() {
partialConsulListener = subscribeConfig(false);
globalConsulListener = subscribeConfig(true);
}
private ConsulListener subscribeConfig(boolean globalConfig) {<FILL_FUNCTION_BODY>}
@Override
public void unsubscribeConfig() {
unsubscribeConfig(partialConsulListener, false);
unsubscribeConfig(globalConsulListener, true);
executorService.shutdownNow();
}
private void unsubscribeConfig(ConsulListener consulListener, boolean globalConfig) {
if (consulListener == null) {
return;
}
String group = getGroup();
String dataId = getDataId(globalConfig);
logUnsubscribeStarted(globalConfig);
try {
consulOperation.unsubscribeConfig(group, dataId, consulListener);
} catch (Exception e) {
logUnsubscribeFailed(e, globalConfig);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.CONSUL;
}
} |
String group = getGroup();
String dataId = getDataId(globalConfig);
logSubscribeStarted(globalConfig);
try {
return consulOperation.subscribeConfig(group, dataId, executorService, new ConsulSubscribeCallback() {
@Override
public void callback(String config) {
callbackConfig(config, globalConfig);
}
});
} catch (Exception e) {
logSubscribeFailed(e, globalConfig);
}
return null;
| 189 | 395 | 128 | 523 |
554 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter-etcd/src/main/java/com/nepxion/discovery/plugin/configcenter/etcd/adapter/EtcdConfigAdapter.java | EtcdConfigAdapter | subscribeConfig | class EtcdConfigAdapter extends ConfigAdapter {
@Autowired
private EtcdOperation etcdOperation;
private Watch partialWatchClient;
private Watch globalWatchClient;
@Override
public String getConfig(String group, String dataId) throws Exception {
return etcdOperation.getConfig(group, dataId);
}
@PostConstruct
@Override
public void subscribeConfig() {
partialWatchClient = subscribeConfig(false);
globalWatchClient = subscribeConfig(true);
}
private Watch subscribeConfig(boolean globalConfig) {<FILL_FUNCTION_BODY>}
@Override
public void unsubscribeConfig() {
unsubscribeConfig(partialWatchClient, false);
unsubscribeConfig(globalWatchClient, true);
}
private void unsubscribeConfig(Watch watchClient, boolean globalConfig) {
if (watchClient == null) {
return;
}
String group = getGroup();
String dataId = getDataId(globalConfig);
logUnsubscribeStarted(globalConfig);
try {
etcdOperation.unsubscribeConfig(group, dataId, watchClient);
} catch (Exception e) {
logUnsubscribeFailed(e, globalConfig);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.ETCD;
}
} |
String group = getGroup();
String dataId = getDataId(globalConfig);
logSubscribeStarted(globalConfig);
try {
return etcdOperation.subscribeConfig(group, dataId, new EtcdSubscribeCallback() {
@Override
public void callback(String config) {
callbackConfig(config, globalConfig);
}
});
} catch (Exception e) {
logSubscribeFailed(e, globalConfig);
}
return null;
| 188 | 340 | 124 | 464 |
555 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/configcenter/nacos/adapter/NacosConfigAdapter.java | NacosConfigAdapter | subscribeConfig | class NacosConfigAdapter extends ConfigAdapter {
private ExecutorService executorService = DiscoveryThreadPoolFactory.getExecutorService("nacos-config");
@Autowired
private NacosOperation nacosOperation;
private Listener partialListener;
private Listener globalListener;
@Override
public String getConfig(String group, String dataId) throws Exception {
return nacosOperation.getConfig(group, dataId);
}
@PostConstruct
@Override
public void subscribeConfig() {
partialListener = subscribeConfig(false);
globalListener = subscribeConfig(true);
}
private Listener subscribeConfig(boolean globalConfig) {<FILL_FUNCTION_BODY>}
@Override
public void unsubscribeConfig() {
unsubscribeConfig(partialListener, false);
unsubscribeConfig(globalListener, true);
executorService.shutdownNow();
}
private void unsubscribeConfig(Listener listener, boolean globalConfig) {
if (listener == null) {
return;
}
String group = getGroup();
String dataId = getDataId(globalConfig);
logUnsubscribeStarted(globalConfig);
try {
nacosOperation.unsubscribeConfig(group, dataId, listener);
} catch (Exception e) {
logUnsubscribeFailed(e, globalConfig);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.NACOS;
}
} |
String group = getGroup();
String dataId = getDataId(globalConfig);
logSubscribeStarted(globalConfig);
try {
return nacosOperation.subscribeConfig(group, dataId, executorService, new NacosSubscribeCallback() {
@Override
public void callback(String config) {
callbackConfig(config, globalConfig);
}
});
} catch (Exception e) {
logSubscribeFailed(e, globalConfig);
}
return null;
| 189 | 379 | 130 | 509 |
556 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter-redis/src/main/java/com/nepxion/discovery/plugin/configcenter/redis/adapter/RedisConfigAdapter.java | RedisConfigAdapter | subscribeConfig | class RedisConfigAdapter extends ConfigAdapter {
@Autowired
private RedisOperation redisOperation;
private MessageListenerAdapter partialMessageListenerAdapter;
private MessageListenerAdapter globalMessageListenerAdapter;
@Override
public String getConfig(String group, String dataId) throws Exception {
return redisOperation.getConfig(group, dataId);
}
@PostConstruct
@Override
public void subscribeConfig() {<FILL_FUNCTION_BODY>}
public void subscribePartialConfig(String config) {
subscribeConfig(config, false);
}
public void subscribeGlobalConfig(String config) {
subscribeConfig(config, true);
}
private void subscribeConfig(String config, boolean globalConfig) {
redisOperation.subscribeConfig(config, new RedisSubscribeCallback() {
@Override
public void callback(String config) {
callbackConfig(config, globalConfig);
}
});
}
@Override
public void unsubscribeConfig() {
unsubscribeConfig(partialMessageListenerAdapter, false);
unsubscribeConfig(globalMessageListenerAdapter, true);
}
private void unsubscribeConfig(MessageListenerAdapter messageListenerAdapter, boolean globalConfig) {
if (messageListenerAdapter == null) {
return;
}
String group = getGroup();
String dataId = getDataId(globalConfig);
logUnsubscribeStarted(globalConfig);
try {
redisOperation.unsubscribeConfig(group, dataId, messageListenerAdapter);
} catch (Exception e) {
logUnsubscribeFailed(e, globalConfig);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.REDIS;
}
} |
String group = getGroup();
logSubscribeStarted(false);
try {
partialMessageListenerAdapter = redisOperation.subscribeConfig(group, getDataId(false), this, "subscribePartialConfig");
} catch (Exception e) {
logSubscribeFailed(e, false);
}
logSubscribeStarted(true);
try {
globalMessageListenerAdapter = redisOperation.subscribeConfig(group, getDataId(true), this, "subscribeGlobalConfig");
} catch (Exception e) {
logSubscribeFailed(e, true);
}
| 150 | 434 | 148 | 582 |
557 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/configcenter/zookeeper/adapter/ZookeeperConfigAdapter.java | ZookeeperConfigAdapter | subscribeConfig | class ZookeeperConfigAdapter extends ConfigAdapter {
@Autowired
private ZookeeperOperation zookeeperOperation;
private ZookeeperListener partialZookeeperListener;
private ZookeeperListener globalZookeeperListener;
@Override
public String getConfig(String group, String dataId) throws Exception {
return zookeeperOperation.getConfig(group, dataId);
}
@PostConstruct
@Override
public void subscribeConfig() {
partialZookeeperListener = subscribeConfig(false);
globalZookeeperListener = subscribeConfig(true);
}
private ZookeeperListener subscribeConfig(boolean globalConfig) {<FILL_FUNCTION_BODY>}
@Override
public void unsubscribeConfig() {
unsubscribeConfig(partialZookeeperListener, false);
unsubscribeConfig(globalZookeeperListener, true);
}
private void unsubscribeConfig(ZookeeperListener zookeeperListener, boolean globalConfig) {
if (zookeeperListener == null) {
return;
}
String group = getGroup();
String dataId = getDataId(globalConfig);
logUnsubscribeStarted(globalConfig);
try {
zookeeperOperation.unsubscribeConfig(group, dataId, zookeeperListener);
} catch (Exception e) {
logUnsubscribeFailed(e, globalConfig);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.ZOOKEEPER;
}
} |
String group = getGroup();
String dataId = getDataId(globalConfig);
logSubscribeStarted(globalConfig);
try {
return zookeeperOperation.subscribeConfig(group, dataId, new ZookeeperSubscribeCallback() {
@Override
public void callback(String config) {
callbackConfig(config, globalConfig);
}
});
} catch (Exception e) {
logSubscribeFailed(e, globalConfig);
}
return null;
| 188 | 395 | 128 | 523 |
558 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/adapter/ConfigAdapter.java | ConfigAdapter | callbackConfig | class ConfigAdapter extends RemoteConfigLoader implements PluginConfigAdapter {
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private PluginEventWapper pluginEventWapper;
@Autowired
private ConfigLogger configLogger;
@Override
public String[] getConfigList() throws Exception {
String[] configList = new String[2];
configList[0] = getConfig(false);
configList[1] = getConfig(true);
return configList;
}
public String getConfig(boolean globalConfig) throws Exception {
logGetStarted(globalConfig);
String group = getGroup();
String dataId = getDataId(globalConfig);
String config = getConfig(group, dataId);
if (StringUtils.isNotBlank(config)) {
logFound(globalConfig);
} else {
logNotFound(globalConfig);
}
return config;
}
public void callbackConfig(String config, boolean globalConfig) {<FILL_FUNCTION_BODY>}
public String getGroup() {
return pluginAdapter.getGroup();
}
public String getServiceId() {
return pluginAdapter.getServiceId();
}
public String getDataId(boolean globalConfig) {
String group = getGroup();
String serviceId = getServiceId();
return globalConfig ? group : serviceId;
}
public void fireRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent, boolean async) {
pluginEventWapper.fireRuleUpdated(ruleUpdatedEvent, async);
}
public void fireRuleCleared(RuleClearedEvent ruleClearedEvent, boolean async) {
pluginEventWapper.fireRuleCleared(ruleClearedEvent, async);
}
public SubscriptionType getSubscriptionType(boolean globalConfig) {
return globalConfig ? SubscriptionType.GLOBAL : SubscriptionType.PARTIAL;
}
public void logGetStarted(boolean globalConfig) {
configLogger.logGetStarted(globalConfig);
}
public void logSubscribeStarted(boolean globalConfig) {
configLogger.logSubscribeStarted(globalConfig);
}
public void logSubscribeFailed(Exception e, boolean globalConfig) {
configLogger.logSubscribeFailed(e, globalConfig);
}
public void logUnsubscribeStarted(boolean globalConfig) {
configLogger.logUnsubscribeStarted(globalConfig);
}
public void logUnsubscribeFailed(Exception e, boolean globalConfig) {
configLogger.logUnsubscribeFailed(e, globalConfig);
}
public void logFound(boolean globalConfig) {
configLogger.logFound(globalConfig);
}
public void logNotFound(boolean globalConfig) {
configLogger.logNotFound(globalConfig);
}
public void logUpdatedEvent(boolean globalConfig) {
configLogger.logUpdatedEvent(globalConfig);
}
public void logClearedEvent(boolean globalConfig) {
configLogger.logClearedEvent(globalConfig);
}
public void logUpdatedSame(boolean globalConfig) {
configLogger.logUpdatedSame(globalConfig);
}
public boolean isConfigSingleKey() {
ConfigType configType = getConfigType();
return ConfigType.isSingleKey(configType);
}
public abstract String getConfig(String group, String dataId) throws Exception;
} |
SubscriptionType subscriptionType = getSubscriptionType(globalConfig);
if (StringUtils.isNotBlank(config)) {
logUpdatedEvent(globalConfig);
RuleEntity ruleEntity = null;
if (globalConfig) {
ruleEntity = pluginAdapter.getDynamicGlobalRule();
} else {
ruleEntity = pluginAdapter.getDynamicPartialRule();
}
String rule = null;
if (ruleEntity != null) {
rule = ruleEntity.getContent();
}
if (!StringUtils.equals(rule, config)) {
fireRuleUpdated(new RuleUpdatedEvent(subscriptionType, config), true);
} else {
logUpdatedSame(globalConfig);
}
} else {
logClearedEvent(globalConfig);
fireRuleCleared(new RuleClearedEvent(subscriptionType), true);
}
| 310 | 860 | 217 | 1,077 |
559 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/configuration/ConfigAutoConfiguration.java | ConfigAutoConfiguration | localConfigLoader | class ConfigAutoConfiguration {
@Autowired
private PluginContextAware pluginContextAware;
@Bean
public LocalConfigLoader localConfigLoader() {<FILL_FUNCTION_BODY>}
@Bean
public ConfigInitializer configInitializer() {
return new ConfigInitializer();
}
@Bean
public ConfigLogger configLogger() {
return new ConfigLogger();
}
} |
return new LocalConfigLoader() {
@Override
protected String getPath() {
return pluginContextAware.getConfigPath();
}
};
| 80 | 106 | 42 | 148 |
560 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/initializer/ConfigInitializer.java | ConfigInitializer | initialize | class ConfigInitializer {
private static final Logger LOG = LoggerFactory.getLogger(ConfigInitializer.class);
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private PluginConfigParser pluginConfigParser;
@Autowired
private PluginEventWapper pluginEventWapper;
@Autowired
private LocalConfigLoader localConfigLoader;
@Autowired(required = false)
private RemoteConfigLoader remoteConfigLoader;
@Value("${" + DiscoveryConstant.SPRING_APPLICATION_PARAMETER_EVENT_ONSTART_ENABLED + ":true}")
private Boolean parameterEventOnstartEnabled;
@PostConstruct
public void initialize() {<FILL_FUNCTION_BODY>}
private String[] getRemoteConfigList() {
if (remoteConfigLoader != null) {
String[] configList = null;
try {
configList = remoteConfigLoader.getConfigList();
} catch (Exception e) {
LOG.warn("Get remote config list failed", e);
}
return configList;
} else {
LOG.info("Remote config loader isn't provided");
}
return null;
}
private String[] getLocalConfigList() {
String[] configList = null;
try {
configList = localConfigLoader.getConfigList();
} catch (Exception e) {
LOG.warn("Get local config list failed", e);
}
return configList;
}
} |
LOG.info("------------- Load Discovery Config --------------");
String[] remoteConfigList = getRemoteConfigList();
if (remoteConfigList != null) {
String partialRemoteConfig = remoteConfigList[0];
if (StringUtils.isNotEmpty(partialRemoteConfig)) {
LOG.info("Initialize partial remote config...");
try {
RuleEntity ruleEntity = pluginConfigParser.parse(partialRemoteConfig);
pluginAdapter.setDynamicPartialRule(ruleEntity);
} catch (Exception e) {
LOG.error("Initialize partial remote config failed", e);
pluginEventWapper.fireRuleFailure(new RuleFailureEvent(SubscriptionType.PARTIAL, partialRemoteConfig, e));
}
}
String globalRemoteConfig = remoteConfigList[1];
if (StringUtils.isNotEmpty(globalRemoteConfig)) {
LOG.info("Initialize global remote config...");
try {
RuleEntity ruleEntity = pluginConfigParser.parse(globalRemoteConfig);
pluginAdapter.setDynamicGlobalRule(ruleEntity);
} catch (Exception e) {
LOG.error("Initialize global remote config failed", e);
pluginEventWapper.fireRuleFailure(new RuleFailureEvent(SubscriptionType.GLOBAL, globalRemoteConfig, e));
}
}
}
String[] localConfigList = getLocalConfigList();
if (localConfigList != null) {
String localConfig = localConfigList[0];
if (StringUtils.isNotEmpty(localConfig)) {
LOG.info("Initialize local config...");
try {
RuleEntity ruleEntity = pluginConfigParser.parse(localConfig);
pluginAdapter.setLocalRule(ruleEntity);
} catch (Exception e) {
LOG.error("Initialize local config failed", e);
}
}
}
if (remoteConfigList == null && localConfigList == null) {
LOG.info("No configs are found");
}
// 初始化配置的时候,是否触发fireParameterChanged的EventBus事件
if (parameterEventOnstartEnabled) {
pluginEventWapper.fireParameterChanged();
}
LOG.info("--------------------------------------------------");
| 752 | 388 | 545 | 933 |
561 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/loader/LocalConfigLoader.java | LocalConfigLoader | getConfigList | class LocalConfigLoader implements ConfigLoader {
@Autowired
private ApplicationContext applicationContext;
@Override
public String[] getConfigList() throws Exception {<FILL_FUNCTION_BODY>}
protected abstract String getPath();
} |
String path = getPath();
String[] config = new String[1];
config[0] = FileUtil.getText(applicationContext, path);
return config;
| 48 | 63 | 46 | 109 |
562 | Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/logger/ConfigLogger.java | ConfigLogger | logUpdatedSame | class ConfigLogger {
private static final Logger LOG = LoggerFactory.getLogger(ConfigLogger.class);
@Autowired(required = false)
private ConfigAdapter configAdapter;
public void logGetStarted(boolean globalConfig) {
if (configAdapter == null) {
return;
}
String group = configAdapter.getGroup();
String dataId = configAdapter.getDataId(globalConfig);
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.info("Get {} config from {} server, " + getLogKey(), subscriptionType, configType, group, dataId);
}
public void logSubscribeStarted(boolean globalConfig) {
if (configAdapter == null) {
return;
}
String group = configAdapter.getGroup();
String dataId = configAdapter.getDataId(globalConfig);
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.info("Subscribe {} config from {} server, " + getLogKey(), subscriptionType, configType, group, dataId);
}
public void logSubscribeFailed(Exception e, boolean globalConfig) {
if (configAdapter == null) {
return;
}
String group = configAdapter.getGroup();
String dataId = configAdapter.getDataId(globalConfig);
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.error("Subscribe {} config from {} server failed, " + getLogKey(), subscriptionType, configType, group, dataId, e);
}
public void logUnsubscribeStarted(boolean globalConfig) {
if (configAdapter == null) {
return;
}
String group = configAdapter.getGroup();
String dataId = configAdapter.getDataId(globalConfig);
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.info("Unsubscribe {} config from {} server, " + getLogKey(), subscriptionType, configType, group, dataId);
}
public void logUnsubscribeFailed(Exception e, boolean globalConfig) {
if (configAdapter == null) {
return;
}
String group = configAdapter.getGroup();
String dataId = configAdapter.getDataId(globalConfig);
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.error("Unsubscribe {} config from {} server failed, " + getLogKey(), subscriptionType, configType, group, dataId, e);
}
public void logFound(boolean globalConfig) {
if (configAdapter == null) {
return;
}
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.info("Found {} config from {} server", subscriptionType, configType);
}
public void logNotFound(boolean globalConfig) {
if (configAdapter == null) {
return;
}
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.info("Not found {} config from {} server", subscriptionType, configType);
}
public void logUpdatedEvent(boolean globalConfig) {
if (configAdapter == null) {
return;
}
String group = configAdapter.getGroup();
String dataId = configAdapter.getDataId(globalConfig);
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.info("Get {} config updated event from {} server, " + getLogKey(), subscriptionType, configType, group, dataId);
}
public void logClearedEvent(boolean globalConfig) {
if (configAdapter == null) {
return;
}
String group = configAdapter.getGroup();
String dataId = configAdapter.getDataId(globalConfig);
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.info("Get {} config cleared event from {} server, " + getLogKey(), subscriptionType, configType, group, dataId);
}
public void logUpdatedSame(boolean globalConfig) {<FILL_FUNCTION_BODY>}
private String getLogKey() {
if (configAdapter == null) {
return null;
}
return configAdapter.isConfigSingleKey() ? "key={}-{}" : "group={}, dataId={}";
}
} |
if (configAdapter == null) {
return;
}
String group = configAdapter.getGroup();
String dataId = configAdapter.getDataId(globalConfig);
SubscriptionType subscriptionType = configAdapter.getSubscriptionType(globalConfig);
ConfigType configType = configAdapter.getConfigType();
LOG.info("Updated {} config from {} server is same as current config, ignore to update, " + getLogKey(), subscriptionType, configType, group, dataId);
| 109 | 1,221 | 121 | 1,342 |
563 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginParserAutoConfiguration.java | PluginParserAutoConfiguration | pluginConfigParser | class PluginParserAutoConfiguration {
@Autowired
private Environment environment;
@Bean
public PluginConfigParser pluginConfigParser() {<FILL_FUNCTION_BODY>}
@Bean
public PluginConfigDeparser pluginDeconfigParser() {
String configFormat = environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT);
ConfigFormatType configFormatType = ConfigFormatType.fromString(configFormat);
switch (configFormatType) {
case XML_FORMAT:
return new XmlConfigDeparser();
case JSON_FORMAT:
return new JsonConfigDeparser();
}
throw new DiscoveryException("Invalid config format for '" + configFormat + "'");
}
} |
String configFormat = environment.getProperty(DiscoveryConstant.SPRING_APPLICATION_CONFIG_FORMAT, String.class, DiscoveryConstant.XML_FORMAT);
ConfigFormatType configFormatType = ConfigFormatType.fromString(configFormat);
switch (configFormatType) {
case XML_FORMAT:
return new XmlConfigParser();
case JSON_FORMAT:
return new JsonConfigParser();
}
throw new DiscoveryException("Invalid config format for '" + configFormat + "'");
| 127 | 196 | 124 | 320 |
564 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/json/JsonConfigDeparser.java | JsonConfigDeparser | deparse | class JsonConfigDeparser implements PluginConfigDeparser {
private static final Logger LOG = LoggerFactory.getLogger(JsonConfigDeparser.class);
@Override
public String deparse(RuleEntity ruleEntity) {<FILL_FUNCTION_BODY>}
} |
if (ruleEntity == null) {
throw new DiscoveryException("RuleEntity is null");
}
LOG.info("Start to deparse RuleEntity to json...");
try {
String config = JsonUtil.toPrettyJson(ruleEntity);
LOG.info("Rule content=\n{}", config);
return config;
} catch (Exception e) {
throw new DiscoveryException(e.getMessage(), e);
}
| 140 | 68 | 115 | 183 |
565 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter-parser/src/main/java/com/nepxion/discovery/plugin/framework/parser/json/JsonConfigParser.java | JsonConfigParser | parse | class JsonConfigParser implements PluginConfigParser {
private static final Logger LOG = LoggerFactory.getLogger(JsonConfigParser.class);
@Override
public RuleEntity parse(String config) {<FILL_FUNCTION_BODY>}
} |
if (StringUtils.isEmpty(config)) {
throw new DiscoveryException("Config is null or empty");
}
LOG.info("Start to parse rule from json...");
try {
RuleEntity ruleEntity = JsonUtil.fromJson(config, RuleEntity.class);
ruleEntity.setContent(config);
LOG.info("Rule content=\n{}", config);
return ruleEntity;
} catch (Exception e) {
throw new DiscoveryException(e.getMessage(), e);
}
| 153 | 63 | 131 | 194 |
569 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/cache/PluginCache.java | PluginCache | get | class PluginCache {
private LoadingCache<String, String> loadingCache;
public PluginCache() {
loadingCache = Caffeine.newBuilder()
.expireAfterWrite(365 * 100, TimeUnit.DAYS)
.initialCapacity(10)
.maximumSize(100)
.recordStats()
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
return StringUtils.EMPTY;
}
});
}
public boolean put(String key, String value) {
loadingCache.put(key, value);
return Boolean.TRUE;
}
public String get(String key) {<FILL_FUNCTION_BODY>}
public boolean clear(String key) {
loadingCache.invalidate(key);
return Boolean.TRUE;
}
} |
try {
return loadingCache.get(key);
} catch (Exception e) {
return StringUtils.EMPTY;
}
| 60 | 234 | 39 | 273 |
570 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/cache/RuleCache.java | RuleCache | get | class RuleCache {
private LoadingCache<String, RuleEntity> loadingCache;
public RuleCache() {
loadingCache = Caffeine.newBuilder()
.expireAfterWrite(365 * 100, TimeUnit.DAYS)
.initialCapacity(2)
.maximumSize(10)
.recordStats()
.build(new CacheLoader<String, RuleEntity>() {
@Override
public RuleEntity load(String key) throws Exception {
return null;
}
});
}
public boolean put(String key, RuleEntity ruleEntity) {
loadingCache.put(key, ruleEntity);
return Boolean.TRUE;
}
public RuleEntity get(String key) {<FILL_FUNCTION_BODY>}
public boolean clear(String key) {
loadingCache.invalidate(key);
return Boolean.TRUE;
}
} |
try {
return loadingCache.get(key);
} catch (Exception e) {
return null;
}
| 60 | 232 | 34 | 266 |
571 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginAutoConfiguration.java | PluginAutoConfiguration | strategyWeightRandomLoadBalance | class PluginAutoConfiguration {
@Value("${" + DiscoveryConstant.SPRING_APPLICATION_WEIGHT_RANDOM_TYPE + ":" + DiscoveryConstant.MAP_WEIGHT_RANDOM + "}")
private String weightRandomType;
@Bean
@LoadBalanced
public RestTemplate pluginRestTemplate() {
return new RestTemplate();
}
@Bean
public PluginContextAware pluginContextAware() {
return new PluginContextAware();
}
@Bean
public PluginPublisher pluginPublisher() {
return new PluginPublisher();
}
@Bean
public PluginSubscriber pluginSubscriber() {
return new PluginSubscriber();
}
@Bean
public PluginEventWapper pluginEventWapper() {
return new PluginEventWapper();
}
@Bean
public PluginCache pluginCache() {
return new PluginCache();
}
@Bean
public RuleCache ruleCache() {
return new RuleCache();
}
@Bean
@ConditionalOnMissingBean
public RuleWeightRandomLoadBalance<WeightFilterEntity> ruleWeightRandomLoadBalance(PluginAdapter pluginAdapter) {
WeightRandomType type = WeightRandomType.fromString(weightRandomType);
switch (type) {
case MAP_WEIGHT_RANDOM:
return new RuleMapWeightRandomLoadBalance(pluginAdapter);
case ARRAY_WEIGHT_RANDOM:
return new RuleArrayWeightRandomLoadBalance(pluginAdapter);
}
return null;
}
@Bean
@ConditionalOnMissingBean
public StrategyWeightRandomLoadBalance<WeightFilterEntity> strategyWeightRandomLoadBalance(PluginAdapter pluginAdapter, @Autowired(required = false) PluginContextHolder pluginContextHolder) {<FILL_FUNCTION_BODY>}
@Bean
@ConditionalOnMissingBean
public WeightRandomProcessor<String> strategyWeightRandomProcessor() {
WeightRandomType type = WeightRandomType.fromString(weightRandomType);
switch (type) {
case MAP_WEIGHT_RANDOM:
return new MapWeightRandomProcessor<String>();
case ARRAY_WEIGHT_RANDOM:
return new ArrayWeightRandomProcessor<String>();
}
return null;
}
@Bean
public RegisterListenerExecutor registerListenerExecutor() {
return new RegisterListenerExecutor();
}
@Bean
public DiscoveryListenerExecutor discoveryListenerExecutor() {
return new DiscoveryListenerExecutor();
}
@Bean
public LoadBalanceListenerExecutor loadBalanceListenerExecutor() {
return new LoadBalanceListenerExecutor();
}
@Bean
@ConditionalOnMissingBean
public HostFilterRegisterListener hostFilterRegisterListener() {
return new HostFilterRegisterListener();
}
@Bean
@ConditionalOnMissingBean
public CountFilterRegisterListener countFilterRegisterListener() {
return new CountFilterRegisterListener();
}
@Bean
@ConditionalOnMissingBean
public HostFilterDiscoveryListener hostFilterDiscoveryListener() {
return new HostFilterDiscoveryListener();
}
@Bean
@ConditionalOnMissingBean
public VersionFilterDiscoveryListener versionFilterDiscoveryListener() {
return new VersionFilterDiscoveryListener();
}
@Bean
@ConditionalOnMissingBean
public RegionFilterDiscoveryListener regionFilterDiscoveryListener() {
return new RegionFilterDiscoveryListener();
}
@Bean
@ConditionalOnMissingBean
public HostFilterLoadBalanceListener hostFilterLoadBalanceListener() {
return new HostFilterLoadBalanceListener();
}
@Bean
@ConditionalOnMissingBean
public VersionFilterLoadBalanceListener versionFilterLoadBalanceListener() {
return new VersionFilterLoadBalanceListener();
}
@Bean
@ConditionalOnMissingBean
public RegionFilterLoadBalanceListener regionFilterLoadBalanceListener() {
return new RegionFilterLoadBalanceListener();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = DiscoveryConstant.SPRING_APPLICATION_NO_SERVERS_NOTIFY_ENABLED, matchIfMissing = false)
public NotificationLoadBalanceListener notificationLoadBalanceListener() {
return new NotificationLoadBalanceListener();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = DiscoveryConstant.SPRING_APPLICATION_GROUP_GENERATOR_ENABLED, matchIfMissing = false)
public GroupGenerator groupGenerator() {
return new GroupGenerator();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = DiscoveryConstant.SPRING_APPLICATION_GIT_GENERATOR_ENABLED, matchIfMissing = false)
public GitGenerator gitGenerator() {
return new GitGenerator();
}
} |
WeightRandomType type = WeightRandomType.fromString(weightRandomType);
switch (type) {
case MAP_WEIGHT_RANDOM:
return new StrategyMapWeightRandomLoadBalance(pluginAdapter, pluginContextHolder);
case ARRAY_WEIGHT_RANDOM:
return new StrategyArrayWeightRandomLoadBalance(pluginAdapter, pluginContextHolder);
}
return null;
| 107 | 1,236 | 104 | 1,340 |
572 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginLoadBalanceConfiguration.java | PluginLoadBalanceConfiguration | ribbonLoadBalancer | class PluginLoadBalanceConfiguration {
@RibbonClientName
private String serviceId = "client";
@Autowired
private PropertiesFactory propertiesFactory;
@Autowired
private LoadBalanceListenerExecutor loadBalanceListenerExecutor;
@Bean
@ConditionalOnMissingBean
public IRule ribbonRule(IClientConfig config) {
if (this.propertiesFactory.isSet(IRule.class, serviceId)) {
return this.propertiesFactory.get(IRule.class, config, serviceId);
}
ZoneAvoidanceRuleDecorator rule = new ZoneAvoidanceRuleDecorator();
rule.initWithNiwsConfig(config);
return rule;
}
@Bean
public ILoadBalancer ribbonLoadBalancer(IClientConfig config, ServerList<Server> serverList, ServerListFilter<Server> serverListFilter, IRule rule, IPing ping, ServerListUpdater serverListUpdater) {<FILL_FUNCTION_BODY>}
} |
if (this.propertiesFactory.isSet(ILoadBalancer.class, serviceId)) {
return this.propertiesFactory.get(ILoadBalancer.class, config, serviceId);
}
ZoneAwareLoadBalancer<?> loadBalancer = new ZoneAwareLoadBalancer<>(config, rule, ping, serverList, serverListFilter, serverListUpdater);
loadBalanceListenerExecutor.setLoadBalancer(loadBalancer);
return loadBalancer;
| 73 | 253 | 120 | 373 |
573 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginApplicationContextInitializer.java | PluginApplicationContextInitializer | initialize | class PluginApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {
private static final Logger LOG = LoggerFactory.getLogger(PluginApplicationContextInitializer.class);
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {<FILL_FUNCTION_BODY>}
private void initializeDefaultProperties(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String path = PluginContextAware.getDefaultPropertiesPath(environment);
try {
DiscoveryProperties properties = new DiscoveryProperties(path, DiscoveryConstant.ENCODING_GBK, DiscoveryConstant.ENCODING_UTF_8);
Map<String, String> propertiesMap = properties.getMap();
for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// 如果已经设置,则尊重已经设置的值
if (environment.getProperty(key) == null && System.getProperty(key) == null && System.getenv(key.toUpperCase()) == null) {
System.setProperty(key, value);
}
}
LOG.info("{} is loaded...", path);
} catch (IOException e) {
}
}
protected String getPrefixGroup(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
Boolean isGroupGeneratorEnabled = PluginContextAware.isGroupGeneratorEnabled(environment);
if (isGroupGeneratorEnabled) {
GroupGenerator groupGenerator = applicationContext.getBean(GroupGenerator.class);
return groupGenerator.getGroup();
}
return null;
}
protected String getGitVersion(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
Boolean isGitGeneratorEnabled = PluginContextAware.isGitGeneratorEnabled(environment);
if (isGitGeneratorEnabled) {
GitGenerator gitGenerator = applicationContext.getBean(GitGenerator.class);
return gitGenerator.getVersion();
}
return null;
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 1;
}
protected abstract Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException;
} |
if (!(applicationContext instanceof AnnotationConfigApplicationContext)) {
/*String bannerShown = System.getProperty(BannerConstant.BANNER_SHOWN, "true");
if (Boolean.valueOf(bannerShown)) {
System.out.println("");
System.out.println("╔═══╗");
System.out.println("╚╗╔╗║");
System.out.println(" ║║║╠╦══╦══╦══╦╗╔╦══╦═╦╗ ╔╗");
System.out.println(" ║║║╠╣══╣╔═╣╔╗║╚╝║║═╣╔╣║ ║║");
System.out.println("╔╝╚╝║╠══║╚═╣╚╝╠╗╔╣║═╣║║╚═╝║");
System.out.println("╚═══╩╩══╩══╩══╝╚╝╚══╩╝╚═╗╔╝");
System.out.println(" ╔═╝║");
System.out.println(" ╚══╝");
System.out.println("Nepxion Discovery v" + DiscoveryConstant.DISCOVERY_VERSION);
System.out.println("");
}*/
LogoBanner logoBanner = new LogoBanner(PluginApplicationContextInitializer.class, "/com/nepxion/discovery/resource/logo.txt", "Welcome to Nepxion", 9, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta, Color.red, Color.green, Color.cyan }, true);
NepxionBanner.show(logoBanner, new Description(BannerConstant.VERSION + ":", DiscoveryConstant.DISCOVERY_VERSION, 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1));
logoBanner = new LogoBanner(PluginApplicationContextInitializer.class, "/com/nepxion/ribbon/resource/logo.txt", "Welcome to Nepxion", 6, 5, new Color[] { Color.red, Color.green, Color.cyan, Color.blue, Color.yellow, Color.magenta }, true);
NepxionBanner.show(logoBanner, new Description("LoadBalancer:", LoadBalancerType.RIBBON.toString(), 0, 1), new Description(BannerConstant.GITHUB + ":", BannerConstant.NEPXION_GITHUB + "/Discovery", 0, 1));
initializeDefaultProperties(applicationContext);
}
applicationContext.getBeanFactory().addBeanPostProcessor(new SmartInstantiationAwareBeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DiscoveryClient) {
DiscoveryClient discoveryClient = (DiscoveryClient) bean;
return new DiscoveryClientDecorator(discoveryClient, applicationContext);
} else {
return afterInitialization(applicationContext, bean, beanName);
}
}
});
| 616 | 601 | 858 | 1,459 |
574 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/context/PluginEnvironmentPostProcessor.java | PluginEnvironmentPostProcessor | postProcessEnvironment | class PluginEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
} |
if (EnvironmentUtil.isStandardEnvironment(environment)) {
String uuid = UuidUtil.getTimeUUID();
System.setProperty(DiscoveryConstant.SPRING_APPLICATION_UUID, uuid);
}
| 51 | 83 | 58 | 141 |
575 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/DiscoveryClientDecorator.java | DiscoveryClientDecorator | getInstances | class DiscoveryClientDecorator implements DiscoveryClient, DiscoveryClientDelegate<DiscoveryClient> {
// private static final Logger LOG = LoggerFactory.getLogger(DiscoveryClientDecorator.class);
private DiscoveryClient discoveryClient;
private ConfigurableApplicationContext applicationContext;
public DiscoveryClientDecorator(DiscoveryClient discoveryClient, ConfigurableApplicationContext applicationContext) {
this.discoveryClient = discoveryClient;
this.applicationContext = applicationContext;
}
public DiscoveryClient getDelegate() {
return discoveryClient;
}
@Override
public List<ServiceInstance> getInstances(String serviceId) {<FILL_FUNCTION_BODY>}
public List<ServiceInstance> getRealInstances(String serviceId) {
return discoveryClient.getInstances(serviceId);
}
@Override
public List<String> getServices() {
List<String> services = getRealServices();
try {
DiscoveryListenerExecutor discoveryListenerExecutor = applicationContext.getBean(DiscoveryListenerExecutor.class);
discoveryListenerExecutor.onGetServices(services);
} catch (BeansException e) {
// LOG.warn("Get bean for DiscoveryListenerExecutor failed, ignore to executor listener");
}
return services;
}
public List<String> getRealServices() {
return discoveryClient.getServices();
}
@Override
public String description() {
return discoveryClient.description();
}
} |
List<ServiceInstance> instances = getRealInstances(serviceId);
try {
DiscoveryListenerExecutor discoveryListenerExecutor = applicationContext.getBean(DiscoveryListenerExecutor.class);
discoveryListenerExecutor.onGetInstances(serviceId, instances);
} catch (BeansException e) {
// LOG.warn("Get bean for DiscoveryListenerExecutor failed, ignore to executor listener");
}
return instances;
| 103 | 370 | 106 | 476 |
576 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/PredicateBasedRuleDecorator.java | PredicateBasedRuleDecorator | choose | class PredicateBasedRuleDecorator extends PredicateBasedRule {
@Autowired
private StrategyWeightRandomLoadBalance<WeightFilterEntity> strategyWeightRandomLoadBalance;
@Autowired
private RuleWeightRandomLoadBalance<WeightFilterEntity> ruleWeightRandomLoadBalance;
@Autowired(required = false)
private DiscoveryEnabledLoadBalance discoveryEnabledLoadBalance;
// 必须执行getEligibleServers,否则叠加执行权重规则和版本区域策略会失效
private List<Server> getServerList(Object key) {
return getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key);
}
@Override
public Server choose(Object key) {<FILL_FUNCTION_BODY>}
public Server filterChoose(Object key) {
ILoadBalancer lb = getLoadBalancer();
List<Server> serverList = new ArrayList<Server>();
serverList.addAll(lb.getAllServers());
if (discoveryEnabledLoadBalance != null) {
discoveryEnabledLoadBalance.filter(serverList);
}
Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(serverList, key);
if (server.isPresent()) {
return server.get();
} else {
return null;
}
}
} |
boolean isTriggered = false;
WeightFilterEntity strategyWeightFilterEntity = strategyWeightRandomLoadBalance.getT();
if (strategyWeightFilterEntity != null && strategyWeightFilterEntity.hasWeight()) {
isTriggered = true;
List<Server> serverList = getServerList(key);
boolean isWeightChecked = strategyWeightRandomLoadBalance.checkWeight(serverList, strategyWeightFilterEntity);
if (isWeightChecked) {
try {
return strategyWeightRandomLoadBalance.choose(serverList, strategyWeightFilterEntity);
} catch (Exception e) {
return filterChoose(key);
}
} else {
return filterChoose(key);
}
}
if (!isTriggered) {
WeightFilterEntity ruleWeightFilterEntity = ruleWeightRandomLoadBalance.getT();
if (ruleWeightFilterEntity != null && ruleWeightFilterEntity.hasWeight()) {
List<Server> serverList = getServerList(key);
boolean isWeightChecked = ruleWeightRandomLoadBalance.checkWeight(serverList, ruleWeightFilterEntity);
if (isWeightChecked) {
try {
return ruleWeightRandomLoadBalance.choose(serverList, ruleWeightFilterEntity);
} catch (Exception e) {
return filterChoose(key);
}
} else {
return filterChoose(key);
}
}
}
return filterChoose(key);
| 547 | 346 | 358 | 704 |
577 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZoneAvoidanceRuleDecorator.java | ZoneAvoidanceRuleDecorator | choose | class ZoneAvoidanceRuleDecorator extends ZoneAvoidanceRule {
@Autowired
private StrategyWeightRandomLoadBalance<WeightFilterEntity> strategyWeightRandomLoadBalance;
@Autowired
private RuleWeightRandomLoadBalance<WeightFilterEntity> ruleWeightRandomLoadBalance;
@Autowired(required = false)
private DiscoveryEnabledLoadBalance discoveryEnabledLoadBalance;
// 必须执行getEligibleServers,否则叠加执行权重规则和版本区域策略会失效
private List<Server> getServerList(Object key) {
return getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key);
}
@Override
public Server choose(Object key) {<FILL_FUNCTION_BODY>}
public Server filterChoose(Object key) {
ILoadBalancer lb = getLoadBalancer();
List<Server> serverList = new ArrayList<Server>();
serverList.addAll(lb.getAllServers());
if (discoveryEnabledLoadBalance != null) {
discoveryEnabledLoadBalance.filter(serverList);
}
Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(serverList, key);
if (server.isPresent()) {
return server.get();
} else {
return null;
}
}
} |
boolean isTriggered = false;
WeightFilterEntity strategyWeightFilterEntity = strategyWeightRandomLoadBalance.getT();
if (strategyWeightFilterEntity != null && strategyWeightFilterEntity.hasWeight()) {
isTriggered = true;
List<Server> serverList = getServerList(key);
boolean isWeightChecked = strategyWeightRandomLoadBalance.checkWeight(serverList, strategyWeightFilterEntity);
if (isWeightChecked) {
try {
return strategyWeightRandomLoadBalance.choose(serverList, strategyWeightFilterEntity);
} catch (Exception e) {
return filterChoose(key);
}
} else {
return filterChoose(key);
}
}
if (!isTriggered) {
WeightFilterEntity ruleWeightFilterEntity = ruleWeightRandomLoadBalance.getT();
if (ruleWeightFilterEntity != null && ruleWeightFilterEntity.hasWeight()) {
List<Server> serverList = getServerList(key);
boolean isWeightChecked = ruleWeightRandomLoadBalance.checkWeight(serverList, ruleWeightFilterEntity);
if (isWeightChecked) {
try {
return ruleWeightRandomLoadBalance.choose(serverList, ruleWeightFilterEntity);
} catch (Exception e) {
return filterChoose(key);
}
} else {
return filterChoose(key);
}
}
}
return filterChoose(key);
| 547 | 348 | 358 | 706 |
578 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginEventWapper.java | PluginEventWapper | fireParameterChanged | class PluginEventWapper {
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private PluginPublisher pluginPublisher;
@Autowired
private PluginSubscriber pluginSubscriber;
public void fireRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent, boolean async) {
if (async) {
pluginPublisher.asyncPublish(ruleUpdatedEvent);
} else {
pluginSubscriber.onRuleUpdated(ruleUpdatedEvent);
}
}
public void fireRuleCleared(RuleClearedEvent ruleClearedEvent, boolean async) {
if (async) {
pluginPublisher.asyncPublish(ruleClearedEvent);
} else {
pluginSubscriber.onRuleCleared(ruleClearedEvent);
}
}
public void fireRuleFailure(RuleFailureEvent ruleFailureEvent) {
pluginPublisher.asyncPublish(ruleFailureEvent);
}
public void fireVersionUpdated(VersionUpdatedEvent versionUpdatedEvent, boolean async) {
if (async) {
pluginPublisher.asyncPublish(versionUpdatedEvent);
} else {
pluginSubscriber.onVersionUpdated(versionUpdatedEvent);
}
}
public void fireVersionCleared(VersionClearedEvent versionClearedEvent, boolean async) {
if (async) {
pluginPublisher.asyncPublish(versionClearedEvent);
} else {
pluginSubscriber.onVersionCleared(versionClearedEvent);
}
}
public void fireParameterChanged(ParameterChangedEvent parameterChangedEvent) {
pluginPublisher.asyncPublish(parameterChangedEvent);
}
public void fireParameterChanged() {<FILL_FUNCTION_BODY>}
public void fireRegisterFailure(RegisterFailureEvent registerFailureEvent) {
pluginPublisher.asyncPublish(registerFailureEvent);
}
} |
RuleEntity ruleEntity = pluginAdapter.getRule();
fireParameterChanged(new ParameterChangedEvent(ruleEntity != null ? ruleEntity.getParameterEntity() : null));
| 31 | 468 | 45 | 513 |
579 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginSubscriber.java | PluginSubscriber | onVersionUpdated | class PluginSubscriber {
private static final Logger LOG = LoggerFactory.getLogger(PluginSubscriber.class);
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private PluginConfigParser pluginConfigParser;
@Autowired
private PluginEventWapper pluginEventWapper;
@Autowired
private LoadBalanceListenerExecutor loadBalanceListenerExecutor;
@Subscribe
public void onRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent) {
LOG.info("Rule updating has been triggered");
if (ruleUpdatedEvent == null) {
throw new DiscoveryException("RuleUpdatedEvent can't be null");
}
SubscriptionType subscriptionType = ruleUpdatedEvent.getSubscriptionType();
String rule = ruleUpdatedEvent.getRule();
try {
RuleEntity ruleEntity = pluginConfigParser.parse(rule);
switch (subscriptionType) {
case GLOBAL:
pluginAdapter.setDynamicGlobalRule(ruleEntity);
break;
case PARTIAL:
pluginAdapter.setDynamicPartialRule(ruleEntity);
break;
}
pluginEventWapper.fireParameterChanged();
} catch (Exception e) {
LOG.error("Parse rule xml failed", e);
pluginEventWapper.fireRuleFailure(new RuleFailureEvent(subscriptionType, rule, e));
throw e;
}
refreshLoadBalancer();
}
@Subscribe
public void onRuleCleared(RuleClearedEvent ruleClearedEvent) {
LOG.info("Rule clearing has been triggered");
if (ruleClearedEvent == null) {
throw new DiscoveryException("RuleClearedEvent can't be null");
}
SubscriptionType subscriptionType = ruleClearedEvent.getSubscriptionType();
switch (subscriptionType) {
case GLOBAL:
pluginAdapter.clearDynamicGlobalRule();
break;
case PARTIAL:
pluginAdapter.clearDynamicPartialRule();
break;
}
pluginEventWapper.fireParameterChanged();
refreshLoadBalancer();
}
@Subscribe
public void onVersionUpdated(VersionUpdatedEvent versionUpdatedEvent) {<FILL_FUNCTION_BODY>}
@Subscribe
public void onVersionCleared(VersionClearedEvent versionClearedEvent) {
LOG.info("Version clearing has been triggered");
if (versionClearedEvent == null) {
throw new DiscoveryException("VersionClearedEvent can't be null");
}
String localVersion = versionClearedEvent.getLocalVersion();
if (StringUtils.isEmpty(localVersion)) {
pluginAdapter.clearDynamicVersion();
refreshLoadBalancer();
LOG.info("Version has been cleared");
} else {
if (StringUtils.equals(pluginAdapter.getLocalVersion(), localVersion)) {
pluginAdapter.clearDynamicVersion();
refreshLoadBalancer();
LOG.info("Version has been cleared");
} else {
throw new DiscoveryException("Version clearing will be ignored, because input localVersion=" + localVersion + ", current localVersion=" + pluginAdapter.getLocalVersion());
}
}
}
// 当规则或者版本更新后,强制刷新负载均衡缓存
private void refreshLoadBalancer() {
ZoneAwareLoadBalancer<?> loadBalancer = loadBalanceListenerExecutor.getLoadBalancer();
if (loadBalancer == null) {
return;
}
loadBalancer.updateListOfServers();
}
} |
LOG.info("Version updating has been triggered");
if (versionUpdatedEvent == null) {
throw new DiscoveryException("VersionUpdatedEvent can't be null");
}
String dynamicVersion = versionUpdatedEvent.getDynamicVersion();
String localVersion = versionUpdatedEvent.getLocalVersion();
if (StringUtils.isEmpty(localVersion)) {
pluginAdapter.setDynamicVersion(dynamicVersion);
refreshLoadBalancer();
LOG.info("Version has been updated, new version is {}", dynamicVersion);
} else {
if (StringUtils.equals(pluginAdapter.getLocalVersion(), localVersion)) {
pluginAdapter.setDynamicVersion(dynamicVersion);
refreshLoadBalancer();
LOG.info("Version has been updated, new version is {}", dynamicVersion);
} else {
throw new DiscoveryException("Version updating will be ignored, because input localVersion=" + localVersion + ", current localVersion=" + pluginAdapter.getLocalVersion());
}
}
| 278 | 896 | 244 | 1,140 |
580 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/generator/GitGenerator.java | GitGenerator | match | class GitGenerator {
private static final Logger LOG = LoggerFactory.getLogger(GitGenerator.class);
@Autowired
private ApplicationContext applicationContext;
private String generatorPath;
private String versionKey;
private String text;
private Map<String, String> map;
@PostConstruct
public void initialize() {
generatorPath = PluginContextAware.getGitGeneratorPath(applicationContext.getEnvironment());
versionKey = PluginContextAware.getGitVersionKey(applicationContext.getEnvironment());
initializeText();
initializeJsonMap();
initializePropertiesMap();
String version = getVersion();
LOG.info("--------------------------------------------------");
if (StringUtils.isNotEmpty(version)) {
LOG.info("Use {}={} as metadata version", versionKey, version);
} else {
LOG.error("Not found value of {}, use default metadata version setting", versionKey);
}
LOG.info("--------------------------------------------------");
}
private void initializeText() {
text = FileUtil.getText(applicationContext, generatorPath);
}
private void initializeJsonMap() {
if (StringUtils.isEmpty(text)) {
return;
}
if (MapUtils.isNotEmpty(map)) {
return;
}
try {
map = JsonUtil.fromJson(text, new TypeReference<Map<String, String>>() {
});
} catch (Exception e) {
}
}
private void initializePropertiesMap() {
if (StringUtils.isEmpty(text)) {
return;
}
if (MapUtils.isNotEmpty(map)) {
return;
}
try {
DiscoveryProperties properties = new DiscoveryProperties(text, DiscoveryConstant.ENCODING_UTF_8);
map = properties.getMap();
} catch (Exception e) {
}
}
public String getVersionKey() {
return versionKey;
}
public String getGeneratorPath() {
return generatorPath;
}
public String getText() {
return text;
}
public Map<String, String> getMap() {
return map;
}
public String getVersion() {
if (MapUtils.isEmpty(map)) {
return null;
}
return match(versionKey, map);
// return map.get(versionKey);
}
private String match(String versionKey, Map<String, String> map) {<FILL_FUNCTION_BODY>}
} |
String value = new String(versionKey);
for (Map.Entry<String, String> entry : map.entrySet()) {
String regex = "\\{" + entry.getKey() + "\\}";
// String regex = "\\$\\{" + entry.getKey() + "\\}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(value);
value = matcher.replaceAll(entry.getValue());
}
return value;
| 131 | 642 | 125 | 767 |
581 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/generator/GroupGenerator.java | GroupGenerator | initialize | class GroupGenerator {
private static final Logger LOG = LoggerFactory.getLogger(GroupGenerator.class);
@Autowired
private ApplicationContext applicationContext;
private Integer generatorLength;
private String generatorCharacter;
private String applicationName;
private String group;
@PostConstruct
public void initialize() {<FILL_FUNCTION_BODY>}
public Integer getGeneratorLength() {
return generatorLength;
}
public String getGeneratorCharacter() {
return generatorCharacter;
}
public String getApplicationName() {
return applicationName;
}
public String getGroup() {
return group;
}
} |
generatorLength = PluginContextAware.getGroupGeneratorLength(applicationContext.getEnvironment());
generatorCharacter = PluginContextAware.getGroupGeneratorCharacter(applicationContext.getEnvironment());
applicationName = PluginContextAware.getApplicationName(applicationContext.getEnvironment());
int characterIndex = applicationName.indexOf(generatorCharacter);
if (generatorLength > 0) {
group = applicationName.substring(0, generatorLength);
} else if (StringUtils.isNotEmpty(generatorCharacter) && characterIndex > 0) {
group = applicationName.substring(0, characterIndex);
}
LOG.info("--------------------------------------------------");
if (StringUtils.isNotEmpty(group)) {
LOG.info("Use application name prefix={} as metadata group", group);
} else {
LOG.error("Not substring application name prefix for generator length={} or character={}, use default metadata group setting", generatorLength, generatorCharacter);
}
LOG.info("--------------------------------------------------");
| 203 | 171 | 242 | 413 |
582 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/DiscoveryListenerExecutor.java | DiscoveryListenerExecutor | onGetInstances | class DiscoveryListenerExecutor {
@Autowired
private List<DiscoveryListener> discoveryListenerList;
public void onGetInstances(String serviceId, List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
public void onGetServices(List<String> services) {
for (DiscoveryListener discoveryListener : discoveryListenerList) {
discoveryListener.onGetServices(services);
}
}
} |
for (DiscoveryListener discoveryListener : discoveryListenerList) {
discoveryListener.onGetInstances(serviceId, instances);
}
| 39 | 110 | 36 | 146 |
583 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/HostFilterDiscoveryListener.java | HostFilterDiscoveryListener | applyHostFilter | class HostFilterDiscoveryListener extends AbstractDiscoveryListener {
@Override
public void onGetInstances(String serviceId, List<ServiceInstance> instances) {
applyHostFilter(serviceId, instances);
}
private void applyHostFilter(String providerServiceId, List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
private boolean validateBlacklist(List<String> allFilterValueList, String host) {
for (String filterValue : allFilterValueList) {
if (host.startsWith(filterValue)) {
return true;
}
}
return false;
}
private boolean validateWhitelist(List<String> allFilterValueList, String host) {
boolean matched = true;
for (String filterValue : allFilterValueList) {
if (host.startsWith(filterValue)) {
matched = false;
break;
}
}
return matched;
}
@Override
public void onGetServices(List<String> services) {
}
@Override
public int getOrder() {
// Highest priority
return HIGHEST_PRECEDENCE;
}
} |
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return;
}
DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return;
}
HostFilterEntity hostFilterEntity = discoveryEntity.getHostFilterEntity();
if (hostFilterEntity == null) {
return;
}
FilterType filterType = hostFilterEntity.getFilterType();
List<String> globalFilterValueList = hostFilterEntity.getFilterValueList();
Map<String, List<String>> filterMap = hostFilterEntity.getFilterMap();
List<String> filterValueList = filterMap.get(providerServiceId);
if (CollectionUtils.isEmpty(globalFilterValueList) && CollectionUtils.isEmpty(filterValueList)) {
return;
}
List<String> allFilterValueList = new ArrayList<String>();
if (CollectionUtils.isNotEmpty(globalFilterValueList)) {
allFilterValueList.addAll(globalFilterValueList);
}
if (CollectionUtils.isNotEmpty(filterValueList)) {
allFilterValueList.addAll(filterValueList);
}
Iterator<ServiceInstance> iterator = instances.iterator();
while (iterator.hasNext()) {
ServiceInstance instance = iterator.next();
String host = instance.getHost();
switch (filterType) {
case BLACKLIST:
if (validateBlacklist(allFilterValueList, host)) {
iterator.remove();
}
break;
case WHITELIST:
if (validateWhitelist(allFilterValueList, host)) {
iterator.remove();
}
break;
}
}
| 576 | 301 | 439 | 740 |
584 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/RegionFilterDiscoveryListener.java | RegionFilterDiscoveryListener | applyRegionFilter | class RegionFilterDiscoveryListener extends AbstractDiscoveryListener {
@Override
public void onGetInstances(String serviceId, List<ServiceInstance> instances) {
String consumerServiceId = pluginAdapter.getServiceId();
String consumerServiceRegion = pluginAdapter.getRegion();
applyRegionFilter(consumerServiceId, consumerServiceRegion, serviceId, instances);
}
private void applyRegionFilter(String consumerServiceId, String consumerServiceRegion, String providerServiceId, List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
@Override
public void onGetServices(List<String> services) {
}
@Override
public int getOrder() {
// After version filter
return HIGHEST_PRECEDENCE + 2;
}
} |
// 如果消费端未配置区域号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生
if (StringUtils.isEmpty(consumerServiceRegion)) {
return;
}
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return;
}
DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return;
}
RegionFilterEntity regionFilterEntity = discoveryEntity.getRegionFilterEntity();
if (regionFilterEntity == null) {
return;
}
Map<String, List<RegionEntity>> regionEntityMap = regionFilterEntity.getRegionEntityMap();
if (MapUtils.isEmpty(regionEntityMap)) {
return;
}
List<RegionEntity> regionEntityList = regionEntityMap.get(consumerServiceId);
if (CollectionUtils.isEmpty(regionEntityList)) {
return;
}
// 当前区域的消费端所能调用提供端的区域号列表
List<String> allNoFilterValueList = null;
// 提供端规则未作任何定义
boolean providerConditionDefined = false;
for (RegionEntity regionEntity : regionEntityList) {
String providerServiceName = regionEntity.getProviderServiceName();
if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) {
providerConditionDefined = true;
List<String> consumerRegionValueList = regionEntity.getConsumerRegionValueList();
List<String> providerRegionValueList = regionEntity.getProviderRegionValueList();
// 判断consumer-region-value值是否包含当前消费端的区域号
// 如果consumerRegionValueList为空,表示消费端区域列表未指定,那么任意消费端区域可以访问指定区域提供端区域
if (CollectionUtils.isNotEmpty(consumerRegionValueList)) {
if (consumerRegionValueList.contains(consumerServiceRegion)) {
if (allNoFilterValueList == null) {
allNoFilterValueList = new ArrayList<String>();
}
if (CollectionUtils.isNotEmpty(providerRegionValueList)) {
allNoFilterValueList.addAll(providerRegionValueList);
}
} // 这里的条件,在每一次循环都不满足,会让allNoFilterValueList为null,意味着定义的区域关系都不匹配
} else {
if (allNoFilterValueList == null) {
allNoFilterValueList = new ArrayList<String>();
}
if (CollectionUtils.isNotEmpty(providerRegionValueList)) {
allNoFilterValueList.addAll(providerRegionValueList);
}
}
}
}
if (allNoFilterValueList != null) {
// 当allNoFilterValueList为空列表,意味着区域对应关系未做任何定义(即所有的providerRegionValueList为空),不需要执行过滤,直接返回
if (allNoFilterValueList.isEmpty()) {
return;
} else {
Iterator<ServiceInstance> iterator = instances.iterator();
while (iterator.hasNext()) {
ServiceInstance instance = iterator.next();
String instanceRegion = pluginAdapter.getInstanceRegion(instance);
if (!allNoFilterValueList.contains(instanceRegion)) {
iterator.remove();
}
}
}
} else {
if (providerConditionDefined) {
// 当allNoFilterValueList为null, 意味着定义的区域关系都不匹配,直接清空所有实例
instances.clear();
}
}
| 1,167 | 196 | 903 | 1,099 |
585 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/VersionFilterDiscoveryListener.java | VersionFilterDiscoveryListener | applyVersionFilter | class VersionFilterDiscoveryListener extends AbstractDiscoveryListener {
@Override
public void onGetInstances(String serviceId, List<ServiceInstance> instances) {
String consumerServiceId = pluginAdapter.getServiceId();
String consumerServiceVersion = pluginAdapter.getVersion();
applyVersionFilter(consumerServiceId, consumerServiceVersion, serviceId, instances);
}
private void applyVersionFilter(String consumerServiceId, String consumerServiceVersion, String providerServiceId, List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
@Override
public void onGetServices(List<String> services) {
}
@Override
public int getOrder() {
// After host filter
return HIGHEST_PRECEDENCE + 1;
}
} |
// 如果消费端未配置版本号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生
if (StringUtils.isEmpty(consumerServiceVersion)) {
return;
}
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return;
}
DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return;
}
VersionFilterEntity versionFilterEntity = discoveryEntity.getVersionFilterEntity();
if (versionFilterEntity == null) {
return;
}
Map<String, List<VersionEntity>> versionEntityMap = versionFilterEntity.getVersionEntityMap();
if (MapUtils.isEmpty(versionEntityMap)) {
return;
}
List<VersionEntity> versionEntityList = versionEntityMap.get(consumerServiceId);
if (CollectionUtils.isEmpty(versionEntityList)) {
return;
}
// 当前版本的消费端所能调用提供端的版本号列表
List<String> allNoFilterValueList = null;
// 提供端规则未作任何定义
boolean providerConditionDefined = false;
for (VersionEntity versionEntity : versionEntityList) {
String providerServiceName = versionEntity.getProviderServiceName();
if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) {
providerConditionDefined = true;
List<String> consumerVersionValueList = versionEntity.getConsumerVersionValueList();
List<String> providerVersionValueList = versionEntity.getProviderVersionValueList();
// 判断consumer-version-value值是否包含当前消费端的版本号
// 如果consumerVersionValueList为空,表示消费端版本列表未指定,那么任意消费端版本可以访问指定版本提供端版本
if (CollectionUtils.isNotEmpty(consumerVersionValueList)) {
if (consumerVersionValueList.contains(consumerServiceVersion)) {
if (allNoFilterValueList == null) {
allNoFilterValueList = new ArrayList<String>();
}
if (CollectionUtils.isNotEmpty(providerVersionValueList)) {
allNoFilterValueList.addAll(providerVersionValueList);
}
} // 这里的条件,在每一次循环都不满足,会让allNoFilterValueList为null,意味着定义的版本关系都不匹配
} else {
if (allNoFilterValueList == null) {
allNoFilterValueList = new ArrayList<String>();
}
if (CollectionUtils.isNotEmpty(providerVersionValueList)) {
allNoFilterValueList.addAll(providerVersionValueList);
}
}
}
}
if (allNoFilterValueList != null) {
// 当allNoFilterValueList为空列表,意味着版本对应关系未做任何定义(即所有的providerVersionValueList为空),不需要执行过滤,直接返回
if (allNoFilterValueList.isEmpty()) {
return;
} else {
Iterator<ServiceInstance> iterator = instances.iterator();
while (iterator.hasNext()) {
ServiceInstance instance = iterator.next();
String instanceVersion = pluginAdapter.getInstanceVersion(instance);
if (!allNoFilterValueList.contains(instanceVersion)) {
iterator.remove();
}
}
}
} else {
if (providerConditionDefined) {
// 当allNoFilterValueList为null, 意味着定义的版本关系都不匹配,直接清空所有实例
instances.clear();
}
}
| 1,167 | 196 | 903 | 1,099 |
586 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/HostFilterLoadBalanceListener.java | HostFilterLoadBalanceListener | applyHostFilter | class HostFilterLoadBalanceListener extends AbstractLoadBalanceListener {
@Override
public void onGetServers(String serviceId, List<? extends Server> servers) {
applyHostFilter(serviceId, servers);
}
private void applyHostFilter(String providerServiceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>}
private boolean validateBlacklist(List<String> allFilterValueList, String host) {
for (String filterValue : allFilterValueList) {
if (host.startsWith(filterValue)) {
return true;
}
}
return false;
}
private boolean validateWhitelist(List<String> allFilterValueList, String host) {
boolean matched = true;
for (String filterValue : allFilterValueList) {
if (host.startsWith(filterValue)) {
matched = false;
break;
}
}
return matched;
}
@Override
public int getOrder() {
// Highest priority
return HIGHEST_PRECEDENCE;
}
} |
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return;
}
DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return;
}
HostFilterEntity hostFilterEntity = discoveryEntity.getHostFilterEntity();
if (hostFilterEntity == null) {
return;
}
FilterType filterType = hostFilterEntity.getFilterType();
List<String> globalFilterValueList = hostFilterEntity.getFilterValueList();
Map<String, List<String>> filterMap = hostFilterEntity.getFilterMap();
List<String> filterValueList = filterMap.get(providerServiceId);
if (CollectionUtils.isEmpty(globalFilterValueList) && CollectionUtils.isEmpty(filterValueList)) {
return;
}
List<String> allFilterValueList = new ArrayList<String>();
if (CollectionUtils.isNotEmpty(globalFilterValueList)) {
allFilterValueList.addAll(globalFilterValueList);
}
if (CollectionUtils.isNotEmpty(filterValueList)) {
allFilterValueList.addAll(filterValueList);
}
Iterator<? extends Server> iterator = servers.iterator();
while (iterator.hasNext()) {
Server server = iterator.next();
String host = server.getHost();
switch (filterType) {
case BLACKLIST:
if (validateBlacklist(allFilterValueList, host)) {
iterator.remove();
}
break;
case WHITELIST:
if (validateWhitelist(allFilterValueList, host)) {
iterator.remove();
}
break;
}
}
| 578 | 281 | 439 | 720 |
587 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListenerExecutor.java | LoadBalanceListenerExecutor | onGetServers | class LoadBalanceListenerExecutor {
@Autowired
private List<LoadBalanceListener> loadBalanceListenerList;
private ZoneAwareLoadBalancer<?> loadBalancer;
public void onGetServers(String serviceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>}
public ZoneAwareLoadBalancer<?> getLoadBalancer() {
return loadBalancer;
}
public void setLoadBalancer(ZoneAwareLoadBalancer<?> loadBalancer) {
this.loadBalancer = loadBalancer;
}
} |
for (LoadBalanceListener loadBalanceListener : loadBalanceListenerList) {
loadBalanceListener.onGetServers(serviceId, servers);
}
| 39 | 152 | 43 | 195 |
588 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/NotificationLoadBalanceListener.java | NotificationLoadBalanceListener | onGetServers | class NotificationLoadBalanceListener extends AbstractLoadBalanceListener {
private static final Logger LOG = LoggerFactory.getLogger(NotificationLoadBalanceListener.class);
@Override
public void onGetServers(String serviceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
} |
if (servers.size() == 0) {
LOG.warn("********** No server instances found for serviceId={}, perhaps they are isolated, filtered or not registered **********", serviceId);
}
| 53 | 108 | 52 | 160 |
589 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/RegionFilterLoadBalanceListener.java | RegionFilterLoadBalanceListener | applyRegionFilter | class RegionFilterLoadBalanceListener extends AbstractLoadBalanceListener {
@Override
public void onGetServers(String serviceId, List<? extends Server> servers) {
String consumerServiceId = pluginAdapter.getServiceId();
String consumerServiceRegion = pluginAdapter.getRegion();
applyRegionFilter(consumerServiceId, consumerServiceRegion, serviceId, servers);
}
private void applyRegionFilter(String consumerServiceId, String consumerServiceRegion, String providerServiceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
// After version filter
return HIGHEST_PRECEDENCE + 2;
}
} |
// 如果消费端未配置区域号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生
if (StringUtils.isEmpty(consumerServiceRegion)) {
return;
}
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return;
}
DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return;
}
RegionFilterEntity regionFilterEntity = discoveryEntity.getRegionFilterEntity();
if (regionFilterEntity == null) {
return;
}
Map<String, List<RegionEntity>> regionEntityMap = regionFilterEntity.getRegionEntityMap();
if (MapUtils.isEmpty(regionEntityMap)) {
return;
}
List<RegionEntity> regionEntityList = regionEntityMap.get(consumerServiceId);
if (CollectionUtils.isEmpty(regionEntityList)) {
return;
}
// 当前区域的消费端所能调用提供端的区域号列表
List<String> allNoFilterValueList = null;
// 提供端规则未作任何定义
boolean providerConditionDefined = false;
for (RegionEntity regionEntity : regionEntityList) {
String providerServiceName = regionEntity.getProviderServiceName();
if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) {
providerConditionDefined = true;
List<String> consumerRegionValueList = regionEntity.getConsumerRegionValueList();
List<String> providerRegionValueList = regionEntity.getProviderRegionValueList();
// 判断consumer-region-value值是否包含当前消费端的区域号
// 如果consumerRegionValueList为空,表示消费端区域列表未指定,那么任意消费端区域可以访问指定区域提供端区域
if (CollectionUtils.isNotEmpty(consumerRegionValueList)) {
if (consumerRegionValueList.contains(consumerServiceRegion)) {
if (allNoFilterValueList == null) {
allNoFilterValueList = new ArrayList<String>();
}
if (CollectionUtils.isNotEmpty(providerRegionValueList)) {
allNoFilterValueList.addAll(providerRegionValueList);
}
} // 这里的条件,在每一次循环都不满足,会让allNoFilterValueList为null,意味着定义的区域关系都不匹配
} else {
if (allNoFilterValueList == null) {
allNoFilterValueList = new ArrayList<String>();
}
if (CollectionUtils.isNotEmpty(providerRegionValueList)) {
allNoFilterValueList.addAll(providerRegionValueList);
}
}
}
}
if (allNoFilterValueList != null) {
// 当allNoFilterValueList为空列表,意味着区域对应关系未做任何定义(即所有的providerRegionValueList为空),不需要执行过滤,直接返回
if (allNoFilterValueList.isEmpty()) {
return;
} else {
Iterator<? extends Server> iterator = servers.iterator();
while (iterator.hasNext()) {
Server server = iterator.next();
String serverRegion = pluginAdapter.getServerRegion(server);
if (!allNoFilterValueList.contains(serverRegion)) {
iterator.remove();
}
}
}
} else {
if (providerConditionDefined) {
// 当allNoFilterValueList为null, 意味着定义的区域关系都不匹配,直接清空所有实例
servers.clear();
}
}
| 1,169 | 176 | 904 | 1,080 |
590 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/VersionFilterLoadBalanceListener.java | VersionFilterLoadBalanceListener | applyVersionFilter | class VersionFilterLoadBalanceListener extends AbstractLoadBalanceListener {
@Override
public void onGetServers(String serviceId, List<? extends Server> servers) {
String consumerServiceId = pluginAdapter.getServiceId();
String consumerServiceVersion = pluginAdapter.getVersion();
applyVersionFilter(consumerServiceId, consumerServiceVersion, serviceId, servers);
}
private void applyVersionFilter(String consumerServiceId, String consumerServiceVersion, String providerServiceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
// After host filter
return HIGHEST_PRECEDENCE + 1;
}
} |
// 如果消费端未配置版本号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生
if (StringUtils.isEmpty(consumerServiceVersion)) {
return;
}
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return;
}
DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return;
}
VersionFilterEntity versionFilterEntity = discoveryEntity.getVersionFilterEntity();
if (versionFilterEntity == null) {
return;
}
Map<String, List<VersionEntity>> versionEntityMap = versionFilterEntity.getVersionEntityMap();
if (MapUtils.isEmpty(versionEntityMap)) {
return;
}
List<VersionEntity> versionEntityList = versionEntityMap.get(consumerServiceId);
if (CollectionUtils.isEmpty(versionEntityList)) {
return;
}
// 当前版本的消费端所能调用提供端的版本号列表
List<String> allNoFilterValueList = null;
// 提供端规则未作任何定义
boolean providerConditionDefined = false;
for (VersionEntity versionEntity : versionEntityList) {
String providerServiceName = versionEntity.getProviderServiceName();
if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) {
providerConditionDefined = true;
List<String> consumerVersionValueList = versionEntity.getConsumerVersionValueList();
List<String> providerVersionValueList = versionEntity.getProviderVersionValueList();
// 判断consumer-version-value值是否包含当前消费端的版本号
// 如果consumerVersionValueList为空,表示消费端版本列表未指定,那么任意消费端版本可以访问指定版本提供端版本
if (CollectionUtils.isNotEmpty(consumerVersionValueList)) {
if (consumerVersionValueList.contains(consumerServiceVersion)) {
if (allNoFilterValueList == null) {
allNoFilterValueList = new ArrayList<String>();
}
if (CollectionUtils.isNotEmpty(providerVersionValueList)) {
allNoFilterValueList.addAll(providerVersionValueList);
}
} // 这里的条件,在每一次循环都不满足,会让allNoFilterValueList为null,意味着定义的版本关系都不匹配
} else {
if (allNoFilterValueList == null) {
allNoFilterValueList = new ArrayList<String>();
}
if (CollectionUtils.isNotEmpty(providerVersionValueList)) {
allNoFilterValueList.addAll(providerVersionValueList);
}
}
}
}
if (allNoFilterValueList != null) {
// 当allNoFilterValueList为空列表,意味着版本对应关系未做任何定义(即所有的providerVersionValueList为空),不需要执行过滤,直接返回
if (allNoFilterValueList.isEmpty()) {
return;
} else {
Iterator<? extends Server> iterator = servers.iterator();
while (iterator.hasNext()) {
Server server = iterator.next();
String serverVersion = pluginAdapter.getServerVersion(server);
if (!allNoFilterValueList.contains(serverVersion)) {
iterator.remove();
}
}
}
} else {
if (providerConditionDefined) {
// 当allNoFilterValueList为null, 意味着定义的版本关系都不匹配,直接清空所有实例
servers.clear();
}
}
| 1,169 | 176 | 904 | 1,080 |
591 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/CountFilterRegisterListener.java | CountFilterRegisterListener | applyCountFilter | class CountFilterRegisterListener extends AbstractRegisterListener {
@Autowired
@Lazy
protected DiscoveryClientDecorator discoveryClient;
@Override
public void onRegister(Registration registration) {
String serviceId = pluginAdapter.getServiceId();
String host = pluginAdapter.getHost();
int port = pluginAdapter.getPort();
applyCountFilter(serviceId, host, port);
}
private void applyCountFilter(String serviceId, String host, int port) {<FILL_FUNCTION_BODY>}
private void onRegisterFailure(int maxCount, String serviceId, String host, int port) {
String description = serviceId + " for " + host + ":" + port + " is rejected to register to Register server, reach max limited count=" + maxCount;
pluginEventWapper.fireRegisterFailure(new RegisterFailureEvent(DiscoveryConstant.REACH_MAX_LIMITED_COUNT, description, serviceId, host, port));
throw new DiscoveryException(description);
}
@Override
public void onDeregister(Registration registration) {
}
@Override
public void onSetStatus(Registration registration, String status) {
}
@Override
public void onClose() {
}
@Override
public int getOrder() {
// 由于通过服务数来判断是否注册满,需要第一优先级执行,否则服务列表已经被其它监听器过滤过了,其数目就不准确了
// Highest priority
return HIGHEST_PRECEDENCE;
}
} |
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return;
}
RegisterEntity registerEntity = ruleEntity.getRegisterEntity();
if (registerEntity == null) {
return;
}
CountFilterEntity countFilterEntity = registerEntity.getCountFilterEntity();
if (countFilterEntity == null) {
return;
}
Integer globalFilterValue = countFilterEntity.getFilterValue();
Map<String, Integer> filterMap = countFilterEntity.getFilterMap();
Integer filterValue = filterMap.get(serviceId);
// 如果局部值存在,就取局部值,否则取全局值
Integer maxCount = null;
if (filterValue != null) {
maxCount = filterValue;
} else {
maxCount = globalFilterValue;
}
if (maxCount == null) {
return;
}
int count = discoveryClient.getRealInstances(serviceId).size();
if (count >= maxCount) {
onRegisterFailure(maxCount, serviceId, host, port);
}
| 324 | 396 | 282 | 678 |
592 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/HostFilterRegisterListener.java | HostFilterRegisterListener | applyHostFilter | class HostFilterRegisterListener extends AbstractRegisterListener {
@Override
public void onRegister(Registration registration) {
String serviceId = pluginAdapter.getServiceId();
String host = pluginAdapter.getHost();
int port = pluginAdapter.getPort();
applyHostFilter(serviceId, host, port);
}
private void applyHostFilter(String serviceId, String host, int port) {<FILL_FUNCTION_BODY>}
private void validateBlacklist(FilterType filterType, List<String> allFilterValueList, String serviceId, String host, int port) {
for (String filterValue : allFilterValueList) {
if (host.startsWith(filterValue)) {
onRegisterFailure(filterType, allFilterValueList, serviceId, host, port);
}
}
}
private void validateWhitelist(FilterType filterType, List<String> allFilterValueList, String serviceId, String host, int port) {
boolean matched = true;
for (String filterValue : allFilterValueList) {
if (host.startsWith(filterValue)) {
matched = false;
break;
}
}
if (matched) {
onRegisterFailure(filterType, allFilterValueList, serviceId, host, port);
}
}
private void onRegisterFailure(FilterType filterType, List<String> allFilterValueList, String serviceId, String host, int port) {
String description = serviceId + " for " + host + ":" + port + " is rejected to register to Register server, not match host " + filterType + "=" + allFilterValueList;
pluginEventWapper.fireRegisterFailure(new RegisterFailureEvent(filterType.toString(), description, serviceId, host, port));
throw new DiscoveryException(description);
}
@Override
public void onDeregister(Registration registration) {
}
@Override
public void onSetStatus(Registration registration, String status) {
}
@Override
public void onClose() {
}
@Override
public int getOrder() {
// After count filter
return HIGHEST_PRECEDENCE + 1;
}
} |
RuleEntity ruleEntity = pluginAdapter.getRule();
if (ruleEntity == null) {
return;
}
RegisterEntity registerEntity = ruleEntity.getRegisterEntity();
if (registerEntity == null) {
return;
}
HostFilterEntity hostFilterEntity = registerEntity.getHostFilterEntity();
if (hostFilterEntity == null) {
return;
}
FilterType filterType = hostFilterEntity.getFilterType();
List<String> globalFilterValueList = hostFilterEntity.getFilterValueList();
Map<String, List<String>> filterMap = hostFilterEntity.getFilterMap();
List<String> filterValueList = filterMap.get(serviceId);
if (CollectionUtils.isEmpty(globalFilterValueList) && CollectionUtils.isEmpty(filterValueList)) {
return;
}
List<String> allFilterValueList = new ArrayList<String>();
if (CollectionUtils.isNotEmpty(globalFilterValueList)) {
allFilterValueList.addAll(globalFilterValueList);
}
if (CollectionUtils.isNotEmpty(filterValueList)) {
allFilterValueList.addAll(filterValueList);
}
switch (filterType) {
case BLACKLIST:
validateBlacklist(filterType, allFilterValueList, serviceId, host, port);
break;
case WHITELIST:
validateWhitelist(filterType, allFilterValueList, serviceId, host, port);
break;
}
| 399 | 556 | 376 | 932 |
593 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListenerExecutor.java | RegisterListenerExecutor | onSetStatus | class RegisterListenerExecutor {
@Autowired
private List<RegisterListener> registerListenerList;
public void onRegister(Registration registration) {
for (RegisterListener registerListener : registerListenerList) {
registerListener.onRegister(registration);
}
}
public void onDeregister(Registration registration) {
for (RegisterListener registerListener : registerListenerList) {
registerListener.onDeregister(registration);
}
}
public void onSetStatus(Registration registration, String status) {<FILL_FUNCTION_BODY>}
public void onClose() {
for (RegisterListener registerListener : registerListenerList) {
registerListener.onClose();
}
}
} |
for (RegisterListener registerListener : registerListenerList) {
registerListener.onSetStatus(registration, status);
}
| 39 | 186 | 34 | 220 |
594 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractArrayWeightRandomLoadBalance.java | AbstractArrayWeightRandomLoadBalance | choose | class AbstractArrayWeightRandomLoadBalance<T> implements WeightRandomLoadBalance<T> {
@Override
public Server choose(List<Server> serverList, T t) {<FILL_FUNCTION_BODY>}
} |
if (CollectionUtils.isEmpty(serverList)) {
return null;
}
List<Pair<Server, Integer>> weightList = new ArrayList<Pair<Server, Integer>>();
for (Server server : serverList) {
int weight = getWeight(server, t);
weightList.add(new ImmutablePair<Server, Integer>(server, weight));
}
ArrayWeightRandom<Server, Integer> weightRandom = new ArrayWeightRandom<Server, Integer>(weightList);
return weightRandom.random();
| 125 | 57 | 131 | 188 |
595 | Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractMapWeightRandomLoadBalance.java | AbstractMapWeightRandomLoadBalance | choose | class AbstractMapWeightRandomLoadBalance<T> implements WeightRandomLoadBalance<T> {
@Override
public Server choose(List<Server> serverList, T t) {<FILL_FUNCTION_BODY>}
} |
if (CollectionUtils.isEmpty(serverList)) {
return null;
}
List<Pair<Server, Integer>> weightList = new ArrayList<Pair<Server, Integer>>();
for (Server server : serverList) {
int weight = getWeight(server, t);
weightList.add(new ImmutablePair<Server, Integer>(server, weight));
}
MapWeightRandom<Server, Integer> weightRandom = new MapWeightRandom<Server, Integer>(weightList);
return weightRandom.random();
| 125 | 57 | 131 | 188 |