From a96f98acce131a2ef0efb242c2eda2cc3e45bb70 Mon Sep 17 00:00:00 2001 From: wujimin Date: Sat, 6 Jul 2019 22:12:29 +0800 Subject: [PATCH 1/2] [SCB-1348[WIP][WEAK] change SchemaLoader to SwaggerLoader --- .../serviceregistry/RegistryUtils.java | 4 + .../consumer/StaticMicroserviceVersions.java | 7 +- .../registry/ServiceRegistryFactory.java | 3 +- .../swagger/SwaggerLoader.java | 90 +++++++++++++++---- .../swagger/TestSwaggerLoader.java | 84 ++++++++++++++++- 5 files changed, 166 insertions(+), 22 deletions(-) diff --git a/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/RegistryUtils.java b/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/RegistryUtils.java index e75eeec1980..cdfad6bc8ea 100644 --- a/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/RegistryUtils.java +++ b/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/RegistryUtils.java @@ -58,6 +58,10 @@ private RegistryUtils() { } public static void init() { + if (serviceRegistry != null) { + return; + } + MicroserviceConfigLoader loader = ConfigUtil.getMicroserviceConfigLoader(); MicroserviceDefinition microserviceDefinition = new MicroserviceDefinition(loader.getConfigModels()); serviceRegistry = diff --git a/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/consumer/StaticMicroserviceVersions.java b/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/consumer/StaticMicroserviceVersions.java index 99b144aed90..1df2a23d492 100644 --- a/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/consumer/StaticMicroserviceVersions.java +++ b/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/consumer/StaticMicroserviceVersions.java @@ -25,6 +25,9 @@ import org.apache.servicecomb.serviceregistry.api.response.FindInstancesResponse; import org.apache.servicecomb.serviceregistry.client.http.MicroserviceInstances; import org.apache.servicecomb.serviceregistry.version.Version; +import org.apache.servicecomb.swagger.SwaggerUtils; + +import io.swagger.models.Swagger; public class StaticMicroserviceVersions extends MicroserviceVersions { private Class schemaIntfCls; @@ -40,7 +43,9 @@ public StaticMicroserviceVersions(AppManager appManager, String appId, String mi public StaticMicroserviceVersions init(Class schemaIntfCls, String version, List addedInstances) { this.schemaIntfCls = schemaIntfCls; - this.appManager.getServiceRegistry().getSwaggerLoader().registerSwagger(appId, shortName, shortName, schemaIntfCls); + Swagger swagger = this.appManager.getServiceRegistry().getSwaggerLoader() + .registerSwagger(appId, shortName, shortName, schemaIntfCls); + microservice.addSchema(shortName, SwaggerUtils.swaggerToString(swagger)); createMicroservice(version); diff --git a/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/registry/ServiceRegistryFactory.java b/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/registry/ServiceRegistryFactory.java index 1acccad3dd2..ce44b79473a 100644 --- a/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/registry/ServiceRegistryFactory.java +++ b/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/registry/ServiceRegistryFactory.java @@ -18,6 +18,7 @@ package org.apache.servicecomb.serviceregistry.registry; import org.apache.servicecomb.config.archaius.sources.MicroserviceConfigLoader; +import org.apache.servicecomb.foundation.common.event.SimpleEventBus; import org.apache.servicecomb.serviceregistry.ServiceRegistry; import org.apache.servicecomb.serviceregistry.client.LocalServiceRegistryClientImpl; import org.apache.servicecomb.serviceregistry.config.ServiceRegistryConfig; @@ -62,7 +63,7 @@ public static ServiceRegistry createLocal() { } public static ServiceRegistry createLocal(String localFile) { - EventBus eventBus = new EventBus(); + EventBus eventBus = new SimpleEventBus(); ServiceRegistryConfig serviceRegistryConfig = ServiceRegistryConfig.INSTANCE; MicroserviceConfigLoader loader = new MicroserviceConfigLoader(); loader.loadAndSort(); diff --git a/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/swagger/SwaggerLoader.java b/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/swagger/SwaggerLoader.java index 6a3339e204d..9740399ffd4 100644 --- a/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/swagger/SwaggerLoader.java +++ b/service-registry/src/main/java/org/apache/servicecomb/serviceregistry/swagger/SwaggerLoader.java @@ -16,11 +16,16 @@ */ package org.apache.servicecomb.serviceregistry.swagger; +import java.io.InputStream; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Optional; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.IOUtils; import org.apache.servicecomb.foundation.common.concurrent.ConcurrentHashMapEx; import org.apache.servicecomb.foundation.common.utils.JvmUtils; import org.apache.servicecomb.serviceregistry.ServiceRegistry; @@ -47,20 +52,83 @@ public SwaggerLoader(ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } + /** + *
+   * register swaggers in the location to current microservice
+   * Scenes for contract first mode:
+   *  1.consumer
+   *    manager manage some product, can only know product microservice names after deploy
+   *    and can only register swagger after product registered
+   *    in fact, consumers can load swagger from ServiceCenter
+   *    so for consumer, this logic is not necessary, just keep it for compatible
+   *  2.producer
+   *    deploy to different microservice name in different product
+   *    can register swaggers in BootListener.onBeforeProducerProvider
+   * 
+ * @param swaggersLocation eg. "test/schemas", will load all test/schemas/*.yaml + */ + public void registerSwaggersInLocation(String swaggersLocation) { + String microserviceName = serviceRegistry.getMicroservice().getServiceName(); + registerSwaggersInLocation(microserviceName, swaggersLocation); + } + + public void registerSwaggersInLocation(String microserviceName, String swaggersLocation) { + try (InputStream inputStream = JvmUtils.findClassLoader().getResourceAsStream(swaggersLocation)) { + if (inputStream == null) { + LOGGER.error("register swagger in not exist location: \"{}\".", swaggersLocation); + return; + } + + List files = IOUtils.readLines(inputStream, StandardCharsets.UTF_8); + + for (String file : files) { + if (!file.endsWith(".yaml")) { + continue; + } + + URL url = JvmUtils.findClassLoader().getResource(swaggersLocation + "/" + file); + String schemaId = FilenameUtils.getBaseName(url.getPath()); + Swagger swagger = SwaggerUtils.parseAndValidateSwagger(url); + registerSwagger(microserviceName, schemaId, swagger); + } + } catch (Throwable e) { + throw new IllegalStateException(String.format( + "failed to register swaggers, microserviceName=%s, location=%s.", microserviceName, swaggersLocation), + e); + } + } + + public void registerSwagger(String schemaId, Swagger swagger) { + registerSwagger(serviceRegistry.getMicroservice().getServiceName(), schemaId, swagger); + } + + public void registerSwagger(String microserviceName, String schemaId, String swaggerContent) { + try { + Swagger swagger = SwaggerUtils.parseAndValidateSwagger(swaggerContent); + registerSwagger(microserviceName, schemaId, swagger); + } catch (Throwable e) { + throw new IllegalStateException( + String.format("Parse the swagger for %s:%s failed", microserviceName, schemaId), + e); + } + } + public void registerSwagger(String microserviceName, String schemaId, Swagger swagger) { MicroserviceNameParser parser = new MicroserviceNameParser(serviceRegistry.getAppId(), microserviceName); registerSwagger(parser.getAppId(), parser.getShortName(), schemaId, swagger); } - public void registerSwagger(String appId, String shortName, String schemaId, Class cls) { + public Swagger registerSwagger(String appId, String shortName, String schemaId, Class cls) { Swagger swagger = SwaggerGenerator.generate(cls); registerSwagger(appId, shortName, schemaId, swagger); + return swagger; } public void registerSwagger(String appId, String shortName, String schemaId, Swagger swagger) { apps.computeIfAbsent(appId, k -> new ConcurrentHashMapEx<>()) .computeIfAbsent(shortName, k -> new ConcurrentHashMapEx<>()) .put(schemaId, swagger); + LOGGER.info("register swagger appId={}, name={}, schemaId={}.", appId, shortName, schemaId); } public void unregisterSwagger(String appId, String shortName, String schemaId) { @@ -78,7 +146,7 @@ public Swagger loadSwagger(Microservice microservice, String schemaId) { return loadFromRemote(microservice, schemaId); } - private Swagger loadLocalSwagger(String appId, String shortName, String schemaId) { + public Swagger loadLocalSwagger(String appId, String shortName, String schemaId) { Swagger swagger = loadFromMemory(appId, shortName, schemaId); if (swagger != null) { return swagger; @@ -87,7 +155,7 @@ private Swagger loadLocalSwagger(String appId, String shortName, String schemaId return loadFromResource(appId, shortName, schemaId); } - private Swagger loadFromMemory(String appId, String shortName, String schemaId) { + Swagger loadFromMemory(String appId, String shortName, String schemaId) { return Optional.ofNullable(apps.get(appId)) .map(microservices -> microservices.get(shortName)) .map(schemas -> schemas.get(schemaId)) @@ -111,19 +179,7 @@ private Swagger loadFromResource(String path) { return null; } - return parseAndValidateSwagger(url); - } - - private Swagger parseAndValidateSwagger(URL url) { - Swagger swagger = SwaggerUtils.parseSwagger(url); - SwaggerUtils.validateSwagger(swagger); - return swagger; - } - - private Swagger parseAndValidateSwagger(String swaggerContent) { - Swagger swagger = SwaggerUtils.parseSwagger(swaggerContent); - SwaggerUtils.validateSwagger(swagger); - return swagger; + return SwaggerUtils.parseAndValidateSwagger(url); } private Swagger loadFromRemote(Microservice microservice, String schemaId) { @@ -138,7 +194,7 @@ private Swagger loadFromRemote(Microservice microservice, String schemaId) { microservice.getServiceId(), schemaId); LOGGER.debug(schemaContent); - return parseAndValidateSwagger(schemaContent); + return SwaggerUtils.parseAndValidateSwagger(schemaContent); } throw new IllegalStateException( diff --git a/service-registry/src/test/java/org/apache/servicecomb/serviceregistry/swagger/TestSwaggerLoader.java b/service-registry/src/test/java/org/apache/servicecomb/serviceregistry/swagger/TestSwaggerLoader.java index ae4372c0b5a..68261e7b921 100644 --- a/service-registry/src/test/java/org/apache/servicecomb/serviceregistry/swagger/TestSwaggerLoader.java +++ b/service-registry/src/test/java/org/apache/servicecomb/serviceregistry/swagger/TestSwaggerLoader.java @@ -16,11 +16,25 @@ */ package org.apache.servicecomb.serviceregistry.swagger; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.core.Is.is; + +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.InputStream; import java.net.URL; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.ws.Holder; import org.apache.commons.io.IOUtils; +import org.apache.servicecomb.foundation.common.exceptions.ServiceCombException; import org.apache.servicecomb.foundation.common.utils.JvmUtils; import org.apache.servicecomb.serviceregistry.TestRegistryBase; import org.apache.servicecomb.serviceregistry.api.registry.Microservice; @@ -32,6 +46,7 @@ import org.junit.rules.ExpectedException; import io.swagger.models.Swagger; +import mockit.Deencapsulation; import mockit.Expectations; import mockit.Mock; import mockit.MockUp; @@ -123,14 +138,41 @@ public void loadFromResource_diffApp_dirWithApp() throws IOException { Assert.assertEquals(swagger, loadedSwagger); } - private void mockLocalResource(Swagger swagger, String path) throws IOException { + private void mockLocalResource(Swagger swagger, String path) { + mockLocalResource(SwaggerUtils.swaggerToString(swagger), path); + } + + private void mockLocalResource(String content, String path) { + Map resourceMap = new HashMap<>(); + resourceMap.put(path, content); + + mockLocalResource(resourceMap); + } + + private void mockLocalResource(Map resourceMap) { + Holder pathHolder = new Holder<>(); URL url = new MockUp() { + @Mock + String getPath() { + return pathHolder.value; + } + @Mock + String toExternalForm() { + return pathHolder.value; + } }.getMockInstance(); ClassLoader classLoader = new MockUp() { @Mock URL getResource(String name) { - return path.equals(name) ? url : null; + pathHolder.value = name; + return resourceMap.containsKey(name) ? url : null; + } + + @Mock + InputStream getResourceAsStream(String name) { + String content = resourceMap.get(name); + return content == null ? null : new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); } }.getMockInstance(); new Expectations(JvmUtils.class) { @@ -142,8 +184,44 @@ URL getResource(String name) { new MockUp() { @Mock String toString(URL url, Charset encoding) { - return SwaggerUtils.swaggerToString(swagger); + return resourceMap.get(url.getPath()); } }; } + + @Test + public void should_ignore_not_exist_location_when_register_swagger_in_location() { + Map apps = Deencapsulation.getField(serviceRegistry.getSwaggerLoader(), "apps"); + apps.clear(); + serviceRegistry.getSwaggerLoader().registerSwaggersInLocation("notExistPath"); + assertThat(apps).isEmpty(); + } + + @Test + public void should_ignore_non_yaml_file_when_register_swagger_in_location() { + serviceRegistry.getSwaggerLoader().registerSwaggersInLocation("swagger-del"); + assertThat(serviceRegistry.getSwaggerLoader().loadFromMemory(appId, serviceName, "other")).isNull(); + } + + @Test + public void should_throw_exception_when_register_invalid_swagger_in_location() { + expectedException.expect(IllegalStateException.class); + expectedException.expectMessage("failed to register swaggers, microserviceName=default, location=location."); + expectedException.expectCause(instanceOf(ServiceCombException.class)); + expectedException.expectCause(allOf(instanceOf(ServiceCombException.class), + hasProperty("message", is("Parse swagger from url failed, url=location/invalid.yaml")))); + + Map resourceMap = new HashMap<>(); + resourceMap.put("location", "invalid.yaml"); + resourceMap.put("location/invalid.yaml", "invalid yaml content"); + mockLocalResource(resourceMap); + + serviceRegistry.getSwaggerLoader().registerSwaggersInLocation("location"); + } + + @Test + public void should_correct_register_swagger_in_location() { + serviceRegistry.getSwaggerLoader().registerSwaggersInLocation("swagger-del"); + assertThat(serviceRegistry.getSwaggerLoader().loadFromMemory(appId, serviceName, "hello")).isNotNull(); + } } From 9472662e44725b4e8e8e2eea58315cd391aa1947 Mon Sep 17 00:00:00 2001 From: wujimin Date: Sun, 7 Jul 2019 01:51:55 +0800 Subject: [PATCH 2/2] [SCB-1348[WIP][WEAK] delete SchemaLoader --- .../loader/DynamicSchemaLoader.java | 81 ----------- .../definition/loader/SchemaListener.java | 25 ---- .../loader/SchemaListenerManager.java | 77 ---------- .../core/definition/loader/SchemaLoader.java | 133 ------------------ 4 files changed, 316 deletions(-) delete mode 100644 core/src/main/java/org/apache/servicecomb/core/definition/loader/DynamicSchemaLoader.java delete mode 100644 core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaListener.java delete mode 100644 core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaListenerManager.java delete mode 100644 core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaLoader.java diff --git a/core/src/main/java/org/apache/servicecomb/core/definition/loader/DynamicSchemaLoader.java b/core/src/main/java/org/apache/servicecomb/core/definition/loader/DynamicSchemaLoader.java deleted file mode 100644 index 2e782edac35..00000000000 --- a/core/src/main/java/org/apache/servicecomb/core/definition/loader/DynamicSchemaLoader.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.servicecomb.core.definition.loader; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.servicecomb.core.CseContext; -import org.apache.servicecomb.core.definition.SchemaMeta; -import org.apache.servicecomb.foundation.common.config.PaaSResourceUtils; -import org.apache.servicecomb.serviceregistry.RegistryUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; - -/* - * 场景: - * 1.consumer - * 网管调用产品 - * 网管事先不知道产品对应的微服务名 - * 产品注册到网管后,网管根据注册信息,进行契约注册 - * 2.producer - * 需要支持在不同的产品中部署为不同的微服务名 - * 微服务名是由环境变量等等方式注入的 - * 此时可以在BootListener中进行注册(必须在producer初始化之前注册契约) - * - * @Deprecated This class is deprecated because when making calls to a provider, schemas will be downloaded from service enter. - * And at provider, schemas will register to service center when starting up. - */ -@Deprecated -public class DynamicSchemaLoader { - private static final Logger LOGGER = LoggerFactory.getLogger(DynamicSchemaLoader.class); - - public static final DynamicSchemaLoader INSTANCE = new DynamicSchemaLoader(); - - private DynamicSchemaLoader() { - } - - /** - * 动态注册指定目录下的schema契约到当前服务 - * @param schemaLocation eg. "classpath*:schemas/*.yaml" - */ - public void registerSchemas(String schemaLocation) { - registerSchemas(RegistryUtils.getMicroservice().getServiceName(), schemaLocation); - } - - /** - * 动态注册指定目录下的schema契约到指定服务 - * @param microserviceName name of microservice - * @param schemaLocation eg. "classpath*:schemas/*.yaml" - */ - public void registerSchemas(String microserviceName, String schemaLocation) { - LOGGER.info("dynamic register schemas for {} in {}", microserviceName, schemaLocation); - - List schemaMetaList = new ArrayList<>(); - Resource[] resArr = PaaSResourceUtils.getResources(schemaLocation); - for (Resource resource : resArr) { - SchemaMeta schemaMeta = - CseContext.getInstance().getSchemaLoader().registerSchema(microserviceName, resource); - - schemaMetaList.add(schemaMeta); - } - - CseContext.getInstance().getSchemaListenerManager().notifySchemaListener(schemaMetaList); - } -} diff --git a/core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaListener.java b/core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaListener.java deleted file mode 100644 index 9166ee4d412..00000000000 --- a/core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaListener.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.servicecomb.core.definition.loader; - -import org.apache.servicecomb.core.definition.SchemaMeta; - -public interface SchemaListener { - // 不必考虑多线程并发 - void onSchemaLoaded(SchemaMeta... schemaMetas); -} diff --git a/core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaListenerManager.java b/core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaListenerManager.java deleted file mode 100644 index e58c0f4baef..00000000000 --- a/core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaListenerManager.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.servicecomb.core.definition.loader; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.servicecomb.core.SCBEngine; -import org.apache.servicecomb.core.definition.MicroserviceMeta; -import org.apache.servicecomb.core.definition.SchemaMeta; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -/** - * key为microserviceName - */ -@Component -public class SchemaListenerManager { - - @Autowired(required = false) - private List schemaListenerList = new ArrayList<>(); - - public void setSchemaListenerList(List schemaListenerList) { - this.schemaListenerList = schemaListenerList; - } - - public void notifySchemaListener(MicroserviceMeta... microserviceMetas) { - List schemaMetaList = new ArrayList<>(); - for (MicroserviceMeta microserviceMeta : microserviceMetas) { - schemaMetaList.addAll(microserviceMeta.getSchemaMetas()); - } - notifySchemaListener(schemaMetaList.toArray(new SchemaMeta[schemaMetaList.size()])); - } - - public void notifySchemaListener() { - //only one instance - MicroserviceMeta microserviceMeta = SCBEngine.getInstance().getProducerMicroserviceMeta(); - notifySchemaListener(microserviceMeta); - } - - public void notifySchemaListener(SchemaMeta... schemaMetas) { - for (SchemaListener listener : schemaListenerList) { - listener.onSchemaLoaded(schemaMetas); - } - } - - public void notifySchemaListener(List schemaMetaList) { - SchemaMeta[] schemaMetas = schemaMetaList.toArray(new SchemaMeta[schemaMetaList.size()]); - notifySchemaListener(schemaMetas); - } - - public SchemaMeta ensureFindSchemaMeta(String schemaId) { - MicroserviceMeta microserviceMeta = SCBEngine.getInstance().getProducerMicroserviceMeta(); - return microserviceMeta.ensureFindSchemaMeta(schemaId); - } - - public Collection getAllSchemaMeta() { - MicroserviceMeta microserviceMeta = SCBEngine.getInstance().getProducerMicroserviceMeta(); - return microserviceMeta.getSchemaMetas(); - } -} diff --git a/core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaLoader.java b/core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaLoader.java deleted file mode 100644 index 3fc4d62c576..00000000000 --- a/core/src/main/java/org/apache/servicecomb/core/definition/loader/SchemaLoader.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.servicecomb.core.definition.loader; - -import java.nio.charset.StandardCharsets; -import java.util.List; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; -import org.apache.servicecomb.core.Handler; -import org.apache.servicecomb.core.SCBEngine; -import org.apache.servicecomb.core.definition.MicroserviceMeta; -import org.apache.servicecomb.core.definition.SchemaMeta; -import org.apache.servicecomb.core.definition.SchemaUtils; -import org.apache.servicecomb.core.handler.ConsumerHandlerManager; -import org.apache.servicecomb.core.handler.ProducerHandlerManager; -import org.apache.servicecomb.serviceregistry.RegistryUtils; -import org.apache.servicecomb.serviceregistry.api.Const; -import org.apache.servicecomb.serviceregistry.api.registry.BasePath; -import org.apache.servicecomb.serviceregistry.api.registry.Microservice; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -import com.netflix.config.DynamicPropertyFactory; - -import io.swagger.models.Swagger; - -@Component -public class SchemaLoader { - private static final Logger LOGGER = LoggerFactory.getLogger(SchemaLoader.class); - - /* - * resource的路径格式,至少是以这个形式结尾:schemaId.yaml - */ - public SchemaMeta registerSchema(String microserviceName, Resource resource) { - try { - String schemaId = FilenameUtils.getBaseName(resource.getFilename()); - - String swaggerContent = IOUtils.toString(resource.getURL(), StandardCharsets.UTF_8); - SchemaMeta schemaMeta = registerSchema(microserviceName, schemaId, swaggerContent); - - return schemaMeta; - } catch (Throwable e) { - throw new Error(e); - } - } - - public SchemaMeta registerSchema(String microserviceName, String schemaId, String swaggerContent) { - Swagger swagger = SchemaUtils.parseSwagger(swaggerContent); - if (swagger == null) { - throw new Error(String.format("Parse the swagger for %s:%s failed", microserviceName, schemaId)); - } - - return registerSchema(schemaId, swagger); - } - - public SchemaMeta registerSchema(String schemaId, - Swagger swagger) { - MicroserviceMeta microserviceMeta = SCBEngine.getInstance().getProducerMicroserviceMeta(); - return registerSchema(microserviceMeta, schemaId, swagger); - } - - public SchemaMeta registerSchema(MicroserviceMeta microserviceMeta, String schemaId, - Swagger swagger) { - String microserviceName = microserviceMeta.getName(); - LOGGER.info("register schema {}/{}/{}", microserviceMeta.getAppId(), microserviceName, schemaId); - - SchemaMeta schemaMeta = new SchemaMeta(swagger, microserviceMeta, schemaId); - - List producerHandlerChain = ProducerHandlerManager.INSTANCE.getOrCreate(microserviceName); - schemaMeta.setProviderHandlerChain(producerHandlerChain); - - List consumerHandlerChain = ConsumerHandlerManager.INSTANCE.getOrCreate(microserviceName); - schemaMeta.setConsumerHandlerChain(consumerHandlerChain); - - microserviceMeta.regSchemaMeta(schemaMeta); - - addSchemaPath2Microservice(microserviceName, swagger.getBasePath()); - - return schemaMeta; - } - - void addSchemaPath2Microservice(String microserviceName, String basePath) { - if (DynamicPropertyFactory.getInstance().getBooleanProperty(Const.REGISTER_SERVICE_PATH, false).get()) { - putSelfBasePathIfAbsent(microserviceName, basePath); - } - } - - void putSelfBasePathIfAbsent(String microserviceName, String basePath) { - if (basePath == null || basePath.length() == 0) { - return; - } - - Microservice microservice = RegistryUtils.getMicroservice(); - if (!microservice.getServiceName().equals(microserviceName)) { - return; - } - - String urlPrefix = System.getProperty(Const.URL_PREFIX); - if (!StringUtils.isEmpty(urlPrefix) && !basePath.startsWith(urlPrefix)) { - basePath = urlPrefix + basePath; - } - - List paths = microservice.getPaths(); - for (BasePath path : paths) { - if (path.getPath().equals(basePath)) { - return; - } - } - - BasePath basePathObj = new BasePath(); - basePathObj.setPath(basePath); - paths.add(basePathObj); - } -}