Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicecomb.foundation.common.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;

public final class FileUtils {
private FileUtils() {

}

// result is path of a directory or a jar
// eg:
// io.servicecomb.foundation.common.utils.ResourceUtils -> ....../target/classes
// org.apache.commons.codec.binary.StringUtils -> ....../commons-codec/commons-codec/1.9/commons-codec-1.9.jar
public static String findRootPath(Class<?> cls) {
String resourceName =
"/" + ClassUtils.convertClassNameToResourcePath(cls.getName()) + ClassUtils.CLASS_FILE_SUFFIX;
URL url = cls.getResource(resourceName);
return findRootPath(url, resourceName);
}

// ....../target/classes/config/conf.xml -> ....../target/classes/
public static String findRootPath(URL url, String suffix) {
String path = url.getPath();
try {
// convert 'a%20b' to 'a b'
path = URLDecoder.decode(path, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Failed to decode url, path=" + path, e);
}
if (!path.endsWith(suffix)) {
throw new IllegalArgumentException(String.format("url '%s' is not end with '%s'.", path, suffix));
}

if (ResourceUtils.isJarURL(url)) {
// protocol:/....jar!....suffix
int idx = path.indexOf('!');
path = path.substring(url.getProtocol().length() + 2, idx);
} else {
path = path.substring(0, path.length() - suffix.length());
}

File file = new File(path);
return file.getPath();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicecomb.foundation.common.utils;

import java.io.File;
import java.net.URL;

import org.junit.Assert;
import org.junit.Test;

public class TestFileUtils {
@Test
public void testFileClassRootPath() {
String path = FileUtils.findRootPath(FileUtils.class);
File file = new File(path, FileUtils.class.getName().replace('.', '/') + ".class");
Assert.assertTrue(file.exists());
}

@Test
public void testJarClassRootPath() {
String path = FileUtils.findRootPath(String.class);
File file = new File(path);
Assert.assertTrue(file.exists());
}

@Test
public void testFileUrlRootPath() {
String suffix = "config/config.inc.xml";
URL url = Thread.currentThread().getContextClassLoader().getResource(suffix);
String path = FileUtils.findRootPath(url, suffix);
File file = new File(path, suffix);
Assert.assertTrue(file.exists());

String invalidSuffix = suffix + "x";
try {
FileUtils.findRootPath(url, invalidSuffix);
Assert.fail("must throw exception");
} catch (IllegalArgumentException e) {
Assert.assertEquals(
String.format("url '%s' is not end with '%s'.", url.getPath(), invalidSuffix),
e.getMessage());
}
}

@Test
public void testJarUrlRootPath() {
String suffix = "META-INF/maven/commons-codec/commons-codec/pom.xml";
URL url = Thread.currentThread().getContextClassLoader().getResource(suffix);
String path = FileUtils.findRootPath(url, suffix);
File file = new File(path);
Assert.assertTrue(file.exists());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import org.springframework.util.ResourceUtils;

import io.servicecomb.foundation.common.utils.FileUtils;

public abstract class AbstractConfigLoader {
protected String orderKey = "config-order";

Expand Down Expand Up @@ -54,9 +57,9 @@ public ConfigModel load(URL url, String resourceName) throws IOException {

ConfigModel configModel = new ConfigModel();
configModel.setUrl(url);
// if (resourceName != null) {
// configModel.setRootPath(FileUtils.findRootPath(url, resourceName));
// }
if (resourceName != null) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the resourceName is null , it's better to throw the exception here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resourceName is null when load additional config.
it's normal, not a exception

configModel.setRootPath(FileUtils.findRootPath(url, resourceName));
}
configModel.setConfig(config);
Object objOrder = config.get(orderKey);
if (objOrder != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package io.servicecomb.config;

import java.io.File;
import java.util.List;

import org.apache.commons.configuration.AbstractConfiguration;
Expand All @@ -33,6 +34,6 @@ public void testCreateDynamicConfig() {
List<ConfigModel> list = loader.getConfigModels();
Assert.assertEquals(loader, ConfigUtil.getMicroserviceConfigLoader(dynamicConfig));
Assert.assertEquals(1, list.size());
// Assert.assertTrue(new File(list.get(0).getRootPath()).exists());
Assert.assertTrue(new File(list.get(0).getRootPath()).exists());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import io.servicecomb.serviceregistry.api.Const;

/**
* Created by on 2016/12/5.
* Created by on 2016/12/5.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Microservice {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,11 @@
public class MicroserviceDefinition {
private static final Logger LOGGER = LoggerFactory.getLogger(MicroserviceDefinition.class);

// microservice.yaml parent path
// microservice.yaml root path
// if need to find microservice by root path, then rootPath must not be empty
private String rootPath;

private List<ConfigModel> configModelList;
private List<ConfigModel> configModels;

private Configuration configuration;

Expand All @@ -43,22 +44,22 @@ public String getMicroserviceName() {
return microserviceName;
}

public MicroserviceDefinition(List<ConfigModel> configModelList) {
if (configModelList == null || configModelList.isEmpty()) {
throw new IllegalArgumentException("configModelList can not be null or empty.");
public MicroserviceDefinition(List<ConfigModel> configModels) {
if (configModels == null || configModels.isEmpty()) {
throw new IllegalArgumentException("configModels can not be null or empty.");
}

this.rootPath = configModelList.get(0).getRootPath();
this.configModelList = configModelList;
this.configuration = ConfigUtil.createConfig(configModelList);
this.rootPath = configModels.get(0).getRootPath();
this.configModels = configModels;
this.configuration = ConfigUtil.createConfig(configModels);
this.microserviceName = configuration.getString(DefinitionConst.qulifiedServiceNameKey);

// log paths first, even microserviceName is invalid, this can help user to find problems
logConfigPath();

// the configuration we used
// when resolve placeholder failed
// the result will remain ${var}......
// the result will remains ${var}
if (StringUtils.isEmpty(microserviceName) || microserviceName.indexOf("${") != -1) {
throw new IllegalArgumentException("MicroserviceName " + microserviceName + " is invalid.");
}
Expand All @@ -67,7 +68,7 @@ public MicroserviceDefinition(List<ConfigModel> configModelList) {
// microserviceName maybe null
public void logConfigPath() {
List<String> pathList = new ArrayList<>();
for (ConfigModel configModel : configModelList) {
for (ConfigModel configModel : configModels) {
pathList.add(configModel.getUrl().toString());
}
LOGGER.info("load microservice config, name={}, rootPath={}, paths={}",
Expand All @@ -80,8 +81,8 @@ public String getRootPath() {
return rootPath;
}

public List<ConfigModel> getConfigModelList() {
return configModelList;
public List<ConfigModel> getConfigModels() {
return configModels;
}

public Configuration getConfiguration() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package io.servicecomb.serviceregistry.definition;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
Expand Down Expand Up @@ -60,8 +61,8 @@ private ConfigModel createConfigModel(String app, String name) throws MalformedU
public void testDefaultAppId() {
MicroserviceDefinitionManager microserviceDefinitionManager = createMicroserviceDefinitionManager();
Assert.assertEquals("default", microserviceDefinitionManager.getAppId());
// Assert.assertEquals(new File(this.getClass().getClassLoader().getResource("").getPath()).getPath(),
// microserviceDefinitionManager.getDefinitionMap().get("default").getRootPath());
Assert.assertEquals(new File(this.getClass().getClassLoader().getResource("").getPath()).getPath(),
microserviceDefinitionManager.getDefinitionMap().get("default").getRootPath());
}

@Test
Expand All @@ -85,8 +86,7 @@ public void testMultiAppId() throws MalformedURLException {
createMicroserviceDefinitionManager(c1, c2);
Assert.assertEquals(1, 2);
} catch (Throwable e) {
Assert.assertEquals("Not allowed multiple appId in one process, but have app1 and app2.",
e.getMessage());
Assert.assertEquals("Not allowed multiple appId in one process, but have app1 and app2.", e.getMessage());
}
}

Expand All @@ -102,8 +102,7 @@ public void testDuplicateMicroserviceName() throws MalformedURLException {
createMicroserviceDefinitionManager(c1, c2);
Assert.fail("should throw exception");
} catch (IllegalArgumentException e) {
Assert.assertEquals("Create from [default, ${ms1}, ${ms2}], but get [default, ms]",
e.getMessage());
Assert.assertEquals("Create from [default, ${ms1}, ${ms2}], but get [default, ms]", e.getMessage());
}
}

Expand All @@ -115,8 +114,7 @@ public void testInvalidMicroserviceName() throws MalformedURLException {
createMicroserviceDefinitionManager(c1);
Assert.assertEquals(1, 2);
} catch (Throwable e) {
Assert.assertEquals("MicroserviceName ${var} is invalid.",
e.getMessage());
Assert.assertEquals("MicroserviceName ${var} is invalid.", e.getMessage());
}
}
}