1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

merge nacos

This commit is contained in:
派哒 2021-02-04 11:32:41 +08:00
parent 8154fd3eb3
commit 539cc06869
14 changed files with 702 additions and 1091 deletions

View File

@ -105,7 +105,6 @@
<version>2.0.0</version> <version>2.0.0</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -16,12 +16,16 @@
package com.alibaba.cloud.nacos.client; package com.alibaba.cloud.nacos.client;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Map; import java.util.Map;
import com.alibaba.cloud.nacos.NacosConfigProperties; import com.alibaba.cloud.nacos.NacosConfigProperties;
import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.util.CollectionUtils;
/** /**
* @author xiaojing * @author xiaojing
@ -50,7 +54,7 @@ public class NacosPropertySource extends MapPropertySource {
private final boolean isRefreshable; private final boolean isRefreshable;
NacosPropertySource(String group, String dataId, Map<String, Object> source, NacosPropertySource(String group, String dataId, Map<String, Object> source,
Date timestamp, boolean isRefreshable) { Date timestamp, boolean isRefreshable) {
super(String.join(NacosConfigProperties.COMMAS, dataId, group), source); super(String.join(NacosConfigProperties.COMMAS, dataId, group), source);
this.group = group; this.group = group;
this.dataId = dataId; this.dataId = dataId;
@ -58,6 +62,32 @@ public class NacosPropertySource extends MapPropertySource {
this.isRefreshable = isRefreshable; this.isRefreshable = isRefreshable;
} }
NacosPropertySource(List<PropertySource<?>> propertySources, String group,
String dataId, Date timestamp, boolean isRefreshable) {
this(group, dataId, getSourceMap(group, dataId, propertySources), timestamp,
isRefreshable);
}
private static Map<String, Object> getSourceMap(String group, String dataId,
List<PropertySource<?>> propertySources) {
if (CollectionUtils.isEmpty(propertySources)) {
return Collections.emptyMap();
}
// If only one, return the internal element, otherwise wrap it.
if (propertySources.size() == 1) {
PropertySource propertySource = propertySources.get(0);
if (propertySource != null && propertySource.getSource() instanceof Map) {
return (Map<String, Object>) propertySource.getSource();
}
}
// If it is multiple, it will be returned as it is, and the internal elements
// cannot be directly retrieved, so the user needs to implement the retrieval
// logic by himself
return Collections.singletonMap(
String.join(NacosConfigProperties.COMMAS, dataId, group),
propertySources);
}
public String getGroup() { public String getGroup() {
return this.group; return this.group;
} }

View File

@ -16,17 +16,18 @@
package com.alibaba.cloud.nacos.client; package com.alibaba.cloud.nacos.client;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository; import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.parser.NacosDataParserHandler; import com.alibaba.cloud.nacos.parser.NacosDataParserHandler;
import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
@ -38,8 +39,6 @@ public class NacosPropertySourceBuilder {
private static final Logger log = LoggerFactory private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceBuilder.class); .getLogger(NacosPropertySourceBuilder.class);
private static final Map<String, Object> EMPTY_MAP = new LinkedHashMap();
private ConfigService configService; private ConfigService configService;
private long timeout; private long timeout;
@ -71,14 +70,15 @@ public class NacosPropertySourceBuilder {
*/ */
NacosPropertySource build(String dataId, String group, String fileExtension, NacosPropertySource build(String dataId, String group, String fileExtension,
boolean isRefreshable) { boolean isRefreshable) {
Map<String, Object> p = loadNacosData(dataId, group, fileExtension); List<PropertySource<?>> propertySources = loadNacosData(dataId, group,
NacosPropertySource nacosPropertySource = new NacosPropertySource(group, dataId, fileExtension);
p, new Date(), isRefreshable); NacosPropertySource nacosPropertySource = new NacosPropertySource(propertySources,
group, dataId, new Date(), isRefreshable);
NacosPropertySourceRepository.collectNacosPropertySource(nacosPropertySource); NacosPropertySourceRepository.collectNacosPropertySource(nacosPropertySource);
return nacosPropertySource; return nacosPropertySource;
} }
private Map<String, Object> loadNacosData(String dataId, String group, private List<PropertySource<?>> loadNacosData(String dataId, String group,
String fileExtension) { String fileExtension) {
String data = null; String data = null;
try { try {
@ -87,24 +87,23 @@ public class NacosPropertySourceBuilder {
log.warn( log.warn(
"Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]", "Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]",
dataId, group); dataId, group);
return EMPTY_MAP; return Collections.emptyList();
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug(String.format( log.debug(String.format(
"Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId, "Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId,
group, data)); group, data));
} }
Map<String, Object> dataMap = NacosDataParserHandler.getInstance() return NacosDataParserHandler.getInstance().parseNacosData(dataId, data,
.parseNacosData( data, fileExtension); fileExtension);
return dataMap == null ? EMPTY_MAP : dataMap;
} }
catch (NacosException e) { catch (NacosException e) {
log.error("get data from Nacos error,dataId:{}, ", dataId, e); log.error("get data from Nacos error,dataId:{} ", dataId, e);
} }
catch (Exception e) { catch (Exception e) {
log.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, e); log.error("parse data from Nacos error,dataId:{},data:{}", dataId, data, e);
} }
return EMPTY_MAP; return Collections.emptyList();
} }
} }

View File

@ -1,175 +0,0 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.util.StringUtils;
/**
* @author zkz
*/
public abstract class AbstractNacosDataParser {
protected static final String DOT = ".";
protected static final String VALUE = "value";
protected static final String EMPTY_STRING = "";
private String extension;
private AbstractNacosDataParser nextParser;
protected AbstractNacosDataParser(String extension) {
if (StringUtils.isEmpty(extension)) {
throw new IllegalArgumentException("extension cannot be empty");
}
this.extension = extension.toLowerCase();
}
/**
* Verify dataId extensions.
* @param extension file extension. json or xml or yml or yaml or properties
* @return valid or not
*/
public final boolean checkFileExtension(String extension) {
if (this.isLegal(extension.toLowerCase())) {
return true;
}
if (this.nextParser == null) {
return false;
}
return this.nextParser.checkFileExtension(extension);
}
/**
* Parsing nacos configuration content.
* @param data config data from Nacos
* @param extension file extension. json or xml or yml or yaml or properties
* @return result of Properties
* @throws IOException thrown if there is a problem parsing config.
*/
public final Map<String, Object> parseNacosData(String data, String extension)
throws IOException {
if (extension == null || extension.length() < 1) {
throw new IllegalStateException("The file extension cannot be empty");
}
if (this.isLegal(extension.toLowerCase())) {
return this.doParse(data);
}
if (this.nextParser == null) {
throw new IllegalStateException(getTips(extension));
}
return this.nextParser.parseNacosData(data, extension);
}
/**
* Core logic for parsing.
* @param data config from Nacos
* @return result of Properties
* @throws IOException thrown if there is a problem parsing config.
*/
protected abstract Map<String, Object> doParse(String data) throws IOException;
protected AbstractNacosDataParser setNextParser(AbstractNacosDataParser nextParser) {
this.nextParser = nextParser;
return this;
}
public AbstractNacosDataParser addNextParser(AbstractNacosDataParser nextParser) {
if (this.nextParser == null) {
this.nextParser = nextParser;
}
else {
this.nextParser.addNextParser(nextParser);
}
return this;
}
protected boolean isLegal(String extension) {
return this.extension.equalsIgnoreCase(extension)
|| this.extension.contains(extension);
}
protected void flattenedMap(Map<String, Object> result, Map<String, Object> dataMap,
String parentKey) {
Set<Map.Entry<String, Object>> entries = dataMap.entrySet();
for (Iterator<Map.Entry<String, Object>> iterator = entries.iterator(); iterator
.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object value = entry.getValue();
String fullKey = StringUtils.isEmpty(parentKey) ? key : key.startsWith("[")
? parentKey.concat(key) : parentKey.concat(DOT).concat(key);
if (value instanceof Map) {
Map<String, Object> map = (Map<String, Object>) value;
flattenedMap(result, map, fullKey);
continue;
}
else if (value instanceof Collection) {
int count = 0;
Collection<Object> collection = (Collection<Object>) value;
for (Object object : collection) {
flattenedMap(result,
Collections.singletonMap("[" + (count++) + "]", object),
fullKey);
}
continue;
}
result.put(fullKey, value);
}
}
/**
* Reload the key ending in `value` if need.
*/
protected Map<String, Object> reloadMap(Map<String, Object> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, Object> result = new LinkedHashMap<>(map);
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if (key.contains(DOT)) {
int idx = key.lastIndexOf(DOT);
String suffix = key.substring(idx + 1);
if (VALUE.equalsIgnoreCase(suffix)) {
result.put(key.substring(0, idx), entry.getValue());
}
}
}
return result;
}
public static String getTips(String fileName) {
return String.format(
"[%s] must contains file extension with properties|yaml|yml|xml|json",
fileName);
}
}

View File

@ -17,13 +17,8 @@
package com.alibaba.cloud.nacos.parser; package com.alibaba.cloud.nacos.parser;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.*;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set;
import org.springframework.boot.env.PropertySourceLoader; import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySource;
@ -102,7 +97,7 @@ public abstract class AbstractPropertySourceLoader implements PropertySourceLoad
Set<Entry<String, Object>> entries = dataMap.entrySet(); Set<Entry<String, Object>> entries = dataMap.entrySet();
for (Iterator<Entry<String, Object>> iterator = entries.iterator(); iterator for (Iterator<Entry<String, Object>> iterator = entries.iterator(); iterator
.hasNext();) { .hasNext();) {
Map.Entry<String, Object> entry = iterator.next(); Entry<String, Object> entry = iterator.next();
String key = entry.getKey(); String key = entry.getKey();
Object value = entry.getValue(); Object value = entry.getValue();

View File

@ -1,66 +0,0 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* @author zkz
* @author yuhuangbin
*/
public class NacosDataJsonParser extends AbstractNacosDataParser {
protected NacosDataJsonParser() {
super("json");
}
@Override
protected Map<String, Object> doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, Object> map = parseJSON2Map(data);
return this.reloadMap(map);
}
/**
* JSON to Map.
* @param json json data
* @return the map convert by json string
* @throws IOException thrown if there is a problem parsing config.
*/
private Map<String, Object> parseJSON2Map(String json) throws IOException {
Map<String, Object> result = new LinkedHashMap<>(32);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> nacosDataMap = mapper.readValue(json, LinkedHashMap.class);
if (CollectionUtils.isEmpty(nacosDataMap)) {
return result;
}
flattenedMap(result, nacosDataMap, EMPTY_STRING);
return result;
}
}

View File

@ -16,64 +16,139 @@
package com.alibaba.cloud.nacos.parser; package com.alibaba.cloud.nacos.parser;
import static com.alibaba.cloud.nacos.parser.AbstractPropertySourceLoader.DOT;
import com.alibaba.cloud.nacos.utils.NacosConfigUtils;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.*;
import java.util.stream.Collectors;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/** /**
* @author zkz * @author zkz
*/ */
public final class NacosDataParserHandler { public final class NacosDataParserHandler {
private AbstractNacosDataParser parser; /**
* default extension.
*/
private static final String DEFAULT_EXTENSION = "properties";
private static List<PropertySourceLoader> propertySourceLoaders;
private NacosDataParserHandler() { private NacosDataParserHandler() {
parser = this.createParser(); propertySourceLoaders = SpringFactoriesLoader
.loadFactories(PropertySourceLoader.class, getClass().getClassLoader());
} }
/** /**
* Parsing nacos configuration content. * Parsing nacos configuration content.
* @param data config from Nacos * @param configName name of nacos-config
* @param extension file extension. json or xml or yml or yaml or properties * @param configValue value from nacos-config
* @return result of LinkedHashMap * @param extension identifies the type of configValue
* @return result of Map
* @throws IOException thrown if there is a problem parsing config. * @throws IOException thrown if there is a problem parsing config.
*/ */
public Map<String, Object> parseNacosData(String data, String extension) public List<PropertySource<?>> parseNacosData(String configName, String configValue,
throws IOException { String extension) throws IOException {
if (null == parser) { if (StringUtils.isEmpty(configValue)) {
parser = this.createParser(); return Collections.emptyList();
} }
return parser.parseNacosData(data, extension); if (StringUtils.isEmpty(extension)) {
extension = this.getFileExtension(configName);
}
for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) {
if (!canLoadFileExtension(propertySourceLoader, extension)) {
continue;
}
NacosByteArrayResource nacosByteArrayResource;
if (propertySourceLoader instanceof PropertiesPropertySourceLoader) {
// PropertiesPropertySourceLoader internal is to use the ISO_8859_1,
// the Chinese will be garbled, needs to transform into unicode.
nacosByteArrayResource = new NacosByteArrayResource(
NacosConfigUtils.selectiveConvertUnicode(configValue).getBytes(),
configName);
}
else {
nacosByteArrayResource = new NacosByteArrayResource(
configValue.getBytes(), configName);
}
nacosByteArrayResource.setFilename(getFileName(configName, extension));
List<PropertySource<?>> propertySourceList = propertySourceLoader
.load(configName, nacosByteArrayResource);
if (CollectionUtils.isEmpty(propertySourceList)) {
return Collections.emptyList();
}
return propertySourceList.stream().filter(Objects::nonNull)
.map(propertySource -> {
if (propertySource instanceof EnumerablePropertySource) {
String[] propertyNames = ((EnumerablePropertySource) propertySource)
.getPropertyNames();
if (propertyNames != null && propertyNames.length > 0) {
Map<String, Object> map = new LinkedHashMap<>();
Arrays.stream(propertyNames).forEach(name -> {
map.put(name, propertySource.getProperty(name));
});
return new OriginTrackedMapPropertySource(propertySource.getName(), map);
}
}
return propertySource;
}).collect(Collectors.toList());
}
return Collections.emptyList();
} }
/** /**
* check the validity of file extensions in dataid. * check the current extension can be processed.
* @param dataIdAry array of dataId * @param loader the propertySourceLoader
* @return dataId handle success or not * @param extension file extension
* @return if can match extension
*/ */
public boolean checkDataId(String... dataIdAry) { private boolean canLoadFileExtension(PropertySourceLoader loader, String extension) {
StringBuilder stringBuilder = new StringBuilder(); return Arrays.stream(loader.getFileExtensions())
for (String dataId : dataIdAry) { .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(extension,
int idx = dataId.lastIndexOf(AbstractNacosDataParser.DOT); fileExtension));
if (idx > 0 && idx < dataId.length() - 1) {
String extension = dataId.substring(idx + 1);
if (parser.checkFileExtension(extension)) {
break;
}
}
// add tips
stringBuilder.append(dataId).append(",");
}
if (stringBuilder.length() > 0) {
String result = stringBuilder.substring(0, stringBuilder.length() - 1);
throw new IllegalStateException(AbstractNacosDataParser.getTips(result));
}
return true;
} }
private AbstractNacosDataParser createParser() { /**
return new NacosDataPropertiesParser().addNextParser(new NacosDataYamlParser()) * @param name filename
.addNextParser(new NacosDataXmlParser()) * @return file extension, default {@code DEFAULT_EXTENSION} if don't get
.addNextParser(new NacosDataJsonParser()); */
public String getFileExtension(String name) {
if (StringUtils.isEmpty(name)) {
return DEFAULT_EXTENSION;
}
int idx = name.lastIndexOf(DOT);
if (idx > 0 && idx < name.length() - 1) {
return name.substring(idx + 1);
}
return DEFAULT_EXTENSION;
}
private String getFileName(String name, String extension) {
if (StringUtils.isEmpty(extension)) {
return name;
}
if (StringUtils.isEmpty(name)) {
return extension;
}
int idx = name.lastIndexOf(DOT);
if (idx > 0 && idx < name.length() - 1) {
String ext = name.substring(idx + 1);
if (extension.equalsIgnoreCase(ext)) {
return name;
}
}
return name + DOT + extension;
} }
public static NacosDataParserHandler getInstance() { public static NacosDataParserHandler getInstance() {

View File

@ -1,66 +0,0 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
* @author zkz
*/
public class NacosDataPropertiesParser extends AbstractNacosDataParser {
private static final Logger log = LoggerFactory
.getLogger(NacosDataPropertiesParser.class);
public NacosDataPropertiesParser() {
super("properties");
}
@Override
protected Map<String, Object> doParse(String data) throws IOException {
Map<String, Object> result = new LinkedHashMap<>();
try (BufferedReader reader = new BufferedReader(new StringReader(data))) {
for (String line = reader.readLine(); line != null; line = reader
.readLine()) {
String dataLine = line.trim();
if (StringUtils.isEmpty(dataLine) || dataLine.startsWith("#")) {
continue;
}
int index = dataLine.indexOf("=");
if (index == -1) {
log.warn("the config data is invalid {}", dataLine);
continue;
}
String key = dataLine.substring(0, index);
String value = dataLine.substring(index + 1);
result.put(key.trim(), value.trim());
}
}
return result;
}
}

View File

@ -1,129 +0,0 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.springframework.util.StringUtils;
/**
* With relatively few usage scenarios, only simple parsing is performed to reduce jar
* dependencies.
*
* @author zkz
*/
public class NacosDataXmlParser extends AbstractNacosDataParser {
public NacosDataXmlParser() {
super("xml");
}
@Override
protected Map<String, Object> doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, Object> map = parseXml2Map(data);
return this.reloadMap(map);
}
private Map<String, Object> parseXml2Map(String xml) throws IOException {
xml = xml.replaceAll("\\r", "").replaceAll("\\n", "").replaceAll("\\t", "");
Map<String, Object> map = new LinkedHashMap<>(32);
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = documentBuilder
.parse(new InputSource(new StringReader(xml)));
if (null == document) {
return null;
}
parseNodeList(document.getChildNodes(), map, "");
}
catch (Exception e) {
throw new IOException("The xml content parse error.", e.getCause());
}
return map;
}
private void parseNodeList(NodeList nodeList, Map<String, Object> map,
String parentKey) {
if (nodeList == null || nodeList.getLength() < 1) {
return;
}
parentKey = parentKey == null ? "" : parentKey;
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String value = node.getNodeValue();
value = value == null ? "" : value.trim();
String name = node.getNodeName();
name = name == null ? "" : name.trim();
if (StringUtils.isEmpty(name)) {
continue;
}
String key = StringUtils.isEmpty(parentKey) ? name : parentKey + DOT + name;
NamedNodeMap nodeMap = node.getAttributes();
parseNodeAttr(nodeMap, map, key);
if (node.getNodeType() == Node.ELEMENT_NODE && node.hasChildNodes()) {
parseNodeList(node.getChildNodes(), map, key);
continue;
}
if (value.length() < 1) {
continue;
}
map.put(parentKey, value);
}
}
private void parseNodeAttr(NamedNodeMap nodeMap, Map<String, Object> map,
String parentKey) {
if (null == nodeMap || nodeMap.getLength() < 1) {
return;
}
for (int i = 0; i < nodeMap.getLength(); i++) {
Node node = nodeMap.item(i);
if (null == node) {
continue;
}
if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
if (StringUtils.isEmpty(node.getNodeName())) {
continue;
}
if (StringUtils.isEmpty(node.getNodeValue())) {
continue;
}
map.put(String.join(DOT, parentKey, node.getNodeName()),
node.getNodeValue());
}
}
}
}

View File

@ -1,44 +0,0 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.nacos.parser;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ByteArrayResource;
/**
* @author zkz
*/
public class NacosDataYamlParser extends AbstractNacosDataParser {
public NacosDataYamlParser() {
super(",yml,yaml,");
}
@Override
protected Map<String, Object> doParse(String data) {
YamlMapFactoryBean yamlFactory = new YamlMapFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
Map<String, Object> result = new LinkedHashMap<>();
flattenedMap(result, yamlFactory.getObject(), EMPTY_STRING);
return result;
}
}

View File

@ -21,21 +21,19 @@ import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.springframework.boot.env.OriginTrackedMapPropertySource; import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.PropertiesPropertySourceLoader; import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/** /**
* Parsing for XML requires overwriting the default * Parsing for XML requires overwriting the default

View File

@ -7,5 +7,4 @@ org.springframework.boot.diagnostics.FailureAnalyzer=\
com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureAnalyzer com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureAnalyzer
org.springframework.boot.env.PropertySourceLoader=\ org.springframework.boot.env.PropertySourceLoader=\
com.alibaba.cloud.nacos.parser.NacosJsonPropertySourceLoader,\ com.alibaba.cloud.nacos.parser.NacosJsonPropertySourceLoader,\
com.alibaba.cloud.nacos.parser.NacosXmlPropertySourceLoader com.alibaba.cloud.nacos.parser.NacosXmlPropertySourceLoader
com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureAnalyzer

View File

@ -1,255 +1,255 @@
///* /*
// * Copyright 2013-2018 the original author or authors. * Copyright 2013-2018 the original author or authors.
// * *
// * Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at * You may obtain a copy of the License at
// * *
// * https://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
// * *
// * Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
// * limitations under the License. * limitations under the License.
// */ */
//
//package com.alibaba.cloud.nacos; package com.alibaba.cloud.nacos;
//
//import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
//import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
//
//import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator; import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
//import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
//import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
//import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
//import com.alibaba.nacos.client.config.NacosConfigService; import com.alibaba.nacos.client.config.NacosConfigService;
//
//import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
//import java.lang.reflect.Method; import java.lang.reflect.Method;
//import java.util.Map; import java.util.Map;
//
//import org.junit.Test; import org.junit.Test;
//import org.junit.runner.RunWith; import org.junit.runner.RunWith;
//import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
//import org.powermock.api.support.MethodProxy; import org.powermock.api.support.MethodProxy;
//import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PowerMockIgnore;
//import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
//import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
//import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.powermock.modules.junit4.PowerMockRunnerDelegate;
//import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
//import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
//import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
//import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
//import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
//
///** /**
// * @author zkz * @author zkz
// */ */
//
//@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
//@PowerMockIgnore({ "javax.management.*", "javax.xml.parsers.*", @PowerMockIgnore({ "javax.management.*", "javax.xml.parsers.*",
// "com.sun.org.apache.xerces.internal.jaxp.*", "org.w3c.dom.*" }) "com.sun.org.apache.xerces.internal.jaxp.*", "org.w3c.dom.*" })
//@PowerMockRunnerDelegate(SpringRunner.class) @PowerMockRunnerDelegate(SpringRunner.class)
//@PrepareForTest({ NacosConfigService.class }) @PrepareForTest({ NacosConfigService.class })
//@SpringBootTest(classes = NacosConfigurationNoSuffixTest.TestConfig.class, properties = { @SpringBootTest(classes = NacosConfigurationNoSuffixTest.TestConfig.class, properties = {
// "spring.application.name=app-no-suffix", "spring.profiles.active=dev", "spring.application.name=app-no-suffix", "spring.profiles.active=dev",
// "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", "spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
// "spring.cloud.nacos.config.namespace=test-namespace", "spring.cloud.nacos.config.namespace=test-namespace",
// "spring.cloud.nacos.config.encode=utf-8", "spring.cloud.nacos.config.encode=utf-8",
// "spring.cloud.nacos.config.timeout=1000", "spring.cloud.nacos.config.timeout=1000",
// "spring.cloud.nacos.config.group=test-group", "spring.cloud.nacos.config.group=test-group",
// "spring.cloud.nacos.config.name=test-no-suffix-name", "spring.cloud.nacos.config.name=test-no-suffix-name",
// "spring.cloud.nacos.config.cluster-name=test-cluster", "spring.cloud.nacos.config.cluster-name=test-cluster",
// "spring.cloud.nacos.config.contextPath=test-contextpath", "spring.cloud.nacos.config.contextPath=test-contextpath",
// "spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json", "spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json",
// "spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties", "spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties",
// "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP", "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
// "spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data2.xml", "spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data2.xml",
// "spring.cloud.nacos.config.accessKey=test-accessKey", "spring.cloud.nacos.config.accessKey=test-accessKey",
// "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE) "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
//public class NacosConfigurationNoSuffixTest { public class NacosConfigurationNoSuffixTest {
//
// static { static {
//
// try { try {
//
// Method method = PowerMockito.method(NacosConfigService.class, "getConfig", Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
// String.class, String.class, long.class); String.class, String.class, long.class);
// MethodProxy.proxy(method, new InvocationHandler() { MethodProxy.proxy(method, new InvocationHandler() {
// @Override @Override
// public Object invoke(Object proxy, Method method, Object[] args) public Object invoke(Object proxy, Method method, Object[] args)
// throws Throwable { throws Throwable {
//
// if ("app-no-suffix".equals(args[0]) && "test-group".equals(args[1])) { if ("app-no-suffix".equals(args[0]) && "test-group".equals(args[1])) {
// return "test-no-suffix=value-no-suffix-1"; return "test-no-suffix=value-no-suffix-1";
// } }
// if ("app-no-suffix.properties".equals(args[0]) if ("app-no-suffix.properties".equals(args[0])
// && "test-group".equals(args[1])) { && "test-group".equals(args[1])) {
// return "test-no-suffix=value-no-suffix-2"; return "test-no-suffix=value-no-suffix-2";
// } }
//
// if ("test-no-suffix-name".equals(args[0]) if ("test-no-suffix-name".equals(args[0])
// && "test-group".equals(args[1])) { && "test-group".equals(args[1])) {
// return "test-no-suffix-assign=assign-value-no-suffix-111"; return "test-no-suffix-assign=assign-value-no-suffix-111";
// } }
// if ("test-no-suffix-name.properties".equals(args[0]) if ("test-no-suffix-name.properties".equals(args[0])
// && "test-group".equals(args[1])) { && "test-group".equals(args[1])) {
// return "test-no-suffix-assign=assign-value-no-suffix-222"; return "test-no-suffix-assign=assign-value-no-suffix-222";
// } }
// if ("test-no-suffix-name-dev.properties".equals(args[0]) if ("test-no-suffix-name-dev.properties".equals(args[0])
// && "test-group".equals(args[1])) { && "test-group".equals(args[1])) {
// return "test-no-suffix-assign=assign-dev-value-no-suffix-333"; return "test-no-suffix-assign=assign-dev-value-no-suffix-333";
// } }
//
// if ("ext-json-test.json".equals(args[0]) if ("ext-json-test.json".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) { && "DEFAULT_GROUP".equals(args[1])) {
// return "{\n" + " \"people\":{\n" return "{\n" + " \"people\":{\n"
// + " \"firstName\":\"Brett\",\n" + " \"firstName\":\"Brett\",\n"
// + " \"lastName\":\"McLaughlin\"\n" + " }\n" + " \"lastName\":\"McLaughlin\"\n" + " }\n"
// + "}"; + "}";
// } }
//
// if ("ext-config-common02.properties".equals(args[0]) if ("ext-config-common02.properties".equals(args[0])
// && "GLOBAL_GROUP".equals(args[1])) { && "GLOBAL_GROUP".equals(args[1])) {
// return "global-ext-config=global-config-value-2"; return "global-ext-config=global-config-value-2";
// } }
//
// if ("shared-data1.properties".equals(args[0]) if ("shared-data1.properties".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) { && "DEFAULT_GROUP".equals(args[1])) {
// return "shared-name=shared-value-1"; return "shared-name=shared-value-1";
// } }
//
// if ("shared-data2.xml".equals(args[0]) if ("shared-data2.xml".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) { && "DEFAULT_GROUP".equals(args[1])) {
// return "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n" return "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n"
// + " <Service name=\"Catalina\"> \n" + " <Service name=\"Catalina\"> \n"
// + " <Connector value=\"第二个连接器\"> \n" + " <Connector value=\"第二个连接器\"> \n"
// + " <open>开启服务</open> \n" + " <open>开启服务</open> \n"
// + " <init>初始化一下</init> \n" + " <init>初始化一下</init> \n"
// + " <process>\n" + " <top>\n" + " <process>\n" + " <top>\n"
// + " <first>one</first>\n" + " <first>one</first>\n"
// + " <sencond value=\"two\">\n" + " <sencond value=\"two\">\n"
// + " <third>three</third>\n" + " <third>three</third>\n"
// + " </sencond>\n" + " </sencond>\n"
// + " </top>\n" + " </process> \n" + " </top>\n" + " </process> \n"
// + " <destory>销毁一下</destory> \n" + " <destory>销毁一下</destory> \n"
// + " <close>关闭服务</close> \n" + " <close>关闭服务</close> \n"
// + " </Connector> \n" + " </Service> \n" + " </Connector> \n" + " </Service> \n"
// + "</Server> "; + "</Server> ";
// } }
//
// return ""; return "";
// } }
// }); });
//
// } }
// catch (Exception ignore) { catch (Exception ignore) {
// ignore.printStackTrace(); ignore.printStackTrace();
//
// } }
// } }
//
// @Autowired @Autowired
// private NacosPropertySourceLocator locator; private NacosPropertySourceLocator locator;
//
// @Autowired @Autowired
// private NacosConfigProperties properties; private NacosConfigProperties properties;
//
// @Autowired @Autowired
// private NacosRefreshHistory refreshHistory; private NacosRefreshHistory refreshHistory;
//
// @Autowired @Autowired
// private Environment environment; private Environment environment;
//
// @Test @Test
// public void contextLoads() throws Exception { public void contextLoads() throws Exception {
//
// assertThat(locator).isNotNull(); assertThat(locator).isNotNull();
// assertThat(properties).isNotNull(); assertThat(properties).isNotNull();
//
// checkoutNacosConfigServerAddr(); checkoutNacosConfigServerAddr();
// checkoutNacosConfigNamespace(); checkoutNacosConfigNamespace();
// checkoutNacosConfigClusterName(); checkoutNacosConfigClusterName();
// checkoutNacosConfigAccessKey(); checkoutNacosConfigAccessKey();
// checkoutNacosConfigSecrectKey(); checkoutNacosConfigSecrectKey();
// checkoutNacosConfigName(); checkoutNacosConfigName();
// checkoutNacosConfigGroup(); checkoutNacosConfigGroup();
// checkoutNacosConfigContextPath(); checkoutNacosConfigContextPath();
// checkoutNacosConfigFileExtension(); checkoutNacosConfigFileExtension();
// checkoutNacosConfigTimeout(); checkoutNacosConfigTimeout();
// checkoutNacosConfigEncode(); checkoutNacosConfigEncode();
//
// checkoutEndpoint(); checkoutEndpoint();
// checkEnvironmentProperties(); checkEnvironmentProperties();
// } }
//
// private void checkEnvironmentProperties() { private void checkEnvironmentProperties() {
// assertThat(environment.getProperty("test-no-suffix")).isNull(); assertThat(environment.getProperty("test-no-suffix")).isNull();
// assertThat(environment.getProperty("test-no-suffix-assign")) assertThat(environment.getProperty("test-no-suffix-assign"))
// .isEqualTo("assign-dev-value-no-suffix-333"); .isEqualTo("assign-dev-value-no-suffix-333");
// } }
//
// private void checkoutNacosConfigServerAddr() { private void checkoutNacosConfigServerAddr() {
// assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848"); assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848");
// } }
//
// private void checkoutNacosConfigNamespace() { private void checkoutNacosConfigNamespace() {
// assertThat(properties.getNamespace()).isEqualTo("test-namespace"); assertThat(properties.getNamespace()).isEqualTo("test-namespace");
// } }
//
// private void checkoutNacosConfigClusterName() { private void checkoutNacosConfigClusterName() {
// assertThat(properties.getClusterName()).isEqualTo("test-cluster"); assertThat(properties.getClusterName()).isEqualTo("test-cluster");
// } }
//
// private void checkoutNacosConfigAccessKey() { private void checkoutNacosConfigAccessKey() {
// assertThat(properties.getAccessKey()).isEqualTo("test-accessKey"); assertThat(properties.getAccessKey()).isEqualTo("test-accessKey");
// } }
//
// private void checkoutNacosConfigSecrectKey() { private void checkoutNacosConfigSecrectKey() {
// assertThat(properties.getSecretKey()).isEqualTo("test-secretKey"); assertThat(properties.getSecretKey()).isEqualTo("test-secretKey");
// } }
//
// private void checkoutNacosConfigContextPath() { private void checkoutNacosConfigContextPath() {
// assertThat(properties.getContextPath()).isEqualTo("test-contextpath"); assertThat(properties.getContextPath()).isEqualTo("test-contextpath");
// } }
//
// private void checkoutNacosConfigName() { private void checkoutNacosConfigName() {
// assertThat(properties.getName()).isEqualTo("test-no-suffix-name"); assertThat(properties.getName()).isEqualTo("test-no-suffix-name");
// } }
//
// private void checkoutNacosConfigGroup() { private void checkoutNacosConfigGroup() {
// assertThat(properties.getGroup()).isEqualTo("test-group"); assertThat(properties.getGroup()).isEqualTo("test-group");
// } }
//
// private void checkoutNacosConfigFileExtension() { private void checkoutNacosConfigFileExtension() {
// assertThat(properties.getFileExtension()).isEqualTo("properties"); assertThat(properties.getFileExtension()).isEqualTo("properties");
// } }
//
// private void checkoutNacosConfigTimeout() { private void checkoutNacosConfigTimeout() {
// assertThat(properties.getTimeout()).isEqualTo(1000); assertThat(properties.getTimeout()).isEqualTo(1000);
// } }
//
// private void checkoutNacosConfigEncode() { private void checkoutNacosConfigEncode() {
// assertThat(properties.getEncode()).isEqualTo("utf-8"); assertThat(properties.getEncode()).isEqualTo("utf-8");
// } }
//
// private void checkoutEndpoint() throws Exception { private void checkoutEndpoint() throws Exception {
// NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties, NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
// refreshHistory); refreshHistory);
// Map<String, Object> map = nacosConfigEndpoint.invoke(); Map<String, Object> map = nacosConfigEndpoint.invoke();
// assertThat(properties).isEqualTo(map.get("NacosConfigProperties")); assertThat(properties).isEqualTo(map.get("NacosConfigProperties"));
// assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory")); assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory"));
// } }
//
// @Configuration @Configuration
// @EnableAutoConfiguration @EnableAutoConfiguration
// @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
// NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
// public static class TestConfig { public static class TestConfig {
//
// } }
//
//} }

View File

@ -1,285 +1,281 @@
///* /*
// * Copyright 2013-2018 the original author or authors. * Copyright 2013-2018 the original author or authors.
// * *
// * Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at * You may obtain a copy of the License at
// * *
// * https://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
// * *
// * Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
// * limitations under the License. * limitations under the License.
// */ */
//
//package com.alibaba.cloud.nacos; package com.alibaba.cloud.nacos;
//
//import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.InvocationHandler;
//import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; import java.lang.reflect.Method;
// import java.util.Map;
//import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
//import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint; import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
//import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
//import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
//import com.alibaba.nacos.client.config.NacosConfigService; import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
// import com.alibaba.nacos.client.config.NacosConfigService;
//import java.lang.reflect.InvocationHandler; import org.junit.Test;
//import java.lang.reflect.Method; import org.junit.runner.RunWith;
//import java.util.Map; import org.powermock.api.mockito.PowerMockito;
// import org.powermock.api.support.MethodProxy;
//import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore;
//import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest;
//import org.powermock.api.mockito.PowerMockito; import org.powermock.modules.junit4.PowerMockRunner;
//import org.powermock.api.support.MethodProxy; import org.powermock.modules.junit4.PowerMockRunnerDelegate;
//import org.powermock.core.classloader.annotations.PowerMockIgnore;
//import org.powermock.core.classloader.annotations.PrepareForTest; import org.springframework.beans.factory.annotation.Autowired;
//import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
//import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
//import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration;
//import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.core.env.Environment;
//import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.env.Environment; import static org.assertj.core.api.Assertions.assertThat;
//import org.springframework.test.context.junit4.SpringRunner; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
//
///** /**
// * @author zkz * @author zkz
// */ */
//@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
//@PowerMockIgnore({ "javax.management.*", "javax.xml.parsers.*", @PowerMockIgnore("javax.management.*")
// "com.sun.org.apache.xerces.internal.jaxp.*", "org.w3c.dom.*" }) @PowerMockRunnerDelegate(SpringRunner.class)
//@PowerMockRunnerDelegate(SpringRunner.class) @PrepareForTest({ NacosConfigService.class })
//@PrepareForTest({ NacosConfigService.class }) @SpringBootTest(classes = NacosConfigurationXmlJsonTest.TestConfig.class, properties = {
//@SpringBootTest(classes = NacosConfigurationXmlJsonTest.TestConfig.class, properties = { "spring.application.name=xmlApp", "spring.profiles.active=dev",
// "spring.application.name=xmlApp", "spring.profiles.active=dev", "spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
// "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", "spring.cloud.nacos.config.namespace=test-namespace",
// "spring.cloud.nacos.config.namespace=test-namespace", "spring.cloud.nacos.config.encode=utf-8",
// "spring.cloud.nacos.config.encode=utf-8", "spring.cloud.nacos.config.timeout=1000",
// "spring.cloud.nacos.config.timeout=1000", "spring.cloud.nacos.config.group=test-group",
// "spring.cloud.nacos.config.group=test-group", "spring.cloud.nacos.config.name=test-name",
// "spring.cloud.nacos.config.name=test-name", "spring.cloud.nacos.config.cluster-name=test-cluster",
// "spring.cloud.nacos.config.cluster-name=test-cluster", "spring.cloud.nacos.config.file-extension=xml",
// "spring.cloud.nacos.config.file-extension=xml", "spring.cloud.nacos.config.contextPath=test-contextpath",
// "spring.cloud.nacos.config.contextPath=test-contextpath", "spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json",
// "spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json", "spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties",
// "spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties", "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
// "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP", "spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data.json",
// "spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data.json", "spring.cloud.nacos.config.accessKey=test-accessKey",
// "spring.cloud.nacos.config.accessKey=test-accessKey", "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
// "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE) public class NacosConfigurationXmlJsonTest {
//public class NacosConfigurationXmlJsonTest {
// static {
// static {
// try {
// try {
// Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
// Method method = PowerMockito.method(NacosConfigService.class, "getConfig", String.class, String.class, long.class);
// String.class, String.class, long.class); MethodProxy.proxy(method, new InvocationHandler() {
// MethodProxy.proxy(method, new InvocationHandler() { @Override
// @Override public Object invoke(Object proxy, Method method, Object[] args)
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// throws Throwable {
// if ("xmlApp.xml".equals(args[0]) && "test-group".equals(args[1])) {
// if ("xmlApp.xml".equals(args[0]) && "test-group".equals(args[1])) { return "<top>\n" + " <first>one</first>\n"
// return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<top>\n" + " <sencond value=\"two\">\n"
// + " <first>one</first>\n" + " <third>three</third>\n" + " </sencond>\n"
// + " <sencond value=\"two\">\n" + "</top>";
// + " <third>three</third>\n" + " </sencond>\n" }
// + "</top>"; if ("test-name.xml".equals(args[0]) && "test-group".equals(args[1])) {
// } return "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n"
// if ("test-name.xml".equals(args[0]) && "test-group".equals(args[1])) { + " <Service name=\"Catalina\"> \n"
// return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + " <Connector value=\"第二个连接器\"> \n"
// + "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n" + " <open>开启服务</open> \n"
// + " <Service name=\"Catalina\"> \n" + " <init>初始化一下</init> \n"
// + " <Connector value=\"第二个连接器\"> \n" + " <process>\n" + " <top>\n"
// + " <open>开启服务</open> \n" + " <first>one</first>\n"
// + " <init>初始化一下</init> \n" + " <sencond value=\"two\">\n"
// + " <process>\n" + " <top>\n" + " <third>three</third>\n"
// + " <first>one</first>\n" + " </sencond>\n"
// + " <sencond value=\"two\">\n" + " </top>\n" + " </process> \n"
// + " <third>three</third>\n" + " <destory>销毁一下</destory> \n"
// + " </sencond>\n" + " <close>关闭服务</close> \n"
// + " </top>\n" + " </process> \n" + " </Connector> \n" + " </Service> \n"
// + " <destory>销毁一下</destory> \n" + "</Server> ";
// + " <close>关闭服务</close> \n" }
// + " </Connector> \n" + " </Service> \n"
// + "</Server> "; if ("test-name-dev.xml".equals(args[0])
// } && "test-group".equals(args[1])) {
// return "<application android:label=\"@string/app_name\" android:icon=\"@drawable/osg\">\n"
// if ("test-name-dev.xml".equals(args[0]) + " <activity android:name=\".osgViewer\"\n"
// && "test-group".equals(args[1])) { + " android:label=\"@string/app_name\" android:screenOrientation=\"landscape\">\n"
// return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + " <intent-filter>\n"
// + "<application android:label=\"@string/app_name\" android:icon=\"@drawable/osg\">\n" + " <action android:name=\"android.intent.action.MAIN\" />\n"
// + " <activity android:name=\".osgViewer\"\n" + " <category android:name=\"android.intent.category.LAUNCHER\" />\n"
// + " android:label=\"@string/app_name\" android:screenOrientation=\"landscape\">\n" + " </intent-filter>\n" + " </activity>\n"
// + " <intent-filter>\n" + "</application>";
// + " <action android:name=\"android.intent.action.MAIN\" />\n" }
// + " <category android:name=\"android.intent.category.LAUNCHER\" />\n"
// + " </intent-filter>\n" + " </activity>\n" if ("ext-json-test.json".equals(args[0])
// + "</application>"; && "DEFAULT_GROUP".equals(args[1])) {
// } return "{\n" + " \"people\":{\n"
// + " \"firstName\":\"Brett\",\n"
// if ("ext-json-test.json".equals(args[0]) + " \"lastName\":\"McLaughlin\"\n" + " }\n"
// && "DEFAULT_GROUP".equals(args[1])) { + "}";
// return "{\n" + " \"people\":{\n" }
// + " \"firstName\":\"Brett\",\n"
// + " \"lastName\":\"McLaughlin\"\n" + " }\n" if ("ext-config-common02.properties".equals(args[0])
// + "}"; && "GLOBAL_GROUP".equals(args[1])) {
// } return "global-ext-config=global-config-value-2";
// }
// if ("ext-config-common02.properties".equals(args[0])
// && "GLOBAL_GROUP".equals(args[1])) { if ("shared-data1.properties".equals(args[0])
// return "global-ext-config=global-config-value-2"; && "DEFAULT_GROUP".equals(args[1])) {
// } return "shared-name=shared-value-1";
// }
// if ("shared-data1.properties".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) { if ("shared-data.json".equals(args[0])
// return "shared-name=shared-value-1"; && "DEFAULT_GROUP".equals(args[1])) {
// } return "{\n" + " \"test\" : {\n"
// + " \"name\" : \"test\",\n"
// if ("shared-data.json".equals(args[0]) + " \"list\" : [\n" + " {\n"
// && "DEFAULT_GROUP".equals(args[1])) { + " \"name\" :\"listname1\",\n"
// return "{\n" + " \"test\" : {\n" + " \"age\":1\n" + " },\n"
// + " \"name\" : \"test\",\n" + " {\n"
// + " \"list\" : [\n" + " {\n" + " \"name\" :\"listname2\",\n"
// + " \"name\" :\"listname1\",\n" + " \"age\":2\n" + " }\n"
// + " \"age\":1\n" + " },\n" + " ],\n" + " \"metadata\" : {\n"
// + " {\n" + " \"intKey\" : 123,\n"
// + " \"name\" :\"listname2\",\n" + " \"booleanKey\" : true\n" + " }\n"
// + " \"age\":2\n" + " }\n" + " }\n" + "}";
// + " ],\n" + " \"metadata\" : {\n" }
// + " \"intKey\" : 123,\n"
// + " \"booleanKey\" : true\n" + " }\n" return "";
// + " }\n" + "}"; }
// } });
//
// return ""; }
// } catch (Exception ignore) {
// }); ignore.printStackTrace();
//
// } }
// catch (Exception ignore) { }
// ignore.printStackTrace();
// @Autowired
// } private NacosPropertySourceLocator locator;
// }
// @Autowired
// @Autowired private NacosConfigProperties properties;
// private NacosPropertySourceLocator locator;
// @Autowired
// @Autowired private NacosRefreshHistory refreshHistory;
// private NacosConfigProperties properties;
// @Autowired
// @Autowired private Environment environment;
// private NacosRefreshHistory refreshHistory;
// @Test
// @Autowired public void contextLoads() throws Exception {
// private Environment environment;
// assertThat(locator).isNotNull();
// @Test assertThat(properties).isNotNull();
// public void contextLoads() throws Exception {
// checkoutNacosConfigServerAddr();
// assertThat(locator).isNotNull(); checkoutNacosConfigNamespace();
// assertThat(properties).isNotNull(); checkoutNacosConfigClusterName();
// checkoutNacosConfigAccessKey();
// checkoutNacosConfigServerAddr(); checkoutNacosConfigSecrectKey();
// checkoutNacosConfigNamespace(); checkoutNacosConfigName();
// checkoutNacosConfigClusterName(); checkoutNacosConfigGroup();
// checkoutNacosConfigAccessKey(); checkoutNacosConfigContextPath();
// checkoutNacosConfigSecrectKey(); checkoutNacosConfigFileExtension();
// checkoutNacosConfigName(); checkoutNacosConfigTimeout();
// checkoutNacosConfigGroup(); checkoutNacosConfigEncode();
// checkoutNacosConfigContextPath();
// checkoutNacosConfigFileExtension(); checkoutEndpoint();
// checkoutNacosConfigTimeout();
// checkoutNacosConfigEncode(); checkJsonParser();
// }
// checkoutEndpoint();
// private void checkJsonParser() {
// checkJsonParser(); assertThat(environment.getProperty("test.name", String.class)).isEqualTo("test");
// }
// assertThat(environment.getProperty("test.list[0].name", String.class))
// private void checkJsonParser() { .isEqualTo("listname1");
// assertThat(environment.getProperty("test.name", String.class)).isEqualTo("test"); assertThat(environment.getProperty("test.list[0].age", Integer.class))
// .isEqualTo(1);
// assertThat(environment.getProperty("test.list[0].name", String.class))
// .isEqualTo("listname1"); assertThat(environment.getProperty("test.list[1].name", String.class))
// assertThat(environment.getProperty("test.list[0].age", Integer.class)) .isEqualTo("listname2");
// .isEqualTo(1); assertThat(environment.getProperty("test.list[1].age", Integer.class))
// .isEqualTo(2);
// assertThat(environment.getProperty("test.list[1].name", String.class))
// .isEqualTo("listname2"); assertThat(
// assertThat(environment.getProperty("test.list[1].age", Integer.class)) (Integer) environment.getProperty("test.metadata.intKey", Object.class))
// .isEqualTo(2); .isEqualTo(123);
// assertThat((Boolean) environment.getProperty("test.metadata.booleanKey",
// assertThat( Object.class)).isEqualTo(true);
// (Integer) environment.getProperty("test.metadata.intKey", Object.class)) }
// .isEqualTo(123);
// assertThat((Boolean) environment.getProperty("test.metadata.booleanKey", private void checkoutNacosConfigServerAddr() {
// Object.class)).isEqualTo(true); assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848");
// } }
//
// private void checkoutNacosConfigServerAddr() { private void checkoutNacosConfigNamespace() {
// assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848"); assertThat(properties.getNamespace()).isEqualTo("test-namespace");
// } }
//
// private void checkoutNacosConfigNamespace() { private void checkoutNacosConfigClusterName() {
// assertThat(properties.getNamespace()).isEqualTo("test-namespace"); assertThat(properties.getClusterName()).isEqualTo("test-cluster");
// } }
//
// private void checkoutNacosConfigClusterName() { private void checkoutNacosConfigAccessKey() {
// assertThat(properties.getClusterName()).isEqualTo("test-cluster"); assertThat(properties.getAccessKey()).isEqualTo("test-accessKey");
// } }
//
// private void checkoutNacosConfigAccessKey() { private void checkoutNacosConfigSecrectKey() {
// assertThat(properties.getAccessKey()).isEqualTo("test-accessKey"); assertThat(properties.getSecretKey()).isEqualTo("test-secretKey");
// } }
//
// private void checkoutNacosConfigSecrectKey() { private void checkoutNacosConfigContextPath() {
// assertThat(properties.getSecretKey()).isEqualTo("test-secretKey"); assertThat(properties.getContextPath()).isEqualTo("test-contextpath");
// } }
//
// private void checkoutNacosConfigContextPath() { private void checkoutNacosConfigName() {
// assertThat(properties.getContextPath()).isEqualTo("test-contextpath"); assertThat(properties.getName()).isEqualTo("test-name");
// } }
//
// private void checkoutNacosConfigName() { private void checkoutNacosConfigGroup() {
// assertThat(properties.getName()).isEqualTo("test-name"); assertThat(properties.getGroup()).isEqualTo("test-group");
// } }
//
// private void checkoutNacosConfigGroup() { private void checkoutNacosConfigFileExtension() {
// assertThat(properties.getGroup()).isEqualTo("test-group"); assertThat(properties.getFileExtension()).isEqualTo("xml");
// } }
//
// private void checkoutNacosConfigFileExtension() { private void checkoutNacosConfigTimeout() {
// assertThat(properties.getFileExtension()).isEqualTo("xml"); assertThat(properties.getTimeout()).isEqualTo(1000);
// } }
//
// private void checkoutNacosConfigTimeout() { private void checkoutNacosConfigEncode() {
// assertThat(properties.getTimeout()).isEqualTo(1000); assertThat(properties.getEncode()).isEqualTo("utf-8");
// } }
//
// private void checkoutNacosConfigEncode() { private void checkoutEndpoint() throws Exception {
// assertThat(properties.getEncode()).isEqualTo("utf-8"); NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
// } refreshHistory);
// Map<String, Object> map = nacosConfigEndpoint.invoke();
// private void checkoutEndpoint() throws Exception { assertThat(properties).isEqualTo(map.get("NacosConfigProperties"));
// NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties, assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory"));
// refreshHistory); }
// Map<String, Object> map = nacosConfigEndpoint.invoke();
// assertThat(properties).isEqualTo(map.get("NacosConfigProperties")); @Configuration
// assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory")); @EnableAutoConfiguration
// } @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
// NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
// @Configuration public static class TestConfig {
// @EnableAutoConfiguration
// @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, }
// NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
// public static class TestConfig { }
//
// }
//
//}