proj_name
stringclasses 157
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
49
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 27
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
---|---|---|---|---|---|---|---|---|---|
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/FormatUtil.java | FormatUtil | getFormatType | class FormatUtil {
public static FormatType getFormatType(String content) {<FILL_FUNCTION_BODY>}
} |
if (XmlUtil.isXmlFormat(content)) {
return FormatType.XML_FORMAT;
} else if (JsonUtil.isJsonFormat(content)) {
return FormatType.JSON_FORMAT;
/*} else if (YamlUtil.isYamlFormat(content)) {
return FormatType.YAML_FORMAT;
} else if (PropertiesUtil.isPropertiesFormat(content)) {
return FormatType.PROPERTIES_FORMAT;*/
} else {
return FormatType.TEXT_FORMAT;
}
| 33 | 131 | 164 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/IOUtil.java | IOUtil | getInputStream | class IOUtil {
public static InputStream getInputStream(String path) throws IOException {<FILL_FUNCTION_BODY>}
} |
// 从Resource路径获取
InputStream inputStream = IOUtil.class.getClassLoader().getResourceAsStream(path);
if (inputStream == null) {
// 从文件路径获取
inputStream = new FileInputStream(path);
}
return inputStream;
| 34 | 75 | 109 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/JsonUtil.java | NullKeySerializer | fromJson | class NullKeySerializer extends StdSerializer<Object> {
private static final long serialVersionUID = -9176767187240330396L;
public NullKeySerializer() {
this(null);
}
public NullKeySerializer(Class<Object> object) {
super(object);
}
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeFieldName(StringUtils.EMPTY);
}
}
public static <T> String toJson(T object) {
if (object == null) {
throw new IllegalArgumentException("Object is null");
}
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
public static <T> String toPrettyJson(T object) {
if (object == null) {
throw new IllegalArgumentException("Object is null");
}
try {
return objectMapper.writer(discoveryPrettyPrinter).writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
public static <T> T fromJson(String json, Class<T> clazz) {<FILL_FUNCTION_BODY> |
if (StringUtils.isEmpty(json)) {
throw new IllegalArgumentException("Json is null or empty");
}
try {
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
| 356 | 75 | 431 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/MathsUtil.java | MathsUtil | calculate | class MathsUtil {
private static final char ASTERISK = '*';
public static Long calculate(String value) {<FILL_FUNCTION_BODY>}
} |
if (StringUtils.isEmpty(value)) {
return null;
}
long result = 1;
try {
String[] array = StringUtils.split(value, ASTERISK);
for (String data : array) {
result *= Long.parseLong(data.trim());
}
} catch (Exception e) {
return null;
}
return result;
| 46 | 103 | 149 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PluginInfoUtil.java | PluginInfoUtil | assembleAll | class PluginInfoUtil {
private static Pattern pattern = Pattern.compile("\\[\\S+\\]");
public static List<Map<String, String>> assembleAll(String text, String filters) {
List<String> filterList = StringUtil.splitToList(filters, ",");
return assembleAll(text, filterList);
}
public static List<Map<String, String>> assembleAll(String text, List<String> filterList) {<FILL_FUNCTION_BODY>}
public static Map<String, String> assembleSingle(String text, String filters) {
List<String> filterList = StringUtil.splitToList(filters, ",");
return assembleSingle(text, filterList);
}
public static Map<String, String> assembleSingle(String text, List<String> filterList) {
text = StringUtils.replace(text, "][", "] [");
Matcher matcher = pattern.matcher(text);
Map<String, String> map = new LinkedHashMap<String, String>();
while (matcher.find()) {
String group = matcher.group();
String value = StringUtils.substringBetween(group, "[", "]");
String[] array = StringUtils.split(value, "=");
if (CollectionUtils.isEmpty(filterList) || filterList.contains(array[0])) {
map.put(array[0], array[1]);
}
}
return map;
}
public static String extractAll(String text, String filters) {
List<String> filterList = StringUtil.splitToList(filters, ",");
return extractAll(text, filterList);
}
public static String extractAll(String text, List<String> filterList) {
if (CollectionUtils.isEmpty(filterList)) {
return text;
}
StringBuilder stringBuilder = new StringBuilder();
List<Map<String, String>> list = assembleAll(text, filterList);
for (Map<String, String> map : list) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
stringBuilder.append("[").append(key).append("=").append(value).append("]");
}
stringBuilder.append(" -> ");
}
stringBuilder.delete(stringBuilder.length() - 4, stringBuilder.length());
return stringBuilder.toString();
}
public static String substringSingle(String text, String keyword) {
if (text.contains("[" + keyword + "=")) {
String value = text.substring(text.indexOf("[" + keyword + "=") + keyword.length() + 2);
return value.substring(0, value.indexOf("]"));
}
return null;
}
} |
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
List<String> singleList = StringUtil.splitToList(text, " -> ");
for (String value : singleList) {
Map<String, String> map = assembleSingle(value, filterList);
list.add(map);
}
return list;
| 727 | 96 | 823 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PropertiesUtil.java | PropertiesUtil | addProperty | class PropertiesUtil {
public static final Pattern PATTERN = Pattern.compile("-(\\w)");
public static void enrichProperties(Properties properties, Environment environment, String prefix, boolean replaceExistedKey, boolean ignoreEmptyValue) {
enrichProperties(properties, environment, PATTERN, prefix, replaceExistedKey, ignoreEmptyValue);
}
public static void enrichProperties(Properties properties, Environment environment, Pattern pattern, String prefix, boolean replaceExistedKey, boolean ignoreEmptyValue) {
Map<String, Object> map = PropertySourcesUtils.getSubProperties((ConfigurableEnvironment) environment, prefix);
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = resolveKey(pattern, entry.getKey());
String value = String.valueOf(entry.getValue());
addProperty(properties, key, value, replaceExistedKey, ignoreEmptyValue);
}
}
public static void addProperty(Properties properties, String key, String value, boolean replaceExistedKey, boolean ignoreEmptyValue) {<FILL_FUNCTION_BODY>}
public static void addProperty(Properties properties, String key, String value, boolean ignoreEmptyValue) {
if (StringUtils.isBlank(value)) {
if (!ignoreEmptyValue) {
properties.put(key, value);
}
} else {
properties.put(key, value);
}
}
public static String resolveKey(String key) {
return resolveKey(PATTERN, key);
}
public static String resolveKey(Pattern pattern, String key) {
Matcher matcher = pattern.matcher(key);
StringBuffer stringBuffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(stringBuffer, matcher.group(1).toUpperCase());
}
matcher.appendTail(stringBuffer);
return stringBuffer.toString();
}
public static boolean isPropertiesFormat(String properties) {
if (StringUtils.isBlank(properties)) {
return false;
}
InputStream inputStream = null;
Reader reader = null;
try {
inputStream = IOUtils.toInputStream(properties, DiscoveryConstant.ENCODING_UTF_8);
reader = new InputStreamReader(inputStream, DiscoveryConstant.ENCODING_UTF_8);
new Properties().load(reader);
return true;
} catch (Exception e) {
return false;
} finally {
if (reader != null) {
IOUtils.closeQuietly(reader);
}
if (inputStream != null) {
IOUtils.closeQuietly(inputStream);
}
}
}
} |
if (properties.containsKey(key)) {
if (replaceExistedKey) {
addProperty(properties, key, value, ignoreEmptyValue);
}
} else {
addProperty(properties, key, value, ignoreEmptyValue);
}
| 681 | 66 | 747 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ReflectionUtil.java | ReflectionUtil | getValue | 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 {
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);
}
public static Object getValue(Class<?> clazz, Object instance, String name) throws NoSuchFieldException, IllegalAccessException {<FILL_FUNCTION_BODY>}
} |
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);
| 234 | 87 | 321 | <no_super_class> |
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;
| 188 | 74 | 262 | <no_super_class> |
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;
| 500 | 186 | 686 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/StringUtil.java | StringUtil | convertToString | 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) {<FILL_FUNCTION_BODY>}
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) {
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;
}
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 (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();
| 1,711 | 114 | 1,825 | <no_super_class> |
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;
| 78 | 88 | 166 | <no_super_class> |
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();
| 671 | 217 | 888 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/VersionSortUtil.java | VersionSortUtil | assembleVersionList | class VersionSortUtil {
public static List<String> assembleVersionList(List<InstanceEntity> instanceEntityList, VersionSortType versionSortType) {<FILL_FUNCTION_BODY>}
public static List<String> getVersionList(List<VersionSortEntity> versionSortEntityList, VersionSortType versionSortType) {
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;
}
} |
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;
| 340 | 270 | 610 | <no_super_class> |
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;
}
| 33 | 42 | 75 | <no_super_class> |
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;
}
| 457 | 87 | 544 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/yaml/YamlSafeConstructor.java | YamlSafeConstructor | getClassForName | class YamlSafeConstructor extends Constructor {
private Set<String> supportedTypes;
public YamlSafeConstructor(Set<Class<?>> supportedClasses) {
supportedTypes = supportedClasses.stream().map(Class::getName).collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
}
@Override
protected Class<?> getClassForName(String name) throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
} |
Assert.state(supportedTypes.contains(name), "Unsupported '" + name + "' type encountered in YAML document");
return super.getClassForName(name);
| 121 | 45 | 166 | <no_super_class> |
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;
| 891 | 601 | 1,492 | <no_super_class> |
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();
| 544 | 273 | 817 | <no_super_class> |
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;
| 69 | 40 | 109 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/configuration/SwaggerConfiguration.java | SwaggerConfiguration | apply | 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) {
return new Function<Class<?>, Boolean>() {
@Override
public Boolean apply(Class<?> input) {<FILL_FUNCTION_BODY>}
};
}
@SuppressWarnings("deprecation")
private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
return Optional.fromNullable(input.declaringClass());
}
} |
String[] subPackages = basePackage.split(DiscoveryConstant.SEPARATE);
for (String subPackage : subPackages) {
boolean matched = input.getPackage().getName().startsWith(subPackage.trim());
if (matched) {
return true;
}
}
return false;
| 1,714 | 83 | 1,797 | <no_super_class> |
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));
}
| 51 | 582 | 633 | <no_super_class> |
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;
| 206 | 115 | 321 | <no_super_class> |
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);
}
| 159 | 64 | 223 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/FailoverEndpoint.java | FailoverEndpoint | doClearFailover | 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) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doCreateFailover(String failoverType, String group, String serviceId, String failoverValue) {
try {
String result = failoverResource.createFailover(FailoverType.fromString(failoverType), group, serviceId, failoverValue);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
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.clearFailover(FailoverType.fromString(failoverType), group);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 1,330 | 70 | 1,400 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/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) 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) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doInspectToList(InspectorDebugEntity inspectorDebugEntity) {
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);
}
}
} |
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);
}
| 449 | 105 | 554 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/SentinelEndpoint.java | SentinelEndpoint | doRemoteSentinelClear | 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) {
try {
boolean result = sentinelResource.updateRemoteSentinel(SentinelRuleType.fromString(ruleType), group, serviceId, rule);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doRemoteSentinelClear(String ruleType, String group, String serviceId) {<FILL_FUNCTION_BODY>}
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.clearRemoteSentinel(SentinelRuleType.fromString(ruleType), group, serviceId);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 1,853 | 77 | 1,930 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/endpoint/VersionEndpoint.java | VersionEndpoint | doVersionClear | 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) {
try {
List<ResultEntity> resultEntityList = versionResource.updateVersion(serviceId, version, async);
return ResponseUtil.getSuccessResponse(resultEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doVersionClear(String serviceId, String version, boolean async) {<FILL_FUNCTION_BODY>}
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.clearVersion(serviceId, version, async);
return ResponseUtil.getSuccessResponse(resultEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 1,149 | 70 | 1,219 | <no_super_class> |
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;
| 57 | 152 | 209 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/ConfigResourceImpl.java | ConfigResourceImpl | updateRemoteConfig | 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 {<FILL_FUNCTION_BODY>}
@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) {
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;
}
@Override
public RuleEntity parse(String config) {
return pluginConfigParser.parse(config);
}
@Override
public String deparse(RuleEntity ruleEntity) {
return pluginConfigDeparser.deparse(ruleEntity);
}
} |
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);
| 1,240 | 64 | 1,304 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/FailoverResourceImpl.java | FailoverResourceImpl | clearFailover | 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) {<FILL_FUNCTION_BODY>}
private void setFailover(FailoverType failoverType, StrategyFailoverEntity strategyFailoverEntity, String failoverValue) {
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;
}
}
} |
StrategyFailoverEntity strategyFailoverEntity = ruleEntity.getStrategyFailoverEntity();
if (strategyFailoverEntity != null) {
setFailover(failoverType, strategyFailoverEntity, null);
}
| 748 | 58 | 806 | <methods>public non-sealed void <init>() ,public com.nepxion.discovery.common.entity.RuleEntity getRemoteRuleEntity(java.lang.String, java.lang.String) ,public boolean updateRemoteRuleEntity(java.lang.String, java.lang.String, com.nepxion.discovery.common.entity.RuleEntity) <variables>private static final Logger LOG,private com.nepxion.discovery.console.resource.ConfigResource configResource |
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);
| 172 | 277 | 449 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/RouteResourceImpl.java | RouteResourceImpl | updateAllRoute | 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) {
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);
}
}
@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) {<FILL_FUNCTION_BODY>}
@Override
public List<ResultEntity> viewAllRoute(GatewayType gatewayType, String serviceId) {
RouteViewAllRestInvoker routeViewAllRestInvoker = new RouteViewAllRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType);
return routeViewAllRestInvoker.invoke();
}
} |
RouteUpdateAllRestInvoker routeUpdateAllRestInvoker = new RouteUpdateAllRestInvoker(serviceResource, serviceId, consoleRestTemplate, gatewayType, route);
return routeUpdateAllRestInvoker.invoke();
| 809 | 54 | 863 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/resource/SentinelResourceImpl.java | SentinelResourceImpl | clearRemoteSentinel | 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) {
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);
}
}
@Override
public boolean clearRemoteSentinel(SentinelRuleType ruleType, String group, String serviceId) {<FILL_FUNCTION_BODY>}
@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(), DiscoveryConstant.EMPTY_JSON_RULE_MULTIPLE, FormatType.JSON_FORMAT);
} catch (Exception e) {
throw new DiscoveryException("Clear remote " + ruleType.getDescription() + " failed, group={}, serviceId={}", e);
}
| 595 | 101 | 696 | <no_super_class> |
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();
| 222 | 49 | 271 | <no_super_class> |
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;
| 361 | 389 | 750 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelClearRestInvoker.java | SentinelClearRestInvoker | getSuffixPath | class SentinelClearRestInvoker extends AbstractRestInvoker {
private SentinelRuleType ruleType;
public SentinelClearRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, SentinelRuleType ruleType) {
super(serviceResource, serviceId, restTemplate);
this.ruleType = ruleType;
}
@Override
protected String getDescription() {
return "Sentinel rules cleared";
}
@Override
protected String getSuffixPath() {<FILL_FUNCTION_BODY>}
@Override
protected String doRest(String url) {
return restTemplate.postForEntity(url, null, String.class).getBody();
}
} |
String path = StringUtils.equals(ruleType.toString(), "param-flow") ? "sentinel-param" : "sentinel-core";
return path + "/clear-" + ruleType + "-rules";
| 184 | 55 | 239 | <methods>public void <init>(com.nepxion.discovery.console.resource.ServiceResource, java.lang.String, RestTemplate) ,public void <init>(com.nepxion.discovery.console.resource.ServiceResource, java.lang.String, RestTemplate, boolean) ,public List<com.nepxion.discovery.common.entity.ResultEntity> invoke() <variables>private static final Logger LOG,protected boolean async,protected RestTemplate restTemplate,protected java.lang.String serviceId,protected com.nepxion.discovery.console.resource.ServiceResource serviceResource |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelUpdateRestInvoker.java | SentinelUpdateRestInvoker | getSuffixPath | class SentinelUpdateRestInvoker extends AbstractRestInvoker {
private SentinelRuleType ruleType;
private String rule;
public SentinelUpdateRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, SentinelRuleType ruleType, String rule) {
super(serviceResource, serviceId, restTemplate);
this.ruleType = ruleType;
this.rule = rule;
}
@Override
protected String getDescription() {
return "Sentinel rules updated";
}
@Override
protected String getSuffixPath() {<FILL_FUNCTION_BODY>}
@Override
protected String doRest(String url) {
return restTemplate.postForEntity(url, getInvokeEntity(rule), String.class).getBody();
}
} |
String path = StringUtils.equals(ruleType.toString(), "param-flow") ? "sentinel-param" : "sentinel-core";
return path + "/update-" + ruleType + "-rules";
| 206 | 55 | 261 | <methods>public void <init>(com.nepxion.discovery.console.resource.ServiceResource, java.lang.String, RestTemplate) ,public void <init>(com.nepxion.discovery.console.resource.ServiceResource, java.lang.String, RestTemplate, boolean) ,public List<com.nepxion.discovery.common.entity.ResultEntity> invoke() <variables>private static final Logger LOG,protected boolean async,protected RestTemplate restTemplate,protected java.lang.String serviceId,protected com.nepxion.discovery.console.resource.ServiceResource serviceResource |
Nepxion_Discovery | Discovery/discovery-console/discovery-console-starter/src/main/java/com/nepxion/discovery/console/rest/SentinelViewRestInvoker.java | SentinelViewRestInvoker | getSuffixPath | class SentinelViewRestInvoker extends AbstractRestInvoker {
private SentinelRuleType ruleType;
public SentinelViewRestInvoker(ServiceResource serviceResource, String serviceId, RestTemplate restTemplate, SentinelRuleType ruleType) {
super(serviceResource, serviceId, restTemplate);
this.ruleType = ruleType;
}
@Override
protected String getDescription() {
return "Sentinel rules viewed";
}
@Override
protected String getSuffixPath() {<FILL_FUNCTION_BODY>}
@Override
protected String doRest(String url) {
return restTemplate.getForEntity(url, String.class).getBody();
}
} |
String path = StringUtils.equals(ruleType.toString(), "param-flow") ? "sentinel-param" : "sentinel-core";
return path + "/view-" + ruleType + "-rules";
| 182 | 55 | 237 | <methods>public void <init>(com.nepxion.discovery.console.resource.ServiceResource, java.lang.String, RestTemplate) ,public void <init>(com.nepxion.discovery.console.resource.ServiceResource, java.lang.String, RestTemplate, boolean) ,public List<com.nepxion.discovery.common.entity.ResultEntity> invoke() <variables>private static final Logger LOG,protected boolean async,protected RestTemplate restTemplate,protected java.lang.String serviceId,protected com.nepxion.discovery.console.resource.ServiceResource serviceResource |
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 | discoveryDocket | 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() {<FILL_FUNCTION_BODY>}
@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) {
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;
}
};
}
@SuppressWarnings("deprecation")
private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
return Optional.fromNullable(input.declaringClass());
}
} |
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());
| 1,596 | 205 | 1,801 | <no_super_class> |
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);
}
| 784 | 60 | 844 | <no_super_class> |
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 | doDelete | 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) {<FILL_FUNCTION_BODY>}
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) {
try {
GatewayStrategyRouteEntity gatewayStrategyRouteEntity = gatewayStrategyRouteResource.view(routeId);
return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewAll() {
try {
List<GatewayStrategyRouteEntity> gatewayStrategyRouteEntityList = gatewayStrategyRouteResource.viewAll();
return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
gatewayStrategyRouteResource.delete(routeId);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 1,144 | 56 | 1,200 | <no_super_class> |
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);
}
| 270 | 59 | 329 | <no_super_class> |
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);
}
| 350 | 62 | 412 | <no_super_class> |
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 | doNativeRoute | 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) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doRemoteRoute(String routeServiceId, String routeProtocol, String routeHost, int routePort, String routeContextPath) {
try {
List<RouterEntity> routerEntityList = routerResource.getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath);
return ResponseUtil.getSuccessResponse(routerEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
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);
return ResponseUtil.getSuccessResponse(routerEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 1,007 | 71 | 1,078 | <no_super_class> |
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);
}
| 524 | 72 | 596 | <no_super_class> |
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);
}
| 607 | 59 | 666 | <no_super_class> |
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 | doUpdate | 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) {<FILL_FUNCTION_BODY>}
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() {
try {
List<String> versionList = versionResource.view();
return ResponseUtil.getSuccessResponse(versionList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
versionResource.update(version, async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 923 | 55 | 978 | <no_super_class> |
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 | doModify | 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) {<FILL_FUNCTION_BODY>}
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) {
try {
ZuulStrategyRouteEntity zuulStrategyRouteEntity = zuulStrategyRouteResource.view(routeId);
return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewAll() {
try {
List<ZuulStrategyRouteEntity> zuulStrategyRouteEntityList = zuulStrategyRouteResource.viewAll();
return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
zuulStrategyRouteResource.modify(zuulStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 1,180 | 63 | 1,243 | <no_super_class> |
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;
| 291 | 301 | 592 | <no_super_class> |
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 | getInstance | 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) {
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;
}
}
@Override
public String inspect(List<String> service) {
InspectorEntity inspectorEntity = new InspectorEntity();
inspectorEntity.setServiceIdList(service);
return inspect(inspectorEntity).getResult();
}
private ServiceInstance getInstance(String serviceId) {<FILL_FUNCTION_BODY>}
} |
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);
| 658 | 117 | 775 | <no_super_class> |
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 | retrieveRouterEntityList | 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) {
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;
}
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) {<FILL_FUNCTION_BODY>}
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);
}
} |
List<RouterEntity> routerEntityList = routerEntityMap.get(routerDepth);
if (routerEntityList == null) {
routerEntityList = new ArrayList<RouterEntity>();
routerEntityMap.put(routerDepth, routerEntityList);
}
return routerEntityList;
| 1,906 | 75 | 1,981 | <no_super_class> |
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;
| 286 | 322 | 608 | <no_super_class> |
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);
| 316 | 198 | 514 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ConfigEndpoint.java | ConfigEndpoint | doClear | 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() {
try {
String configType = configResource.getConfigType().toString();
return ResponseUtil.getSuccessResponse(configType);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
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) {<FILL_FUNCTION_BODY>}
private ResponseEntity<?> doView() {
try {
List<String> ruleList = configResource.view();
return ResponseUtil.getSuccessResponse(ruleList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
configResource.clear(async);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 571 | 53 | 624 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/GatewayStrategyRouteEndpoint.java | GatewayStrategyRouteEndpoint | doModify | 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) {<FILL_FUNCTION_BODY>}
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) {
try {
GatewayStrategyRouteEntity gatewayStrategyRouteEntity = gatewayStrategyRouteResource.view(routeId);
return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewAll() {
try {
List<GatewayStrategyRouteEntity> gatewayStrategyRouteEntityList = gatewayStrategyRouteResource.viewAll();
return ResponseUtil.getSuccessResponse(gatewayStrategyRouteEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
gatewayStrategyRouteResource.modify(gatewayStrategyRouteEntity);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 862 | 60 | 922 | <no_super_class> |
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);
}
| 201 | 59 | 260 | <no_super_class> |
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) {
try {
InspectorEntity result = inspectorResource.inspect(inspectorEntity);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doInspect(List<String> service) {<FILL_FUNCTION_BODY>}
} |
try {
String result = inspectorResource.inspect(service);
return ResponseUtil.getSuccessResponse(result);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 256 | 58 | 314 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/RouterEndpoint.java | RouterEndpoint | doInfo | 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() {<FILL_FUNCTION_BODY>}
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) {
try {
List<RouterEntity> routerEntityList = routerResource.getRouterEntityList(routeServiceId, routeProtocol, routeHost, routePort, routeContextPath);
return ResponseUtil.getSuccessResponse(routerEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doRoutes(String routeServiceIds) {
try {
RouterEntity routerEntity = routerResource.routeTree(routeServiceIds);
return ResponseUtil.getSuccessResponse(routerEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
} |
try {
RouterEntity routerEntity = routerResource.getRouterEntity();
return ResponseUtil.getSuccessResponse(routerEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 669 | 61 | 730 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/SentinelCoreEndpoint.java | SentinelCoreEndpoint | doClearDegradeRules | 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() {
try {
List<FlowRule> flowRules = sentinelCoreResource.viewFlowRules();
return ResponseUtil.getSuccessResponse(flowRules);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doUpdateDegradeRules(String rule) {
try {
sentinelCoreResource.updateDegradeRules(rule);
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doClearDegradeRules() {<FILL_FUNCTION_BODY>}
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 {
sentinelCoreResource.clearDegradeRules();
return ResponseUtil.getSuccessResponse(true);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 1,647 | 59 | 1,706 | <no_super_class> |
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);
}
| 395 | 72 | 467 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ServiceEndpoint.java | ServiceEndpoint | doGatewayList | 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) {
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);
}
}
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) {<FILL_FUNCTION_BODY>}
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<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);
}
| 1,586 | 120 | 1,706 | <no_super_class> |
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);
}
| 286 | 59 | 345 | <no_super_class> |
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);
}
| 472 | 59 | 531 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/endpoint/ZuulStrategyRouteEndpoint.java | ZuulStrategyRouteEndpoint | doViewAll | 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) {
try {
ZuulStrategyRouteEntity zuulStrategyRouteEntity = zuulStrategyRouteResource.view(routeId);
return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntity);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
}
private ResponseEntity<?> doViewAll() {<FILL_FUNCTION_BODY>}
} |
try {
List<ZuulStrategyRouteEntity> zuulStrategyRouteEntityList = zuulStrategyRouteResource.viewAll();
return ResponseUtil.getSuccessResponse(zuulStrategyRouteEntityList);
} catch (Exception e) {
return ResponseUtil.getFailureResponse(e);
}
| 886 | 79 | 965 | <no_super_class> |
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;
| 291 | 301 | 592 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/InspectorResourceImpl.java | InspectorResourceImpl | getInstance | 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) {
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;
}
}
@Override
public String inspect(List<String> service) {
InspectorEntity inspectorEntity = new InspectorEntity();
inspectorEntity.setServiceIdList(service);
return inspect(inspectorEntity).getResult();
}
private ServiceInstance getInstance(String serviceId) {<FILL_FUNCTION_BODY>}
} |
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);
| 658 | 117 | 775 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/RouterResourceImpl.java | RouterResourceImpl | getRouterEntityList | 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) {<FILL_FUNCTION_BODY>}
@Override
public RouterEntity routeTree(String routeServiceIds) {
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;
}
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);
}
} |
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;
| 1,799 | 182 | 1,981 | <no_super_class> |
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;
| 286 | 322 | 608 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-admin-center/discovery-plugin-admin-center-starter/src/main/java/com/nepxion/discovery/plugin/admincenter/resource/VersionResourceImpl.java | VersionResourceImpl | view | class VersionResourceImpl implements VersionResource {
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private PluginEventWapper pluginEventWapper;
@Override
public void update(String version, boolean async) {
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);
}
@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() {<FILL_FUNCTION_BODY>}
} |
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;
| 403 | 111 | 514 | <no_super_class> |
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;
| 359 | 124 | 483 | <methods>public non-sealed void <init>() ,public void callbackConfig(java.lang.String, boolean) ,public void fireRuleCleared(com.nepxion.discovery.plugin.framework.event.RuleClearedEvent, boolean) ,public void fireRuleUpdated(com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent, boolean) ,public java.lang.String getConfig(boolean) throws java.lang.Exception,public abstract java.lang.String getConfig(java.lang.String, java.lang.String) throws java.lang.Exception,public java.lang.String[] getConfigList() throws java.lang.Exception,public java.lang.String getDataId(boolean) ,public java.lang.String getGroup() ,public java.lang.String getServiceId() ,public com.nepxion.discovery.common.entity.SubscriptionType getSubscriptionType(boolean) ,public boolean isConfigSingleKey() ,public void logClearedEvent(boolean) ,public void logFound(boolean) ,public void logGetStarted(boolean) ,public void logNotFound(boolean) ,public void logSubscribeFailed(java.lang.Exception, boolean) ,public void logSubscribeStarted(boolean) ,public void logUnsubscribeFailed(java.lang.Exception, boolean) ,public void logUnsubscribeStarted(boolean) ,public void logUpdatedEvent(boolean) ,public void logUpdatedSame(boolean) <variables>private com.nepxion.discovery.plugin.configcenter.logger.ConfigLogger configLogger,private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,private com.nepxion.discovery.plugin.framework.event.PluginEventWapper pluginEventWapper |
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;
| 395 | 128 | 523 | <methods>public non-sealed void <init>() ,public void callbackConfig(java.lang.String, boolean) ,public void fireRuleCleared(com.nepxion.discovery.plugin.framework.event.RuleClearedEvent, boolean) ,public void fireRuleUpdated(com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent, boolean) ,public java.lang.String getConfig(boolean) throws java.lang.Exception,public abstract java.lang.String getConfig(java.lang.String, java.lang.String) throws java.lang.Exception,public java.lang.String[] getConfigList() throws java.lang.Exception,public java.lang.String getDataId(boolean) ,public java.lang.String getGroup() ,public java.lang.String getServiceId() ,public com.nepxion.discovery.common.entity.SubscriptionType getSubscriptionType(boolean) ,public boolean isConfigSingleKey() ,public void logClearedEvent(boolean) ,public void logFound(boolean) ,public void logGetStarted(boolean) ,public void logNotFound(boolean) ,public void logSubscribeFailed(java.lang.Exception, boolean) ,public void logSubscribeStarted(boolean) ,public void logUnsubscribeFailed(java.lang.Exception, boolean) ,public void logUnsubscribeStarted(boolean) ,public void logUpdatedEvent(boolean) ,public void logUpdatedSame(boolean) <variables>private com.nepxion.discovery.plugin.configcenter.logger.ConfigLogger configLogger,private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,private com.nepxion.discovery.plugin.framework.event.PluginEventWapper pluginEventWapper |
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;
| 340 | 124 | 464 | <methods>public non-sealed void <init>() ,public void callbackConfig(java.lang.String, boolean) ,public void fireRuleCleared(com.nepxion.discovery.plugin.framework.event.RuleClearedEvent, boolean) ,public void fireRuleUpdated(com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent, boolean) ,public java.lang.String getConfig(boolean) throws java.lang.Exception,public abstract java.lang.String getConfig(java.lang.String, java.lang.String) throws java.lang.Exception,public java.lang.String[] getConfigList() throws java.lang.Exception,public java.lang.String getDataId(boolean) ,public java.lang.String getGroup() ,public java.lang.String getServiceId() ,public com.nepxion.discovery.common.entity.SubscriptionType getSubscriptionType(boolean) ,public boolean isConfigSingleKey() ,public void logClearedEvent(boolean) ,public void logFound(boolean) ,public void logGetStarted(boolean) ,public void logNotFound(boolean) ,public void logSubscribeFailed(java.lang.Exception, boolean) ,public void logSubscribeStarted(boolean) ,public void logUnsubscribeFailed(java.lang.Exception, boolean) ,public void logUnsubscribeStarted(boolean) ,public void logUpdatedEvent(boolean) ,public void logUpdatedSame(boolean) <variables>private com.nepxion.discovery.plugin.configcenter.logger.ConfigLogger configLogger,private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,private com.nepxion.discovery.plugin.framework.event.PluginEventWapper pluginEventWapper |
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;
| 379 | 130 | 509 | <methods>public non-sealed void <init>() ,public void callbackConfig(java.lang.String, boolean) ,public void fireRuleCleared(com.nepxion.discovery.plugin.framework.event.RuleClearedEvent, boolean) ,public void fireRuleUpdated(com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent, boolean) ,public java.lang.String getConfig(boolean) throws java.lang.Exception,public abstract java.lang.String getConfig(java.lang.String, java.lang.String) throws java.lang.Exception,public java.lang.String[] getConfigList() throws java.lang.Exception,public java.lang.String getDataId(boolean) ,public java.lang.String getGroup() ,public java.lang.String getServiceId() ,public com.nepxion.discovery.common.entity.SubscriptionType getSubscriptionType(boolean) ,public boolean isConfigSingleKey() ,public void logClearedEvent(boolean) ,public void logFound(boolean) ,public void logGetStarted(boolean) ,public void logNotFound(boolean) ,public void logSubscribeFailed(java.lang.Exception, boolean) ,public void logSubscribeStarted(boolean) ,public void logUnsubscribeFailed(java.lang.Exception, boolean) ,public void logUnsubscribeStarted(boolean) ,public void logUpdatedEvent(boolean) ,public void logUpdatedSame(boolean) <variables>private com.nepxion.discovery.plugin.configcenter.logger.ConfigLogger configLogger,private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,private com.nepxion.discovery.plugin.framework.event.PluginEventWapper pluginEventWapper |
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 | unsubscribeConfig | 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() {
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);
}
}
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) {<FILL_FUNCTION_BODY>}
@Override
public ConfigType getConfigType() {
return ConfigType.REDIS;
}
} |
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);
}
| 479 | 103 | 582 | <methods>public non-sealed void <init>() ,public void callbackConfig(java.lang.String, boolean) ,public void fireRuleCleared(com.nepxion.discovery.plugin.framework.event.RuleClearedEvent, boolean) ,public void fireRuleUpdated(com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent, boolean) ,public java.lang.String getConfig(boolean) throws java.lang.Exception,public abstract java.lang.String getConfig(java.lang.String, java.lang.String) throws java.lang.Exception,public java.lang.String[] getConfigList() throws java.lang.Exception,public java.lang.String getDataId(boolean) ,public java.lang.String getGroup() ,public java.lang.String getServiceId() ,public com.nepxion.discovery.common.entity.SubscriptionType getSubscriptionType(boolean) ,public boolean isConfigSingleKey() ,public void logClearedEvent(boolean) ,public void logFound(boolean) ,public void logGetStarted(boolean) ,public void logNotFound(boolean) ,public void logSubscribeFailed(java.lang.Exception, boolean) ,public void logSubscribeStarted(boolean) ,public void logUnsubscribeFailed(java.lang.Exception, boolean) ,public void logUnsubscribeStarted(boolean) ,public void logUpdatedEvent(boolean) ,public void logUpdatedSame(boolean) <variables>private com.nepxion.discovery.plugin.configcenter.logger.ConfigLogger configLogger,private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,private com.nepxion.discovery.plugin.framework.event.PluginEventWapper pluginEventWapper |
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;
| 395 | 128 | 523 | <methods>public non-sealed void <init>() ,public void callbackConfig(java.lang.String, boolean) ,public void fireRuleCleared(com.nepxion.discovery.plugin.framework.event.RuleClearedEvent, boolean) ,public void fireRuleUpdated(com.nepxion.discovery.plugin.framework.event.RuleUpdatedEvent, boolean) ,public java.lang.String getConfig(boolean) throws java.lang.Exception,public abstract java.lang.String getConfig(java.lang.String, java.lang.String) throws java.lang.Exception,public java.lang.String[] getConfigList() throws java.lang.Exception,public java.lang.String getDataId(boolean) ,public java.lang.String getGroup() ,public java.lang.String getServiceId() ,public com.nepxion.discovery.common.entity.SubscriptionType getSubscriptionType(boolean) ,public boolean isConfigSingleKey() ,public void logClearedEvent(boolean) ,public void logFound(boolean) ,public void logGetStarted(boolean) ,public void logNotFound(boolean) ,public void logSubscribeFailed(java.lang.Exception, boolean) ,public void logSubscribeStarted(boolean) ,public void logUnsubscribeFailed(java.lang.Exception, boolean) ,public void logUnsubscribeStarted(boolean) ,public void logUpdatedEvent(boolean) ,public void logUpdatedSame(boolean) <variables>private com.nepxion.discovery.plugin.configcenter.logger.ConfigLogger configLogger,private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,private com.nepxion.discovery.plugin.framework.event.PluginEventWapper pluginEventWapper |
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);
}
| 860 | 217 | 1,077 | <methods>public non-sealed void <init>() ,public void destroy() throws java.lang.Exception,public abstract void subscribeConfig() ,public abstract void unsubscribeConfig() <variables> |
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();
}
};
| 106 | 42 | 148 | <no_super_class> |
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("--------------------------------------------------");
| 388 | 545 | 933 | <no_super_class> |
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;
| 63 | 46 | 109 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-config-center/discovery-plugin-config-center-starter/src/main/java/com/nepxion/discovery/plugin/configcenter/logger/ConfigLogger.java | ConfigLogger | logClearedEvent | 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) {<FILL_FUNCTION_BODY>}
public void logUpdatedSame(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("Updated {} config from {} server is same as current config, ignore to update, " + getLogKey(), subscriptionType, configType, group, dataId);
}
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("Get {} config cleared event from {} server, " + getLogKey(), subscriptionType, configType, group, dataId);
| 1,228 | 114 | 1,342 | <no_super_class> |
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 + "'");
| 196 | 124 | 320 | <no_super_class> |
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);
}
| 68 | 115 | 183 | <no_super_class> |
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);
}
| 63 | 131 | 194 | <no_super_class> |
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;
}
| 234 | 39 | 273 | <no_super_class> |
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;
}
| 232 | 34 | 266 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/configuration/PluginAutoConfiguration.java | PluginAutoConfiguration | strategyWeightRandomProcessor | 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) {
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;
}
@Bean
@ConditionalOnMissingBean
public WeightRandomProcessor<String> strategyWeightRandomProcessor() {<FILL_FUNCTION_BODY>}
@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 MapWeightRandomProcessor<String>();
case ARRAY_WEIGHT_RANDOM:
return new ArrayWeightRandomProcessor<String>();
}
return null;
| 1,252 | 88 | 1,340 | <no_super_class> |
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;
| 253 | 120 | 373 | <no_super_class> |
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);
}
}
});
| 601 | 858 | 1,459 | <no_super_class> |
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);
}
| 83 | 58 | 141 | <no_super_class> |
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;
| 370 | 106 | 476 | <no_super_class> |
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);
| 346 | 358 | 704 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/decorator/ZoneAvoidanceRuleDecorator.java | ZoneAvoidanceRuleDecorator | filterChoose | 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) {
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);
}
public Server filterChoose(Object key) {<FILL_FUNCTION_BODY>}
} |
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;
}
| 569 | 137 | 706 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginEventWapper.java | PluginEventWapper | fireVersionUpdated | 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) {<FILL_FUNCTION_BODY>}
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() {
RuleEntity ruleEntity = pluginAdapter.getRule();
fireParameterChanged(new ParameterChangedEvent(ruleEntity != null ? ruleEntity.getParameterEntity() : null));
}
public void fireRegisterFailure(RegisterFailureEvent registerFailureEvent) {
pluginPublisher.asyncPublish(registerFailureEvent);
}
} |
if (async) {
pluginPublisher.asyncPublish(versionUpdatedEvent);
} else {
pluginSubscriber.onVersionUpdated(versionUpdatedEvent);
}
| 466 | 47 | 513 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/event/PluginSubscriber.java | PluginSubscriber | onRuleUpdated | 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) {<FILL_FUNCTION_BODY>}
@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) {
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());
}
}
}
@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("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();
| 906 | 234 | 1,140 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/generator/GitGenerator.java | GitGenerator | initialize | 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() {<FILL_FUNCTION_BODY>}
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) {
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;
}
} |
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("--------------------------------------------------");
| 612 | 155 | 767 | <no_super_class> |
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("--------------------------------------------------");
| 171 | 242 | 413 | <no_super_class> |
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);
}
| 110 | 36 | 146 | <no_super_class> |
Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/HostFilterDiscoveryListener.java | HostFilterDiscoveryListener | validateBlacklist | class HostFilterDiscoveryListener extends AbstractDiscoveryListener {
@Override
public void onGetInstances(String serviceId, List<ServiceInstance> instances) {
applyHostFilter(serviceId, instances);
}
private void applyHostFilter(String providerServiceId, List<ServiceInstance> instances) {
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;
}
}
}
private boolean validateBlacklist(List<String> allFilterValueList, String host) {<FILL_FUNCTION_BODY>}
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;
}
} |
for (String filterValue : allFilterValueList) {
if (host.startsWith(filterValue)) {
return true;
}
}
return false;
| 692 | 48 | 740 | <methods>public non-sealed void <init>() ,public DiscoveryClient getDiscoveryClient() <variables>protected DiscoveryClient discoveryClient |
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();
}
}
| 196 | 903 | 1,099 | <methods>public non-sealed void <init>() ,public DiscoveryClient getDiscoveryClient() <variables>protected DiscoveryClient discoveryClient |
Nepxion_Discovery | Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/discovery/VersionFilterDiscoveryListener.java | VersionFilterDiscoveryListener | onGetInstances | class VersionFilterDiscoveryListener extends AbstractDiscoveryListener {
@Override
public void onGetInstances(String serviceId, List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
private void applyVersionFilter(String consumerServiceId, String consumerServiceVersion, String providerServiceId, List<ServiceInstance> instances) {
// 如果消费端未配置版本号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生
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();
}
}
}
@Override
public void onGetServices(List<String> services) {
}
@Override
public int getOrder() {
// After host filter
return HIGHEST_PRECEDENCE + 1;
}
} |
String consumerServiceId = pluginAdapter.getServiceId();
String consumerServiceVersion = pluginAdapter.getVersion();
applyVersionFilter(consumerServiceId, consumerServiceVersion, serviceId, instances);
| 1,048 | 51 | 1,099 | <methods>public non-sealed void <init>() ,public DiscoveryClient getDiscoveryClient() <variables>protected DiscoveryClient discoveryClient |