diff options
Diffstat (limited to 'apiroute/apiroute-service')
129 files changed, 10993 insertions, 11669 deletions
diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/ApiRouteApp.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/ApiRouteApp.java index 496d275..fb8147d 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/ApiRouteApp.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/ApiRouteApp.java @@ -1,26 +1,17 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute; -import io.dropwizard.Application; -import io.dropwizard.assets.AssetsBundle; -import io.dropwizard.server.SimpleServerFactory; -import io.dropwizard.setup.Bootstrap; -import io.dropwizard.setup.Environment; -import io.swagger.jaxrs.config.BeanConfig; -import io.swagger.jaxrs.listing.ApiListingResource; import org.onap.msb.apiroute.health.ApiRouteHealthCheck; import org.onap.msb.apiroute.resources.ApiRouteResource; @@ -34,17 +25,25 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude; +import io.dropwizard.Application; +import io.dropwizard.assets.AssetsBundle; +import io.dropwizard.server.SimpleServerFactory; +import io.dropwizard.setup.Bootstrap; +import io.dropwizard.setup.Environment; +import io.swagger.jaxrs.config.BeanConfig; +import io.swagger.jaxrs.listing.ApiListingResource; + public class ApiRouteApp extends Application<ApiRouteAppConfig> { private static final Logger LOGGER = LoggerFactory.getLogger(ApiRouteApp.class); public static void main(String[] args) throws Exception { new ApiRouteApp().run(args); - + InitRouteServiceWrapper.getInstance().initFilterConfig(); - + InitRouteServiceWrapper.getInstance().initDataSynchro(); - + InitRouteServiceWrapper.getInstance().initHealthCheck(); } @@ -56,50 +55,49 @@ public class ApiRouteApp extends Application<ApiRouteAppConfig> { @Override public void initialize(Bootstrap<ApiRouteAppConfig> bootstrap) { - super.initialize(bootstrap); - + super.initialize(bootstrap); + } @Override public void run(ApiRouteAppConfig configuration, Environment environment) throws Exception { - - - ConfigUtil.getInstance().initRootPath(); - - - String iuiRootPath=ConfigUtil.getInstance().getIUI_ROOT_PATH(); - - // new AssetsBundle("/iui-metrics", "/"+iuiRootPath+"/microservices/metrics","index.html", "iui-metrics").run(environment); - - new AssetsBundle("/iui-route", "/"+iuiRootPath+"/microservices", "index.html","iui-microservices").run(environment); - - new AssetsBundle("/api-doc", "/"+iuiRootPath+"/microservices/api-doc","index.html", "api-doc").run(environment); - - new AssetsBundle("/ext", "/"+iuiRootPath+"/microservices/ext","index.html", "ext").run(environment); - - - - - final ApiRouteHealthCheck healthCheck =new ApiRouteHealthCheck(); + + + ConfigUtil.getInstance().initRootPath(); + + + String iuiRootPath = ConfigUtil.getInstance().getIUI_ROOT_PATH(); + + // new AssetsBundle("/iui-metrics", "/"+iuiRootPath+"/microservices/metrics","index.html", + // "iui-metrics").run(environment); + + new AssetsBundle("/iui-route", "/" + iuiRootPath + "/microservices", "index.html", "iui-microservices") + .run(environment); + + new AssetsBundle("/api-doc", "/" + iuiRootPath + "/microservices/api-doc", "index.html", "api-doc") + .run(environment); + + new AssetsBundle("/ext", "/" + iuiRootPath + "/microservices/ext", "index.html", "ext").run(environment); + + + + final ApiRouteHealthCheck healthCheck = new ApiRouteHealthCheck(); environment.healthChecks().register("consulCheck", healthCheck); - + environment.jersey().register(new ApiRouteResource()); - environment.jersey().register(new IuiRouteResource()); + environment.jersey().register(new IuiRouteResource()); environment.jersey().register(new CustomRouteResource()); environment.jersey().register(new MicroServiceResource()); - + // initSwaggerConfig(environment, configuration); - + ConfigUtil.getInstance().initConsulIp(); ConfigUtil.getInstance().initDiscoverInfo(configuration); // InitRouteServiceWrapper.getInstance().initMetricsConfig(configuration); - - + + } - - - private void initSwaggerConfig(Environment environment, ApiRouteAppConfig configuration) { @@ -111,7 +109,7 @@ public class ApiRouteApp extends Application<ApiRouteAppConfig> { config.setTitle("ApiRoute RESTful API"); config.setVersion("1.0.0"); config.setResourcePackage("org.onap.msb.apiroute.resources"); - SimpleServerFactory simpleServerFactory =(SimpleServerFactory) configuration.getServerFactory(); + SimpleServerFactory simpleServerFactory = (SimpleServerFactory) configuration.getServerFactory(); String basePath = simpleServerFactory.getApplicationContextPath(); String rootPath = simpleServerFactory.getJerseyRootPath(); @@ -123,8 +121,7 @@ public class ApiRouteApp extends Application<ApiRouteAppConfig> { config.setBasePath(basePath); config.setScan(true); } - - + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/ApiRouteAppConfig.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/ApiRouteAppConfig.java index 4cccab8..5af5d8c 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/ApiRouteAppConfig.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/ApiRouteAppConfig.java @@ -1,38 +1,32 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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. ******************************************************************************/ /** -* Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE) -* -* 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. -*/ + * Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE) + * + * 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 org.onap.msb.apiroute; -import io.dropwizard.Configuration; - import javax.validation.Valid; import org.hibernate.validator.constraints.NotEmpty; @@ -40,19 +34,21 @@ import org.onap.msb.apiroute.api.DiscoverInfo; import com.fasterxml.jackson.annotation.JsonProperty; -public class ApiRouteAppConfig extends Configuration { +import io.dropwizard.Configuration; + +public class ApiRouteAppConfig extends Configuration { @NotEmpty - private String defaultWorkspace = "apiroute-works"; + private String defaultWorkspace = "apiroute-works"; @NotEmpty private String defaultName = "Stranger"; - - + + @Valid private DiscoverInfo discoverInfo; - - - @JsonProperty + + + @JsonProperty public String getDefaultWorkspace() { return defaultWorkspace; } @@ -72,7 +68,7 @@ public class ApiRouteAppConfig extends Configuration { this.defaultName = name; } - + @JsonProperty public DiscoverInfo getDiscoverInfo() { @@ -83,8 +79,7 @@ public class ApiRouteAppConfig extends Configuration { public void setDiscoverInfo(DiscoverInfo discoverInfo) { this.discoverInfo = discoverInfo; } - - - + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/SyncDataManager.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/SyncDataManager.java index aa211aa..0acb9ee 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/SyncDataManager.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/SyncDataManager.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute; @@ -34,117 +32,108 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SyncDataManager { - private static Consul consul; - private static WatchCatalogServicesTask serviceListWatchTask; - private final static Map<String, WatchServiceHealthTask> serviceWatchTaskMap = new ConcurrentHashMap<String, WatchServiceHealthTask>(); - - private static final Logger LOGGER = LoggerFactory - .getLogger(SyncDataManager.class); + private static Consul consul; + private static WatchCatalogServicesTask serviceListWatchTask; + private final static Map<String, WatchServiceHealthTask> serviceWatchTaskMap = + new ConcurrentHashMap<String, WatchServiceHealthTask>(); - private SyncDataManager() { - } + private static final Logger LOGGER = LoggerFactory.getLogger(SyncDataManager.class); - public static void initSyncTask(final String ip, final int port) { - consul = Consul.builder().withHostAndPort(ip, port).build(); - startWatchServiceList(); - startQueueConsumer(); - } - - public static void startWatchServiceList() { - - LOGGER.info("===========start to WatchServiceList============"); - - // create service list watch task - serviceListWatchTask = new WatchCatalogServicesTask( - consul.catalogClient(), RouteUtil.WATCH_SECOND); - - // first,write data to serviceListQueue buffer. - // second,async thread will read data from serviceListQueue buffer. - serviceListWatchTask.addHandler(new WriteBufferHandler<HttpEntity>( - ServiceData.DataType.service_list)); - - // start watch - serviceListWatchTask.startWatch(); - } - - public static void startQueueConsumer() { - LOGGER.info("===========start to QueueConsumer Thread============"); - - // start ServiceListConsumer - new Thread(new ServiceListConsumer(), "ServiceListConsumerThread") - .start(); - - // start Service Consumer - int serviceQueneNum = RouteUtil.SERVICE_DATA_QUEUE_NUM; - for (int i = 0; i < serviceQueneNum; i++) { - new Thread(new ServiceConsumer(i), "ServiceConsumerThread" + i) - .start(); - } - - } - - public static void startWatchService(final String serviceName) { - - LOGGER.info("===========start to Watch Service[" + serviceName - + "]============"); - // create service watch task - WatchServiceHealthTask serviceWatchTask = new WatchServiceHealthTask( - consul.healthClient(), serviceName, RouteUtil.WATCH_SECOND); - - // 1.service Data Empty filter - serviceWatchTask - .addFilter(new CheckServiceDataEmptyAndAutoStopWatchFilter( - serviceName)); - - // 2.service change filter - serviceWatchTask.addFilter(new ServiceModifyIndexFilter()); - - // 3.apigateway tag filter:check tag and auto stop watch - serviceWatchTask.addFilter(new CheckTagAndAutoStopWatchFilter( - serviceName)); - - // start watch - serviceWatchTask.startWatch(); - - // save - serviceWatchTaskMap.put(serviceName, serviceWatchTask); - } - - public static void stopWatchServiceList() { - if (serviceListWatchTask != null) { - serviceListWatchTask.removeAllFilter(); - serviceListWatchTask.removeAllHandler(); - serviceListWatchTask.stopWatch(); - } - } - - public static void stopWatchService(String serviceName) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("stop " + serviceName + " service watch!"); - } - - WatchServiceHealthTask watchTask = serviceWatchTaskMap.get(serviceName); - if (watchTask != null) { - watchTask.removeAllFilter(); - watchTask.removeAllHandler(); - watchTask.stopWatch(); - } - serviceWatchTaskMap.remove(serviceName); - } - - public static boolean resetIndex(String serviceName) { - - WatchServiceHealthTask watchTask = serviceWatchTaskMap.get(serviceName); + private SyncDataManager() {} - if (watchTask != null) { - return watchTask.resetIndex(); - } + public static void initSyncTask(final String ip, final int port) { + consul = Consul.builder().withHostAndPort(ip, port).build(); + startWatchServiceList(); + startQueueConsumer(); + } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("reset modify index.did not find:" + serviceName); - } + public static void startWatchServiceList() { - return false; - } + LOGGER.info("===========start to WatchServiceList============"); + + // create service list watch task + serviceListWatchTask = new WatchCatalogServicesTask(consul.catalogClient(), RouteUtil.WATCH_SECOND); + + // first,write data to serviceListQueue buffer. + // second,async thread will read data from serviceListQueue buffer. + serviceListWatchTask.addHandler(new WriteBufferHandler<HttpEntity>(ServiceData.DataType.service_list)); + + // start watch + serviceListWatchTask.startWatch(); + } + + public static void startQueueConsumer() { + LOGGER.info("===========start to QueueConsumer Thread============"); + + // start ServiceListConsumer + new Thread(new ServiceListConsumer(), "ServiceListConsumerThread").start(); + + // start Service Consumer + int serviceQueneNum = RouteUtil.SERVICE_DATA_QUEUE_NUM; + for (int i = 0; i < serviceQueneNum; i++) { + new Thread(new ServiceConsumer(i), "ServiceConsumerThread" + i).start(); + } + + } + + public static void startWatchService(final String serviceName) { + + LOGGER.info("===========start to Watch Service[" + serviceName + "]============"); + // create service watch task + WatchServiceHealthTask serviceWatchTask = + new WatchServiceHealthTask(consul.healthClient(), serviceName, RouteUtil.WATCH_SECOND); + + // 1.service Data Empty filter + serviceWatchTask.addFilter(new CheckServiceDataEmptyAndAutoStopWatchFilter(serviceName)); + + // 2.service change filter + serviceWatchTask.addFilter(new ServiceModifyIndexFilter()); + + // 3.apigateway tag filter:check tag and auto stop watch + serviceWatchTask.addFilter(new CheckTagAndAutoStopWatchFilter(serviceName)); + + // start watch + serviceWatchTask.startWatch(); + + // save + serviceWatchTaskMap.put(serviceName, serviceWatchTask); + } + + public static void stopWatchServiceList() { + if (serviceListWatchTask != null) { + serviceListWatchTask.removeAllFilter(); + serviceListWatchTask.removeAllHandler(); + serviceListWatchTask.stopWatch(); + } + } + + public static void stopWatchService(String serviceName) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("stop " + serviceName + " service watch!"); + } + + WatchServiceHealthTask watchTask = serviceWatchTaskMap.get(serviceName); + if (watchTask != null) { + watchTask.removeAllFilter(); + watchTask.removeAllHandler(); + watchTask.stopWatch(); + } + serviceWatchTaskMap.remove(serviceName); + } + + public static boolean resetIndex(String serviceName) { + + WatchServiceHealthTask watchTask = serviceWatchTaskMap.get(serviceName); + + if (watchTask != null) { + return watchTask.resetIndex(); + } + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("reset modify index.did not find:" + serviceName); + } + + return false; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/ApiRouteInfo.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/ApiRouteInfo.java index 5751289..3d370c5 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/ApiRouteInfo.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/ApiRouteInfo.java @@ -1,107 +1,107 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; -import io.swagger.annotations.ApiModelProperty; - -import java.io.Serializable; import java.util.Arrays; import java.util.Objects; +import io.swagger.annotations.ApiModelProperty; + public class ApiRouteInfo extends RouteInfo { - private static final long serialVersionUID = 1L; - - @ApiModelProperty(example = "v1", required = true) - private String version; - - - private String apiJson=""; //swagger json Path - - @ApiModelProperty(value = "[apiJson Type] 0:local file 1: remote file", allowableValues = "0,1", example = "1") - private String apiJsonType="1"; - private String metricsUrl=""; - - - - public String getVersion() { - return version; - } - public void setVersion(String version) { - this.version = version; - } - - public String getApiJson() { - return apiJson; - } - public void setApiJson(String apiJson) { - this.apiJson = apiJson; - } - - - - - public String getApiJsonType() { - return apiJsonType; - } - public void setApiJsonType(String apiJsonType) { - this.apiJsonType = apiJsonType; - } - public String getMetricsUrl() { - return metricsUrl; - } - public void setMetricsUrl(String metricsUrl) { - this.metricsUrl = metricsUrl; - } - - - - - @Override - public Object clone() throws CloneNotSupportedException - { - return super.clone(); + private static final long serialVersionUID = 1L; + + @ApiModelProperty(example = "v1", required = true) + private String version; + + + private String apiJson = ""; // swagger json Path + + @ApiModelProperty(value = "[apiJson Type] 0:local file 1: remote file", allowableValues = "0,1", example = "1") + private String apiJsonType = "1"; + private String metricsUrl = ""; + + + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getApiJson() { + return apiJson; + } + + public void setApiJson(String apiJson) { + this.apiJson = apiJson; + } + + + + public String getApiJsonType() { + return apiJsonType; + } + + public void setApiJsonType(String apiJsonType) { + this.apiJsonType = apiJsonType; + } + + public String getMetricsUrl() { + return metricsUrl; + } + + public void setMetricsUrl(String metricsUrl) { + this.metricsUrl = metricsUrl; + } + + + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + ApiRouteInfo that = (ApiRouteInfo) o; + return Objects.equals(isEnable_ssl(), that.isEnable_ssl()) + && Objects.equals(getServiceName(), that.getServiceName()) + && Objects.equals(version, that.version) && Objects.equals(getUrl(), that.getUrl()) + && Objects.equals(apiJson, that.apiJson) && Objects.equals(apiJsonType, that.apiJsonType) + && Objects.equals(metricsUrl, that.metricsUrl) + && Objects.equals(getControl(), that.getControl()) + && Objects.equals(getStatus(), that.getStatus()) + && Objects.equals(getVisualRange(), that.getVisualRange()) + && Objects.equals(getUseOwnUpstream(), that.getUseOwnUpstream()) + && Arrays.equals(getServers(), that.getServers()) && Objects.equals(getHost(), that.getHost()) + && Objects.equals(getNamespace(), that.getNamespace()) + && Objects.equals(getPublish_port(), that.getPublish_port()) + && Objects.equals(getConsulServiceName(), that.getConsulServiceName()) + && Objects.equals(getPublishProtocol(), that.getPublishProtocol()); + } + + @Override + public int hashCode() { + return Objects.hash(getServiceName(), version, getUrl(), apiJson, apiJsonType, metricsUrl, getControl(), + getStatus(), getVisualRange(), getServers(), getHost(), getNamespace(), getPublish_port(), + isEnable_ssl(), getConsulServiceName(), getPublishProtocol()); } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ApiRouteInfo that = (ApiRouteInfo) o; - return Objects.equals(isEnable_ssl(), that.isEnable_ssl()) && - Objects.equals(getServiceName(), that.getServiceName()) && - Objects.equals(version, that.version) && - Objects.equals(getUrl(), that.getUrl()) && - Objects.equals(apiJson, that.apiJson) && - Objects.equals(apiJsonType, that.apiJsonType) && - Objects.equals(metricsUrl, that.metricsUrl) && - Objects.equals(getControl(), that.getControl()) && - Objects.equals(getStatus(), that.getStatus()) && - Objects.equals(getVisualRange(), that.getVisualRange()) && - Objects.equals(getUseOwnUpstream(), that.getUseOwnUpstream()) && - Arrays.equals(getServers(), that.getServers()) && - Objects.equals(getHost(), that.getHost()) && - Objects.equals(getNamespace(), that.getNamespace()) && - Objects.equals(getPublish_port(), that.getPublish_port()) && - Objects.equals(getConsulServiceName(), that.getConsulServiceName()) && - Objects.equals(getPublishProtocol(), that.getPublishProtocol()); - } - - @Override - public int hashCode() { - return Objects.hash(getServiceName(), version, getUrl(), apiJson, apiJsonType, metricsUrl, getControl(), getStatus(), getVisualRange(), getServers(), getHost(), getNamespace(), getPublish_port(), isEnable_ssl(), getConsulServiceName(), getPublishProtocol()); - } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/CustomDateSerializer.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/CustomDateSerializer.java index a5a9337..95e9f72 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/CustomDateSerializer.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/CustomDateSerializer.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; @@ -24,16 +22,14 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; -public class CustomDateSerializer extends JsonSerializer<Date> { - - @Override - public void serialize(Date value, - JsonGenerator jsonGenerator, - SerializerProvider provider) - throws IOException, JsonProcessingException { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - jsonGenerator.writeString(sdf.format(value)); - } - - -} +public class CustomDateSerializer extends JsonSerializer<Date> { + + @Override + public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider) + throws IOException, JsonProcessingException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + jsonGenerator.writeString(sdf.format(value)); + } + + +} diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/CustomRouteInfo.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/CustomRouteInfo.java index f92a1ca..83b65a7 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/CustomRouteInfo.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/CustomRouteInfo.java @@ -1,24 +1,22 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; -public class CustomRouteInfo extends RouteInfo{ +public class CustomRouteInfo extends RouteInfo { + + private static final long serialVersionUID = 1L; + - private static final long serialVersionUID = 1L; - - } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/DiscoverInfo.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/DiscoverInfo.java index 5257c0b..50cbdec 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/DiscoverInfo.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/DiscoverInfo.java @@ -1,55 +1,57 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; import java.io.Serializable; -public class DiscoverInfo implements Serializable{ +public class DiscoverInfo implements Serializable { private static final long serialVersionUID = 1L; - private String ip; + private String ip; private int port; private boolean enabled; - + public String getIp() { return ip; } + public void setIp(String ip) { this.ip = ip; } + public int getPort() { return port; } + public void setPort(int port) { this.port = port; } + public boolean isEnabled() { return enabled; } + public void setEnabled(boolean enabled) { this.enabled = enabled; } - + @Override public String toString() { - // TODO Auto-generated method stub - return this.ip+":"+this.port; + // TODO Auto-generated method stub + return this.ip + ":" + this.port; } - - - + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/IuiRouteInfo.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/IuiRouteInfo.java index 4fc693c..cd3998a 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/IuiRouteInfo.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/IuiRouteInfo.java @@ -1,25 +1,23 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; -public class IuiRouteInfo extends RouteInfo{ +public class IuiRouteInfo extends RouteInfo { + + private static final long serialVersionUID = 1L; + - private static final long serialVersionUID = 1L; - - } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/MicroServiceFullInfo.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/MicroServiceFullInfo.java index d4d6686..a5c5bf0 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/MicroServiceFullInfo.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/MicroServiceFullInfo.java @@ -1,97 +1,102 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; -import io.swagger.annotations.ApiModelProperty; - import java.io.Serializable; import java.util.Objects; import java.util.Set; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.swagger.annotations.ApiModelProperty; + @JsonIgnoreProperties(ignoreUnknown = true) -public class MicroServiceFullInfo implements Serializable { +public class MicroServiceFullInfo implements Serializable { private static final long serialVersionUID = 1L; - + @ApiModelProperty(required = true) private String serviceName; - + @ApiModelProperty(example = "v1") - private String version=""; - - @ApiModelProperty(value = "Target Service URL,start with /",example = "/api/serviceName/v1", required = true) - private String url=""; - - @ApiModelProperty(value = "Service Protocol", allowableValues = "REST,UI, MQ, FTP,SNMP,TCP,UDP", example = "REST",required = true) + private String version = ""; + + @ApiModelProperty(value = "Target Service URL,start with /", example = "/api/serviceName/v1", required = true) + private String url = ""; + + @ApiModelProperty(value = "Service Protocol", allowableValues = "REST,UI, MQ, FTP,SNMP,TCP,UDP", example = "REST", + required = true) private String protocol = ""; - + @ApiModelProperty(value = "[visual Range]interSystem:0,inSystem:1", allowableValues = "0,1", example = "1") private String visualRange = "1"; - + @ApiModelProperty(value = "lb policy", allowableValues = "round-robin,hash,least_conn", example = "hash") - private String lb_policy=""; - - private String namespace=""; - - private String host=""; - - private String path=""; - - private String publish_port=""; - + private String lb_policy = ""; + + private String namespace = ""; + + private String host = ""; + + private String path = ""; + + private String publish_port = ""; + @ApiModelProperty(value = "enable ssl", allowableValues = "true,false", example = "false") - private boolean enable_ssl=false; //true:https:开启SSL加密, false:http - - private String custom; //PORTAL协议标志 - + private boolean enable_ssl = false; // true:https:开启SSL加密, false:http + + private String custom; // PORTAL协议标志 + private Set<Node> nodes; - + @ApiModelProperty(value = "Service Status", allowableValues = "0,1", example = "1") - private String status = "1"; //0:disable 1:enable - + private String status = "1"; // 0:disable 1:enable + + - - public String getServiceName() { return serviceName; } + public void setServiceName(String serviceName) { this.serviceName = serviceName; } + public String getVersion() { return version; } + public void setVersion(String version) { this.version = version; } + public String getUrl() { return url; } + public void setUrl(String url) { this.url = url; } + public String getProtocol() { return protocol; } + public void setProtocol(String protocol) { this.protocol = protocol; } - + public String getVisualRange() { return visualRange; } @@ -99,7 +104,7 @@ public class MicroServiceFullInfo implements Serializable { public void setVisualRange(String visualRange) { this.visualRange = visualRange; } - + public String getLb_policy() { return lb_policy; @@ -110,28 +115,31 @@ public class MicroServiceFullInfo implements Serializable { } public String getNamespace() { - return namespace; + return namespace; } public void setNamespace(String namespace) { - this.namespace = namespace; + this.namespace = namespace; } - + public String getHost() { - return host; + return host; } + public void setHost(String host) { - this.host = host; + this.host = host; } + public String getPath() { - return path; + return path; } + public void setPath(String path) { - this.path = path; + this.path = path; } - - + + public Set<Node> getNodes() { return nodes; @@ -140,56 +148,60 @@ public class MicroServiceFullInfo implements Serializable { public void setNodes(Set<Node> nodes) { this.nodes = nodes; } - + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + public String getPublish_port() { - return publish_port; + return publish_port; } + public void setPublish_port(String publish_port) { - this.publish_port = publish_port; + this.publish_port = publish_port; } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; MicroServiceFullInfo that = (MicroServiceFullInfo) o; - return Objects.equals(serviceName, that.serviceName) && - Objects.equals(version, that.version) && - Objects.equals(url, that.url) && - Objects.equals(protocol, that.protocol) && - Objects.equals(visualRange, that.visualRange) && - Objects.equals(lb_policy, that.lb_policy) && - Objects.equals(namespace, that.namespace) && - Objects.equals(host, that.host) && - Objects.equals(path, that.path) && - Objects.equals(publish_port, that.publish_port) && - Objects.equals(enable_ssl, that.enable_ssl) && - Objects.equals(nodes, that.nodes) && - Objects.equals(status, that.status); + return Objects.equals(serviceName, that.serviceName) && Objects.equals(version, that.version) + && Objects.equals(url, that.url) && Objects.equals(protocol, that.protocol) + && Objects.equals(visualRange, that.visualRange) && Objects.equals(lb_policy, that.lb_policy) + && Objects.equals(namespace, that.namespace) && Objects.equals(host, that.host) + && Objects.equals(path, that.path) && Objects.equals(publish_port, that.publish_port) + && Objects.equals(enable_ssl, that.enable_ssl) && Objects.equals(nodes, that.nodes) + && Objects.equals(status, that.status); } @Override public int hashCode() { - return Objects.hash(serviceName, version, url, protocol, visualRange, lb_policy, namespace, host, path, publish_port, enable_ssl, nodes, status); + return Objects.hash(serviceName, version, url, protocol, visualRange, lb_policy, namespace, host, path, + publish_port, enable_ssl, nodes, status); } + public boolean isEnable_ssl() { - return enable_ssl; + return enable_ssl; } + public void setEnable_ssl(boolean enable_ssl) { - this.enable_ssl = enable_ssl; + this.enable_ssl = enable_ssl; } + public String getCustom() { - return custom; + return custom; } + public void setCustom(String custom) { - this.custom = custom; + this.custom = custom; } - - + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/Node.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/Node.java index 41db8e7..4257c53 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/Node.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/Node.java @@ -1,45 +1,43 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; -import io.swagger.annotations.ApiModelProperty; - import java.io.Serializable; import java.util.Objects; +import io.swagger.annotations.ApiModelProperty; + public class Node implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(required = true) private String ip; - + @ApiModelProperty(required = true) private String port; - - private String status="passing"; //实例健康检查状态 - - private int ttl=-1; - + + private String status = "passing"; // 实例健康检查状态 + + private int ttl = -1; + public String getStatus() { - return status; - } + return status; + } - public void setStatus(String status) { - this.status = status; - } + public void setStatus(String status) { + this.status = status; + } public String getIp() { return ip; @@ -65,30 +63,30 @@ public class Node implements Serializable { this.ttl = ttl; } - public Node(){ - + public Node() { + } - - public Node(String ip,String port,int ttl){ + + public Node(String ip, String port, int ttl) { this.ip = ip; this.port = port; this.ttl = ttl; } - - public Node(String ip,String port){ - this.ip = ip; - this.port = port; - } + + public Node(String ip, String port) { + this.ip = ip; + this.port = port; + } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Node node = (Node) o; - return Objects.equals(ttl, node.ttl) && - Objects.equals(ip, node.ip) && - Objects.equals(port, node.port) && - Objects.equals(status, node.status); + return Objects.equals(ttl, node.ttl) && Objects.equals(ip, node.ip) && Objects.equals(port, node.port) + && Objects.equals(status, node.status); } @Override diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/PublishFullAddress.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/PublishFullAddress.java index 49ef54c..59b4c39 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/PublishFullAddress.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/PublishFullAddress.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; @@ -21,43 +19,43 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class PublishFullAddress implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private String ip; + private String ip; - private String port; - + private String port; - private String publish_protocol; - public String getPublish_protocol() { - return publish_protocol; - } + private String publish_protocol; - public void setPublish_protocol(String publish_protocol) { - this.publish_protocol = publish_protocol; - } + public String getPublish_protocol() { + return publish_protocol; + } + public void setPublish_protocol(String publish_protocol) { + this.publish_protocol = publish_protocol; + } - public String getIp() { - return ip; - } - public void setIp(String ip) { - this.ip = ip; - } + public String getIp() { + return ip; + } - public String getPort() { - return port; - } + public void setIp(String ip) { + this.ip = ip; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public PublishFullAddress() { + + } - public void setPort(String port) { - this.port = port; - } - - public PublishFullAddress(){ - - } - } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/RouteInfo.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/RouteInfo.java index 4bf6087..3d1eff9 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/RouteInfo.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/RouteInfo.java @@ -1,194 +1,197 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; -import io.swagger.annotations.ApiModelProperty; - import java.io.Serializable; import java.util.Arrays; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.swagger.annotations.ApiModelProperty; + @JsonIgnoreProperties(ignoreUnknown = true) -public class RouteInfo implements Serializable,Cloneable { - private static final long serialVersionUID = 1L; - @ApiModelProperty(required = true) - private String serviceName; - - @ApiModelProperty(value = "Target Service URL,start with /",example = "/test", required = true) - private String url; - - @ApiModelProperty(value = "[control Range] 0:default 1:readonly 2:hidden ", allowableValues = "0,1,2", example = "0") - private String control="0"; - - @ApiModelProperty(value = "[status] 1:abled 0:disabled ", allowableValues = "0,1", example = "1") - private String status="1"; - - @ApiModelProperty(value = "[visual Range]interSystem:0,inSystem:1", allowableValues = "0,1", example = "1") - private String visualRange = "1"; - - @ApiModelProperty(value = "[LB Policy]non_ip_hash:0,ip_hash:1", allowableValues = "0,1", example = "0") - private String useOwnUpstream="0"; //lb policy - - @ApiModelProperty(required = true) - private RouteServer servers[]; - - private String host=""; - - private String namespace=""; - - private String publish_port=""; - - private boolean enable_ssl=false; //true:https:开启SSL加密, false:http - - private String consulServiceName=""; - - private String publishProtocol="http"; - - - - public String getPublish_port() { - return publish_port; - } - public void setPublish_port(String publish_port) { - this.publish_port = publish_port; - } - - - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - -public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public RouteServer[] getServers() { - return servers.clone(); - } - - public void setServers(RouteServer[] servers) { - this.servers = servers.clone(); - } - - public String getControl() { - return control; - } - - public void setControl(String control) { - this.control = control; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getVisualRange() { - return visualRange; - } - - public void setVisualRange(String visualRange) { - this.visualRange = visualRange; - } - - public String getUseOwnUpstream() { - return useOwnUpstream; - } - - public void setUseOwnUpstream(String useOwnUpstream) { - this.useOwnUpstream = useOwnUpstream; - } - - public String getNamespace() { - return namespace; - } - - public void setNamespace(String namespace) { - this.namespace = namespace; - } - public String getConsulServiceName() { - return consulServiceName; - } - public void setConsulServiceName(String consulServiceName) { - this.consulServiceName = consulServiceName; - } - - @Override - public Object clone() throws CloneNotSupportedException - { - return super.clone(); - } - public String getPublishProtocol() { - return publishProtocol; - } - public void setPublishProtocol(String publishProtocol) { - this.publishProtocol = publishProtocol; - } - public boolean isEnable_ssl() { - return enable_ssl; - } - public void setEnable_ssl(boolean enable_ssl) { - this.enable_ssl = enable_ssl; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - RouteInfo that = (RouteInfo) o; - return Objects.equals(enable_ssl, that.enable_ssl) && - Objects.equals(serviceName, that.serviceName) && - Objects.equals(url, that.url) && - Objects.equals(control, that.control) && - Objects.equals(status, that.status) && - Objects.equals(visualRange, that.visualRange) && - Objects.equals(useOwnUpstream, that.useOwnUpstream) && - Arrays.equals(servers, that.servers) && - Objects.equals(host, that.host) && - Objects.equals(namespace, that.namespace) && - Objects.equals(publish_port, that.publish_port) && - Objects.equals(consulServiceName, that.consulServiceName) && - Objects.equals(publishProtocol, that.publishProtocol); - } - - @Override - public int hashCode() { - return Objects.hash(serviceName, url, control, status, visualRange, useOwnUpstream, servers, host, namespace, publish_port, enable_ssl, consulServiceName, publishProtocol); - } +public class RouteInfo implements Serializable, Cloneable { + private static final long serialVersionUID = 1L; + @ApiModelProperty(required = true) + private String serviceName; + + @ApiModelProperty(value = "Target Service URL,start with /", example = "/test", required = true) + private String url; + + @ApiModelProperty(value = "[control Range] 0:default 1:readonly 2:hidden ", allowableValues = "0,1,2", + example = "0") + private String control = "0"; + + @ApiModelProperty(value = "[status] 1:abled 0:disabled ", allowableValues = "0,1", example = "1") + private String status = "1"; + + @ApiModelProperty(value = "[visual Range]interSystem:0,inSystem:1", allowableValues = "0,1", example = "1") + private String visualRange = "1"; + + @ApiModelProperty(value = "[LB Policy]non_ip_hash:0,ip_hash:1", allowableValues = "0,1", example = "0") + private String useOwnUpstream = "0"; // lb policy + + @ApiModelProperty(required = true) + private RouteServer servers[]; + + private String host = ""; + + private String namespace = ""; + + private String publish_port = ""; + + private boolean enable_ssl = false; // true:https:开启SSL加密, false:http + + private String consulServiceName = ""; + + private String publishProtocol = "http"; + + + + public String getPublish_port() { + return publish_port; + } + + public void setPublish_port(String publish_port) { + this.publish_port = publish_port; + } + + + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public RouteServer[] getServers() { + return servers.clone(); + } + + public void setServers(RouteServer[] servers) { + this.servers = servers.clone(); + } + + public String getControl() { + return control; + } + + public void setControl(String control) { + this.control = control; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getVisualRange() { + return visualRange; + } + + public void setVisualRange(String visualRange) { + this.visualRange = visualRange; + } + + public String getUseOwnUpstream() { + return useOwnUpstream; + } + + public void setUseOwnUpstream(String useOwnUpstream) { + this.useOwnUpstream = useOwnUpstream; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public String getConsulServiceName() { + return consulServiceName; + } + + public void setConsulServiceName(String consulServiceName) { + this.consulServiceName = consulServiceName; + } + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + public String getPublishProtocol() { + return publishProtocol; + } + + public void setPublishProtocol(String publishProtocol) { + this.publishProtocol = publishProtocol; + } + + public boolean isEnable_ssl() { + return enable_ssl; + } + + public void setEnable_ssl(boolean enable_ssl) { + this.enable_ssl = enable_ssl; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + RouteInfo that = (RouteInfo) o; + return Objects.equals(enable_ssl, that.enable_ssl) && Objects.equals(serviceName, that.serviceName) + && Objects.equals(url, that.url) && Objects.equals(control, that.control) + && Objects.equals(status, that.status) && Objects.equals(visualRange, that.visualRange) + && Objects.equals(useOwnUpstream, that.useOwnUpstream) && Arrays.equals(servers, that.servers) + && Objects.equals(host, that.host) && Objects.equals(namespace, that.namespace) + && Objects.equals(publish_port, that.publish_port) + && Objects.equals(consulServiceName, that.consulServiceName) + && Objects.equals(publishProtocol, that.publishProtocol); + } + + @Override + public int hashCode() { + return Objects.hash(serviceName, url, control, status, visualRange, useOwnUpstream, servers, host, namespace, + publish_port, enable_ssl, consulServiceName, publishProtocol); + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/RouteServer.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/RouteServer.java index e5922b4..ef4b62c 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/RouteServer.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/RouteServer.java @@ -1,62 +1,60 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api; -import io.swagger.annotations.ApiModelProperty; - import java.io.Serializable; import java.util.Objects; +import io.swagger.annotations.ApiModelProperty; + + +public class RouteServer implements Serializable { + private static final long serialVersionUID = 1L; + @ApiModelProperty(required = true) + private String ip; + + @ApiModelProperty(required = true) + private String port; + private int weight = 0; + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + -public class RouteServer implements Serializable{ - private static final long serialVersionUID = 1L; - @ApiModelProperty(required = true) - private String ip; - - @ApiModelProperty(required = true) - private String port; - private int weight=0; - - public String getIp() { - return ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - - - - public int getWeight() { - return weight; - } - - public void setWeight(int weight) { - this.weight = weight; - } - - public RouteServer(){ - - } - - public RouteServer(String ip,String port){ - this.ip=ip; - this.port=port; - this.weight=0; - } + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public RouteServer() { + + } + + public RouteServer(String ip, String port) { + this.ip = ip; + this.port = port; + this.weight = 0; + } public String getPort() { return port; @@ -66,18 +64,18 @@ public class RouteServer implements Serializable{ this.port = port; } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - RouteServer that = (RouteServer) o; - return Objects.equals(weight, that.weight) && - Objects.equals(ip, that.ip) && - Objects.equals(port, that.port); - } - - @Override - public int hashCode() { - return Objects.hash(ip, port, weight); - } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + RouteServer that = (RouteServer) o; + return Objects.equals(weight, that.weight) && Objects.equals(ip, that.ip) && Objects.equals(port, that.port); + } + + @Override + public int hashCode() { + return Objects.hash(ip, port, weight); + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/ExtendedInternalServerErrorException.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/ExtendedInternalServerErrorException.java index 86456cd..6514104 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/ExtendedInternalServerErrorException.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/ExtendedInternalServerErrorException.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api.exception; @@ -20,9 +18,10 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public class ExtendedInternalServerErrorException extends InternalServerErrorException { - + public ExtendedInternalServerErrorException(final String message) { - super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(message).type(MediaType.TEXT_PLAIN).build()); + super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(message).type(MediaType.TEXT_PLAIN) + .build()); } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/ExtendedNotFoundException.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/ExtendedNotFoundException.java index d65f944..c37e226 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/ExtendedNotFoundException.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/ExtendedNotFoundException.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api.exception; diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/UnprocessableEntityException.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/UnprocessableEntityException.java index 6c0fc8f..ad41d28 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/UnprocessableEntityException.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/api/exception/UnprocessableEntityException.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.api.exception; @@ -21,13 +19,13 @@ import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; -public class UnprocessableEntityException extends ClientErrorException{ - private static final long serialVersionUID = -8266622745725405656L; - - public UnprocessableEntityException(final String message) { - super(Response.status(HttpStatus.SC_UNPROCESSABLE_ENTITY).entity(message).type(MediaType.TEXT_PLAIN).build()); - } - - +public class UnprocessableEntityException extends ClientErrorException { + private static final long serialVersionUID = -8266622745725405656L; + + public UnprocessableEntityException(final String message) { + super(Response.status(HttpStatus.SC_UNPROCESSABLE_ENTITY).entity(message).type(MediaType.TEXT_PLAIN).build()); + } + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/ApiRouteHealthCheck.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/ApiRouteHealthCheck.java index 7edf882..6868f99 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/ApiRouteHealthCheck.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/ApiRouteHealthCheck.java @@ -1,33 +1,29 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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. ******************************************************************************/ /** -* Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE) -* -* 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. -*/ + * Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE) + * + * 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 org.onap.msb.apiroute.health; import org.onap.msb.apiroute.api.DiscoverInfo; @@ -40,26 +36,23 @@ import com.codahale.metrics.health.HealthCheck; public class ApiRouteHealthCheck extends HealthCheck { - public ApiRouteHealthCheck() { - } + public ApiRouteHealthCheck() {} @Override protected Result check() throws Exception { - DiscoverInfo discoverInfo=ConfigUtil.getInstance().getDiscoverInfo(); - - String checkUrl = - (new StringBuilder().append("http://").append(discoverInfo.toString()) - .append(RouteUtil.MSB_CHECK_URL)).toString(); + DiscoverInfo discoverInfo = ConfigUtil.getInstance().getDiscoverInfo(); + + String checkUrl = (new StringBuilder().append("http://").append(discoverInfo.toString()) + .append(RouteUtil.MSB_CHECK_URL)).toString(); + + int resultStatus = HttpClientUtil.httpGetStatus(checkUrl); + + if (resultStatus == 200) { + return Result.healthy(); + } else { + return Result.unhealthy("check consul fail:[status]" + resultStatus); + } - int resultStatus = HttpClientUtil.httpGetStatus(checkUrl); - - if(resultStatus==200){ - return Result.healthy(); - } - else{ - return Result.unhealthy("check consul fail:[status]"+resultStatus); - } - } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheck.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheck.java index 40d169a..545e4c8 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheck.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheck.java @@ -1,23 +1,19 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.health; import org.apache.commons.lang3.StringUtils; -import org.onap.msb.apiroute.ApiRouteApp; -import org.onap.msb.apiroute.wrapper.InitRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.util.ConfigUtil; import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; import org.onap.msb.apiroute.wrapper.util.HttpGetResult; @@ -28,120 +24,110 @@ import com.codahale.metrics.health.HealthCheck; public class ConsulLinkHealthCheck extends HealthCheck implements Runnable { - private static final Logger LOGGER = LoggerFactory - .getLogger(ConsulLinkHealthCheck.class); - - private final static String CONSUL_IP_ENV = ConfigUtil.getInstance().getConsul_ip(); - - private static int failedLoopCheckNum = 12; - private static int failedTimer = 5 * 1000; - - private static int normalTimer = 20 * 1000; - private static Result result = Result.healthy(); - - private String CHECK_IP = "127.0.0.1"; - private String CHECK_PORT = "8500"; - private String CHECK_URL = "http://" + CHECK_IP + ":" + CHECK_PORT - + "/v1/status/leader"; - - public static Result getResult() { - return result; - } - - @Override - protected Result check() { - // TODO Auto-generated method stub - - if (!StringUtils.isBlank(CONSUL_IP_ENV)) { - CHECK_IP = CONSUL_IP_ENV; - CHECK_URL = "http://" + CHECK_IP + ":" + CHECK_PORT - + "/v1/status/leader"; - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("check consul URL:" + CHECK_URL); - } - - try { - - HttpGetResult result = HttpClientUtil - .httpGetStatusAndBody(CHECK_URL); - - //response format:"127.0.0.1:8300" - if (result.getStatusCode() == 200 && result.getBody() != null - && result.getBody().contains(":8300")) { - return Result.healthy(); - } else { - return Result.unhealthy("check consul link " + CHECK_URL - + " fail:" + result.getStatusCode()+":"+result.getBody()); - } - - } catch (Exception e) { - LOGGER.warn( - "ConsulLinkHealthCheck:" + CHECK_URL + " execption", e); - return Result.unhealthy("check consul link " + CHECK_URL - + " exception:{}"); - } - - } - - return Result.healthy(); - } - - @Override - public void run() { - // TODO Auto-generated method stub - while (true) { - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("consul link check starttime:" - + System.currentTimeMillis()); - } - - result = checkWithPolicy(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("consul link check result:" + result.isHealthy() - + " message:" + result.getMessage()); - - LOGGER.debug("consul link check endtime:" - + System.currentTimeMillis()); - } - - try { - Thread.sleep(normalTimer); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - LOGGER.warn("loop check consul,thread sleep excepiton", e); - } - } - } - - private Result checkWithPolicy() { - int failedNum = 0; - Result temp = Result.healthy(); - - do { - // check again - temp = check(); - - // healthy break; - if (temp.isHealthy()) { - break; - } - - // unhealthy go on - failedNum++; - - try { - Thread.sleep(failedTimer); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - LOGGER.warn("loop check consul,thread sleep excepiton", e); - } - - } while (failedNum <= failedLoopCheckNum); - - return temp; - } - + private static final Logger LOGGER = LoggerFactory.getLogger(ConsulLinkHealthCheck.class); + + private final static String CONSUL_IP_ENV = ConfigUtil.getInstance().getConsul_ip(); + + private static int failedLoopCheckNum = 12; + private static int failedTimer = 5 * 1000; + + private static int normalTimer = 20 * 1000; + private static Result result = Result.healthy(); + + private String CHECK_IP = "127.0.0.1"; + private String CHECK_PORT = "8500"; + private String CHECK_URL = "http://" + CHECK_IP + ":" + CHECK_PORT + "/v1/status/leader"; + + public static Result getResult() { + return result; + } + + @Override + protected Result check() { + // TODO Auto-generated method stub + + if (!StringUtils.isBlank(CONSUL_IP_ENV)) { + CHECK_IP = CONSUL_IP_ENV; + CHECK_URL = "http://" + CHECK_IP + ":" + CHECK_PORT + "/v1/status/leader"; + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("check consul URL:" + CHECK_URL); + } + + try { + + HttpGetResult result = HttpClientUtil.httpGetStatusAndBody(CHECK_URL); + + // response format:"127.0.0.1:8300" + if (result.getStatusCode() == 200 && result.getBody() != null && result.getBody().contains(":8300")) { + return Result.healthy(); + } else { + return Result.unhealthy("check consul link " + CHECK_URL + " fail:" + result.getStatusCode() + ":" + + result.getBody()); + } + + } catch (Exception e) { + LOGGER.warn("ConsulLinkHealthCheck:" + CHECK_URL + " execption", e); + return Result.unhealthy("check consul link " + CHECK_URL + " exception:{}"); + } + + } + + return Result.healthy(); + } + + @Override + public void run() { + // TODO Auto-generated method stub + while (true) { + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("consul link check starttime:" + System.currentTimeMillis()); + } + + result = checkWithPolicy(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("consul link check result:" + result.isHealthy() + " message:" + result.getMessage()); + + LOGGER.debug("consul link check endtime:" + System.currentTimeMillis()); + } + + try { + Thread.sleep(normalTimer); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + LOGGER.warn("loop check consul,thread sleep excepiton", e); + } + } + } + + private Result checkWithPolicy() { + int failedNum = 0; + Result temp = Result.healthy(); + + do { + // check again + temp = check(); + + // healthy break; + if (temp.isHealthy()) { + break; + } + + // unhealthy go on + failedNum++; + + try { + Thread.sleep(failedTimer); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + LOGGER.warn("loop check consul,thread sleep excepiton", e); + } + + } while (failedNum <= failedLoopCheckNum); + + return temp; + } + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/OpenRestyHealthCheck.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/OpenRestyHealthCheck.java index 1f5a9e2..be3266a 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/OpenRestyHealthCheck.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/OpenRestyHealthCheck.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.health; @@ -23,32 +21,29 @@ import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck; public class OpenRestyHealthCheck extends HealthCheck { - private static final Logger LOGGER = LoggerFactory - .getLogger(OpenRestyHealthCheck.class); - private String CHECK_IP="127.0.0.1"; - private String CHECK_PORT="80"; - private String CHECK_URL = "http://"+CHECK_IP+":"+CHECK_PORT+"/api/microservices/v1/apiRoute/discoverInfo"; - - @Override - protected Result check() throws Exception { - // TODO Auto-generated method stub - - if(!StringUtils.isBlank(System.getenv("HTTP_OVERWRITE_PORT"))) - { - CHECK_PORT=System.getenv("HTTP_OVERWRITE_PORT"); - CHECK_URL = "http://"+CHECK_IP+":"+CHECK_PORT+"/api/microservices/v1/apiRoute/discoverInfo"; - LOGGER.info("check openresty URL:"+CHECK_URL); - } - - int resultStatus = HttpClientUtil.httpGetStatus(CHECK_URL); - - if (resultStatus == 200) { - return Result.healthy(); - } else { - return Result - .unhealthy("check openresty fail:" + resultStatus); - } - - } + private static final Logger LOGGER = LoggerFactory.getLogger(OpenRestyHealthCheck.class); + private String CHECK_IP = "127.0.0.1"; + private String CHECK_PORT = "80"; + private String CHECK_URL = "http://" + CHECK_IP + ":" + CHECK_PORT + "/api/microservices/v1/apiRoute/discoverInfo"; + + @Override + protected Result check() throws Exception { + // TODO Auto-generated method stub + + if (!StringUtils.isBlank(System.getenv("HTTP_OVERWRITE_PORT"))) { + CHECK_PORT = System.getenv("HTTP_OVERWRITE_PORT"); + CHECK_URL = "http://" + CHECK_IP + ":" + CHECK_PORT + "/api/microservices/v1/apiRoute/discoverInfo"; + LOGGER.info("check openresty URL:" + CHECK_URL); + } + + int resultStatus = HttpClientUtil.httpGetStatus(CHECK_URL); + + if (resultStatus == 200) { + return Result.healthy(); + } else { + return Result.unhealthy("check openresty fail:" + resultStatus); + } + + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/RedisHealthCheck.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/RedisHealthCheck.java index 48bfa48..2f2ec4c 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/RedisHealthCheck.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/health/RedisHealthCheck.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.health; @@ -21,155 +19,151 @@ import org.onap.msb.apiroute.wrapper.util.JedisUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import redis.clients.jedis.Jedis; - import com.codahale.metrics.health.HealthCheck; +import redis.clients.jedis.Jedis; + public class RedisHealthCheck extends HealthCheck implements Runnable { - private static final Logger LOGGER = LoggerFactory - .getLogger(RedisHealthCheck.class); - - public static boolean writeCheckFlag = true; - private static Result result = Result.healthy(); - - private static int failedLoopCheckNum = 12; - private static int failedTimer = 5 * 1000; - - private static int normalTimer = 20 * 1000; - - public static Result getResult() { - return result; - } - - @Override - protected Result check() { - - // check write - if (writeCheckFlag) { - Result writeCheckResult = checkWrite(); - if (writeCheckResult.isHealthy()) { - writeCheckFlag = false; - } - - // write failed - if (!writeCheckResult.isHealthy()) { - return writeCheckResult; - } - } - - // check read - Result readCheckResult = checkRead(); - - // read failed - if (!readCheckResult.isHealthy()) { - return readCheckResult; - } - - return Result.healthy(); - } - - private Result checkRead() { - Jedis jedisHandle = null; - - Result healthRst = Result.healthy(); - try { - - jedisHandle = JedisUtil.borrowJedisInstance(); - jedisHandle.get("healthchek:checktime"); - - } catch (Exception e) { - LOGGER.warn("RedisHealthCheck exception", e); - healthRst = Result.unhealthy(e); - } finally { - JedisUtil.returnJedisInstance(jedisHandle); - } - - return healthRst; - } - - private Result checkWrite() { - Jedis jedisHandle = null; - - Result healthRst = Result.healthy(); - try { - - long currentTime = System.currentTimeMillis(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String date = sdf.format(currentTime); - - jedisHandle = JedisUtil.borrowJedisInstance(); - String statusCode = jedisHandle.set("healthchek:checktime", date); - - if (statusCode != null && statusCode.equals("OK")) { - healthRst = Result.healthy("check redis:" + statusCode); - } else { - healthRst = Result.unhealthy("check redis:" + statusCode); - } - - } catch (Exception e) { - LOGGER.warn("RedisHealthCheck exception", e); - healthRst = Result.unhealthy(e); - } finally { - JedisUtil.returnJedisInstance(jedisHandle); - } - - return healthRst; - } - - @Override - public void run() { - // TODO Auto-generated method stub - while (true) { - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("redis check starttime:" - + System.currentTimeMillis()); - } - - result = checkWithPolicy(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("redis check result:" + result.isHealthy() - + " message:" + result.getMessage()); - - LOGGER.debug("redis check endtime:" - + System.currentTimeMillis()); - } - - try { - Thread.sleep(normalTimer); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - LOGGER.warn("loop check redis,thread sleep excepiton", e); - } - } - } - - private Result checkWithPolicy() { - int failedNum = 0; - Result temp = Result.healthy(); - - do { - // check again - temp = check(); - - // healthy break; - if (temp.isHealthy()) { - break; - } - - // unhealthy go on - failedNum++; - - try { - Thread.sleep(failedTimer); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - LOGGER.warn("loop check redis,thread sleep excepiton", e); - } - - } while (failedNum <= failedLoopCheckNum); - - return temp; - } + private static final Logger LOGGER = LoggerFactory.getLogger(RedisHealthCheck.class); + + public static boolean writeCheckFlag = true; + private static Result result = Result.healthy(); + + private static int failedLoopCheckNum = 12; + private static int failedTimer = 5 * 1000; + + private static int normalTimer = 20 * 1000; + + public static Result getResult() { + return result; + } + + @Override + protected Result check() { + + // check write + if (writeCheckFlag) { + Result writeCheckResult = checkWrite(); + if (writeCheckResult.isHealthy()) { + writeCheckFlag = false; + } + + // write failed + if (!writeCheckResult.isHealthy()) { + return writeCheckResult; + } + } + + // check read + Result readCheckResult = checkRead(); + + // read failed + if (!readCheckResult.isHealthy()) { + return readCheckResult; + } + + return Result.healthy(); + } + + private Result checkRead() { + Jedis jedisHandle = null; + + Result healthRst = Result.healthy(); + try { + + jedisHandle = JedisUtil.borrowJedisInstance(); + jedisHandle.get("healthchek:checktime"); + + } catch (Exception e) { + LOGGER.warn("RedisHealthCheck exception", e); + healthRst = Result.unhealthy(e); + } finally { + JedisUtil.returnJedisInstance(jedisHandle); + } + + return healthRst; + } + + private Result checkWrite() { + Jedis jedisHandle = null; + + Result healthRst = Result.healthy(); + try { + + long currentTime = System.currentTimeMillis(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = sdf.format(currentTime); + + jedisHandle = JedisUtil.borrowJedisInstance(); + String statusCode = jedisHandle.set("healthchek:checktime", date); + + if (statusCode != null && statusCode.equals("OK")) { + healthRst = Result.healthy("check redis:" + statusCode); + } else { + healthRst = Result.unhealthy("check redis:" + statusCode); + } + + } catch (Exception e) { + LOGGER.warn("RedisHealthCheck exception", e); + healthRst = Result.unhealthy(e); + } finally { + JedisUtil.returnJedisInstance(jedisHandle); + } + + return healthRst; + } + + @Override + public void run() { + // TODO Auto-generated method stub + while (true) { + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("redis check starttime:" + System.currentTimeMillis()); + } + + result = checkWithPolicy(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("redis check result:" + result.isHealthy() + " message:" + result.getMessage()); + + LOGGER.debug("redis check endtime:" + System.currentTimeMillis()); + } + + try { + Thread.sleep(normalTimer); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + LOGGER.warn("loop check redis,thread sleep excepiton", e); + } + } + } + + private Result checkWithPolicy() { + int failedNum = 0; + Result temp = Result.healthy(); + + do { + // check again + temp = check(); + + // healthy break; + if (temp.isHealthy()) { + break; + } + + // unhealthy go on + failedNum++; + + try { + Thread.sleep(failedTimer); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + LOGGER.warn("loop check redis,thread sleep excepiton", e); + } + + } while (failedNum <= failedLoopCheckNum); + + return temp; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/ApiRouteResource.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/ApiRouteResource.java index 6da841c..0dcaa75 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/ApiRouteResource.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/ApiRouteResource.java @@ -1,26 +1,18 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.resources; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - import java.net.URI; import java.util.List; @@ -43,172 +35,225 @@ import org.apache.http.HttpStatus; import org.onap.msb.apiroute.api.ApiRouteInfo; import org.onap.msb.apiroute.api.DiscoverInfo; import org.onap.msb.apiroute.wrapper.ApiRouteServiceWrapper; -import org.onap.msb.apiroute.wrapper.CustomRouteServiceWrapper; -import org.onap.msb.apiroute.wrapper.IuiRouteServiceWrapper; -import org.onap.msb.apiroute.wrapper.util.CommonUtil; import org.onap.msb.apiroute.wrapper.util.ConfigUtil; -import org.onap.msb.apiroute.wrapper.util.JacksonJsonUtil; import com.codahale.metrics.annotation.Timed; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + @Path("/apiRoute") -@Api(tags = { "ApiRoute" }) +@Api(tags = {"ApiRoute"}) @Produces(MediaType.APPLICATION_JSON) public class ApiRouteResource { @Context UriInfo uriInfo; // actual uri info - @GET - @Path("/") - @ApiOperation(value = "get all ApiRoute ", code = HttpStatus.SC_OK,response = ApiRouteInfo.class, responseContainer = "List") - @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get ApiRouteInfo List fail", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public List<ApiRouteInfo> getApiRoutes(@ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - return ApiRouteServiceWrapper.getInstance().getAllApiRouteInstances(routeWay); - } - - @POST - @Path("/") - @ApiOperation(value = "add one ApiRoute ", code = HttpStatus.SC_CREATED,response = ApiRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable ApiRouteInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "add ApiRouteInfo fail", response = String.class), - @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable ApiRouteInfo JSON REQUEST", response = String.class)}) + @GET + @Path("/") + @ApiOperation(value = "get all ApiRoute ", code = HttpStatus.SC_OK, response = ApiRouteInfo.class, + responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, + message = "get ApiRouteInfo List fail", response = String.class)}) @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response addApiRoute( - @ApiParam(value = "ApiRoute Instance Info", required = true) ApiRouteInfo apiRouteInfo, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - ApiRouteInfo new_apiRouteInfo = ApiRouteServiceWrapper.getInstance().saveApiRouteInstance4Rest(apiRouteInfo,routeWay); - URI returnURI = uriInfo.getAbsolutePathBuilder().path("/" + new_apiRouteInfo.getServiceName()+"/version/"+new_apiRouteInfo.getVersion()).build(); + @Timed + public List<ApiRouteInfo> getApiRoutes(@ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + return ApiRouteServiceWrapper.getInstance().getAllApiRouteInstances(routeWay); + } + + @POST + @Path("/") + @ApiOperation(value = "add one ApiRoute ", code = HttpStatus.SC_CREATED, response = ApiRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable ApiRouteInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "add ApiRouteInfo fail", + response = String.class), + @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable ApiRouteInfo JSON REQUEST", + response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public Response addApiRoute(@ApiParam(value = "ApiRoute Instance Info", required = true) ApiRouteInfo apiRouteInfo, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + ApiRouteInfo new_apiRouteInfo = + ApiRouteServiceWrapper.getInstance().saveApiRouteInstance4Rest(apiRouteInfo, routeWay); + URI returnURI = uriInfo.getAbsolutePathBuilder() + .path("/" + new_apiRouteInfo.getServiceName() + "/version/" + new_apiRouteInfo.getVersion()) + .build(); return Response.created(returnURI).entity(new_apiRouteInfo).build(); - } - - @GET - @Path("/{serviceName}/version/{version}") - @ApiOperation(value = "get one ApiRoute ",code = HttpStatus.SC_OK, response = ApiRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "ApiRouteInfo not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable ApiRouteInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get ApiRouteInfo fail", response = String.class)}) + } + + @GET + @Path("/{serviceName}/version/{version}") + @ApiOperation(value = "get one ApiRoute ", code = HttpStatus.SC_OK, response = ApiRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "ApiRouteInfo not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable ApiRouteInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get ApiRouteInfo fail", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) - @Timed - public ApiRouteInfo getApiRoute( - @ApiParam(value = "ApiRoute serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "ApiRoute version,if the version is empty, please enter \"null\"", required = false) @PathParam("version") @DefaultValue("") String version, - @ApiParam(value = "ApiRoute host", required = false) @QueryParam("host") String host, - @ApiParam(value = "ApiRoute Publish port", required = false) @QueryParam("publish_port") @DefaultValue("")String publish_port, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - return ApiRouteServiceWrapper.getInstance().getApiRouteInstance(serviceName,version,host,publish_port,routeWay); - - } - - @PUT - @Path("/{serviceName}/version/{version}") - @ApiOperation(value = "update one ApiRoute by serviceName and version", code = HttpStatus.SC_CREATED,response = ApiRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable ApiRouteInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update ApiRouteInfo fail", response = String.class), - @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable ApiRouteInfo JSON REQUEST", response = String.class)}) + @Timed + public ApiRouteInfo getApiRoute( + @ApiParam(value = "ApiRoute serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "ApiRoute version,if the version is empty, please enter \"null\"", + required = false) @PathParam("version") @DefaultValue("") String version, + @ApiParam(value = "ApiRoute host", required = false) @QueryParam("host") String host, + @ApiParam(value = "ApiRoute Publish port", + required = false) @QueryParam("publish_port") @DefaultValue("") String publish_port, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + return ApiRouteServiceWrapper.getInstance().getApiRouteInstance(serviceName, version, host, publish_port, + routeWay); + + } + + @PUT + @Path("/{serviceName}/version/{version}") + @ApiOperation(value = "update one ApiRoute by serviceName and version", code = HttpStatus.SC_CREATED, + response = ApiRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable ApiRouteInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update ApiRouteInfo fail", + response = String.class), + @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable ApiRouteInfo JSON REQUEST", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response updateApiRoute( - @ApiParam(value = "ApiRoute serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "ApiRoute version,if the version is empty, please enter \"null\"", required = false) @PathParam("version") @DefaultValue("") String version, - @ApiParam(value = "ApiRoute Instance Info", required = true) ApiRouteInfo apiRouteInfo, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - ApiRouteInfo new_apiRouteInfo = ApiRouteServiceWrapper.getInstance().saveApiRouteInstance4Rest(apiRouteInfo,routeWay); - URI returnURI =uriInfo.getAbsolutePathBuilder().path("/" + new_apiRouteInfo.getServiceName()+"/version/"+new_apiRouteInfo.getVersion()).build(); + @Timed + public Response updateApiRoute( + @ApiParam(value = "ApiRoute serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "ApiRoute version,if the version is empty, please enter \"null\"", + required = false) @PathParam("version") @DefaultValue("") String version, + @ApiParam(value = "ApiRoute Instance Info", required = true) ApiRouteInfo apiRouteInfo, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + ApiRouteInfo new_apiRouteInfo = + ApiRouteServiceWrapper.getInstance().saveApiRouteInstance4Rest(apiRouteInfo, routeWay); + URI returnURI = uriInfo.getAbsolutePathBuilder() + .path("/" + new_apiRouteInfo.getServiceName() + "/version/" + new_apiRouteInfo.getVersion()) + .build(); return Response.created(returnURI).entity(new_apiRouteInfo).build(); - } - - - - @DELETE - @Path("/{serviceName}/version/{version}") - @ApiOperation(value = "delete one ApiRoute by serviceName and version", code = HttpStatus.SC_NO_CONTENT) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete ApiRouteInfo succeed "), - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "ApiRouteInfo not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete ApiRouteInfo fail", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public void deleteApiRoute( - @ApiParam(value = "ApiRoute serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "ApiRoute version,if the version is empty, please enter \"null\"", required = false) @PathParam("version") @DefaultValue("") String version, - @ApiParam(value = "ApiRoute host", required = false) @QueryParam("host") String host, - @ApiParam(value = "ApiRoute Publish port", required = false) @QueryParam("publish_port") @DefaultValue("")String publish_port, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - ApiRouteServiceWrapper.getInstance().deleteApiRoute(serviceName, version,host,publish_port,routeWay); - } - - - @GET - @Path("/apiDocs") - @ApiOperation(value = "get all Local apiDoc ", code = HttpStatus.SC_OK, response = String.class, responseContainer = "List") - @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get apiDoc List fail", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public String[] getApiDocs() { - - return ApiRouteServiceWrapper.getInstance().getAllApiDocs(); - } - - - @GET + } + + + + @DELETE + @Path("/{serviceName}/version/{version}") + @ApiOperation(value = "delete one ApiRoute by serviceName and version", code = HttpStatus.SC_NO_CONTENT) + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete ApiRouteInfo succeed "), + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "ApiRouteInfo not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete ApiRouteInfo fail", + response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public void deleteApiRoute( + @ApiParam(value = "ApiRoute serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "ApiRoute version,if the version is empty, please enter \"null\"", + required = false) @PathParam("version") @DefaultValue("") String version, + @ApiParam(value = "ApiRoute host", required = false) @QueryParam("host") String host, + @ApiParam(value = "ApiRoute Publish port", + required = false) @QueryParam("publish_port") @DefaultValue("") String publish_port, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + ApiRouteServiceWrapper.getInstance().deleteApiRoute(serviceName, version, host, publish_port, routeWay); + } + + + @GET + @Path("/apiDocs") + @ApiOperation(value = "get all Local apiDoc ", code = HttpStatus.SC_OK, response = String.class, + responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get apiDoc List fail", + response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public String[] getApiDocs() { + + return ApiRouteServiceWrapper.getInstance().getAllApiDocs(); + } + + + @GET @Path("/discoverInfo") - @ApiOperation(value = "get discover Info ", code = HttpStatus.SC_OK,response = DiscoverInfo.class) - @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get discover Info fail", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "get discover Info ", code = HttpStatus.SC_OK, response = DiscoverInfo.class) + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get discover Info fail", + response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) @Timed public DiscoverInfo getServiceDiscoverInfo() { - return ConfigUtil.getInstance().getDiscoverInfo(); + return ConfigUtil.getInstance().getDiscoverInfo(); } - - @PUT - @Path("/{serviceName}/version/{version}/status/{status}") - @ApiOperation(value = "update one ApiRoute status by serviceName and version", code = HttpStatus.SC_CREATED,response = ApiRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable ApiRouteInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "ApiRouteInfo not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update status fail", response = String.class)}) + + @PUT + @Path("/{serviceName}/version/{version}/status/{status}") + @ApiOperation(value = "update one ApiRoute status by serviceName and version", code = HttpStatus.SC_CREATED, + response = ApiRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable ApiRouteInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "ApiRouteInfo not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update status fail", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response updateApiRouteStatus( - @ApiParam(value = "ApiRoute serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "ApiRoute version,if the version is empty, please enter \"null\"", required = false) @PathParam("version") @DefaultValue("") String version, - @ApiParam(value = "ApiRoute status,1:abled 0:disabled", required = true) @PathParam("status") String status, - @ApiParam(value = "ApiRoute host", required = false) @QueryParam("host") String host, - @ApiParam(value = "ApiRoute Publish port", required = false) @QueryParam("publish_port") @DefaultValue("")String publish_port, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - ApiRouteInfo new_apiRouteInfo = ApiRouteServiceWrapper.getInstance().updateApiRouteStatus(serviceName,version,host,publish_port,status,routeWay); + @Timed + public Response updateApiRouteStatus( + @ApiParam(value = "ApiRoute serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "ApiRoute version,if the version is empty, please enter \"null\"", + required = false) @PathParam("version") @DefaultValue("") String version, + @ApiParam(value = "ApiRoute status,1:abled 0:disabled", + required = true) @PathParam("status") String status, + @ApiParam(value = "ApiRoute host", required = false) @QueryParam("host") String host, + @ApiParam(value = "ApiRoute Publish port", + required = false) @QueryParam("publish_port") @DefaultValue("") String publish_port, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + ApiRouteInfo new_apiRouteInfo = ApiRouteServiceWrapper.getInstance().updateApiRouteStatus(serviceName, version, + host, publish_port, status, routeWay); return Response.created(uriInfo.getAbsolutePathBuilder().build()).entity(new_apiRouteInfo).build(); - } - - @GET + } + + @GET @Path("/export") - @ApiOperation(value = "export all route service Info by json-file", code = HttpStatus.SC_OK,response = String.class) + @ApiOperation(value = "export all route service Info by json-file", code = HttpStatus.SC_OK, + response = String.class) @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "export fail", response = String.class), - @ApiResponse(code = HttpStatus.SC_NOT_ACCEPTABLE, message = " not Acceptable client-side", response = String.class)}) - @Produces(MediaType.TEXT_PLAIN) - public Response exportService(@ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) throws Exception { + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "export fail", + response = String.class), + @ApiResponse(code = HttpStatus.SC_NOT_ACCEPTABLE, message = " not Acceptable client-side", + response = String.class)}) + @Produces(MediaType.TEXT_PLAIN) + public Response exportService( + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) + throws Exception { - ResponseBuilder response = Response.ok( ApiRouteServiceWrapper.getInstance().getAllrouteByJson(routeWay)); - return response.header("Content-Disposition", "attachment; filename=\"RouteService.json\"").build(); + ResponseBuilder response = Response.ok(ApiRouteServiceWrapper.getInstance().getAllrouteByJson(routeWay)); + return response.header("Content-Disposition", "attachment; filename=\"RouteService.json\"").build(); } - + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/CustomRouteResource.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/CustomRouteResource.java index f7ba0bc..986c4c9 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/CustomRouteResource.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/CustomRouteResource.java @@ -1,26 +1,18 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.resources; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - import java.net.URI; import java.util.List; @@ -43,122 +35,163 @@ import org.onap.msb.apiroute.wrapper.CustomRouteServiceWrapper; import com.codahale.metrics.annotation.Timed; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + @Path("/customRoute") -@Api(tags = { "CustomRoute" }) +@Api(tags = {"CustomRoute"}) @Produces(MediaType.APPLICATION_JSON) public class CustomRouteResource { - + @Context UriInfo uriInfo; // actual uri info - - @GET - @Path("/all") - @ApiOperation(value = "get all CustomRoute ", code = HttpStatus.SC_OK,response = CustomRouteInfo.class, responseContainer = "List") - @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get CustomRouteInfo List fail", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public List<CustomRouteInfo> getCustomRoutes(@ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - return CustomRouteServiceWrapper.getInstance().getAllCustomRouteInstances(routeWay); - } - - @POST - @Path("/instance") - @ApiOperation(value = "add one CustomRoute ", code = HttpStatus.SC_CREATED,response = CustomRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable CustomRouteInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "add CustomRouteInfo fail", response = String.class), - @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable CustomRouteInfo JSON REQUEST", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response addCustomRoute( - @ApiParam(value = "CustomRoute Instance Info", required = true) CustomRouteInfo customRouteInfo, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - CustomRouteInfo new_customRouteInfo = CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance4Rest(customRouteInfo,routeWay); - URI returnURI =uriInfo.getAbsolutePathBuilder().path("/instance?serviceName=" + new_customRouteInfo.getServiceName()).build(); + + @GET + @Path("/all") + @ApiOperation(value = "get all CustomRoute ", code = HttpStatus.SC_OK, response = CustomRouteInfo.class, + responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, + message = "get CustomRouteInfo List fail", response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public List<CustomRouteInfo> getCustomRoutes(@ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + return CustomRouteServiceWrapper.getInstance().getAllCustomRouteInstances(routeWay); + } + + @POST + @Path("/instance") + @ApiOperation(value = "add one CustomRoute ", code = HttpStatus.SC_CREATED, response = CustomRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable CustomRouteInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "add CustomRouteInfo fail", + response = String.class), + @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, + message = "Unprocessable CustomRouteInfo JSON REQUEST", response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public Response addCustomRoute( + @ApiParam(value = "CustomRoute Instance Info", required = true) CustomRouteInfo customRouteInfo, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + CustomRouteInfo new_customRouteInfo = + CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance4Rest(customRouteInfo, routeWay); + URI returnURI = uriInfo.getAbsolutePathBuilder() + .path("/instance?serviceName=" + new_customRouteInfo.getServiceName()).build(); return Response.created(returnURI).entity(new_customRouteInfo).build(); - } - - @GET - @Path("/instance") - @ApiOperation(value = "get one CustomRoute ",code = HttpStatus.SC_OK, response = CustomRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "CustomRoute not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable CustomRoute Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get CustomRoute fail", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public CustomRouteInfo getCustomRoute( - @ApiParam(value = "CustomRoute serviceName", required = false) @QueryParam("serviceName") String serviceName, - @ApiParam(value = "CustomRoute host", required = false) @QueryParam("host") String host, - @ApiParam(value = "CustomRoute Publish port", required = false) @QueryParam("publish_port") @DefaultValue("")String publish_port, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - - return CustomRouteServiceWrapper.getInstance().getCustomRouteInstance(serviceName,host,publish_port,routeWay); - - } - - @PUT - @Path("/instance") - @ApiOperation(value = "update one CustomRoute by serviceName", code = HttpStatus.SC_CREATED,response = CustomRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable CustomRoute Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update CustomRoute fail", response = String.class), - @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable CustomRoute JSON REQUEST", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response updateCustomRoute( - @ApiParam(value = "CustomRoute serviceName", required = true) @QueryParam("serviceName") String serviceName, - @ApiParam(value = "CustomRoute Instance Info", required = true) CustomRouteInfo customRoute, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay - ) { - - CustomRouteInfo new_customRouteInfo= CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance4Rest(customRoute,routeWay); + } + + @GET + @Path("/instance") + @ApiOperation(value = "get one CustomRoute ", code = HttpStatus.SC_OK, response = CustomRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "CustomRoute not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable CustomRoute Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get CustomRoute fail", + response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public CustomRouteInfo getCustomRoute( + @ApiParam(value = "CustomRoute serviceName", + required = false) @QueryParam("serviceName") String serviceName, + @ApiParam(value = "CustomRoute host", required = false) @QueryParam("host") String host, + @ApiParam(value = "CustomRoute Publish port", + required = false) @QueryParam("publish_port") @DefaultValue("") String publish_port, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + + return CustomRouteServiceWrapper.getInstance().getCustomRouteInstance(serviceName, host, publish_port, + routeWay); + + } + + @PUT + @Path("/instance") + @ApiOperation(value = "update one CustomRoute by serviceName", code = HttpStatus.SC_CREATED, + response = CustomRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable CustomRoute Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update CustomRoute fail", + response = String.class), + @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable CustomRoute JSON REQUEST", + response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public Response updateCustomRoute( + @ApiParam(value = "CustomRoute serviceName", + required = true) @QueryParam("serviceName") String serviceName, + @ApiParam(value = "CustomRoute Instance Info", required = true) CustomRouteInfo customRoute, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + CustomRouteInfo new_customRouteInfo = + CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance4Rest(customRoute, routeWay); return Response.created(uriInfo.getAbsolutePathBuilder().build()).entity(new_customRouteInfo).build(); - } - - @DELETE - @Path("/instance") - @ApiOperation(value = "delete one CustomRoute by serviceName", code = HttpStatus.SC_NO_CONTENT) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete customRoute succeed "), - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "customRoute not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete customRoute fail", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public void deleteCustomRoute( - @ApiParam(value = "CustomRoute serviceName", required = true) @QueryParam("serviceName") String serviceName, - @ApiParam(value = "CustomRoute host", required = false) @QueryParam("host") String host, - @ApiParam(value = "CustomRoute Publish port", required = false) @QueryParam("publish_port") @DefaultValue("")String publish_port, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - CustomRouteServiceWrapper.getInstance().deleteCustomRoute(serviceName,host,publish_port,routeWay); - - } - - @PUT - @Path("/status") - @ApiOperation(value = "update one CustomRoute status by serviceName ",code = HttpStatus.SC_CREATED, response = CustomRouteInfo.class) + } + + @DELETE + @Path("/instance") + @ApiOperation(value = "delete one CustomRoute by serviceName", code = HttpStatus.SC_NO_CONTENT) + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete customRoute succeed "), + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "customRoute not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete customRoute fail", + response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public void deleteCustomRoute( + @ApiParam(value = "CustomRoute serviceName", + required = true) @QueryParam("serviceName") String serviceName, + @ApiParam(value = "CustomRoute host", required = false) @QueryParam("host") String host, + @ApiParam(value = "CustomRoute Publish port", + required = false) @QueryParam("publish_port") @DefaultValue("") String publish_port, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + CustomRouteServiceWrapper.getInstance().deleteCustomRoute(serviceName, host, publish_port, routeWay); + + } + + @PUT + @Path("/status") + @ApiOperation(value = "update one CustomRoute status by serviceName ", code = HttpStatus.SC_CREATED, + response = CustomRouteInfo.class) @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable customRoute Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "customRoute not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update status fail", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response updateCustomRouteStatus( - @ApiParam(value = "CustomRoute serviceName", required = true) @QueryParam("serviceName") String serviceName, - @ApiParam(value = "CustomRoute host", required = false) @QueryParam("host") String host, - @ApiParam(value = "CustomRoute status,1:abled 0:disabled", required = true) @QueryParam("status") String status, - @ApiParam(value = "CustomRoute Publish port", required = false) @QueryParam("publish_port") @DefaultValue("")String publish_port, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - CustomRouteInfo new_customRouteInfo = CustomRouteServiceWrapper.getInstance().updateCustomRouteStatus(serviceName,host,publish_port,status,routeWay); + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable customRoute Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "customRoute not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update status fail", + response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public Response updateCustomRouteStatus( + @ApiParam(value = "CustomRoute serviceName", + required = true) @QueryParam("serviceName") String serviceName, + @ApiParam(value = "CustomRoute host", required = false) @QueryParam("host") String host, + @ApiParam(value = "CustomRoute status,1:abled 0:disabled", + required = true) @QueryParam("status") String status, + @ApiParam(value = "CustomRoute Publish port", + required = false) @QueryParam("publish_port") @DefaultValue("") String publish_port, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + CustomRouteInfo new_customRouteInfo = CustomRouteServiceWrapper.getInstance() + .updateCustomRouteStatus(serviceName, host, publish_port, status, routeWay); return Response.created(uriInfo.getAbsolutePathBuilder().build()).entity(new_customRouteInfo).build(); - } + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/IuiRouteResource.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/IuiRouteResource.java index d21be95..43bcf99 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/IuiRouteResource.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/IuiRouteResource.java @@ -1,26 +1,18 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.resources; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - import java.net.URI; import java.util.List; @@ -44,119 +36,158 @@ import org.onap.msb.apiroute.wrapper.IuiRouteServiceWrapper; import com.codahale.metrics.annotation.Timed; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + @Path("/iuiRoute") -@Api(tags = { "iuiRoute" }) +@Api(tags = {"iuiRoute"}) @Produces(MediaType.APPLICATION_JSON) public class IuiRouteResource { @Context UriInfo uriInfo; // actual uri info - @GET - @Path("/") - @ApiOperation(value = "get all iuiRoute ", code = HttpStatus.SC_OK,response = IuiRouteInfo.class, responseContainer = "List") - @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get iuiRouteInfo List fail", response = String.class)}) + @GET + @Path("/") + @ApiOperation(value = "get all iuiRoute ", code = HttpStatus.SC_OK, response = IuiRouteInfo.class, + responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, + message = "get iuiRouteInfo List fail", response = String.class)}) @Produces(MediaType.APPLICATION_JSON) - @Timed - public List<IuiRouteInfo> getIuiRoutes(@ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - return IuiRouteServiceWrapper.getInstance().getAllIuiRouteInstances(routeWay); - } - - @POST - @Path("/") - @ApiOperation(value = "add one iuiRoute ", code = HttpStatus.SC_CREATED,response = IuiRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable iuiRouteInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "add iuiRouteInfo fail", response = String.class), - @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable iuiRouteInfo JSON REQUEST", response = String.class)}) + @Timed + public List<IuiRouteInfo> getIuiRoutes(@ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + return IuiRouteServiceWrapper.getInstance().getAllIuiRouteInstances(routeWay); + } + + @POST + @Path("/") + @ApiOperation(value = "add one iuiRoute ", code = HttpStatus.SC_CREATED, response = IuiRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable iuiRouteInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "add iuiRouteInfo fail", + response = String.class), + @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable iuiRouteInfo JSON REQUEST", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response addIuiRoute( - @ApiParam(value = "iuiRoute Instance Info", required = true) IuiRouteInfo iuiRouteInfo, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - IuiRouteInfo new_iuiRouteInfo = IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance4Rest(iuiRouteInfo,routeWay); - URI returnURI =uriInfo.getAbsolutePathBuilder().path("/" + new_iuiRouteInfo.getServiceName()).build(); + @Timed + public Response addIuiRoute(@ApiParam(value = "iuiRoute Instance Info", required = true) IuiRouteInfo iuiRouteInfo, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + IuiRouteInfo new_iuiRouteInfo = + IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance4Rest(iuiRouteInfo, routeWay); + URI returnURI = uriInfo.getAbsolutePathBuilder().path("/" + new_iuiRouteInfo.getServiceName()).build(); return Response.created(returnURI).entity(new_iuiRouteInfo).build(); - } - - @GET - @Path("/{serviceName}") - @ApiOperation(value = "get one iuiRoute ",code = HttpStatus.SC_OK, response = IuiRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "IuiRouteInfo not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable IuiRouteInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get IuiRouteInfo fail", response = String.class)}) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public IuiRouteInfo getIuiRoute( - @ApiParam(value = "iuiRoute serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "iuiRoute host", required = false) @QueryParam("host") String host, - @ApiParam(value = "iuiRoute Publish port", required = false) @QueryParam("publish_port") @DefaultValue("")String publish_port, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - return IuiRouteServiceWrapper.getInstance().getIuiRouteInstance(serviceName,host,publish_port,routeWay); - - } - - @PUT - @Path("/{serviceName}") - @ApiOperation(value = "update one iuiRoute by serviceName", code = HttpStatus.SC_CREATED,response = IuiRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable IuiRouteInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update IuiRouteInfo fail", response = String.class), - @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable IuiRouteInfo JSON REQUEST", response = String.class)}) + } + + @GET + @Path("/{serviceName}") + @ApiOperation(value = "get one iuiRoute ", code = HttpStatus.SC_OK, response = IuiRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "IuiRouteInfo not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable IuiRouteInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get IuiRouteInfo fail", + response = String.class)}) + @Produces(MediaType.APPLICATION_JSON) + @Timed + public IuiRouteInfo getIuiRoute( + @ApiParam(value = "iuiRoute serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "iuiRoute host", required = false) @QueryParam("host") String host, + @ApiParam(value = "iuiRoute Publish port", + required = false) @QueryParam("publish_port") @DefaultValue("") String publish_port, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + return IuiRouteServiceWrapper.getInstance().getIuiRouteInstance(serviceName, host, publish_port, routeWay); + + } + + @PUT + @Path("/{serviceName}") + @ApiOperation(value = "update one iuiRoute by serviceName", code = HttpStatus.SC_CREATED, + response = IuiRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable IuiRouteInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update IuiRouteInfo fail", + response = String.class), + @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable IuiRouteInfo JSON REQUEST", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response updateIuiRoute( - @ApiParam(value = "iuiRoute serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "iuiRoute Instance Info", required = true) IuiRouteInfo iuiRouteInfo, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - IuiRouteInfo new_iuiRouteInfo = IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance4Rest(iuiRouteInfo,routeWay); - URI returnURI =uriInfo.getAbsolutePathBuilder().path("/" + serviceName).build(); + @Timed + public Response updateIuiRoute( + @ApiParam(value = "iuiRoute serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "iuiRoute Instance Info", required = true) IuiRouteInfo iuiRouteInfo, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + IuiRouteInfo new_iuiRouteInfo = + IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance4Rest(iuiRouteInfo, routeWay); + URI returnURI = uriInfo.getAbsolutePathBuilder().path("/" + serviceName).build(); return Response.created(returnURI).entity(new_iuiRouteInfo).build(); - } - - @DELETE - @Path("/{serviceName}") - @ApiOperation(value = "delete one iuiRoute by serviceName", code = HttpStatus.SC_NO_CONTENT) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete IuiRouteInfo succeed "), - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "IuiRouteInfo not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete IuiRouteInfo fail", response = String.class)}) + } + + @DELETE + @Path("/{serviceName}") + @ApiOperation(value = "delete one iuiRoute by serviceName", code = HttpStatus.SC_NO_CONTENT) + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete IuiRouteInfo succeed "), + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "IuiRouteInfo not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete IuiRouteInfo fail", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) - @Timed - public void deleteIuiRoute( - @ApiParam(value = "iuiRoute serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "iuiRoute host", required = false) @QueryParam("host") String host, - @ApiParam(value = "iuiRoute Publish port", required = false) @QueryParam("publish_port") @DefaultValue("")String publish_port, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - IuiRouteServiceWrapper.getInstance().deleteIuiRoute(serviceName,host,publish_port,routeWay); - - } - - @PUT - @Path("/{serviceName}/status/{status}") - @ApiOperation(value = "update one iuiRoute status by serviceName ",code = HttpStatus.SC_CREATED, response = IuiRouteInfo.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable IuiRouteInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "IuiRouteInfo not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update IuiRouteInfo status fail", response = String.class)}) + @Timed + public void deleteIuiRoute( + @ApiParam(value = "iuiRoute serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "iuiRoute host", required = false) @QueryParam("host") String host, + @ApiParam(value = "iuiRoute Publish port", + required = false) @QueryParam("publish_port") @DefaultValue("") String publish_port, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + IuiRouteServiceWrapper.getInstance().deleteIuiRoute(serviceName, host, publish_port, routeWay); + + } + + @PUT + @Path("/{serviceName}/status/{status}") + @ApiOperation(value = "update one iuiRoute status by serviceName ", code = HttpStatus.SC_CREATED, + response = IuiRouteInfo.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable IuiRouteInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "IuiRouteInfo not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, + message = "update IuiRouteInfo status fail", response = String.class)}) @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response updateIuiRouteStatus( - @ApiParam(value = "iuiRoute serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "iuiRoute host", required = false) @QueryParam("host") String host, - @ApiParam(value = "iuiRoute status,1:abled 0:disabled", required = true) @PathParam("status") String status, - @ApiParam(value = "iuiRoute Publish port", required = false) @QueryParam("publish_port") @DefaultValue("")String publish_port, - @ApiParam(value = "Route Way", required = false) @QueryParam("routeWay") @DefaultValue("ip")String routeWay) { - - IuiRouteInfo new_iuiRouteInfo = IuiRouteServiceWrapper.getInstance().updateIuiRouteStatus(serviceName,host,publish_port,status,routeWay); - URI returnURI =uriInfo.getAbsolutePathBuilder().path("/" + serviceName).build(); + @Timed + public Response updateIuiRouteStatus( + @ApiParam(value = "iuiRoute serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "iuiRoute host", required = false) @QueryParam("host") String host, + @ApiParam(value = "iuiRoute status,1:abled 0:disabled", + required = true) @PathParam("status") String status, + @ApiParam(value = "iuiRoute Publish port", + required = false) @QueryParam("publish_port") @DefaultValue("") String publish_port, + @ApiParam(value = "Route Way", + required = false) @QueryParam("routeWay") @DefaultValue("ip") String routeWay) { + + IuiRouteInfo new_iuiRouteInfo = IuiRouteServiceWrapper.getInstance().updateIuiRouteStatus(serviceName, host, + publish_port, status, routeWay); + URI returnURI = uriInfo.getAbsolutePathBuilder().path("/" + serviceName).build(); return Response.created(returnURI).entity(new_iuiRouteInfo).build(); - } - + } + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/MicroServiceResource.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/MicroServiceResource.java index 4f02c8e..ba850db 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/MicroServiceResource.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/resources/MicroServiceResource.java @@ -1,26 +1,18 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.resources; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - import java.net.URI; import java.util.List; @@ -52,20 +44,27 @@ import org.slf4j.LoggerFactory; import com.codahale.metrics.annotation.Timed; import com.codahale.metrics.health.HealthCheck.Result; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + @Path("/services") // @Api(tags = {"MSB-Service Resource"}) @Produces(MediaType.APPLICATION_JSON) public class MicroServiceResource { - private static final Logger LOGGER = LoggerFactory.getLogger(MicroServiceResource.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MicroServiceResource.class); @Context UriInfo uriInfo; // actual uri info @GET @Path("/") - @ApiOperation(value = "get all microservices ", code = HttpStatus.SC_OK, response = MicroServiceFullInfo.class, responseContainer = "List") - @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get microservice List fail", response = String.class)}) + @ApiOperation(value = "get all microservices ", code = HttpStatus.SC_OK, response = MicroServiceFullInfo.class, + responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, + message = "get microservice List fail", response = String.class)}) @Produces(MediaType.APPLICATION_JSON) @Timed public List<MicroServiceFullInfo> getMicroService() { @@ -76,21 +75,29 @@ public class MicroServiceResource { @Path("/") @ApiOperation(value = "add one microservice ", code = HttpStatus.SC_CREATED, response = MicroServiceFullInfo.class) @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "add microservice fail", response = String.class), - @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable MicroServiceInfo JSON REQUEST", response = String.class)}) + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "add microservice fail", + response = String.class), + @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, + message = "Unprocessable MicroServiceInfo JSON REQUEST", response = String.class)}) @Produces(MediaType.APPLICATION_JSON) @Timed public Response addMicroService( - @ApiParam(value = "MicroServiceInfo Instance Info", required = true) MicroServiceFullInfo microServiceInfo, - @Context HttpServletRequest request, - @ApiParam(value = "createOrUpdate", required = false) @QueryParam("createOrUpdate") @DefaultValue("true") boolean createOrUpdate, - @ApiParam(value = "port", required = false) @QueryParam("port") @DefaultValue("") String port) { - - String ip=MicroServiceUtil.getRealIp(request); - - MicroServiceFullInfo microServiceFullInfo =MicroServiceWrapper.getInstance().saveMicroServiceInstance(microServiceInfo,createOrUpdate,ip,port); - URI returnURI =uriInfo.getAbsolutePathBuilder().path("/" + microServiceInfo.getServiceName() + "/version/"+ microServiceInfo.getVersion()).build(); + @ApiParam(value = "MicroServiceInfo Instance Info", + required = true) MicroServiceFullInfo microServiceInfo, + @Context HttpServletRequest request, + @ApiParam(value = "createOrUpdate", + required = false) @QueryParam("createOrUpdate") @DefaultValue("true") boolean createOrUpdate, + @ApiParam(value = "port", required = false) @QueryParam("port") @DefaultValue("") String port) { + + String ip = MicroServiceUtil.getRealIp(request); + + MicroServiceFullInfo microServiceFullInfo = MicroServiceWrapper.getInstance() + .saveMicroServiceInstance(microServiceInfo, createOrUpdate, ip, port); + URI returnURI = uriInfo.getAbsolutePathBuilder() + .path("/" + microServiceInfo.getServiceName() + "/version/" + microServiceInfo.getVersion()) + .build(); return Response.created(returnURI).entity(microServiceFullInfo).build(); } @@ -100,14 +107,17 @@ public class MicroServiceResource { @Path("/{serviceName}/version/{version}") @ApiOperation(value = "get one microservice ", code = HttpStatus.SC_OK, response = MicroServiceFullInfo.class) @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "microservice not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get microservice fail", response = String.class)}) + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "get microservice fail", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) @Timed public MicroServiceFullInfo getMicroService( - @ApiParam(value = "microservice serviceName") @PathParam("serviceName") String serviceName, - @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"") @PathParam("version") @DefaultValue("") String version) { + @ApiParam(value = "microservice serviceName") @PathParam("serviceName") String serviceName, + @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"") @PathParam("version") @DefaultValue("") String version) { return MicroServiceWrapper.getInstance().getMicroServiceInstance(serviceName, version); @@ -117,46 +127,53 @@ public class MicroServiceResource { @PUT @Path("/{serviceName}/version/{version}") - @ApiOperation(value = "update one microservice by serviceName and version", code = HttpStatus.SC_CREATED, response = MicroServiceFullInfo.class) + @ApiOperation(value = "update one microservice by serviceName and version", code = HttpStatus.SC_CREATED, + response = MicroServiceFullInfo.class) @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update microservice fail", response = String.class), - @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = "Unprocessable MicroServiceInfo JSON REQUEST", response = String.class)}) + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update microservice fail", + response = String.class), + @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, + message = "Unprocessable MicroServiceInfo JSON REQUEST", response = String.class)}) @Produces(MediaType.APPLICATION_JSON) @Timed public Response updateMicroService( - @ApiParam(value = "microservice serviceName") @PathParam("serviceName") String serviceName, - @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"") @PathParam("version") @DefaultValue("") String version, - @ApiParam(value = "microservice Instance Info", required = true) MicroServiceFullInfo microServiceInfo, - @Context HttpServletRequest request) { - - String ip=MicroServiceUtil.getRealIp(request); - MicroServiceFullInfo microServiceFullInfo = MicroServiceWrapper.getInstance().saveMicroServiceInstance(microServiceInfo, - false,ip,""); + @ApiParam(value = "microservice serviceName") @PathParam("serviceName") String serviceName, + @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"") @PathParam("version") @DefaultValue("") String version, + @ApiParam(value = "microservice Instance Info", + required = true) MicroServiceFullInfo microServiceInfo, + @Context HttpServletRequest request) { + + String ip = MicroServiceUtil.getRealIp(request); + MicroServiceFullInfo microServiceFullInfo = + MicroServiceWrapper.getInstance().saveMicroServiceInstance(microServiceInfo, false, ip, ""); return Response.created(uriInfo.getAbsolutePathBuilder().build()).entity(microServiceFullInfo).build(); } - @DELETE @Path("/{serviceName}/version/{version}/nodes/{ip}/{port}") @ApiOperation(value = "delete single node by serviceName and version and node", code = HttpStatus.SC_NO_CONTENT) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete node succeed "), - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "node not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete node fail", response = String.class)}) + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete node succeed "), + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "node not found", response = String.class), + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete node fail", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) @Timed public void deleteNode( - @ApiParam(value = "microservice serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"", required = false) @PathParam("version") @DefaultValue("") String version, - @ApiParam(value = "ip") @PathParam("ip") String ip, - @ApiParam(value = "port") @PathParam("port") String port) { + @ApiParam(value = "microservice serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"", + required = false) @PathParam("version") @DefaultValue("") String version, + @ApiParam(value = "ip") @PathParam("ip") String ip, + @ApiParam(value = "port") @PathParam("port") String port) { - MicroServiceWrapper.getInstance().deleteMicroServiceInstance(serviceName, version, ip,port); + MicroServiceWrapper.getInstance().deleteMicroServiceInstance(serviceName, version, ip, port); } @@ -164,65 +181,77 @@ public class MicroServiceResource { @DELETE @Path("/{serviceName}/version/{version}") @ApiOperation(value = "delete one full microservice by serviceName and version", code = HttpStatus.SC_NO_CONTENT) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete microservice succeed "), - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "microservice not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete microservice fail", response = String.class)}) + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_NO_CONTENT, message = "delete microservice succeed "), + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "delete microservice fail", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) @Timed public void deleteMicroService( - @ApiParam(value = "microservice serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"", required = false) @PathParam("version") @DefaultValue("") String version) { + @ApiParam(value = "microservice serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"", + required = false) @PathParam("version") @DefaultValue("") String version) { - MicroServiceWrapper.getInstance().deleteMicroService(serviceName, version); + MicroServiceWrapper.getInstance().deleteMicroService(serviceName, version); } @PUT @Path("/{serviceName}/version/{version}/status/{status}") - @ApiOperation(value = "update microservice status by serviceName and version", code = HttpStatus.SC_CREATED, response = MicroServiceFullInfo.class) + @ApiOperation(value = "update microservice status by serviceName and version", code = HttpStatus.SC_CREATED, + response = MicroServiceFullInfo.class) @ApiResponses(value = { - @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "microservice not found", response = String.class), - @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update status fail", response = String.class)}) + @ApiResponse(code = HttpStatus.SC_UNPROCESSABLE_ENTITY, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "update status fail", + response = String.class)}) @Produces(MediaType.APPLICATION_JSON) @Timed public Response updateServiceStatus( - @ApiParam(value = "microservice serviceName", required = true) @PathParam("serviceName") String serviceName, - @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"", required = false) @PathParam("version") @DefaultValue("") String version, - @ApiParam(value = "status,1:abled 0:disabled") @PathParam("status") String status) { + @ApiParam(value = "microservice serviceName", + required = true) @PathParam("serviceName") String serviceName, + @ApiParam(value = "microservice version,if the version is empty, please enter \"null\"", + required = false) @PathParam("version") @DefaultValue("") String version, + @ApiParam(value = "status,1:abled 0:disabled") @PathParam("status") String status) { - MicroServiceFullInfo microServiceFullInfo = MicroServiceWrapper.getInstance().updateMicroServiceStatus(serviceName, version,status); + MicroServiceFullInfo microServiceFullInfo = + MicroServiceWrapper.getInstance().updateMicroServiceStatus(serviceName, version, status); return Response.created(uriInfo.getAbsolutePathBuilder().build()).entity(microServiceFullInfo).build(); } - - @GET - @Path("/health") - @ApiOperation(value = "apigateway healthy check ", code = HttpStatus.SC_OK, response = String.class) - @ApiResponses(value = { @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "check fail", response = String.class) }) - @Produces(MediaType.TEXT_PLAIN) - @Timed - public Response health() { - - // redis - Result rst = RedisHealthCheck.getResult(); - if (!rst.isHealthy()) { - LOGGER.warn("health check failed:"+rst.getMessage()); - throw new ExtendedInternalServerErrorException(rst.getMessage()); - } - - //consul - rst = ConsulLinkHealthCheck.getResult(); - if (!rst.isHealthy()) { - LOGGER.warn("health check failed:"+rst.getMessage()); - throw new ExtendedInternalServerErrorException(rst.getMessage()); - } - - return Response.ok("apigateway healthy check:ok").build(); - } + + @GET + @Path("/health") + @ApiOperation(value = "apigateway healthy check ", code = HttpStatus.SC_OK, response = String.class) + @ApiResponses(value = {@ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "check fail", + response = String.class)}) + @Produces(MediaType.TEXT_PLAIN) + @Timed + public Response health() { + + // redis + Result rst = RedisHealthCheck.getResult(); + if (!rst.isHealthy()) { + LOGGER.warn("health check failed:" + rst.getMessage()); + throw new ExtendedInternalServerErrorException(rst.getMessage()); + } + + // consul + rst = ConsulLinkHealthCheck.getResult(); + if (!rst.isHealthy()) { + LOGGER.warn("health check failed:" + rst.getMessage()); + throw new ExtendedInternalServerErrorException(rst.getMessage()); + } + + return Response.ok("apigateway healthy check:ok").build(); + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapper.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapper.java index 9c0eca3..69a5586 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapper.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapper.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; @@ -33,241 +31,257 @@ import org.slf4j.LoggerFactory; -public class ApiRouteServiceWrapper { +public class ApiRouteServiceWrapper { - private static final Logger LOGGER = LoggerFactory.getLogger(ApiRouteServiceWrapper.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ApiRouteServiceWrapper.class); - private static ApiRouteServiceWrapper instance = new ApiRouteServiceWrapper(); + private static ApiRouteServiceWrapper instance = new ApiRouteServiceWrapper(); - private ApiRouteServiceWrapper() {} - - public static ApiRouteServiceWrapper getInstance() { - return instance; - } + private ApiRouteServiceWrapper() {} + public static ApiRouteServiceWrapper getInstance() { + return instance; + } - public List<ApiRouteInfo> getAllApiRouteInstances(String routeWay) { - - RouteUtil.checkRouteWay(routeWay); - - try { - String apiRedisKey=RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, routeWay); - return ApiRouteService.getInstance().getMultiApiRouteInstances(apiRedisKey); - - } catch (Exception e) { - throw new ExtendedInternalServerErrorException(e.getMessage()); - } - } + public List<ApiRouteInfo> getAllApiRouteInstances(String routeWay) { + RouteUtil.checkRouteWay(routeWay); + try { + String apiRedisKey = RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, routeWay); - /** - * @Title: getApiRouteInstance - * @Description: TODO(Through the name + version for a single service object information) - * @param: @param serviceName - * @param: @param version - * @param: @return - * @return: ApiRouteInfo - */ - public ApiRouteInfo getApiRouteInstance(String serviceName, String version, String host,String publish_port,String routeWay) { + return ApiRouteService.getInstance().getMultiApiRouteInstances(apiRedisKey); - RouteUtil.checkRouteWay(routeWay); - - if ("null".equals(version)) { - version = ""; + } catch (Exception e) { + throw new ExtendedInternalServerErrorException(e.getMessage()); + } } - RouteUtil.checkServiceNameAndVersion(serviceName,version); - - String apiRedisPrefixedKey=RouteUtil.getAPIRedisPrefixedKey(serviceName, version, host, publish_port, routeWay); - - ApiRouteInfo apiRouteInfo; - try { - apiRouteInfo = ApiRouteService.getInstance().getApiRouteInstance(apiRedisPrefixedKey); - } catch (Exception e) { - LOGGER.error("get ApiRouteInstance throw exception", e); - throw new ExtendedInternalServerErrorException("get ApiRouteInstance throw exception" + e.getMessage()); - } - - if (null == apiRouteInfo) { - throw new ExtendedNotFoundException("Api RouteInfo not found"); - } + /** + * @Title: getApiRouteInstance + * @Description: TODO(Through the name + version for a single service object information) + * @param: @param serviceName + * @param: @param version + * @param: @return + * @return: ApiRouteInfo + */ + public ApiRouteInfo getApiRouteInstance(String serviceName, String version, String host, String publish_port, + String routeWay) { - return apiRouteInfo; + RouteUtil.checkRouteWay(routeWay); - } + if ("null".equals(version)) { + version = ""; + } - + RouteUtil.checkServiceNameAndVersion(serviceName, version); - /** - * @Title updateApiRouteStatus - * @Description TODO(update ApiRoute Status) - * @param serviceName - * @param version - * @param status - * @return - * @return RouteResult - */ - public synchronized ApiRouteInfo updateApiRouteStatus(String serviceName, String version,String host,String publish_port, - String status,String routeWay) { + String apiRedisPrefixedKey = + RouteUtil.getAPIRedisPrefixedKey(serviceName, version, host, publish_port, routeWay); - RouteUtil.checkRouteWay(routeWay); - - if ("null".equals(version)) { - version = ""; - } - - RouteUtil.checkServiceNameAndVersion(serviceName,version); - - RouteUtil.checkServiceStatus(status); - - - String apiRedisPrefixedKey=RouteUtil.getAPIRedisPrefixedKey(serviceName, version, host, publish_port, routeWay); - - try { - ApiRouteService.getInstance().updateApiRouteStatus2Redis(apiRedisPrefixedKey, status); - } catch (Exception e) { - LOGGER.error("update ApiRoute status throw exception", e); - throw new ExtendedInternalServerErrorException(e.getMessage()); - } + ApiRouteInfo apiRouteInfo; + try { + apiRouteInfo = ApiRouteService.getInstance().getApiRouteInstance(apiRedisPrefixedKey); + } catch (Exception e) { + LOGGER.error("get ApiRouteInstance throw exception", e); + throw new ExtendedInternalServerErrorException("get ApiRouteInstance throw exception" + e.getMessage()); + } + + + + if (null == apiRouteInfo) { + throw new ExtendedNotFoundException("Api RouteInfo not found"); + } + + return apiRouteInfo; - ApiRouteInfo new_apiRouteInfo = getApiRouteInstance(serviceName, version,host,publish_port,routeWay); - return new_apiRouteInfo; - } - - - /** - * @Title: saveApiRouteInstance - * @Description: TODO(save ApiRouteInstance) - * @param: @param apiRouteInfo - * @param: @return - * @return: ApiRouteInfo - */ - public synchronized ApiRouteInfo saveApiRouteInstance4Rest(ApiRouteInfo apiRouteInfo,String routeWay) { - - RouteUtil.checkRouteWay(routeWay); - - RouteUtil.checkRouterInfoFormat(apiRouteInfo); - - try { - saveApiRouteInstance(apiRouteInfo,routeWay); - } catch (Exception e) { - throw new ExtendedInternalServerErrorException("save apiRouteInfo fail: [serviceName]"+apiRouteInfo.getServiceName()+"[version]"+apiRouteInfo.getVersion()+" [routeWay]"+routeWay+e.getMessage()); } - - return apiRouteInfo; - } - - - - public synchronized void saveApiRouteInstance(ApiRouteInfo apiRouteInfo,String routeWay) throws Exception { - try { - String apiRedisPrefixedKey=RouteUtil.getAPIRedisPrefixedKey(apiRouteInfo.getServiceName(), apiRouteInfo.getVersion(), apiRouteInfo.getHost(), apiRouteInfo.getPublish_port(), routeWay); - - ApiRouteService.getInstance().saveApiRouteService2Redis(apiRouteInfo, apiRedisPrefixedKey); - LOGGER.info("save apiRouteInfo [serviceName]"+apiRouteInfo.getServiceName()+"[version]"+apiRouteInfo.getVersion()+" [routeWay]"+routeWay+" success"); - } catch (Exception e) { - LOGGER.error("save apiRouteInfo [serviceName]"+apiRouteInfo.getServiceName()+"[version]"+apiRouteInfo.getVersion()+" [routeWay]"+routeWay+" throw exception", e); - throw e; + + + + /** + * @Title updateApiRouteStatus + * @Description TODO(update ApiRoute Status) + * @param serviceName + * @param version + * @param status + * @return + * @return RouteResult + */ + public synchronized ApiRouteInfo updateApiRouteStatus(String serviceName, String version, String host, + String publish_port, String status, String routeWay) { + + RouteUtil.checkRouteWay(routeWay); + + if ("null".equals(version)) { + version = ""; + } + + RouteUtil.checkServiceNameAndVersion(serviceName, version); + + RouteUtil.checkServiceStatus(status); + + + String apiRedisPrefixedKey = + RouteUtil.getAPIRedisPrefixedKey(serviceName, version, host, publish_port, routeWay); + + try { + ApiRouteService.getInstance().updateApiRouteStatus2Redis(apiRedisPrefixedKey, status); + } catch (Exception e) { + LOGGER.error("update ApiRoute status throw exception", e); + throw new ExtendedInternalServerErrorException(e.getMessage()); + } + + ApiRouteInfo new_apiRouteInfo = getApiRouteInstance(serviceName, version, host, publish_port, routeWay); + return new_apiRouteInfo; } - - - } - - - - /** - * @Title: deleteApiRoute - * @Description: TODO(delete one ApiRoute) - * @param: @param type - * @param: @param serviceName - * @param: @param version - * @param: @param delKey - * @param: @return - * @return: void - */ - public synchronized void deleteApiRoute(String serviceName, String version, String host,String publish_port,String routeWay) { - - RouteUtil.checkRouteWay(routeWay); - - if ("null".equals(version)) { - version = ""; + + + /** + * @Title: saveApiRouteInstance + * @Description: TODO(save ApiRouteInstance) + * @param: @param apiRouteInfo + * @param: @return + * @return: ApiRouteInfo + */ + public synchronized ApiRouteInfo saveApiRouteInstance4Rest(ApiRouteInfo apiRouteInfo, String routeWay) { + + RouteUtil.checkRouteWay(routeWay); + + RouteUtil.checkRouterInfoFormat(apiRouteInfo); + + try { + saveApiRouteInstance(apiRouteInfo, routeWay); + } catch (Exception e) { + throw new ExtendedInternalServerErrorException( + "save apiRouteInfo fail: [serviceName]" + apiRouteInfo.getServiceName() + "[version]" + + apiRouteInfo.getVersion() + " [routeWay]" + routeWay + e.getMessage()); + } + + return apiRouteInfo; } - RouteUtil.checkServiceNameAndVersion(serviceName,version); - String apiRedisPrefixedKey=RouteUtil.getAPIRedisPrefixedKey(serviceName, version, host, publish_port, routeWay); - - try { - ApiRouteService.getInstance() - .deleteApiRouteService2Redis(apiRedisPrefixedKey); - LOGGER.info("delete apiRouteInfo [serviceName]"+serviceName+"[version]"+version+" [host]"+host +" [publish_port]"+publish_port+" [routeWay]"+routeWay+" success"); + public synchronized void saveApiRouteInstance(ApiRouteInfo apiRouteInfo, String routeWay) throws Exception { + try { + String apiRedisPrefixedKey = + RouteUtil.getAPIRedisPrefixedKey(apiRouteInfo.getServiceName(), apiRouteInfo.getVersion(), + apiRouteInfo.getHost(), apiRouteInfo.getPublish_port(), routeWay); + + ApiRouteService.getInstance().saveApiRouteService2Redis(apiRouteInfo, apiRedisPrefixedKey); + LOGGER.info("save apiRouteInfo [serviceName]" + apiRouteInfo.getServiceName() + "[version]" + + apiRouteInfo.getVersion() + " [routeWay]" + routeWay + " success"); + } catch (Exception e) { + LOGGER.error("save apiRouteInfo [serviceName]" + apiRouteInfo.getServiceName() + "[version]" + + apiRouteInfo.getVersion() + " [routeWay]" + routeWay + " throw exception", e); + throw e; + } + } - catch (ExtendedNotFoundException e) { - throw e; - }catch (Exception e) { - LOGGER.error("delete apiRouteInfo [serviceName]"+serviceName+"[version]"+version+" [host]"+host +" [publish_port]"+publish_port+" [routeWay]"+routeWay+" throw exception", e); - throw new ExtendedInternalServerErrorException("delete apiRouteInfo [serviceName]"+serviceName+"[version]"+version+e.getMessage()); + + + /** + * @Title: deleteApiRoute + * @Description: TODO(delete one ApiRoute) + * @param: @param type + * @param: @param serviceName + * @param: @param version + * @param: @param delKey + * @param: @return + * @return: void + */ + public synchronized void deleteApiRoute(String serviceName, String version, String host, String publish_port, + String routeWay) { + + RouteUtil.checkRouteWay(routeWay); + + if ("null".equals(version)) { + version = ""; + } + + RouteUtil.checkServiceNameAndVersion(serviceName, version); + + String apiRedisPrefixedKey = + RouteUtil.getAPIRedisPrefixedKey(serviceName, version, host, publish_port, routeWay); + + + try { + ApiRouteService.getInstance().deleteApiRouteService2Redis(apiRedisPrefixedKey); + LOGGER.info("delete apiRouteInfo [serviceName]" + serviceName + "[version]" + version + " [host]" + host + + " [publish_port]" + publish_port + " [routeWay]" + routeWay + " success"); + + } catch (ExtendedNotFoundException e) { + throw e; + } catch (Exception e) { + LOGGER.error("delete apiRouteInfo [serviceName]" + serviceName + "[version]" + version + " [host]" + host + + " [publish_port]" + publish_port + " [routeWay]" + routeWay + " throw exception", e); + + throw new ExtendedInternalServerErrorException( + "delete apiRouteInfo [serviceName]" + serviceName + "[version]" + version + e.getMessage()); + } + + } - - - } - - - /** - * @Title: getAllApiDocs - * @Description: TODO(For local ext\initSwaggerJson directory of all the json file directory) - * @param: @return - * @return: String[] - */ - public String[] getAllApiDocs() { - URL apiDocsPath = ApiRouteServiceWrapper.class.getResource("/ext/initSwaggerJson"); - if (apiDocsPath != null) { - String path = apiDocsPath.getPath(); - - try { - return FileUtil.readfile(path); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - LOGGER.error("read ApiDocs Files throw FileNotFoundException", e); - throw new ExtendedInternalServerErrorException("read ApiDocs Files throw FileNotFoundException:" + e.getMessage()); - } catch (IOException e) { - // TODO Auto-generated catch block - LOGGER.error("read ApiDocs Files throw IOexception", e); - throw new ExtendedInternalServerErrorException("read ApiDocs Files throw IOexception:" + e.getMessage()); - } + + /** + * @Title: getAllApiDocs + * @Description: TODO(For local ext\initSwaggerJson directory of all the json file directory) + * @param: @return + * @return: String[] + */ + public String[] getAllApiDocs() { + URL apiDocsPath = ApiRouteServiceWrapper.class.getResource("/ext/initSwaggerJson"); + if (apiDocsPath != null) { + String path = apiDocsPath.getPath(); + + try { + return FileUtil.readfile(path); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + LOGGER.error("read ApiDocs Files throw FileNotFoundException", e); + throw new ExtendedInternalServerErrorException( + "read ApiDocs Files throw FileNotFoundException:" + e.getMessage()); + } catch (IOException e) { + // TODO Auto-generated catch block + LOGGER.error("read ApiDocs Files throw IOexception", e); + throw new ExtendedInternalServerErrorException( + "read ApiDocs Files throw IOexception:" + e.getMessage()); + } + + } + + return null; } - return null; - } - - public String getAllrouteByJson(String routeWay){ - - Object[] apirouteArray= ApiRouteServiceWrapper.getInstance().getAllApiRouteInstances(routeWay).toArray(); - Object[] iuirouteArray= IuiRouteServiceWrapper.getInstance().getAllIuiRouteInstances(routeWay).toArray(); - Object[] customrouteArray= CustomRouteServiceWrapper.getInstance().getAllCustomRouteInstances(routeWay).toArray(); - - Object[] temprouteArray =CommonUtil.concat(apirouteArray, iuirouteArray); - Object[] allrouteArray=CommonUtil.concat(temprouteArray, customrouteArray); - - - String allrouteJson; - try { - allrouteJson = JacksonJsonUtil.beanToJson(allrouteArray); - } catch (Exception e) { - LOGGER.error("exportService beanToJson throw Exception", e); - throw new ExtendedInternalServerErrorException("exportService beanToJson throw Exception:"+ e.getMessage()); + public String getAllrouteByJson(String routeWay) { + + Object[] apirouteArray = ApiRouteServiceWrapper.getInstance().getAllApiRouteInstances(routeWay).toArray(); + Object[] iuirouteArray = IuiRouteServiceWrapper.getInstance().getAllIuiRouteInstances(routeWay).toArray(); + Object[] customrouteArray = + CustomRouteServiceWrapper.getInstance().getAllCustomRouteInstances(routeWay).toArray(); + + Object[] temprouteArray = CommonUtil.concat(apirouteArray, iuirouteArray); + Object[] allrouteArray = CommonUtil.concat(temprouteArray, customrouteArray); + + + String allrouteJson; + try { + allrouteJson = JacksonJsonUtil.beanToJson(allrouteArray); + } catch (Exception e) { + LOGGER.error("exportService beanToJson throw Exception", e); + throw new ExtendedInternalServerErrorException( + "exportService beanToJson throw Exception:" + e.getMessage()); + } + return allrouteJson; } - return allrouteJson; - } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapper.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapper.java index 825a572..3328d70 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapper.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapper.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; @@ -28,190 +26,189 @@ import org.slf4j.LoggerFactory; public class CustomRouteServiceWrapper { - private static final Logger LOGGER = LoggerFactory.getLogger(CustomRouteServiceWrapper.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CustomRouteServiceWrapper.class); - private static CustomRouteServiceWrapper instance = new CustomRouteServiceWrapper(); + private static CustomRouteServiceWrapper instance = new CustomRouteServiceWrapper(); - private CustomRouteServiceWrapper() {} + private CustomRouteServiceWrapper() {} - public static CustomRouteServiceWrapper getInstance() { - return instance; - } + public static CustomRouteServiceWrapper getInstance() { + return instance; + } + + + /** + * @Title: getAllCustomRouteService + * @Description: TODO(get AllCustomRoute Service) + * @param: @return + * @return: CustomRouteInfo[] + */ + public List<CustomRouteInfo> getAllCustomRouteInstances(String routeWay) { + + RouteUtil.checkRouteWay(routeWay); + try { + String customRedisKey = RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, routeWay); + return CustomRouteService.getInstance().getMultiCustomRouteInstances(customRedisKey); - /** - * @Title: getAllCustomRouteService - * @Description: TODO(get AllCustomRoute Service) - * @param: @return - * @return: CustomRouteInfo[] - */ - public List<CustomRouteInfo> getAllCustomRouteInstances(String routeWay) { + } catch (Exception e) { + throw new ExtendedInternalServerErrorException(e.getMessage()); + } - RouteUtil.checkRouteWay(routeWay); - - try { - String customRedisKey = RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, routeWay); - return CustomRouteService.getInstance().getMultiCustomRouteInstances(customRedisKey); - } catch (Exception e) { - throw new ExtendedInternalServerErrorException(e.getMessage()); } - } + /** + * @Title: getCustomRouteInstance + * @Description: TODO(get CustomRouteInstance by serviceName) + * @param: @param serviceName + * @param: @return + * @return: CustomRouteInfo + */ + public CustomRouteInfo getCustomRouteInstance(String serviceName, String host, String publish_port, + String routeWay) { + RouteUtil.checkRouteWay(routeWay); - /** - * @Title: getCustomRouteInstance - * @Description: TODO(get CustomRouteInstance by serviceName) - * @param: @param serviceName - * @param: @return - * @return: CustomRouteInfo - */ - public CustomRouteInfo getCustomRouteInstance(String serviceName, String host, - String publish_port, String routeWay) { + String customRedisPrefixedKey = + RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, serviceName, host, publish_port, routeWay); - RouteUtil.checkRouteWay(routeWay); + CustomRouteInfo customRouteInfo; + try { + customRouteInfo = CustomRouteService.getInstance().getCustomRouteInstance(customRedisPrefixedKey); + } catch (Exception e) { + LOGGER.error("get customRouteInstance throw exception", e); + throw new ExtendedInternalServerErrorException("get customRouteInstance throw exception" + e.getMessage()); + } - String customRedisPrefixedKey = - RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, serviceName, host, publish_port, - routeWay); - CustomRouteInfo customRouteInfo; - try { - customRouteInfo = - CustomRouteService.getInstance().getCustomRouteInstance(customRedisPrefixedKey); - } catch (Exception e) { - LOGGER.error("get customRouteInstance throw exception", e); - throw new ExtendedInternalServerErrorException("get customRouteInstance throw exception"+ e.getMessage()); - } + if (null == customRouteInfo) { + throw new ExtendedNotFoundException("customRoute Info not found"); + } - if (null == customRouteInfo) { - throw new ExtendedNotFoundException("customRoute Info not found"); + return customRouteInfo; } - return customRouteInfo; - } + /** + * @Title updateCustomRouteStatus + * @Description TODO(update one CustomRoute Status) + * @param serviceName + * @param status + * @return + * @return RouteResult + */ + public synchronized CustomRouteInfo updateCustomRouteStatus(String serviceName, String host, String publish_port, + String status, String routeWay) { + RouteUtil.checkRouteWay(routeWay); - /** - * @Title updateCustomRouteStatus - * @Description TODO(update one CustomRoute Status) - * @param serviceName - * @param status - * @return - * @return RouteResult - */ - public synchronized CustomRouteInfo updateCustomRouteStatus(String serviceName, String host, - String publish_port, String status, String routeWay) { + RouteUtil.checkServiceStatus(status); - RouteUtil.checkRouteWay(routeWay); + String customRedisPrefixedKey = + RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, serviceName, host, publish_port, routeWay); - RouteUtil.checkServiceStatus(status); - String customRedisPrefixedKey = - RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, serviceName, host, publish_port, - routeWay); + try { + CustomRouteService.getInstance().updateCustomRouteStatus2Redis(customRedisPrefixedKey, status); + } catch (Exception e) { + LOGGER.error("update CustomRoute status throw exception", e); + throw new ExtendedInternalServerErrorException(e.getMessage()); + } + CustomRouteInfo new_customRouteInfo = getCustomRouteInstance(serviceName, host, publish_port, routeWay); - try { - CustomRouteService.getInstance() - .updateCustomRouteStatus2Redis(customRedisPrefixedKey, status); - } catch (Exception e) { - LOGGER.error("update CustomRoute status throw exception", e); - throw new ExtendedInternalServerErrorException(e.getMessage()); + return new_customRouteInfo; } - CustomRouteInfo new_customRouteInfo = - getCustomRouteInstance(serviceName, host, publish_port, routeWay); + /** + * @Title: saveCustomRouteInstance + * @Description: TODO(save one CustomRouteInstance) + * @param: @param CustomRouteInfo + * @param: @return + * @return: CustomRouteInfo + */ + public synchronized CustomRouteInfo saveCustomRouteInstance4Rest(CustomRouteInfo customRouteInfo, String routeWay) { - return new_customRouteInfo; - } + RouteUtil.checkRouteWay(routeWay); - /** - * @Title: saveCustomRouteInstance - * @Description: TODO(save one CustomRouteInstance) - * @param: @param CustomRouteInfo - * @param: @return - * @return: CustomRouteInfo - */ - public synchronized CustomRouteInfo saveCustomRouteInstance4Rest(CustomRouteInfo customRouteInfo, - String routeWay) { + RouteUtil.checkRouterInfoFormat(customRouteInfo); - RouteUtil.checkRouteWay(routeWay); + try { + saveCustomRouteInstance(customRouteInfo, routeWay); - RouteUtil.checkRouterInfoFormat(customRouteInfo); + } catch (Exception e) { - try { - saveCustomRouteInstance(customRouteInfo, routeWay); + throw new ExtendedInternalServerErrorException("save CustomRouteInfo fail: [serviceName]" + + customRouteInfo.getServiceName() + e.getMessage()); + } - } catch (Exception e) { + return customRouteInfo; - throw new ExtendedInternalServerErrorException("save CustomRouteInfo fail: [serviceName]"+customRouteInfo.getServiceName()+e.getMessage()); } - return customRouteInfo; - } + public synchronized CustomRouteInfo saveCustomRouteInstance(CustomRouteInfo customRouteInfo, String routeWay) + throws Exception { + try { + String customRedisPrefixedKey = + RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, customRouteInfo.getServiceName(), + customRouteInfo.getHost(), customRouteInfo.getPublish_port(), routeWay);; - public synchronized CustomRouteInfo saveCustomRouteInstance(CustomRouteInfo customRouteInfo, - String routeWay) throws Exception { - try { - String customRedisPrefixedKey = - RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, customRouteInfo.getServiceName(), - customRouteInfo.getHost(), customRouteInfo.getPublish_port(), routeWay);; + CustomRouteService.getInstance().saveCustomRouteService2Redis(customRouteInfo, customRedisPrefixedKey); + LOGGER.info("save CustomRouteInfo [serviceName]" + customRouteInfo.getServiceName() + " [host]" + + customRouteInfo.getHost() + " [publish_port]" + customRouteInfo.getPublish_port() + + " [routeWay]" + routeWay + " success"); - - CustomRouteService.getInstance().saveCustomRouteService2Redis(customRouteInfo, - customRedisPrefixedKey); - LOGGER.info("save CustomRouteInfo [serviceName]"+customRouteInfo.getServiceName()+" [host]"+customRouteInfo.getHost() +" [publish_port]"+customRouteInfo.getPublish_port()+" [routeWay]"+routeWay+" success"); + } catch (Exception e) { + LOGGER.error("save CustomRouteInfo [serviceName]" + customRouteInfo.getServiceName() + " [host]" + + customRouteInfo.getHost() + " [publish_port]" + customRouteInfo.getPublish_port() + + " [routeWay]" + routeWay + " throw exception", e); - } catch (Exception e) { - LOGGER.error("save CustomRouteInfo [serviceName]"+customRouteInfo.getServiceName()+" [host]"+customRouteInfo.getHost() +" [publish_port]"+customRouteInfo.getPublish_port()+" [routeWay]"+routeWay+" throw exception", e); + throw e; + } + + return customRouteInfo; - throw e; - } - - return customRouteInfo; - - } - - - /** - * @Title: deleteCustomRoute - * @Description: TODO(delete one CustomRoute) - * @param: @param type - * @param: @param serviceName - * @param: @param delKey - * @param: @return - * @return: void - */ - public synchronized void deleteCustomRoute(String serviceName, String host, String publish_port, - String routeWay) { - - RouteUtil.checkRouteWay(routeWay); - - String customRedisPrefixedKey = - RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, serviceName, host, publish_port, - routeWay); - - try { - CustomRouteService.getInstance().deleteCustomRouteService2Redis(customRedisPrefixedKey); - LOGGER.info("delete CustomRouteInfo [serviceName]"+serviceName+" [host]"+host +" [publish_port]"+publish_port+" [routeWay]"+routeWay+" success"); - - } catch (ExtendedNotFoundException e) { - throw e; - } catch (Exception e) { - LOGGER.error("delete CustomRouteInfo [serviceName]"+serviceName+" [host]"+host +" [publish_port]"+publish_port+" [routeWay]"+routeWay+" throw exception", e); - throw new ExtendedInternalServerErrorException("delete CustomRouteInfo [serviceName]"+serviceName+e.getMessage()); } + /** + * @Title: deleteCustomRoute + * @Description: TODO(delete one CustomRoute) + * @param: @param type + * @param: @param serviceName + * @param: @param delKey + * @param: @return + * @return: void + */ + public synchronized void deleteCustomRoute(String serviceName, String host, String publish_port, String routeWay) { - } + RouteUtil.checkRouteWay(routeWay); + + String customRedisPrefixedKey = + RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, serviceName, host, publish_port, routeWay); + + try { + CustomRouteService.getInstance().deleteCustomRouteService2Redis(customRedisPrefixedKey); + LOGGER.info("delete CustomRouteInfo [serviceName]" + serviceName + " [host]" + host + " [publish_port]" + + publish_port + " [routeWay]" + routeWay + " success"); + + } catch (ExtendedNotFoundException e) { + throw e; + } catch (Exception e) { + LOGGER.error("delete CustomRouteInfo [serviceName]" + serviceName + " [host]" + host + " [publish_port]" + + publish_port + " [routeWay]" + routeWay + " throw exception", e); + throw new ExtendedInternalServerErrorException( + "delete CustomRouteInfo [serviceName]" + serviceName + e.getMessage()); + } + + + + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapper.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapper.java index 6e44a69..f96d045 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapper.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapper.java @@ -1,34 +1,25 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; -import io.dropwizard.jetty.HttpConnectorFactory; -import io.dropwizard.server.SimpleServerFactory; - -import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStreamWriter; import java.net.URL; import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.onap.msb.apiroute.ApiRouteApp; import org.onap.msb.apiroute.ApiRouteAppConfig; import org.onap.msb.apiroute.SyncDataManager; import org.onap.msb.apiroute.api.ApiRouteInfo; @@ -50,381 +41,378 @@ import org.onap.msb.apiroute.wrapper.util.RouteUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import redis.clients.jedis.Jedis; - import com.fasterxml.jackson.core.type.TypeReference; +import io.dropwizard.jetty.HttpConnectorFactory; +import io.dropwizard.server.SimpleServerFactory; +import redis.clients.jedis.Jedis; + public class InitRouteServiceWrapper { - private static final Logger LOGGER = LoggerFactory.getLogger(InitRouteServiceWrapper.class); + private static final Logger LOGGER = LoggerFactory.getLogger(InitRouteServiceWrapper.class); - private static InitRouteServiceWrapper instance = new InitRouteServiceWrapper(); + private static InitRouteServiceWrapper instance = new InitRouteServiceWrapper(); - private InitRouteServiceWrapper() {} + private InitRouteServiceWrapper() {} - public static InitRouteServiceWrapper getInstance() { - return instance; - } + public static InitRouteServiceWrapper getInstance() { + return instance; + } - /** - * The listener registration service changes - */ - public void registerServiceChangeListener() { + /** + * The listener registration service changes + */ + public void registerServiceChangeListener() { - RouteNotify.getInstance().addServiceChangeListener(new MicroServiceChangeListener()); + RouteNotify.getInstance().addServiceChangeListener(new MicroServiceChangeListener()); - } - - public void initFilterConfig(){ - //route init - ConfigUtil.getInstance().initRouteWay(); - ConfigUtil.getInstance().initApiGatewayPort(); - ConfigUtil.getInstance().initRouteNameSpaceMatches(); - ConfigUtil.getInstance().initRouteLabelsMatches(); - ConfigUtil.getInstance().initNodeMetaQueryParam(); - - } - - public void initDataSynchro(){ - - registerServiceChangeListener(); + } - boolean ifRedisConnect=startCheckRedisConnect(); + public void initFilterConfig() { + // route init + ConfigUtil.getInstance().initRouteWay(); + ConfigUtil.getInstance().initApiGatewayPort(); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + ConfigUtil.getInstance().initRouteLabelsMatches(); + ConfigUtil.getInstance().initNodeMetaQueryParam(); - if(ifRedisConnect){ - initRouteInfoFromJson(); - runConsulClientApp(); } - } - - public void initHealthCheck() - { - LOGGER.info("start check consul link thread"); - Thread tConsul= new Thread(new ConsulLinkHealthCheck(),"_healthcheck_consul_"); - tConsul.setDaemon(true); - tConsul.start(); - - LOGGER.info("start check redis thread"); - Thread tRedies= new Thread(new RedisHealthCheck(),"_healthcheck_redis_"); - tRedies.setDaemon(true); - tRedies.start(); - } + public void initDataSynchro() { + + registerServiceChangeListener(); + + boolean ifRedisConnect = startCheckRedisConnect(); + if (ifRedisConnect) { + initRouteInfoFromJson(); + runConsulClientApp(); + } + } + public void initHealthCheck() { + LOGGER.info("start check consul link thread"); + Thread tConsul = new Thread(new ConsulLinkHealthCheck(), "_healthcheck_consul_"); + tConsul.setDaemon(true); + tConsul.start(); + + LOGGER.info("start check redis thread"); + Thread tRedies = new Thread(new RedisHealthCheck(), "_healthcheck_redis_"); + tRedies.setDaemon(true); + tRedies.start(); + } - public boolean startCheckRedisConnect() { + + + public boolean startCheckRedisConnect() { int n = 0; while (true) { - if (!checkRedisConnect()) { - n++; - LOGGER.warn(n + "/10 : Initial Route Configuration——redis connection fail..."); - - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - LOGGER.error("Thread.sleep throw except:" + e.getMessage()); - } + if (!checkRedisConnect()) { + n++; + LOGGER.warn(n + "/10 : Initial Route Configuration——redis connection fail..."); + + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + LOGGER.error("Thread.sleep throw except:" + e.getMessage()); + } - if (n >= 10) { - LOGGER.error("Initial Route Configuration——redis connection fail,timeout exit..."); - return false; + if (n >= 10) { + LOGGER.error("Initial Route Configuration——redis connection fail,timeout exit..."); + return false; + } + } else { + LOGGER.warn(" Initial Route Configuration——redis connection success..."); + return true; } - } else { - LOGGER.warn(" Initial Route Configuration——redis connection success..."); - return true; - } } - - } - - - // Open the consul to monitor subscription service - public void runConsulClientApp() { - - String consulIP; - int consulPort; - String consulConfSource="Default"; - - - DiscoverInfo discoverInfo = ConfigUtil.getInstance().getDiscoverInfo(); - - if (discoverInfo.isEnabled()) { - LOGGER.warn("starting to initial consul Configuration"); - String[] routeWay = ConfigUtil.getInstance().getRouteWay(); - try { - String sys_consulIp=ConfigUtil.getInstance().getConsul_ip(); - if (StringUtils.isNotBlank(sys_consulIp)) { - consulIP = sys_consulIp.trim(); - consulPort = RouteUtil.consulDeafultPort; - consulConfSource="env:CONSUL_IP"; - } else { - consulIP = discoverInfo.getIp(); - consulPort = discoverInfo.getPort(); - consulConfSource="init discoverInfo"; - } - LOGGER.warn("init consul sync Address from [ "+consulConfSource+" ]:" + consulIP + ":" + consulPort); + } - // Registration service discovery routing - // api - ApiRouteInfo discoverApiService = new ApiRouteInfo(); - discoverApiService.setServiceName("msdiscover"); - discoverApiService.setUrl("/api/microservices/v1"); - discoverApiService.setVersion("v1"); - discoverApiService.setMetricsUrl("/admin/metrics"); - discoverApiService.setApiJson("/api/microservices/v1/swagger.json"); - discoverApiService.setHost("msb"); - RouteServer[] servers = new RouteServer[1]; - servers[0] = new RouteServer(discoverInfo.getIp(), String.valueOf(discoverInfo.getPort())); - discoverApiService.setServers(servers); + // Open the consul to monitor subscription service + public void runConsulClientApp() { + String consulIP; + int consulPort; + String consulConfSource = "Default"; - for (int i = 0; i < routeWay.length; i++) { - ApiRouteServiceWrapper.getInstance().saveApiRouteInstance4Rest(discoverApiService, - routeWay[i]); - } + DiscoverInfo discoverInfo = ConfigUtil.getInstance().getDiscoverInfo(); + if (discoverInfo.isEnabled()) { + LOGGER.warn("starting to initial consul Configuration"); + String[] routeWay = ConfigUtil.getInstance().getRouteWay(); + try { + String sys_consulIp = ConfigUtil.getInstance().getConsul_ip(); + if (StringUtils.isNotBlank(sys_consulIp)) { + consulIP = sys_consulIp.trim(); + consulPort = RouteUtil.consulDeafultPort; + consulConfSource = "env:CONSUL_IP"; + } else { + consulIP = discoverInfo.getIp(); + consulPort = discoverInfo.getPort(); + consulConfSource = "init discoverInfo"; + } - // iui - IuiRouteInfo discoverIUIService = new IuiRouteInfo(); - discoverIUIService.setServiceName("msdiscover"); - discoverIUIService.setUrl("/iui/microservices"); - discoverIUIService.setHost("msb"); - discoverIUIService.setServers(servers); + LOGGER.warn("init consul sync Address from [ " + consulConfSource + " ]:" + consulIP + ":" + + consulPort); - for (int i = 0; i < routeWay.length; i++) { - IuiRouteServiceWrapper.getInstance() - .saveIuiRouteInstance(discoverIUIService, routeWay[i]); - } + // Registration service discovery routing + // api + ApiRouteInfo discoverApiService = new ApiRouteInfo(); + discoverApiService.setServiceName("msdiscover"); + discoverApiService.setUrl("/api/microservices/v1"); + discoverApiService.setVersion("v1"); + discoverApiService.setMetricsUrl("/admin/metrics"); + discoverApiService.setApiJson("/api/microservices/v1/swagger.json"); + discoverApiService.setHost("msb"); + RouteServer[] servers = new RouteServer[1]; + servers[0] = new RouteServer(discoverInfo.getIp(), String.valueOf(discoverInfo.getPort())); + discoverApiService.setServers(servers); - /* - * ConsulClientApp consulClientApp = new ConsulClientApp(consulIP, consulPort); - * consulClientApp.startServiceListen(); - */ - // SyncDataManager syncDataManager = new SyncDataManager(); - // Monitor serviceList change - SyncDataManager.initSyncTask(consulIP, consulPort); + for (int i = 0; i < routeWay.length; i++) { + ApiRouteServiceWrapper.getInstance().saveApiRouteInstance4Rest(discoverApiService, routeWay[i]); + } - LOGGER.warn("start monitor consul service--" + consulIP + ":" + consulPort); - } catch (Exception e) { - LOGGER.error("start monitor consul service fail:" + e.getMessage()); - } - } - + // iui + IuiRouteInfo discoverIUIService = new IuiRouteInfo(); + discoverIUIService.setServiceName("msdiscover"); + discoverIUIService.setUrl("/iui/microservices"); + discoverIUIService.setHost("msb"); + discoverIUIService.setServers(servers); - } + for (int i = 0; i < routeWay.length; i++) { + IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(discoverIUIService, routeWay[i]); + } + /* + * ConsulClientApp consulClientApp = new ConsulClientApp(consulIP, consulPort); + * consulClientApp.startServiceListen(); + */ - /** - * @Title: initRouteInfoFromJson - * @Description: TODO(According to the JSON file configuration initialization route data) - * @return: void - */ - public void initRouteInfoFromJson() { - LOGGER.info("starting to initial Route Configuration"); - URL apiDocsPath = InitRouteServiceWrapper.class.getResource("/ext/initServices"); - if (apiDocsPath != null) { - String path = apiDocsPath.getPath(); + // SyncDataManager syncDataManager = new SyncDataManager(); + // Monitor serviceList change + SyncDataManager.initSyncTask(consulIP, consulPort); - LOGGER.info("read JsonFilefolder:" + path); - try { - File[] files = FileUtil.readFileFolder(path); - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if (file.isFile() && file.getName().endsWith(".json")) { - LOGGER.info("read JsonFile:" + file.getPath()); - String fileContent = FileUtil.readFile(file.getPath()); - saveInitService2redis(fileContent); - } else { - LOGGER.warn(file.getName() + " is not a right file"); - } + LOGGER.warn("start monitor consul service--" + consulIP + ":" + consulPort); + } catch (Exception e) { + LOGGER.error("start monitor consul service fail:" + e.getMessage()); + } } - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - LOGGER.error("read initServices Files throw FileNotFoundException", e); - } catch (IOException e) { - // TODO Auto-generated catch block - LOGGER.error("read initServices Files throw IOexception", e); - } + } + + + + /** + * @Title: initRouteInfoFromJson + * @Description: TODO(According to the JSON file configuration initialization route data) + * @return: void + */ + public void initRouteInfoFromJson() { + LOGGER.info("starting to initial Route Configuration"); + URL apiDocsPath = InitRouteServiceWrapper.class.getResource("/ext/initServices"); + if (apiDocsPath != null) { + String path = apiDocsPath.getPath(); + + LOGGER.info("read JsonFilefolder:" + path); + + try { + File[] files = FileUtil.readFileFolder(path); + for (int i = 0; i < files.length; i++) { + File file = files[i]; + if (file.isFile() && file.getName().endsWith(".json")) { + LOGGER.info("read JsonFile:" + file.getPath()); + String fileContent = FileUtil.readFile(file.getPath()); + saveInitService2redis(fileContent); + } else { + LOGGER.warn(file.getName() + " is not a right file"); + } + } + + + + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + LOGGER.error("read initServices Files throw FileNotFoundException", e); + } catch (IOException e) { + // TODO Auto-generated catch block + LOGGER.error("read initServices Files throw IOexception", e); + } + + } + + } - } + private void saveInitService2redis(String fileContent) { + String[] routeWay = ConfigUtil.getInstance().getRouteWay(); + String iuiRootPath = ConfigUtil.getInstance().getIUI_ROOT_PATH(); + try { + List<ApiRouteInfo> routeList = + JacksonJsonUtil.jsonToListBean(fileContent, new TypeReference<List<ApiRouteInfo>>() {}); + for (ApiRouteInfo route : routeList) { + String url = route.getUrl(); - private void saveInitService2redis(String fileContent) { + if (RegExpTestUtil.urlRegExpTest(route.getServiceName())) { - String[] routeWay = ConfigUtil.getInstance().getRouteWay(); - String iuiRootPath = ConfigUtil.getInstance().getIUI_ROOT_PATH(); + for (int i = 0; i < routeWay.length; i++) { + try { - try { - List<ApiRouteInfo> routeList = - JacksonJsonUtil.jsonToListBean(fileContent, new TypeReference<List<ApiRouteInfo>>() {}); - for (ApiRouteInfo route : routeList) { - String url = route.getUrl(); + CustomRouteServiceWrapper.getInstance().getCustomRouteInstance(route.getServiceName(), + route.getHost(), "", routeWay[i]); - if (RegExpTestUtil.urlRegExpTest(route.getServiceName())) { + } catch (ExtendedNotFoundException e) { - for (int i = 0; i < routeWay.length; i++) { - try { + LOGGER.info("initCustomRoute: ServiceName--" + route.getServiceName()); - CustomRouteServiceWrapper.getInstance().getCustomRouteInstance( - route.getServiceName(), route.getHost(), "", routeWay[i]); + CustomRouteInfo customRouteInfo = new CustomRouteInfo(); + customRouteInfo.setControl(route.getControl()); + customRouteInfo.setServers(route.getServers()); + customRouteInfo.setServiceName(route.getServiceName()); + customRouteInfo.setStatus(route.getStatus()); + customRouteInfo.setUrl(route.getUrl()); + customRouteInfo.setHost(route.getHost()); - } catch (ExtendedNotFoundException e) { - LOGGER.info("initCustomRoute: ServiceName--" + route.getServiceName()); - CustomRouteInfo customRouteInfo = new CustomRouteInfo(); - customRouteInfo.setControl(route.getControl()); - customRouteInfo.setServers(route.getServers()); - customRouteInfo.setServiceName(route.getServiceName()); - customRouteInfo.setStatus(route.getStatus()); - customRouteInfo.setUrl(route.getUrl()); - customRouteInfo.setHost(route.getHost()); + CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfo, + routeWay[i]); + } + } + } else { + if (RegExpTestUtil.apiRouteUrlRegExpTest(url) || url.startsWith("/api/microservices/") + || url.startsWith("/admin/microservices/")) { - CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfo, - routeWay[i]); + for (int i = 0; i < routeWay.length; i++) { + try { - } - } - } else { + ApiRouteServiceWrapper.getInstance().getApiRouteInstance(route.getServiceName(), + route.getVersion(), route.getHost(), route.getPublish_port(), + routeWay[i]); - if (RegExpTestUtil.apiRouteUrlRegExpTest(url) || url.startsWith("/api/microservices/") || url.startsWith("/admin/microservices/")) { + } catch (ExtendedNotFoundException e) { + LOGGER.info("initapiRoute: ServiceName--" + route.getServiceName()); - for (int i = 0; i < routeWay.length; i++) { - try { + if (url.startsWith("/api/microservices")) { + if (StringUtils.isNotBlank(System.getenv("dwApp_server_connector_port"))) { + replaceApigatewayPort(route.getServers(), + System.getenv("dwApp_server_connector_port")); + } + } - ApiRouteServiceWrapper.getInstance().getApiRouteInstance(route.getServiceName(), - route.getVersion(), route.getHost(), route.getPublish_port(), routeWay[i]); + if (url.startsWith("/admin/microservices")) { + replaceApigatewayPort(route.getServers(), ConfigUtil.getInstance().getServerPort()); + } - } catch (ExtendedNotFoundException e) { - LOGGER.info("initapiRoute: ServiceName--" + route.getServiceName()); + ApiRouteServiceWrapper.getInstance().saveApiRouteInstance4Rest(route, routeWay[i]); - if (url.startsWith("/api/microservices")) { - if (StringUtils.isNotBlank(System.getenv("dwApp_server_connector_port"))) { - replaceApigatewayPort(route.getServers(), - System.getenv("dwApp_server_connector_port")); - } - } - - if (url.startsWith("/admin/microservices")) { - replaceApigatewayPort(route.getServers(),ConfigUtil.getInstance().getServerPort()); - } + } + } - ApiRouteServiceWrapper.getInstance().saveApiRouteInstance4Rest(route, routeWay[i]); - } - } + } else if (RegExpTestUtil.iuiRouteUrlRegExpTest(url) || url.equals("/iui/microservices")) { + for (int i = 0; i < routeWay.length; i++) { + try { - } else if (RegExpTestUtil.iuiRouteUrlRegExpTest(url) || url.equals("/iui/microservices")) { + IuiRouteServiceWrapper.getInstance().getIuiRouteInstance(route.getServiceName(), + route.getHost(), "", routeWay[i]); - for (int i = 0; i < routeWay.length; i++) { - try { + } catch (ExtendedNotFoundException e) { - IuiRouteServiceWrapper.getInstance().getIuiRouteInstance(route.getServiceName(), - route.getHost(), "", routeWay[i]); + LOGGER.info(" initiuiRoute: ServiceName--" + route.getServiceName()); + IuiRouteInfo iuiRouteInfo = new IuiRouteInfo(); + iuiRouteInfo.setControl(route.getControl()); + iuiRouteInfo.setServers(route.getServers()); + iuiRouteInfo.setServiceName(route.getServiceName()); + iuiRouteInfo.setStatus(route.getStatus()); + iuiRouteInfo.setHost(route.getHost()); - } catch (ExtendedNotFoundException e) { - LOGGER.info(" initiuiRoute: ServiceName--" + route.getServiceName()); - IuiRouteInfo iuiRouteInfo = new IuiRouteInfo(); - iuiRouteInfo.setControl(route.getControl()); - iuiRouteInfo.setServers(route.getServers()); - iuiRouteInfo.setServiceName(route.getServiceName()); - iuiRouteInfo.setStatus(route.getStatus()); - iuiRouteInfo.setHost(route.getHost()); + if (url.equals("/iui/microservices")) { + iuiRouteInfo.setUrl("/" + iuiRootPath + "/microservices"); + if (StringUtils.isNotBlank(System.getenv("dwApp_server_connector_port"))) { + replaceApigatewayPort(iuiRouteInfo.getServers(), + System.getenv("dwApp_server_connector_port")); + } + } else { + iuiRouteInfo.setUrl(route.getUrl()); + } + IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(iuiRouteInfo, routeWay[i]); - if (url.equals("/iui/microservices")) { - iuiRouteInfo.setUrl("/" + iuiRootPath + "/microservices"); - if (StringUtils.isNotBlank(System.getenv("dwApp_server_connector_port"))) { - replaceApigatewayPort(iuiRouteInfo.getServers(), - System.getenv("dwApp_server_connector_port")); - } - } else { - iuiRouteInfo.setUrl(route.getUrl()); + + } + } + + } else { + LOGGER.error("init Service throw exception——serviceName: " + route.getServiceName() + ",url:" + + url); + } } - IuiRouteServiceWrapper.getInstance() - .saveIuiRouteInstance(iuiRouteInfo, routeWay[i]); - } } - } else { - LOGGER.error("init Service throw exception——serviceName: " + route.getServiceName() - + ",url:" + url); - } + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.error("read initServices Files throw exception", e); } + } + private void replaceApigatewayPort(RouteServer[] servers, String apigatewayPort) { + for (int i = 0; i < servers.length; i++) { + servers[i].setPort(apigatewayPort); + } + } - } + public void initMetricsConfig(ApiRouteAppConfig configuration) { - } catch (Exception e) { - // TODO Auto-generated catch block - LOGGER.error("read initServices Files throw exception", e); + SimpleServerFactory simpleServerFactory = (SimpleServerFactory) configuration.getServerFactory(); + HttpConnectorFactory httpConnectorFactory = (HttpConnectorFactory) simpleServerFactory.getConnector(); + String metricsUrl = "http://127.0.0.1:" + httpConnectorFactory.getPort() + + simpleServerFactory.getAdminContextPath() + "/metrics"; + ConfigUtil.getInstance().setMetricsUrl(metricsUrl); } - } - private void replaceApigatewayPort(RouteServer[] servers, String apigatewayPort) { - for (int i = 0; i < servers.length; i++) { - servers[i].setPort(apigatewayPort); + private boolean checkRedisConnect() { + Jedis jedis = null; + try { + jedis = JedisUtil.borrowJedisInstance(); + return true; + } catch (Exception e) { + LOGGER.error("checkRedisConnect call redis throw exception", e); + } finally { + JedisUtil.returnJedisInstance(jedis); + } + + return false; } - } - - public void initMetricsConfig(ApiRouteAppConfig configuration) { - - SimpleServerFactory simpleServerFactory = - (SimpleServerFactory) configuration.getServerFactory(); - HttpConnectorFactory httpConnectorFactory = - (HttpConnectorFactory) simpleServerFactory.getConnector(); - String metricsUrl = - "http://127.0.0.1:" + httpConnectorFactory.getPort() - + simpleServerFactory.getAdminContextPath() + "/metrics"; - ConfigUtil.getInstance().setMetricsUrl(metricsUrl); - } - - - private boolean checkRedisConnect() { - Jedis jedis = null; - try { - jedis = JedisUtil.borrowJedisInstance(); - return true; - } catch (Exception e) { - LOGGER.error("checkRedisConnect call redis throw exception", e); - }finally { - JedisUtil.returnJedisInstance(jedis); - } - - return false; - } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapper.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapper.java index 2a86b58..2030beb 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapper.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapper.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; @@ -28,193 +26,186 @@ import org.slf4j.LoggerFactory; public class IuiRouteServiceWrapper { - private static final Logger LOGGER = LoggerFactory.getLogger(IuiRouteServiceWrapper.class); + private static final Logger LOGGER = LoggerFactory.getLogger(IuiRouteServiceWrapper.class); - private static IuiRouteServiceWrapper instance = new IuiRouteServiceWrapper(); + private static IuiRouteServiceWrapper instance = new IuiRouteServiceWrapper(); - private IuiRouteServiceWrapper() {} + private IuiRouteServiceWrapper() {} - public static IuiRouteServiceWrapper getInstance() { - return instance; - } + public static IuiRouteServiceWrapper getInstance() { + return instance; + } - /** - * @Title: getAllIuiRouteService - * @Description: TODO(get All IuiRouteServices) - * @param: @return - * @return: IuiRouteInfo[] - */ - public List<IuiRouteInfo> getAllIuiRouteInstances(String routeWay) { + /** + * @Title: getAllIuiRouteService + * @Description: TODO(get All IuiRouteServices) + * @param: @return + * @return: IuiRouteInfo[] + */ + public List<IuiRouteInfo> getAllIuiRouteInstances(String routeWay) { - RouteUtil.checkRouteWay(routeWay); - - try { - String iuiRedisKey = RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, routeWay); + RouteUtil.checkRouteWay(routeWay); - return IuiRouteService.getInstance().getMultiIuiRouteInstances(iuiRedisKey); + try { + String iuiRedisKey = RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, routeWay); - } catch (Exception e) { - throw new ExtendedInternalServerErrorException(e.getMessage()); - } + return IuiRouteService.getInstance().getMultiIuiRouteInstances(iuiRedisKey); + } catch (Exception e) { + throw new ExtendedInternalServerErrorException(e.getMessage()); + } - } + } - /** - * @Title: getIuiRouteInstance - * @Description: TODO(get one IuiRouteInstance by serviceName) - * @param: @param serviceName - * @param: @return - * @return: IuiRouteInfo - */ - public IuiRouteInfo getIuiRouteInstance(String serviceName, String host, String publish_port, - String routeWay) { - RouteUtil.checkRouteWay(routeWay); + /** + * @Title: getIuiRouteInstance + * @Description: TODO(get one IuiRouteInstance by serviceName) + * @param: @param serviceName + * @param: @return + * @return: IuiRouteInfo + */ + public IuiRouteInfo getIuiRouteInstance(String serviceName, String host, String publish_port, String routeWay) { - String iuiRedisPrefixedKey = - RouteUtil - .getRedisPrefixedKey(RouteUtil.IUIROUTE, serviceName, host, publish_port, routeWay); + RouteUtil.checkRouteWay(routeWay); - IuiRouteInfo iuiRouteInfo; - try { - iuiRouteInfo = IuiRouteService.getInstance().getIuiRouteInstance(iuiRedisPrefixedKey); - } catch (Exception e) { - LOGGER.error("get IuiRouteInstance throw exception", e); - throw new ExtendedInternalServerErrorException("get IuiRouteInstance throw exception" - + e.getMessage()); - } + String iuiRedisPrefixedKey = + RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE, serviceName, host, publish_port, routeWay); + IuiRouteInfo iuiRouteInfo; + try { + iuiRouteInfo = IuiRouteService.getInstance().getIuiRouteInstance(iuiRedisPrefixedKey); + } catch (Exception e) { + LOGGER.error("get IuiRouteInstance throw exception", e); + throw new ExtendedInternalServerErrorException("get IuiRouteInstance throw exception" + e.getMessage()); + } - if (null == iuiRouteInfo) { - throw new ExtendedNotFoundException("iui RouteInfo not found"); + + if (null == iuiRouteInfo) { + throw new ExtendedNotFoundException("iui RouteInfo not found"); + } + + return iuiRouteInfo; } - return iuiRouteInfo; - } + /** + * @Title updateIuiRouteStatus + * @Description TODO(update one IuiRoute Status) + * @param serviceName + * @param status + * @return + * @return RouteResult + */ + public synchronized IuiRouteInfo updateIuiRouteStatus(String serviceName, String host, String publish_port, + String status, String routeWay) { - /** - * @Title updateIuiRouteStatus - * @Description TODO(update one IuiRoute Status) - * @param serviceName - * @param status - * @return - * @return RouteResult - */ - public synchronized IuiRouteInfo updateIuiRouteStatus(String serviceName, String host, - String publish_port, String status, String routeWay) { + RouteUtil.checkRouteWay(routeWay); - RouteUtil.checkRouteWay(routeWay); + RouteUtil.checkServiceStatus(status); - RouteUtil.checkServiceStatus(status); + try { + String iuiRedisPrefixedKey = RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE, serviceName, host, + publish_port, routeWay); - try { - String iuiRedisPrefixedKey = - RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE, serviceName, host, publish_port, - routeWay); + IuiRouteService.getInstance().updateIuiRouteStatus2Redis(iuiRedisPrefixedKey, status); - IuiRouteService.getInstance().updateIuiRouteStatus2Redis(iuiRedisPrefixedKey, status); + } catch (Exception e) { + LOGGER.error("update IuiRoute status throw exception", e); + throw new ExtendedInternalServerErrorException(e.getMessage()); + } - } catch (Exception e) { - LOGGER.error("update IuiRoute status throw exception", e); - throw new ExtendedInternalServerErrorException(e.getMessage()); + IuiRouteInfo new_iuiRouteInfo = getIuiRouteInstance(serviceName, host, publish_port, routeWay); + + return new_iuiRouteInfo; } - IuiRouteInfo new_iuiRouteInfo = getIuiRouteInstance(serviceName, host, publish_port, routeWay); + /** + * @Title: saveIuiRouteInstance + * @Description: TODO(save one IuiRouteInstance) + * @param: @param IuiRouteInfo + * @param: @return + * @return: IuiRouteInfo + */ + public synchronized IuiRouteInfo saveIuiRouteInstance4Rest(IuiRouteInfo iuiRouteInfo, String routeWay) { + + RouteUtil.checkRouteWay(routeWay); - return new_iuiRouteInfo; - } + RouteUtil.checkRouterInfoFormat(iuiRouteInfo); - /** - * @Title: saveIuiRouteInstance - * @Description: TODO(save one IuiRouteInstance) - * @param: @param IuiRouteInfo - * @param: @return - * @return: IuiRouteInfo - */ - public synchronized IuiRouteInfo saveIuiRouteInstance4Rest(IuiRouteInfo iuiRouteInfo, - String routeWay) { - RouteUtil.checkRouteWay(routeWay); + try { + saveIuiRouteInstance(iuiRouteInfo, routeWay); + } catch (Exception e) { + throw new ExtendedInternalServerErrorException( + "save iuiRouteInfo fail: [serviceName]" + iuiRouteInfo.getServiceName() + e.getMessage()); + } + + return iuiRouteInfo; + } - RouteUtil.checkRouterInfoFormat(iuiRouteInfo); + public synchronized void saveIuiRouteInstance(IuiRouteInfo iuiRouteInfo, String routeWay) throws Exception { + try { + String iuiRedisPrefixedKey = + RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE, iuiRouteInfo.getServiceName(), + iuiRouteInfo.getHost(), iuiRouteInfo.getPublish_port(), routeWay); - try { - saveIuiRouteInstance(iuiRouteInfo, routeWay); - } catch (Exception e) { - throw new ExtendedInternalServerErrorException("save iuiRouteInfo fail: [serviceName]" - + iuiRouteInfo.getServiceName() + e.getMessage()); + IuiRouteService.getInstance().saveIuiRouteService2Redis(iuiRouteInfo, iuiRedisPrefixedKey); + LOGGER.info("save iuiRouteInfo [serviceName]" + iuiRouteInfo.getServiceName() + " [host]" + + iuiRouteInfo.getHost() + " [publish_port]" + iuiRouteInfo.getPublish_port() + + " [routeWay]" + routeWay + " success"); + + } catch (Exception e) { + LOGGER.error("save iuiRouteInfo [serviceName]" + iuiRouteInfo.getServiceName() + " [host]" + + iuiRouteInfo.getHost() + " [publish_port]" + iuiRouteInfo.getPublish_port() + + " [routeWay]" + routeWay + " throw exception", e); + throw e; + } } - return iuiRouteInfo; - } - public synchronized void saveIuiRouteInstance(IuiRouteInfo iuiRouteInfo, String routeWay) - throws Exception { - try { - String iuiRedisPrefixedKey = - RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE, iuiRouteInfo.getServiceName(), - iuiRouteInfo.getHost(), iuiRouteInfo.getPublish_port(), routeWay); + /** + * @Title: deleteIuiRoute + * @Description: TODO(delete one IuiRoute) + * @param: @param type + * @param: @param serviceName + * @param: @param delKey + * @param: @return + * @return: void + */ + public synchronized void deleteIuiRoute(String serviceName, String host, String publish_port, String routeWay) { - IuiRouteService.getInstance().saveIuiRouteService2Redis(iuiRouteInfo, iuiRedisPrefixedKey); - LOGGER.info("save iuiRouteInfo [serviceName]" + iuiRouteInfo.getServiceName() + " [host]" - + iuiRouteInfo.getHost() + " [publish_port]" + iuiRouteInfo.getPublish_port() - + " [routeWay]" + routeWay + " success"); + RouteUtil.checkRouteWay(routeWay); - } catch (Exception e) { - LOGGER.error("save iuiRouteInfo [serviceName]" + iuiRouteInfo.getServiceName() + " [host]" - + iuiRouteInfo.getHost() + " [publish_port]" + iuiRouteInfo.getPublish_port() - + " [routeWay]" + routeWay + " throw exception", e); - throw e; - } - } - - - - /** - * @Title: deleteIuiRoute - * @Description: TODO(delete one IuiRoute) - * @param: @param type - * @param: @param serviceName - * @param: @param delKey - * @param: @return - * @return: void - */ - public synchronized void deleteIuiRoute(String serviceName, String host, String publish_port, - String routeWay) { - - RouteUtil.checkRouteWay(routeWay); - - String iuiRedisPrefixedKey = - RouteUtil - .getRedisPrefixedKey(RouteUtil.IUIROUTE, serviceName, host, publish_port, routeWay); - - try { - IuiRouteService.getInstance().deleteIuiRouteService2Redis(iuiRedisPrefixedKey); - LOGGER.info("delete iuiRouteInfo [serviceName]" + serviceName + " [host]" + host - + " [publish_port]" + publish_port + " [routeWay]" + routeWay + " success"); - - } catch (ExtendedNotFoundException e) { - throw e; - } catch (Exception e) { - LOGGER.error("delete iuiRouteInfo [serviceName]" + serviceName + " [host]" + host - + " [publish_port]" + publish_port + " [routeWay]" + routeWay + " throw exception", e); - throw new ExtendedInternalServerErrorException("delete iuiRouteInfo [serviceName]" + serviceName +e.getMessage()); - } + String iuiRedisPrefixedKey = + RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE, serviceName, host, publish_port, routeWay); + + try { + IuiRouteService.getInstance().deleteIuiRouteService2Redis(iuiRedisPrefixedKey); + LOGGER.info("delete iuiRouteInfo [serviceName]" + serviceName + " [host]" + host + " [publish_port]" + + publish_port + " [routeWay]" + routeWay + " success"); + } catch (ExtendedNotFoundException e) { + throw e; + } catch (Exception e) { + LOGGER.error("delete iuiRouteInfo [serviceName]" + serviceName + " [host]" + host + " [publish_port]" + + publish_port + " [routeWay]" + routeWay + " throw exception", e); + throw new ExtendedInternalServerErrorException( + "delete iuiRouteInfo [serviceName]" + serviceName + e.getMessage()); + } - } + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapper.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapper.java index 588a792..fb20ba1 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapper.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapper.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; @@ -37,360 +35,363 @@ import org.slf4j.LoggerFactory; public class MicroServiceWrapper { - private static final Logger LOGGER = LoggerFactory.getLogger(MicroServiceWrapper.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MicroServiceWrapper.class); - private static MicroServiceWrapper instance = new MicroServiceWrapper(); + private static MicroServiceWrapper instance = new MicroServiceWrapper(); - private MicroServiceWrapper() {} + private MicroServiceWrapper() {} - public static MicroServiceWrapper getInstance() { - return instance; - } - + public static MicroServiceWrapper getInstance() { + return instance; + } - /** - * @Title: getAllMicroServiceInstances - * @Description: getAllMicroServiceInstances - * @param: @return - * @return: Response - * @throws Exception - */ - public List<MicroServiceFullInfo> getAllMicroServiceInstances() { + /** + * @Title: getAllMicroServiceInstances + * @Description: getAllMicroServiceInstances + * @param: @return + * @return: Response + * @throws Exception + */ + public List<MicroServiceFullInfo> getAllMicroServiceInstances() { - try { - return MicroServiceFullService.getInstance().getAllMicroServiceInstances(); + try { + return MicroServiceFullService.getInstance().getAllMicroServiceInstances(); - } catch (Exception e) { - throw new ExtendedInternalServerErrorException(e.getMessage()); - } + } catch (Exception e) { + throw new ExtendedInternalServerErrorException(e.getMessage()); + } - } - - public Set<String> getAllMicroServiceKey() { - int failedNum = 0; - int retryCount=3; - int failedTimer = 5 * 1000; - - Set<String> serviceKeys=null; - - do { - - try { - serviceKeys= MicroServiceFullService.getInstance().getAllMicroServiceKey(); - break; - - } catch (Exception e) { - - LOGGER.error(failedNum + "/"+retryCount+" : get AllMicroServiceKey fail"+e); - failedNum++; - - try { - Thread.sleep(failedTimer); - } catch (InterruptedException ex) { - LOGGER.warn("get AllMicroServiceKey Thread.sleep throw except:" + ex.getMessage()); - } - } - - }while (failedNum <= retryCount); - - - return serviceKeys; - - } - - - - - /** - * @Title: getMicroServiceInstance - * @Description: (getMicroServiceInstance) - * @param: @param serviceName - * @param: @param version - * @param: @return - * @return: ApiRouteInfo - */ - public MicroServiceFullInfo getMicroServiceInstance(String serviceName, String version) { - if ("null".equals(version)) { - version = ""; } - serviceName = serviceName.replace("*", "/"); - RouteUtil.checkServiceNameAndVersion(serviceName, version); + public Set<String> getAllMicroServiceKey() { + int failedNum = 0; + int retryCount = 3; + int failedTimer = 5 * 1000; - MicroServiceFullInfo microServiceInfo; - try { - microServiceInfo = - MicroServiceFullService.getInstance().getMicroServiceInstance(serviceName, version); + Set<String> serviceKeys = null; - } catch (Exception e) { - throw new ExtendedInternalServerErrorException(e.getMessage()); - } + do { - if (null == microServiceInfo) { - String errInfo = "microservice not found: serviceName-" + serviceName + ",version-" + version; - throw new ExtendedNotFoundException(errInfo); + try { + serviceKeys = MicroServiceFullService.getInstance().getAllMicroServiceKey(); + break; - } + } catch (Exception e) { - return microServiceInfo; - } + LOGGER.error(failedNum + "/" + retryCount + " : get AllMicroServiceKey fail" + e); + failedNum++; + try { + Thread.sleep(failedTimer); + } catch (InterruptedException ex) { + LOGGER.warn("get AllMicroServiceKey Thread.sleep throw except:" + ex.getMessage()); + } + } + } while (failedNum <= retryCount); - /** - * @Title updateMicroServiceStatus - * @Description updateMicroServiceStatus - * @param serviceName - * @param version - * @param status - * @return - * @return RouteResult - */ - public synchronized MicroServiceFullInfo updateMicroServiceStatus(String serviceName, - String version, String status) { + return serviceKeys; - if ("null".equals(version)) { - version = ""; } - serviceName = serviceName.replace("*", "/"); - RouteUtil.checkServiceNameAndVersion(serviceName, version); - RouteUtil.checkServiceStatus(status); - try { + /** + * @Title: getMicroServiceInstance + * @Description: (getMicroServiceInstance) + * @param: @param serviceName + * @param: @param version + * @param: @return + * @return: ApiRouteInfo + */ + public MicroServiceFullInfo getMicroServiceInstance(String serviceName, String version) { + if ("null".equals(version)) { + version = ""; + } + serviceName = serviceName.replace("*", "/"); - MicroServiceFullService.getInstance().updateMicroServiceStatus(serviceName, version, status); + RouteUtil.checkServiceNameAndVersion(serviceName, version); - MicroServiceFullInfo newMicroServiceInfo = - MicroServiceFullService.getInstance().getMicroServiceInstance(serviceName, version); + MicroServiceFullInfo microServiceInfo; + try { + microServiceInfo = MicroServiceFullService.getInstance().getMicroServiceInstance(serviceName, version); - // Notify the listeners - RouteNotify.getInstance().noticeUpdateStatusListener(newMicroServiceInfo, status); + } catch (Exception e) { + throw new ExtendedInternalServerErrorException(e.getMessage()); + } + + if (null == microServiceInfo) { + String errInfo = "microservice not found: serviceName-" + serviceName + ",version-" + version; + throw new ExtendedNotFoundException(errInfo); + } - return newMicroServiceInfo; - } catch (NullPointerException e) { - throw new ExtendedNotFoundException(e.getMessage()); - } catch (Exception e) { - LOGGER.error("update MicroServiceNode throw exception", e); - throw new ExtendedInternalServerErrorException(e.getMessage()); + return microServiceInfo; } - } + /** + * @Title updateMicroServiceStatus + * @Description updateMicroServiceStatus + * @param serviceName + * @param version + * @param status + * @return + * @return RouteResult + */ + + public synchronized MicroServiceFullInfo updateMicroServiceStatus(String serviceName, String version, + String status) { + + if ("null".equals(version)) { + version = ""; + } + serviceName = serviceName.replace("*", "/"); - public synchronized MicroServiceFullInfo saveMicroServiceInstance( - MicroServiceFullInfo microServiceInfo, boolean createOrUpdate, String requestIP, - String serverPort) { + RouteUtil.checkServiceNameAndVersion(serviceName, version); - RouteUtil.checkMicroServiceInfoFormat(microServiceInfo, requestIP); + RouteUtil.checkServiceStatus(status); - try { + try { - if (createOrUpdate == false) { - deleteServiceAndnoticeRoute(microServiceInfo); - } + MicroServiceFullService.getInstance().updateMicroServiceStatus(serviceName, version, status); - saveServiceAndnoticeRoute(microServiceInfo); + MicroServiceFullInfo newMicroServiceInfo = + MicroServiceFullService.getInstance().getMicroServiceInstance(serviceName, version); + // Notify the listeners + RouteNotify.getInstance().noticeUpdateStatusListener(newMicroServiceInfo, status); - MicroServiceFullInfo newMicroServiceInfo = - MicroServiceFullService.getInstance().getMicroServiceInstance( - microServiceInfo.getServiceName(), microServiceInfo.getVersion()); + return newMicroServiceInfo; + } catch (NullPointerException e) { + throw new ExtendedNotFoundException(e.getMessage()); + } catch (Exception e) { + LOGGER.error("update MicroServiceNode throw exception", e); + throw new ExtendedInternalServerErrorException(e.getMessage()); + } - return newMicroServiceInfo; - } catch (UnprocessableEntityException e) { - throw e; - } catch (Exception e) { - throw new ExtendedInternalServerErrorException("save MicroServiceInfo fail :[serviceName]" + microServiceInfo.getServiceName() - + "[version]" + microServiceInfo.getVersion()+ e.getMessage()); } - } + public synchronized MicroServiceFullInfo saveMicroServiceInstance(MicroServiceFullInfo microServiceInfo, + boolean createOrUpdate, String requestIP, String serverPort) { - public synchronized void deleteMicroService4AllVersion(String serviceName) { - try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo, requestIP); - List<MicroServiceFullInfo> microServiceList4AllVersion = - MicroServiceFullService.getInstance().getAllVersionsOfTheService(serviceName); + try { - if (microServiceList4AllVersion.size() == 0) { - LOGGER.info("delete MicroServiceInfo for All Version Fail:serviceName-" + serviceName - + " not fond"); - } else { - for (MicroServiceFullInfo microServiceInfo : microServiceList4AllVersion) { - deleteServiceAndnoticeRoute(microServiceInfo); - } - } + if (createOrUpdate == false) { + deleteServiceAndnoticeRoute(microServiceInfo); + } - } catch (Exception e) { - LOGGER.error("delete MicroServiceInfo for all version :serviceName-" + serviceName +" throw exception", e); + saveServiceAndnoticeRoute(microServiceInfo); - } - } + MicroServiceFullInfo newMicroServiceInfo = MicroServiceFullService.getInstance() + .getMicroServiceInstance(microServiceInfo.getServiceName(), microServiceInfo.getVersion()); - public synchronized void deleteMicroService(String serviceName, String version) { - if ("null".equals(version)) { - version = ""; - } - serviceName = serviceName.replace("*", "/"); - RouteUtil.checkServiceNameAndVersion(serviceName, version); + return newMicroServiceInfo; - try { + } catch (UnprocessableEntityException e) { + throw e; + } catch (Exception e) { + throw new ExtendedInternalServerErrorException( + "save MicroServiceInfo fail :[serviceName]" + microServiceInfo.getServiceName() + + "[version]" + microServiceInfo.getVersion() + e.getMessage()); + } - MicroServiceFullInfo microServiceInfo = - MicroServiceFullService.getInstance().getMicroServiceInstance(serviceName, version); + } - if (microServiceInfo == null) { - LOGGER.error("delete MicroServiceInfo FAIL:serviceName-" + serviceName + ",version-"+ version + " not fond "); - } else { - deleteServiceAndnoticeRoute(microServiceInfo); - } + public synchronized void deleteMicroService4AllVersion(String serviceName) { + try { + List<MicroServiceFullInfo> microServiceList4AllVersion = + MicroServiceFullService.getInstance().getAllVersionsOfTheService(serviceName); - } catch (ExtendedNotFoundException e) { - throw e; - } catch (Exception e) { + if (microServiceList4AllVersion.size() == 0) { + LOGGER.info("delete MicroServiceInfo for All Version Fail:serviceName-" + serviceName + " not fond"); + } else { + for (MicroServiceFullInfo microServiceInfo : microServiceList4AllVersion) { + deleteServiceAndnoticeRoute(microServiceInfo); + } + } - throw new ExtendedInternalServerErrorException("delete MicroServiceInfo serviceName-" + serviceName + ",version-" + version+e.getMessage()); + } catch (Exception e) { + LOGGER.error("delete MicroServiceInfo for all version :serviceName-" + serviceName + " throw exception", e); + } } - } + public synchronized void deleteMicroService(String serviceName, String version) { + if ("null".equals(version)) { + version = ""; + } + serviceName = serviceName.replace("*", "/"); - public synchronized void deleteMicroServiceInstance(String serviceName, String version, - String ip, String port) { - if ("null".equals(version)) { - version = ""; - } - serviceName = serviceName.replace("*", "/"); + RouteUtil.checkServiceNameAndVersion(serviceName, version); - RouteUtil.checkServiceNameAndVersion(serviceName, version); + try { - if (!RegExpTestUtil.ipRegExpTest(ip)) { - throw new UnprocessableEntityException("delete MicroServiceInfo FAIL:IP(" + ip+ ")is not a valid IP address"); - } + MicroServiceFullInfo microServiceInfo = + MicroServiceFullService.getInstance().getMicroServiceInstance(serviceName, version); - if (!RegExpTestUtil.portRegExpTest(port)) { - throw new UnprocessableEntityException("delete MicroServiceInfo FAIL:Port(" + port + ")is not a valid Port address"); - } + if (microServiceInfo == null) { + LOGGER.error("delete MicroServiceInfo FAIL:serviceName-" + serviceName + ",version-" + version + + " not fond "); + } else { + deleteServiceAndnoticeRoute(microServiceInfo); + } - try { - MicroServiceFullInfo microServiceInfo = - MicroServiceFullService.getInstance().getMicroServiceInstance(serviceName, version); - if (microServiceInfo == null) { - throw new UnprocessableEntityException("delete MicroServiceInfo FAIL:serviceName-"+ serviceName + ",version-" + version + " not fond "); - } + } catch (ExtendedNotFoundException e) { + throw e; + } catch (Exception e) { - Set<Node> nodes = microServiceInfo.getNodes(); + throw new ExtendedInternalServerErrorException("delete MicroServiceInfo serviceName-" + serviceName + + ",version-" + version + e.getMessage()); - boolean ifFindBNode = false; + } - for (Node node : nodes) { - if (node.getIp().equals(ip) && node.getPort().equals(port)) { - ifFindBNode = true; - nodes.remove(node); - if (nodes.isEmpty()) { - // delete MicroService - deleteServiceAndnoticeRoute(microServiceInfo); - } else { - // delete Node - MicroServiceFullService.getInstance().saveMicroServiceInfo2Redis(microServiceInfo); - RouteNotify.getInstance().noticeRouteListener4Update(serviceName, version, - microServiceInfo); - } + } - break; + public synchronized void deleteMicroServiceInstance(String serviceName, String version, String ip, String port) { + if ("null".equals(version)) { + version = ""; } - } + serviceName = serviceName.replace("*", "/"); - if (!ifFindBNode) { - throw new ExtendedNotFoundException("delete MicroServiceInfo FAIL:serviceName-"+ serviceName + ",version-" + version +",node-" + ip + ":" + port + " not fond "); - } + RouteUtil.checkServiceNameAndVersion(serviceName, version); + if (!RegExpTestUtil.ipRegExpTest(ip)) { + throw new UnprocessableEntityException( + "delete MicroServiceInfo FAIL:IP(" + ip + ")is not a valid IP address"); + } - } catch (ExtendedNotFoundException e) { - throw e; - } catch (Exception e) { - throw new ExtendedInternalServerErrorException("delete MicroServiceInfo :serviceName-"+ serviceName + ",version-" + version+",node-" + ip + ":" + port +"throw exception"+e.getMessage()); + if (!RegExpTestUtil.portRegExpTest(port)) { + throw new UnprocessableEntityException( + "delete MicroServiceInfo FAIL:Port(" + port + ")is not a valid Port address"); + } - } - } + try { + MicroServiceFullInfo microServiceInfo = + MicroServiceFullService.getInstance().getMicroServiceInstance(serviceName, version); + + if (microServiceInfo == null) { + throw new UnprocessableEntityException("delete MicroServiceInfo FAIL:serviceName-" + serviceName + + ",version-" + version + " not fond "); + } + + Set<Node> nodes = microServiceInfo.getNodes(); + + boolean ifFindBNode = false; + + for (Node node : nodes) { + if (node.getIp().equals(ip) && node.getPort().equals(port)) { + ifFindBNode = true; + nodes.remove(node); + + if (nodes.isEmpty()) { + // delete MicroService + deleteServiceAndnoticeRoute(microServiceInfo); + } else { + // delete Node + MicroServiceFullService.getInstance().saveMicroServiceInfo2Redis(microServiceInfo); + RouteNotify.getInstance().noticeRouteListener4Update(serviceName, version, microServiceInfo); + } + break; + } + } - public void deleteServiceAndnoticeRoute(MicroServiceFullInfo service) throws Exception { + if (!ifFindBNode) { + throw new ExtendedNotFoundException("delete MicroServiceInfo FAIL:serviceName-" + serviceName + + ",version-" + version + ",node-" + ip + ":" + port + " not fond "); + } - try { - // Delete the redis record - MicroServiceFullService.getInstance().deleteMicroService(service.getServiceName(), - service.getVersion()); - LOGGER.info("delete MicroServiceInfo And notice to Route success:[serviceName]"+ service.getServiceName() + "[version]" + service.getVersion()); - // Notify the listeners - RouteNotify.getInstance().noticeRouteListener4Delete(service); - - } catch (Exception e) { - LOGGER.error("delete MicroService And synchro to Route:[serviceName]"+ service.getServiceName() + "[version]" + service.getVersion()+" throw exception", e); - throw e; + } catch (ExtendedNotFoundException e) { + throw e; + } catch (Exception e) { + throw new ExtendedInternalServerErrorException("delete MicroServiceInfo :serviceName-" + serviceName + + ",version-" + version + ",node-" + ip + ":" + port + "throw exception" + e.getMessage()); + + } + } - } - public void saveServiceAndnoticeRoute(MicroServiceFullInfo service) throws Exception { - try { - // save the redis record - MicroServiceFullService.getInstance().saveMicroServiceInfo2Redis(service); - - LOGGER.info("save MicroServiceInfo And notice to Route success:[serviceName]"+ service.getServiceName() + "[version]" + service.getVersion()); + public void deleteServiceAndnoticeRoute(MicroServiceFullInfo service) throws Exception { - // Notify the listeners - RouteNotify.getInstance().noticeRouteListener4Add(service); + try { + // Delete the redis record + MicroServiceFullService.getInstance().deleteMicroService(service.getServiceName(), service.getVersion()); + LOGGER.info("delete MicroServiceInfo And notice to Route success:[serviceName]" + service.getServiceName() + + "[version]" + service.getVersion()); + // Notify the listeners + RouteNotify.getInstance().noticeRouteListener4Delete(service); - } catch (Exception e) { - LOGGER.error("save MicroServiceInfo And synchro to Route fail :[serviceName]" + service.getServiceName()+ "[version]" + service.getVersion() + " throw exception", e); - throw e; + } catch (Exception e) { + LOGGER.error("delete MicroService And synchro to Route:[serviceName]" + service.getServiceName() + + "[version]" + service.getVersion() + " throw exception", e); + throw e; + } } - } - public Set<String> getAllVersion(String serviceName) { - Set<String> serviceVersionSet = new HashSet<String>(); - try { - String pattern = MicroServiceUtil.getServiceKey(serviceName, "*"); - Set<String> serviceKeySet = RedisAccessWrapper.filterKeys(pattern); + public void saveServiceAndnoticeRoute(MicroServiceFullInfo service) throws Exception { + + try { + // save the redis record + MicroServiceFullService.getInstance().saveMicroServiceInfo2Redis(service); + LOGGER.info("save MicroServiceInfo And notice to Route success:[serviceName]" + service.getServiceName() + + "[version]" + service.getVersion()); - Pattern serviceKeyRegexPattern = MicroServiceUtil.getServiceKeyRegexPattern(); - for (String serviceKey : serviceKeySet) { - Matcher matcher = serviceKeyRegexPattern.matcher(serviceKey); - if (matcher.matches()) { - serviceVersionSet.add(matcher.group("version")); + // Notify the listeners + RouteNotify.getInstance().noticeRouteListener4Add(service); + + + } catch (Exception e) { + LOGGER.error("save MicroServiceInfo And synchro to Route fail :[serviceName]" + service.getServiceName() + + "[version]" + service.getVersion() + " throw exception", e); + throw e; } - } - } catch (Exception e) { - LOGGER.error("getAllVersion [serviceName]:" + serviceName + " throw exception", e); } - return serviceVersionSet; + public Set<String> getAllVersion(String serviceName) { + Set<String> serviceVersionSet = new HashSet<String>(); + try { + String pattern = MicroServiceUtil.getServiceKey(serviceName, "*"); + Set<String> serviceKeySet = RedisAccessWrapper.filterKeys(pattern); + + + Pattern serviceKeyRegexPattern = MicroServiceUtil.getServiceKeyRegexPattern(); + for (String serviceKey : serviceKeySet) { + Matcher matcher = serviceKeyRegexPattern.matcher(serviceKey); + if (matcher.matches()) { + serviceVersionSet.add(matcher.group("version")); + } + } + } catch (Exception e) { + LOGGER.error("getAllVersion [serviceName]:" + serviceName + " throw exception", e); + } - } + return serviceVersionSet; + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/CatalogClient.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/CatalogClient.java index bb0edbf..0632108 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/CatalogClient.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/CatalogClient.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend; @@ -32,71 +30,64 @@ import com.orbitz.consul.option.QueryOptions; */ public class CatalogClient { - private static final Logger LOGGER = LoggerFactory - .getLogger(CatalogClient.class); - - private static final TypeReference<HttpEntity> TYPE_SERVICES_MAP = new TypeReference<HttpEntity>() { - }; - - - private static final String CATALOG_URI_8500 = "/v1/catalog"; - private static final String CATAlOG_URI_10081 = "/api/catalog/v1"; - - private static final String GET_SERVICES_URI = "/services"; - - private static final Http httpClient = Http.getInstance(); - - private HttpHost targetHost = null; - private String catalogUri = CATAlOG_URI_10081; - - CatalogClient(final HttpHost targetHost) { - this.targetHost = targetHost; - if (targetHost.getPort() == 8500) { - catalogUri = CATALOG_URI_8500; - } - } - - /** - * Retrieves all services for a given datacenter with - * {@link com.orbitz.consul.option.QueryOptions}. - * - * GET /v1/catalog/services?dc={datacenter} - * - * @param catalogOptions - * Catalog specific options to use. - * @param queryOptions - * The Query Options to use. - * @return A {@link com.orbitz.consul.model.ConsulResponse} containing a map - * of service name to list of tags. - */ - public void getServices(CatalogOptions catalogOptions, - QueryOptions queryOptions, - ConsulResponseCallback<HttpEntity> callback) { - - // prepare access path - // path:10081 vs 8500 - String path = targetHost.toString() + catalogUri + GET_SERVICES_URI; - - // params:wait,index,dc...... - String params = Http.optionsFrom(catalogOptions, queryOptions); - - // node meta: ns,external,internal..... - String node_meta = ConfigUtil.getInstance().getNodeMetaQueryParam(); - - // add params - path = (params != null && !params.isEmpty()) ? path += "?" + params - : path; - - // add node_meta - if (node_meta != null && !node_meta.isEmpty()) { - path = path.contains("?") ? path +"&"+ node_meta : path + "?" - + node_meta; - } - - // async watch services - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("get all services:" + path); - } - httpClient.asyncGetDelayHandle(path, TYPE_SERVICES_MAP, callback); - } + private static final Logger LOGGER = LoggerFactory.getLogger(CatalogClient.class); + + private static final TypeReference<HttpEntity> TYPE_SERVICES_MAP = new TypeReference<HttpEntity>() {}; + + + private static final String CATALOG_URI_8500 = "/v1/catalog"; + private static final String CATAlOG_URI_10081 = "/api/catalog/v1"; + + private static final String GET_SERVICES_URI = "/services"; + + private static final Http httpClient = Http.getInstance(); + + private HttpHost targetHost = null; + private String catalogUri = CATAlOG_URI_10081; + + CatalogClient(final HttpHost targetHost) { + this.targetHost = targetHost; + if (targetHost.getPort() == 8500) { + catalogUri = CATALOG_URI_8500; + } + } + + /** + * Retrieves all services for a given datacenter with + * {@link com.orbitz.consul.option.QueryOptions}. + * + * GET /v1/catalog/services?dc={datacenter} + * + * @param catalogOptions Catalog specific options to use. + * @param queryOptions The Query Options to use. + * @return A {@link com.orbitz.consul.model.ConsulResponse} containing a map of service name to + * list of tags. + */ + public void getServices(CatalogOptions catalogOptions, QueryOptions queryOptions, + ConsulResponseCallback<HttpEntity> callback) { + + // prepare access path + // path:10081 vs 8500 + String path = targetHost.toString() + catalogUri + GET_SERVICES_URI; + + // params:wait,index,dc...... + String params = Http.optionsFrom(catalogOptions, queryOptions); + + // node meta: ns,external,internal..... + String node_meta = ConfigUtil.getInstance().getNodeMetaQueryParam(); + + // add params + path = (params != null && !params.isEmpty()) ? path += "?" + params : path; + + // add node_meta + if (node_meta != null && !node_meta.isEmpty()) { + path = path.contains("?") ? path + "&" + node_meta : path + "?" + node_meta; + } + + // async watch services + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("get all services:" + path); + } + httpClient.asyncGetDelayHandle(path, TYPE_SERVICES_MAP, callback); + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/Consul.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/Consul.java index a83e9ab..24427c5 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/Consul.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/Consul.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend; @@ -22,91 +20,90 @@ import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; public class Consul { - /** - * Default Consul HTTP API host. - */ - public static final String DEFAULT_HTTP_HOST = "localhost"; - - /** - * Default Consul HTTP API port. - */ - public static final int DEFAULT_HTTP_PORT = 8500; - - private static final Logger LOGGER = LoggerFactory - .getLogger(Consul.class); - - private final CatalogClient catalogClient; - private final HealthClient healthClient; - - private Consul(CatalogClient catalogClient, HealthClient healthClient) { - this.catalogClient = catalogClient; - this.healthClient = healthClient; - } - - /** - * Get the Catalog HTTP client. - * <p> - * /v1/catalog - * - * @return The Catalog HTTP client. - */ - public CatalogClient catalogClient() { - return catalogClient; - } - - /** - * Get the Health HTTP client. - * <p> - * /v1/health - * - * @return The Health HTTP client. - */ - public HealthClient healthClient() { - return healthClient; - } - - /** - * Creates a new {@link Builder} object. - * - * @return A new Consul builder. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * Used to create a default Consul client. - * - * @return A default {@link Consul} client. - */ - @VisibleForTesting - public static Consul newClient() { - return builder().build(); - } - - public static class Builder { - - private HttpHost targetHost; - - { - targetHost = new HttpHost(DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT); - } - - Builder() { - - } - - public Builder withHostAndPort(String hostname, int port) { - this.targetHost = new HttpHost(hostname, port); - return this; - } - - public Consul build() { - LOGGER.info("********build consul:"+targetHost.toString()+"****************"); - CatalogClient catalogClient = new CatalogClient(targetHost); - HealthClient healthClient = new HealthClient(targetHost); - return new Consul(catalogClient,healthClient); - } - - } + /** + * Default Consul HTTP API host. + */ + public static final String DEFAULT_HTTP_HOST = "localhost"; + + /** + * Default Consul HTTP API port. + */ + public static final int DEFAULT_HTTP_PORT = 8500; + + private static final Logger LOGGER = LoggerFactory.getLogger(Consul.class); + + private final CatalogClient catalogClient; + private final HealthClient healthClient; + + private Consul(CatalogClient catalogClient, HealthClient healthClient) { + this.catalogClient = catalogClient; + this.healthClient = healthClient; + } + + /** + * Get the Catalog HTTP client. + * <p> + * /v1/catalog + * + * @return The Catalog HTTP client. + */ + public CatalogClient catalogClient() { + return catalogClient; + } + + /** + * Get the Health HTTP client. + * <p> + * /v1/health + * + * @return The Health HTTP client. + */ + public HealthClient healthClient() { + return healthClient; + } + + /** + * Creates a new {@link Builder} object. + * + * @return A new Consul builder. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Used to create a default Consul client. + * + * @return A default {@link Consul} client. + */ + @VisibleForTesting + public static Consul newClient() { + return builder().build(); + } + + public static class Builder { + + private HttpHost targetHost; + + { + targetHost = new HttpHost(DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT); + } + + Builder() { + + } + + public Builder withHostAndPort(String hostname, int port) { + this.targetHost = new HttpHost(hostname, port); + return this; + } + + public Consul build() { + LOGGER.info("********build consul:" + targetHost.toString() + "****************"); + CatalogClient catalogClient = new CatalogClient(targetHost); + HealthClient healthClient = new HealthClient(targetHost); + return new Consul(catalogClient, healthClient); + } + + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/HealthClient.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/HealthClient.java index 85c9b78..3809247 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/HealthClient.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/HealthClient.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend; @@ -32,96 +30,84 @@ import com.orbitz.consul.option.QueryOptions; * HTTP Client for /v1/health/ endpoints. */ public class HealthClient { - private final static Logger LOGGER = LoggerFactory - .getLogger(HealthClient.class); - - private static final TypeReference<List<ServiceHealth>> TYPE_SERVICE_HEALTH_LIST = new TypeReference<List<ServiceHealth>>() { - }; - - private static final String HEALTH_URI_10081 = "/api/health/v1"; - private static final String HEALTH_URI_8500 = "/v1/health"; - private static final String GET_HEALTH_SERVICE_URI = "/service"; - -// private static final String GET_HEALTH_SERVICE_URI = "/v1/health/service"; - -// private static final String GET_HEALTH_SERVICE_URI = "/api/health/v1/service"; - - private final static Http httpClient = Http.getInstance(); - - private HttpHost targetHost = null; - private String healthUri = HEALTH_URI_10081; - - HealthClient(final HttpHost targetHost) { - this.targetHost = targetHost; - - if(targetHost.getPort() == 8500) - { - healthUri = HEALTH_URI_8500; - } - } - - /** - * Asynchronously retrieves the healthchecks for all healthy service - * instances in a given datacenter with - * {@link com.orbitz.consul.option.QueryOptions}. - * - * GET /v1/health/service/{service}?dc={datacenter}&passing - * - * Experimental. - * - * @param service - * The service to query. - * @param catalogOptions - * The catalog specific options to use. - * @param queryOptions - * The Query Options to use. - * @param callback - * Callback implemented by callee to handle results. - */ - public void getHealthyServiceInstances(String service, - CatalogOptions catalogOptions, QueryOptions queryOptions, - ConsulResponseCallback<List<ServiceHealth>> callback) { - // prepare access path - String path = targetHost.toString() + healthUri + GET_HEALTH_SERVICE_URI + "/"+ service; - - String params = Http.optionsFrom(catalogOptions, queryOptions); - path = (params != null && !params.isEmpty()) ? path += "?" - + params : path; //query all nodes without filter for health - - // async watch -// LOGGER.info("get health paasing service:" + path); - httpClient.asyncGetDelayHandle(path, TYPE_SERVICE_HEALTH_LIST, callback); - } - - /** - * Asynchronously retrieves the healthchecks for all nodes in a given - * datacenter with {@link com.orbitz.consul.option.QueryOptions}. - * - * GET /v1/health/service/{service}?dc={datacenter} - * - * Experimental. - * - * @param service - * The service to query. - * @param catalogOptions - * The catalog specific options to use. - * @param queryOptions - * The Query Options to use. - * @param callback - * Callback implemented by callee to handle results. - */ - public void getAllServiceInstances(String service, - CatalogOptions catalogOptions, QueryOptions queryOptions, - ConsulResponseCallback<List<ServiceHealth>> callback) { - - // prepare access path - String path = targetHost.toString() + healthUri + GET_HEALTH_SERVICE_URI + "/"+ service; - String params = Http.optionsFrom(catalogOptions, queryOptions); - path = (params != null && !params.isEmpty()) ? path += "?" + params - : path; - - // async watch -// LOGGER.debug("get service:" + path); - httpClient.asyncGetDelayHandle(path, TYPE_SERVICE_HEALTH_LIST, callback); - } + private final static Logger LOGGER = LoggerFactory.getLogger(HealthClient.class); + + private static final TypeReference<List<ServiceHealth>> TYPE_SERVICE_HEALTH_LIST = + new TypeReference<List<ServiceHealth>>() {}; + + private static final String HEALTH_URI_10081 = "/api/health/v1"; + private static final String HEALTH_URI_8500 = "/v1/health"; + private static final String GET_HEALTH_SERVICE_URI = "/service"; + + // private static final String GET_HEALTH_SERVICE_URI = "/v1/health/service"; + + // private static final String GET_HEALTH_SERVICE_URI = "/api/health/v1/service"; + + private final static Http httpClient = Http.getInstance(); + + private HttpHost targetHost = null; + private String healthUri = HEALTH_URI_10081; + + HealthClient(final HttpHost targetHost) { + this.targetHost = targetHost; + + if (targetHost.getPort() == 8500) { + healthUri = HEALTH_URI_8500; + } + } + + /** + * Asynchronously retrieves the healthchecks for all healthy service instances in a given + * datacenter with {@link com.orbitz.consul.option.QueryOptions}. + * + * GET /v1/health/service/{service}?dc={datacenter}&passing + * + * Experimental. + * + * @param service The service to query. + * @param catalogOptions The catalog specific options to use. + * @param queryOptions The Query Options to use. + * @param callback Callback implemented by callee to handle results. + */ + public void getHealthyServiceInstances(String service, CatalogOptions catalogOptions, QueryOptions queryOptions, + ConsulResponseCallback<List<ServiceHealth>> callback) { + // prepare access path + String path = targetHost.toString() + healthUri + GET_HEALTH_SERVICE_URI + "/" + service; + + String params = Http.optionsFrom(catalogOptions, queryOptions); + path = (params != null && !params.isEmpty()) ? path += "?" + params : path; // query all + // nodes without + // filter for + // health + + // async watch + // LOGGER.info("get health paasing service:" + path); + httpClient.asyncGetDelayHandle(path, TYPE_SERVICE_HEALTH_LIST, callback); + } + + /** + * Asynchronously retrieves the healthchecks for all nodes in a given datacenter with + * {@link com.orbitz.consul.option.QueryOptions}. + * + * GET /v1/health/service/{service}?dc={datacenter} + * + * Experimental. + * + * @param service The service to query. + * @param catalogOptions The catalog specific options to use. + * @param queryOptions The Query Options to use. + * @param callback Callback implemented by callee to handle results. + */ + public void getAllServiceInstances(String service, CatalogOptions catalogOptions, QueryOptions queryOptions, + ConsulResponseCallback<List<ServiceHealth>> callback) { + + // prepare access path + String path = targetHost.toString() + healthUri + GET_HEALTH_SERVICE_URI + "/" + service; + String params = Http.optionsFrom(catalogOptions, queryOptions); + path = (params != null && !params.isEmpty()) ? path += "?" + params : path; + + // async watch + // LOGGER.debug("get service:" + path); + httpClient.asyncGetDelayHandle(path, TYPE_SERVICE_HEALTH_LIST, callback); + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/ConsulResponseCallback.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/ConsulResponseCallback.java index 536cfbd..faa00d0 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/ConsulResponseCallback.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/ConsulResponseCallback.java @@ -1,25 +1,23 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.async; import com.orbitz.consul.model.ConsulResponse; /** - * For API calls that support long-polling, this callback is used to handle - * the result on success or failure for an async HTTP call. + * For API calls that support long-polling, this callback is used to handle the result on success or + * failure for an async HTTP call. * * @param <T> The Response type. */ @@ -38,7 +36,7 @@ public interface ConsulResponseCallback<T> { * @param consulResponse The Consul response. */ void onDelayComplete(OriginalConsulResponse<T> originalConsulResponse); - + /** * Callback for an unsuccessful request. * diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/ConsulResponseHeader.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/ConsulResponseHeader.java index 136fd49..76e0ff9 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/ConsulResponseHeader.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/ConsulResponseHeader.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.async; @@ -21,7 +19,7 @@ public class ConsulResponseHeader { private final long lastContact; private final boolean knownLeader; private final BigInteger index; - + public ConsulResponseHeader(long lastContact, boolean knownLeader, BigInteger index) { this.lastContact = lastContact; this.knownLeader = knownLeader; diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/OriginalConsulResponse.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/OriginalConsulResponse.java index 3b72b24..6ad7c01 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/OriginalConsulResponse.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/async/OriginalConsulResponse.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.async; @@ -20,9 +18,9 @@ import org.apache.http.HttpResponse; import com.fasterxml.jackson.core.type.TypeReference; public class OriginalConsulResponse<T> { - final HttpResponse response; - final TypeReference<T> responseType; - + final HttpResponse response; + final TypeReference<T> responseType; + public OriginalConsulResponse(HttpResponse response, TypeReference<T> responseType) { this.response = response; this.responseType = responseType; @@ -34,9 +32,9 @@ public class OriginalConsulResponse<T> { } public TypeReference<T> getResponseType() { - return responseType; - } - - - + return responseType; + } + + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ConsulCache.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ConsulCache.java index 5325b89..b389efc 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ConsulCache.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ConsulCache.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.cache; @@ -44,273 +42,248 @@ import com.orbitz.consul.option.ImmutableQueryOptions; import com.orbitz.consul.option.QueryOptions; /** - * A cache structure that can provide an up-to-date read-only map backed by - * consul data + * A cache structure that can provide an up-to-date read-only map backed by consul data * * @param <V> */ public class ConsulCache<T> { - enum State { - latent, starting, started, stopped - } - - private final static Logger LOGGER = LoggerFactory - .getLogger(ConsulCache.class); - - @VisibleForTesting - static final String BACKOFF_DELAY_PROPERTY = "com.orbitz.consul.cache.backOffDelay"; - private static final long BACKOFF_DELAY_QTY_IN_MS = getBackOffDelayInMs(System - .getProperties()); - - private final AtomicReference<BigInteger> latestIndex = new AtomicReference<BigInteger>( - null); - private final AtomicReference<State> state = new AtomicReference<State>( - State.latent); - private final CountDownLatch initLatch = new CountDownLatch(1); - private final ScheduledExecutorService executorService = Executors - .newSingleThreadScheduledExecutor(); - private final CopyOnWriteArrayList<Listener<T>> listeners = new CopyOnWriteArrayList<Listener<T>>(); - - private final CallbackConsumer<T> callBackConsumer; - private final ConsulResponseCallback<T> responseCallback; - - ConsulCache(CallbackConsumer<T> callbackConsumer) { - - this.callBackConsumer = callbackConsumer; - - this.responseCallback = new ConsulResponseCallback<T>() { - @Override - public void onComplete(ConsulResponse<T> consulResponse) { - - if (consulResponse.isKnownLeader()) { - if (!isRunning()) { - return; - } - updateIndex(consulResponse); - - for (Listener<T> l : listeners) { - l.notify(consulResponse); - } - - if (state.compareAndSet(State.starting, State.started)) { - initLatch.countDown(); - } - - runCallback(); - } else { - onFailure(new ConsulException( - "Consul cluster has no elected leader")); - } - } - - @Override - public void onDelayComplete( - OriginalConsulResponse<T> originalConsulResponse) { - - try { - // get header - ConsulResponseHeader consulResponseHeader = Http - .consulResponseHeader(originalConsulResponse - .getResponse()); - - if (consulResponseHeader.isKnownLeader()) { - if (!isRunning()) { - return; - } - - boolean isConuslIndexChanged = isConuslIndexChanged(consulResponseHeader - .getIndex()); - // consul index different - if (isConuslIndexChanged) { - - updateIndex(consulResponseHeader.getIndex()); - - // get T type data - ConsulResponse<T> consulResponse = Http - .consulResponse(originalConsulResponse - .getResponseType(), - originalConsulResponse - .getResponse()); - - // notify customer to custom T data - for (Listener<T> l : listeners) { - l.notify(consulResponse); - } - } - - if (state.compareAndSet(State.starting, State.started)) { - initLatch.countDown(); - } - - runCallback(); - - } else { - onFailure(new ConsulException( - "Consul cluster has no elected leader")); - } - } catch (Exception e) { - onFailure(e); - } - - } - - @Override - public void onFailure(Throwable throwable) { - - if (!isRunning()) { - return; - } - LOGGER.error( - String.format( - "Error getting response from consul. will retry in %d %s", - BACKOFF_DELAY_QTY_IN_MS, TimeUnit.MILLISECONDS), - throwable); - - executorService.schedule(new Runnable() { - @Override - public void run() { - runCallback(); - } - }, BACKOFF_DELAY_QTY_IN_MS, TimeUnit.MILLISECONDS); - } - }; - } - - @VisibleForTesting - static long getBackOffDelayInMs(Properties properties) { - String backOffDelay = null; - try { - backOffDelay = properties.getProperty(BACKOFF_DELAY_PROPERTY); - if (!Strings.isNullOrEmpty(backOffDelay)) { - return Long.parseLong(backOffDelay); - } - } catch (Exception ex) { - LOGGER.warn( - backOffDelay != null ? String.format( - "Error parsing property variable %s: %s", - BACKOFF_DELAY_PROPERTY, backOffDelay) : String - .format("Error extracting property variable %s", - BACKOFF_DELAY_PROPERTY), ex); - } - return TimeUnit.SECONDS.toMillis(10); - } - - public void start() throws Exception { - checkState(state.compareAndSet(State.latent, State.starting), - "Cannot transition from state %s to %s", state.get(), - State.starting); - runCallback(); - } - - public void stop() throws Exception { - State previous = state.getAndSet(State.stopped); - if (previous != State.stopped) { - executorService.shutdownNow(); - } - } - - private void runCallback() { - if (isRunning()) { - callBackConsumer.consume(latestIndex.get(), responseCallback); - } - } - - private boolean isRunning() { - return state.get() == State.started || state.get() == State.starting; - } - - public boolean awaitInitialized(long timeout, TimeUnit unit) - throws InterruptedException { - return initLatch.await(timeout, unit); - } - - private void updateIndex(ConsulResponse<T> consulResponse) { - if (consulResponse != null && consulResponse.getIndex() != null) { - this.latestIndex.set(consulResponse.getIndex()); - } - } - - public void updateIndex(BigInteger index) { - if (index != null) { - this.latestIndex.set(index); - } - } - - protected static QueryOptions watchParams(final BigInteger index, - final int blockSeconds, QueryOptions queryOptions) { - checkArgument(!queryOptions.getIndex().isPresent() - && !queryOptions.getWait().isPresent(), - "Index and wait cannot be overridden"); - - return ImmutableQueryOptions.builder() - .from(watchDefaultParams(index, blockSeconds)) - .token(queryOptions.getToken()) - .consistencyMode(queryOptions.getConsistencyMode()) - .near(queryOptions.getNear()).build(); - } - - private static QueryOptions watchDefaultParams(final BigInteger index, - final int blockSeconds) { - if (index == null) { - return QueryOptions.BLANK; - } else { - return QueryOptions.blockSeconds(blockSeconds, index).build(); - } - } - - /** - * passed in by creators to vary the content of the cached values - * - * @param <V> - */ - protected interface CallbackConsumer<T> { - void consume(BigInteger index, ConsulResponseCallback<T> callback); - } - - /** - * Implementers can register a listener to receive a new map when it changes - * - * @param <V> - */ - public interface Listener<T> { - void notify(ConsulResponse<T> newValues); - } - - public boolean addListener(Listener<T> listener) { - boolean added = listeners.add(listener); - return added; - } - - public List<Listener<T>> getListeners() { - return Collections.unmodifiableList(listeners); - } - - public boolean removeListener(Listener<T> listener) { - return listeners.remove(listener); - } - - @VisibleForTesting - protected State getState() { - return state.get(); - } - - private boolean isConuslIndexChanged(final BigInteger index) { - - if (index != null && !index.equals(latestIndex.get())) { - - if (LOGGER.isDebugEnabled()) { - // 第一次不打印 - if (latestIndex.get() != null) { - LOGGER.debug("consul index compare:new-" + index + " old-" - + latestIndex.get()); - } - - } - - return true; - } - - return false; - } + enum State { + latent, starting, started, stopped + } + + private final static Logger LOGGER = LoggerFactory.getLogger(ConsulCache.class); + + @VisibleForTesting + static final String BACKOFF_DELAY_PROPERTY = "com.orbitz.consul.cache.backOffDelay"; + private static final long BACKOFF_DELAY_QTY_IN_MS = getBackOffDelayInMs(System.getProperties()); + + private final AtomicReference<BigInteger> latestIndex = new AtomicReference<BigInteger>(null); + private final AtomicReference<State> state = new AtomicReference<State>(State.latent); + private final CountDownLatch initLatch = new CountDownLatch(1); + private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + private final CopyOnWriteArrayList<Listener<T>> listeners = new CopyOnWriteArrayList<Listener<T>>(); + + private final CallbackConsumer<T> callBackConsumer; + private final ConsulResponseCallback<T> responseCallback; + + ConsulCache(CallbackConsumer<T> callbackConsumer) { + + this.callBackConsumer = callbackConsumer; + + this.responseCallback = new ConsulResponseCallback<T>() { + @Override + public void onComplete(ConsulResponse<T> consulResponse) { + + if (consulResponse.isKnownLeader()) { + if (!isRunning()) { + return; + } + updateIndex(consulResponse); + + for (Listener<T> l : listeners) { + l.notify(consulResponse); + } + + if (state.compareAndSet(State.starting, State.started)) { + initLatch.countDown(); + } + + runCallback(); + } else { + onFailure(new ConsulException("Consul cluster has no elected leader")); + } + } + + @Override + public void onDelayComplete(OriginalConsulResponse<T> originalConsulResponse) { + + try { + // get header + ConsulResponseHeader consulResponseHeader = + Http.consulResponseHeader(originalConsulResponse.getResponse()); + + if (consulResponseHeader.isKnownLeader()) { + if (!isRunning()) { + return; + } + + boolean isConuslIndexChanged = isConuslIndexChanged(consulResponseHeader.getIndex()); + // consul index different + if (isConuslIndexChanged) { + + updateIndex(consulResponseHeader.getIndex()); + + // get T type data + ConsulResponse<T> consulResponse = + Http.consulResponse(originalConsulResponse.getResponseType(), + originalConsulResponse.getResponse()); + + // notify customer to custom T data + for (Listener<T> l : listeners) { + l.notify(consulResponse); + } + } + + if (state.compareAndSet(State.starting, State.started)) { + initLatch.countDown(); + } + + runCallback(); + + } else { + onFailure(new ConsulException("Consul cluster has no elected leader")); + } + } catch (Exception e) { + onFailure(e); + } + + } + + @Override + public void onFailure(Throwable throwable) { + + if (!isRunning()) { + return; + } + LOGGER.error(String.format("Error getting response from consul. will retry in %d %s", + BACKOFF_DELAY_QTY_IN_MS, TimeUnit.MILLISECONDS), throwable); + + executorService.schedule(new Runnable() { + @Override + public void run() { + runCallback(); + } + }, BACKOFF_DELAY_QTY_IN_MS, TimeUnit.MILLISECONDS); + } + }; + } + + @VisibleForTesting + static long getBackOffDelayInMs(Properties properties) { + String backOffDelay = null; + try { + backOffDelay = properties.getProperty(BACKOFF_DELAY_PROPERTY); + if (!Strings.isNullOrEmpty(backOffDelay)) { + return Long.parseLong(backOffDelay); + } + } catch (Exception ex) { + LOGGER.warn(backOffDelay != null + ? String.format("Error parsing property variable %s: %s", BACKOFF_DELAY_PROPERTY, + backOffDelay) + : String.format("Error extracting property variable %s", BACKOFF_DELAY_PROPERTY), ex); + } + return TimeUnit.SECONDS.toMillis(10); + } + + public void start() throws Exception { + checkState(state.compareAndSet(State.latent, State.starting), "Cannot transition from state %s to %s", + state.get(), State.starting); + runCallback(); + } + + public void stop() throws Exception { + State previous = state.getAndSet(State.stopped); + if (previous != State.stopped) { + executorService.shutdownNow(); + } + } + + private void runCallback() { + if (isRunning()) { + callBackConsumer.consume(latestIndex.get(), responseCallback); + } + } + + private boolean isRunning() { + return state.get() == State.started || state.get() == State.starting; + } + + public boolean awaitInitialized(long timeout, TimeUnit unit) throws InterruptedException { + return initLatch.await(timeout, unit); + } + + private void updateIndex(ConsulResponse<T> consulResponse) { + if (consulResponse != null && consulResponse.getIndex() != null) { + this.latestIndex.set(consulResponse.getIndex()); + } + } + + public void updateIndex(BigInteger index) { + if (index != null) { + this.latestIndex.set(index); + } + } + + protected static QueryOptions watchParams(final BigInteger index, final int blockSeconds, + QueryOptions queryOptions) { + checkArgument(!queryOptions.getIndex().isPresent() && !queryOptions.getWait().isPresent(), + "Index and wait cannot be overridden"); + + return ImmutableQueryOptions.builder().from(watchDefaultParams(index, blockSeconds)) + .token(queryOptions.getToken()).consistencyMode(queryOptions.getConsistencyMode()) + .near(queryOptions.getNear()).build(); + } + + private static QueryOptions watchDefaultParams(final BigInteger index, final int blockSeconds) { + if (index == null) { + return QueryOptions.BLANK; + } else { + return QueryOptions.blockSeconds(blockSeconds, index).build(); + } + } + + /** + * passed in by creators to vary the content of the cached values + * + * @param <V> + */ + protected interface CallbackConsumer<T> { + void consume(BigInteger index, ConsulResponseCallback<T> callback); + } + + /** + * Implementers can register a listener to receive a new map when it changes + * + * @param <V> + */ + public interface Listener<T> { + void notify(ConsulResponse<T> newValues); + } + + public boolean addListener(Listener<T> listener) { + boolean added = listeners.add(listener); + return added; + } + + public List<Listener<T>> getListeners() { + return Collections.unmodifiableList(listeners); + } + + public boolean removeListener(Listener<T> listener) { + return listeners.remove(listener); + } + + @VisibleForTesting + protected State getState() { + return state.get(); + } + + private boolean isConuslIndexChanged(final BigInteger index) { + + if (index != null && !index.equals(latestIndex.get())) { + + if (LOGGER.isDebugEnabled()) { + // 第一次不打印 + if (latestIndex.get() != null) { + LOGGER.debug("consul index compare:new-" + index + " old-" + latestIndex.get()); + } + + } + + return true; + } + + return false; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCache.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCache.java index f8bd224..1b10730 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCache.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCache.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.cache; @@ -36,41 +34,32 @@ public class ServiceHealthCache extends ConsulCache<List<ServiceHealth>> { * Keys will be a {@link HostAndPort} object made up of the service's address/port combo * * @param healthClient the {@link HealthClient} - * @param serviceName the name of the service - * @param passing include only passing services? + * @param serviceName the name of the service + * @param passing include only passing services? * @return a cache object */ - public static ServiceHealthCache newCache( - final HealthClient healthClient, - final String serviceName, - final boolean passing, - final CatalogOptions catalogOptions, - final int watchSeconds, - final QueryOptions queryOptions) { + public static ServiceHealthCache newCache(final HealthClient healthClient, final String serviceName, + final boolean passing, final CatalogOptions catalogOptions, final int watchSeconds, + final QueryOptions queryOptions) { CallbackConsumer<List<ServiceHealth>> callbackConsumer = new CallbackConsumer<List<ServiceHealth>>() { - @Override - public void consume(BigInteger index, - ConsulResponseCallback<List<ServiceHealth>> callback) { - // TODO Auto-generated method stub + @Override + public void consume(BigInteger index, ConsulResponseCallback<List<ServiceHealth>> callback) { + // TODO Auto-generated method stub QueryOptions params = watchParams(index, watchSeconds, queryOptions); if (passing) { healthClient.getHealthyServiceInstances(serviceName, catalogOptions, params, callback); } else { healthClient.getAllServiceInstances(serviceName, catalogOptions, params, callback); } - } + } }; return new ServiceHealthCache(callbackConsumer); } - public static ServiceHealthCache newCache( - final HealthClient healthClient, - final String serviceName, - final boolean passing, - final CatalogOptions catalogOptions, - final int watchSeconds) { + public static ServiceHealthCache newCache(final HealthClient healthClient, final String serviceName, + final boolean passing, final CatalogOptions catalogOptions, final int watchSeconds) { return newCache(healthClient, serviceName, passing, catalogOptions, watchSeconds, QueryOptions.BLANK); } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCache.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCache.java index e0961f0..ced3c2c 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCache.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCache.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.cache; @@ -25,29 +23,26 @@ import com.orbitz.consul.option.CatalogOptions; import com.orbitz.consul.option.QueryOptions; public class ServicesCatalogCache extends ConsulCache<HttpEntity> { - + private ServicesCatalogCache(CallbackConsumer<HttpEntity> callbackConsumer) { super(callbackConsumer); } - public static ServicesCatalogCache newCache( - final CatalogClient catalogClient, - final CatalogOptions catalogOptions, - final QueryOptions queryOptions, - final int watchSeconds) { - + public static ServicesCatalogCache newCache(final CatalogClient catalogClient, final CatalogOptions catalogOptions, + final QueryOptions queryOptions, final int watchSeconds) { + CallbackConsumer<HttpEntity> callbackConsumer = new CallbackConsumer<HttpEntity>() { @Override public void consume(BigInteger index, ConsulResponseCallback<HttpEntity> callback) { - QueryOptions params = watchParams(index, watchSeconds, queryOptions); - catalogClient.getServices(catalogOptions, params,callback); + QueryOptions params = watchParams(index, watchSeconds, queryOptions); + catalogClient.getServices(catalogOptions, params, callback); } }; return new ServicesCatalogCache(callbackConsumer); } - + public static ServicesCatalogCache newCache(final CatalogClient catalogClient) { return newCache(catalogClient, CatalogOptions.BLANK, QueryOptions.BLANK, 10); } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilter.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilter.java index 5730b4b..49246cf 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilter.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilter.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -33,81 +31,69 @@ import com.orbitz.consul.model.health.ImmutableNode; -public class CheckServiceDataEmptyAndAutoStopWatchFilter implements - WatchTask.Filter<List<ServiceHealth>> { - - private final static Logger LOGGER = LoggerFactory - .getLogger(CheckServiceDataEmptyAndAutoStopWatchFilter.class); - private final String serviceName; - - public CheckServiceDataEmptyAndAutoStopWatchFilter( - final String serviceName) { - this.serviceName = serviceName; - } - - @Override - public boolean filter(ConsulResponse<List<ServiceHealth>> object) { - // TODO Auto-generated method stub - boolean result = check(object); - - if (!result) { - // create delete - writeServiceToQueue4Del(); - // stop watch - SyncDataManager.stopWatchService(serviceName); - } - - return result; - } - - // when: - // 1)service had been deleted - // 2)service Health check was not passing - // single service return [],size==0 - // stop this service watching task and create delete event - private boolean check(ConsulResponse<List<ServiceHealth>> object) { - boolean result = true; - - if (object == null || object.getResponse() == null - || object.getResponse().size() == 0) { - LOGGER.info("check service-{},its data is empty", - serviceName); - return false; - } - - return result; - } - - private void writeServiceToQueue4Del() { - ServiceData<List<ServiceHealth>> data = new ServiceData<List<ServiceHealth>>(); - data.setDataType(ServiceData.DataType.service); - data.setOperate(ServiceData.Operate.delete); - - // tell the subsequent operation the service name which will be deleted - Service service = ImmutableService.builder().id("").port(0).address("") - .service(serviceName).addTags("").createIndex(0).modifyIndex(0).build(); - ServiceHealth serviceHealth = ImmutableServiceHealth.builder() - .service(service) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); - List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); - serviceHealthList.add(serviceHealth); - - data.setData(serviceHealthList); - - LOGGER.info("put delete service[" - + serviceName - + "] to service queue :because of deleted "); - - try { - QueueManager.getInstance().putIn(data); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - LOGGER.warn( - "put delete service[" - + serviceName - + "] to service queue interrupted because of deleted:", - e); - } - } +public class CheckServiceDataEmptyAndAutoStopWatchFilter implements WatchTask.Filter<List<ServiceHealth>> { + + private final static Logger LOGGER = LoggerFactory.getLogger(CheckServiceDataEmptyAndAutoStopWatchFilter.class); + private final String serviceName; + + public CheckServiceDataEmptyAndAutoStopWatchFilter(final String serviceName) { + this.serviceName = serviceName; + } + + @Override + public boolean filter(ConsulResponse<List<ServiceHealth>> object) { + // TODO Auto-generated method stub + boolean result = check(object); + + if (!result) { + // create delete + writeServiceToQueue4Del(); + // stop watch + SyncDataManager.stopWatchService(serviceName); + } + + return result; + } + + // when: + // 1)service had been deleted + // 2)service Health check was not passing + // single service return [],size==0 + // stop this service watching task and create delete event + private boolean check(ConsulResponse<List<ServiceHealth>> object) { + boolean result = true; + + if (object == null || object.getResponse() == null || object.getResponse().size() == 0) { + LOGGER.info("check service-{},its data is empty", serviceName); + return false; + } + + return result; + } + + private void writeServiceToQueue4Del() { + ServiceData<List<ServiceHealth>> data = new ServiceData<List<ServiceHealth>>(); + data.setDataType(ServiceData.DataType.service); + data.setOperate(ServiceData.Operate.delete); + + // tell the subsequent operation the service name which will be deleted + Service service = ImmutableService.builder().id("").port(0).address("").service(serviceName).addTags("") + .createIndex(0).modifyIndex(0).build(); + ServiceHealth serviceHealth = ImmutableServiceHealth.builder().service(service) + .node(ImmutableNode.builder().node("").address("").build()).build(); + List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); + serviceHealthList.add(serviceHealth); + + data.setData(serviceHealthList); + + LOGGER.info("put delete service[" + serviceName + "] to service queue :because of deleted "); + + try { + QueueManager.getInstance().putIn(data); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + LOGGER.warn("put delete service[" + serviceName + "] to service queue interrupted because of deleted:", + e); + } + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilter.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilter.java index 6dfc86a..49f3aa4 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilter.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilter.java @@ -1,24 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; import java.util.ArrayList; import java.util.List; -import org.onap.msb.apiroute.SyncDataManager; import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; import org.onap.msb.apiroute.wrapper.queue.QueueManager; import org.onap.msb.apiroute.wrapper.queue.ServiceData; @@ -29,83 +26,74 @@ import org.slf4j.LoggerFactory; import com.orbitz.consul.model.ConsulResponse; -public class CheckTagAndAutoStopWatchFilter implements - WatchTask.Filter<List<ServiceHealth>> { - - private final static Logger LOGGER = LoggerFactory - .getLogger(CheckTagAndAutoStopWatchFilter.class); - - private final String serviceName; - - public CheckTagAndAutoStopWatchFilter(final String serviceName) { - this.serviceName = serviceName; - } - - // from consul,the response data:List<ServiceHealth> - // filter ServiceHealth list and find the ServiceHealths which satisfy the - // tags conditions - // 1)if all ServiceHealth don't satisfy,create delete event and stop watch - // 2)if have some ServiceHealths satisfy the tags conditions,create update - // event and send these ServiceHealths - @Override - public boolean filter(ConsulResponse<List<ServiceHealth>> object) { - // TODO Auto-generated method stub - - // find #ServiceHealth# which satisfy the tag conditions - List<ServiceHealth> satisfyList = getSatisfyList(object); - - // no satisfied ServiceHealth - if (satisfyList.isEmpty()) { - - LOGGER.info("put delete service[" - + serviceName - + "] to service queue :because of NO tag meet the conditions"); - - // create delete - writeServiceToQueue(object.getResponse(), - ServiceData.Operate.delete); - // stop watch - //SyncDataManager.stopWatchService(serviceName); - return false; - } - - LOGGER.info("put update service[" - + serviceName - + "] to service queue :which tags meet the conditions"); - - // put the satisfy list to queue - writeServiceToQueue(satisfyList, ServiceData.Operate.update); - - return true; - } - - private List<ServiceHealth> getSatisfyList( - ConsulResponse<List<ServiceHealth>> object) { - List<ServiceHealth> satisfyList = new ArrayList<ServiceHealth>(); - for (ServiceHealth health : object.getResponse()) { - - if (ServiceFilter.getInstance().isFilterCheck(health)) { - satisfyList.add(health); - } - } - - return satisfyList; - } - - private void writeServiceToQueue(List<ServiceHealth> serviceData, - Operate operate) { - ServiceData<List<ServiceHealth>> data = new ServiceData<List<ServiceHealth>>(); - data.setOperate(operate); - data.setDataType(ServiceData.DataType.service); - data.setData(serviceData); - - - try { - QueueManager.getInstance().putIn(data); - } catch (InterruptedException e) { - LOGGER.warn("put " + operate + " service[" + serviceName - + "] to service queue interrupted ", e); - } - - } +public class CheckTagAndAutoStopWatchFilter implements WatchTask.Filter<List<ServiceHealth>> { + + private final static Logger LOGGER = LoggerFactory.getLogger(CheckTagAndAutoStopWatchFilter.class); + + private final String serviceName; + + public CheckTagAndAutoStopWatchFilter(final String serviceName) { + this.serviceName = serviceName; + } + + // from consul,the response data:List<ServiceHealth> + // filter ServiceHealth list and find the ServiceHealths which satisfy the + // tags conditions + // 1)if all ServiceHealth don't satisfy,create delete event and stop watch + // 2)if have some ServiceHealths satisfy the tags conditions,create update + // event and send these ServiceHealths + @Override + public boolean filter(ConsulResponse<List<ServiceHealth>> object) { + // TODO Auto-generated method stub + + // find #ServiceHealth# which satisfy the tag conditions + List<ServiceHealth> satisfyList = getSatisfyList(object); + + // no satisfied ServiceHealth + if (satisfyList.isEmpty()) { + + LOGGER.info("put delete service[" + serviceName + + "] to service queue :because of NO tag meet the conditions"); + + // create delete + writeServiceToQueue(object.getResponse(), ServiceData.Operate.delete); + // stop watch + // SyncDataManager.stopWatchService(serviceName); + return false; + } + + LOGGER.info("put update service[" + serviceName + "] to service queue :which tags meet the conditions"); + + // put the satisfy list to queue + writeServiceToQueue(satisfyList, ServiceData.Operate.update); + + return true; + } + + private List<ServiceHealth> getSatisfyList(ConsulResponse<List<ServiceHealth>> object) { + List<ServiceHealth> satisfyList = new ArrayList<ServiceHealth>(); + for (ServiceHealth health : object.getResponse()) { + + if (ServiceFilter.getInstance().isFilterCheck(health)) { + satisfyList.add(health); + } + } + + return satisfyList; + } + + private void writeServiceToQueue(List<ServiceHealth> serviceData, Operate operate) { + ServiceData<List<ServiceHealth>> data = new ServiceData<List<ServiceHealth>>(); + data.setOperate(operate); + data.setDataType(ServiceData.DataType.service); + data.setData(serviceData); + + + try { + QueueManager.getInstance().putIn(data); + } catch (InterruptedException e) { + LOGGER.warn("put " + operate + " service[" + serviceName + "] to service queue interrupted ", e); + } + + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilter.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilter.java index 08c27a7..ccba7c9 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilter.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilter.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -25,39 +23,36 @@ import com.orbitz.consul.model.ConsulResponse; public class ConsulIndexFilter<T> implements WatchTask.Filter<T> { - private final static Logger LOGGER = LoggerFactory - .getLogger(ConsulIndexFilter.class); - - private final AtomicReference<BigInteger> latestIndex = new AtomicReference<BigInteger>( - null); - - @Override - public boolean filter(final ConsulResponse<T> object) { - // TODO Auto-generated method stub - return isChanged(object); - } - - private boolean isChanged(final ConsulResponse<T> consulResponse) { - - if (consulResponse != null && consulResponse.getIndex() != null - && !consulResponse.getIndex().equals(latestIndex.get())) { - - if(LOGGER.isDebugEnabled()){ - //第一次不打印 - if (latestIndex.get()!=null) { - LOGGER.debug("consul index compare:new-" - + consulResponse.getIndex() + " old-" - + latestIndex.get()); - } - - } - - this.latestIndex.set(consulResponse.getIndex()); - return true; - } - - return false; - } - - + private final static Logger LOGGER = LoggerFactory.getLogger(ConsulIndexFilter.class); + + private final AtomicReference<BigInteger> latestIndex = new AtomicReference<BigInteger>(null); + + @Override + public boolean filter(final ConsulResponse<T> object) { + // TODO Auto-generated method stub + return isChanged(object); + } + + private boolean isChanged(final ConsulResponse<T> consulResponse) { + + if (consulResponse != null && consulResponse.getIndex() != null + && !consulResponse.getIndex().equals(latestIndex.get())) { + + if (LOGGER.isDebugEnabled()) { + // 第一次不打印 + if (latestIndex.get() != null) { + LOGGER.debug("consul index compare:new-" + consulResponse.getIndex() + " old-" + + latestIndex.get()); + } + + } + + this.latestIndex.set(consulResponse.getIndex()); + return true; + } + + return false; + } + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilter.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilter.java index 6f90b80..6694b68 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilter.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilter.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -30,107 +28,104 @@ import com.orbitz.consul.model.health.HealthCheck; public class ServiceModifyIndexFilter implements WatchTask.Filter<List<ServiceHealth>> { - private final AtomicReference<ImmutableList<ServiceHealth>> lastResponse = - new AtomicReference<ImmutableList<ServiceHealth>>(ImmutableList.<ServiceHealth>of()); + private final AtomicReference<ImmutableList<ServiceHealth>> lastResponse = + new AtomicReference<ImmutableList<ServiceHealth>>(ImmutableList.<ServiceHealth>of()); - private final static Logger LOGGER = LoggerFactory.getLogger(ServiceModifyIndexFilter.class); + private final static Logger LOGGER = LoggerFactory.getLogger(ServiceModifyIndexFilter.class); - @Override - public boolean filter(ConsulResponse<List<ServiceHealth>> object) { - // TODO Auto-generated method stub + @Override + public boolean filter(ConsulResponse<List<ServiceHealth>> object) { + // TODO Auto-generated method stub - List<ServiceHealth> newList=object.getResponse(); - if(realFilter(newList)){ - lastResponse.set(ImmutableList.copyOf(newList)); - return true; - } - - return false; - } - - private boolean realFilter(List<ServiceHealth> newList) { - // 1)判断list的size,不等则改变 - if (newList.size() != lastResponse.get().size()) { - // 第一次不打印 - if (lastResponse.get().size() != 0) { - LOGGER.info(newList.get(0).getService().getService() - + " instance count is different.new_count:" + newList.size() + " old_count:" - + lastResponse.get().size()); - } - - return true; + List<ServiceHealth> newList = object.getResponse(); + if (realFilter(newList)) { + lastResponse.set(ImmutableList.copyOf(newList)); + return true; + } + + return false; } - - - // 2)循环服务实例判断服务内容和健康检查是否改变 - for (ServiceHealth newData : newList) { - ServiceHealth sameIdOldData = findSameIdInOldList(newData); - // 若在oldlist中不存在,则改变 - if (sameIdOldData == null) { - - LOGGER.info(newData.getService().getId() - + " is a new service instance.the createindex:" - + newData.getService().getCreateIndex() - + " the modifyIndex:" - + newData.getService().getModifyIndex()); - - return true; - } - - // 若在oldlist中存在,则比较ModifyIndex的值和健康检查状态.不等则改变 - if(!compareService(newData,sameIdOldData)){ - LOGGER.info(newData.getService().getId() +" instance is change because of modifyIndex or health check" ); - return true; - } + + private boolean realFilter(List<ServiceHealth> newList) { + // 1)判断list的size,不等则改变 + if (newList.size() != lastResponse.get().size()) { + // 第一次不打印 + if (lastResponse.get().size() != 0) { + LOGGER.info(newList.get(0).getService().getService() + " instance count is different.new_count:" + + newList.size() + " old_count:" + lastResponse.get().size()); + } + + return true; + } + + + // 2)循环服务实例判断服务内容和健康检查是否改变 + for (ServiceHealth newData : newList) { + ServiceHealth sameIdOldData = findSameIdInOldList(newData); + // 若在oldlist中不存在,则改变 + if (sameIdOldData == null) { + + LOGGER.info(newData.getService().getId() + " is a new service instance.the createindex:" + + newData.getService().getCreateIndex() + " the modifyIndex:" + + newData.getService().getModifyIndex()); + + return true; + } + + // 若在oldlist中存在,则比较ModifyIndex的值和健康检查状态.不等则改变 + if (!compareService(newData, sameIdOldData)) { + LOGGER.info(newData.getService().getId() + + " instance is change because of modifyIndex or health check"); + return true; + } + } + + return false; + + } - - return false; - } + private boolean compareService(ServiceHealth oldData, ServiceHealth newData) { + + return compareServiceInfo(oldData.getService(), newData.getService()) + && compareServiceHealthStatus(oldData.getChecks(), newData.getChecks()); + } - private boolean compareService(ServiceHealth oldData,ServiceHealth newData) { - - return compareServiceInfo(oldData.getService(),newData.getService()) && - compareServiceHealthStatus(oldData.getChecks(),newData.getChecks()); - - } - - private boolean compareServiceInfo(Service oldServiceInfo, Service newServiceInfo) { - if (oldServiceInfo.getModifyIndex() != newServiceInfo.getModifyIndex()) { - LOGGER.info(newServiceInfo.getId() + " new_modifyIndex:" - + newServiceInfo.getModifyIndex() + " old_modifyIndex:" - + oldServiceInfo.getModifyIndex()); - return false; + private boolean compareServiceInfo(Service oldServiceInfo, Service newServiceInfo) { + if (oldServiceInfo.getModifyIndex() != newServiceInfo.getModifyIndex()) { + LOGGER.info(newServiceInfo.getId() + " new_modifyIndex:" + newServiceInfo.getModifyIndex() + + " old_modifyIndex:" + oldServiceInfo.getModifyIndex()); + return false; + } + return true; } - return true; - } - - private boolean compareServiceHealthStatus(List<HealthCheck> oldData, List<HealthCheck> newData) { - boolean oldHealthCheck=ServiceFilter.getInstance().isFilterHealthCheck(oldData); - boolean newHealthCheck=ServiceFilter.getInstance().isFilterHealthCheck(newData); - return oldHealthCheck==newHealthCheck; - - } - - - private ServiceHealth findSameIdInOldList(ServiceHealth newData) { - for (ServiceHealth oldData : lastResponse.get()) { - if (oldData.getService().getId().equals(newData.getService().getId())) { - return oldData; - } + + private boolean compareServiceHealthStatus(List<HealthCheck> oldData, List<HealthCheck> newData) { + boolean oldHealthCheck = ServiceFilter.getInstance().isFilterHealthCheck(oldData); + boolean newHealthCheck = ServiceFilter.getInstance().isFilterHealthCheck(newData); + return oldHealthCheck == newHealthCheck; + } - return null; - } - public boolean resetModifyIndex() { - // clear last response - lastResponse.set(ImmutableList.<ServiceHealth>of()); - return true; - } + private ServiceHealth findSameIdInOldList(ServiceHealth newData) { + for (ServiceHealth oldData : lastResponse.get()) { + if (oldData.getService().getId().equals(newData.getService().getId())) { + return oldData; + } + } + + return null; + } + + public boolean resetModifyIndex() { + // clear last response + lastResponse.set(ImmutableList.<ServiceHealth>of()); + return true; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTask.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTask.java index 678bb87..5cf4017 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTask.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTask.java @@ -1,105 +1,88 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; import org.apache.http.HttpEntity; import org.onap.msb.apiroute.wrapper.consulextend.CatalogClient; -import org.onap.msb.apiroute.wrapper.consulextend.cache.ServicesCatalogCache; import org.onap.msb.apiroute.wrapper.consulextend.cache.ConsulCache.Listener; +import org.onap.msb.apiroute.wrapper.consulextend.cache.ServicesCatalogCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.orbitz.consul.option.CatalogOptions; import com.orbitz.consul.option.QueryOptions; -public class WatchCatalogServicesTask extends WatchTask<HttpEntity> { +public class WatchCatalogServicesTask extends WatchTask<HttpEntity> { + + private final static Logger LOGGER = LoggerFactory.getLogger(WatchCatalogServicesTask.class); + + private ServicesCatalogCache servicesCache = null; + + public WatchCatalogServicesTask(final CatalogClient catalogClient, final CatalogOptions catalogOptions, + final QueryOptions queryOptions, final int watchSeconds) { + initCache(catalogClient, catalogOptions, queryOptions, watchSeconds); + } + + public WatchCatalogServicesTask(final CatalogClient catalogClient, final int watchSeconds) { + initCache(catalogClient, CatalogOptions.BLANK, QueryOptions.BLANK, watchSeconds); + } + + public WatchCatalogServicesTask(final CatalogClient catalogClient) { + initCache(catalogClient, CatalogOptions.BLANK, QueryOptions.BLANK, 10); + } + + private ServicesCatalogCache initCache(final CatalogClient catalogClient, final CatalogOptions catalogOptions, + final QueryOptions queryOptions, final int watchSeconds) { + LOGGER.info("************create all services watch task*****************"); + servicesCache = ServicesCatalogCache.newCache(catalogClient, catalogOptions, queryOptions, watchSeconds); + + servicesCache.addListener((Listener<HttpEntity>) new InternalListener()); - private final static Logger LOGGER = LoggerFactory - .getLogger(WatchCatalogServicesTask.class); - - private ServicesCatalogCache servicesCache = null; - - public WatchCatalogServicesTask( - final CatalogClient catalogClient, - final CatalogOptions catalogOptions, - final QueryOptions queryOptions, - final int watchSeconds) - { - initCache(catalogClient,catalogOptions,queryOptions,watchSeconds); - } - - public WatchCatalogServicesTask( - final CatalogClient catalogClient, - final int watchSeconds) - { - initCache(catalogClient,CatalogOptions.BLANK,QueryOptions.BLANK,watchSeconds); - } - - public WatchCatalogServicesTask( - final CatalogClient catalogClient) - { - initCache(catalogClient,CatalogOptions.BLANK,QueryOptions.BLANK,10); - } - - private ServicesCatalogCache initCache(final CatalogClient catalogClient, - final CatalogOptions catalogOptions, - final QueryOptions queryOptions, - final int watchSeconds) { - LOGGER.info("************create all services watch task*****************"); - servicesCache = ServicesCatalogCache.newCache(catalogClient, - catalogOptions, queryOptions, watchSeconds); + return servicesCache; + } - servicesCache - .addListener((Listener<HttpEntity>) new InternalListener()); + @Override + public boolean startWatch() { + // TODO Auto-generated method stub + if (servicesCache != null) { + try { + servicesCache.start(); + LOGGER.info("************start all services watch task*****************"); + return true; + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.warn("start service list watch failed:", e); + } + } - return servicesCache; - } - - @Override - public boolean startWatch() { - // TODO Auto-generated method stub - if(servicesCache!=null) - { - try { - servicesCache.start(); - LOGGER.info("************start all services watch task*****************"); - return true; - } catch (Exception e) { - // TODO Auto-generated catch block - LOGGER.warn("start service list watch failed:", e); - } - } - - return false; - } + return false; + } - @Override - public boolean stopWatch() { - // TODO Auto-generated method stub - if (servicesCache != null) { - try { - servicesCache.stop(); - LOGGER.info("************stop all services watch task*****************"); - return true; - } catch (Exception e) { - // TODO Auto-generated catch block - LOGGER.warn("stop service list watch failed:", e); - } - } - return false; - } + @Override + public boolean stopWatch() { + // TODO Auto-generated method stub + if (servicesCache != null) { + try { + servicesCache.stop(); + LOGGER.info("************stop all services watch task*****************"); + return true; + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.warn("stop service list watch failed:", e); + } + } + return false; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTask.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTask.java index 73a5176..9fad93d 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTask.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTask.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -19,8 +17,8 @@ import java.math.BigInteger; import java.util.List; import org.onap.msb.apiroute.wrapper.consulextend.HealthClient; -import org.onap.msb.apiroute.wrapper.consulextend.cache.ServiceHealthCache; import org.onap.msb.apiroute.wrapper.consulextend.cache.ConsulCache.Listener; +import org.onap.msb.apiroute.wrapper.consulextend.cache.ServiceHealthCache; import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,115 +27,102 @@ import com.orbitz.consul.option.CatalogOptions; import com.orbitz.consul.option.QueryOptions; public class WatchServiceHealthTask extends WatchTask<List<ServiceHealth>> { - private final static Logger LOGGER = LoggerFactory - .getLogger(WatchServiceHealthTask.class); - - private ServiceHealthCache serviceHealthCache = null; - private String serviceName=""; - - public String getServiceName() { - return serviceName; - } - - public WatchServiceHealthTask(final HealthClient healthClient, - final String serviceName,final boolean passing, - final CatalogOptions catalogOptions, final int watchSeconds, - final QueryOptions queryOptions) { - initCache(healthClient, serviceName, passing, catalogOptions, - watchSeconds, queryOptions); - } - - public WatchServiceHealthTask(final HealthClient healthClient, - final String serviceName,final boolean passing, - final int watchSeconds) - - { - initCache(healthClient, serviceName, passing, CatalogOptions.BLANK, - watchSeconds, QueryOptions.BLANK); - } - - public WatchServiceHealthTask(final HealthClient healthClient, - final String serviceName, final int watchSeconds) - - { - initCache(healthClient, serviceName, true, CatalogOptions.BLANK, - watchSeconds, QueryOptions.BLANK); - } - - private ServiceHealthCache initCache(final HealthClient healthClient, - final String serviceName,final boolean passing, - final CatalogOptions catalogOptions, final int watchSeconds, - final QueryOptions queryOptions) { -// LOGGER.info("************create {} watch task*****************",serviceName); - this.serviceName = serviceName; - serviceHealthCache = ServiceHealthCache.newCache(healthClient, - serviceName, passing, catalogOptions, watchSeconds, - queryOptions); - - serviceHealthCache - .addListener((Listener<List<ServiceHealth>>) new InternalListener()); - - return serviceHealthCache; - } - - public boolean startWatch() { - - if(serviceHealthCache!=null) - { - try { - serviceHealthCache.start(); - LOGGER.info("************start {} watch task*****************",serviceName); - return true; - } catch (Exception e) { - // TODO Auto-generated catch block - LOGGER.warn("start service watch failed:", e); - } - } - - return false; - - } - - public boolean stopWatch(){ - if (serviceHealthCache != null) { - try { - serviceHealthCache.stop(); - LOGGER.info("************stop {} watch task*****************",serviceName); - return true; - } catch (Exception e) { - // TODO Auto-generated catch block - LOGGER.warn("stop service watch failed:", e); - } - } - - return false; - } - - - public boolean resetIndex() - { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("reset " + serviceName + " consul index"); - } - - //reset consul index - serviceHealthCache.updateIndex(BigInteger.valueOf(0)); - - - //reset modify index - for (WatchTask.Filter<List<ServiceHealth>> filter : getAllFilters()) { - if (filter instanceof ServiceModifyIndexFilter) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("reset " + serviceName + " modify index"); - } - return ((ServiceModifyIndexFilter) filter).resetModifyIndex(); - } - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("reset modify index.did not find filter:" + serviceName); - } - - return false; - } + private final static Logger LOGGER = LoggerFactory.getLogger(WatchServiceHealthTask.class); + + private ServiceHealthCache serviceHealthCache = null; + private String serviceName = ""; + + public String getServiceName() { + return serviceName; + } + + public WatchServiceHealthTask(final HealthClient healthClient, final String serviceName, final boolean passing, + final CatalogOptions catalogOptions, final int watchSeconds, final QueryOptions queryOptions) { + initCache(healthClient, serviceName, passing, catalogOptions, watchSeconds, queryOptions); + } + + public WatchServiceHealthTask(final HealthClient healthClient, final String serviceName, final boolean passing, + final int watchSeconds) + + { + initCache(healthClient, serviceName, passing, CatalogOptions.BLANK, watchSeconds, QueryOptions.BLANK); + } + + public WatchServiceHealthTask(final HealthClient healthClient, final String serviceName, final int watchSeconds) + + { + initCache(healthClient, serviceName, true, CatalogOptions.BLANK, watchSeconds, QueryOptions.BLANK); + } + + private ServiceHealthCache initCache(final HealthClient healthClient, final String serviceName, + final boolean passing, final CatalogOptions catalogOptions, final int watchSeconds, + final QueryOptions queryOptions) { + // LOGGER.info("************create {} watch task*****************",serviceName); + this.serviceName = serviceName; + serviceHealthCache = ServiceHealthCache.newCache(healthClient, serviceName, passing, catalogOptions, + watchSeconds, queryOptions); + + serviceHealthCache.addListener((Listener<List<ServiceHealth>>) new InternalListener()); + + return serviceHealthCache; + } + + public boolean startWatch() { + + if (serviceHealthCache != null) { + try { + serviceHealthCache.start(); + LOGGER.info("************start {} watch task*****************", serviceName); + return true; + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.warn("start service watch failed:", e); + } + } + + return false; + + } + + public boolean stopWatch() { + if (serviceHealthCache != null) { + try { + serviceHealthCache.stop(); + LOGGER.info("************stop {} watch task*****************", serviceName); + return true; + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.warn("stop service watch failed:", e); + } + } + + return false; + } + + + public boolean resetIndex() { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("reset " + serviceName + " consul index"); + } + + // reset consul index + serviceHealthCache.updateIndex(BigInteger.valueOf(0)); + + + // reset modify index + for (WatchTask.Filter<List<ServiceHealth>> filter : getAllFilters()) { + if (filter instanceof ServiceModifyIndexFilter) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("reset " + serviceName + " modify index"); + } + return ((ServiceModifyIndexFilter) filter).resetModifyIndex(); + } + } + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("reset modify index.did not find filter:" + serviceName); + } + + return false; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchTask.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchTask.java index f565335..f12f95f 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchTask.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchTask.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -24,79 +22,77 @@ import org.slf4j.LoggerFactory; import com.orbitz.consul.model.ConsulResponse; public abstract class WatchTask<T> { - private final CopyOnWriteArrayList<Filter<T>> filters = new CopyOnWriteArrayList<Filter<T>>(); - private final CopyOnWriteArrayList<Handler<T>> handlers = new CopyOnWriteArrayList<Handler<T>>(); - private final static Logger LOGGER = LoggerFactory - .getLogger(WatchTask.class); - - //start - public abstract boolean startWatch(); - - //stop - public abstract boolean stopWatch(); - - // filters - public interface Filter<T> { - public boolean filter(final ConsulResponse<T> object); - } - - public boolean addFilter(Filter<T> filter) { - boolean added = filters.add(filter); - return added; - } - - public void removeAllFilter() { - filters.clear(); - } - - - public final CopyOnWriteArrayList<Filter<T>> getAllFilters(){ - return filters; - } - - // handlers - public interface Handler<T> { - void handle(final ConsulResponse<T> object); - } - - public boolean addHandler(Handler<T> handler) { - boolean added = handlers.add(handler); - return added; - } - - public void removeAllHandler() { - handlers.clear(); - } - - // internal listener - protected class InternalListener implements ConsulCache.Listener<T> { - @Override - public void notify(ConsulResponse<T> newValues) { - - long startTime = System.currentTimeMillis(); - - // filter - for (Filter<T> f : filters) { - // false,return - if (!f.filter(newValues)) { - return; - } - } - - // handle - for (Handler<T> h : handlers) { - h.handle(newValues); - } - - long endTime = System.currentTimeMillis(); - - if(endTime-startTime > 10*1000) - { - LOGGER.info("WatchTask THEAD WORK TIMEOUT"); - } - } - - } + private final CopyOnWriteArrayList<Filter<T>> filters = new CopyOnWriteArrayList<Filter<T>>(); + private final CopyOnWriteArrayList<Handler<T>> handlers = new CopyOnWriteArrayList<Handler<T>>(); + private final static Logger LOGGER = LoggerFactory.getLogger(WatchTask.class); + + // start + public abstract boolean startWatch(); + + // stop + public abstract boolean stopWatch(); + + // filters + public interface Filter<T> { + public boolean filter(final ConsulResponse<T> object); + } + + public boolean addFilter(Filter<T> filter) { + boolean added = filters.add(filter); + return added; + } + + public void removeAllFilter() { + filters.clear(); + } + + + public final CopyOnWriteArrayList<Filter<T>> getAllFilters() { + return filters; + } + + // handlers + public interface Handler<T> { + void handle(final ConsulResponse<T> object); + } + + public boolean addHandler(Handler<T> handler) { + boolean added = handlers.add(handler); + return added; + } + + public void removeAllHandler() { + handlers.clear(); + } + + // internal listener + protected class InternalListener implements ConsulCache.Listener<T> { + @Override + public void notify(ConsulResponse<T> newValues) { + + long startTime = System.currentTimeMillis(); + + // filter + for (Filter<T> f : filters) { + // false,return + if (!f.filter(newValues)) { + return; + } + } + + // handle + for (Handler<T> h : handlers) { + h.handle(newValues); + } + + long endTime = System.currentTimeMillis(); + + if (endTime - startTime > 10 * 1000) { + LOGGER.info("WatchTask THEAD WORK TIMEOUT"); + } + } + + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandler.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandler.java index c4df452..517003a 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandler.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandler.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -24,28 +22,27 @@ import com.orbitz.consul.model.ConsulResponse; public class WriteBufferHandler<T> implements WatchTask.Handler<T> { - private static final Logger LOGGER = LoggerFactory - .getLogger(WriteBufferHandler.class); - private final ServiceData.DataType dataType; - - - public WriteBufferHandler(final ServiceData.DataType dataType) { - this.dataType =dataType; - } - - @Override - public void handle(ConsulResponse<T> object) { - // TODO Auto-generated method stub - ServiceData<T> data = new ServiceData<T>(); - data.setDataType(dataType); - data.setData(object.getResponse()); - - try { - QueueManager.getInstance().putIn(data); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - LOGGER.warn("put data to buffer interrupted:", e); - } - } + private static final Logger LOGGER = LoggerFactory.getLogger(WriteBufferHandler.class); + private final ServiceData.DataType dataType; + + + public WriteBufferHandler(final ServiceData.DataType dataType) { + this.dataType = dataType; + } + + @Override + public void handle(ConsulResponse<T> object) { + // TODO Auto-generated method stub + ServiceData<T> data = new ServiceData<T>(); + data.setDataType(dataType); + data.setData(object.getResponse()); + + try { + QueueManager.getInstance().putIn(data); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + LOGGER.warn("put data to buffer interrupted:", e); + } + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/Service.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/Service.java index cd85955..4d33941 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/Service.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/Service.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.model.health; @@ -30,25 +28,25 @@ import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public abstract class Service { - @JsonProperty("ID") - public abstract String getId(); + @JsonProperty("ID") + public abstract String getId(); - @JsonProperty("Service") - public abstract String getService(); + @JsonProperty("Service") + public abstract String getService(); - @JsonProperty("Tags") - @JsonDeserialize(as = ImmutableList.class, contentAs = String.class) - public abstract List<String> getTags(); + @JsonProperty("Tags") + @JsonDeserialize(as = ImmutableList.class, contentAs = String.class) + public abstract List<String> getTags(); - @JsonProperty("Address") - public abstract String getAddress(); + @JsonProperty("Address") + public abstract String getAddress(); - @JsonProperty("Port") - public abstract int getPort(); + @JsonProperty("Port") + public abstract int getPort(); - @JsonProperty("CreateIndex") - public abstract int getCreateIndex(); + @JsonProperty("CreateIndex") + public abstract int getCreateIndex(); - @JsonProperty("ModifyIndex") - public abstract int getModifyIndex(); + @JsonProperty("ModifyIndex") + public abstract int getModifyIndex(); } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealth.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealth.java index 007836a..1819bd7 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealth.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealth.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.model.health; @@ -26,6 +24,7 @@ import com.orbitz.consul.model.health.Node; import org.immutables.value.Value; import java.util.List; + @Value.Immutable @JsonSerialize(as = ImmutableServiceHealth.class) @JsonDeserialize(as = ImmutableServiceHealth.class) @@ -41,5 +40,5 @@ public abstract class ServiceHealth { @JsonProperty("Checks") @JsonDeserialize(as = ImmutableList.class, contentAs = HealthCheck.class) public abstract List<HealthCheck> getChecks(); - + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/util/Http.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/util/Http.java index f6b9d6c..ce2dc7c 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/util/Http.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/consulextend/util/Http.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.util; @@ -47,250 +45,215 @@ import com.orbitz.consul.option.QueryOptions; import com.orbitz.consul.util.Jackson; public class Http { - private static final Logger LOGGER = LoggerFactory.getLogger(Http.class); - - private final static CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients - .custom().setMaxConnTotal(Integer.MAX_VALUE) - .setMaxConnPerRoute(Integer.MAX_VALUE).build(); - - private static Http instance = null; - - private Http() { - } - - public static Http getInstance() { - if (instance == null) { - instance = new Http(); - httpAsyncClient.start(); - } - - return instance; - } - - // async get data from consul,and handle response immediately - public <T> void asyncGet(String requestURI, - final TypeReference<T> responseType, - final ConsulResponseCallback<T> callback, final Integer... okCodes) { - // LOGGER.info("Async request:"+requestURI); - - httpAsyncClient.execute(new HttpGet(requestURI), - new FutureCallback<HttpResponse>() { - - public void completed(final HttpResponse response) { - callback.onComplete(consulResponse(responseType, - response)); - } - - public void failed(final Exception ex) { - callback.onFailure(ex); - } - - public void cancelled() { - LOGGER.warn("cancelled async request"); - } - }); - } - - // async get data from consul,and handle response delay - public <T> void asyncGetDelayHandle(String requestURI, - final TypeReference<T> responseType, - final ConsulResponseCallback<T> callback, final Integer... okCodes) { - - httpAsyncClient.execute(new HttpGet(requestURI), - new FutureCallback<HttpResponse>() { - - public void completed(final HttpResponse response) { - OriginalConsulResponse<T> originalConsulResponse = new OriginalConsulResponse<T>( - response, responseType); - - //handle not 2xx code - if (!isSuccessful(response)) { - - LOGGER.warn("response statuscode:" - + response.getStatusLine().getStatusCode()); - - callback.onFailure(new ConsulException( - "response statuscode:" - + response.getStatusLine() - .getStatusCode())); - } else { - callback.onDelayComplete(originalConsulResponse); - } - - } - - public void failed(final Exception ex) { - callback.onFailure(ex); - } - - public void cancelled() { - LOGGER.warn("cancelled async request"); - } - }); - } - - public static ConsulResponseHeader consulResponseHeader( - HttpResponse response) { - String indexHeaderValue = response.getFirstHeader("X-Consul-Index") - .getValue(); - String lastContactHeaderValue = response.getFirstHeader( - "X-Consul-Lastcontact").getValue(); - String knownLeaderHeaderValue = response.getFirstHeader( - "X-Consul-Knownleader").getValue(); - - BigInteger index = indexHeaderValue == null ? new BigInteger("0") - : new BigInteger(indexHeaderValue); - long lastContact = lastContactHeaderValue == null ? 0 : Long - .parseLong(lastContactHeaderValue); - boolean knownLeader = knownLeaderHeaderValue == null ? false : Boolean - .parseBoolean(knownLeaderHeaderValue); - - return new ConsulResponseHeader(lastContact, knownLeader, index); - } - - public static <T> ConsulResponse<T> consulResponse( - TypeReference<T> responseType, HttpResponse response) { - - String indexHeaderValue = response.getFirstHeader("X-Consul-Index") - .getValue(); - String lastContactHeaderValue = response.getFirstHeader( - "X-Consul-Lastcontact").getValue(); - String knownLeaderHeaderValue = response.getFirstHeader( - "X-Consul-Knownleader").getValue(); - - BigInteger index = indexHeaderValue == null ? new BigInteger("0") - : new BigInteger(indexHeaderValue); - long lastContact = lastContactHeaderValue == null ? 0 : Long - .parseLong(lastContactHeaderValue); - boolean knownLeader = knownLeaderHeaderValue == null ? false : Boolean - .parseBoolean(knownLeaderHeaderValue); - - ConsulResponse<T> consulResponse = new ConsulResponse<T>(readResponse( - response, responseType), lastContact, knownLeader, index); - return consulResponse; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static <T> T readResponse(HttpResponse response, - TypeReference<T> responseType) { - - // read streamed entity - T object; - - // HttpEntity,read original data. - Type _type = responseType.getType(); - if (_type instanceof Class - && (((Class) _type).isAssignableFrom(HttpEntity.class))) { - object = (T) response.getEntity(); - return object; - } - - // String,read original data. - if (_type instanceof Class - && (((Class) _type).isAssignableFrom(String.class))) { - - try { - - object = (T) IOUtils - .toString(response.getEntity().getContent()); - response.getEntity().getContent().close(); - - } catch (UnsupportedOperationException e) { - object = (T) ""; - LOGGER.warn("covert streamed entity to String exception:", e); - } catch (IOException e) { - object = (T) ""; - LOGGER.warn("covert streamed entity to String exception:", e); - } - - return object; - } - - // change data type - try { - object = Jackson.MAPPER.readValue( - response.getEntity().getContent(), responseType); - } catch (IOException e) { - LOGGER.warn("covert streamed entity to object exception:", e); - object = readDefaultResponse(responseType); - } - - return object; - } - - @SuppressWarnings("unchecked") - public static <T> T readDefaultResponse(TypeReference<T> responseType) { - Type _type = responseType.getType(); - if (_type instanceof ParameterizedType - && ((ParameterizedType) _type).getRawType() == List.class) { - return (T) ImmutableList.of(); - } else if (_type instanceof ParameterizedType - && ((ParameterizedType) _type).getRawType() == Map.class) { - return (T) ImmutableMap.of(); - } else { - // Not sure if this case will be reached, but if it is it'll be nice - // to know - throw new IllegalStateException( - "Cannot determine empty representation for " + _type); - } - } - - public static boolean isSuccessful(HttpResponse response, - Integer... okCodes) { - return HttpStatus.isSuccess(response.getStatusLine().getStatusCode()) - || Sets.newHashSet(okCodes).contains( - response.getStatusLine().getStatusCode()); - } - - public static String optionsFrom(CatalogOptions catalogOptions, - QueryOptions queryOptions) { - String params = ""; - - if (catalogOptions != null) { - Map<String, Object> options = catalogOptions.toQuery(); - - if (options.containsKey("dc")) { - params += "dc=" + options.get("dc"); - } - if (options.containsKey("tag")) { - params += params.isEmpty() ? "" : "&"; - params += "tag=" + options.get("tag"); - } - } - - if (queryOptions != null) { - Map<String, Object> options = queryOptions.toQuery(); - - if (options.containsKey("consistent")) { - params += params.isEmpty() ? "" : "&"; - params += "consistent=" + options.get("consistent"); - } - if (options.containsKey("stale")) { - params += params.isEmpty() ? "" : "&"; - params += "stale=" + options.get("stale"); - } - if (options.containsKey("wait")) { - params += params.isEmpty() ? "" : "&"; - params += "wait=" + options.get("wait"); - } - - if (options.containsKey("index")) { - params += params.isEmpty() ? "" : "&"; - params += "index=" + options.get("index"); - } - if (options.containsKey("token")) { - params += params.isEmpty() ? "" : "&"; - params += "token=" + options.get("token"); - } - if (options.containsKey("near")) { - params += params.isEmpty() ? "" : "&"; - params += "near=" + options.get("near"); - } - if (options.containsKey("dc")) { - params += params.isEmpty() ? "" : "&"; - params += "dc=" + options.get("dc"); - } - } - return params; - } + private static final Logger LOGGER = LoggerFactory.getLogger(Http.class); + + private final static CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom() + .setMaxConnTotal(Integer.MAX_VALUE).setMaxConnPerRoute(Integer.MAX_VALUE).build(); + + private static Http instance = null; + + private Http() {} + + public static Http getInstance() { + if (instance == null) { + instance = new Http(); + httpAsyncClient.start(); + } + + return instance; + } + + // async get data from consul,and handle response immediately + public <T> void asyncGet(String requestURI, final TypeReference<T> responseType, + final ConsulResponseCallback<T> callback, final Integer... okCodes) { + // LOGGER.info("Async request:"+requestURI); + + httpAsyncClient.execute(new HttpGet(requestURI), new FutureCallback<HttpResponse>() { + + public void completed(final HttpResponse response) { + callback.onComplete(consulResponse(responseType, response)); + } + + public void failed(final Exception ex) { + callback.onFailure(ex); + } + + public void cancelled() { + LOGGER.warn("cancelled async request"); + } + }); + } + + // async get data from consul,and handle response delay + public <T> void asyncGetDelayHandle(String requestURI, final TypeReference<T> responseType, + final ConsulResponseCallback<T> callback, final Integer... okCodes) { + + httpAsyncClient.execute(new HttpGet(requestURI), new FutureCallback<HttpResponse>() { + + public void completed(final HttpResponse response) { + OriginalConsulResponse<T> originalConsulResponse = + new OriginalConsulResponse<T>(response, responseType); + + // handle not 2xx code + if (!isSuccessful(response)) { + + LOGGER.warn("response statuscode:" + response.getStatusLine().getStatusCode()); + + callback.onFailure(new ConsulException( + "response statuscode:" + response.getStatusLine().getStatusCode())); + } else { + callback.onDelayComplete(originalConsulResponse); + } + + } + + public void failed(final Exception ex) { + callback.onFailure(ex); + } + + public void cancelled() { + LOGGER.warn("cancelled async request"); + } + }); + } + + public static ConsulResponseHeader consulResponseHeader(HttpResponse response) { + String indexHeaderValue = response.getFirstHeader("X-Consul-Index").getValue(); + String lastContactHeaderValue = response.getFirstHeader("X-Consul-Lastcontact").getValue(); + String knownLeaderHeaderValue = response.getFirstHeader("X-Consul-Knownleader").getValue(); + + BigInteger index = indexHeaderValue == null ? new BigInteger("0") : new BigInteger(indexHeaderValue); + long lastContact = lastContactHeaderValue == null ? 0 : Long.parseLong(lastContactHeaderValue); + boolean knownLeader = knownLeaderHeaderValue == null ? false : Boolean.parseBoolean(knownLeaderHeaderValue); + + return new ConsulResponseHeader(lastContact, knownLeader, index); + } + + public static <T> ConsulResponse<T> consulResponse(TypeReference<T> responseType, HttpResponse response) { + + String indexHeaderValue = response.getFirstHeader("X-Consul-Index").getValue(); + String lastContactHeaderValue = response.getFirstHeader("X-Consul-Lastcontact").getValue(); + String knownLeaderHeaderValue = response.getFirstHeader("X-Consul-Knownleader").getValue(); + + BigInteger index = indexHeaderValue == null ? new BigInteger("0") : new BigInteger(indexHeaderValue); + long lastContact = lastContactHeaderValue == null ? 0 : Long.parseLong(lastContactHeaderValue); + boolean knownLeader = knownLeaderHeaderValue == null ? false : Boolean.parseBoolean(knownLeaderHeaderValue); + + ConsulResponse<T> consulResponse = + new ConsulResponse<T>(readResponse(response, responseType), lastContact, knownLeader, index); + return consulResponse; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static <T> T readResponse(HttpResponse response, TypeReference<T> responseType) { + + // read streamed entity + T object; + + // HttpEntity,read original data. + Type _type = responseType.getType(); + if (_type instanceof Class && (((Class) _type).isAssignableFrom(HttpEntity.class))) { + object = (T) response.getEntity(); + return object; + } + + // String,read original data. + if (_type instanceof Class && (((Class) _type).isAssignableFrom(String.class))) { + + try { + + object = (T) IOUtils.toString(response.getEntity().getContent()); + response.getEntity().getContent().close(); + + } catch (UnsupportedOperationException e) { + object = (T) ""; + LOGGER.warn("covert streamed entity to String exception:", e); + } catch (IOException e) { + object = (T) ""; + LOGGER.warn("covert streamed entity to String exception:", e); + } + + return object; + } + + // change data type + try { + object = Jackson.MAPPER.readValue(response.getEntity().getContent(), responseType); + } catch (IOException e) { + LOGGER.warn("covert streamed entity to object exception:", e); + object = readDefaultResponse(responseType); + } + + return object; + } + + @SuppressWarnings("unchecked") + public static <T> T readDefaultResponse(TypeReference<T> responseType) { + Type _type = responseType.getType(); + if (_type instanceof ParameterizedType && ((ParameterizedType) _type).getRawType() == List.class) { + return (T) ImmutableList.of(); + } else if (_type instanceof ParameterizedType && ((ParameterizedType) _type).getRawType() == Map.class) { + return (T) ImmutableMap.of(); + } else { + // Not sure if this case will be reached, but if it is it'll be nice + // to know + throw new IllegalStateException("Cannot determine empty representation for " + _type); + } + } + + public static boolean isSuccessful(HttpResponse response, Integer... okCodes) { + return HttpStatus.isSuccess(response.getStatusLine().getStatusCode()) + || Sets.newHashSet(okCodes).contains(response.getStatusLine().getStatusCode()); + } + + public static String optionsFrom(CatalogOptions catalogOptions, QueryOptions queryOptions) { + String params = ""; + + if (catalogOptions != null) { + Map<String, Object> options = catalogOptions.toQuery(); + + if (options.containsKey("dc")) { + params += "dc=" + options.get("dc"); + } + if (options.containsKey("tag")) { + params += params.isEmpty() ? "" : "&"; + params += "tag=" + options.get("tag"); + } + } + + if (queryOptions != null) { + Map<String, Object> options = queryOptions.toQuery(); + + if (options.containsKey("consistent")) { + params += params.isEmpty() ? "" : "&"; + params += "consistent=" + options.get("consistent"); + } + if (options.containsKey("stale")) { + params += params.isEmpty() ? "" : "&"; + params += "stale=" + options.get("stale"); + } + if (options.containsKey("wait")) { + params += params.isEmpty() ? "" : "&"; + params += "wait=" + options.get("wait"); + } + + if (options.containsKey("index")) { + params += params.isEmpty() ? "" : "&"; + params += "index=" + options.get("index"); + } + if (options.containsKey("token")) { + params += params.isEmpty() ? "" : "&"; + params += "token=" + options.get("token"); + } + if (options.containsKey("near")) { + params += params.isEmpty() ? "" : "&"; + params += "near=" + options.get("near"); + } + if (options.containsKey("dc")) { + params += params.isEmpty() ? "" : "&"; + params += "dc=" + options.get("dc"); + } + } + return params; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/DAOConstants.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/DAOConstants.java index 8cf2c04..876d5d6 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/DAOConstants.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/DAOConstants.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao; diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/DAOFactory.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/DAOFactory.java index 5836fc1..21d452c 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/DAOFactory.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/DAOFactory.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao; @@ -24,10 +22,11 @@ public class DAOFactory { private static final IRouteDAO routeDAO = new RouteDAOImpl(); private static final IServiceDAO serviceDAO = new ServiceDAOImpl(); - public static IRouteDAO getRouteDAO(){ + public static IRouteDAO getRouteDAO() { return routeDAO; } - public static IServiceDAO getServiceDAO(){ + + public static IServiceDAO getServiceDAO() { return serviceDAO; } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/RedisAccessWrapper.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/RedisAccessWrapper.java index a789c0a..db74a42 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/RedisAccessWrapper.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/RedisAccessWrapper.java @@ -1,46 +1,45 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import org.onap.msb.apiroute.wrapper.util.JedisUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import redis.clients.jedis.Jedis; import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - public class RedisAccessWrapper { private static final Logger LOGGER = LoggerFactory.getLogger(RedisAccessWrapper.class); - //An iteration starts when the cursor is set to 0 + // An iteration starts when the cursor is set to 0 private static final String REDIS_SCAN_POINTER_NEW_ITERATION = "0"; - //An iteration terminated when the cursor returned by the server is 0 + // An iteration terminated when the cursor returned by the server is 0 private static final String REDIS_SCAN_POINTER_ITERATION_END = "0"; private static final int REDIS_SCAN_COUNT = 50; - public static void save(String key,String value) throws Exception { + public static void save(String key, String value) throws Exception { Jedis jedis = null; try { jedis = JedisUtil.borrowJedisInstance(); - jedis.set(key,value); + jedis.set(key, value); } finally { JedisUtil.returnJedisInstance(jedis); } @@ -52,7 +51,7 @@ public class RedisAccessWrapper { try { jedis = JedisUtil.borrowJedisInstance(); value = jedis.get(key); - }finally { + } finally { JedisUtil.returnJedisInstance(jedis); } return value; @@ -88,9 +87,9 @@ public class RedisAccessWrapper { Jedis jedis = null; try { jedis = JedisUtil.borrowJedisInstance(); - for(String key : keySet){ + for (String key : keySet) { String value = jedis.get(key); - if(value !=null && !"".equals(value)){ + if (value != null && !"".equals(value)) { valueList.add(value); } } @@ -106,7 +105,7 @@ public class RedisAccessWrapper { Jedis jedis = null; try { jedis = JedisUtil.borrowJedisInstance(); - for(String key : keySet){ + for (String key : keySet) { long reply = jedis.del(key); replySum = replySum + reply; } @@ -117,12 +116,13 @@ public class RedisAccessWrapper { } /** - * filter the keys according to the given pattern - * using "scan" instead of using "keys", incrementally iterate the keys space + * filter the keys according to the given pattern using "scan" instead of using "keys", + * incrementally iterate the keys space + * * @param pattern the input filter pattern * @return the matched keys set */ - public static Set<String> filterKeys(String pattern) throws Exception{ + public static Set<String> filterKeys(String pattern) throws Exception { long start = System.currentTimeMillis(); Jedis jedis = null; Set<String> filteredKeys = new HashSet<>(); @@ -131,17 +131,17 @@ public class RedisAccessWrapper { scanParams.count(REDIS_SCAN_COUNT); try { jedis = JedisUtil.borrowJedisInstance(); - ScanResult<String> scanResult = jedis.scan(REDIS_SCAN_POINTER_NEW_ITERATION,scanParams); + ScanResult<String> scanResult = jedis.scan(REDIS_SCAN_POINTER_NEW_ITERATION, scanParams); filteredKeys.addAll(scanResult.getResult()); - while(!scanResult.getStringCursor().equals(REDIS_SCAN_POINTER_ITERATION_END)){ - scanResult = jedis.scan(scanResult.getStringCursor(),scanParams); + while (!scanResult.getStringCursor().equals(REDIS_SCAN_POINTER_ITERATION_END)) { + scanResult = jedis.scan(scanResult.getStringCursor(), scanParams); filteredKeys.addAll(scanResult.getResult()); } } finally { JedisUtil.returnJedisInstance(jedis); } long end = System.currentTimeMillis(); - long costTime = end-start; + long costTime = end - start; LOGGER.info("filterKeys " + pattern + " count:" + filteredKeys.size() + " cost: " + costTime); return filteredKeys; } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/IRouteDAO.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/IRouteDAO.java index b4157d4..7a1c310 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/IRouteDAO.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/IRouteDAO.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.route; diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/RouteDAOImpl.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/RouteDAOImpl.java index 29e8066..c365c8c 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/RouteDAOImpl.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/RouteDAOImpl.java @@ -1,22 +1,18 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.route; -import com.fasterxml.jackson.core.JsonProcessingException; - import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -25,17 +21,19 @@ import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; import org.onap.msb.apiroute.wrapper.dao.route.bean.RouteInfo; import org.onap.msb.apiroute.wrapper.util.Jackson; -public class RouteDAOImpl implements IRouteDAO{ +import com.fasterxml.jackson.core.JsonProcessingException; + +public class RouteDAOImpl implements IRouteDAO { public void saveRoute(String key, RouteInfo routeInfo) throws Exception { String routeInfoStr = null; // change orginal url from “/” to empty string accord to the rewrite rule while forwarding - if("/".equals(routeInfo.getSpec().getUrl())){ + if ("/".equals(routeInfo.getSpec().getUrl())) { routeInfo.getSpec().setUrl(""); } try { routeInfoStr = Jackson.MAPPER.writeValueAsString(routeInfo); } catch (JsonProcessingException e) { - throw new Exception("error occurred while parsing RouteInfo to json data",e); + throw new Exception("error occurred while parsing RouteInfo to json data", e); } RedisAccessWrapper.save(key, routeInfoStr); } @@ -48,7 +46,7 @@ public class RouteDAOImpl implements IRouteDAO{ try { routeInfo = Jackson.MAPPER.readValue(routeInfoStr, RouteInfo.class); } catch (IOException e) { - throw new Exception("error occurred while parsing the redis json data to RouteInfo",e); + throw new Exception("error occurred while parsing the redis json data to RouteInfo", e); } return routeInfo; } @@ -62,7 +60,7 @@ public class RouteDAOImpl implements IRouteDAO{ routeInfo = Jackson.MAPPER.readValue(routeInfoStr, RouteInfo.class); routeInfoList.add(routeInfo); } catch (IOException e) { - throw new Exception("error occurred while parsing the redis json data to RouteInfo",e); + throw new Exception("error occurred while parsing the redis json data to RouteInfo", e); } } return routeInfoList; @@ -72,7 +70,7 @@ public class RouteDAOImpl implements IRouteDAO{ return RedisAccessWrapper.delete(key); } - public long deleteMultiRoute(String keyPattern) throws Exception{ + public long deleteMultiRoute(String keyPattern) throws Exception { return RedisAccessWrapper.deleteMultiKeys(keyPattern); } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Metadata.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Metadata.java index 0e0aa7f..3a30d28 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Metadata.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Metadata.java @@ -1,63 +1,55 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.route.bean; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + import com.fasterxml.jackson.annotation.JsonFormat; + import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - @AllArgsConstructor @NoArgsConstructor -@Getter @Setter +@Getter +@Setter public class Metadata { private String name; private String namespace; private String uid = ""; - //@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") - //private Date creationTimestamp; + // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") + // private Date creationTimestamp; @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssXXX") private Date updateTimestamp; private Map labels = new HashMap(); private String[] annotations = null; /* - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Metadata metadata = (Metadata) o; - return Objects.equals(name, metadata.name) && - Objects.equals(namespace, metadata.namespace) && - Objects.equals(uid, metadata.uid) && - //Objects.equals(creationTimestamp, metadata.creationTimestamp) && - Objects.equals(updateTimestamp, metadata.updateTimestamp) && - Objects.equals(labels, metadata.labels) && - Objects.equals(annotations, metadata.annotations); - } - - @Override - public int hashCode() { - //return Objects.hash(name, namespace, uid, creationTimestamp, updateTimestamp, labels, annotations); - return Objects.hash(name, namespace, uid, updateTimestamp, labels, annotations); - } - */ + * @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || + * getClass() != o.getClass()) return false; Metadata metadata = (Metadata) o; return + * Objects.equals(name, metadata.name) && Objects.equals(namespace, metadata.namespace) && + * Objects.equals(uid, metadata.uid) && //Objects.equals(creationTimestamp, + * metadata.creationTimestamp) && Objects.equals(updateTimestamp, metadata.updateTimestamp) && + * Objects.equals(labels, metadata.labels) && Objects.equals(annotations, metadata.annotations); + * } + * + * @Override public int hashCode() { //return Objects.hash(name, namespace, uid, + * creationTimestamp, updateTimestamp, labels, annotations); return Objects.hash(name, + * namespace, uid, updateTimestamp, labels, annotations); } + */ } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Node.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Node.java index d33898f..45a3827 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Node.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Node.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.route.bean; @@ -22,26 +20,18 @@ import lombok.Setter; @AllArgsConstructor @NoArgsConstructor -@Getter @Setter +@Getter +@Setter public class Node { private String ip; private int port; - private int weight=0; + private int weight = 0; /* - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Node node = (Node) o; - return Objects.equals(port, node.port) && - Objects.equals(weight, node.weight) && - Objects.equals(ip, node.ip); - } - - @Override - public int hashCode() { - return Objects.hash(ip, port, weight); - } - */ + * @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || + * getClass() != o.getClass()) return false; Node node = (Node) o; return Objects.equals(port, + * node.port) && Objects.equals(weight, node.weight) && Objects.equals(ip, node.ip); } + * + * @Override public int hashCode() { return Objects.hash(ip, port, weight); } + */ } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/RouteInfo.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/RouteInfo.java index bd329c1..622c471 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/RouteInfo.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/RouteInfo.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.route.bean; @@ -34,61 +32,24 @@ public class RouteInfo { private Spec spec; /** - Example route: - { - "kind" : "route", - "apiVersion" : "v1", - "status" : "1" - "metadata" : { - "name" : "kubernetes", - "namespace" : "default", - "uid" : "0b6f198e-c6ab-11e6-86aa-fa163ee2118b", - "creationTimestamp" : "2016-12-20T11:54:21Z", - "updateTimestamp" : "", - "labels" : { - "component" : "apiserver", - "provider" : "kubernetes" - }, - "annotations" : {} - }, - "spec" : { - "visualRange" : 0, - "url" : "", - "publish_port" : "", - "host" : "", - "apijson" : "", - "apijsontype" : "" - "metricsUrl" : "" - "consulServiceName" : "" - "useOwnUpstream" : "" //是否使用该服务独立的upstream转发 - "publishProtocol" : "", //发布地址使用http还是http协议 - "enable_ssl" : "0|1", //转发时,使用http还是http转发。http:0/https:1 - "controll" : "", //是否可以修改 - "nodes" : [{ - "ip" : 10.10.10.2, - "port" : 8080, - "weight" : "" - } - ], - } -} + * Example route: { "kind" : "route", "apiVersion" : "v1", "status" : "1" "metadata" : { "name" + * : "kubernetes", "namespace" : "default", "uid" : "0b6f198e-c6ab-11e6-86aa-fa163ee2118b", + * "creationTimestamp" : "2016-12-20T11:54:21Z", "updateTimestamp" : "", "labels" : { + * "component" : "apiserver", "provider" : "kubernetes" }, "annotations" : {} }, "spec" : { + * "visualRange" : 0, "url" : "", "publish_port" : "", "host" : "", "apijson" : "", + * "apijsontype" : "" "metricsUrl" : "" "consulServiceName" : "" "useOwnUpstream" : "" + * //是否使用该服务独立的upstream转发 "publishProtocol" : "", //发布地址使用http还是http协议 "enable_ssl" : "0|1", + * //转发时,使用http还是http转发。http:0/https:1 "controll" : "", //是否可以修改 "nodes" : [{ "ip" : 10.10.10.2, + * "port" : 8080, "weight" : "" } ], } } + */ + /* + * @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || + * getClass() != o.getClass()) return false; RouteInfo that = (RouteInfo) o; return + * Objects.equals(kind, that.kind) && Objects.equals(apiVersion, that.apiVersion) && + * Objects.equals(status, that.status) && Objects.equals(metadata, that.metadata) && + * Objects.equals(spec, that.spec); } + * + * @Override public int hashCode() { return Objects.hash(kind, apiVersion, status, metadata, + * spec); } */ - /* - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - RouteInfo that = (RouteInfo) o; - return Objects.equals(kind, that.kind) && - Objects.equals(apiVersion, that.apiVersion) && - Objects.equals(status, that.status) && - Objects.equals(metadata, that.metadata) && - Objects.equals(spec, that.spec); - } - - @Override - public int hashCode() { - return Objects.hash(kind, apiVersion, status, metadata, spec); - } - */ } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Spec.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Spec.java index a2bb3d3..d9445c1 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Spec.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/route/bean/Spec.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.route.bean; @@ -22,7 +20,8 @@ import lombok.Setter; @AllArgsConstructor @NoArgsConstructor -@Getter @Setter +@Getter +@Setter public class Spec { private String visualRange = ""; private String url = ""; @@ -39,29 +38,19 @@ public class Spec { private Node[] nodes; /* - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Spec spec = (Spec) o; - return Objects.equals(enable_ssl, spec.enable_ssl) && - Objects.equals(visualRange, spec.visualRange) && - Objects.equals(url, spec.url) && - Objects.equals(publish_port, spec.publish_port) && - Objects.equals(host, spec.host) && - Objects.equals(apijson, spec.apijson) && - Objects.equals(apijsontype, spec.apijsontype) && - Objects.equals(metricsUrl, spec.metricsUrl) && - Objects.equals(consulServiceName, spec.consulServiceName) && - Objects.equals(useOwnUpstream, spec.useOwnUpstream) && - Objects.equals(publish_protocol, spec.publish_protocol) && - Objects.equals(control, spec.control) && - Arrays.equals(nodes, spec.nodes); - } - - @Override - public int hashCode() { - return Objects.hash(visualRange, url, publish_port, host, apijson, apijsontype, metricsUrl, consulServiceName, useOwnUpstream, publish_protocol, enable_ssl, control, nodes); - } - */ + * @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || + * getClass() != o.getClass()) return false; Spec spec = (Spec) o; return + * Objects.equals(enable_ssl, spec.enable_ssl) && Objects.equals(visualRange, spec.visualRange) + * && Objects.equals(url, spec.url) && Objects.equals(publish_port, spec.publish_port) && + * Objects.equals(host, spec.host) && Objects.equals(apijson, spec.apijson) && + * Objects.equals(apijsontype, spec.apijsontype) && Objects.equals(metricsUrl, spec.metricsUrl) + * && Objects.equals(consulServiceName, spec.consulServiceName) && + * Objects.equals(useOwnUpstream, spec.useOwnUpstream) && Objects.equals(publish_protocol, + * spec.publish_protocol) && Objects.equals(control, spec.control) && Arrays.equals(nodes, + * spec.nodes); } + * + * @Override public int hashCode() { return Objects.hash(visualRange, url, publish_port, host, + * apijson, apijsontype, metricsUrl, consulServiceName, useOwnUpstream, publish_protocol, + * enable_ssl, control, nodes); } + */ } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/IServiceDAO.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/IServiceDAO.java index cd17057..1de2c2c 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/IServiceDAO.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/IServiceDAO.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.service; diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/ServiceDAOImpl.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/ServiceDAOImpl.java index 9ed0455..950963b 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/ServiceDAOImpl.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/ServiceDAOImpl.java @@ -1,22 +1,18 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.service; -import com.fasterxml.jackson.core.JsonProcessingException; - import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -25,13 +21,15 @@ import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; import org.onap.msb.apiroute.wrapper.dao.service.bean.ServiceInfo; import org.onap.msb.apiroute.wrapper.util.Jackson; -public class ServiceDAOImpl implements IServiceDAO{ +import com.fasterxml.jackson.core.JsonProcessingException; + +public class ServiceDAOImpl implements IServiceDAO { public void saveService(String key, ServiceInfo serviceInfo) throws Exception { String serviceInfoStr = null; try { serviceInfoStr = Jackson.MAPPER.writeValueAsString(serviceInfo); } catch (JsonProcessingException e) { - throw new Exception("error occurred while parsing ServiceInfo to json data",e); + throw new Exception("error occurred while parsing ServiceInfo to json data", e); } RedisAccessWrapper.save(key, serviceInfoStr); } @@ -44,7 +42,7 @@ public class ServiceDAOImpl implements IServiceDAO{ try { serviceInfo = Jackson.MAPPER.readValue(serviceInfoStr, ServiceInfo.class); } catch (IOException e) { - throw new Exception("error occurred while parsing the redis json data to ServiceInfo",e); + throw new Exception("error occurred while parsing the redis json data to ServiceInfo", e); } return serviceInfo; } @@ -58,7 +56,7 @@ public class ServiceDAOImpl implements IServiceDAO{ serviceInfo = Jackson.MAPPER.readValue(serviceInfoStr, ServiceInfo.class); routeInfoList.add(serviceInfo); } catch (IOException e) { - throw new Exception("error occurred while parsing the redis json data to ServiceInfo",e); + throw new Exception("error occurred while parsing the redis json data to ServiceInfo", e); } } return routeInfoList; @@ -68,7 +66,7 @@ public class ServiceDAOImpl implements IServiceDAO{ return RedisAccessWrapper.delete(key); } - public long deleteMultiService(String keyPattern) throws Exception{ + public long deleteMultiService(String keyPattern) throws Exception { return RedisAccessWrapper.deleteMultiKeys(keyPattern); } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Metadata.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Metadata.java index ec22592..687c58e 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Metadata.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Metadata.java @@ -1,65 +1,57 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.service.bean; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + import com.fasterxml.jackson.annotation.JsonFormat; + import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - @AllArgsConstructor @NoArgsConstructor -@Getter @Setter +@Getter +@Setter public class Metadata { private String name; private String namespace; private String uid = ""; - //@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") - //private Date creationTimestamp; - // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") + // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") + // private Date creationTimestamp; + // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssXXX") private Date updateTimestamp; private Map labels = new HashMap(); - //private String[] annotations = new String[]{}; + // private String[] annotations = new String[]{}; private String[] annotations = null; /* - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Metadata metadata = (Metadata) o; - return Objects.equals(name, metadata.name) && - Objects.equals(namespace, metadata.namespace) && - Objects.equals(uid, metadata.uid) && - //Objects.equals(creationTimestamp, metadata.creationTimestamp) && - Objects.equals(updateTimestamp, metadata.updateTimestamp) && - Objects.equals(labels, metadata.labels) && - Objects.equals(annotations, metadata.annotations); - } - - @Override - public int hashCode() { - //return Objects.hash(name, namespace, uid, creationTimestamp, updateTimestamp, labels, annotations); - return Objects.hash(name, namespace, uid, updateTimestamp, labels, annotations); - } - */ + * @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || + * getClass() != o.getClass()) return false; Metadata metadata = (Metadata) o; return + * Objects.equals(name, metadata.name) && Objects.equals(namespace, metadata.namespace) && + * Objects.equals(uid, metadata.uid) && //Objects.equals(creationTimestamp, + * metadata.creationTimestamp) && Objects.equals(updateTimestamp, metadata.updateTimestamp) && + * Objects.equals(labels, metadata.labels) && Objects.equals(annotations, metadata.annotations); + * } + * + * @Override public int hashCode() { //return Objects.hash(name, namespace, uid, + * creationTimestamp, updateTimestamp, labels, annotations); return Objects.hash(name, + * namespace, uid, updateTimestamp, labels, annotations); } + */ } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Node.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Node.java index 02c2991..72c8da7 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Node.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Node.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.service.bean; @@ -22,26 +20,18 @@ import lombok.Setter; @AllArgsConstructor @NoArgsConstructor -@Getter @Setter +@Getter +@Setter public class Node { private String ip; private String port; - private int ttl=-1; + private int ttl = -1; /* - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Node node = (Node) o; - return Objects.equals(port, node.port) && - Objects.equals(ttl, node.ttl) && - Objects.equals(ip, node.ip); - } - - @Override - public int hashCode() { - return Objects.hash(ip, port, ttl); - } - */ + * @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || + * getClass() != o.getClass()) return false; Node node = (Node) o; return Objects.equals(port, + * node.port) && Objects.equals(ttl, node.ttl) && Objects.equals(ip, node.ip); } + * + * @Override public int hashCode() { return Objects.hash(ip, port, ttl); } + */ } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/ServiceInfo.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/ServiceInfo.java index 800c77f..72d940d 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/ServiceInfo.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/ServiceInfo.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.service.bean; @@ -34,58 +32,24 @@ public class ServiceInfo { private Spec spec; /** - Example Service: - { - "kind" : "service", - "apiVersion" : "v1", - "metadata" : { - "name" : "kubernetes", - "namespace" : "default", - "uid" : "0b6f198e-c6ab-11e6-86aa-fa163ee2118b", - "creationTimestamp" : "2016-12-20T11:54:21Z", - "labels" : { - "component" : "apiserver", - "provider" : "kubernetes" - }, - "annotations" : {} - }, - "spec" : { - "visualRange" : 0, - "url" : "", - "path" : "", - "publish_port" : "", - "host" : "", - "protocol" : "", - "lb_policy" : "", - "enable_ssl" : "0|1", //转发时,使用http还是http转发。http:0/https:1 - "nodes" : [{ - "ip" : 10.10.10.2, - "port" : 8080, - "ttl" : - } - ], - } - "status" : "" - } - + * Example Service: { "kind" : "service", "apiVersion" : "v1", "metadata" : { "name" : + * "kubernetes", "namespace" : "default", "uid" : "0b6f198e-c6ab-11e6-86aa-fa163ee2118b", + * "creationTimestamp" : "2016-12-20T11:54:21Z", "labels" : { "component" : "apiserver", + * "provider" : "kubernetes" }, "annotations" : {} }, "spec" : { "visualRange" : 0, "url" : "", + * "path" : "", "publish_port" : "", "host" : "", "protocol" : "", "lb_policy" : "", + * "enable_ssl" : "0|1", //转发时,使用http还是http转发。http:0/https:1 "nodes" : [{ "ip" : 10.10.10.2, + * "port" : 8080, "ttl" : } ], } "status" : "" } + * */ - /* - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ServiceInfo that = (ServiceInfo) o; - return Objects.equals(kind, that.kind) && - Objects.equals(apiVersion, that.apiVersion) && - Objects.equals(status, that.status) && - Objects.equals(metadata, that.metadata) && - Objects.equals(spec, that.spec); - } - - @Override - public int hashCode() { - return Objects.hash(kind, apiVersion, status, metadata, spec); - } - */ + /* + * @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || + * getClass() != o.getClass()) return false; ServiceInfo that = (ServiceInfo) o; return + * Objects.equals(kind, that.kind) && Objects.equals(apiVersion, that.apiVersion) && + * Objects.equals(status, that.status) && Objects.equals(metadata, that.metadata) && + * Objects.equals(spec, that.spec); } + * + * @Override public int hashCode() { return Objects.hash(kind, apiVersion, status, metadata, + * spec); } + */ } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Spec.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Spec.java index 4741200..062d868 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Spec.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/dao/service/bean/Spec.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.dao.service.bean; @@ -22,7 +20,8 @@ import lombok.Setter; @AllArgsConstructor @NoArgsConstructor -@Getter @Setter +@Getter +@Setter public class Spec { private String visualRange = ""; private String url = ""; @@ -35,25 +34,15 @@ public class Spec { private Node[] nodes; /* - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Spec spec = (Spec) o; - return Objects.equals(enable_ssl, spec.enable_ssl) && - Objects.equals(visualRange, spec.visualRange) && - Objects.equals(url, spec.url) && - Objects.equals(path, spec.path) && - Objects.equals(publish_port, spec.publish_port) && - Objects.equals(host, spec.host) && - Objects.equals(protocol, spec.protocol) && - Objects.equals(lb_policy, spec.lb_policy) && - Arrays.equals(nodes, spec.nodes); - } - - @Override - public int hashCode() { - return Objects.hash(visualRange, url, path, publish_port, host, protocol, lb_policy, enable_ssl, nodes); - } - */ + * @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || + * getClass() != o.getClass()) return false; Spec spec = (Spec) o; return + * Objects.equals(enable_ssl, spec.enable_ssl) && Objects.equals(visualRange, spec.visualRange) + * && Objects.equals(url, spec.url) && Objects.equals(path, spec.path) && + * Objects.equals(publish_port, spec.publish_port) && Objects.equals(host, spec.host) && + * Objects.equals(protocol, spec.protocol) && Objects.equals(lb_policy, spec.lb_policy) && + * Arrays.equals(nodes, spec.nodes); } + * + * @Override public int hashCode() { return Objects.hash(visualRange, url, path, publish_port, + * host, protocol, lb_policy, enable_ssl, nodes); } + */ } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/BaseQueue.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/BaseQueue.java index 4d77204..f6d7bba 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/BaseQueue.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/BaseQueue.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.queue; @@ -21,31 +19,27 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public abstract class BaseQueue<T> { - - private final List<BlockingQueue<ServiceData<T>>> queueArray= new ArrayList<BlockingQueue<ServiceData<T>>>(); - - public BaseQueue(int queueNum,int queueCapacity) - { - for(int i=0;queueNum>0 && i<queueNum;i++) - { - queueArray.add(new LinkedBlockingQueue<ServiceData<T>>(queueCapacity)); - } - } - - public int getQueneNum(){ - return queueArray.size(); - } - - protected BlockingQueue<ServiceData<T>> getQueue(int index) - { - return queueArray.get(index); - } - - public abstract void put(final ServiceData<T> data) throws InterruptedException; - - public abstract ServiceData<T> take(final int queueIndex) throws InterruptedException; - - - + + private final List<BlockingQueue<ServiceData<T>>> queueArray = new ArrayList<BlockingQueue<ServiceData<T>>>(); + + public BaseQueue(int queueNum, int queueCapacity) { + for (int i = 0; queueNum > 0 && i < queueNum; i++) { + queueArray.add(new LinkedBlockingQueue<ServiceData<T>>(queueCapacity)); + } + } + + public int getQueneNum() { + return queueArray.size(); + } + + protected BlockingQueue<ServiceData<T>> getQueue(int index) { + return queueArray.get(index); + } + + public abstract void put(final ServiceData<T> data) throws InterruptedException; + + public abstract ServiceData<T> take(final int queueIndex) throws InterruptedException; + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/QueueManager.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/QueueManager.java index f959032..ab492b2 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/QueueManager.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/QueueManager.java @@ -1,22 +1,19 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.queue; import java.util.List; -import java.util.Map; import org.apache.http.HttpEntity; import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; @@ -28,53 +25,48 @@ import org.slf4j.LoggerFactory; public class QueueManager { - private static final Logger LOGGER = LoggerFactory - .getLogger(QueueManager.class); + private static final Logger LOGGER = LoggerFactory.getLogger(QueueManager.class); - private final BaseQueue<HttpEntity> serviceListQueue; - private final BaseQueue<List<ServiceHealth>> serviceQueue; + private final BaseQueue<HttpEntity> serviceListQueue; + private final BaseQueue<List<ServiceHealth>> serviceQueue; - private volatile static QueueManager instance = null; + private volatile static QueueManager instance = null; - public static QueueManager getInstance() { - if (instance == null) { - synchronized (QueueManager.class) { - if (instance == null) { - instance = new QueueManager(); - } - } - } - return instance; - } + public static QueueManager getInstance() { + if (instance == null) { + synchronized (QueueManager.class) { + if (instance == null) { + instance = new QueueManager(); + } + } + } + return instance; + } - private QueueManager() { - serviceListQueue = new ServiceListQueue( - RouteUtil.SERVICE_LIST_QUEUE_CAPACITY); - serviceQueue = new ServiceQueue(RouteUtil.SERVICE_DATA_QUEUE_NUM, - RouteUtil.SERVICE_QUEUE_CAPACITY); - } + private QueueManager() { + serviceListQueue = new ServiceListQueue(RouteUtil.SERVICE_LIST_QUEUE_CAPACITY); + serviceQueue = new ServiceQueue(RouteUtil.SERVICE_DATA_QUEUE_NUM, RouteUtil.SERVICE_QUEUE_CAPACITY); + } - public ServiceData<HttpEntity> takeFromServiceListQueue( - int queueIndex) throws InterruptedException { - return serviceListQueue.take(queueIndex); - } + public ServiceData<HttpEntity> takeFromServiceListQueue(int queueIndex) throws InterruptedException { + return serviceListQueue.take(queueIndex); + } - public ServiceData<List<ServiceHealth>> takeFromServiceQueue(int queueIndex) - throws InterruptedException { - return serviceQueue.take(queueIndex); - } + public ServiceData<List<ServiceHealth>> takeFromServiceQueue(int queueIndex) throws InterruptedException { + return serviceQueue.take(queueIndex); + } - @SuppressWarnings("unchecked") - public <T> void putIn(ServiceData<T> data) throws InterruptedException { + @SuppressWarnings("unchecked") + public <T> void putIn(ServiceData<T> data) throws InterruptedException { - if (data.getDataType() == ServiceData.DataType.service_list) { - LOGGER.debug("putIn service_list queue success"); - serviceListQueue.put((ServiceData<HttpEntity>) data); - } else if (data.getDataType() == ServiceData.DataType.service) { - serviceQueue.put((ServiceData<List<ServiceHealth>>) data); - } else { - LOGGER.warn("DATA TYPE NOT SUPPORT:"+data.getDataType()); - } - } + if (data.getDataType() == ServiceData.DataType.service_list) { + LOGGER.debug("putIn service_list queue success"); + serviceListQueue.put((ServiceData<HttpEntity>) data); + } else if (data.getDataType() == ServiceData.DataType.service) { + serviceQueue.put((ServiceData<List<ServiceHealth>>) data); + } else { + LOGGER.warn("DATA TYPE NOT SUPPORT:" + data.getDataType()); + } + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceConsumer.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceConsumer.java index 90a8477..fb8d9a4 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceConsumer.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceConsumer.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.queue; @@ -33,150 +31,153 @@ import org.slf4j.LoggerFactory; public class ServiceConsumer implements Runnable { - private static final Logger LOGGER = LoggerFactory.getLogger(ServiceConsumer.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceConsumer.class); - private boolean isRunning = true; + private boolean isRunning = true; - private int index; - - - private static final int retryCount=3; + private int index; - //缓存服务信息:key:服务名 和对应的版本列表Set<String> - private final Map<String, Set<String>> lastVersionResponse = new HashMap<String, Set<String>>(); - public ServiceConsumer(final int index) { - this.index = index; - } + private static final int retryCount = 3; + // 缓存服务信息:key:服务名 和对应的版本列表Set<String> + private final Map<String, Set<String>> lastVersionResponse = new HashMap<String, Set<String>>(); - public void run() { + public ServiceConsumer(final int index) { + this.index = index; + } - LOGGER.info("run Service Consumer Thread [" + index + "]"); - while (isRunning) { - try { - ServiceData<List<ServiceHealth>> serviceData; + public void run() { - serviceData = QueueManager.getInstance().takeFromServiceQueue(index); + LOGGER.info("run Service Consumer Thread [" + index + "]"); - // LOGGER.info("Service Consumer Thread [" + index + - // "] take out serviceData from Queue successfully"); + while (isRunning) { + try { + ServiceData<List<ServiceHealth>> serviceData; - if (serviceData.getOperate() == ServiceData.Operate.delete) { - // 删除服务 - deleteMicroService(serviceData); - } else { - // 更新服务 - updateMicroService(serviceData); - } - } catch (InterruptedException e) { - LOGGER.error("ServiceConsumer throw InterruptedException: ", e); - Thread.currentThread().interrupt(); - } + serviceData = QueueManager.getInstance().takeFromServiceQueue(index); - } - } + // LOGGER.info("Service Consumer Thread [" + index + + // "] take out serviceData from Queue successfully"); + if (serviceData.getOperate() == ServiceData.Operate.delete) { + // 删除服务 + deleteMicroService(serviceData); + } else { + // 更新服务 + updateMicroService(serviceData); + } + } catch (InterruptedException e) { + LOGGER.error("ServiceConsumer throw InterruptedException: ", e); + Thread.currentThread().interrupt(); + } + } + } - private void deleteMicroService(ServiceData<List<ServiceHealth>> serviceData) { - String serviceName = null; - try { - if (serviceData.getData() == null || serviceData.getData().size() == 0) { - throw new Exception("sysn deleteMicroService is wrong:serviceData is empty"); - } - - serviceName = serviceData.getData().get(0).getService().getService(); -// LOGGER.info("Service Consumer [" + index + "] start to delete MicroService:[serviceName] " -// + serviceName); - //ServiceListCache.removeService(serviceName); - MicroServiceWrapper.getInstance().deleteMicroService4AllVersion(serviceName); - } catch (Exception e) { - LOGGER.error("delete MicroServiceInfo 4AllVersion fail from consul:[serviceName]" + serviceName, e); - //删除失败,重试三次 - for(int i=0;i<retryCount;i++){ - + private void deleteMicroService(ServiceData<List<ServiceHealth>> serviceData) { + String serviceName = null; try { - Thread.sleep(1000); - } catch (InterruptedException ex) { - LOGGER.error("delete MicroServiceInfo 4AllVersion Thread.sleep throw except:" + ex.getMessage()); - } - if(reDeleteMicroService(serviceName)){ - LOGGER.info((i+1) + "/"+retryCount+" : retry to delete MicroServiceInfo success [serviceName]" + serviceName); - break; - } - else{ - LOGGER.error((i+1) + "/"+retryCount+" : retry to delete MicroServiceInfo still fail [serviceName]" + serviceName); + if (serviceData.getData() == null || serviceData.getData().size() == 0) { + throw new Exception("sysn deleteMicroService is wrong:serviceData is empty"); + } + + serviceName = serviceData.getData().get(0).getService().getService(); + // LOGGER.info("Service Consumer [" + index + "] start to delete + // MicroService:[serviceName] " + // + serviceName); + + // ServiceListCache.removeService(serviceName); + MicroServiceWrapper.getInstance().deleteMicroService4AllVersion(serviceName); + + } catch (Exception e) { + LOGGER.error("delete MicroServiceInfo 4AllVersion fail from consul:[serviceName]" + serviceName, e); + // 删除失败,重试三次 + for (int i = 0; i < retryCount; i++) { + + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + LOGGER.error("delete MicroServiceInfo 4AllVersion Thread.sleep throw except:" + ex.getMessage()); + } + if (reDeleteMicroService(serviceName)) { + LOGGER.info((i + 1) + "/" + retryCount + " : retry to delete MicroServiceInfo success [serviceName]" + + serviceName); + break; + } else { + LOGGER.error((i + 1) + "/" + retryCount + + " : retry to delete MicroServiceInfo still fail [serviceName]" + serviceName); + } + } } - } } - } - - private boolean reDeleteMicroService(String serviceName){ - try { - MicroServiceWrapper.getInstance().deleteMicroService4AllVersion(serviceName); - return true; - } catch (Exception e) { - return false; + + private boolean reDeleteMicroService(String serviceName) { + try { + MicroServiceWrapper.getInstance().deleteMicroService4AllVersion(serviceName); + return true; + } catch (Exception e) { + return false; + } } - } - private void updateMicroService(ServiceData<List<ServiceHealth>> serviceData) { + private void updateMicroService(ServiceData<List<ServiceHealth>> serviceData) { - if (serviceData.getData() == null || serviceData.getData().size() == 0) { - LOGGER.warn("sysn updateMicroService is wrong:serviceData is empty "); - return; - } + if (serviceData.getData() == null || serviceData.getData().size() == 0) { + LOGGER.warn("sysn updateMicroService is wrong:serviceData is empty "); + return; + } + + String serviceName = ""; + + try { + + serviceName = serviceData.getData().get(0).getService().getService(); + List<ServiceHealth> serviceNodeList = serviceData.getData(); + + + Map<String, MicroServiceFullInfo> microServiceInfo4version = + ServiceFilter.getInstance().transMicroServiceInfoFromConsul(serviceNodeList); + + // 删除数据库中已不存在的版本号服务信息 + Set<String> newAllVersion = microServiceInfo4version.keySet(); - String serviceName = ""; + if (lastVersionResponse.containsKey(serviceName)) { + Set<String> dbAllVersionSet = lastVersionResponse.get(serviceName); + // Set<String> + // dbAllVersionSet=MicroServiceWrapper.getInstance().getAllVersion(serviceName); + Set<String> delVersionList = CommonUtil.getDiffrent(newAllVersion, dbAllVersionSet); - try { + if (delVersionList.size() > 0) { - serviceName = serviceData.getData().get(0).getService().getService(); - List<ServiceHealth> serviceNodeList = serviceData.getData(); + LOGGER.info("MicroService version is change from consul:[serviceName]" + serviceName + "[version]" + + delVersionList); - Map<String, MicroServiceFullInfo> microServiceInfo4version = - ServiceFilter.getInstance().transMicroServiceInfoFromConsul(serviceNodeList); + for (String version : delVersionList) { + MicroServiceWrapper.getInstance().deleteMicroService(serviceName, version); + } - // 删除数据库中已不存在的版本号服务信息 - Set<String> newAllVersion = microServiceInfo4version.keySet(); + } + } - if (lastVersionResponse.containsKey(serviceName)) { - Set<String> dbAllVersionSet = lastVersionResponse.get(serviceName); - // Set<String> dbAllVersionSet=MicroServiceWrapper.getInstance().getAllVersion(serviceName); - Set<String> delVersionList = CommonUtil.getDiffrent(newAllVersion, dbAllVersionSet); + lastVersionResponse.put(serviceName, newAllVersion); - if (delVersionList.size() > 0) { + for (Map.Entry<String, MicroServiceFullInfo> entry : microServiceInfo4version.entrySet()) { + MicroServiceFullInfo new_microServiceFullInfo = entry.getValue(); + MicroServiceWrapper.getInstance().saveServiceAndnoticeRoute(new_microServiceFullInfo); - LOGGER.info("MicroService version is change from consul:[serviceName]" + serviceName - + "[version]" + delVersionList); + } - for (String version : delVersionList) { - MicroServiceWrapper.getInstance().deleteMicroService(serviceName, version); - } - + } catch (Exception e) { + LOGGER.error("update MicroServiceInfo fail from consul:[serviceName]" + serviceName); + // 更新失败,重置任务服务的modifyIndex,等待重新更新 + RedisHealthCheck.writeCheckFlag = true; + SyncDataManager.resetIndex(serviceName); } - } - - lastVersionResponse.put(serviceName, newAllVersion); - - for (Map.Entry<String, MicroServiceFullInfo> entry : microServiceInfo4version.entrySet()) { - MicroServiceFullInfo new_microServiceFullInfo = entry.getValue(); - MicroServiceWrapper.getInstance().saveServiceAndnoticeRoute(new_microServiceFullInfo); - - } - - - } catch (Exception e) { - LOGGER.error("update MicroServiceInfo fail from consul:[serviceName]" + serviceName); - //更新失败,重置任务服务的modifyIndex,等待重新更新 - RedisHealthCheck.writeCheckFlag = true; - SyncDataManager.resetIndex(serviceName); } - } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceData.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceData.java index be77603..90e8048 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceData.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceData.java @@ -1,68 +1,66 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.queue; public class ServiceData<T> { - public static enum Type { - consul - }; + public static enum Type { + consul + }; - public static enum Operate { - update, delete - }; + public static enum Operate { + update, delete + }; - public static enum DataType { - service_list, service - } + public static enum DataType { + service_list, service + } - private Type type = Type.consul; - private DataType dataType; - private T data; - private Operate operate = Operate.update; + private Type type = Type.consul; + private DataType dataType; + private T data; + private Operate operate = Operate.update; - public Type getType() { - return type; - } + public Type getType() { + return type; + } - public void setType(Type type) { - this.type = type; - } + public void setType(Type type) { + this.type = type; + } - public DataType getDataType() { - return dataType; - } + public DataType getDataType() { + return dataType; + } - public void setDataType(DataType dataType) { - this.dataType = dataType; - } + public void setDataType(DataType dataType) { + this.dataType = dataType; + } - public T getData() { - return data; - } + public T getData() { + return data; + } - public void setData(T data) { - this.data = data; - } + public void setData(T data) { + this.data = data; + } - public Operate getOperate() { - return operate; - } + public Operate getOperate() { + return operate; + } - public void setOperate(Operate operate) { - this.operate = operate; - } + public void setOperate(Operate operate) { + this.operate = operate; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListCache.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListCache.java index 5f178d9..9d3ebbd 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListCache.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListCache.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.queue; @@ -24,26 +22,27 @@ import org.slf4j.LoggerFactory; public class ServiceListCache { - - private static final Logger LOGGER = LoggerFactory.getLogger(ServiceListCache.class); - - private final static AtomicReference<Set<String>> serviceNameList4Cache = new AtomicReference<Set<String>>(new HashSet<String>()); - - public static Set<String> getLatestServiceNamelist() { - return serviceNameList4Cache.get(); - } - - public static void setLatestServiceNamelist(Set<String> newServicenamelist){ - serviceNameList4Cache.set(newServicenamelist); - LOGGER.info("------current total Watch Service Num :"+ newServicenamelist.size()); - } - - public synchronized static void removeService(String serviceName){ - - Set<String> servicenamelist=serviceNameList4Cache.get(); - servicenamelist.remove(serviceName); - serviceNameList4Cache.set(servicenamelist); - LOGGER.info("------current total Watch Service Num :"+ servicenamelist.size()); + + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceListCache.class); + + private final static AtomicReference<Set<String>> serviceNameList4Cache = + new AtomicReference<Set<String>>(new HashSet<String>()); + + public static Set<String> getLatestServiceNamelist() { + return serviceNameList4Cache.get(); + } + + public static void setLatestServiceNamelist(Set<String> newServicenamelist) { + serviceNameList4Cache.set(newServicenamelist); + LOGGER.info("------current total Watch Service Num :" + newServicenamelist.size()); + } + + public synchronized static void removeService(String serviceName) { + + Set<String> servicenamelist = serviceNameList4Cache.get(); + servicenamelist.remove(serviceName); + serviceNameList4Cache.set(servicenamelist); + LOGGER.info("------current total Watch Service Num :" + servicenamelist.size()); } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListConsumer.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListConsumer.java index 617a4e5..c673d78 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListConsumer.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListConsumer.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.queue; @@ -36,189 +34,171 @@ import com.fasterxml.jackson.core.JsonToken; public class ServiceListConsumer implements Runnable { - private static final Logger LOGGER = LoggerFactory - .getLogger(ServiceListConsumer.class); - - private boolean isRunning = true; - - private int index; - - - public ServiceListConsumer() { - this.index = 0; - } - - public void run() { - LOGGER.info("run ServiceList Consumer Thread [" + index + "]"); - - while (isRunning) { - try { - // 取最新一条记录 - ServiceData<HttpEntity> serviceData = QueueManager - .getInstance().takeFromServiceListQueue(index); - LOGGER.debug("ServiceList Consumer Thread [" + index + - "] take out serviceData from Queue successfully"); - - HttpEntity newValues = serviceData.getData(); - - Set<String> newServiceNameList = filterServiceList(newValues); - - if (ServiceListCache.getLatestServiceNamelist().size() == 0) { - boolean initSuccess=initServiceList(newServiceNameList); - if(initSuccess){ - ServiceListCache.setLatestServiceNamelist(newServiceNameList); - } - } else { - updateServiceList(newServiceNameList); - ServiceListCache.setLatestServiceNamelist(newServiceNameList); - } - - - } catch (Exception e) { - LOGGER.error( - "ServiceListConsumer throw Exception: ", e); - } - } - } - - private void startWatchService(String serviceName) { - // start to Watch service nodes - - SyncDataManager.startWatchService(serviceName); - } - - private void updateServiceList(Set<String> newServiceNameList) { - Set<String> registerServiceNameList = CommonUtil.getDiffrent( - ServiceListCache.getLatestServiceNamelist(), newServiceNameList); - - if (registerServiceNameList.size() > 0) { - LOGGER.info("***need to start Watch Service num from consul :" - + registerServiceNameList.size()); - - for (String serviceName : registerServiceNameList) { - startWatchService(serviceName); - } - } - } - - private boolean initServiceList(Set<String> newServiceNameList) { - LOGGER.info("***start to initialize service List when System startup ***"); - - Set<String> dbServiceNameList = MicroServiceWrapper - .getInstance().getAllMicroServiceKey(); - - if(dbServiceNameList==null){ - LOGGER.error("init ServiceList from redis fail "); - return false; - } - - - // 对比删除redis脏数据 - Set<String> delServiceNameList = CommonUtil.getDiffrent( - newServiceNameList, dbServiceNameList); - - LOGGER.info("***need to delete Service num from redis :" - + delServiceNameList.size()); - for (String serviceName : delServiceNameList) { - try { - MicroServiceWrapper.getInstance() - .deleteMicroService4AllVersion(serviceName); - LOGGER.info("delete MicroService success from initialize:[serviceName]" - + serviceName); - - } catch (Exception e) { - LOGGER.error( - "initialize serviceList :Delete MicroServiceInfo serviceName:" - + serviceName + " FAIL : ", e); - } - } - - // 启动同步开启监听全部服务列表 - LOGGER.info("***need to start Watch Service num from initialize :" - + newServiceNameList.size()); - - for (String serviceName : newServiceNameList) { - startWatchService(serviceName); - } - - return true; - - } - - /*private ImmutableSet<String> filterServiceList( - final Map<String, List<String>> serviceList) { - if (serviceList == null || serviceList.isEmpty()) { - return ImmutableSet.of(); - } - - final ImmutableSet.Builder<String> builder = ImmutableSet.builder(); - - for (Map.Entry<String, List<String>> entry : serviceList.entrySet()) { - - String key = entry.getKey(); - if (key != null && !"consul".equals(key)) { - - List<String> value = entry.getValue(); - if (ServiceFilter.getInstance().isFilterService(value)) { - builder.add(key); - } - } - } - - LOGGER.info("consul all service num:" + serviceList.size()); - LOGGER.info("consul filter service num:" + builder.build().size()); - - return builder.build(); - } -*/ - private Set<String> filterServiceList(final HttpEntity serviceList) { - - if (serviceList == null || serviceList.getContentLength() == 0) { - return new HashSet<String>(); - } - - final Set<String> builder = new HashSet<String>(); - - JsonFactory f = new JsonFactory(); - JsonParser jp = null; - List<String> tagList = null; - int inputServiceNum = 0; - try { - jp = f.createParser(serviceList.getContent()); - jp.nextToken(); - while (jp.nextToken() != JsonToken.END_OBJECT) { - String serviceName = jp.getCurrentName(); - inputServiceNum++; - jp.nextToken(); - tagList = new ArrayList<>(); - while (jp.nextToken() != JsonToken.END_ARRAY) { - tagList.add(jp.getText()); - } - - if (serviceName != null && !"consul".equals(serviceName)) { - if (ServiceFilter.getInstance().isFilterService(tagList)) { - builder.add(serviceName); - } - } - } - } catch (IOException e) { - LOGGER.warn("parse service list error",e); - return new HashSet<String>(); - } finally { - try { - jp.close(); - } catch (IOException e) { - LOGGER.warn("parse service list error",e); - return new HashSet<String>(); - } - } - - int latestServiceNum=ServiceListCache.getLatestServiceNamelist().size(); -// if(latestServiceNum!=builder.size()){ - LOGGER.info("[consul] all service num:" + inputServiceNum+ ", filter service num: new——" + builder.size()+" old——"+latestServiceNum); -// } - - return builder; - } + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceListConsumer.class); + + private boolean isRunning = true; + + private int index; + + + public ServiceListConsumer() { + this.index = 0; + } + + public void run() { + LOGGER.info("run ServiceList Consumer Thread [" + index + "]"); + + while (isRunning) { + try { + // 取最新一条记录 + ServiceData<HttpEntity> serviceData = QueueManager.getInstance().takeFromServiceListQueue(index); + LOGGER.debug("ServiceList Consumer Thread [" + index + + "] take out serviceData from Queue successfully"); + + HttpEntity newValues = serviceData.getData(); + + Set<String> newServiceNameList = filterServiceList(newValues); + + if (ServiceListCache.getLatestServiceNamelist().size() == 0) { + boolean initSuccess = initServiceList(newServiceNameList); + if (initSuccess) { + ServiceListCache.setLatestServiceNamelist(newServiceNameList); + } + } else { + updateServiceList(newServiceNameList); + ServiceListCache.setLatestServiceNamelist(newServiceNameList); + } + + + } catch (Exception e) { + LOGGER.error("ServiceListConsumer throw Exception: ", e); + } + } + } + + private void startWatchService(String serviceName) { + // start to Watch service nodes + + SyncDataManager.startWatchService(serviceName); + } + + private void updateServiceList(Set<String> newServiceNameList) { + Set<String> registerServiceNameList = + CommonUtil.getDiffrent(ServiceListCache.getLatestServiceNamelist(), newServiceNameList); + + if (registerServiceNameList.size() > 0) { + LOGGER.info("***need to start Watch Service num from consul :" + registerServiceNameList.size()); + + for (String serviceName : registerServiceNameList) { + startWatchService(serviceName); + } + } + } + + private boolean initServiceList(Set<String> newServiceNameList) { + LOGGER.info("***start to initialize service List when System startup ***"); + + Set<String> dbServiceNameList = MicroServiceWrapper.getInstance().getAllMicroServiceKey(); + + if (dbServiceNameList == null) { + LOGGER.error("init ServiceList from redis fail "); + return false; + } + + + // 对比删除redis脏数据 + Set<String> delServiceNameList = CommonUtil.getDiffrent(newServiceNameList, dbServiceNameList); + + LOGGER.info("***need to delete Service num from redis :" + delServiceNameList.size()); + for (String serviceName : delServiceNameList) { + try { + MicroServiceWrapper.getInstance().deleteMicroService4AllVersion(serviceName); + LOGGER.info("delete MicroService success from initialize:[serviceName]" + serviceName); + + } catch (Exception e) { + LOGGER.error("initialize serviceList :Delete MicroServiceInfo serviceName:" + serviceName + " FAIL : ", + e); + } + } + + // 启动同步开启监听全部服务列表 + LOGGER.info("***need to start Watch Service num from initialize :" + newServiceNameList.size()); + + for (String serviceName : newServiceNameList) { + startWatchService(serviceName); + } + + return true; + + } + + /* + * private ImmutableSet<String> filterServiceList( final Map<String, List<String>> serviceList) + * { if (serviceList == null || serviceList.isEmpty()) { return ImmutableSet.of(); } + * + * final ImmutableSet.Builder<String> builder = ImmutableSet.builder(); + * + * for (Map.Entry<String, List<String>> entry : serviceList.entrySet()) { + * + * String key = entry.getKey(); if (key != null && !"consul".equals(key)) { + * + * List<String> value = entry.getValue(); if + * (ServiceFilter.getInstance().isFilterService(value)) { builder.add(key); } } } + * + * LOGGER.info("consul all service num:" + serviceList.size()); + * LOGGER.info("consul filter service num:" + builder.build().size()); + * + * return builder.build(); } + */ + private Set<String> filterServiceList(final HttpEntity serviceList) { + + if (serviceList == null || serviceList.getContentLength() == 0) { + return new HashSet<String>(); + } + + final Set<String> builder = new HashSet<String>(); + + JsonFactory f = new JsonFactory(); + JsonParser jp = null; + List<String> tagList = null; + int inputServiceNum = 0; + try { + jp = f.createParser(serviceList.getContent()); + jp.nextToken(); + while (jp.nextToken() != JsonToken.END_OBJECT) { + String serviceName = jp.getCurrentName(); + inputServiceNum++; + jp.nextToken(); + tagList = new ArrayList<>(); + while (jp.nextToken() != JsonToken.END_ARRAY) { + tagList.add(jp.getText()); + } + + if (serviceName != null && !"consul".equals(serviceName)) { + if (ServiceFilter.getInstance().isFilterService(tagList)) { + builder.add(serviceName); + } + } + } + } catch (IOException e) { + LOGGER.warn("parse service list error", e); + return new HashSet<String>(); + } finally { + try { + jp.close(); + } catch (IOException e) { + LOGGER.warn("parse service list error", e); + return new HashSet<String>(); + } + } + + int latestServiceNum = ServiceListCache.getLatestServiceNamelist().size(); + // if(latestServiceNum!=builder.size()){ + LOGGER.info("[consul] all service num:" + inputServiceNum + ", filter service num: new——" + builder.size() + + " old——" + latestServiceNum); + // } + + return builder; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListQueue.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListQueue.java index 8c802bd..04e23de 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListQueue.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceListQueue.java @@ -1,22 +1,18 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.queue; -import java.util.List; -import java.util.Map; import java.util.concurrent.BlockingQueue; import org.apache.http.HttpEntity; @@ -25,50 +21,48 @@ import org.slf4j.LoggerFactory; public class ServiceListQueue extends BaseQueue<HttpEntity> { - private static final Logger LOGGER = LoggerFactory.getLogger(ServiceListQueue.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceListQueue.class); - - private static final int SERVICE_LIST_DATA_QUEUE_NUM = 1; - private static final int SERVICE_LIST_QUEUE_INDEX = 0; - public ServiceListQueue(final int queueCapacity) { - super(SERVICE_LIST_DATA_QUEUE_NUM,queueCapacity); - } + private static final int SERVICE_LIST_DATA_QUEUE_NUM = 1; + private static final int SERVICE_LIST_QUEUE_INDEX = 0; - @Override - public void put(ServiceData<HttpEntity> data) throws InterruptedException { - BlockingQueue<ServiceData<HttpEntity>> queue=getQueue(SERVICE_LIST_QUEUE_INDEX); - - int size=queue.size(); -// LOGGER.info("before put ServiceListQueue[size:"+size+"] success :[service num]"+data.getData().size()); - //先清空队列 - if(size>0){ - queue.clear(); + public ServiceListQueue(final int queueCapacity) { + super(SERVICE_LIST_DATA_QUEUE_NUM, queueCapacity); } - //插入记录 - queue.put(data); - - } - @Override - public ServiceData<HttpEntity> take(int queueIndex) throws InterruptedException { - BlockingQueue<ServiceData<HttpEntity>> queue = getQueue(queueIndex); - ServiceData<HttpEntity> serviceData = queue.take(); - return serviceData; - - /*//取队列最新一条数据 - if (queue.isEmpty()) { - LOGGER.info("take a single serviceData from ServiceListQueue "); - return serviceData; - } else { - List<ServiceData<Map<String, List<String>>>> serviceDataList = - new ArrayList<ServiceData<Map<String, List<String>>>>(); - //一次性从BlockingQueue获取所有数据 - queue.drainTo(serviceDataList); - LOGGER.info("take multiple serviceDatas from ServiceListQueue :[num]"+serviceDataList.size()); - return serviceDataList.get(serviceDataList.size() - 1); - }*/ - } + @Override + public void put(ServiceData<HttpEntity> data) throws InterruptedException { + BlockingQueue<ServiceData<HttpEntity>> queue = getQueue(SERVICE_LIST_QUEUE_INDEX); + + int size = queue.size(); + // LOGGER.info("before put ServiceListQueue[size:"+size+"] success :[service + // num]"+data.getData().size()); + // 先清空队列 + if (size > 0) { + queue.clear(); + } + // 插入记录 + queue.put(data); + + } + + @Override + public ServiceData<HttpEntity> take(int queueIndex) throws InterruptedException { + BlockingQueue<ServiceData<HttpEntity>> queue = getQueue(queueIndex); + ServiceData<HttpEntity> serviceData = queue.take(); + return serviceData; + + /* + * //取队列最新一条数据 if (queue.isEmpty()) { + * LOGGER.info("take a single serviceData from ServiceListQueue "); return serviceData; } + * else { List<ServiceData<Map<String, List<String>>>> serviceDataList = new + * ArrayList<ServiceData<Map<String, List<String>>>>(); //一次性从BlockingQueue获取所有数据 + * queue.drainTo(serviceDataList); + * LOGGER.info("take multiple serviceDatas from ServiceListQueue :[num]"+serviceDataList. + * size()); return serviceDataList.get(serviceDataList.size() - 1); } + */ + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceQueue.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceQueue.java index 2282ae9..b1e9144 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceQueue.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/queue/ServiceQueue.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.queue; @@ -24,37 +22,41 @@ import org.slf4j.LoggerFactory; public class ServiceQueue extends BaseQueue<List<ServiceHealth>> { - - private static final Logger LOGGER = LoggerFactory.getLogger(ServiceQueue.class); - - private int queneNum; - - public ServiceQueue(final int queneNum,final int queueCapacity) { - super(queneNum,queueCapacity); - this.queneNum=queneNum; - } - - - @Override - public void put(final ServiceData<List<ServiceHealth>> data) throws InterruptedException { - if(data.getData()==null || data.getData().size()==0) return; - - String serviceName = data.getData().get(0).getService().getService(); - long serviceNameHashCode=serviceName.hashCode() & 0x7FFFFFFF; - int queneIndex=(int) (serviceNameHashCode % queneNum); - -// LOGGER.info("put ServiceQueue [serviceName.hashCode():"+serviceNameHashCode+",queneIndex:"+queneIndex+",queneNum:"+queneNum+"] :[serviceName]"+serviceName); - - BlockingQueue<ServiceData<List<ServiceHealth>>> queue=getQueue(queneIndex); - queue.put(data); - - LOGGER.info("put ServiceQueue[index:"+queneIndex+",size:"+queue.size()+"] success :[serviceName]"+serviceName); - } - - @Override - public ServiceData<List<ServiceHealth>> take(final int queueIndex) throws InterruptedException { - return getQueue(queueIndex).take(); - } - + + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceQueue.class); + + private int queneNum; + + public ServiceQueue(final int queneNum, final int queueCapacity) { + super(queneNum, queueCapacity); + this.queneNum = queneNum; + } + + + @Override + public void put(final ServiceData<List<ServiceHealth>> data) throws InterruptedException { + if (data.getData() == null || data.getData().size() == 0) + return; + + String serviceName = data.getData().get(0).getService().getService(); + long serviceNameHashCode = serviceName.hashCode() & 0x7FFFFFFF; + int queneIndex = (int) (serviceNameHashCode % queneNum); + + // LOGGER.info("put ServiceQueue + // [serviceName.hashCode():"+serviceNameHashCode+",queneIndex:"+queneIndex+",queneNum:"+queneNum+"] + // :[serviceName]"+serviceName); + + BlockingQueue<ServiceData<List<ServiceHealth>>> queue = getQueue(queneIndex); + queue.put(data); + + LOGGER.info("put ServiceQueue[index:" + queneIndex + ",size:" + queue.size() + "] success :[serviceName]" + + serviceName); + } + + @Override + public ServiceData<List<ServiceHealth>> take(final int queueIndex) throws InterruptedException { + return getQueue(queueIndex).take(); + } + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/ApiRouteService.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/ApiRouteService.java index bbe5b86..52b8c31 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/ApiRouteService.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/ApiRouteService.java @@ -1,20 +1,22 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.service; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + import org.onap.msb.apiroute.api.ApiRouteInfo; import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.wrapper.dao.DAOFactory; @@ -26,25 +28,20 @@ import org.onap.msb.apiroute.wrapper.dao.route.bean.Spec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - public class ApiRouteService { private static final Logger LOGGER = LoggerFactory.getLogger(ApiRouteService.class); private static final ApiRouteService instance = new ApiRouteService(); private IRouteDAO routeDAO = DAOFactory.getRouteDAO(); - private ApiRouteService() { - } + private ApiRouteService() {} public static ApiRouteService getInstance() { return instance; } public void saveApiRouteService2Redis(ApiRouteInfo apiRouteInfo, String routeKey) throws Exception { - if(apiRouteInfo ==null){ + if (apiRouteInfo == null) { throw new Exception("input apiRouteInfo to be saved is null!"); } RouteInfo routeInfo = APIRouteAdapter.toRouteInfo(apiRouteInfo); @@ -63,7 +60,7 @@ public class ApiRouteService { ApiRouteInfo apiRouteInfo = null; RouteInfo routeInfo = null; routeInfo = routeDAO.queryRoute(routeKey); - if(routeInfo!=null) { + if (routeInfo != null) { apiRouteInfo = APIRouteAdapter.fromRouteInfo(routeInfo); } return apiRouteInfo; @@ -74,24 +71,25 @@ public class ApiRouteService { List<RouteInfo> routeInfoList = routeDAO.queryMultiRoute(apiRedisKeyPattern); for (RouteInfo routeInfo : routeInfoList) { if (routeInfo != null) { - ApiRouteInfo apiRouteInfo = APIRouteAdapter.fromRouteInfo(routeInfo);; + ApiRouteInfo apiRouteInfo = APIRouteAdapter.fromRouteInfo(routeInfo);; apiRouteList.add(apiRouteInfo); } } return apiRouteList; } - public void updateApiRouteStatus2Redis(String routeKey,String status) throws Exception { + public void updateApiRouteStatus2Redis(String routeKey, String status) throws Exception { RouteInfo routeInfo = routeDAO.queryRoute(routeKey); - if(routeInfo != null){ + if (routeInfo != null) { routeInfo.setStatus(status); - routeDAO.saveRoute(routeKey,routeInfo); - }else{ + routeDAO.saveRoute(routeKey, routeInfo); + } else { throw new Exception("service to be updated is not exist! Update failed"); } } } + class APIRouteAdapter { public static RouteInfo toRouteInfo(ApiRouteInfo apiRouteInfo) { RouteInfo routeInfo = new RouteInfo(); @@ -114,14 +112,14 @@ class APIRouteAdapter { spec.setControl(apiRouteInfo.getControl()); RouteServer[] routeServers = apiRouteInfo.getServers(); List<Node> nodeList = new ArrayList<>(); - for (RouteServer server: routeServers){ + for (RouteServer server : routeServers) { Node node = new Node(); node.setIp(server.getIp()); node.setPort(Integer.parseInt(server.getPort())); node.setWeight(server.getWeight()); nodeList.add(node); } - spec.setNodes(nodeList.toArray(new Node[]{})); + spec.setNodes(nodeList.toArray(new Node[] {})); routeInfo.setSpec(spec); Metadata metadata = new Metadata(); @@ -156,14 +154,14 @@ class APIRouteAdapter { apiRouteInfo.setControl(spec.getControl()); Node[] nodes = spec.getNodes(); List<RouteServer> routeServerList = new ArrayList<>(); - for (Node node: nodes){ + for (Node node : nodes) { RouteServer routeServer = new RouteServer(); routeServer.setIp(node.getIp()); routeServer.setPort(String.valueOf(node.getPort())); routeServer.setWeight(node.getWeight()); routeServerList.add(routeServer); } - apiRouteInfo.setServers(routeServerList.toArray(new RouteServer[]{})); + apiRouteInfo.setServers(routeServerList.toArray(new RouteServer[] {})); Metadata metadata = routeInfo.getMetadata(); apiRouteInfo.setServiceName(metadata.getName()); diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/CustomRouteService.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/CustomRouteService.java index 4106ce7..cb8eb50 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/CustomRouteService.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/CustomRouteService.java @@ -1,20 +1,22 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.service; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + import org.onap.msb.apiroute.api.CustomRouteInfo; import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.wrapper.dao.DAOFactory; @@ -26,10 +28,6 @@ import org.onap.msb.apiroute.wrapper.dao.route.bean.Spec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - public class CustomRouteService { private static final Logger LOGGER = LoggerFactory.getLogger(CustomRouteService.class); @@ -37,15 +35,14 @@ public class CustomRouteService { private static final CustomRouteService instance = new CustomRouteService(); private IRouteDAO routeDAO = DAOFactory.getRouteDAO(); - private CustomRouteService() { - } + private CustomRouteService() {} public static CustomRouteService getInstance() { return instance; } public void saveCustomRouteService2Redis(CustomRouteInfo customRouteInfo, String routeKey) throws Exception { - if(customRouteInfo ==null){ + if (customRouteInfo == null) { throw new Exception("input customRouteInfo to be saved is null!"); } RouteInfo routeInfo = CustomRouteAdapter.toRouteInfo(customRouteInfo); @@ -64,7 +61,7 @@ public class CustomRouteService { CustomRouteInfo customRouteInfo = null; RouteInfo routeInfo = null; routeInfo = routeDAO.queryRoute(routeKey); - if(routeInfo!=null) { + if (routeInfo != null) { customRouteInfo = CustomRouteAdapter.fromRouteInfo(routeInfo); } return customRouteInfo; @@ -82,18 +79,19 @@ public class CustomRouteService { return customRouteList; } - public void updateCustomRouteStatus2Redis(String routeKey,String status) throws Exception { + public void updateCustomRouteStatus2Redis(String routeKey, String status) throws Exception { RouteInfo routeInfo = routeDAO.queryRoute(routeKey); - if(routeInfo != null){ + if (routeInfo != null) { routeInfo.setStatus(status); - routeDAO.saveRoute(routeKey,routeInfo); - }else{ + routeDAO.saveRoute(routeKey, routeInfo); + } else { throw new Exception("service to be updated is not exist! Update failed"); } } } + class CustomRouteAdapter { public static RouteInfo toRouteInfo(CustomRouteInfo customRouteInfo) { RouteInfo routeInfo = new RouteInfo(); @@ -112,14 +110,14 @@ class CustomRouteAdapter { spec.setControl(customRouteInfo.getControl()); RouteServer[] routeServers = customRouteInfo.getServers(); List<Node> nodeList = new ArrayList<>(); - for (RouteServer server: routeServers){ + for (RouteServer server : routeServers) { Node node = new Node(); node.setIp(server.getIp()); node.setPort(Integer.parseInt(server.getPort())); node.setWeight(server.getWeight()); nodeList.add(node); } - spec.setNodes(nodeList.toArray(new Node[]{})); + spec.setNodes(nodeList.toArray(new Node[] {})); routeInfo.setSpec(spec); Metadata metadata = new Metadata(); @@ -149,14 +147,14 @@ class CustomRouteAdapter { customRouteInfo.setControl(spec.getControl()); Node[] nodes = spec.getNodes(); List<RouteServer> routeServerList = new ArrayList<>(); - for (Node node: nodes){ + for (Node node : nodes) { RouteServer routeServer = new RouteServer(); routeServer.setIp(node.getIp()); routeServer.setPort(String.valueOf(node.getPort())); routeServer.setWeight(node.getWeight()); routeServerList.add(routeServer); } - customRouteInfo.setServers(routeServerList.toArray(new RouteServer[]{})); + customRouteInfo.setServers(routeServerList.toArray(new RouteServer[] {})); Metadata metadata = routeInfo.getMetadata(); customRouteInfo.setServiceName(metadata.getName()); diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/IuiRouteService.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/IuiRouteService.java index c602456..87a5e30 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/IuiRouteService.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/IuiRouteService.java @@ -1,20 +1,22 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.service; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + import org.onap.msb.apiroute.api.IuiRouteInfo; import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.wrapper.dao.DAOFactory; @@ -26,10 +28,6 @@ import org.onap.msb.apiroute.wrapper.dao.route.bean.Spec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - public class IuiRouteService { private static final Logger LOGGER = LoggerFactory.getLogger(CustomRouteService.class); @@ -37,15 +35,14 @@ public class IuiRouteService { private static final IuiRouteService instance = new IuiRouteService(); private IRouteDAO routeDAO = DAOFactory.getRouteDAO(); - private IuiRouteService() { - } + private IuiRouteService() {} public static IuiRouteService getInstance() { return instance; } public void saveIuiRouteService2Redis(IuiRouteInfo iuiRouteInfo, String routeKey) throws Exception { - if(iuiRouteInfo ==null){ + if (iuiRouteInfo == null) { throw new Exception("input apiRouteInfo to be saved is null!"); } RouteInfo routeInfo = IuiRouteAdapter.toRouteInfo(iuiRouteInfo); @@ -64,7 +61,7 @@ public class IuiRouteService { IuiRouteInfo iuiRouteInfo = null; RouteInfo routeInfo = null; routeInfo = routeDAO.queryRoute(routeKey); - if(routeInfo!=null) { + if (routeInfo != null) { iuiRouteInfo = IuiRouteAdapter.fromRouteInfo(routeInfo); } return iuiRouteInfo; @@ -82,18 +79,19 @@ public class IuiRouteService { return iuiRouteList; } - public void updateIuiRouteStatus2Redis(String routeKey,String status) throws Exception { + public void updateIuiRouteStatus2Redis(String routeKey, String status) throws Exception { RouteInfo routeInfo = routeDAO.queryRoute(routeKey); - if(routeInfo != null){ + if (routeInfo != null) { routeInfo.setStatus(status); - routeDAO.saveRoute(routeKey,routeInfo); - }else{ + routeDAO.saveRoute(routeKey, routeInfo); + } else { throw new Exception("service to be updated is not exist! Update failed"); } } } + class IuiRouteAdapter { public static RouteInfo toRouteInfo(IuiRouteInfo iuiRouteInfo) { RouteInfo routeInfo = new RouteInfo(); @@ -112,14 +110,14 @@ class IuiRouteAdapter { spec.setControl(iuiRouteInfo.getControl()); RouteServer[] routeServers = iuiRouteInfo.getServers(); List<Node> nodeList = new ArrayList<>(); - for (RouteServer server: routeServers){ + for (RouteServer server : routeServers) { Node node = new Node(); node.setIp(server.getIp()); node.setPort(Integer.parseInt(server.getPort())); node.setWeight(server.getWeight()); nodeList.add(node); } - spec.setNodes(nodeList.toArray(new Node[]{})); + spec.setNodes(nodeList.toArray(new Node[] {})); routeInfo.setSpec(spec); Metadata metadata = new Metadata(); @@ -148,14 +146,14 @@ class IuiRouteAdapter { iuiRouteInfo.setControl(spec.getControl()); Node[] nodes = spec.getNodes(); List<RouteServer> routeServerList = new ArrayList<>(); - for (Node node: nodes){ + for (Node node : nodes) { RouteServer routeServer = new RouteServer(); routeServer.setIp(node.getIp()); routeServer.setPort(String.valueOf(node.getPort())); routeServer.setWeight(node.getWeight()); routeServerList.add(routeServer); } - iuiRouteInfo.setServers(routeServerList.toArray(new RouteServer[]{})); + iuiRouteInfo.setServers(routeServerList.toArray(new RouteServer[] {})); Metadata metadata = routeInfo.getMetadata(); iuiRouteInfo.setServiceName(metadata.getName()); diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullService.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullService.java index 97427c3..0af369e 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullService.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullService.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.service; @@ -34,8 +32,6 @@ import org.onap.msb.apiroute.wrapper.util.MicroServiceUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.ImmutableSet; - public class MicroServiceFullService { private static final Logger LOGGER = LoggerFactory.getLogger(MicroServiceFullService.class); @@ -43,8 +39,7 @@ public class MicroServiceFullService { private IServiceDAO serviceDAO = DAOFactory.getServiceDAO(); - private MicroServiceFullService() { - } + private MicroServiceFullService() {} public static MicroServiceFullService getInstance() { return instance; @@ -57,8 +52,7 @@ public class MicroServiceFullService { List<ServiceInfo> serviceInfoList = serviceDAO.queryMultiService(serviceKeyPattern); for (ServiceInfo serviceInfo : serviceInfoList) { if (serviceInfo != null) { - MicroServiceFullInfo microServiceFullInfo = MicroServiceFullAdapter.fromServiceInfo(serviceInfo); - ; + MicroServiceFullInfo microServiceFullInfo = MicroServiceFullAdapter.fromServiceInfo(serviceInfo);; microServiceFullInfoList.add(microServiceFullInfo); } } @@ -82,29 +76,28 @@ public class MicroServiceFullService { } public void saveMicroServiceInfo2Redis(MicroServiceFullInfo microServiceFullInfo) throws Exception { - if(microServiceFullInfo ==null){ + if (microServiceFullInfo == null) { throw new Exception("input microServiceInfo to be saved is null!"); } ServiceInfo serviceInfo = MicroServiceFullAdapter.toServiceInfo(microServiceFullInfo); - String serviceKey = MicroServiceUtil.getServiceKey(microServiceFullInfo.getServiceName(),microServiceFullInfo.getVersion()); - serviceDAO.saveService(serviceKey,serviceInfo); + String serviceKey = MicroServiceUtil.getServiceKey(microServiceFullInfo.getServiceName(), + microServiceFullInfo.getVersion()); + serviceDAO.saveService(serviceKey, serviceInfo); } - public void updateMicroServiceStatus(String serviceName, String version, String status) - throws Exception { + public void updateMicroServiceStatus(String serviceName, String version, String status) throws Exception { if (null == version || "null".equals(version)) { version = ""; } String serviceKey = MicroServiceUtil.getServiceKey(serviceName, version); ServiceInfo serviceInfo = serviceDAO.queryService(serviceKey); - if(serviceInfo != null){ + if (serviceInfo != null) { serviceInfo.setStatus(status); - serviceDAO.saveService(serviceKey,serviceInfo); + serviceDAO.saveService(serviceKey, serviceInfo); } } - public boolean existsMicroServiceInstance(String serviceName, String version) - throws Exception { + public boolean existsMicroServiceInstance(String serviceName, String version) throws Exception { if (null == version || "null".equals(version)) { version = ""; } @@ -112,8 +105,7 @@ public class MicroServiceFullService { return RedisAccessWrapper.isExist(serviceKey); } - public MicroServiceFullInfo getMicroServiceInstance(String serviceName, String version) - throws Exception { + public MicroServiceFullInfo getMicroServiceInstance(String serviceName, String version) throws Exception { if (null == version || "null".equals(version)) { version = ""; } @@ -123,7 +115,7 @@ public class MicroServiceFullService { ServiceInfo serviceInfo = null; serviceInfo = serviceDAO.queryService(serviceKey); - if(serviceInfo!=null) { + if (serviceInfo != null) { microServiceInfo = MicroServiceFullAdapter.fromServiceInfo(serviceInfo); } return microServiceInfo; @@ -131,6 +123,7 @@ public class MicroServiceFullService { /** * query all the versions of the given ServiceName + * * @param serviceName * @return * @throws Exception @@ -162,6 +155,7 @@ public class MicroServiceFullService { } } + class MicroServiceFullAdapter { public static ServiceInfo toServiceInfo(MicroServiceFullInfo microServiceFullInfo) { ServiceInfo serviceInfo = new ServiceInfo(); @@ -180,13 +174,14 @@ class MicroServiceFullAdapter { Set<org.onap.msb.apiroute.api.Node> nodeSet = microServiceFullInfo.getNodes(); List<org.onap.msb.apiroute.wrapper.dao.service.bean.Node> serviceNodeList = new ArrayList<>(); for (org.onap.msb.apiroute.api.Node node : nodeSet) { - org.onap.msb.apiroute.wrapper.dao.service.bean.Node serviceNode = new org.onap.msb.apiroute.wrapper.dao.service.bean.Node(); + org.onap.msb.apiroute.wrapper.dao.service.bean.Node serviceNode = + new org.onap.msb.apiroute.wrapper.dao.service.bean.Node(); serviceNode.setIp(node.getIp()); serviceNode.setPort(node.getPort()); serviceNode.setTtl(node.getTtl()); serviceNodeList.add(serviceNode); } - spec.setNodes(serviceNodeList.toArray(new org.onap.msb.apiroute.wrapper.dao.service.bean.Node[]{})); + spec.setNodes(serviceNodeList.toArray(new org.onap.msb.apiroute.wrapper.dao.service.bean.Node[] {})); serviceInfo.setSpec(spec); Metadata metadata = new Metadata(); diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/IMicroServiceChangeListener.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/IMicroServiceChangeListener.java index 2abc0be..77dafbd 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/IMicroServiceChangeListener.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/IMicroServiceChangeListener.java @@ -1,34 +1,30 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.serviceListener; import org.onap.msb.apiroute.api.MicroServiceFullInfo; -import org.onap.msb.apiroute.api.Node; public interface IMicroServiceChangeListener { public void onSave(MicroServiceFullInfo microServiceInfo) throws Exception; - + public void onDelete(MicroServiceFullInfo microServiceInfo) throws Exception; - - public void onChange(String serviceName,String version,MicroServiceFullInfo microServiceInfo) throws Exception; - - public void onStatusChange(String serviceName,String version,String host, String protocol,String publish_port, - String status); - + + public void onChange(String serviceName, String version, MicroServiceFullInfo microServiceInfo) throws Exception; + + public void onStatusChange(String serviceName, String version, String host, String protocol, String publish_port, + String status); diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListener.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListener.java index 17bc353..2e1b8ff 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListener.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListener.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.serviceListener; @@ -31,7 +29,6 @@ import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.wrapper.ApiRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.CustomRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.IuiRouteServiceWrapper; -import org.onap.msb.apiroute.wrapper.util.CommonUtil; import org.onap.msb.apiroute.wrapper.util.ConfigUtil; import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; import org.onap.msb.apiroute.wrapper.util.JacksonJsonUtil; @@ -44,751 +41,728 @@ import com.fasterxml.jackson.core.type.TypeReference; public class MicroServiceChangeListener implements IMicroServiceChangeListener { - private static final Logger LOGGER = LoggerFactory.getLogger(MicroServiceChangeListener.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MicroServiceChangeListener.class); - @Override - public void onDelete(MicroServiceFullInfo microServiceInfo) throws Exception { + @Override + public void onDelete(MicroServiceFullInfo microServiceInfo) throws Exception { - String path = microServiceInfo.getPath(); + String path = microServiceInfo.getPath(); - String[] routeWay = ConfigUtil.getInstance().getRouteWay(); + String[] routeWay = ConfigUtil.getInstance().getRouteWay(); - for (int i = 0; i < routeWay.length; i++) { + for (int i = 0; i < routeWay.length; i++) { - if (StringUtils.isNotBlank(path) && !"/".equals(path)) { - // 1.按path优先判断类型 - String host = getHost(microServiceInfo); - deleteServiceByUrl(path, host, microServiceInfo.getPublish_port(), routeWay[i]); - } else { - // 2.1 域名判断url - if (RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay[i]) && ifRootByDomain(microServiceInfo)) { - deleteServiceByDomain4Root(microServiceInfo); - } else { - // 2.2 按协议优先判断类型 - deleteServiceByProtocol(microServiceInfo, routeWay[i]); - } - - } + if (StringUtils.isNotBlank(path) && !"/".equals(path)) { + // 1.按path优先判断类型 + String host = getHost(microServiceInfo); + deleteServiceByUrl(path, host, microServiceInfo.getPublish_port(), routeWay[i]); + } else { + // 2.1 域名判断url + if (RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay[i]) && ifRootByDomain(microServiceInfo)) { + deleteServiceByDomain4Root(microServiceInfo); + } else { + // 2.2 按协议优先判断类型 + deleteServiceByProtocol(microServiceInfo, routeWay[i]); + } + } - } - - } + } - @Override - public void onSave(MicroServiceFullInfo microServiceInfo) throws Exception { + } - String path = microServiceInfo.getPath(); - String[] routeWay = ConfigUtil.getInstance().getRouteWay(); - for (int i = 0; i < routeWay.length; i++) { - // 1.按path优先判断类型 - if (StringUtils.isNotBlank(path) && !"/".equals(path)) { - saveServiceByPath(microServiceInfo, routeWay[i]); - } else { - // 2.1 域名判断url - if (RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay[i]) && ifRootByDomain(microServiceInfo)) { - saveServiceByDomain4Root(microServiceInfo); - } else { - // 2.2 按协议优先判断类型 - saveServiceByProtocol(microServiceInfo, routeWay[i]); + @Override + public void onSave(MicroServiceFullInfo microServiceInfo) throws Exception { + + String path = microServiceInfo.getPath(); + String[] routeWay = ConfigUtil.getInstance().getRouteWay(); + + for (int i = 0; i < routeWay.length; i++) { + // 1.按path优先判断类型 + if (StringUtils.isNotBlank(path) && !"/".equals(path)) { + saveServiceByPath(microServiceInfo, routeWay[i]); + } else { + // 2.1 域名判断url + if (RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay[i]) && ifRootByDomain(microServiceInfo)) { + saveServiceByDomain4Root(microServiceInfo); + } else { + // 2.2 按协议优先判断类型 + saveServiceByProtocol(microServiceInfo, routeWay[i]); + } + } } - } - } - } - - - //判断按协议发布地址是否和注册的URL一致,如果一致发布地址保存为/,否则保存为协议类型的发布地址 - private boolean ifRootByDomain(MicroServiceFullInfo microServiceInfo){ - - - if("/".equals(microServiceInfo.getUrl())) return true; - - String protocol = microServiceInfo.getProtocol(); - String routeName = - RouteUtil.getRouteNameByns(microServiceInfo.getServiceName(), - microServiceInfo.getNamespace()); - String publishUrl=""; - String version = ""; - if (StringUtils.isNotBlank(microServiceInfo.getVersion())) { - version = "/" + microServiceInfo.getVersion(); } - switch (protocol) { - case RouteUtil.PROTOCOL_UI: - publishUrl = "/iui/" + routeName; - break; - case RouteUtil.PROTOCOL_REST: - publishUrl = "/api/" + routeName + version; - break; - case RouteUtil.PROTOCOL_HTTP: - publishUrl = "/" + routeName + version; - break; - } - return publishUrl.equals(microServiceInfo.getUrl()); - - } + // 判断按协议发布地址是否和注册的URL一致,如果一致发布地址保存为/,否则保存为协议类型的发布地址 + private boolean ifRootByDomain(MicroServiceFullInfo microServiceInfo) { - private void saveServiceByDomain4Root(MicroServiceFullInfo microServiceInfo) throws Exception { - CustomRouteInfo[] customRouteInfos = - this.buildCustomRouteInfo(microServiceInfo, "/", RouteUtil.ROUTEWAY_DOMAIN); - for (int i = 0; i < customRouteInfos.length; i++) { - customRouteInfos[i].setUrl("/"); - CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfos[i], - RouteUtil.ROUTEWAY_DOMAIN); - } - } - - private void deleteServiceByDomain4Root(MicroServiceFullInfo microServiceInfo) throws Exception { - - CustomRouteServiceWrapper.getInstance().deleteCustomRoute("/", getHost(microServiceInfo), - microServiceInfo.getPublish_port(), RouteUtil.ROUTEWAY_DOMAIN); - } - - /** - * @Title saveServiceByProtocol - * @Description TODO(按用户注册协议保存服务) - * @param microServiceInfo - * @param routeWay - * @return void - * @throws Exception - */ - private void saveServiceByProtocol(MicroServiceFullInfo microServiceInfo, String routeWay) - throws Exception { - String protocol = microServiceInfo.getProtocol(); - String routeName = - RouteUtil.getRouteNameByns(microServiceInfo.getServiceName(), - microServiceInfo.getNamespace()); - - switch (protocol) { - case RouteUtil.PROTOCOL_UI: - IuiRouteInfo[] iuiRouteInfos = - this.buildIuiRouteInfo(microServiceInfo, routeName, routeWay); - for (int i = 0; i < iuiRouteInfos.length; i++) { - IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(iuiRouteInfos[i], routeWay); - } - break; + if ("/".equals(microServiceInfo.getUrl())) + return true; - case RouteUtil.PROTOCOL_REST: + String protocol = microServiceInfo.getProtocol(); + String routeName = + RouteUtil.getRouteNameByns(microServiceInfo.getServiceName(), microServiceInfo.getNamespace()); + String publishUrl = ""; + String version = ""; + if (StringUtils.isNotBlank(microServiceInfo.getVersion())) { + version = "/" + microServiceInfo.getVersion(); + } - ApiRouteInfo[] apiRouteInfos = - this.buildApiRouteInfo(microServiceInfo, routeName, microServiceInfo.getVersion(), - routeWay); - for (int i = 0; i < apiRouteInfos.length; i++) { - ApiRouteServiceWrapper.getInstance().saveApiRouteInstance(apiRouteInfos[i], routeWay); + switch (protocol) { + case RouteUtil.PROTOCOL_UI: + publishUrl = "/iui/" + routeName; + break; + case RouteUtil.PROTOCOL_REST: + publishUrl = "/api/" + routeName + version; + break; + case RouteUtil.PROTOCOL_HTTP: + publishUrl = "/" + routeName + version; + break; } - break; - case RouteUtil.PROTOCOL_HTTP: + return publishUrl.equals(microServiceInfo.getUrl()); + + } + + + private void saveServiceByDomain4Root(MicroServiceFullInfo microServiceInfo) throws Exception { + CustomRouteInfo[] customRouteInfos = - this.buildCustomRouteInfo(microServiceInfo, - getHttpName(routeName, microServiceInfo.getVersion()), routeWay); + this.buildCustomRouteInfo(microServiceInfo, "/", RouteUtil.ROUTEWAY_DOMAIN); for (int i = 0; i < customRouteInfos.length; i++) { - CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfos[i], - routeWay); + customRouteInfos[i].setUrl("/"); + CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfos[i], + RouteUtil.ROUTEWAY_DOMAIN); } - break; } - } - - /** - * @Title deleteServiceByProtocol - * @Description TODO(按用户注册协议删除服务) - * @param microServiceInfo - * @param routeWay - * @return void - */ - private void deleteServiceByProtocol(MicroServiceFullInfo microServiceInfo, String routeWay) { - String protocol = microServiceInfo.getProtocol(); - String host = getHost(microServiceInfo); - String routeName = - RouteUtil.getRouteNameByns(microServiceInfo.getServiceName(), - microServiceInfo.getNamespace()); - - if (RouteUtil.PROTOCOL_UI.equals(protocol)) { - - if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { - // two ports - String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); - if (publishPorts.length == 2) { - IuiRouteServiceWrapper.getInstance().deleteIuiRoute(routeName, host, publishPorts[0], - routeWay); - IuiRouteServiceWrapper.getInstance().deleteIuiRoute(routeName, host, publishPorts[1], - routeWay); - return; - } - } - - IuiRouteServiceWrapper.getInstance().deleteIuiRoute(routeName, host, - microServiceInfo.getPublish_port(), routeWay); - } else if (RouteUtil.PROTOCOL_REST.equals(protocol)) { - - if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { - // two ports - String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); - if (publishPorts.length == 2) { - ApiRouteServiceWrapper.getInstance().deleteApiRoute(routeName, - microServiceInfo.getVersion(), host, publishPorts[0], routeWay); - ApiRouteServiceWrapper.getInstance().deleteApiRoute(routeName, - microServiceInfo.getVersion(), host, publishPorts[1], routeWay); - return; - } - } - ApiRouteServiceWrapper.getInstance().deleteApiRoute(routeName, microServiceInfo.getVersion(), - host, microServiceInfo.getPublish_port(), routeWay); - } else if (RouteUtil.PROTOCOL_HTTP.equals(protocol)) { - - if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { - // two ports - String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); - if (publishPorts.length == 2) { - CustomRouteServiceWrapper.getInstance().deleteCustomRoute( - getHttpName(routeName, microServiceInfo.getVersion()), host, publishPorts[0], - routeWay); - CustomRouteServiceWrapper.getInstance().deleteCustomRoute( - getHttpName(routeName, microServiceInfo.getVersion()), host, publishPorts[1], - routeWay); - return; - } - } - CustomRouteServiceWrapper.getInstance().deleteCustomRoute( - getHttpName(routeName, microServiceInfo.getVersion()), host, - microServiceInfo.getPublish_port(), routeWay); - } - } - - /** - * @Title saveServiceByUrl - * @Description TODO(按URL地址判断服务协议并保存到路由表) - * @param url - * @param microServiceInfo - * @param routeWay - * @return void - * @throws Exception - */ - private void saveServiceByPath(MicroServiceFullInfo microServiceInfo, String routeWay) - throws Exception { - String redis_serviceName; - String path=microServiceInfo.getPath(); - if (RegExpTestUtil.apiRouteUrlRegExpTest(path)) { - // protocol:"REST" - String[] serviceKey = RegExpTestUtil.apiServiceNameMatch4URL(path); - if (serviceKey == null) { - LOGGER.error("save api Service ByUrl is error:[url]" + path); - return; - } - redis_serviceName = serviceKey[0]; - String redis_serviceVersion = serviceKey[1]; - - ApiRouteInfo[] apiRouteInfos = - this.buildApiRouteInfo(microServiceInfo, redis_serviceName, redis_serviceVersion, - routeWay); - for (int i = 0; i < apiRouteInfos.length; i++) { - ApiRouteServiceWrapper.getInstance().saveApiRouteInstance(apiRouteInfos[i], routeWay); - } - } else if (RegExpTestUtil.iuiRouteUrlRegExpTest(path)) { - // protocol:"UI" - // 根据url获取服务名 - redis_serviceName = RegExpTestUtil.iuiServiceNameMatch4URL(path); - if (redis_serviceName == null) { - LOGGER.error("save iui Service ByUrl is error:[url]" + path); - return; - } - IuiRouteInfo[] iuiRouteInfos = - this.buildIuiRouteInfo(microServiceInfo, redis_serviceName, routeWay); - for (int i = 0; i < iuiRouteInfos.length; i++) { - IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(iuiRouteInfos[i], routeWay); - } - } else { - // protocol:"HTTP"; - redis_serviceName = path; - CustomRouteInfo[] customRouteInfos = - this.buildCustomRouteInfo(microServiceInfo, redis_serviceName, routeWay); - for (int i = 0; i < customRouteInfos.length; i++) { - CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfos[i], - routeWay); - } + + private void deleteServiceByDomain4Root(MicroServiceFullInfo microServiceInfo) throws Exception { + + CustomRouteServiceWrapper.getInstance().deleteCustomRoute("/", getHost(microServiceInfo), + microServiceInfo.getPublish_port(), RouteUtil.ROUTEWAY_DOMAIN); } - } - - /** - * @Title deleteServiceByUrl - * @Description TODO(按URL地址判断服务协议并从路由表删除) - * @param url - * @param host - * @param publish_port - * @param routeWay - * @return void - */ - private void deleteServiceByUrl(String url, String host, String publish_port, String routeWay) { - // 根据Url格式判断服务类型 - String redis_serviceName; - - if (RegExpTestUtil.apiRouteUrlRegExpTest(url)) { - // protocol:"REST" - String[] serviceKey = RegExpTestUtil.apiServiceNameMatch4URL(url); - if (serviceKey == null) { - LOGGER.error("delete api Service ByUrl is error:[url]" + url); - return; - } - - redis_serviceName = serviceKey[0]; - String redis_serviceVersion = serviceKey[1]; - - if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { - // two ports - String[] publishPorts = StringUtils.split(publish_port, "|"); - if (publishPorts.length == 2) { - ApiRouteServiceWrapper.getInstance().deleteApiRoute(redis_serviceName, - redis_serviceVersion, host, publishPorts[0], routeWay); - ApiRouteServiceWrapper.getInstance().deleteApiRoute(redis_serviceName, - redis_serviceVersion, host, publishPorts[1], routeWay); - return; + + /** + * @Title saveServiceByProtocol + * @Description TODO(按用户注册协议保存服务) + * @param microServiceInfo + * @param routeWay + * @return void + * @throws Exception + */ + private void saveServiceByProtocol(MicroServiceFullInfo microServiceInfo, String routeWay) throws Exception { + String protocol = microServiceInfo.getProtocol(); + String routeName = + RouteUtil.getRouteNameByns(microServiceInfo.getServiceName(), microServiceInfo.getNamespace()); + + switch (protocol) { + case RouteUtil.PROTOCOL_UI: + IuiRouteInfo[] iuiRouteInfos = this.buildIuiRouteInfo(microServiceInfo, routeName, routeWay); + for (int i = 0; i < iuiRouteInfos.length; i++) { + IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(iuiRouteInfos[i], routeWay); + } + break; + + case RouteUtil.PROTOCOL_REST: + + ApiRouteInfo[] apiRouteInfos = this.buildApiRouteInfo(microServiceInfo, routeName, + microServiceInfo.getVersion(), routeWay); + for (int i = 0; i < apiRouteInfos.length; i++) { + ApiRouteServiceWrapper.getInstance().saveApiRouteInstance(apiRouteInfos[i], routeWay); + } + break; + case RouteUtil.PROTOCOL_HTTP: + CustomRouteInfo[] customRouteInfos = this.buildCustomRouteInfo(microServiceInfo, + getHttpName(routeName, microServiceInfo.getVersion()), routeWay); + for (int i = 0; i < customRouteInfos.length; i++) { + CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfos[i], routeWay); + } + break; } - } - - ApiRouteServiceWrapper.getInstance().deleteApiRoute(redis_serviceName, redis_serviceVersion, - host, publish_port, routeWay); - - - - } else if (RegExpTestUtil.iuiRouteUrlRegExpTest(url)) { - // protocol:"UI" - // 根据url获取服务名 - redis_serviceName = RegExpTestUtil.iuiServiceNameMatch4URL(url); - if (redis_serviceName == null) { - LOGGER.error("delete iui Service ByUrl is error:[url]" + url); - return; - } - - if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { - // two ports - String[] publishPorts = StringUtils.split(publish_port, "|"); - if (publishPorts.length == 2) { - IuiRouteServiceWrapper.getInstance().deleteIuiRoute(redis_serviceName, host, - publishPorts[0], routeWay); - IuiRouteServiceWrapper.getInstance().deleteIuiRoute(redis_serviceName, host, - publishPorts[1], routeWay); - return; + } + + /** + * @Title deleteServiceByProtocol + * @Description TODO(按用户注册协议删除服务) + * @param microServiceInfo + * @param routeWay + * @return void + */ + private void deleteServiceByProtocol(MicroServiceFullInfo microServiceInfo, String routeWay) { + String protocol = microServiceInfo.getProtocol(); + String host = getHost(microServiceInfo); + String routeName = + RouteUtil.getRouteNameByns(microServiceInfo.getServiceName(), microServiceInfo.getNamespace()); + + if (RouteUtil.PROTOCOL_UI.equals(protocol)) { + + if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { + // two ports + String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); + if (publishPorts.length == 2) { + IuiRouteServiceWrapper.getInstance().deleteIuiRoute(routeName, host, publishPorts[0], routeWay); + IuiRouteServiceWrapper.getInstance().deleteIuiRoute(routeName, host, publishPorts[1], routeWay); + return; + } + } + + IuiRouteServiceWrapper.getInstance().deleteIuiRoute(routeName, host, microServiceInfo.getPublish_port(), + routeWay); + } else if (RouteUtil.PROTOCOL_REST.equals(protocol)) { + + if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { + // two ports + String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); + if (publishPorts.length == 2) { + ApiRouteServiceWrapper.getInstance().deleteApiRoute(routeName, microServiceInfo.getVersion(), host, + publishPorts[0], routeWay); + ApiRouteServiceWrapper.getInstance().deleteApiRoute(routeName, microServiceInfo.getVersion(), host, + publishPorts[1], routeWay); + return; + } + } + ApiRouteServiceWrapper.getInstance().deleteApiRoute(routeName, microServiceInfo.getVersion(), host, + microServiceInfo.getPublish_port(), routeWay); + } else if (RouteUtil.PROTOCOL_HTTP.equals(protocol)) { + + if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { + // two ports + String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); + if (publishPorts.length == 2) { + CustomRouteServiceWrapper.getInstance().deleteCustomRoute( + getHttpName(routeName, microServiceInfo.getVersion()), host, publishPorts[0], + routeWay); + CustomRouteServiceWrapper.getInstance().deleteCustomRoute( + getHttpName(routeName, microServiceInfo.getVersion()), host, publishPorts[1], + routeWay); + return; + } + } + CustomRouteServiceWrapper.getInstance().deleteCustomRoute( + getHttpName(routeName, microServiceInfo.getVersion()), host, + microServiceInfo.getPublish_port(), routeWay); } - } + } - IuiRouteServiceWrapper.getInstance().deleteIuiRoute(redis_serviceName, host, publish_port, - routeWay); + /** + * @Title saveServiceByUrl + * @Description TODO(按URL地址判断服务协议并保存到路由表) + * @param url + * @param microServiceInfo + * @param routeWay + * @return void + * @throws Exception + */ + private void saveServiceByPath(MicroServiceFullInfo microServiceInfo, String routeWay) throws Exception { + String redis_serviceName; + String path = microServiceInfo.getPath(); + if (RegExpTestUtil.apiRouteUrlRegExpTest(path)) { + // protocol:"REST" + String[] serviceKey = RegExpTestUtil.apiServiceNameMatch4URL(path); + if (serviceKey == null) { + LOGGER.error("save api Service ByUrl is error:[url]" + path); + return; + } + redis_serviceName = serviceKey[0]; + String redis_serviceVersion = serviceKey[1]; + + ApiRouteInfo[] apiRouteInfos = + this.buildApiRouteInfo(microServiceInfo, redis_serviceName, redis_serviceVersion, routeWay); + for (int i = 0; i < apiRouteInfos.length; i++) { + ApiRouteServiceWrapper.getInstance().saveApiRouteInstance(apiRouteInfos[i], routeWay); + } + } else if (RegExpTestUtil.iuiRouteUrlRegExpTest(path)) { + // protocol:"UI" + // 根据url获取服务名 + redis_serviceName = RegExpTestUtil.iuiServiceNameMatch4URL(path); + if (redis_serviceName == null) { + LOGGER.error("save iui Service ByUrl is error:[url]" + path); + return; + } + IuiRouteInfo[] iuiRouteInfos = this.buildIuiRouteInfo(microServiceInfo, redis_serviceName, routeWay); + for (int i = 0; i < iuiRouteInfos.length; i++) { + IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(iuiRouteInfos[i], routeWay); + } + } else { + // protocol:"HTTP"; + redis_serviceName = path; + CustomRouteInfo[] customRouteInfos = + this.buildCustomRouteInfo(microServiceInfo, redis_serviceName, routeWay); + for (int i = 0; i < customRouteInfos.length; i++) { + CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfos[i], routeWay); + } + } + } + /** + * @Title deleteServiceByUrl + * @Description TODO(按URL地址判断服务协议并从路由表删除) + * @param url + * @param host + * @param publish_port + * @param routeWay + * @return void + */ + private void deleteServiceByUrl(String url, String host, String publish_port, String routeWay) { + // 根据Url格式判断服务类型 + String redis_serviceName; + + if (RegExpTestUtil.apiRouteUrlRegExpTest(url)) { + // protocol:"REST" + String[] serviceKey = RegExpTestUtil.apiServiceNameMatch4URL(url); + if (serviceKey == null) { + LOGGER.error("delete api Service ByUrl is error:[url]" + url); + return; + } + + redis_serviceName = serviceKey[0]; + String redis_serviceVersion = serviceKey[1]; + + if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { + // two ports + String[] publishPorts = StringUtils.split(publish_port, "|"); + if (publishPorts.length == 2) { + ApiRouteServiceWrapper.getInstance().deleteApiRoute(redis_serviceName, redis_serviceVersion, host, + publishPorts[0], routeWay); + ApiRouteServiceWrapper.getInstance().deleteApiRoute(redis_serviceName, redis_serviceVersion, host, + publishPorts[1], routeWay); + return; + } + } + + ApiRouteServiceWrapper.getInstance().deleteApiRoute(redis_serviceName, redis_serviceVersion, host, + publish_port, routeWay); + + + + } else if (RegExpTestUtil.iuiRouteUrlRegExpTest(url)) { + // protocol:"UI" + // 根据url获取服务名 + redis_serviceName = RegExpTestUtil.iuiServiceNameMatch4URL(url); + if (redis_serviceName == null) { + LOGGER.error("delete iui Service ByUrl is error:[url]" + url); + return; + } + + if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { + // two ports + String[] publishPorts = StringUtils.split(publish_port, "|"); + if (publishPorts.length == 2) { + IuiRouteServiceWrapper.getInstance().deleteIuiRoute(redis_serviceName, host, publishPorts[0], + routeWay); + IuiRouteServiceWrapper.getInstance().deleteIuiRoute(redis_serviceName, host, publishPorts[1], + routeWay); + return; + } + } + + IuiRouteServiceWrapper.getInstance().deleteIuiRoute(redis_serviceName, host, publish_port, routeWay); - } else { - // protocol:"HTTP"; - redis_serviceName = url; - if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { - // two ports - String[] publishPorts = StringUtils.split(publish_port, "|"); - if (publishPorts.length == 2) { - CustomRouteServiceWrapper.getInstance().deleteCustomRoute(redis_serviceName, host, - publishPorts[0], routeWay); - CustomRouteServiceWrapper.getInstance().deleteCustomRoute(redis_serviceName, host, - publishPorts[1], routeWay); - return; + } else { + // protocol:"HTTP"; + redis_serviceName = url; + + if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { + // two ports + String[] publishPorts = StringUtils.split(publish_port, "|"); + if (publishPorts.length == 2) { + CustomRouteServiceWrapper.getInstance().deleteCustomRoute(redis_serviceName, host, publishPorts[0], + routeWay); + CustomRouteServiceWrapper.getInstance().deleteCustomRoute(redis_serviceName, host, publishPorts[1], + routeWay); + return; + } + } + + CustomRouteServiceWrapper.getInstance().deleteCustomRoute(redis_serviceName, host, publish_port, routeWay); } - } - CustomRouteServiceWrapper.getInstance().deleteCustomRoute(redis_serviceName, host, - publish_port, routeWay); } - } + /** + * @Title getCustomName + * @Description TODO(获取HTTP服务路由名) + * @param routeName + * @param version + * @return + * @return String + */ + private String getHttpName(String routeName, String version) { + if (!routeName.startsWith("/")) { + routeName = "/" + routeName; + } - /** - * @Title getCustomName - * @Description TODO(获取HTTP服务路由名) - * @param routeName - * @param version - * @return - * @return String - */ - private String getHttpName(String routeName, String version) { - if (!routeName.startsWith("/")) { - routeName = "/" + routeName; + if (StringUtils.isNotBlank(version)) { + routeName += "/" + version; + } + return routeName; } - if (StringUtils.isNotBlank(version)) { - routeName += "/" + version; - } - return routeName; - } + private String getHost(MicroServiceFullInfo microServiceInfo) { + String host; + if (StringUtils.isNotBlank(microServiceInfo.getHost())) { + host = microServiceInfo.getHost().toLowerCase(); + } else { + // host为空,取默认规则 服务名-ns + host = microServiceInfo.getServiceName().toLowerCase(); + } - private String getHost(MicroServiceFullInfo microServiceInfo) { - String host; - if (StringUtils.isNotBlank(microServiceInfo.getHost())) { - host = microServiceInfo.getHost().toLowerCase(); - } else { - // host为空,取默认规则 服务名-ns - host = microServiceInfo.getServiceName().toLowerCase(); + return host; } - return host; - } - - - - @Override - public void onChange(String serviceName, String version, MicroServiceFullInfo microServiceInfo) - throws Exception { - // TODO Auto-generated method stub - - if (RouteUtil.PROTOCOL_UI.equals(microServiceInfo.getProtocol())) { - IuiRouteInfo[] iuiRouteInfos = - this.buildIuiRouteInfo(microServiceInfo, serviceName, RouteUtil.ROUTEWAY_IP); - for (int i = 0; i < iuiRouteInfos.length; i++) { - IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(iuiRouteInfos[i], - RouteUtil.ROUTEWAY_IP); - } - } else if (RouteUtil.PROTOCOL_REST.equals(microServiceInfo.getProtocol())) { - ApiRouteInfo[] apiRouteInfos = - this.buildApiRouteInfo(microServiceInfo, serviceName, version, RouteUtil.ROUTEWAY_IP); - for (int i = 0; i < apiRouteInfos.length; i++) { - ApiRouteServiceWrapper.getInstance().saveApiRouteInstance(apiRouteInfos[i], - RouteUtil.ROUTEWAY_IP); - } - } else if (RouteUtil.PROTOCOL_HTTP.equals(microServiceInfo.getProtocol())) { - if (!serviceName.startsWith("/")) { - serviceName = "/" + serviceName; - } - CustomRouteInfo[] customRouteInfos = - this.buildCustomRouteInfo(microServiceInfo, serviceName, RouteUtil.ROUTEWAY_IP); - for (int i = 0; i < customRouteInfos.length; i++) { - CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfos[i], - RouteUtil.ROUTEWAY_IP); - } - } - } - @Override - public void onStatusChange(String serviceName, String version, String host, String protocol, - String publish_port, String status) { + @Override + public void onChange(String serviceName, String version, MicroServiceFullInfo microServiceInfo) throws Exception { + // TODO Auto-generated method stub + + if (RouteUtil.PROTOCOL_UI.equals(microServiceInfo.getProtocol())) { + IuiRouteInfo[] iuiRouteInfos = this.buildIuiRouteInfo(microServiceInfo, serviceName, RouteUtil.ROUTEWAY_IP); + for (int i = 0; i < iuiRouteInfos.length; i++) { + IuiRouteServiceWrapper.getInstance().saveIuiRouteInstance(iuiRouteInfos[i], RouteUtil.ROUTEWAY_IP); + } + } else if (RouteUtil.PROTOCOL_REST.equals(microServiceInfo.getProtocol())) { + ApiRouteInfo[] apiRouteInfos = + this.buildApiRouteInfo(microServiceInfo, serviceName, version, RouteUtil.ROUTEWAY_IP); + for (int i = 0; i < apiRouteInfos.length; i++) { + ApiRouteServiceWrapper.getInstance().saveApiRouteInstance(apiRouteInfos[i], RouteUtil.ROUTEWAY_IP); + } + } else if (RouteUtil.PROTOCOL_HTTP.equals(microServiceInfo.getProtocol())) { + if (!serviceName.startsWith("/")) { + serviceName = "/" + serviceName; + } + CustomRouteInfo[] customRouteInfos = + this.buildCustomRouteInfo(microServiceInfo, serviceName, RouteUtil.ROUTEWAY_IP); + for (int i = 0; i < customRouteInfos.length; i++) { + CustomRouteServiceWrapper.getInstance().saveCustomRouteInstance(customRouteInfos[i], + RouteUtil.ROUTEWAY_IP); + } + } + } - // 获取服务的host - if (StringUtils.isBlank(host)) { - host = serviceName.toLowerCase(); - } + @Override + public void onStatusChange(String serviceName, String version, String host, String protocol, String publish_port, + String status) { - if (RouteUtil.PROTOCOL_UI.equals(protocol)) { + // 获取服务的host - IuiRouteServiceWrapper.getInstance().updateIuiRouteStatus(serviceName, host, publish_port, - status, RouteUtil.ROUTEWAY_IP); + if (StringUtils.isBlank(host)) { + host = serviceName.toLowerCase(); + } - } else if (RouteUtil.PROTOCOL_REST.equals(protocol)) { - ApiRouteServiceWrapper.getInstance().updateApiRouteStatus(serviceName, version, host, - publish_port, status, RouteUtil.ROUTEWAY_IP); + if (RouteUtil.PROTOCOL_UI.equals(protocol)) { - } else if (RouteUtil.PROTOCOL_HTTP.equals(protocol)) { - if (!serviceName.startsWith("/")) { - serviceName = "/" + serviceName; - } - CustomRouteServiceWrapper.getInstance().updateCustomRouteStatus(serviceName, host, - publish_port, status, RouteUtil.ROUTEWAY_IP); - } + IuiRouteServiceWrapper.getInstance().updateIuiRouteStatus(serviceName, host, publish_port, status, + RouteUtil.ROUTEWAY_IP); + } else if (RouteUtil.PROTOCOL_REST.equals(protocol)) { + ApiRouteServiceWrapper.getInstance().updateApiRouteStatus(serviceName, version, host, publish_port, status, + RouteUtil.ROUTEWAY_IP); - } + } else if (RouteUtil.PROTOCOL_HTTP.equals(protocol)) { + if (!serviceName.startsWith("/")) { + serviceName = "/" + serviceName; + } + CustomRouteServiceWrapper.getInstance().updateCustomRouteStatus(serviceName, host, publish_port, status, + RouteUtil.ROUTEWAY_IP); + } - private boolean buildRouteHttpProtocol(MicroServiceFullInfo microServiceInfo, String routeWay) { - // Portal协议处理 - if (RouteUtil.CUSTOM_PORTAL.equals(microServiceInfo.getCustom())) { - if (RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay)) { - return true; - } else { - return false; - } } - // 自定义开启SSL处理 - return microServiceInfo.isEnable_ssl(); + private boolean buildRouteHttpProtocol(MicroServiceFullInfo microServiceInfo, String routeWay) { + + // Portal协议处理 + if (RouteUtil.CUSTOM_PORTAL.equals(microServiceInfo.getCustom())) { + if (RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay)) { + return true; + } else { + return false; + } + } - } + // 自定义开启SSL处理 + return microServiceInfo.isEnable_ssl(); + + } - private RouteServer[] buildRouteNodes(MicroServiceFullInfo microServiceInfo, String routeWay) { + private RouteServer[] buildRouteNodes(MicroServiceFullInfo microServiceInfo, String routeWay) { + + // 针对custom=portal场景的域名路由使用apigateway发布地址作为node + if (RouteUtil.CUSTOM_PORTAL.equals(microServiceInfo.getCustom())) { + if (RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay)) { + + String discoverServiceName = RouteUtil.getRouteNameByns(microServiceInfo.getServiceName(), + microServiceInfo.getNamespace()); + List<Node> publishNodes = getPublishNodes(discoverServiceName, microServiceInfo.getVersion(), + microServiceInfo.getNamespace()); + if (publishNodes != null && publishNodes.size() > 0) { + RouteServer[] routeServers = new RouteServer[publishNodes.size()]; + int i = 0; + for (Node node : publishNodes) { + RouteServer routeServer = new RouteServer(node.getIp(), node.getPort()); + routeServers[i] = routeServer; + i++; + } + return routeServers; + } + } + } - // 针对custom=portal场景的域名路由使用apigateway发布地址作为node - if (RouteUtil.CUSTOM_PORTAL.equals(microServiceInfo.getCustom())) { - if (RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay)) { - String discoverServiceName = - RouteUtil.getRouteNameByns(microServiceInfo.getServiceName(), - microServiceInfo.getNamespace()); - List<Node> publishNodes = - getPublishNodes(discoverServiceName, microServiceInfo.getVersion(), - microServiceInfo.getNamespace()); - if (publishNodes != null && publishNodes.size() > 0) { - RouteServer[] routeServers = new RouteServer[publishNodes.size()]; - int i = 0; - for (Node node : publishNodes) { + Set<Node> nodes = microServiceInfo.getNodes(); + RouteServer[] routeServers = new RouteServer[nodes.size()]; + int n = 0; + for (Node node : nodes) { RouteServer routeServer = new RouteServer(node.getIp(), node.getPort()); - routeServers[i] = routeServer; - i++; - } - return routeServers; + routeServers[n] = routeServer; + n++; } - } - } + return routeServers; - Set<Node> nodes = microServiceInfo.getNodes(); - RouteServer[] routeServers = new RouteServer[nodes.size()]; - int n = 0; - for (Node node : nodes) { - RouteServer routeServer = new RouteServer(node.getIp(), node.getPort()); - routeServers[n] = routeServer; - n++; } - return routeServers; - - } + /** + * From MicroServiceInfo to ApiRouteInfo + * + * @param microServiceInfo + * @return + */ + private ApiRouteInfo[] buildApiRouteInfo(MicroServiceFullInfo microServiceInfo, String redis_serviceName, + String redis_version, String routeWay) { - /** - * From MicroServiceInfo to ApiRouteInfo - * - * @param microServiceInfo - * @return - */ - private ApiRouteInfo[] buildApiRouteInfo(MicroServiceFullInfo microServiceInfo, - String redis_serviceName, String redis_version, String routeWay) { + ApiRouteInfo apiRouteInfo = new ApiRouteInfo(); + apiRouteInfo.setUrl(microServiceInfo.getUrl()); - ApiRouteInfo apiRouteInfo = new ApiRouteInfo(); - apiRouteInfo.setUrl(microServiceInfo.getUrl()); + apiRouteInfo.setServers(buildRouteNodes(microServiceInfo, routeWay)); - apiRouteInfo.setServers(buildRouteNodes(microServiceInfo, routeWay)); + apiRouteInfo.setVisualRange(RouteUtil.getVisualRangeByRouter(microServiceInfo.getVisualRange())); - apiRouteInfo.setVisualRange(RouteUtil.getVisualRangeByRouter(microServiceInfo.getVisualRange())); + if ("ip_hash".equals(microServiceInfo.getLb_policy())) { + apiRouteInfo.setUseOwnUpstream("1"); + } - if ("ip_hash".equals(microServiceInfo.getLb_policy())) { - apiRouteInfo.setUseOwnUpstream("1"); - } + apiRouteInfo.setConsulServiceName(microServiceInfo.getServiceName()); + apiRouteInfo.setServiceName(redis_serviceName); + apiRouteInfo.setVersion(redis_version); + apiRouteInfo.setApiJson(microServiceInfo.getUrl() + "/swagger.json"); + apiRouteInfo.setMetricsUrl("/admin/metrics"); + apiRouteInfo.setEnable_ssl(buildRouteHttpProtocol(microServiceInfo, routeWay)); + // 默认 HttpProtocol和PublishProtocol=http + if (apiRouteInfo.isEnable_ssl()) { + apiRouteInfo.setPublishProtocol("https"); + } - apiRouteInfo.setConsulServiceName(microServiceInfo.getServiceName()); - apiRouteInfo.setServiceName(redis_serviceName); - apiRouteInfo.setVersion(redis_version); - apiRouteInfo.setApiJson(microServiceInfo.getUrl() + "/swagger.json"); - apiRouteInfo.setMetricsUrl("/admin/metrics"); - apiRouteInfo.setEnable_ssl(buildRouteHttpProtocol(microServiceInfo, routeWay)); - // 默认 HttpProtocol和PublishProtocol=http - if (apiRouteInfo.isEnable_ssl()) { - apiRouteInfo.setPublishProtocol("https"); - } + // 获取服务的host + String host = getHost(microServiceInfo); - // 获取服务的host - String host = getHost(microServiceInfo); + apiRouteInfo.setHost(host.toLowerCase()); + apiRouteInfo.setNamespace(microServiceInfo.getNamespace()); - apiRouteInfo.setHost(host.toLowerCase()); - apiRouteInfo.setNamespace(microServiceInfo.getNamespace()); + if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { - if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { + if (StringUtils.isNotBlank(microServiceInfo.getPublish_port())) { + apiRouteInfo.setPublishProtocol("https"); + } - if (StringUtils.isNotBlank(microServiceInfo.getPublish_port())) { - apiRouteInfo.setPublishProtocol("https"); - } + // 获取服务的发布端口(支持多端口格式:https|http) + String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); + if (publishPorts.length == 2) { + apiRouteInfo.setPublishProtocol("https"); + apiRouteInfo.setPublish_port(publishPorts[0]); - // 获取服务的发布端口(支持多端口格式:https|http) - String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); - if (publishPorts.length == 2) { - apiRouteInfo.setPublishProtocol("https"); - apiRouteInfo.setPublish_port(publishPorts[0]); + try { + ApiRouteInfo apiRouteInfo_http = (ApiRouteInfo) apiRouteInfo.clone(); + apiRouteInfo.setPublishProtocol("http"); + apiRouteInfo.setPublish_port(publishPorts[1]); + return new ApiRouteInfo[] {apiRouteInfo, apiRouteInfo_http}; + } catch (CloneNotSupportedException e) { + LOGGER.error("CLONE is wrong:" + apiRouteInfo); + return new ApiRouteInfo[] {apiRouteInfo}; + } - try { - ApiRouteInfo apiRouteInfo_http = (ApiRouteInfo) apiRouteInfo.clone(); - apiRouteInfo.setPublishProtocol("http"); - apiRouteInfo.setPublish_port(publishPorts[1]); - return new ApiRouteInfo[] {apiRouteInfo, apiRouteInfo_http}; - } catch (CloneNotSupportedException e) { - LOGGER.error("CLONE is wrong:" + apiRouteInfo); - return new ApiRouteInfo[] {apiRouteInfo}; + } } - } - } - - apiRouteInfo.setPublish_port(microServiceInfo.getPublish_port()); - return new ApiRouteInfo[] {apiRouteInfo}; + apiRouteInfo.setPublish_port(microServiceInfo.getPublish_port()); + return new ApiRouteInfo[] {apiRouteInfo}; - } + } - /** - * From MicroServiceInfo to CustomRouteInfo - * - * @param microServiceInfo - * @return - */ - private CustomRouteInfo[] buildCustomRouteInfo(MicroServiceFullInfo microServiceInfo, - String redis_serviceName, String routeWay) { + /** + * From MicroServiceInfo to CustomRouteInfo + * + * @param microServiceInfo + * @return + */ + private CustomRouteInfo[] buildCustomRouteInfo(MicroServiceFullInfo microServiceInfo, String redis_serviceName, + String routeWay) { - CustomRouteInfo customRouteInfo = new CustomRouteInfo(); - customRouteInfo.setUrl(microServiceInfo.getUrl()); + CustomRouteInfo customRouteInfo = new CustomRouteInfo(); + customRouteInfo.setUrl(microServiceInfo.getUrl()); - customRouteInfo.setServers(buildRouteNodes(microServiceInfo, routeWay)); + customRouteInfo.setServers(buildRouteNodes(microServiceInfo, routeWay)); - customRouteInfo.setVisualRange(RouteUtil.getVisualRangeByRouter(microServiceInfo.getVisualRange())); + customRouteInfo.setVisualRange(RouteUtil.getVisualRangeByRouter(microServiceInfo.getVisualRange())); - if ("ip_hash".equals(microServiceInfo.getLb_policy())) { - customRouteInfo.setUseOwnUpstream("1"); - } + if ("ip_hash".equals(microServiceInfo.getLb_policy())) { + customRouteInfo.setUseOwnUpstream("1"); + } - customRouteInfo.setConsulServiceName(microServiceInfo.getServiceName()); - customRouteInfo.setServiceName(redis_serviceName); + customRouteInfo.setConsulServiceName(microServiceInfo.getServiceName()); + customRouteInfo.setServiceName(redis_serviceName); - // 获取服务的host - String host = getHost(microServiceInfo); + // 获取服务的host + String host = getHost(microServiceInfo); - customRouteInfo.setHost(host.toLowerCase()); - customRouteInfo.setNamespace(microServiceInfo.getNamespace()); - customRouteInfo.setEnable_ssl(buildRouteHttpProtocol(microServiceInfo, routeWay)); + customRouteInfo.setHost(host.toLowerCase()); + customRouteInfo.setNamespace(microServiceInfo.getNamespace()); + customRouteInfo.setEnable_ssl(buildRouteHttpProtocol(microServiceInfo, routeWay)); - if (customRouteInfo.isEnable_ssl()) { - customRouteInfo.setPublishProtocol("https"); - } + if (customRouteInfo.isEnable_ssl()) { + customRouteInfo.setPublishProtocol("https"); + } - if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { - if (StringUtils.isNotBlank(microServiceInfo.getPublish_port())) { - customRouteInfo.setPublishProtocol("https"); - } - - String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); - if (publishPorts.length == 2) { - // 获取服务的发布端口(支持多端口格式:https|http) - customRouteInfo.setPublishProtocol("https"); - customRouteInfo.setPublish_port(publishPorts[0]); - - try { - CustomRouteInfo customRouteInfo_http = (CustomRouteInfo) customRouteInfo.clone(); - customRouteInfo.setPublishProtocol("http"); - customRouteInfo.setPublish_port(publishPorts[1]); - return new CustomRouteInfo[] {customRouteInfo, customRouteInfo_http}; - } catch (CloneNotSupportedException e) { - LOGGER.error("CLONE is wrong:" + customRouteInfo); - return new CustomRouteInfo[] {customRouteInfo}; + if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { + if (StringUtils.isNotBlank(microServiceInfo.getPublish_port())) { + customRouteInfo.setPublishProtocol("https"); + } + + String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); + if (publishPorts.length == 2) { + // 获取服务的发布端口(支持多端口格式:https|http) + customRouteInfo.setPublishProtocol("https"); + customRouteInfo.setPublish_port(publishPorts[0]); + + try { + CustomRouteInfo customRouteInfo_http = (CustomRouteInfo) customRouteInfo.clone(); + customRouteInfo.setPublishProtocol("http"); + customRouteInfo.setPublish_port(publishPorts[1]); + return new CustomRouteInfo[] {customRouteInfo, customRouteInfo_http}; + } catch (CloneNotSupportedException e) { + LOGGER.error("CLONE is wrong:" + customRouteInfo); + return new CustomRouteInfo[] {customRouteInfo}; + } + + } } - } - } + customRouteInfo.setPublish_port(microServiceInfo.getPublish_port()); + return new CustomRouteInfo[] {customRouteInfo}; + } - customRouteInfo.setPublish_port(microServiceInfo.getPublish_port()); - return new CustomRouteInfo[] {customRouteInfo}; - } + /** + * From MicroServiceInfo to IuiRouteInfo + * + * @param microServiceInfo + * @return + */ + private IuiRouteInfo[] buildIuiRouteInfo(MicroServiceFullInfo microServiceInfo, String redis_serviceName, + String routeWay) { - /** - * From MicroServiceInfo to IuiRouteInfo - * - * @param microServiceInfo - * @return - */ - private IuiRouteInfo[] buildIuiRouteInfo(MicroServiceFullInfo microServiceInfo, - String redis_serviceName, String routeWay) { + IuiRouteInfo iuiRouteInfo = new IuiRouteInfo(); + iuiRouteInfo.setUrl(microServiceInfo.getUrl()); - IuiRouteInfo iuiRouteInfo = new IuiRouteInfo(); - iuiRouteInfo.setUrl(microServiceInfo.getUrl()); + iuiRouteInfo.setServers(buildRouteNodes(microServiceInfo, routeWay)); - iuiRouteInfo.setServers(buildRouteNodes(microServiceInfo, routeWay)); + iuiRouteInfo.setVisualRange(RouteUtil.getVisualRangeByRouter(microServiceInfo.getVisualRange())); - iuiRouteInfo.setVisualRange(RouteUtil.getVisualRangeByRouter(microServiceInfo.getVisualRange())); + if ("ip_hash".equals(microServiceInfo.getLb_policy())) { + iuiRouteInfo.setUseOwnUpstream("1"); + } - if ("ip_hash".equals(microServiceInfo.getLb_policy())) { - iuiRouteInfo.setUseOwnUpstream("1"); - } + iuiRouteInfo.setConsulServiceName(microServiceInfo.getServiceName()); + iuiRouteInfo.setServiceName(redis_serviceName); - iuiRouteInfo.setConsulServiceName(microServiceInfo.getServiceName()); - iuiRouteInfo.setServiceName(redis_serviceName); + // 获取服务的host + String host = getHost(microServiceInfo); - // 获取服务的host - String host = getHost(microServiceInfo); + iuiRouteInfo.setHost(host.toLowerCase()); + iuiRouteInfo.setNamespace(microServiceInfo.getNamespace()); + iuiRouteInfo.setEnable_ssl(buildRouteHttpProtocol(microServiceInfo, routeWay)); + if (iuiRouteInfo.isEnable_ssl()) { + iuiRouteInfo.setPublishProtocol("https"); + } - iuiRouteInfo.setHost(host.toLowerCase()); - iuiRouteInfo.setNamespace(microServiceInfo.getNamespace()); - iuiRouteInfo.setEnable_ssl(buildRouteHttpProtocol(microServiceInfo, routeWay)); - if (iuiRouteInfo.isEnable_ssl()) { - iuiRouteInfo.setPublishProtocol("https"); + if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { + + if (StringUtils.isNotBlank(microServiceInfo.getPublish_port())) { + iuiRouteInfo.setPublishProtocol("https"); + } + + String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); + if (publishPorts.length == 2) { + // 获取服务的发布端口(支持多端口格式:https|http) + iuiRouteInfo.setPublishProtocol("https"); + iuiRouteInfo.setPublish_port(publishPorts[0]); + + try { + IuiRouteInfo iuiRouteInfo_http = (IuiRouteInfo) iuiRouteInfo.clone(); + iuiRouteInfo.setPublishProtocol("http"); + iuiRouteInfo.setPublish_port(publishPorts[1]); + return new IuiRouteInfo[] {iuiRouteInfo, iuiRouteInfo_http}; + } catch (CloneNotSupportedException e) { + LOGGER.error("CLONE is wrong:" + iuiRouteInfo); + return new IuiRouteInfo[] {iuiRouteInfo}; + } + + } + } + iuiRouteInfo.setPublish_port(microServiceInfo.getPublish_port()); + return new IuiRouteInfo[] {iuiRouteInfo}; } - if (RouteUtil.ROUTEWAY_IP.equals(routeWay)) { - - if (StringUtils.isNotBlank(microServiceInfo.getPublish_port())) { - iuiRouteInfo.setPublishProtocol("https"); - } - - String[] publishPorts = StringUtils.split(microServiceInfo.getPublish_port(), "|"); - if (publishPorts.length == 2) { - // 获取服务的发布端口(支持多端口格式:https|http) - iuiRouteInfo.setPublishProtocol("https"); - iuiRouteInfo.setPublish_port(publishPorts[0]); - - try { - IuiRouteInfo iuiRouteInfo_http = (IuiRouteInfo) iuiRouteInfo.clone(); - iuiRouteInfo.setPublishProtocol("http"); - iuiRouteInfo.setPublish_port(publishPorts[1]); - return new IuiRouteInfo[] {iuiRouteInfo, iuiRouteInfo_http}; - } catch (CloneNotSupportedException e) { - LOGGER.error("CLONE is wrong:" + iuiRouteInfo); - return new IuiRouteInfo[] {iuiRouteInfo}; - } - } - } - iuiRouteInfo.setPublish_port(microServiceInfo.getPublish_port()); - return new IuiRouteInfo[] {iuiRouteInfo}; - } + private List<Node> getPublishNodes(String discoverServiceName, String version, String namespace) { + List<Node> nodes = new ArrayList<Node>(); + if (StringUtils.isBlank(version)) { + version = "null"; + } - private List<Node> getPublishNodes(String discoverServiceName, String version, String namespace) { - List<Node> nodes = new ArrayList<Node>(); + DiscoverInfo discoverInfo = ConfigUtil.getInstance().getDiscoverInfo(); - if (StringUtils.isBlank(version)) { - version = "null"; - } + String allpublishaddressUrl = (new StringBuilder().append("http://").append(discoverInfo.toString()) + .append(RouteUtil.MSB_ROUTE_URL).append("/").append(discoverServiceName).append("/version/") + .append(version).append("/allpublishaddress?namespace=").append(namespace) + .append("&visualRange=0")).toString(); - DiscoverInfo discoverInfo = ConfigUtil.getInstance().getDiscoverInfo(); - - String allpublishaddressUrl = - (new StringBuilder().append("http://").append(discoverInfo.toString()) - .append(RouteUtil.MSB_ROUTE_URL).append("/").append(discoverServiceName) - .append("/version/").append(version).append("/allpublishaddress?namespace=") - .append(namespace).append("&visualRange=0")).toString(); - - String resultJson = HttpClientUtil.httpGet(allpublishaddressUrl); - List<PublishFullAddress> publishFullAddressList = - JacksonJsonUtil - .jsonToListBean(resultJson, new TypeReference<List<PublishFullAddress>>() {}); - if (publishFullAddressList != null && publishFullAddressList.size() > 0) { - for (PublishFullAddress publishFullAddress : publishFullAddressList) { - if (StringUtils.isNotBlank(publishFullAddress.getIp()) - && "https".equals(publishFullAddress.getPublish_protocol())) { - nodes.add(new Node(publishFullAddress.getIp(), publishFullAddress.getPort())); + String resultJson = HttpClientUtil.httpGet(allpublishaddressUrl); + List<PublishFullAddress> publishFullAddressList = + JacksonJsonUtil.jsonToListBean(resultJson, new TypeReference<List<PublishFullAddress>>() {}); + if (publishFullAddressList != null && publishFullAddressList.size() > 0) { + for (PublishFullAddress publishFullAddress : publishFullAddressList) { + if (StringUtils.isNotBlank(publishFullAddress.getIp()) + && "https".equals(publishFullAddress.getPublish_protocol())) { + nodes.add(new Node(publishFullAddress.getIp(), publishFullAddress.getPort())); + } + + } } - } + return nodes; } - return nodes; - } - } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/RouteNotify.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/RouteNotify.java index d2d7e32..5cc8abe 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/RouteNotify.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/serviceListener/RouteNotify.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.serviceListener; @@ -22,71 +20,68 @@ import org.onap.msb.apiroute.api.MicroServiceFullInfo; import org.onap.msb.apiroute.wrapper.util.ServiceFilter; public class RouteNotify { - - private static RouteNotify instance = new RouteNotify(); - private List<IMicroServiceChangeListener> serviceListenerlist = - new ArrayList<IMicroServiceChangeListener>(); + private static RouteNotify instance = new RouteNotify(); - private RouteNotify() {} + private List<IMicroServiceChangeListener> serviceListenerlist = new ArrayList<IMicroServiceChangeListener>(); - public static RouteNotify getInstance() { - return instance; - } + private RouteNotify() {} - - public void addServiceChangeListener(IMicroServiceChangeListener listener) { - synchronized (serviceListenerlist) { - serviceListenerlist.add(listener); + public static RouteNotify getInstance() { + return instance; } - } - /* public void removeServiceChangeListener(IMicroServiceChangeListener listener) { - synchronized (serviceListenerlist) { - serviceListenerlist.remove(listener); + public void addServiceChangeListener(IMicroServiceChangeListener listener) { + synchronized (serviceListenerlist) { + serviceListenerlist.add(listener); + } } - }*/ - public void noticeRouteListener4Update(String serviceName, String version, MicroServiceFullInfo microServiceInfo) throws Exception { - if (ServiceFilter.getInstance().isNeedNotifyByProtocol(microServiceInfo.getProtocol())) { - for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { - serviceListener.onChange(serviceName, version, microServiceInfo); - } - } + /* + * public void removeServiceChangeListener(IMicroServiceChangeListener listener) { synchronized + * (serviceListenerlist) { serviceListenerlist.remove(listener); } } + */ - } - public void noticeUpdateStatusListener(MicroServiceFullInfo microServiceInfo, String status) { + public void noticeRouteListener4Update(String serviceName, String version, MicroServiceFullInfo microServiceInfo) + throws Exception { + if (ServiceFilter.getInstance().isNeedNotifyByProtocol(microServiceInfo.getProtocol())) { + for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { + serviceListener.onChange(serviceName, version, microServiceInfo); + } + } - for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { - serviceListener.onStatusChange(microServiceInfo.getServiceName(), - microServiceInfo.getVersion(), microServiceInfo.getHost(),microServiceInfo.getProtocol(), microServiceInfo.getPublish_port(),status); } - } + public void noticeUpdateStatusListener(MicroServiceFullInfo microServiceInfo, String status) { - - - public void noticeRouteListener4Add(MicroServiceFullInfo microServiceInfo) throws Exception { - if (ServiceFilter.getInstance().isNeedNotifyByProtocol(microServiceInfo.getProtocol())) { for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { - serviceListener.onSave(microServiceInfo); + serviceListener.onStatusChange(microServiceInfo.getServiceName(), microServiceInfo.getVersion(), + microServiceInfo.getHost(), microServiceInfo.getProtocol(), + microServiceInfo.getPublish_port(), status); } } - } - - public void noticeRouteListener4Delete(MicroServiceFullInfo microServiceInfo) throws Exception { - if (ServiceFilter.getInstance().isNeedNotifyByProtocol(microServiceInfo.getProtocol())) { - for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { - serviceListener.onDelete(microServiceInfo); + + + + public void noticeRouteListener4Add(MicroServiceFullInfo microServiceInfo) throws Exception { + if (ServiceFilter.getInstance().isNeedNotifyByProtocol(microServiceInfo.getProtocol())) { + for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { + serviceListener.onSave(microServiceInfo); + } + } + } + + public void noticeRouteListener4Delete(MicroServiceFullInfo microServiceInfo) throws Exception { + if (ServiceFilter.getInstance().isNeedNotifyByProtocol(microServiceInfo.getProtocol())) { + for (IMicroServiceChangeListener serviceListener : serviceListenerlist) { + serviceListener.onDelete(microServiceInfo); + } } } - } - - } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/CommonUtil.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/CommonUtil.java index edd0a44..30e473a 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/CommonUtil.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/CommonUtil.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -22,70 +20,70 @@ import org.apache.commons.lang3.StringUtils; public class CommonUtil { - public static final int SC_OK = 200; - - public static Object[] concat(Object[] a, Object[] b) { - Object[] c = new Object[a.length + b.length]; - System.arraycopy(a, 0, c, 0, a.length); - System.arraycopy(b, 0, c, a.length, b.length); - return c; - } - - public static boolean contain(String strArray, String str) { - String[] array = StringUtils.split(strArray, ","); - return contain(array, str); - } - - public static boolean contain(String[] array, String str) { - for (int i = 0; i < array.length; i++) { - if (array[i].trim().equals(str)) { - return true; - } - } - return false; + public static final int SC_OK = 200; - } + public static Object[] concat(Object[] a, Object[] b) { + Object[] c = new Object[a.length + b.length]; + System.arraycopy(a, 0, c, 0, a.length); + System.arraycopy(b, 0, c, a.length, b.length); + return c; + } - public static boolean contain(String[] array, String value[]) { - for (int i = 0; i < array.length; i++) { - for (int n = 0; n < value.length; n++) { - if (array[i].equals(value[n])) { - return true; - } - } + public static boolean contain(String strArray, String str) { + String[] array = StringUtils.split(strArray, ","); + return contain(array, str); } - return false; - } + public static boolean contain(String[] array, String str) { + for (int i = 0; i < array.length; i++) { + if (array[i].trim().equals(str)) { + return true; + } + } + return false; - /** - * @param <T> - * @Title getDiffrent - * @Description TODO(Extract the list1 and list2 different data sets) - * @param list1 - * @param list2 - * @return TODO(a new List in list2 but not in list1) - * @return List<String> - */ - public static <T> Set<T> getDiffrent(Set<T> list1, Set<T> list2) { + } - HashSet<T> set_all = new HashSet<T>(); + public static boolean contain(String[] array, String value[]) { + for (int i = 0; i < array.length; i++) { + for (int n = 0; n < value.length; n++) { + if (array[i].equals(value[n])) { + return true; + } + } + } + return false; - for (T t1 : list1) { - set_all.add(t1); } + /** + * @param <T> + * @Title getDiffrent + * @Description TODO(Extract the list1 and list2 different data sets) + * @param list1 + * @param list2 + * @return TODO(a new List in list2 but not in list1) + * @return List<String> + */ + public static <T> Set<T> getDiffrent(Set<T> list1, Set<T> list2) { + + HashSet<T> set_all = new HashSet<T>(); + + for (T t1 : list1) { + set_all.add(t1); + } - Set<T> diff = new HashSet<T>(); - for (T t2 : list2) { - if (set_all.add(t2)) { // in list2 but not in list1 - diff.add(t2); - } - } + Set<T> diff = new HashSet<T>(); + for (T t2 : list2) { + if (set_all.add(t2)) { // in list2 but not in list1 + diff.add(t2); + } + } - return diff; - } + + return diff; + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/ConfigUtil.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/ConfigUtil.java index f40bc42..e0318ba 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/ConfigUtil.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/ConfigUtil.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -31,430 +29,413 @@ import com.fasterxml.jackson.databind.ObjectMapper; @SuppressWarnings("unchecked") public class ConfigUtil { - private final static ConfigUtil instance = new ConfigUtil(); - - - private ConfigUtil() {} - - public static ConfigUtil getInstance() { - return instance; - } - - private static final Logger LOGGER = LoggerFactory.getLogger(ConfigUtil.class); - - private String serverPort="80"; - - private String IUI_ROOT_PATH="iui"; - - private String API_ROOT_PATH="api"; - - private String namespaceMatches="all"; - - private String visualRangeMatches="0"; - - private String nodeMetaQueryParam=""; - - private String network_plane_typeMatches=""; - - private String[] routeWay={"ip"}; - - private Map<String,String> labelMapMatches; - - private DiscoverInfo discoverInfo=new DiscoverInfo(); - - private String consul_ip=""; - - private String metricsUrl = "http://127.0.0.1:8066/admin/metrics"; - - public void initRootPath() { - String apiRootPathConfSource="Default"; - String iuiRootPathConfSource="Default"; - - try { - - URL urlRootPath = - ConfigUtil.class.getResource("/ext/initUrlRootPath/initUrlRootPath.json"); - if (urlRootPath != null) { - String path = urlRootPath.getPath(); - - LOGGER.warn("read initUrlRootPath:" + path); - - String fileContent = FileUtil.readFile(path); - ObjectMapper mapper = new ObjectMapper(); - - Map<String, String> map = mapper.readValue(fileContent, HashMap.class); - if (map.get("iuiRootPath") != null) { - IUI_ROOT_PATH = map.get("iuiRootPath"); - iuiRootPathConfSource="initUrlRootPath.json"; - } - if (map.get("apiRootPath") != null) { - API_ROOT_PATH = map.get("apiRootPath"); - apiRootPathConfSource="initUrlRootPath.json"; - } - - } - } catch (IOException e) { - // TODO Auto-generated catch block - LOGGER.error("init UrlRootPath throw exception", e); + private final static ConfigUtil instance = new ConfigUtil(); + + + private ConfigUtil() {} + + public static ConfigUtil getInstance() { + return instance; } - - LOGGER.warn("init IUI_ROOT_PATH from ["+iuiRootPathConfSource+"]:"+IUI_ROOT_PATH); - LOGGER.warn("init API_ROOT_PATH from ["+apiRootPathConfSource+"]:"+API_ROOT_PATH); - - } - - public void initApiGatewayPort() { - - String env_APIGATEWAY_EXPOSE_PORT=System.getenv("APIGATEWAY_EXPOSE_PORT"); - String httpExposePortConfSource="Default"; - try { - // read initApiGatewayConfig - if (StringUtils.isBlank(env_APIGATEWAY_EXPOSE_PORT)) { - URL apiGatewayConfigPath = - ConfigUtil.class - .getResource("/ext/initApiGatewayConfig/initApiGatewayConfig.json"); - if (apiGatewayConfigPath != null) { - String path = apiGatewayConfigPath.getPath(); - - LOGGER.warn("read initApiGatewayConfig:" + path); - - String fileContent = FileUtil.readFile(path); - ObjectMapper mapper = new ObjectMapper(); - - Map<String, Object> labelMap = mapper.readValue(fileContent, Map.class); - if (labelMap.get("port") != null) { - serverPort = (String) labelMap.get("port"); - httpExposePortConfSource="initApiGatewayConfig.json"; - } + + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigUtil.class); + + private String serverPort = "80"; + + private String IUI_ROOT_PATH = "iui"; + + private String API_ROOT_PATH = "api"; + + private String namespaceMatches = "all"; + + private String visualRangeMatches = "0"; + + private String nodeMetaQueryParam = ""; + + private String network_plane_typeMatches = ""; + + private String[] routeWay = {"ip"}; + + private Map<String, String> labelMapMatches; + + private DiscoverInfo discoverInfo = new DiscoverInfo(); + + private String consul_ip = ""; + + private String metricsUrl = "http://127.0.0.1:8066/admin/metrics"; + + public void initRootPath() { + String apiRootPathConfSource = "Default"; + String iuiRootPathConfSource = "Default"; + + try { + + URL urlRootPath = ConfigUtil.class.getResource("/ext/initUrlRootPath/initUrlRootPath.json"); + if (urlRootPath != null) { + String path = urlRootPath.getPath(); + + LOGGER.warn("read initUrlRootPath:" + path); + + String fileContent = FileUtil.readFile(path); + ObjectMapper mapper = new ObjectMapper(); + + Map<String, String> map = mapper.readValue(fileContent, HashMap.class); + if (map.get("iuiRootPath") != null) { + IUI_ROOT_PATH = map.get("iuiRootPath"); + iuiRootPathConfSource = "initUrlRootPath.json"; + } + if (map.get("apiRootPath") != null) { + API_ROOT_PATH = map.get("apiRootPath"); + apiRootPathConfSource = "initUrlRootPath.json"; + } + + } + } catch (IOException e) { + // TODO Auto-generated catch block + LOGGER.error("init UrlRootPath throw exception", e); } - } else { - serverPort = env_APIGATEWAY_EXPOSE_PORT; - httpExposePortConfSource="env:APIGATEWAY_EXPOSE_PORT"; - } - LOGGER.warn("init APIGATEWAY http publish Port from ["+httpExposePortConfSource+"]:"+serverPort); - } catch (Exception e) { - // TODO Auto-generated catch block - LOGGER.error( - "read initApiGatewayConfig Files or env(APIGATEWAY_EXPOSE_PORT) throw exception", e); - } - - - } - - public void initConsulIp() { - String sys_consulIp=System.getenv("CONSUL_IP"); - if (StringUtils.isNotBlank(sys_consulIp)) { - consul_ip=sys_consulIp; - LOGGER.warn("init consul_Ip from [env:CONSUL_IP]:" + sys_consulIp); + + LOGGER.warn("init IUI_ROOT_PATH from [" + iuiRootPathConfSource + "]:" + IUI_ROOT_PATH); + LOGGER.warn("init API_ROOT_PATH from [" + apiRootPathConfSource + "]:" + API_ROOT_PATH); + } - else{ - LOGGER.warn("init consul_Ip from [env:CONSUL_IP] is blank"); + + public void initApiGatewayPort() { + + String env_APIGATEWAY_EXPOSE_PORT = System.getenv("APIGATEWAY_EXPOSE_PORT"); + String httpExposePortConfSource = "Default"; + try { + // read initApiGatewayConfig + if (StringUtils.isBlank(env_APIGATEWAY_EXPOSE_PORT)) { + URL apiGatewayConfigPath = + ConfigUtil.class.getResource("/ext/initApiGatewayConfig/initApiGatewayConfig.json"); + if (apiGatewayConfigPath != null) { + String path = apiGatewayConfigPath.getPath(); + + LOGGER.warn("read initApiGatewayConfig:" + path); + + String fileContent = FileUtil.readFile(path); + ObjectMapper mapper = new ObjectMapper(); + + Map<String, Object> labelMap = mapper.readValue(fileContent, Map.class); + if (labelMap.get("port") != null) { + serverPort = (String) labelMap.get("port"); + httpExposePortConfSource = "initApiGatewayConfig.json"; + } + } + } else { + serverPort = env_APIGATEWAY_EXPOSE_PORT; + httpExposePortConfSource = "env:APIGATEWAY_EXPOSE_PORT"; + } + LOGGER.warn("init APIGATEWAY http publish Port from [" + httpExposePortConfSource + "]:" + serverPort); + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.error("read initApiGatewayConfig Files or env(APIGATEWAY_EXPOSE_PORT) throw exception", e); + } + + } - - - } - - public void initRouteNameSpaceMatches() { - String env_NAMESPACE=System.getenv("NAMESPACE"); - String namespaceConfSource="Default"; - try { - // read NAMESPACE - if (StringUtils.isBlank(env_NAMESPACE)) { - URL routeLabelsPath = - InitRouteServiceWrapper.class - .getResource("/ext/initRouteLabels/initRouteLabelsMatches.json"); - if (routeLabelsPath != null) { - String path = routeLabelsPath.getPath(); - - String fileContent = FileUtil.readFile(path); - ObjectMapper mapper = new ObjectMapper(); - - Map<String, Object> labelMap = mapper.readValue(fileContent, Map.class); - if (labelMap.get("namespace") != null) { - namespaceMatches = (String) labelMap.get("namespace"); - namespaceConfSource="initRouteLabelsMatches.json"; - } + + public void initConsulIp() { + String sys_consulIp = System.getenv("CONSUL_IP"); + if (StringUtils.isNotBlank(sys_consulIp)) { + consul_ip = sys_consulIp; + LOGGER.warn("init consul_Ip from [env:CONSUL_IP]:" + sys_consulIp); + } else { + LOGGER.warn("init consul_Ip from [env:CONSUL_IP] is blank"); } - } else { - namespaceMatches =env_NAMESPACE; - namespaceConfSource="env:NAMESPACE"; - } - LOGGER.warn("init namespace Filter from ["+namespaceConfSource+"]:" + namespaceMatches); + + } - catch (Exception e) { - // TODO Auto-generated catch block - LOGGER.error("read initRouteNameSpaceMatches Files or env(NAMESPACE) throw exception", - e); + + public void initRouteNameSpaceMatches() { + String env_NAMESPACE = System.getenv("NAMESPACE"); + String namespaceConfSource = "Default"; + try { + // read NAMESPACE + if (StringUtils.isBlank(env_NAMESPACE)) { + URL routeLabelsPath = InitRouteServiceWrapper.class + .getResource("/ext/initRouteLabels/initRouteLabelsMatches.json"); + if (routeLabelsPath != null) { + String path = routeLabelsPath.getPath(); + + String fileContent = FileUtil.readFile(path); + ObjectMapper mapper = new ObjectMapper(); + + Map<String, Object> labelMap = mapper.readValue(fileContent, Map.class); + if (labelMap.get("namespace") != null) { + namespaceMatches = (String) labelMap.get("namespace"); + namespaceConfSource = "initRouteLabelsMatches.json"; + } + } + } else { + namespaceMatches = env_NAMESPACE; + namespaceConfSource = "env:NAMESPACE"; + } + LOGGER.warn("init namespace Filter from [" + namespaceConfSource + "]:" + namespaceMatches); + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.error("read initRouteNameSpaceMatches Files or env(NAMESPACE) throw exception", e); + } + + + } - - - - } - /** - * @Title: initRouteLabelsMatches - * @Description: TODO(According to the environment variable or a JSON file configuration - * initialization Route filter conditions) - * @return: void - */ - public void initRouteLabelsMatches() { - String env_ROUTE_LABELS=System.getenv("ROUTE_LABELS"); - String visualRangeConfSource="Default"; - String networkPlaneConfSource="Default"; - String labelConfSource="Default"; - try { - - // read ROUTE_LABELS - if (StringUtils.isBlank(env_ROUTE_LABELS)) { - URL routeLabelsPath = - InitRouteServiceWrapper.class - .getResource("/ext/initRouteLabels/initRouteLabelsMatches.json"); - if (routeLabelsPath != null) { - String path = routeLabelsPath.getPath(); - - String fileContent = FileUtil.readFile(path); - ObjectMapper mapper = new ObjectMapper(); - - Map<?, ?> labelMap = mapper.readValue(fileContent, Map.class); - if (labelMap.get("predefineLabels") != null) { - Map<String, String> predefineLabelMapMatches = - (Map<String, String>) labelMap.get("predefineLabels"); - if (predefineLabelMapMatches.get("visualRange") != null) { - visualRangeMatches = predefineLabelMapMatches.get("visualRange"); - visualRangeConfSource="initRouteLabelsMatches.json"; + + /** + * @Title: initRouteLabelsMatches + * @Description: TODO(According to the environment variable or a JSON file configuration + * initialization Route filter conditions) + * @return: void + */ + public void initRouteLabelsMatches() { + String env_ROUTE_LABELS = System.getenv("ROUTE_LABELS"); + String visualRangeConfSource = "Default"; + String networkPlaneConfSource = "Default"; + String labelConfSource = "Default"; + try { + + // read ROUTE_LABELS + if (StringUtils.isBlank(env_ROUTE_LABELS)) { + URL routeLabelsPath = InitRouteServiceWrapper.class + .getResource("/ext/initRouteLabels/initRouteLabelsMatches.json"); + if (routeLabelsPath != null) { + String path = routeLabelsPath.getPath(); + + String fileContent = FileUtil.readFile(path); + ObjectMapper mapper = new ObjectMapper(); + + Map<?, ?> labelMap = mapper.readValue(fileContent, Map.class); + if (labelMap.get("predefineLabels") != null) { + Map<String, String> predefineLabelMapMatches = + (Map<String, String>) labelMap.get("predefineLabels"); + if (predefineLabelMapMatches.get("visualRange") != null) { + visualRangeMatches = predefineLabelMapMatches.get("visualRange"); + visualRangeConfSource = "initRouteLabelsMatches.json"; + } + if (predefineLabelMapMatches.get("network_plane_type") != null) { + network_plane_typeMatches = predefineLabelMapMatches.get("network_plane_type"); + networkPlaneConfSource = "initRouteLabelsMatches.json"; + } + } + + if (labelMap.get("customLabels") != null) { + labelMapMatches = (Map<String, String>) labelMap.get("customLabels"); + labelConfSource = "initRouteLabelsMatches.json"; + } + + } + } else { + String[] env_routeLabels = StringUtils.split(env_ROUTE_LABELS, ","); + Map<String, String> labelMap = new HashMap<String, String>(); + + for (int i = 0; i < env_routeLabels.length; i++) { + String[] labels = StringUtils.split(env_routeLabels[i], ":"); + + if ("visualRange".equals(labels[0])) { + visualRangeMatches = labels[1]; + visualRangeConfSource = "env:ROUTE_LABELS"; + } else if ("network_plane_type".equals(labels[0])) { + network_plane_typeMatches = labels[1]; + networkPlaneConfSource = "env:ROUTE_LABELS"; + } else { + labelMap.put(labels[0], labels[1]); + } + + } + + labelConfSource = "env:ROUTE_LABELS"; + labelMapMatches = labelMap; + } - if (predefineLabelMapMatches.get("network_plane_type") != null) { - network_plane_typeMatches = - predefineLabelMapMatches.get("network_plane_type"); - networkPlaneConfSource="initRouteLabelsMatches.json"; + LOGGER.warn("init visualRange Filter from [ " + visualRangeConfSource + " ]:" + visualRangeMatches); + LOGGER.warn("init network_plane_type Filter from [ " + networkPlaneConfSource + " ]:" + + network_plane_typeMatches); + LOGGER.warn("init customLabels Filter from [ " + labelConfSource + " ]:" + labelMapMatches); + } catch (IOException e) { + // TODO Auto-generated catch block + LOGGER.error("read initRouteLabelsPathMatches Files or env(ROUTE_LABELS) throw exception", e); + } + } + + public void initRouteWay() { + String env_ROUTE_WAY = System.getenv("ROUTE_WAY"); + try { + // read NAMESPACE + if (StringUtils.isBlank(env_ROUTE_WAY)) { + URL routeLabelsPath = InitRouteServiceWrapper.class.getResource("/ext/initRouteWay/initRouteWay.json"); + if (routeLabelsPath != null) { + String path = routeLabelsPath.getPath(); + + String fileContent = FileUtil.readFile(path); + ObjectMapper mapper = new ObjectMapper(); + + Map<String, Object> routeWayMap = mapper.readValue(fileContent, Map.class); + String routeWayFromConfig = (String) routeWayMap.get("routeWay"); + if (StringUtils.isNotBlank(routeWayFromConfig)) { + routeWay = StringUtils.split(routeWayFromConfig, RouteUtil.SPLIT_LINE); + LOGGER.warn("init RouteWay from [initRouteWay.json]:" + routeWayFromConfig); + } + } + } else { + routeWay = StringUtils.split(env_ROUTE_WAY, RouteUtil.SPLIT_LINE); + LOGGER.warn("read initRouteWay from [env:ROUTE_WAY]:" + env_ROUTE_WAY); } - } - if (labelMap.get("customLabels") != null) { - labelMapMatches = (Map<String, String>) labelMap.get("customLabels"); - labelConfSource="initRouteLabelsMatches.json"; - } + + } catch (Exception e) { + // TODO Auto-generated catch block + LOGGER.error("read initRouteWay Files or env(ROUTE_WAY) throw exception", e); } - } else { - String[] env_routeLabels = StringUtils.split(env_ROUTE_LABELS, ","); - Map<String, String> labelMap = new HashMap<String, String>(); - - for (int i = 0; i < env_routeLabels.length; i++) { - String[] labels = StringUtils.split(env_routeLabels[i], ":"); - - if ("visualRange".equals(labels[0])) { - visualRangeMatches = labels[1]; - visualRangeConfSource="env:ROUTE_LABELS"; - } else if ("network_plane_type".equals(labels[0])) { - network_plane_typeMatches = labels[1]; - networkPlaneConfSource="env:ROUTE_LABELS"; - } else { - labelMap.put(labels[0], labels[1]); - } + } + + public void initDiscoverInfo(ApiRouteAppConfig configuration) { + DiscoverInfo config_discoverInfo = configuration.getDiscoverInfo(); + + + discoverInfo.setEnabled(config_discoverInfo.isEnabled()); + + String discoverInfoConfSource = "yaml config"; + + if (config_discoverInfo.isEnabled()) { + + String discoverIP; + String env_SDCLIENT_IP = System.getenv("SDCLIENT_IP"); + + if (StringUtils.isBlank(env_SDCLIENT_IP)) { + // yml + discoverIP = config_discoverInfo.getIp(); + } else { + discoverIP = env_SDCLIENT_IP; + discoverInfoConfSource = "env:SDCLIENT_IP"; + } + + discoverInfo.setIp(discoverIP.trim()); + discoverInfo.setPort(config_discoverInfo.getPort()); } - labelConfSource="env:ROUTE_LABELS"; - labelMapMatches = labelMap; - - } - LOGGER.warn("init visualRange Filter from [ "+visualRangeConfSource+" ]:" + visualRangeMatches); - LOGGER.warn("init network_plane_type Filter from [ "+networkPlaneConfSource+" ]:" + network_plane_typeMatches); - LOGGER.warn("init customLabels Filter from [ "+labelConfSource+" ]:" + labelMapMatches); - } catch (IOException e) { - // TODO Auto-generated catch block - LOGGER.error( - "read initRouteLabelsPathMatches Files or env(ROUTE_LABELS) throw exception", - e); + LOGGER.warn("init DiscoverInfo from [" + discoverInfoConfSource + "]--" + discoverInfo.toString() + " Enabled:" + + discoverInfo.isEnabled()); } - } - - public void initRouteWay() { - String env_ROUTE_WAY=System.getenv("ROUTE_WAY"); - try { - // read NAMESPACE - if (StringUtils.isBlank(env_ROUTE_WAY)) { - URL routeLabelsPath = - InitRouteServiceWrapper.class.getResource("/ext/initRouteWay/initRouteWay.json"); - if (routeLabelsPath != null) { - String path = routeLabelsPath.getPath(); - - String fileContent = FileUtil.readFile(path); - ObjectMapper mapper = new ObjectMapper(); - - Map<String, Object> routeWayMap = mapper.readValue(fileContent, Map.class); - String routeWayFromConfig=(String)routeWayMap.get("routeWay"); - if (StringUtils.isNotBlank(routeWayFromConfig)) { - routeWay = - StringUtils.split(routeWayFromConfig, RouteUtil.SPLIT_LINE); - LOGGER.warn("init RouteWay from [initRouteWay.json]:" + routeWayFromConfig); - } + + public void initNodeMetaQueryParam() { + // judge consul register node:caltalog + String env_CONSUL_REGISTER_MODE = System.getenv("CONSUL_REGISTER_MODE"); + + if (env_CONSUL_REGISTER_MODE == null || !env_CONSUL_REGISTER_MODE.trim().equals("catalog")) { + nodeMetaQueryParam = ""; + return; } - } else { - routeWay = StringUtils.split(env_ROUTE_WAY, RouteUtil.SPLIT_LINE); - LOGGER.warn("read initRouteWay from [env:ROUTE_WAY]:" + env_ROUTE_WAY); - } - - + // visual range + String nodemeta_visualrange = nodemeta_visualrange(visualRangeMatches); + + LOGGER.warn("calc nodemeta_visualrange from [" + visualRangeMatches + "]:" + nodemeta_visualrange); + + nodeMetaQueryParam = nodemeta_visualrange; + // name space + String nodemeta_namespace = nodemeta_namespace(namespaceMatches); + LOGGER.warn("calc nodemeta_namespace from [" + namespaceMatches + "]:" + nodemeta_namespace); + + if (!nodeMetaQueryParam.isEmpty() && !nodemeta_namespace.isEmpty()) { + nodeMetaQueryParam += "&"; + } + nodeMetaQueryParam += nodemeta_namespace; + + /* + * // nodemeta = (!nodemeta_visualrange.isEmpty() && !nodemeta_namespace .isEmpty()) ? + * nodemeta_visualrange + "&" + nodemeta_namespace : nodemeta_visualrange + + * nodemeta_namespace; + */ - } catch (Exception e) { - // TODO Auto-generated catch block - LOGGER.error("read initRouteWay Files or env(ROUTE_WAY) throw exception", e); } - } - - public void initDiscoverInfo(ApiRouteAppConfig configuration){ - DiscoverInfo config_discoverInfo = configuration.getDiscoverInfo(); + private String nodemeta_visualrange(final String visualRangeMatches) { + + if (visualRangeMatches == null || visualRangeMatches.isEmpty()) { + return ""; + } + + // external:0 + if (visualRangeMatches.trim().equals("0")) { + return "node-meta=external:true"; + } + + // internal:1 + if (visualRangeMatches.trim().equals("1")) { + return "node-meta=internal:true"; + } + return ""; + } - discoverInfo.setEnabled(config_discoverInfo.isEnabled()); - String discoverInfoConfSource="yaml config"; + private String nodemeta_namespace(final String namespaceMatches) { - if (config_discoverInfo.isEnabled()) { - - String discoverIP; - String env_SDCLIENT_IP=System.getenv("SDCLIENT_IP"); - - if (StringUtils.isBlank(env_SDCLIENT_IP)) { - // yml - discoverIP = config_discoverInfo.getIp(); - } else { - discoverIP = env_SDCLIENT_IP; - discoverInfoConfSource="env:SDCLIENT_IP"; + // exclude null,"",all,&,|,! + if (namespaceMatches == null || namespaceMatches.isEmpty() || namespaceMatches.contains("all") + || namespaceMatches.contains("&") || namespaceMatches.contains("|") + || namespaceMatches.contains("!")) { + return ""; } - discoverInfo.setIp(discoverIP.trim()); - discoverInfo.setPort(config_discoverInfo.getPort()); + return "node-meta=ns:" + namespaceMatches; + } + + public String getServerPort() { + return serverPort; + } + + public String getIUI_ROOT_PATH() { + return IUI_ROOT_PATH; + } + + public String getAPI_ROOT_PATH() { + return API_ROOT_PATH; + } + + public String getNamespaceMatches() { + return namespaceMatches; + } + + public String getVisualRangeMatches() { + return visualRangeMatches; + } + + public String getNetwork_plane_typeMatches() { + return network_plane_typeMatches; + } + + public String[] getRouteWay() { + return routeWay.clone(); + } + + public Map<String, String> getLabelMapMatches() { + return labelMapMatches; + } + + public DiscoverInfo getDiscoverInfo() { + return discoverInfo; + } + + public String getMetricsUrl() { + return metricsUrl; + } + + public void setMetricsUrl(String metricsUrl) { + this.metricsUrl = metricsUrl; + } + + public String getNodeMetaQueryParam() { + return nodeMetaQueryParam; + } + + public String getConsul_ip() { + return consul_ip; } - - LOGGER.warn("init DiscoverInfo from ["+discoverInfoConfSource+"]--" + discoverInfo.toString()+" Enabled:"+discoverInfo.isEnabled()); - } - - public void initNodeMetaQueryParam() { - // judge consul register node:caltalog - String env_CONSUL_REGISTER_MODE = System.getenv("CONSUL_REGISTER_MODE"); - - if (env_CONSUL_REGISTER_MODE == null - || !env_CONSUL_REGISTER_MODE.trim().equals("catalog")) { - nodeMetaQueryParam = ""; - return; - } - - // visual range - String nodemeta_visualrange = nodemeta_visualrange(visualRangeMatches); - - LOGGER.warn("calc nodemeta_visualrange from [" + visualRangeMatches - + "]:" + nodemeta_visualrange); - - nodeMetaQueryParam = nodemeta_visualrange; - - // name space - String nodemeta_namespace = nodemeta_namespace(namespaceMatches); - LOGGER.warn("calc nodemeta_namespace from [" + namespaceMatches + "]:" - + nodemeta_namespace); - - if (!nodeMetaQueryParam.isEmpty() && !nodemeta_namespace.isEmpty()) { - nodeMetaQueryParam += "&"; - } - nodeMetaQueryParam += nodemeta_namespace; - - /* - * // nodemeta = (!nodemeta_visualrange.isEmpty() && !nodemeta_namespace - * .isEmpty()) ? nodemeta_visualrange + "&" + nodemeta_namespace : - * nodemeta_visualrange + nodemeta_namespace; - */ - - } - - private String nodemeta_visualrange(final String visualRangeMatches) { - - if (visualRangeMatches == null || visualRangeMatches.isEmpty()) { - return ""; - } - - // external:0 - if (visualRangeMatches.trim().equals("0")) { - return "node-meta=external:true"; - } - - // internal:1 - if (visualRangeMatches.trim().equals("1")) { - return "node-meta=internal:true"; - } - - return ""; - } - - - private String nodemeta_namespace(final String namespaceMatches) { - - // exclude null,"",all,&,|,! - if (namespaceMatches == null || namespaceMatches.isEmpty() - || namespaceMatches.contains("all") - || namespaceMatches.contains("&") - || namespaceMatches.contains("|") - || namespaceMatches.contains("!")) { - return ""; - } - - return "node-meta=ns:" + namespaceMatches; - } - - public String getServerPort() { - return serverPort; - } - - public String getIUI_ROOT_PATH() { - return IUI_ROOT_PATH; - } - - public String getAPI_ROOT_PATH() { - return API_ROOT_PATH; - } - - public String getNamespaceMatches() { - return namespaceMatches; - } - - public String getVisualRangeMatches() { - return visualRangeMatches; - } - - public String getNetwork_plane_typeMatches() { - return network_plane_typeMatches; - } - - public String[] getRouteWay() { - return routeWay.clone(); - } - - public Map<String, String> getLabelMapMatches() { - return labelMapMatches; - } - - public DiscoverInfo getDiscoverInfo() { - return discoverInfo; - } - - public String getMetricsUrl() { - return metricsUrl; - } - - public void setMetricsUrl(String metricsUrl) { - this.metricsUrl = metricsUrl; - } - - public String getNodeMetaQueryParam() { - return nodeMetaQueryParam; - } - - public String getConsul_ip() { - return consul_ip; - } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/FileUtil.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/FileUtil.java index d8af88c..2b6468b 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/FileUtil.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/FileUtil.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -33,11 +31,11 @@ public final class FileUtil { File[] filelist = file.listFiles(); return filelist; } - + return null; } - public static String readFile(String Path) throws IOException{ + public static String readFile(String Path) throws IOException { BufferedReader reader = null; StringBuffer fileContent = new StringBuffer(); try { @@ -62,7 +60,7 @@ public final class FileUtil { } return fileContent.toString(); } - + /** * Read all the files under a folder */ diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtil.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtil.java index 95fbf31..cb80159 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtil.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtil.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -29,104 +27,104 @@ import org.slf4j.LoggerFactory; public class HttpClientUtil { - private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); - - private static int connectionTimeOut = 2*1000; - - - public static String httpGet(String url){ - String result = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet httpGet = new HttpGet(url); - httpGet.addHeader("Content-type", "application/json; charset=utf-8"); - httpGet.setHeader("Accept", "application/json"); - try { - CloseableHttpResponse res = httpClient.execute(httpGet); - result = EntityUtils.toString(res.getEntity()); - if (res.getStatusLine().getStatusCode() != CommonUtil.SC_OK) { - logger.error(result); - } - res.close(); - } catch (ClientProtocolException e) { - logger.error(url + ":httpGetWithJSON connect faild"); - } catch (IOException e) { - logger.error( url + ":httpGetWithJSON connect faild"); - } finally { - try { - httpClient.close(); - } catch (IOException e) { - logger.error(url + ":close httpClient faild"); - } + private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); + + private static int connectionTimeOut = 2 * 1000; + + + public static String httpGet(String url) { + String result = null; + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader("Content-type", "application/json; charset=utf-8"); + httpGet.setHeader("Accept", "application/json"); + try { + CloseableHttpResponse res = httpClient.execute(httpGet); + result = EntityUtils.toString(res.getEntity()); + if (res.getStatusLine().getStatusCode() != CommonUtil.SC_OK) { + logger.error(result); + } + res.close(); + } catch (ClientProtocolException e) { + logger.error(url + ":httpGetWithJSON connect faild"); + } catch (IOException e) { + logger.error(url + ":httpGetWithJSON connect faild"); + } finally { + try { + httpClient.close(); + } catch (IOException e) { + logger.error(url + ":close httpClient faild"); + } + } + + return result; + } - return result; - - } - - public static HttpGetResult httpGetStatusAndBody(String url){ - HttpGetResult result= new HttpGetResult(); - String body = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet httpGet = new HttpGet(url); - httpGet.addHeader("Content-type", "application/json; charset=utf-8"); - httpGet.setHeader("Accept", "application/json"); - - RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeOut).build(); - httpGet.setConfig(requestConfig); - - try { - CloseableHttpResponse res = httpClient.execute(httpGet); - body = EntityUtils.toString(res.getEntity()); - if (res.getStatusLine().getStatusCode() != CommonUtil.SC_OK) { - logger.error(body); - } - result.setBody(body); - result.setStatusCode(res.getStatusLine().getStatusCode()); - res.close(); - } catch (ClientProtocolException e) { - logger.error(url + ":httpGetWithJSON connect faild",e); - } catch (IOException e) { - logger.error( url + ":httpGetWithJSON connect faild",e); - } finally { - try { - httpClient.close(); - } catch (IOException e) { - logger.error(url + ":close httpClient faild"); - } - } - - return result; - - } - - public static int httpGetStatus(String url) throws Exception{ - int iStatus=500; - CloseableHttpClient httpClient = HttpClients.createDefault(); - - - HttpGet httpGet = new HttpGet(url); - RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超时时间 - httpGet.setConfig(requestConfig); - httpGet.addHeader("Content-type", "application/json; charset=utf-8"); - httpGet.setHeader("Accept", "application/json"); - try { - CloseableHttpResponse res = httpClient.execute(httpGet); - - iStatus=res.getStatusLine().getStatusCode(); - res.close(); - } catch (ClientProtocolException e) { - logger.error(url + " httpGet connect faild:"+e.getMessage()); - } catch (IOException e) { - logger.error(url + " httpGet connect faild:"+e.getMessage()); - } finally { - try { - httpClient.close(); - } catch (IOException e) { - logger.error(url + " httpGet close faild:"+e.getMessage()); - } + public static HttpGetResult httpGetStatusAndBody(String url) { + HttpGetResult result = new HttpGetResult(); + String body = null; + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader("Content-type", "application/json; charset=utf-8"); + httpGet.setHeader("Accept", "application/json"); + + RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeOut).build(); + httpGet.setConfig(requestConfig); + + try { + CloseableHttpResponse res = httpClient.execute(httpGet); + body = EntityUtils.toString(res.getEntity()); + if (res.getStatusLine().getStatusCode() != CommonUtil.SC_OK) { + logger.error(body); + } + result.setBody(body); + result.setStatusCode(res.getStatusLine().getStatusCode()); + res.close(); + } catch (ClientProtocolException e) { + logger.error(url + ":httpGetWithJSON connect faild", e); + } catch (IOException e) { + logger.error(url + ":httpGetWithJSON connect faild", e); + } finally { + try { + httpClient.close(); + } catch (IOException e) { + logger.error(url + ":close httpClient faild"); + } + } + + return result; + } - return iStatus; + public static int httpGetStatus(String url) throws Exception { + int iStatus = 500; + CloseableHttpClient httpClient = HttpClients.createDefault(); + + + HttpGet httpGet = new HttpGet(url); + RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置请求和传输超时时间 + httpGet.setConfig(requestConfig); + httpGet.addHeader("Content-type", "application/json; charset=utf-8"); + httpGet.setHeader("Accept", "application/json"); + try { + CloseableHttpResponse res = httpClient.execute(httpGet); - } + iStatus = res.getStatusLine().getStatusCode(); + res.close(); + } catch (ClientProtocolException e) { + logger.error(url + " httpGet connect faild:" + e.getMessage()); + } catch (IOException e) { + logger.error(url + " httpGet connect faild:" + e.getMessage()); + } finally { + try { + httpClient.close(); + } catch (IOException e) { + logger.error(url + " httpGet close faild:" + e.getMessage()); + } + } + + return iStatus; + + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/HttpGetResult.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/HttpGetResult.java index 3418c43..f231480 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/HttpGetResult.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/HttpGetResult.java @@ -1,34 +1,36 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; public class HttpGetResult { - private int statusCode; - private String body; - public int getStatusCode() { - return statusCode; - } - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - public String getBody() { - return body; - } - public void setBody(String body) { - this.body = body; - } - + private int statusCode; + private String body; + + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/Jackson.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/Jackson.java index 382495d..85c1e3a 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/Jackson.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/Jackson.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -21,7 +19,7 @@ import com.fasterxml.jackson.datatype.jdk7.Jdk7Module; import com.fasterxml.jackson.datatype.joda.JodaModule; public class Jackson { - //use static singleton, make sure to reuse! + // use static singleton, make sure to reuse! public static final ObjectMapper MAPPER = newObjectMapper(); private Jackson() { diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtil.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtil.java index f61fd8a..1e2fe6d 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtil.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtil.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -25,84 +23,84 @@ import com.fasterxml.jackson.databind.SerializationFeature; public class JacksonJsonUtil { - private static final Logger logger = LoggerFactory.getLogger(JacksonJsonUtil.class); + private static final Logger logger = LoggerFactory.getLogger(JacksonJsonUtil.class); - private volatile static ObjectMapper mapper = null; + private volatile static ObjectMapper mapper = null; - private static ObjectMapper getMapperInstance() { - if (mapper == null) { - synchronized (JacksonJsonUtil.class) { + private static ObjectMapper getMapperInstance() { if (mapper == null) { - mapper = new ObjectMapper(); + synchronized (JacksonJsonUtil.class) { + if (mapper == null) { + mapper = new ObjectMapper(); + } + } } - } + return mapper; } - return mapper; - } - - /** - * from java object to json - * - * @param obj - * @return json - * @throws Exception - */ - public static String beanToJson(Object obj) throws Exception { - String json = null; - - ObjectMapper objectMapper = getMapperInstance(); - objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - json = objectMapper.writeValueAsString(obj); - - return json; - } - - - - /** - * from json to java object - * - * @param json - * @param cls - * @return - * @throws Exception - */ - public static Object jsonToBean(String json, Class<?> cls) throws Exception { - Object vo = null; - try { - ObjectMapper objectMapper = getMapperInstance(); - objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - vo = objectMapper.readValue(json, cls); - - } catch (Exception e) { - logger.error(cls + " JsonTobean faild"); - throw new Exception(cls + " JsonTobean faild"); + + /** + * from java object to json + * + * @param obj + * @return json + * @throws Exception + */ + public static String beanToJson(Object obj) throws Exception { + String json = null; + + ObjectMapper objectMapper = getMapperInstance(); + objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + json = objectMapper.writeValueAsString(obj); + + return json; } - return vo; - } - /** - * from json to java List - * - * @param json - * @return - * @throws Exception - */ - public static <T> T jsonToListBean(String json, TypeReference<T> valueTypeRef) { - try { - ObjectMapper objectMapper = getMapperInstance(); + /** + * from json to java object + * + * @param json + * @param cls + * @return + * @throws Exception + */ + public static Object jsonToBean(String json, Class<?> cls) throws Exception { + Object vo = null; + try { + ObjectMapper objectMapper = getMapperInstance(); + objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + vo = objectMapper.readValue(json, cls); + + } catch (Exception e) { + logger.error(cls + " JsonTobean faild"); + throw new Exception(cls + " JsonTobean faild"); + } + return vo; + } + + /** + * from json to java List + * + * @param json + * @return + * @throws Exception + */ + public static <T> T jsonToListBean(String json, TypeReference<T> valueTypeRef) { + try { - return objectMapper.readValue(json, valueTypeRef); + ObjectMapper objectMapper = getMapperInstance(); - } catch (Exception e) { - String errorMsg = " JsonTobean faild:" + e.getMessage(); - logger.error(errorMsg); + + return objectMapper.readValue(json, valueTypeRef); + + } catch (Exception e) { + String errorMsg = " JsonTobean faild:" + e.getMessage(); + logger.error(errorMsg); + } + return null; } - return null; - } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/JedisUtil.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/JedisUtil.java index 0c238d8..96bccad 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/JedisUtil.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/JedisUtil.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -24,7 +22,6 @@ import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import org.apache.commons.lang3.StringUtils; -import org.onap.msb.apiroute.wrapper.InitRouteServiceWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,173 +32,169 @@ import redis.clients.jedis.JedisPoolConfig; public class JedisUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(JedisUtil.class); - private static String host = "127.0.0.1"; - private static int port = 6379; - private static int connectionTimeout = 2000; - private static int DEFAULT_DB_INDEX = 0; + private static final Logger LOGGER = LoggerFactory.getLogger(JedisUtil.class); + private static String host = "127.0.0.1"; + private static int port = 6379; + private static int connectionTimeout = 2000; + private static int DEFAULT_DB_INDEX = 0; - private volatile static JedisPool jedisPool = null; + private volatile static JedisPool jedisPool = null; - public static String propertiesName = "redis.properties"; - private static final String LINE_SEPARATOR = System.getProperty("line.separator"); + public static String propertiesName = "redis.properties"; + private static final String LINE_SEPARATOR = System.getProperty("line.separator"); - private JedisUtil() { - // private constructor + private JedisUtil() { + // private constructor - } + } - private synchronized static JedisPool initialPool() throws IOException { + private synchronized static JedisPool initialPool() throws IOException { - JedisPoolConfig config = new JedisPoolConfig(); - config.setMaxTotal(50); - config.setMaxIdle(30); - config.setMaxWaitMillis(5000); - config.setTestOnBorrow(false); - config.setTestOnReturn(true); + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxTotal(50); + config.setMaxIdle(30); + config.setMaxWaitMillis(5000); + config.setTestOnBorrow(false); + config.setTestOnReturn(true); - URL urlPath = JedisUtil.class.getResource("/ext/redisConf/redis.properties"); - if (urlPath != null) { - String propertiesPath = urlPath.getPath(); + URL urlPath = JedisUtil.class.getResource("/ext/redisConf/redis.properties"); + if (urlPath != null) { + String propertiesPath = urlPath.getPath(); - File propertiesFile = new File(propertiesPath); + File propertiesFile = new File(propertiesPath); - if (propertiesFile.exists()) { + if (propertiesFile.exists()) { - BufferedInputStream inputStream = - new BufferedInputStream(new FileInputStream(propertiesPath)); - ResourceBundle bundle = new PropertyResourceBundle(inputStream); + BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(propertiesPath)); + ResourceBundle bundle = new PropertyResourceBundle(inputStream); - if (bundle == null) { - throw new IllegalArgumentException("[redis.properties] is not found!"); - } + if (bundle == null) { + throw new IllegalArgumentException("[redis.properties] is not found!"); + } - // Set up the connection pool basic information - String strHost = bundle.getString("redis.host"); - if (StringUtils.isNotEmpty(strHost)) { - host = strHost; - } + // Set up the connection pool basic information + String strHost = bundle.getString("redis.host"); + if (StringUtils.isNotEmpty(strHost)) { + host = strHost; + } - // redis port: first read from env - if (StringUtils.isNotBlank(System.getenv("APIGATEWAY_REDIS_PORT"))) { - port = Integer.parseInt(System.getenv("APIGATEWAY_REDIS_PORT")); - } else { - String strPort = bundle.getString("redis.port"); - if (StringUtils.isNotEmpty(strPort)) { - port = Integer.parseInt(strPort); - } - } + // redis port: first read from env + if (StringUtils.isNotBlank(System.getenv("APIGATEWAY_REDIS_PORT"))) { + port = Integer.parseInt(System.getenv("APIGATEWAY_REDIS_PORT")); + } else { + String strPort = bundle.getString("redis.port"); + if (StringUtils.isNotEmpty(strPort)) { + port = Integer.parseInt(strPort); + } + } - String strTimeout = bundle.getString("redis.connectionTimeout"); - if (StringUtils.isNotEmpty(strTimeout)) { - connectionTimeout = Integer.parseInt(strTimeout); - } + String strTimeout = bundle.getString("redis.connectionTimeout"); + if (StringUtils.isNotEmpty(strTimeout)) { + connectionTimeout = Integer.parseInt(strTimeout); + } - String strDbIndex = bundle.getString("redis.db_index"); - if (StringUtils.isNotEmpty(strDbIndex)) { - DEFAULT_DB_INDEX = Integer.parseInt(strDbIndex); - } + String strDbIndex = bundle.getString("redis.db_index"); + if (StringUtils.isNotEmpty(strDbIndex)) { + DEFAULT_DB_INDEX = Integer.parseInt(strDbIndex); + } - String strMaxTotal = bundle.getString("redis.pool.maxTotal"); - if (StringUtils.isNotEmpty(strMaxTotal)) { - config.setMaxTotal(Integer.parseInt(strMaxTotal)); - } + String strMaxTotal = bundle.getString("redis.pool.maxTotal"); + if (StringUtils.isNotEmpty(strMaxTotal)) { + config.setMaxTotal(Integer.parseInt(strMaxTotal)); + } - String strMaxIdle = bundle.getString("redis.pool.maxIdle"); - if (StringUtils.isNotEmpty(strMaxIdle)) { - config.setMaxIdle(Integer.parseInt(strMaxIdle)); - } + String strMaxIdle = bundle.getString("redis.pool.maxIdle"); + if (StringUtils.isNotEmpty(strMaxIdle)) { + config.setMaxIdle(Integer.parseInt(strMaxIdle)); + } - String strMaxWaitMillis = bundle.getString("redis.pool.maxWaitMillis"); - if (StringUtils.isNotEmpty(strMaxWaitMillis)) { - config.setMaxWaitMillis(Long.parseLong(strMaxWaitMillis)); - } + String strMaxWaitMillis = bundle.getString("redis.pool.maxWaitMillis"); + if (StringUtils.isNotEmpty(strMaxWaitMillis)) { + config.setMaxWaitMillis(Long.parseLong(strMaxWaitMillis)); + } - String strTestOnBorrow = bundle.getString("redis.pool.testOnBorrow"); - if (StringUtils.isNotEmpty(strTestOnBorrow)) { - config.setTestOnBorrow(Boolean.valueOf(strTestOnBorrow)); - } + String strTestOnBorrow = bundle.getString("redis.pool.testOnBorrow"); + if (StringUtils.isNotEmpty(strTestOnBorrow)) { + config.setTestOnBorrow(Boolean.valueOf(strTestOnBorrow)); + } + + String strTestOnReturn = bundle.getString("redis.pool.testOnReturn"); + if (StringUtils.isNotEmpty(strTestOnReturn)) { + config.setTestOnReturn(Boolean.valueOf(strTestOnReturn)); + } - String strTestOnReturn = bundle.getString("redis.pool.testOnReturn"); - if (StringUtils.isNotEmpty(strTestOnReturn)) { - config.setTestOnReturn(Boolean.valueOf(strTestOnReturn)); + } } - } - } + StringBuffer redisinfo = new StringBuffer(); + redisinfo.append("------redis.properties------").append(LINE_SEPARATOR); + redisinfo.append("redis.host: ").append(host).append(":").append(port).append(LINE_SEPARATOR); + redisinfo.append("redis.connectionTimeout: ").append(connectionTimeout).append(LINE_SEPARATOR); + redisinfo.append("redis.pool.maxTotal: ").append(config.getMaxTotal()).append(LINE_SEPARATOR); + redisinfo.append("redis.pool.maxIdle: ").append(config.getMaxIdle()).append(LINE_SEPARATOR); + redisinfo.append("redis.pool.maxWaitMillis: ").append(config.getMaxWaitMillis()).append(LINE_SEPARATOR); + redisinfo.append("redis.pool.testOnBorrow: ").append(config.getTestOnBorrow()).append(LINE_SEPARATOR); + redisinfo.append("redis.pool.testOnReturn: ").append(config.getTestOnReturn()).append(LINE_SEPARATOR); + + + LOGGER.info(redisinfo.toString()); + return new JedisPool(config, host, port, connectionTimeout); - StringBuffer redisinfo = new StringBuffer(); - redisinfo.append("------redis.properties------").append(LINE_SEPARATOR); - redisinfo.append("redis.host: ").append(host).append(":").append(port).append(LINE_SEPARATOR); - redisinfo.append("redis.connectionTimeout: ").append(connectionTimeout).append(LINE_SEPARATOR); - redisinfo.append("redis.pool.maxTotal: ").append(config.getMaxTotal()).append(LINE_SEPARATOR); - redisinfo.append("redis.pool.maxIdle: ").append(config.getMaxIdle()).append(LINE_SEPARATOR); - redisinfo.append("redis.pool.maxWaitMillis: ").append(config.getMaxWaitMillis()) - .append(LINE_SEPARATOR); - redisinfo.append("redis.pool.testOnBorrow: ").append(config.getTestOnBorrow()) - .append(LINE_SEPARATOR); - redisinfo.append("redis.pool.testOnReturn: ").append(config.getTestOnReturn()) - .append(LINE_SEPARATOR); - - - LOGGER.info(redisinfo.toString()); - return new JedisPool(config, host, port, connectionTimeout); - - } - - /** - * From the connection pool to obtain jedis instance, use the default database index number 0 - * - * @return - * @throws Exception - */ - public static Jedis borrowJedisInstance() throws Exception { - return borrowJedisInstance(DEFAULT_DB_INDEX); - } - - /** - * From the connection pool to obtain jedis instance, using the specified database index number - * - * @return - * @throws Exception - */ - - public static Jedis borrowJedisInstance(final int dbIndex) throws Exception { - if (jedisPool == null) { - synchronized (JedisUtil.class) { - if (jedisPool == null) { - jedisPool = initialPool(); - } - } } - Jedis resource = jedisPool.getResource(); - if (resource == null) { - throw new Exception("fetch from jedis pool failed,null object!"); + /** + * From the connection pool to obtain jedis instance, use the default database index number 0 + * + * @return + * @throws Exception + */ + public static Jedis borrowJedisInstance() throws Exception { + return borrowJedisInstance(DEFAULT_DB_INDEX); } - resource.select(dbIndex); - return resource; + /** + * From the connection pool to obtain jedis instance, using the specified database index number + * + * @return + * @throws Exception + */ + + public static Jedis borrowJedisInstance(final int dbIndex) throws Exception { + if (jedisPool == null) { + synchronized (JedisUtil.class) { + if (jedisPool == null) { + jedisPool = initialPool(); + } + } + } + Jedis resource = jedisPool.getResource(); + + if (resource == null) { + throw new Exception("fetch from jedis pool failed,null object!"); + } - } + resource.select(dbIndex); + return resource; - /** - * returned to the pool jedis instance - * - * @param jedis - */ - public static void returnJedisInstance(final Jedis jedis) { - if (jedis != null) { - jedis.close(); } - } + + /** + * returned to the pool jedis instance + * + * @param jedis + */ + public static void returnJedisInstance(final Jedis jedis) { + if (jedis != null) { + jedis.close(); + } + } } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtil.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtil.java index e301e92..1ea4ed1 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtil.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtil.java @@ -1,60 +1,60 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; -import org.apache.commons.lang3.StringUtils; +import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; -import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; public class MicroServiceUtil { public static final String PREFIX_PATH = "discover:microservices"; - + private static final Pattern SERVICE_KEY_REGEX_PATTERN = - Pattern.compile("discover:microservices:(?<servicename>[^:]+)(:(?<version>[^:]*))"); + Pattern.compile("discover:microservices:(?<servicename>[^:]+)(:(?<version>[^:]*))"); + - public static String getPrefixedKey(String... paths) { StringBuffer sb = new StringBuffer(); - + sb.append(PREFIX_PATH); - + for (int i = 0; i < paths.length; i++) { sb.append(":"); sb.append(paths[i]); } return sb.toString(); } - - + + public static String getServiceKey(String serviceName, String version) { return getPrefixedKey(serviceName, version); } - public static Pattern getServiceKeyRegexPattern(){ + public static Pattern getServiceKeyRegexPattern() { return SERVICE_KEY_REGEX_PATTERN; } - - + + public static String getRealIp(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { - // After the reverse proxy can have multiple IP value for many times, the first IP is the real IP + // After the reverse proxy can have multiple IP value for many times, the first IP is + // the real IP int index = ip.indexOf(","); if (index != -1) { return ip.substring(0, index); @@ -67,7 +67,7 @@ public class MicroServiceUtil { if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { return ip; } - + return request.getRemoteAddr(); diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtil.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtil.java index 0779dc8..dde9d79 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtil.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtil.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -19,97 +17,94 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegExpTestUtil { - - - private final static String API_KEY_PATTERN ="/api/(?<servicename>[^/]+)(/(?<version>[^/]*)).*"; - - private final static String IUI_KEY_PATTERN ="/iui/(?<servicename>[^/]+)/.*"; - - public static boolean hostRegExpTest(String host){ - - String hostReg = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)" - +":(\\d{1,5})$"; - return Pattern.matches(hostReg, host); - - } - - public static boolean ipRegExpTest(String ip){ - - String hostReg = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." - +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"; - return Pattern.matches(hostReg, ip); - - } - - public static boolean portRegExpTest(String port){ - - String hostReg = "^\\d{1,5}$"; - return Pattern.matches(hostReg, port); - - } - -public static boolean versionRegExpTest(String version){ - - String versionReg = "^v\\d+(\\.\\d+)?$"; - return Pattern.matches(versionReg, version); - - } - -public static boolean urlRegExpTest(String url){ - if(url.equals("/")) return true; - - String urlReg = "^\\/.*((?!\\/).)$"; - return Pattern.matches(urlReg, url); - -} -public static boolean apiRouteUrlRegExpTest(String url){ - - String urlReg = "^\\/"+ConfigUtil.getInstance().getAPI_ROOT_PATH()+"\\/.*$"; - return Pattern.matches(urlReg, url); - -} -public static boolean iuiRouteUrlRegExpTest(String url){ - - String urlReg = "^\\/"+ConfigUtil.getInstance().getIUI_ROOT_PATH()+"\\/.*$"; - return Pattern.matches(urlReg, url); - -} + private final static String API_KEY_PATTERN = "/api/(?<servicename>[^/]+)(/(?<version>[^/]*)).*"; + + private final static String IUI_KEY_PATTERN = "/iui/(?<servicename>[^/]+)/.*"; + + public static boolean hostRegExpTest(String host) { + + String hostReg = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)" + ":(\\d{1,5})$"; + return Pattern.matches(hostReg, host); -public static String[] apiServiceNameMatch4URL(String url){ - Pattern redisKeyPattern =Pattern.compile(API_KEY_PATTERN); - Matcher matcher = redisKeyPattern.matcher(url+"/"); - if (matcher.matches()) { - String version; - if(versionRegExpTest(matcher.group("version"))){ - version=matcher.group("version"); } - else{ - version=""; + + public static boolean ipRegExpTest(String ip) { + + String hostReg = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"; + return Pattern.matches(hostReg, ip); + + } + + public static boolean portRegExpTest(String port) { + + String hostReg = "^\\d{1,5}$"; + return Pattern.matches(hostReg, port); + + } + + public static boolean versionRegExpTest(String version) { + + String versionReg = "^v\\d+(\\.\\d+)?$"; + return Pattern.matches(versionReg, version); + } - return new String[]{matcher.group("servicename"),version}; + + public static boolean urlRegExpTest(String url) { + if (url.equals("/")) + return true; + + String urlReg = "^\\/.*((?!\\/).)$"; + return Pattern.matches(urlReg, url); + } - else{ - return null; + + public static boolean apiRouteUrlRegExpTest(String url) { + + String urlReg = "^\\/" + ConfigUtil.getInstance().getAPI_ROOT_PATH() + "\\/.*$"; + return Pattern.matches(urlReg, url); + } -} + public static boolean iuiRouteUrlRegExpTest(String url) { + + String urlReg = "^\\/" + ConfigUtil.getInstance().getIUI_ROOT_PATH() + "\\/.*$"; + return Pattern.matches(urlReg, url); -public static String iuiServiceNameMatch4URL(String url){ - Pattern redisKeyPattern =Pattern.compile(IUI_KEY_PATTERN); - Matcher matcher = redisKeyPattern.matcher(url+"/"); - if (matcher.matches()) { - return matcher.group("servicename"); } - else{ - return null; + + public static String[] apiServiceNameMatch4URL(String url) { + Pattern redisKeyPattern = Pattern.compile(API_KEY_PATTERN); + Matcher matcher = redisKeyPattern.matcher(url + "/"); + if (matcher.matches()) { + String version; + if (versionRegExpTest(matcher.group("version"))) { + version = matcher.group("version"); + } else { + version = ""; + } + return new String[] {matcher.group("servicename"), version}; + } else { + return null; + } + } + + + public static String iuiServiceNameMatch4URL(String url) { + Pattern redisKeyPattern = Pattern.compile(IUI_KEY_PATTERN); + Matcher matcher = redisKeyPattern.matcher(url + "/"); + if (matcher.matches()) { + return matcher.group("servicename"); + } else { + return null; + } } -} } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/RouteUtil.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/RouteUtil.java index 2189d4d..ae60f50 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/RouteUtil.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/RouteUtil.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -25,320 +23,303 @@ import org.onap.msb.apiroute.api.exception.UnprocessableEntityException; public class RouteUtil { - - public static final int consulDeafultPort=8500; - - public static final String ROUTE_PATH="msb:routing"; - - public static final String ROUTE_PORT_PATH="msb:"; - - public static final String ROUTE_PATH_HOST="msb:host"; - - public static final String APIROUTE="api"; - - public static final String IUIROUTE="iui"; - - public static final String CUSTOMROUTE="custom"; - - public static final String HTTPS_PROTOCOL="https"; - - public static final String CUSTOM_PORTAL="portal"; - - - public static final String PROTOCOL_LIST="REST,HTTP,UI,MQ,FTP,SNMP,TCP,UDP"; - + + public static final int consulDeafultPort = 8500; + + public static final String ROUTE_PATH = "msb:routing"; + + public static final String ROUTE_PORT_PATH = "msb:"; + + public static final String ROUTE_PATH_HOST = "msb:host"; + + public static final String APIROUTE = "api"; + + public static final String IUIROUTE = "iui"; + + public static final String CUSTOMROUTE = "custom"; + + public static final String HTTPS_PROTOCOL = "https"; + + public static final String CUSTOM_PORTAL = "portal"; + + + public static final String PROTOCOL_LIST = "REST,HTTP,UI,MQ,FTP,SNMP,TCP,UDP"; + public static final String MSB_ROUTE_URL = "/api/microservices/v1/services"; - + public static final String MSB_CHECK_URL = "/api/catalog/v1/service/router-all"; - - public static final String visualRangeRange="0,1"; - - public static final String controlRangeMatches="0,1,2"; - - public static final String statusRangeMatches="0,1"; - - public static final String useOwnUpstreamRangeMatches="0,1"; - - public static final String ROUTEWAY_IP="ip"; - - public static final String ROUTEWAY_DOMAIN="domain"; - - public static final String SPLIT_LINE="|"; - - public static final String PROTOCOL_REST="REST"; - - public static final String PROTOCOL_UI="UI"; - - public static final String PROTOCOL_HTTP="HTTP"; - - public static final String FILTER_PROTOCOLS="REST,UI,HTTP"; - - public static final int SERVICE_DATA_QUEUE_NUM=5; - - public static final int SERVICE_QUEUE_CAPACITY=100; - - public static final int SERVICE_LIST_QUEUE_CAPACITY=5; - - public static final int WATCH_SECOND=120; - - public static final String HEALTH_CHECK_PASSING="passing"; - - - - - /** - * @Title: getPrefixedKey - * @Description: TODO(Add base path prefix radis assembly path) - * @param: @param serviceName - * @param: @param version - * @param: @param type - * @param: @return - * @return: String - */ - - public static String getPrefixedKey(String...paths){ - StringBuffer sb= new StringBuffer(); - - if(paths[0].trim().equals("") || paths[0].equals(ConfigUtil.getInstance().getServerPort())){ - sb.append(ROUTE_PATH); - } - else{ - sb.append(ROUTE_PORT_PATH).append(paths[0]); - } - - for (int i = 1; i < paths.length; i++) { - sb.append(":"); - sb.append(paths[i]); - } - return sb.toString(); - } - - public static String getPrefixedKey4Host(String...paths){ - StringBuffer sb= new StringBuffer(); - - sb.append(ROUTE_PATH_HOST); - - - for (int i = 0; i < paths.length; i++) { - sb.append(":"); - sb.append(paths[i]); - } - return sb.toString(); - } - - - - - public static void checkRouteWay(String routeWay){ - if(!CommonUtil.contain(ConfigUtil.getInstance().getRouteWay(),routeWay)){ - String errInfo = "routeWay does not support,must be ip or domain"; - throw new UnprocessableEntityException(errInfo); - } - } - - public static void checkServiceNameAndVersion(String serviceName,String version){ - if (StringUtils.isBlank(serviceName)) { - throw new UnprocessableEntityException("serviceName can't be empty"); - } - - if (StringUtils.isNotBlank(version)) { - if (!RegExpTestUtil.versionRegExpTest(version)) { - throw new UnprocessableEntityException("version is not a valid format"); - } - } + + public static final String visualRangeRange = "0,1"; + + public static final String controlRangeMatches = "0,1,2"; + + public static final String statusRangeMatches = "0,1"; + + public static final String useOwnUpstreamRangeMatches = "0,1"; + + public static final String ROUTEWAY_IP = "ip"; + + public static final String ROUTEWAY_DOMAIN = "domain"; + + public static final String SPLIT_LINE = "|"; + + public static final String PROTOCOL_REST = "REST"; + + public static final String PROTOCOL_UI = "UI"; + + public static final String PROTOCOL_HTTP = "HTTP"; + + public static final String FILTER_PROTOCOLS = "REST,UI,HTTP"; + + public static final int SERVICE_DATA_QUEUE_NUM = 5; + + public static final int SERVICE_QUEUE_CAPACITY = 100; + + public static final int SERVICE_LIST_QUEUE_CAPACITY = 5; + + public static final int WATCH_SECOND = 120; + + public static final String HEALTH_CHECK_PASSING = "passing"; + + + + /** + * @Title: getPrefixedKey + * @Description: TODO(Add base path prefix radis assembly path) + * @param: @param serviceName + * @param: @param version + * @param: @param type + * @param: @return + * @return: String + */ + + public static String getPrefixedKey(String... paths) { + StringBuffer sb = new StringBuffer(); + + if (paths[0].trim().equals("") || paths[0].equals(ConfigUtil.getInstance().getServerPort())) { + sb.append(ROUTE_PATH); + } else { + sb.append(ROUTE_PORT_PATH).append(paths[0]); + } + + for (int i = 1; i < paths.length; i++) { + sb.append(":"); + sb.append(paths[i]); + } + return sb.toString(); + } + + public static String getPrefixedKey4Host(String... paths) { + StringBuffer sb = new StringBuffer(); + + sb.append(ROUTE_PATH_HOST); + + + for (int i = 0; i < paths.length; i++) { + sb.append(":"); + sb.append(paths[i]); + } + return sb.toString(); + } + + + + public static void checkRouteWay(String routeWay) { + if (!CommonUtil.contain(ConfigUtil.getInstance().getRouteWay(), routeWay)) { + String errInfo = "routeWay does not support,must be ip or domain"; + throw new UnprocessableEntityException(errInfo); + } + } + + public static void checkServiceNameAndVersion(String serviceName, String version) { + if (StringUtils.isBlank(serviceName)) { + throw new UnprocessableEntityException("serviceName can't be empty"); + } + + if (StringUtils.isNotBlank(version)) { + if (!RegExpTestUtil.versionRegExpTest(version)) { + throw new UnprocessableEntityException("version is not a valid format"); + } + } + } + + public static void checkServiceStatus(String status) { + if (!CommonUtil.contain(statusRangeMatches, status)) { + throw new UnprocessableEntityException("save RouteInfo Status FAIL:status is wrong,value range:(" + + RouteUtil.statusRangeMatches + ")"); + } + } + + + + public static void checkRouterInfoFormat(RouteInfo routeInfo) { + + if (StringUtils.isBlank(routeInfo.getServiceName()) || routeInfo.getServers().length == 0) { + throw new UnprocessableEntityException("save RouteInfo FAIL: Some required fields are empty"); + } + + if (StringUtils.isNotBlank(routeInfo.getUrl())) { + if (!RegExpTestUtil.urlRegExpTest(routeInfo.getUrl())) { + throw new UnprocessableEntityException( + "save RouteInfo FAIL:url is not a valid format(url must be begin with /)"); + + } + } + + if (!CommonUtil.contain(RouteUtil.visualRangeRange, routeInfo.getVisualRange())) { + throw new UnprocessableEntityException("save RouteInfo FAIL:VisualRange is wrong,value range:(" + + RouteUtil.visualRangeRange + ")"); + } + + if (!CommonUtil.contain(RouteUtil.controlRangeMatches, routeInfo.getControl())) { + throw new UnprocessableEntityException( + "save RouteInfo FAIL:control is wrong,value range:(" + RouteUtil.controlRangeMatches + ")"); + } + + if (!CommonUtil.contain(RouteUtil.statusRangeMatches, routeInfo.getStatus())) { + throw new UnprocessableEntityException( + "save RouteInfo FAIL:status is wrong,value range:(" + RouteUtil.statusRangeMatches + ")"); + } + + if (!CommonUtil.contain(RouteUtil.useOwnUpstreamRangeMatches, routeInfo.getUseOwnUpstream())) { + throw new UnprocessableEntityException("save RouteInfo FAIL:useOwnUpstream is wrong,value range:(" + + RouteUtil.useOwnUpstreamRangeMatches + ")"); + } + + // Check the service instance format + RouteServer[] serverList = routeInfo.getServers(); + for (int i = 0; i < serverList.length; i++) { + RouteServer server = serverList[i]; + if (!RegExpTestUtil.ipRegExpTest(server.getIp())) { + throw new UnprocessableEntityException( + "save RouteInfo FAIL:IP(" + server.getIp() + ")is not a valid ip address"); + } + + if (!RegExpTestUtil.portRegExpTest(server.getPort())) { + throw new UnprocessableEntityException( + "save RouteInfo FAIL:Port(" + server.getPort() + ")is not a valid Port address"); + } + } } - public static void checkServiceStatus(String status){ - if (!CommonUtil.contain(statusRangeMatches, status)) { - throw new UnprocessableEntityException( - "save RouteInfo Status FAIL:status is wrong,value range:(" - + RouteUtil.statusRangeMatches + ")"); - } + public static void checkMicroServiceInfoFormat(MicroServiceFullInfo microServiceInfo, String requestIP) { + // Check the service instance format + if (StringUtils.isBlank(microServiceInfo.getServiceName()) + || StringUtils.isBlank(microServiceInfo.getProtocol()) + || microServiceInfo.getNodes().size() == 0) { + throw new UnprocessableEntityException("register MicroServiceInfo FAIL: Some required fields are empty"); + } + + for (Node node : microServiceInfo.getNodes()) { + + if (node.getIp() == null || node.getIp().isEmpty()) { + node.setIp(requestIP); + } else if (!RegExpTestUtil.ipRegExpTest(node.getIp())) { + throw new UnprocessableEntityException( + "register MicroServiceInfo FAIL:IP(" + node.getIp() + ")is not a valid ip address"); + } + + if (!RegExpTestUtil.portRegExpTest(node.getPort())) { + throw new UnprocessableEntityException("register MicroServiceInfo FAIL:Port(" + node.getPort() + + ")is not a valid Port address"); + } + } + + if (StringUtils.isNotBlank(microServiceInfo.getVersion())) { + if (!RegExpTestUtil.versionRegExpTest(microServiceInfo.getVersion())) { + throw new UnprocessableEntityException("register MicroServiceInfo FAIL:version is not a valid format"); + + } + } + + if (StringUtils.isNotBlank(microServiceInfo.getUrl().trim())) { + if (!RegExpTestUtil.urlRegExpTest(microServiceInfo.getUrl())) { + throw new UnprocessableEntityException( + "register MicroServiceInfo FAIL:url is not a valid format(url must be begin with /)"); + + } + } + + + if (RouteUtil.PROTOCOL_LIST.indexOf(microServiceInfo.getProtocol().trim()) == -1) { + throw new UnprocessableEntityException("register MicroServiceInfo FAIL:Protocol is wrong,value range:(" + + RouteUtil.PROTOCOL_LIST + ")"); + } + } - - - - public static void checkRouterInfoFormat(RouteInfo routeInfo) { - - if (StringUtils.isBlank(routeInfo.getServiceName()) || routeInfo.getServers().length == 0) { - throw new UnprocessableEntityException( - "save RouteInfo FAIL: Some required fields are empty"); - } - - if (StringUtils.isNotBlank(routeInfo.getUrl())) { - if (!RegExpTestUtil.urlRegExpTest(routeInfo.getUrl())) { - throw new UnprocessableEntityException( - "save RouteInfo FAIL:url is not a valid format(url must be begin with /)"); - - } - } - - if (!CommonUtil.contain(RouteUtil.visualRangeRange, routeInfo.getVisualRange())) { - throw new UnprocessableEntityException( - "save RouteInfo FAIL:VisualRange is wrong,value range:(" - + RouteUtil.visualRangeRange + ")"); - } - - if (!CommonUtil.contain(RouteUtil.controlRangeMatches, routeInfo.getControl())) { - throw new UnprocessableEntityException( - "save RouteInfo FAIL:control is wrong,value range:(" - + RouteUtil.controlRangeMatches + ")"); - } - - if (!CommonUtil.contain(RouteUtil.statusRangeMatches, routeInfo.getStatus())) { - throw new UnprocessableEntityException( - "save RouteInfo FAIL:status is wrong,value range:(" - + RouteUtil.statusRangeMatches + ")"); - } - - if (!CommonUtil.contain(RouteUtil.useOwnUpstreamRangeMatches, routeInfo.getUseOwnUpstream())) { - throw new UnprocessableEntityException( - "save RouteInfo FAIL:useOwnUpstream is wrong,value range:(" - + RouteUtil.useOwnUpstreamRangeMatches + ")"); - } - - // Check the service instance format - RouteServer[] serverList = routeInfo.getServers(); - for (int i = 0; i < serverList.length; i++) { - RouteServer server = serverList[i]; - if (!RegExpTestUtil.ipRegExpTest(server.getIp())) { - throw new UnprocessableEntityException("save RouteInfo FAIL:IP(" + server.getIp() - + ")is not a valid ip address"); - } - - if (!RegExpTestUtil.portRegExpTest(server.getPort())) { - throw new UnprocessableEntityException("save RouteInfo FAIL:Port(" + server.getPort() - + ")is not a valid Port address"); - } - } - } - - public static void checkMicroServiceInfoFormat(MicroServiceFullInfo microServiceInfo,String requestIP){ - // Check the service instance format - if (StringUtils.isBlank(microServiceInfo.getServiceName()) - || StringUtils.isBlank(microServiceInfo.getProtocol()) - || microServiceInfo.getNodes().size() == 0) { - throw new UnprocessableEntityException( - "register MicroServiceInfo FAIL: Some required fields are empty"); - } - - for (Node node : microServiceInfo.getNodes()) { - - if (node.getIp() == null || node.getIp().isEmpty()) { - node.setIp(requestIP); - } else if (!RegExpTestUtil.ipRegExpTest(node.getIp())) { - throw new UnprocessableEntityException("register MicroServiceInfo FAIL:IP(" + node.getIp() - + ")is not a valid ip address"); - } - - if (!RegExpTestUtil.portRegExpTest(node.getPort())) { - throw new UnprocessableEntityException("register MicroServiceInfo FAIL:Port(" - + node.getPort() + ")is not a valid Port address"); - } - } - - if (StringUtils.isNotBlank(microServiceInfo.getVersion())) { - if (!RegExpTestUtil.versionRegExpTest(microServiceInfo.getVersion())) { - throw new UnprocessableEntityException( - "register MicroServiceInfo FAIL:version is not a valid format"); - - } - } - - if (StringUtils.isNotBlank(microServiceInfo.getUrl().trim())) { - if (!RegExpTestUtil.urlRegExpTest(microServiceInfo.getUrl())) { - throw new UnprocessableEntityException( - "register MicroServiceInfo FAIL:url is not a valid format(url must be begin with /)"); - - } - } - - - if (RouteUtil.PROTOCOL_LIST.indexOf(microServiceInfo.getProtocol().trim()) == -1) { - throw new UnprocessableEntityException( - "register MicroServiceInfo FAIL:Protocol is wrong,value range:(" - + RouteUtil.PROTOCOL_LIST + ")"); - } - - } - - - public static String getAPIRedisPrefixedKey(String routeName, String version, String host,String publish_port,String routeWay){ - String redisPrefixedKey; - if(ROUTEWAY_DOMAIN.equals(routeWay)){ - redisPrefixedKey= RouteUtil.getPrefixedKey4Host(host, APIROUTE, routeName, version); - } - else{ - redisPrefixedKey=RouteUtil.getPrefixedKey(publish_port, APIROUTE, routeName, version); - } - - return redisPrefixedKey; - } - - public static String getRedisPrefixedKey(String routeType,String routeName, String host,String publish_port,String routeWay){ + + + public static String getAPIRedisPrefixedKey(String routeName, String version, String host, String publish_port, + String routeWay) { String redisPrefixedKey; - if(ROUTEWAY_DOMAIN.equals(routeWay)){ - redisPrefixedKey= RouteUtil.getPrefixedKey4Host(host, routeType, routeName); + if (ROUTEWAY_DOMAIN.equals(routeWay)) { + redisPrefixedKey = RouteUtil.getPrefixedKey4Host(host, APIROUTE, routeName, version); + } else { + redisPrefixedKey = RouteUtil.getPrefixedKey(publish_port, APIROUTE, routeName, version); } - else{ - redisPrefixedKey=RouteUtil.getPrefixedKey(publish_port, routeType, routeName); + + return redisPrefixedKey; + } + + public static String getRedisPrefixedKey(String routeType, String routeName, String host, String publish_port, + String routeWay) { + String redisPrefixedKey; + if (ROUTEWAY_DOMAIN.equals(routeWay)) { + redisPrefixedKey = RouteUtil.getPrefixedKey4Host(host, routeType, routeName); + } else { + redisPrefixedKey = RouteUtil.getPrefixedKey(publish_port, routeType, routeName); } - + return redisPrefixedKey; - } - - public static String getMutiRedisKey(String routeType,String routeWay){ - String redisKey; - if(RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay)){ - redisKey = - RouteUtil.getPrefixedKey4Host("*", routeType, "*"); - - } - else{ - redisKey = - RouteUtil.getPrefixedKey("[^h]*", routeType, "*"); - - } - - return redisKey; - } - - /** - * @Title getRouteNameByns - * @Description TODO(根据服务名和命名空间拆分服务路由名) - * @param serviceName - * @param namespace - * @return - * @return String - */ - public static String getRouteNameByns(String consul_serviceName,String namespace){ - String serviceName=consul_serviceName; - if(StringUtils.isNotBlank(namespace)){ - if(consul_serviceName.endsWith("-"+namespace)){ - serviceName=consul_serviceName.substring(0,consul_serviceName.length()-namespace.length()-1); - } - } - - return serviceName; - } - - public static String getVisualRangeByRouter(String visualRange){ - String[] rangs = StringUtils.split(visualRange, "|"); - if(rangs.length>1){ - String visualRangeMatches=ConfigUtil.getInstance().getVisualRangeMatches(); - if(StringUtils.split(visualRangeMatches, "|").length>1){ - return "0"; - } - else{ - return visualRangeMatches; - } - } - else{ - return visualRange; - } - - } - - + } + + public static String getMutiRedisKey(String routeType, String routeWay) { + String redisKey; + if (RouteUtil.ROUTEWAY_DOMAIN.equals(routeWay)) { + redisKey = RouteUtil.getPrefixedKey4Host("*", routeType, "*"); + + } else { + redisKey = RouteUtil.getPrefixedKey("[^h]*", routeType, "*"); + + } + + return redisKey; + } + + /** + * @Title getRouteNameByns + * @Description TODO(根据服务名和命名空间拆分服务路由名) + * @param serviceName + * @param namespace + * @return + * @return String + */ + public static String getRouteNameByns(String consul_serviceName, String namespace) { + String serviceName = consul_serviceName; + if (StringUtils.isNotBlank(namespace)) { + if (consul_serviceName.endsWith("-" + namespace)) { + serviceName = consul_serviceName.substring(0, consul_serviceName.length() - namespace.length() - 1); + } + } + + return serviceName; + } + + public static String getVisualRangeByRouter(String visualRange) { + String[] rangs = StringUtils.split(visualRange, "|"); + if (rangs.length > 1) { + String visualRangeMatches = ConfigUtil.getInstance().getVisualRangeMatches(); + if (StringUtils.split(visualRangeMatches, "|").length > 1) { + return "0"; + } else { + return visualRangeMatches; + } + } else { + return visualRange; + } + + } + + } diff --git a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/ServiceFilter.java b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/ServiceFilter.java index 1548128..543687b 100644 --- a/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/ServiceFilter.java +++ b/apiroute/apiroute-service/src/main/java/org/onap/msb/apiroute/wrapper/util/ServiceFilter.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -35,496 +33,477 @@ import com.orbitz.consul.model.health.HealthCheck; public class ServiceFilter { - private static ServiceFilter instance = new ServiceFilter(); - - private ServiceFilter() {} - - public static ServiceFilter getInstance() { - return instance; - } - - private static final Logger LOGGER = LoggerFactory.getLogger(ServiceFilter.class); - - - /** - * Determine whether the service needs to send a notification TODO: filter according to the - * agreement, the only notice of agreement for REST \HTTP\ UI interface MSB - REST - * - * @param protocol - * @return - */ - public boolean isNeedNotifyByProtocol(String protocol) { - return CommonUtil.contain(RouteUtil.FILTER_PROTOCOLS, protocol.trim()); - } - - /** - * Determine whether the service needs to send a notification TODO: according to the visual range - * filter conditions Regular language: all 、 default 、 !default 、 A、 |A 、 A|B、 !A&!B - * - * @param visualRange - * @return - */ - public boolean isNeedNotifyByNameSpace(String nameSpace) { - - String namespaceMatches = ConfigUtil.getInstance().getNamespaceMatches(); - String[] namespaceArray = StringUtils.split(namespaceMatches, "|"); - - if (CommonUtil.contain(namespaceArray, "all")) { - return true; - } + private static ServiceFilter instance = new ServiceFilter(); - if (CommonUtil.contain(namespaceArray, "default")) { - if (StringUtils.isEmpty(nameSpace) || "default".equals(nameSpace) ) { - return true; - } else { - return false; - } - } + private ServiceFilter() {} - if (CommonUtil.contain(namespaceArray, "!default")) { - if (StringUtils.isNotEmpty(nameSpace) && !"default".equals(nameSpace)) { - return true; - } else { - return false; - } + public static ServiceFilter getInstance() { + return instance; } - try { - String namespaceReg; - if (namespaceMatches.contains("!")) { - namespaceReg = "^" + namespaceMatches.replaceAll("!", "").replaceAll("&", "|") + "$"; - return !Pattern.matches(namespaceReg, nameSpace); - } else { - namespaceReg = "^" + namespaceMatches + "$"; - return Pattern.matches(namespaceReg, nameSpace); - } - - } catch (Exception e) { - LOGGER.error(" Regular " + namespaceMatches + " throw exception:" + e.getMessage()); - return false; + + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceFilter.class); + + + /** + * Determine whether the service needs to send a notification TODO: filter according to the + * agreement, the only notice of agreement for REST \HTTP\ UI interface MSB - REST + * + * @param protocol + * @return + */ + public boolean isNeedNotifyByProtocol(String protocol) { + return CommonUtil.contain(RouteUtil.FILTER_PROTOCOLS, protocol.trim()); } - } - public boolean isNeedNotifyByVisualRange(String visualRange) { + /** + * Determine whether the service needs to send a notification TODO: according to the visual + * range filter conditions Regular language: all 、 default 、 !default 、 A、 |A 、 A|B、 !A&!B + * + * @param visualRange + * @return + */ + public boolean isNeedNotifyByNameSpace(String nameSpace) { - String[] routeVisualRangeArray = - StringUtils.split(ConfigUtil.getInstance().getVisualRangeMatches(), "|"); + String namespaceMatches = ConfigUtil.getInstance().getNamespaceMatches(); + String[] namespaceArray = StringUtils.split(namespaceMatches, "|"); - String[] serviceVisualRangeArray = StringUtils.split(visualRange, "|"); + if (CommonUtil.contain(namespaceArray, "all")) { + return true; + } - if (CommonUtil.contain(serviceVisualRangeArray, routeVisualRangeArray)) { - return true; - } + if (CommonUtil.contain(namespaceArray, "default")) { + if (StringUtils.isEmpty(nameSpace) || "default".equals(nameSpace)) { + return true; + } else { + return false; + } + } + + if (CommonUtil.contain(namespaceArray, "!default")) { + if (StringUtils.isNotEmpty(nameSpace) && !"default".equals(nameSpace)) { + return true; + } else { + return false; + } + } + try { + String namespaceReg; + if (namespaceMatches.contains("!")) { + namespaceReg = "^" + namespaceMatches.replaceAll("!", "").replaceAll("&", "|") + "$"; + return !Pattern.matches(namespaceReg, nameSpace); + } else { + namespaceReg = "^" + namespaceMatches + "$"; + return Pattern.matches(namespaceReg, nameSpace); + } - return false; + } catch (Exception e) { + LOGGER.error(" Regular " + namespaceMatches + " throw exception:" + e.getMessage()); + return false; + } + } - } + public boolean isNeedNotifyByVisualRange(String visualRange) { - public boolean isNeedNotifyByNetwork_plane_typeMatches(String network_plane_type) { + String[] routeVisualRangeArray = StringUtils.split(ConfigUtil.getInstance().getVisualRangeMatches(), "|"); - String network_plane_typeMatches = ConfigUtil.getInstance().getNetwork_plane_typeMatches(); - if (StringUtils.isBlank(network_plane_typeMatches)) - return true; + String[] serviceVisualRangeArray = StringUtils.split(visualRange, "|"); - String[] routeNetwork_plane_typeArray = StringUtils.split(network_plane_typeMatches, "|"); + if (CommonUtil.contain(serviceVisualRangeArray, routeVisualRangeArray)) { + return true; + } - String[] serviceVisualRangeArray = StringUtils.split(network_plane_type, "|"); + return false; - if (CommonUtil.contain(serviceVisualRangeArray, routeNetwork_plane_typeArray)) { - return true; } - return false; + public boolean isNeedNotifyByNetwork_plane_typeMatches(String network_plane_type) { + + String network_plane_typeMatches = ConfigUtil.getInstance().getNetwork_plane_typeMatches(); + if (StringUtils.isBlank(network_plane_typeMatches)) + return true; + + String[] routeNetwork_plane_typeArray = StringUtils.split(network_plane_typeMatches, "|"); - } + String[] serviceVisualRangeArray = StringUtils.split(network_plane_type, "|"); - /** - * Determine whether the service needs to send a notification TODO: according to the visual range - * filter conditions - * - * @param visualRange - * @return - */ - public boolean isNeedNotifyByRouteLabels(Map<String, String> labelMap) { + if (CommonUtil.contain(serviceVisualRangeArray, routeNetwork_plane_typeArray)) { + return true; + } - Map<String, String> labelMapMatches = ConfigUtil.getInstance().getLabelMapMatches(); + return false; - if (labelMapMatches == null || labelMapMatches.isEmpty()) { - return true; } - for (Map.Entry<String, String> entry : labelMapMatches.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); + /** + * Determine whether the service needs to send a notification TODO: according to the visual + * range filter conditions + * + * @param visualRange + * @return + */ + public boolean isNeedNotifyByRouteLabels(Map<String, String> labelMap) { - // Multiple values match + Map<String, String> labelMapMatches = ConfigUtil.getInstance().getLabelMapMatches(); - if (StringUtils.isBlank(labelMap.get(key))) { - continue; - } + if (labelMapMatches == null || labelMapMatches.isEmpty()) { + return true; + } - String[] routeLalelsArray = StringUtils.split(value, "|"); + for (Map.Entry<String, String> entry : labelMapMatches.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); - String[] serviceLabelsArray = StringUtils.split(labelMap.get(key), "|"); + // Multiple values match - if (CommonUtil.contain(routeLalelsArray, serviceLabelsArray)) { - return true; - } + if (StringUtils.isBlank(labelMap.get(key))) { + continue; + } - } + String[] routeLalelsArray = StringUtils.split(value, "|"); - return false; - } - - - - /* - * public boolean isNeedNotifyByRoute(String protocol, String namespace, String visualRange, - * String network_plane_type, Map<String, String> labelMap) { - * - * return isNeedNotifyByProtocol(protocol) && isNeedNotifyByNameSpace(namespace) && - * isNeedNotifyByVisualRange(visualRange) && isNeedNotifyByRouteLabels(labelMap) && - * isNeedNotifyByNetwork_plane_typeMatches(network_plane_type); - * - * } - */ - - public boolean isFilterCheck(ServiceHealth health){ - return isFilterHealthCheck(health.getChecks()) && isFilterService(health.getService().getTags()); - } - - /** - * @Title isFilterHealthCheck - * @Description TODO(判断服务实例的健康检查信息,全部为passing表示健康检查有效) - * @param List<HealthCheck> - * @return boolean checkList示例——"Checks" : [{ - "Node" : "server", - "CheckID" : "serfHealth", - "Name" : "Serf Health Status", - "Status" : "passing", - "Notes" : "", - "Output" : "Agent alive and reachable", - "ServiceID" : "", - "ServiceName" : "", - "CreateIndex" : 65536, - "ModifyIndex" : 65536 - }, { - "Node" : "server", - "CheckID" : "service:_tcp_roundrobin_1_10.74.151.26_22", - "Name" : "Service 'tcp_roundrobin_1' check", - "Status" : "critical", - "Notes" : "", - "Output" : "dial tcp: missing port in address ok", - "ServiceID" : "_tcp_roundrobin_1_10.74.151.26_22", - "ServiceName" : "tcp_roundrobin_1", - "CreateIndex" : 75988, - "ModifyIndex" : 76173 + String[] serviceLabelsArray = StringUtils.split(labelMap.get(key), "|"); + + if (CommonUtil.contain(routeLalelsArray, serviceLabelsArray)) { + return true; } - ] - */ - public boolean isFilterHealthCheck(List<HealthCheck> checkList){ - if(checkList.isEmpty()){ - return true; - } - - for (HealthCheck check : checkList) { - if (!RouteUtil.HEALTH_CHECK_PASSING.equals(check.getStatus())) { + + } + return false; - } } - - return true; - } - - - - /** - * @Title isFilterService - * @Description TODO(判断来自consul的服务信息是否需要过滤) - * @param List<String> - * @return boolean tagList示例—— [ - * "\"base\":{\"protocol\":\"REST\",\"is_manual\":\"true\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}" - * , "\"ns\":{\"namespace\":\"nsName\"}", - * "\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}" - * ] - */ - @SuppressWarnings("unchecked") - public boolean isFilterService(List<String> tagList) { - - if (tagList == null || tagList.size() == 0) - return false; - - String visualRange = "", network_plane_type = "", protocol = "", namespace = ""; - - //针对多版本不同属性的tag会有多个,只要其中一个匹配即通过过滤,默认不通过 - boolean visualRangeFilter=false,protocolFilter = false, namespaceFilter = false; - boolean hasnamespace=false; - - try { - - for (String tag : tagList) { - - // 提取基础属性tag - if (!protocolFilter && tag.startsWith("\"base\"")) { - String ms_base_json = tag.split("\"base\":")[1]; - - Map<String, String> baseMap = - (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_base_json, Map.class); - - if (baseMap.get("protocol") != null) { - protocol = baseMap.get("protocol"); - if ("PORTAL".equalsIgnoreCase(protocol)) { - protocol = "HTTP"; - } - - if (isNeedNotifyByProtocol(protocol)) { - protocolFilter=true; - } - } - - continue; - } + /* + * public boolean isNeedNotifyByRoute(String protocol, String namespace, String visualRange, + * String network_plane_type, Map<String, String> labelMap) { + * + * return isNeedNotifyByProtocol(protocol) && isNeedNotifyByNameSpace(namespace) && + * isNeedNotifyByVisualRange(visualRange) && isNeedNotifyByRouteLabels(labelMap) && + * isNeedNotifyByNetwork_plane_typeMatches(network_plane_type); + * + * } + */ - // 提取命名空间属性tag - if (!namespaceFilter && tag.startsWith("\"ns\"")) { - String ms_ns_json = tag.split("\"ns\":")[1]; - Map<String, String> nsMap = - (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_ns_json, Map.class); - - if (nsMap.get("namespace") != null) { - namespace = nsMap.get("namespace"); - hasnamespace=true; - - if (isNeedNotifyByNameSpace(namespace)) { - namespaceFilter=true; - } - } + public boolean isFilterCheck(ServiceHealth health) { + return isFilterHealthCheck(health.getChecks()) && isFilterService(health.getService().getTags()); + } - - continue; + /** + * @Title isFilterHealthCheck + * @Description TODO(判断服务实例的健康检查信息,全部为passing表示健康检查有效) + * @param List<HealthCheck> + * @return boolean checkList示例——"Checks" : [{ "Node" : "server", "CheckID" : "serfHealth", + * "Name" : "Serf Health Status", "Status" : "passing", "Notes" : "", "Output" : "Agent + * alive and reachable", "ServiceID" : "", "ServiceName" : "", "CreateIndex" : 65536, + * "ModifyIndex" : 65536 }, { "Node" : "server", "CheckID" : + * "service:_tcp_roundrobin_1_10.74.151.26_22", "Name" : "Service 'tcp_roundrobin_1' + * check", "Status" : "critical", "Notes" : "", "Output" : "dial tcp: missing port in + * address ok", "ServiceID" : "_tcp_roundrobin_1_10.74.151.26_22", "ServiceName" : + * "tcp_roundrobin_1", "CreateIndex" : 75988, "ModifyIndex" : 76173 } ] + */ + public boolean isFilterHealthCheck(List<HealthCheck> checkList) { + if (checkList.isEmpty()) { + return true; } - // 提取Label属性tag - if (tag.startsWith("\"labels\"")) { - String ms_labels_json = "{" + tag.split("\"labels\":\\{")[1]; - // 自定义label标签属性 - Map<String, String> labelMap = - (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_labels_json, Map.class); - - - - if (!visualRangeFilter && labelMap.get("visualRange") != null) { - visualRange = labelMap.get("visualRange"); - labelMap.remove("visualRange"); // 自定义标签排除可见范围和网络平面 - - if(isNeedNotifyByVisualRange(visualRange)){ - visualRangeFilter=true; + for (HealthCheck check : checkList) { + if (!RouteUtil.HEALTH_CHECK_PASSING.equals(check.getStatus())) { + return false; } - } - - - if (labelMap.get("network_plane_type") != null) { - network_plane_type = labelMap.get("network_plane_type"); - labelMap.remove("network_plane_type"); - } - if (!isNeedNotifyByNetwork_plane_typeMatches(network_plane_type)) { - return false; - } + } + + return true; + } + + + + /** + * @Title isFilterService + * @Description TODO(判断来自consul的服务信息是否需要过滤) + * @param List<String> + * @return boolean tagList示例—— [ + * "\"base\":{\"protocol\":\"REST\",\"is_manual\":\"true\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}" + * , "\"ns\":{\"namespace\":\"nsName\"}", + * "\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}" + * ] + */ + @SuppressWarnings("unchecked") + public boolean isFilterService(List<String> tagList) { - if (!isNeedNotifyByRouteLabels(labelMap)) { + if (tagList == null || tagList.size() == 0) return false; - } - continue; - } + String visualRange = "", network_plane_type = "", protocol = "", namespace = ""; - } + // 针对多版本不同属性的tag会有多个,只要其中一个匹配即通过过滤,默认不通过 + boolean visualRangeFilter = false, protocolFilter = false, namespaceFilter = false; + boolean hasnamespace = false; - //针对无命名空间的服务判断是否过滤 - if (!hasnamespace && isNeedNotifyByNameSpace(namespace)) { - namespaceFilter=true; - } + try { - return visualRangeFilter && protocolFilter && namespaceFilter; + for (String tag : tagList) { + // 提取基础属性tag + if (!protocolFilter && tag.startsWith("\"base\"")) { + String ms_base_json = tag.split("\"base\":")[1]; - } catch (Exception e) { - LOGGER.error(" read tag throw exception", e); - return false; - } + Map<String, String> baseMap = + (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_base_json, Map.class); + if (baseMap.get("protocol") != null) { + protocol = baseMap.get("protocol"); + if ("PORTAL".equalsIgnoreCase(protocol)) { + protocol = "HTTP"; + } - } - + if (isNeedNotifyByProtocol(protocol)) { + protocolFilter = true; + } + } - @SuppressWarnings("unchecked") - public Map<String, MicroServiceFullInfo> transMicroServiceInfoFromConsul( - List<ServiceHealth> serviceNodeList) { - // 同名多版本服务MAP - Map<String, MicroServiceFullInfo> microServiceInfo4version = - new HashMap<String, MicroServiceFullInfo>(); - for (ServiceHealth serviceNode : serviceNodeList) { + continue; + } - MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); - String url = ""; - String version = "", visualRange = "", protocol = "", lb_policy = "", namespace = - "", host = "", path = "", publish_port = ""; - boolean enable_ssl = false; + // 提取命名空间属性tag + if (!namespaceFilter && tag.startsWith("\"ns\"")) { + String ms_ns_json = tag.split("\"ns\":")[1]; + Map<String, String> nsMap = (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_ns_json, Map.class); - HashSet<Node> nodes = new HashSet<Node>(); + if (nsMap.get("namespace") != null) { + namespace = nsMap.get("namespace"); + hasnamespace = true; - Service service = serviceNode.getService(); - String serviceName = service.getService(); + if (isNeedNotifyByNameSpace(namespace)) { + namespaceFilter = true; + } + } - try { - List<String> tagList = service.getTags(); - for (String tag : tagList) { + continue; + } - if (tag.startsWith("\"base\"")) { - String ms_base_json = tag.split("\"base\":")[1]; + // 提取Label属性tag + if (tag.startsWith("\"labels\"")) { + String ms_labels_json = "{" + tag.split("\"labels\":\\{")[1]; + // 自定义label标签属性 + Map<String, String> labelMap = + (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_labels_json, Map.class); - Map<String, String> baseMap = - (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_base_json, Map.class); - if (baseMap.get("url") != null) { - url = baseMap.get("url"); - } - if (baseMap.get("version") != null) { - version = baseMap.get("version"); - } + if (!visualRangeFilter && labelMap.get("visualRange") != null) { + visualRange = labelMap.get("visualRange"); + labelMap.remove("visualRange"); // 自定义标签排除可见范围和网络平面 - if (baseMap.get("protocol") != null) { - protocol = baseMap.get("protocol"); - } + if (isNeedNotifyByVisualRange(visualRange)) { + visualRangeFilter = true; + } + } - if (baseMap.get("host") != null) { - host = baseMap.get("host"); - } - if (baseMap.get("path") != null) { - path = baseMap.get("path"); + if (labelMap.get("network_plane_type") != null) { + network_plane_type = labelMap.get("network_plane_type"); + labelMap.remove("network_plane_type"); + } + if (!isNeedNotifyByNetwork_plane_typeMatches(network_plane_type)) { + return false; + } + + if (!isNeedNotifyByRouteLabels(labelMap)) { + return false; + } + + continue; + } + } - if (baseMap.get("publish_port") != null) { - publish_port = baseMap.get("publish_port"); + // 针对无命名空间的服务判断是否过滤 + if (!hasnamespace && isNeedNotifyByNameSpace(namespace)) { + namespaceFilter = true; } + return visualRangeFilter && protocolFilter && namespaceFilter; - if (baseMap.get("enable_ssl") != null) { - enable_ssl = Boolean.valueOf(baseMap.get("enable_ssl")); - } - continue; - } + } catch (Exception e) { + LOGGER.error(" read tag throw exception", e); + return false; + } + + } - if (tag.startsWith("\"ns\"")) { - String ms_ns_json = tag.split("\"ns\":")[1]; - Map<String, String> nsMap = - (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_ns_json, Map.class); - if (nsMap.get("namespace") != null) { - namespace = nsMap.get("namespace"); - } + @SuppressWarnings("unchecked") + public Map<String, MicroServiceFullInfo> transMicroServiceInfoFromConsul(List<ServiceHealth> serviceNodeList) { + // 同名多版本服务MAP + Map<String, MicroServiceFullInfo> microServiceInfo4version = new HashMap<String, MicroServiceFullInfo>(); - continue; - } - if (tag.startsWith("\"labels\"")) { - String ms_labels_json = "{" + tag.split("\"labels\":\\{")[1]; - Map<String, String> labelMap = - (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_labels_json, Map.class); + for (ServiceHealth serviceNode : serviceNodeList) { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + String url = ""; + String version = "", visualRange = "", protocol = "", lb_policy = "", namespace = "", host = "", path = "", + publish_port = ""; + boolean enable_ssl = false; - if (labelMap.get("visualRange") != null) { - visualRange = labelMap.get("visualRange"); - } + HashSet<Node> nodes = new HashSet<Node>(); - /*if (labelMap.get("network_plane_type") != null) { - network_plane_type = labelMap.get("network_plane_type"); - }*/ + Service service = serviceNode.getService(); + String serviceName = service.getService(); - continue; - } + try { + List<String> tagList = service.getTags(); - if (tag.startsWith("\"lb\"")) { - String ms_lb_json = tag.split("\"lb\":")[1]; - Map<String, String> lbMap = - (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_lb_json, Map.class); + for (String tag : tagList) { - if (lbMap.get("lb_policy") != null) { - lb_policy = lbMap.get("lb_policy"); - } - continue; - } + if (tag.startsWith("\"base\"")) { + String ms_base_json = tag.split("\"base\":")[1]; - } + Map<String, String> baseMap = + (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_base_json, Map.class); + if (baseMap.get("url") != null) { + url = baseMap.get("url"); + } + if (baseMap.get("version") != null) { + version = baseMap.get("version"); + } - } catch (Exception e) { - LOGGER.error(serviceName + " read tag throw exception", e); - } + if (baseMap.get("protocol") != null) { + protocol = baseMap.get("protocol"); + } - if (!microServiceInfo4version.containsKey(version)) { + if (baseMap.get("host") != null) { + host = baseMap.get("host"); + } - if ("PORTAL".equalsIgnoreCase(protocol)) { - protocol = "HTTP"; - microServiceInfo.setCustom(RouteUtil.CUSTOM_PORTAL); - } + if (baseMap.get("path") != null) { + path = baseMap.get("path"); + } - microServiceInfo.setProtocol(protocol); - microServiceInfo.setUrl(url); - microServiceInfo.setServiceName(serviceName); - microServiceInfo.setLb_policy(lb_policy); - microServiceInfo.setVisualRange(visualRange); - - microServiceInfo.setEnable_ssl(enable_ssl); - microServiceInfo.setVersion(version); - microServiceInfo.setNamespace(namespace); - microServiceInfo.setHost(host); - microServiceInfo.setPath(path); - //系统间apigateway 保存publish_port - if ("0".equals(ConfigUtil.getInstance().getVisualRangeMatches())) { - microServiceInfo.setPublish_port(publish_port); - } + if (baseMap.get("publish_port") != null) { + publish_port = baseMap.get("publish_port"); + } - nodes.add(new Node(service.getAddress(), String.valueOf(service.getPort()))); - microServiceInfo.setNodes(nodes); - microServiceInfo4version.put(version, microServiceInfo); - } else { + if (baseMap.get("enable_ssl") != null) { + enable_ssl = Boolean.valueOf(baseMap.get("enable_ssl")); + } - Set<Node> newNodes = microServiceInfo4version.get(version).getNodes(); - // 默认node是注册信息的IP和port - newNodes.add(new Node(service.getAddress(), String.valueOf(service.getPort()))); + continue; + } - // 同名多版本同步 - microServiceInfo4version.get(version).setNodes(newNodes); - } + if (tag.startsWith("\"ns\"")) { + String ms_ns_json = tag.split("\"ns\":")[1]; + Map<String, String> nsMap = + (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_ns_json, Map.class); - /* - * // 健康检查信息 List<Check> checks = value.getChecks(); node.setStatus("passing"); for (Check - * check : checks) { if (!"passing".equals(check.getStatus())) { - * node.setStatus(check.getStatus()); break; } } - */ + if (nsMap.get("namespace") != null) { + namespace = nsMap.get("namespace"); + } + continue; + } + if (tag.startsWith("\"labels\"")) { + String ms_labels_json = "{" + tag.split("\"labels\":\\{")[1]; + Map<String, String> labelMap = + (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_labels_json, Map.class); - } - return microServiceInfo4version; + if (labelMap.get("visualRange") != null) { + visualRange = labelMap.get("visualRange"); + } + + /* + * if (labelMap.get("network_plane_type") != null) { network_plane_type = + * labelMap.get("network_plane_type"); } + */ + + continue; + } + + if (tag.startsWith("\"lb\"")) { + String ms_lb_json = tag.split("\"lb\":")[1]; + Map<String, String> lbMap = + (Map<String, String>) JacksonJsonUtil.jsonToBean(ms_lb_json, Map.class); - } + if (lbMap.get("lb_policy") != null) { + lb_policy = lbMap.get("lb_policy"); + } + continue; + } + + } + + + + } catch (Exception e) { + LOGGER.error(serviceName + " read tag throw exception", e); + } + + if (!microServiceInfo4version.containsKey(version)) { + + if ("PORTAL".equalsIgnoreCase(protocol)) { + protocol = "HTTP"; + microServiceInfo.setCustom(RouteUtil.CUSTOM_PORTAL); + } + + microServiceInfo.setProtocol(protocol); + microServiceInfo.setUrl(url); + microServiceInfo.setServiceName(serviceName); + microServiceInfo.setLb_policy(lb_policy); + microServiceInfo.setVisualRange(visualRange); + + microServiceInfo.setEnable_ssl(enable_ssl); + microServiceInfo.setVersion(version); + microServiceInfo.setNamespace(namespace); + microServiceInfo.setHost(host); + microServiceInfo.setPath(path); + // 系统间apigateway 保存publish_port + if ("0".equals(ConfigUtil.getInstance().getVisualRangeMatches())) { + microServiceInfo.setPublish_port(publish_port); + } + + nodes.add(new Node(service.getAddress(), String.valueOf(service.getPort()))); + microServiceInfo.setNodes(nodes); + + microServiceInfo4version.put(version, microServiceInfo); + } else { + + Set<Node> newNodes = microServiceInfo4version.get(version).getNodes(); + // 默认node是注册信息的IP和port + newNodes.add(new Node(service.getAddress(), String.valueOf(service.getPort()))); + + // 同名多版本同步 + microServiceInfo4version.get(version).setNodes(newNodes); + + } + + + /* + * // 健康检查信息 List<Check> checks = value.getChecks(); node.setStatus("passing"); for + * (Check check : checks) { if (!"passing".equals(check.getStatus())) { + * node.setStatus(check.getStatus()); break; } } + */ + + + + } + + return microServiceInfo4version; + + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/SyncDataManagerTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/SyncDataManagerTest.java index e6ab926..91ee211 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/SyncDataManagerTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/SyncDataManagerTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute; @@ -19,7 +17,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.onap.msb.apiroute.SyncDataManager; import org.onap.msb.apiroute.wrapper.consulextend.async.ConsulResponseCallback; import org.onap.msb.apiroute.wrapper.consulextend.util.Http; import org.powermock.api.mockito.PowerMockito; @@ -30,42 +27,33 @@ import org.powermock.modules.junit4.PowerMockRunner; import com.fasterxml.jackson.core.type.TypeReference; @RunWith(PowerMockRunner.class) -@PrepareForTest({ Http.class }) -@PowerMockIgnore({ "javax.net.ssl.*" }) +@PrepareForTest({Http.class}) +@PowerMockIgnore({"javax.net.ssl.*"}) public class SyncDataManagerTest { - @SuppressWarnings("unchecked") - @Before - public void setUpBeforeTest() { - Http http = PowerMockito.mock(Http.class); + @SuppressWarnings("unchecked") + @Before + public void setUpBeforeTest() { + Http http = PowerMockito.mock(Http.class); - PowerMockito - .doNothing() - .when(http) - .asyncGet(Mockito.anyString(), - Mockito.any(TypeReference.class), - Mockito.any(ConsulResponseCallback.class)); + PowerMockito.doNothing().when(http).asyncGet(Mockito.anyString(), Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); - PowerMockito - .doNothing() - .when(http) - .asyncGetDelayHandle(Mockito.anyString(), - Mockito.any(TypeReference.class), - Mockito.any(ConsulResponseCallback.class)); + PowerMockito.doNothing().when(http).asyncGetDelayHandle(Mockito.anyString(), Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); - // - PowerMockito.spy(Http.class); - PowerMockito.when(Http.getInstance()).thenReturn(http); + // + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); - } - - @Test - public void testSyncDataManager() - { - SyncDataManager.initSyncTask("127.0.0.1",8500); - SyncDataManager.startWatchService("huangleibo"); - SyncDataManager.resetIndex("huangleibo"); - SyncDataManager.stopWatchService("huangleibo"); - SyncDataManager.stopWatchServiceList(); - } + } + + @Test + public void testSyncDataManager() { + SyncDataManager.initSyncTask("127.0.0.1", 8500); + SyncDataManager.startWatchService("huangleibo"); + SyncDataManager.resetIndex("huangleibo"); + SyncDataManager.stopWatchService("huangleibo"); + SyncDataManager.stopWatchServiceList(); + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ApiRouteHealthCheckTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ApiRouteHealthCheckTest.java index 46c0632..a8223eb 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ApiRouteHealthCheckTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ApiRouteHealthCheckTest.java @@ -1,24 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.health; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.onap.msb.apiroute.health.ApiRouteHealthCheck; import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -29,56 +26,49 @@ import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck.Result; @RunWith(PowerMockRunner.class) -@PrepareForTest({ HttpClientUtil.class }) +@PrepareForTest({HttpClientUtil.class}) public class ApiRouteHealthCheckTest { - private static final Logger LOGGER = LoggerFactory - .getLogger(ApiRouteHealthCheckTest.class); - - @Test - public void testchecksuccess() - { - PowerMockito.mockStatic(HttpClientUtil.class); - try { - - PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(200); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - ApiRouteHealthCheck check = new ApiRouteHealthCheck(); - Result rst = check.execute(); - - if (!rst.isHealthy()) { - LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); - } - else - { - LOGGER.debug(" testchecksuccess health"); - } - } - - @Test - public void testcheckfailed() - { - PowerMockito.mockStatic(HttpClientUtil.class); - try { - - PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - ApiRouteHealthCheck check = new ApiRouteHealthCheck(); - Result rst = check.execute(); - - if (!rst.isHealthy()) { - LOGGER.warn("testcheckfailed health check failed:"+rst.getMessage()); - } - else - { - LOGGER.debug(" testcheckfailed health"); - } - } + private static final Logger LOGGER = LoggerFactory.getLogger(ApiRouteHealthCheckTest.class); + + @Test + public void testchecksuccess() { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(200); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ApiRouteHealthCheck check = new ApiRouteHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:" + rst.getMessage()); + } else { + LOGGER.debug(" testchecksuccess health"); + } + } + + @Test + public void testcheckfailed() { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ApiRouteHealthCheck check = new ApiRouteHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testcheckfailed health check failed:" + rst.getMessage()); + } else { + LOGGER.debug(" testcheckfailed health"); + } + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheckTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheckTest.java index 309192a..2b1bc4f 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheckTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/ConsulLinkHealthCheckTest.java @@ -1,24 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.health; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.onap.msb.apiroute.health.ConsulLinkHealthCheck; import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -29,90 +26,80 @@ import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck.Result; @RunWith(PowerMockRunner.class) -@PrepareForTest({ HttpClientUtil.class,ConsulLinkHealthCheck.class }) +@PrepareForTest({HttpClientUtil.class, ConsulLinkHealthCheck.class}) public class ConsulLinkHealthCheckTest { - private static final Logger LOGGER = LoggerFactory - .getLogger(ConsulLinkHealthCheckTest.class); - - @Test - public void testchecksuccess() - { - PowerMockito.mockStatic(HttpClientUtil.class); - try { - - PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(200); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("CONSUL_IP")).thenReturn("192.168.0.1"); - - ConsulLinkHealthCheck check = new ConsulLinkHealthCheck(); - Result rst = check.execute(); - - if (!rst.isHealthy()) { - LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); - } - else - { - LOGGER.debug(" testchecksuccess health"); - } - } - - @Test - public void testcheckfailed() - { - PowerMockito.mockStatic(HttpClientUtil.class); - try { - - PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("CONSUL_IP")).thenReturn("192.168.0.1"); - - ConsulLinkHealthCheck check = new ConsulLinkHealthCheck(); - Result rst = check.execute(); - - if (!rst.isHealthy()) { - LOGGER.warn("testcheckfailed health check failed:"+rst.getMessage()); - } - else - { - LOGGER.debug("testcheckfailed health"); - } - } - - - @Test - public void testcheckNoENV() - { - PowerMockito.mockStatic(HttpClientUtil.class); - try { - - PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("CONSUL_IP")).thenReturn(""); - - ConsulLinkHealthCheck check = new ConsulLinkHealthCheck(); - Result rst = check.execute(); - - if (!rst.isHealthy()) { - LOGGER.warn("testcheckNoENV health check failed:"+rst.getMessage()); - } - else - { - LOGGER.debug("testcheckNoENV health"); - } - } + private static final Logger LOGGER = LoggerFactory.getLogger(ConsulLinkHealthCheckTest.class); + + @Test + public void testchecksuccess() { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(200); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_IP")).thenReturn("192.168.0.1"); + + ConsulLinkHealthCheck check = new ConsulLinkHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:" + rst.getMessage()); + } else { + LOGGER.debug(" testchecksuccess health"); + } + } + + @Test + public void testcheckfailed() { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_IP")).thenReturn("192.168.0.1"); + + ConsulLinkHealthCheck check = new ConsulLinkHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testcheckfailed health check failed:" + rst.getMessage()); + } else { + LOGGER.debug("testcheckfailed health"); + } + } + + + @Test + public void testcheckNoENV() { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_IP")).thenReturn(""); + + ConsulLinkHealthCheck check = new ConsulLinkHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testcheckNoENV health check failed:" + rst.getMessage()); + } else { + LOGGER.debug("testcheckNoENV health"); + } + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/OpenRestyHealthCheckTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/OpenRestyHealthCheckTest.java index f147a04..2a22e5a 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/OpenRestyHealthCheckTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/OpenRestyHealthCheckTest.java @@ -1,24 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.health; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.onap.msb.apiroute.health.OpenRestyHealthCheck; import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -29,64 +26,57 @@ import org.slf4j.LoggerFactory; import com.codahale.metrics.health.HealthCheck.Result; @RunWith(PowerMockRunner.class) -@PrepareForTest({ HttpClientUtil.class,OpenRestyHealthCheck.class }) +@PrepareForTest({HttpClientUtil.class, OpenRestyHealthCheck.class}) public class OpenRestyHealthCheckTest { - private static final Logger LOGGER = LoggerFactory - .getLogger(OpenRestyHealthCheckTest.class); - - @Test - public void testchecksuccess() - { - PowerMockito.mockStatic(HttpClientUtil.class); - try { - - PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(200); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("HTTP_OVERWRITE_PORT")).thenReturn("10080"); - - OpenRestyHealthCheck check = new OpenRestyHealthCheck(); - - Result rst = check.execute(); - - if (!rst.isHealthy()) { - LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); - } - else - { - LOGGER.debug(" testchecksuccess health"); - } - } - - @Test - public void testcheckfailed() - { - PowerMockito.mockStatic(HttpClientUtil.class); - try { - - PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("HTTP_OVERWRITE_PORT")).thenReturn(""); - - OpenRestyHealthCheck check = new OpenRestyHealthCheck(); - - Result rst = check.execute(); - - if (!rst.isHealthy()) { - LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); - } - else - { - LOGGER.debug(" testchecksuccess health"); - } - } + private static final Logger LOGGER = LoggerFactory.getLogger(OpenRestyHealthCheckTest.class); + + @Test + public void testchecksuccess() { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(200); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("HTTP_OVERWRITE_PORT")).thenReturn("10080"); + + OpenRestyHealthCheck check = new OpenRestyHealthCheck(); + + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:" + rst.getMessage()); + } else { + LOGGER.debug(" testchecksuccess health"); + } + } + + @Test + public void testcheckfailed() { + PowerMockito.mockStatic(HttpClientUtil.class); + try { + + PowerMockito.when(HttpClientUtil.httpGetStatus(Mockito.anyString())).thenReturn(400); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("HTTP_OVERWRITE_PORT")).thenReturn(""); + + OpenRestyHealthCheck check = new OpenRestyHealthCheck(); + + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:" + rst.getMessage()); + } else { + LOGGER.debug(" testchecksuccess health"); + } + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/RedisHealthCheckTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/RedisHealthCheckTest.java index 0cd429b..16b874e 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/RedisHealthCheckTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/health/RedisHealthCheckTest.java @@ -1,24 +1,21 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.health; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.onap.msb.apiroute.health.RedisHealthCheck; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; import org.onap.msb.apiroute.wrapper.util.JedisUtil; import org.powermock.api.mockito.PowerMockito; @@ -28,65 +25,58 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; - import com.codahale.metrics.health.HealthCheck.Result; import com.fiftyonred.mock_jedis.MockJedisPool; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class RedisHealthCheckTest { - private static final Logger LOGGER = LoggerFactory - .getLogger(RedisHealthCheckTest.class); - - @Before + private static final Logger LOGGER = LoggerFactory.getLogger(RedisHealthCheckTest.class); + + @Before public void setUpBeforeTest() throws Exception { } - - @SuppressWarnings("static-access") - @Test - public void testchecksuccess() - { + + @SuppressWarnings("static-access") + @Test + public void testchecksuccess() { try { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); - PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); - - RedisHealthCheck check = new RedisHealthCheck(); - Result rst = check.execute(); - - if (!rst.isHealthy()) { - LOGGER.warn("testchecksuccess health check failed:"+rst.getMessage()); - } - else - { - LOGGER.debug(" testchecksuccess health"); - } - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testcheckfailed() - { - RedisHealthCheck check = new RedisHealthCheck(); - Result rst = check.execute(); - - if (!rst.isHealthy()) { - LOGGER.warn("testcheckfailed health check failed:"+rst.getMessage()); - } - else - { - LOGGER.debug("testcheckfailed health"); - } - - } + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + RedisHealthCheck check = new RedisHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testchecksuccess health check failed:" + rst.getMessage()); + } else { + LOGGER.debug(" testchecksuccess health"); + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testcheckfailed() { + RedisHealthCheck check = new RedisHealthCheck(); + Result rst = check.execute(); + + if (!rst.isHealthy()) { + LOGGER.warn("testcheckfailed health check failed:" + rst.getMessage()); + } else { + LOGGER.debug("testcheckfailed health"); + } + + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapperTest.java index 9f75b1b..4f3176b 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapperTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/ApiRouteServiceWrapperTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; @@ -26,13 +24,11 @@ import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.onap.msb.apiroute.api.ApiRouteInfo; import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.api.exception.ExtendedNotFoundException; -import org.onap.msb.apiroute.wrapper.ApiRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; import org.onap.msb.apiroute.wrapper.util.ConfigUtil; import org.onap.msb.apiroute.wrapper.util.JacksonJsonUtil; @@ -43,44 +39,44 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; -import com.fiftyonred.mock_jedis.MockJedisPool; - @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RouteUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RouteUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class ApiRouteServiceWrapperTest { private static ApiRouteServiceWrapper apiRouteServiceWrapper; private static Comparator<ApiRouteInfo> apiRouteComparator = null; - + @BeforeClass public static void setUpBeforeClass() throws Exception { - apiRouteServiceWrapper=ApiRouteServiceWrapper.getInstance(); + apiRouteServiceWrapper = ApiRouteServiceWrapper.getInstance(); apiRouteComparator = new Comparator<ApiRouteInfo>() { - @Override - public int compare(ApiRouteInfo o1, ApiRouteInfo o2) { - if (!o1.getServiceName().equals(o2.getServiceName())) - return (o1.getServiceName()).compareTo(o2.getServiceName()); - if (!o1.getVersion().equals(o2.getVersion())) - return (o1.getVersion()).compareTo(o2.getVersion()); - return 0; - } - }; - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); - PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); - ConfigUtil.getInstance().initRouteWay(); + @Override + public int compare(ApiRouteInfo o1, ApiRouteInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + if (!o1.getVersion().equals(o2.getVersion())) + return (o1.getVersion()).compareTo(o2.getVersion()); + return 0; + } + }; + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + ConfigUtil.getInstance().initRouteWay(); } - + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -90,163 +86,162 @@ public class ApiRouteServiceWrapperTest { } }); } - - + + @Test - public void test_getApiRouteInstance_not_exist(){ - try { - apiRouteServiceWrapper.getApiRouteInstance("testForJunit", "v1","","","ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ + public void test_getApiRouteInstance_not_exist() { + try { + apiRouteServiceWrapper.getApiRouteInstance("testForJunit", "v1", "", "", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { Assert.assertTrue(e instanceof ExtendedNotFoundException); } - + } - + @Test - public void test_getApiRouteInstance(){ - - ApiRouteInfo apirouteInfo = buildApiRouteInfo(); - try { - apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); - ApiRouteInfo dbApirouteInfo=apiRouteServiceWrapper.getApiRouteInstance("testapi", "v1", "", "", "ip"); - Assert.assertEquals(apirouteInfo,dbApirouteInfo ); - } catch (Exception e) { + public void test_getApiRouteInstance() { + + ApiRouteInfo apirouteInfo = buildApiRouteInfo(); + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); + ApiRouteInfo dbApirouteInfo = apiRouteServiceWrapper.getApiRouteInstance("testapi", "v1", "", "", "ip"); + Assert.assertEquals(apirouteInfo, dbApirouteInfo); + } catch (Exception e) { Assert.fail("throw exception means error occured!" + e.getMessage()); - } - + } + } - - - + + + @Test - public void test_getAllApiRouteInstances(){ - ApiRouteInfo apirouteInfo = buildApiRouteInfo(); - ApiRouteInfo apirouteInfo2 = buildApiRouteInfo2(); - List<ApiRouteInfo> expected = new ArrayList<>(); - expected.add(apirouteInfo); - expected.add(apirouteInfo2); - Collections.sort(expected, apiRouteComparator); - - try { - apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); - apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo2, "ip"); - - - PowerMockito.mockStatic(RouteUtil.class); - PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, "ip")).thenReturn("msb:routing:api:*"); - List<ApiRouteInfo> apiRouterList=apiRouteServiceWrapper.getAllApiRouteInstances("ip"); - Collections.sort(apiRouterList, apiRouteComparator); - - Assert.assertEquals(expected,apiRouterList); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - + public void test_getAllApiRouteInstances() { + ApiRouteInfo apirouteInfo = buildApiRouteInfo(); + ApiRouteInfo apirouteInfo2 = buildApiRouteInfo2(); + List<ApiRouteInfo> expected = new ArrayList<>(); + expected.add(apirouteInfo); + expected.add(apirouteInfo2); + Collections.sort(expected, apiRouteComparator); + + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo2, "ip"); + + + PowerMockito.mockStatic(RouteUtil.class); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, "ip")).thenReturn("msb:routing:api:*"); + List<ApiRouteInfo> apiRouterList = apiRouteServiceWrapper.getAllApiRouteInstances("ip"); + Collections.sort(apiRouterList, apiRouteComparator); + + Assert.assertEquals(expected, apiRouterList); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } - + @Test - public void test_updateApiRouteStatus(){ - ApiRouteInfo apirouteInfo = buildApiRouteInfo(); - try { - apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); - ApiRouteInfo dbApirouteInfo=apiRouteServiceWrapper.getApiRouteInstance("testapi", "v1", "", "", "ip"); - Assert.assertEquals("1",dbApirouteInfo.getStatus() ); - apiRouteServiceWrapper.updateApiRouteStatus("testapi","v1","","","0", "ip"); - dbApirouteInfo=apiRouteServiceWrapper.getApiRouteInstance("testapi", "v1", "", "", "ip"); - Assert.assertEquals("0",dbApirouteInfo.getStatus() ); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - + public void test_updateApiRouteStatus() { + ApiRouteInfo apirouteInfo = buildApiRouteInfo(); + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); + ApiRouteInfo dbApirouteInfo = apiRouteServiceWrapper.getApiRouteInstance("testapi", "v1", "", "", "ip"); + Assert.assertEquals("1", dbApirouteInfo.getStatus()); + apiRouteServiceWrapper.updateApiRouteStatus("testapi", "v1", "", "", "0", "ip"); + dbApirouteInfo = apiRouteServiceWrapper.getApiRouteInstance("testapi", "v1", "", "", "ip"); + Assert.assertEquals("0", dbApirouteInfo.getStatus()); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } - - - + + + @Test - public void test_deleteApiRoute(){ - ApiRouteInfo apirouteInfo2 = buildApiRouteInfo2(); - try { - apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo2, "ip"); - ApiRouteInfo dbApirouteInfo=apiRouteServiceWrapper.getApiRouteInstance("testapi2", "null","","","ip"); - Assert.assertNotNull(dbApirouteInfo); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - try { - apiRouteServiceWrapper.deleteApiRoute("testapi2", "null","","","ip"); - apiRouteServiceWrapper.getApiRouteInstance("testapi2", "","","","ip"); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } + public void test_deleteApiRoute() { + ApiRouteInfo apirouteInfo2 = buildApiRouteInfo2(); + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo2, "ip"); + ApiRouteInfo dbApirouteInfo = apiRouteServiceWrapper.getApiRouteInstance("testapi2", "null", "", "", "ip"); + Assert.assertNotNull(dbApirouteInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + apiRouteServiceWrapper.deleteApiRoute("testapi2", "null", "", "", "ip"); + apiRouteServiceWrapper.getApiRouteInstance("testapi2", "", "", "", "ip"); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } } - + @Test - public void test_getAllApiDocs(){ - String[] paths=apiRouteServiceWrapper.getAllApiDocs(); - String[] expecteds_paths={"api-doc1.json","api-doc2.json"}; - Arrays.sort(expecteds_paths); - Arrays.sort(paths); - Assert.assertArrayEquals(expecteds_paths, paths); + public void test_getAllApiDocs() { + String[] paths = apiRouteServiceWrapper.getAllApiDocs(); + String[] expecteds_paths = {"api-doc1.json", "api-doc2.json"}; + Arrays.sort(expecteds_paths); + Arrays.sort(paths); + Assert.assertArrayEquals(expecteds_paths, paths); } - + @Test - public void test_getAllrouteByJson(){ - ApiRouteInfo apirouteInfo = buildApiRouteInfo(); - try { - apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); - - ApiRouteInfo[] apirouteList={apirouteInfo}; - String expected_routeJson=JacksonJsonUtil.beanToJson(apirouteList); - - PowerMockito.mockStatic(RouteUtil.class); - PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, "ip")).thenReturn("msb:routing:api:*"); - PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, "ip")).thenReturn("msb:routing:iui:*"); - PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, "ip")).thenReturn("msb:routing:custom:*"); - - String allrouteJson= apiRouteServiceWrapper.getAllrouteByJson("ip"); - Assert.assertEquals(expected_routeJson, allrouteJson); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - - + public void test_getAllrouteByJson() { + ApiRouteInfo apirouteInfo = buildApiRouteInfo(); + try { + apiRouteServiceWrapper.saveApiRouteInstance4Rest(apirouteInfo, "ip"); + + ApiRouteInfo[] apirouteList = {apirouteInfo}; + String expected_routeJson = JacksonJsonUtil.beanToJson(apirouteList); + + PowerMockito.mockStatic(RouteUtil.class); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, "ip")).thenReturn("msb:routing:api:*"); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, "ip")).thenReturn("msb:routing:iui:*"); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, "ip")) + .thenReturn("msb:routing:custom:*"); + + String allrouteJson = apiRouteServiceWrapper.getAllrouteByJson("ip"); + Assert.assertEquals(expected_routeJson, allrouteJson); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + } - - - - private ApiRouteInfo buildApiRouteInfo(){ - ApiRouteInfo apirouteInfo = new ApiRouteInfo(); - apirouteInfo.setServiceName("testapi"); - apirouteInfo.setVersion("v1"); - apirouteInfo.setStatus("1"); - apirouteInfo.setUrl("/api/testapi/v1"); - apirouteInfo.setUseOwnUpstream("0"); - apirouteInfo.setVisualRange("0"); - apirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; - apirouteInfo.setServers(servers); - return apirouteInfo; + + + + private ApiRouteInfo buildApiRouteInfo() { + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi"); + apirouteInfo.setVersion("v1"); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("0"); + apirouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; + apirouteInfo.setServers(servers); + return apirouteInfo; } - - private ApiRouteInfo buildApiRouteInfo2(){ - ApiRouteInfo apirouteInfo = new ApiRouteInfo(); - apirouteInfo.setServiceName("testapi2"); - apirouteInfo.setVersion(""); - apirouteInfo.setStatus("1"); - apirouteInfo.setUrl("/api/testapi2/v1"); - apirouteInfo.setUseOwnUpstream("0"); - apirouteInfo.setVisualRange("1"); - apirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.89","8080")}; - apirouteInfo.setServers(servers); - return apirouteInfo; + + private ApiRouteInfo buildApiRouteInfo2() { + ApiRouteInfo apirouteInfo = new ApiRouteInfo(); + apirouteInfo.setServiceName("testapi2"); + apirouteInfo.setVersion(""); + apirouteInfo.setStatus("1"); + apirouteInfo.setUrl("/api/testapi2/v1"); + apirouteInfo.setUseOwnUpstream("0"); + apirouteInfo.setVisualRange("1"); + apirouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.89", "8080")}; + apirouteInfo.setServers(servers); + return apirouteInfo; } - - + + } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapperTest.java index acbecd1..d72c57c 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapperTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/CustomRouteServiceWrapperTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; @@ -25,13 +23,11 @@ import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.onap.msb.apiroute.api.CustomRouteInfo; import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.api.exception.ExtendedNotFoundException; -import org.onap.msb.apiroute.wrapper.CustomRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; import org.onap.msb.apiroute.wrapper.util.ConfigUtil; import org.onap.msb.apiroute.wrapper.util.JedisUtil; @@ -41,42 +37,42 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; -import com.fiftyonred.mock_jedis.MockJedisPool; - @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RouteUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RouteUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class CustomRouteServiceWrapperTest { - private static CustomRouteServiceWrapper customRouteServiceWrapper; - private static Comparator<CustomRouteInfo> customRouteComparator = null; - + private static CustomRouteServiceWrapper customRouteServiceWrapper; + private static Comparator<CustomRouteInfo> customRouteComparator = null; + @BeforeClass public static void setUpBeforeClass() throws Exception { - customRouteServiceWrapper=CustomRouteServiceWrapper.getInstance(); + customRouteServiceWrapper = CustomRouteServiceWrapper.getInstance(); customRouteComparator = new Comparator<CustomRouteInfo>() { - @Override - public int compare(CustomRouteInfo o1, CustomRouteInfo o2) { - if (!o1.getServiceName().equals(o2.getServiceName())) - return (o1.getServiceName()).compareTo(o2.getServiceName()); - return 0; - } - }; - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); - PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); - ConfigUtil.getInstance().initRouteWay(); + @Override + public int compare(CustomRouteInfo o1, CustomRouteInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + return 0; + } + }; + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + ConfigUtil.getInstance().initRouteWay(); } - + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -86,123 +82,125 @@ public class CustomRouteServiceWrapperTest { } }); } - + @Test - public void test_getCustomRouteInstance_not_exist(){ - try { - customRouteServiceWrapper.getCustomRouteInstance("/testForJunit","","","ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ + public void test_getCustomRouteInstance_not_exist() { + try { + customRouteServiceWrapper.getCustomRouteInstance("/testForJunit", "", "", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { Assert.assertTrue(e instanceof ExtendedNotFoundException); - + } - + } - + @Test - public void test_getCustomRouteInstance(){ - - CustomRouteInfo customrouteInfo = buildCustomRouteInfo(); - try { + public void test_getCustomRouteInstance() { + + CustomRouteInfo customrouteInfo = buildCustomRouteInfo(); + try { customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo, "ip"); - CustomRouteInfo dbCustomRouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/testcustom", "", "", "ip"); - Assert.assertEquals(customrouteInfo,dbCustomRouteInfo ); - } catch (Exception e) { + CustomRouteInfo dbCustomRouteInfo = + customRouteServiceWrapper.getCustomRouteInstance("/testcustom", "", "", "ip"); + Assert.assertEquals(customrouteInfo, dbCustomRouteInfo); + } catch (Exception e) { Assert.fail("throw exception means error occured!" + e.getMessage()); - } - + } + } @Test - public void test_getAllCustomRouteInstances(){ - CustomRouteInfo customrouteInfo = buildCustomRouteInfo(); - CustomRouteInfo customrouteInfo2 = buildCustomRouteInfo2(); - List<CustomRouteInfo> expected = new ArrayList<>(); - expected.add(customrouteInfo); - expected.add(customrouteInfo2); - Collections.sort(expected, customRouteComparator); - - try { - customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo, "ip"); - customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo2, "ip"); - - PowerMockito.mockStatic(RouteUtil.class); - PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, "ip")).thenReturn("msb:routing:custom:*"); - List<CustomRouteInfo> customRouterList=customRouteServiceWrapper.getAllCustomRouteInstances("ip"); - Collections.sort(customRouterList, customRouteComparator); - - Assert.assertEquals(expected,customRouterList); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - + public void test_getAllCustomRouteInstances() { + CustomRouteInfo customrouteInfo = buildCustomRouteInfo(); + CustomRouteInfo customrouteInfo2 = buildCustomRouteInfo2(); + List<CustomRouteInfo> expected = new ArrayList<>(); + expected.add(customrouteInfo); + expected.add(customrouteInfo2); + Collections.sort(expected, customRouteComparator); + + try { + customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo, "ip"); + customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo2, "ip"); + + PowerMockito.mockStatic(RouteUtil.class); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, "ip")) + .thenReturn("msb:routing:custom:*"); + List<CustomRouteInfo> customRouterList = customRouteServiceWrapper.getAllCustomRouteInstances("ip"); + Collections.sort(customRouterList, customRouteComparator); + + Assert.assertEquals(expected, customRouterList); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } - + @Test - public void test_updateCustomRouteStatus(){ - CustomRouteInfo customrouteInfo = buildCustomRouteInfo(); - try { - customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo, "ip"); - CustomRouteInfo dbCustomrouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/testcustom", "", "", "ip"); - Assert.assertEquals("1",dbCustomrouteInfo.getStatus() ); - customRouteServiceWrapper.updateCustomRouteStatus("/testcustom","","","0", "ip"); - dbCustomrouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/testcustom", "", "", "ip"); - Assert.assertEquals("0",dbCustomrouteInfo.getStatus() ); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - + public void test_updateCustomRouteStatus() { + CustomRouteInfo customrouteInfo = buildCustomRouteInfo(); + try { + customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo, "ip"); + CustomRouteInfo dbCustomrouteInfo = + customRouteServiceWrapper.getCustomRouteInstance("/testcustom", "", "", "ip"); + Assert.assertEquals("1", dbCustomrouteInfo.getStatus()); + customRouteServiceWrapper.updateCustomRouteStatus("/testcustom", "", "", "0", "ip"); + dbCustomrouteInfo = customRouteServiceWrapper.getCustomRouteInstance("/testcustom", "", "", "ip"); + Assert.assertEquals("0", dbCustomrouteInfo.getStatus()); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } - - - + + + @Test - public void test_deleteCustomRoute(){ - CustomRouteInfo customrouteInfo2 = buildCustomRouteInfo2(); - try { - customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo2, "ip"); - CustomRouteInfo dbCustomrouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/testcustom2","","","ip"); - Assert.assertNotNull(dbCustomrouteInfo); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - try { - customRouteServiceWrapper.deleteCustomRoute("/testcustom2","","","ip"); - customRouteServiceWrapper.getCustomRouteInstance("/testcustom2","","","ip"); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } + public void test_deleteCustomRoute() { + CustomRouteInfo customrouteInfo2 = buildCustomRouteInfo2(); + try { + customRouteServiceWrapper.saveCustomRouteInstance4Rest(customrouteInfo2, "ip"); + CustomRouteInfo dbCustomrouteInfo = + customRouteServiceWrapper.getCustomRouteInstance("/testcustom2", "", "", "ip"); + Assert.assertNotNull(dbCustomrouteInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + customRouteServiceWrapper.deleteCustomRoute("/testcustom2", "", "", "ip"); + customRouteServiceWrapper.getCustomRouteInstance("/testcustom2", "", "", "ip"); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } } - - - private CustomRouteInfo buildCustomRouteInfo(){ - CustomRouteInfo customrouteInfo = new CustomRouteInfo(); - customrouteInfo.setServiceName("/testcustom"); - customrouteInfo.setStatus("1"); - customrouteInfo.setUrl("/custom/testcustom"); - customrouteInfo.setUseOwnUpstream("0"); - customrouteInfo.setVisualRange("0"); - customrouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; - customrouteInfo.setServers(servers); - return customrouteInfo; + + + private CustomRouteInfo buildCustomRouteInfo() { + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("/testcustom"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("0"); + customrouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; + customrouteInfo.setServers(servers); + return customrouteInfo; } - - private CustomRouteInfo buildCustomRouteInfo2(){ - CustomRouteInfo customrouteInfo = new CustomRouteInfo(); - customrouteInfo.setServiceName("/testcustom2"); - customrouteInfo.setStatus("1"); - customrouteInfo.setUrl("/custom/testcustom"); - customrouteInfo.setUseOwnUpstream("0"); - customrouteInfo.setVisualRange("1"); - customrouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.89","8080")}; - customrouteInfo.setServers(servers); - return customrouteInfo; + + private CustomRouteInfo buildCustomRouteInfo2() { + CustomRouteInfo customrouteInfo = new CustomRouteInfo(); + customrouteInfo.setServiceName("/testcustom2"); + customrouteInfo.setStatus("1"); + customrouteInfo.setUrl("/custom/testcustom"); + customrouteInfo.setUseOwnUpstream("0"); + customrouteInfo.setVisualRange("1"); + customrouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.89", "8080")}; + customrouteInfo.setServers(servers); + return customrouteInfo; } - + } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapperTest.java index 93f8b60..e7b0e4c 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapperTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/InitRouteServiceWrapperTest.java @@ -1,23 +1,18 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; -import io.dropwizard.jetty.HttpConnectorFactory; -import io.dropwizard.server.SimpleServerFactory; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -27,18 +22,12 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.onap.msb.apiroute.ApiRouteAppConfig; import org.onap.msb.apiroute.api.ApiRouteInfo; import org.onap.msb.apiroute.api.CustomRouteInfo; import org.onap.msb.apiroute.api.DiscoverInfo; import org.onap.msb.apiroute.api.IuiRouteInfo; import org.onap.msb.apiroute.api.RouteServer; -import org.onap.msb.apiroute.wrapper.ApiRouteServiceWrapper; -import org.onap.msb.apiroute.wrapper.CustomRouteServiceWrapper; -import org.onap.msb.apiroute.wrapper.InitRouteServiceWrapper; -import org.onap.msb.apiroute.wrapper.IuiRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.consulextend.Consul; import org.onap.msb.apiroute.wrapper.consulextend.async.ConsulResponseCallback; import org.onap.msb.apiroute.wrapper.consulextend.util.Http; @@ -50,207 +39,185 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; - import com.fasterxml.jackson.core.type.TypeReference; import com.fiftyonred.mock_jedis.MockJedisPool; +import io.dropwizard.jetty.HttpConnectorFactory; +import io.dropwizard.server.SimpleServerFactory; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + @RunWith(PowerMockRunner.class) -@PrepareForTest({ JedisUtil.class, RedisAccessWrapper.class, ConfigUtil.class, - Http.class, InitRouteServiceWrapper.class }) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*" }) +@PrepareForTest({JedisUtil.class, RedisAccessWrapper.class, ConfigUtil.class, Http.class, + InitRouteServiceWrapper.class}) +@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*"}) public class InitRouteServiceWrapperTest { - private static InitRouteServiceWrapper initRouteServiceWrapper; - private static Consul consul; - - @SuppressWarnings("unchecked") - @BeforeClass - public static void setUpBeforeClass() throws Exception { - initRouteServiceWrapper = InitRouteServiceWrapper.getInstance(); - - Http http = PowerMockito.mock(Http.class); - - PowerMockito - .doNothing() - .when(http) - .asyncGet(Mockito.anyString(), - Mockito.any(TypeReference.class), - Mockito.any(ConsulResponseCallback.class)); - - PowerMockito - .doNothing() - .when(http) - .asyncGetDelayHandle(Mockito.anyString(), - Mockito.any(TypeReference.class), - Mockito.any(ConsulResponseCallback.class)); - - PowerMockito.spy(Http.class); - PowerMockito.when(Http.getInstance()).thenReturn(http); - - consul = Consul.builder().withHostAndPort("127.0.0.1", 8500).build(); - } - - @Before - public void initReidsMock() throws Exception { - final JedisPool mockJedisPool = new MockJedisPool( - new JedisPoolConfig(), "localhost"); - PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); - PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn( - mockJedisPool.getResource()); - - PowerMockito.replace( - PowerMockito.method(RedisAccessWrapper.class, "filterKeys")) - .with(new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, - Object[] args) throws Throwable { - return mockJedisPool.getResource().keys( - (String) args[0]); - } - }); - } - - @Test - public void test_startCheckRedisConnect() { - try { - boolean ifRedisConnect = initRouteServiceWrapper - .startCheckRedisConnect(); - Assert.assertEquals(true, ifRedisConnect); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - - } - } - - @Test - public void test_runConsulClientApp() { - - DiscoverInfo discoverInfo = new DiscoverInfo(); - discoverInfo.setEnabled(true); - discoverInfo.setIp("127.0.0.1"); - discoverInfo.setPort(10081); - - ApiRouteAppConfig configuration = new ApiRouteAppConfig(); - configuration.setDiscoverInfo(discoverInfo); - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn("127.0.0.1"); - ConfigUtil.getInstance().initDiscoverInfo(configuration); - - try { - initRouteServiceWrapper.runConsulClientApp(); - - ApiRouteInfo discoverApiService = new ApiRouteInfo(); - discoverApiService.setServiceName("msdiscover"); - discoverApiService.setUrl("/api/microservices/v1"); - discoverApiService.setVersion("v1"); - discoverApiService.setMetricsUrl("/admin/metrics"); - discoverApiService.setApiJson("/api/microservices/v1/swagger.json"); - discoverApiService.setHost("msb"); - - RouteServer[] servers = new RouteServer[1]; - servers[0] = new RouteServer(discoverInfo.getIp(), - String.valueOf(discoverInfo.getPort())); - discoverApiService.setServers(servers); - - ApiRouteInfo db_discoverApiService = ApiRouteServiceWrapper - .getInstance().getApiRouteInstance("msdiscover", "v1", - "msb", "", "ip"); - Assert.assertEquals(discoverApiService, db_discoverApiService); - - IuiRouteInfo discoverIUIService = new IuiRouteInfo(); - discoverIUIService.setServiceName("msdiscover"); - discoverIUIService.setUrl("/iui/microservices"); - discoverIUIService.setHost("msb"); - discoverIUIService.setServers(servers); - - Assert.assertEquals( - discoverIUIService, - IuiRouteServiceWrapper.getInstance().getIuiRouteInstance( - "msdiscover", "msb", "", "ip")); - - } catch (Exception e) { - assert false : "throw exception means error occured!" - + e.getMessage(); - } - } - - @Test - public void test_initRouteInfoFromJson() { - try { - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("dwApp_server_connector_port")) - .thenReturn("8068"); - initRouteServiceWrapper.initRouteInfoFromJson(); - - ApiRouteInfo apiroute = new ApiRouteInfo(); - apiroute.setServiceName("microservices"); - apiroute.setUrl("/api/microservices/v1"); - apiroute.setVersion("v1"); - apiroute.setMetricsUrl("/admin/metrics"); - apiroute.setApiJson("/api/microservices/v1/swagger.json"); - apiroute.setHost("msb"); - apiroute.setControl("1"); - apiroute.setStatus("1"); - - RouteServer[] servers = new RouteServer[1]; - servers[0] = new RouteServer("127.0.0.1", "8068"); - apiroute.setServers(servers); - - ApiRouteInfo db_apiService = ApiRouteServiceWrapper - .getInstance() - .getApiRouteInstance("microservices", "v1", "msb", "", "ip"); - Assert.assertEquals(apiroute, db_apiService); - - IuiRouteInfo iuiRoute = new IuiRouteInfo(); - iuiRoute.setServiceName("microservices"); - iuiRoute.setUrl("/iui/microservices"); - iuiRoute.setHost("msb"); - iuiRoute.setControl("1"); - iuiRoute.setStatus("1"); - iuiRoute.setServers(servers); - - Assert.assertEquals(iuiRoute, IuiRouteServiceWrapper.getInstance() - .getIuiRouteInstance("microservices", "msb", "", "ip")); - - CustomRouteInfo customRoute = new CustomRouteInfo(); - customRoute.setServiceName("/custom"); - customRoute.setUrl("/custom"); - customRoute.setHost("msb"); - customRoute.setControl("1"); - customRoute.setStatus("1"); - RouteServer[] servers2 = new RouteServer[1]; - servers2[0] = new RouteServer("127.0.0.1", "8066"); - customRoute.setServers(servers2); - - Assert.assertEquals(customRoute, - CustomRouteServiceWrapper.getInstance() - .getCustomRouteInstance("/custom", "msb", "", "ip")); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - } - - @Test - public void test_initMetricsConfig() { - ApiRouteAppConfig configuration = new ApiRouteAppConfig(); - SimpleServerFactory simpleServerFactory = new SimpleServerFactory(); - HttpConnectorFactory httpConnectorFactory = new HttpConnectorFactory(); - httpConnectorFactory.setPort(8888); - simpleServerFactory.setConnector(httpConnectorFactory); - simpleServerFactory.setAdminContextPath("/admin"); - - configuration.setServerFactory(simpleServerFactory); - - initRouteServiceWrapper.initMetricsConfig(configuration); - - Assert.assertEquals("http://127.0.0.1:8888/admin/metrics", ConfigUtil - .getInstance().getMetricsUrl()); - } + private static InitRouteServiceWrapper initRouteServiceWrapper; + private static Consul consul; + + @SuppressWarnings("unchecked") + @BeforeClass + public static void setUpBeforeClass() throws Exception { + initRouteServiceWrapper = InitRouteServiceWrapper.getInstance(); + + Http http = PowerMockito.mock(Http.class); + + PowerMockito.doNothing().when(http).asyncGet(Mockito.anyString(), Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + PowerMockito.doNothing().when(http).asyncGetDelayHandle(Mockito.anyString(), Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); + + consul = Consul.builder().withHostAndPort("127.0.0.1", 8500).build(); + } + + @Before + public void initReidsMock() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + @Test + public void test_startCheckRedisConnect() { + try { + boolean ifRedisConnect = initRouteServiceWrapper.startCheckRedisConnect(); + Assert.assertEquals(true, ifRedisConnect); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + + } + } + + @Test + public void test_runConsulClientApp() { + + DiscoverInfo discoverInfo = new DiscoverInfo(); + discoverInfo.setEnabled(true); + discoverInfo.setIp("127.0.0.1"); + discoverInfo.setPort(10081); + + ApiRouteAppConfig configuration = new ApiRouteAppConfig(); + configuration.setDiscoverInfo(discoverInfo); + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn("127.0.0.1"); + ConfigUtil.getInstance().initDiscoverInfo(configuration); + + try { + initRouteServiceWrapper.runConsulClientApp(); + + ApiRouteInfo discoverApiService = new ApiRouteInfo(); + discoverApiService.setServiceName("msdiscover"); + discoverApiService.setUrl("/api/microservices/v1"); + discoverApiService.setVersion("v1"); + discoverApiService.setMetricsUrl("/admin/metrics"); + discoverApiService.setApiJson("/api/microservices/v1/swagger.json"); + discoverApiService.setHost("msb"); + + RouteServer[] servers = new RouteServer[1]; + servers[0] = new RouteServer(discoverInfo.getIp(), String.valueOf(discoverInfo.getPort())); + discoverApiService.setServers(servers); + + ApiRouteInfo db_discoverApiService = ApiRouteServiceWrapper.getInstance().getApiRouteInstance("msdiscover", + "v1", "msb", "", "ip"); + Assert.assertEquals(discoverApiService, db_discoverApiService); + + IuiRouteInfo discoverIUIService = new IuiRouteInfo(); + discoverIUIService.setServiceName("msdiscover"); + discoverIUIService.setUrl("/iui/microservices"); + discoverIUIService.setHost("msb"); + discoverIUIService.setServers(servers); + + Assert.assertEquals(discoverIUIService, + IuiRouteServiceWrapper.getInstance().getIuiRouteInstance("msdiscover", "msb", "", "ip")); + + } catch (Exception e) { + assert false : "throw exception means error occured!" + e.getMessage(); + } + } + + @Test + public void test_initRouteInfoFromJson() { + try { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("dwApp_server_connector_port")).thenReturn("8068"); + initRouteServiceWrapper.initRouteInfoFromJson(); + + ApiRouteInfo apiroute = new ApiRouteInfo(); + apiroute.setServiceName("microservices"); + apiroute.setUrl("/api/microservices/v1"); + apiroute.setVersion("v1"); + apiroute.setMetricsUrl("/admin/metrics"); + apiroute.setApiJson("/api/microservices/v1/swagger.json"); + apiroute.setHost("msb"); + apiroute.setControl("1"); + apiroute.setStatus("1"); + + RouteServer[] servers = new RouteServer[1]; + servers[0] = new RouteServer("127.0.0.1", "8068"); + apiroute.setServers(servers); + + ApiRouteInfo db_apiService = ApiRouteServiceWrapper.getInstance().getApiRouteInstance("microservices", "v1", + "msb", "", "ip"); + Assert.assertEquals(apiroute, db_apiService); + + IuiRouteInfo iuiRoute = new IuiRouteInfo(); + iuiRoute.setServiceName("microservices"); + iuiRoute.setUrl("/iui/microservices"); + iuiRoute.setHost("msb"); + iuiRoute.setControl("1"); + iuiRoute.setStatus("1"); + iuiRoute.setServers(servers); + + Assert.assertEquals(iuiRoute, + IuiRouteServiceWrapper.getInstance().getIuiRouteInstance("microservices", "msb", "", "ip")); + + CustomRouteInfo customRoute = new CustomRouteInfo(); + customRoute.setServiceName("/custom"); + customRoute.setUrl("/custom"); + customRoute.setHost("msb"); + customRoute.setControl("1"); + customRoute.setStatus("1"); + RouteServer[] servers2 = new RouteServer[1]; + servers2[0] = new RouteServer("127.0.0.1", "8066"); + customRoute.setServers(servers2); + + Assert.assertEquals(customRoute, + CustomRouteServiceWrapper.getInstance().getCustomRouteInstance("/custom", "msb", "", "ip")); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } + + @Test + public void test_initMetricsConfig() { + ApiRouteAppConfig configuration = new ApiRouteAppConfig(); + SimpleServerFactory simpleServerFactory = new SimpleServerFactory(); + HttpConnectorFactory httpConnectorFactory = new HttpConnectorFactory(); + httpConnectorFactory.setPort(8888); + simpleServerFactory.setConnector(httpConnectorFactory); + simpleServerFactory.setAdminContextPath("/admin"); + + configuration.setServerFactory(simpleServerFactory); + + initRouteServiceWrapper.initMetricsConfig(configuration); + + Assert.assertEquals("http://127.0.0.1:8888/admin/metrics", ConfigUtil.getInstance().getMetricsUrl()); + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapperTest.java index 55759b8..8a5ceca 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapperTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/IuiRouteServiceWrapperTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; @@ -25,13 +23,11 @@ import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.onap.msb.apiroute.api.IuiRouteInfo; import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.api.exception.ExtendedNotFoundException; -import org.onap.msb.apiroute.wrapper.IuiRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; import org.onap.msb.apiroute.wrapper.util.ConfigUtil; import org.onap.msb.apiroute.wrapper.util.JedisUtil; @@ -41,42 +37,42 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; -import com.fiftyonred.mock_jedis.MockJedisPool; - @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RouteUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RouteUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class IuiRouteServiceWrapperTest { private static IuiRouteServiceWrapper iuiRouteServiceWrapper; private static Comparator<IuiRouteInfo> iuiRouteComparator = null; - + @BeforeClass public static void setUpBeforeClass() throws Exception { - iuiRouteServiceWrapper=IuiRouteServiceWrapper.getInstance(); + iuiRouteServiceWrapper = IuiRouteServiceWrapper.getInstance(); iuiRouteComparator = new Comparator<IuiRouteInfo>() { - @Override - public int compare(IuiRouteInfo o1, IuiRouteInfo o2) { - if (!o1.getServiceName().equals(o2.getServiceName())) - return (o1.getServiceName()).compareTo(o2.getServiceName()); - return 0; - } - }; - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); - PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); - ConfigUtil.getInstance().initRouteWay(); + @Override + public int compare(IuiRouteInfo o1, IuiRouteInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + return 0; + } + }; + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + ConfigUtil.getInstance().initRouteWay(); } - + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -86,127 +82,125 @@ public class IuiRouteServiceWrapperTest { } }); } - + @Test - public void test_getIuiRouteInstance_not_exist(){ - try { - iuiRouteServiceWrapper.getIuiRouteInstance("testForJunit","","","ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ + public void test_getIuiRouteInstance_not_exist() { + try { + iuiRouteServiceWrapper.getIuiRouteInstance("testForJunit", "", "", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { Assert.assertTrue(e instanceof ExtendedNotFoundException); - + } - + } - + @Test - public void test_getIuiRouteInstance(){ - - IuiRouteInfo iuirouteInfo = buildIuiRouteInfo(); - try { - iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo, "ip"); - IuiRouteInfo dbIuiRouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("testiui", "", "", "ip"); - Assert.assertEquals(iuirouteInfo,dbIuiRouteInfo ); - } catch (Exception e) { + public void test_getIuiRouteInstance() { + + IuiRouteInfo iuirouteInfo = buildIuiRouteInfo(); + try { + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo, "ip"); + IuiRouteInfo dbIuiRouteInfo = iuiRouteServiceWrapper.getIuiRouteInstance("testiui", "", "", "ip"); + Assert.assertEquals(iuirouteInfo, dbIuiRouteInfo); + } catch (Exception e) { Assert.fail("throw exception means error occured!" + e.getMessage()); - } - + } + } - + @Test - public void test_getAllIuiRouteInstances(){ - IuiRouteInfo iuirouteInfo = buildIuiRouteInfo(); - IuiRouteInfo iuirouteInfo2 = buildIuiRouteInfo2(); - List<IuiRouteInfo> expected = new ArrayList<>(); - expected.add(iuirouteInfo); - expected.add(iuirouteInfo2); - Collections.sort(expected, iuiRouteComparator); - - try { - iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo, "ip"); - iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo2, "ip"); - - - - PowerMockito.mockStatic(RouteUtil.class); - PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, "ip")).thenReturn("msb:routing:iui:*"); - List<IuiRouteInfo> iuiRouterList=iuiRouteServiceWrapper.getAllIuiRouteInstances("ip"); - Collections.sort(iuiRouterList, iuiRouteComparator); - - Assert.assertEquals(expected,iuiRouterList); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - + public void test_getAllIuiRouteInstances() { + IuiRouteInfo iuirouteInfo = buildIuiRouteInfo(); + IuiRouteInfo iuirouteInfo2 = buildIuiRouteInfo2(); + List<IuiRouteInfo> expected = new ArrayList<>(); + expected.add(iuirouteInfo); + expected.add(iuirouteInfo2); + Collections.sort(expected, iuiRouteComparator); + + try { + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo, "ip"); + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo2, "ip"); + + + + PowerMockito.mockStatic(RouteUtil.class); + PowerMockito.when(RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, "ip")).thenReturn("msb:routing:iui:*"); + List<IuiRouteInfo> iuiRouterList = iuiRouteServiceWrapper.getAllIuiRouteInstances("ip"); + Collections.sort(iuiRouterList, iuiRouteComparator); + + Assert.assertEquals(expected, iuiRouterList); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } - + @Test - public void test_updateIuiRouteStatus(){ - IuiRouteInfo iuirouteInfo = buildIuiRouteInfo(); - try { - iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo, "ip"); - IuiRouteInfo dbIuirouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("testiui", "", "", "ip"); - Assert.assertEquals("1",dbIuirouteInfo.getStatus() ); - iuiRouteServiceWrapper.updateIuiRouteStatus("testiui","","","0", "ip"); - dbIuirouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("testiui", "", "", "ip"); - Assert.assertEquals("0",dbIuirouteInfo.getStatus() ); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - + public void test_updateIuiRouteStatus() { + IuiRouteInfo iuirouteInfo = buildIuiRouteInfo(); + try { + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo, "ip"); + IuiRouteInfo dbIuirouteInfo = iuiRouteServiceWrapper.getIuiRouteInstance("testiui", "", "", "ip"); + Assert.assertEquals("1", dbIuirouteInfo.getStatus()); + iuiRouteServiceWrapper.updateIuiRouteStatus("testiui", "", "", "0", "ip"); + dbIuirouteInfo = iuiRouteServiceWrapper.getIuiRouteInstance("testiui", "", "", "ip"); + Assert.assertEquals("0", dbIuirouteInfo.getStatus()); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } - - - + + + @Test - public void test_deleteIuiRoute(){ - IuiRouteInfo iuirouteInfo2 = buildIuiRouteInfo2(); - try { - iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo2, "ip"); - IuiRouteInfo dbIuirouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("testiui2","","","ip"); - Assert.assertNotNull(dbIuirouteInfo); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); - } - try { - iuiRouteServiceWrapper.deleteIuiRoute("testiui2","","","ip"); - iuiRouteServiceWrapper.getIuiRouteInstance("testiui2","","","ip"); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } + public void test_deleteIuiRoute() { + IuiRouteInfo iuirouteInfo2 = buildIuiRouteInfo2(); + try { + iuiRouteServiceWrapper.saveIuiRouteInstance4Rest(iuirouteInfo2, "ip"); + IuiRouteInfo dbIuirouteInfo = iuiRouteServiceWrapper.getIuiRouteInstance("testiui2", "", "", "ip"); + Assert.assertNotNull(dbIuirouteInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + iuiRouteServiceWrapper.deleteIuiRoute("testiui2", "", "", "ip"); + iuiRouteServiceWrapper.getIuiRouteInstance("testiui2", "", "", "ip"); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } } - - - private IuiRouteInfo buildIuiRouteInfo(){ - IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); - iuirouteInfo.setServiceName("testiui"); - iuirouteInfo.setStatus("1"); - iuirouteInfo.setUrl("/iui/testiui"); - iuirouteInfo.setUseOwnUpstream("0"); - iuirouteInfo.setVisualRange("0"); - iuirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; - iuirouteInfo.setServers(servers); - return iuirouteInfo; + + + private IuiRouteInfo buildIuiRouteInfo() { + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("0"); + iuirouteInfo.setEnable_ssl(false); + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; + iuirouteInfo.setServers(servers); + return iuirouteInfo; } - - private IuiRouteInfo buildIuiRouteInfo2(){ - IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); - iuirouteInfo.setServiceName("testiui2"); - iuirouteInfo.setStatus("1"); - iuirouteInfo.setUrl("/iui/testiui"); - iuirouteInfo.setUseOwnUpstream("0"); - iuirouteInfo.setVisualRange("1"); - iuirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.89","8080")}; - iuirouteInfo.setServers(servers); - return iuirouteInfo; + + private IuiRouteInfo buildIuiRouteInfo2() { + IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); + iuirouteInfo.setServiceName("testiui2"); + iuirouteInfo.setStatus("1"); + iuirouteInfo.setUrl("/iui/testiui"); + iuirouteInfo.setUseOwnUpstream("0"); + iuirouteInfo.setVisualRange("1"); + iuirouteInfo.setEnable_ssl(true); + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.89", "8080")}; + iuirouteInfo.setServers(servers); + return iuirouteInfo; } - - + + } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapperTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapperTest.java index a32cccc..516c5ed 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapperTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/MicroServiceWrapperTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper; @@ -32,8 +30,6 @@ import org.junit.runner.RunWith; import org.onap.msb.apiroute.api.MicroServiceFullInfo; import org.onap.msb.apiroute.api.Node; import org.onap.msb.apiroute.api.exception.ExtendedNotFoundException; -import org.onap.msb.apiroute.api.exception.UnprocessableEntityException; -import org.onap.msb.apiroute.wrapper.MicroServiceWrapper; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; import org.onap.msb.apiroute.wrapper.util.JedisUtil; import org.powermock.api.mockito.PowerMockito; @@ -41,269 +37,266 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; -import com.fiftyonred.mock_jedis.MockJedisPool; - @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class MicroServiceWrapperTest { - private static MicroServiceWrapper microServiceWrapper; - private static Comparator<MicroServiceFullInfo> microServiceComparator = null; - - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - microServiceWrapper=MicroServiceWrapper.getInstance(); - microServiceComparator = new Comparator<MicroServiceFullInfo>() { - @Override - public int compare(MicroServiceFullInfo o1, MicroServiceFullInfo o2) { - if (!o1.getServiceName().equals(o2.getServiceName())) - return (o1.getServiceName()).compareTo(o2.getServiceName()); - return 0; - } - }; - } - - @Before - public void setUpBeforeTest() throws Exception { - final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); - PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); - PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); - - PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return mockJedisPool.getResource().keys((String) args[0]); - } - }); - } - - @Test - public void test_getMicroServiceFullInfo_not_exist(){ - try { - microServiceWrapper.getMicroServiceInstance("testForJunit","v1"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - - } - - } - - @Test - public void test_getMicroServiceFullInfo(){ - - MicroServiceFullInfo microServiceFullInfo = buildMicroServiceFullInfo(); + private static MicroServiceWrapper microServiceWrapper; + private static Comparator<MicroServiceFullInfo> microServiceComparator = null; + + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + microServiceWrapper = MicroServiceWrapper.getInstance(); + microServiceComparator = new Comparator<MicroServiceFullInfo>() { + @Override + public int compare(MicroServiceFullInfo o1, MicroServiceFullInfo o2) { + if (!o1.getServiceName().equals(o2.getServiceName())) + return (o1.getServiceName()).compareTo(o2.getServiceName()); + return 0; + } + }; + } + + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + @Test + public void test_getMicroServiceFullInfo_not_exist() { try { - microServiceWrapper.saveMicroServiceInstance(microServiceFullInfo, false, "", ""); - MicroServiceFullInfo dbMicroServiceFullInfo=microServiceWrapper.getMicroServiceInstance("testService", "v1"); - Assert.assertEquals(microServiceFullInfo,dbMicroServiceFullInfo ); + microServiceWrapper.getMicroServiceInstance("testForJunit", "v1"); + Assert.fail("should not process to here."); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } - - } - - @Test - public void test_getAllMicroServiceInstances(){ - MicroServiceFullInfo microService = buildMicroServiceFullInfo(); - MicroServiceFullInfo microService2 = buildMicroServiceFullInfo2(); - List<MicroServiceFullInfo> expected = new ArrayList<>(); - expected.add(microService); - expected.add(microService2); - Collections.sort(expected, microServiceComparator); - - try { - microServiceWrapper.saveMicroServiceInstance(microService, false, "", ""); - microServiceWrapper.saveMicroServiceInstance(microService2, false, "", ""); - - List<MicroServiceFullInfo> microServiceList=microServiceWrapper.getAllMicroServiceInstances(); - Collections.sort(microServiceList, microServiceComparator); - - Assert.assertEquals(expected,microServiceList); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + } - - } - - @Test - public void test_updateMicroServiceStatus(){ - MicroServiceFullInfo microService = buildMicroServiceFullInfo(); - - try { - microServiceWrapper.saveMicroServiceInstance(microService, false, "", ""); - MicroServiceFullInfo dbMicroServiceFullInfo=microServiceWrapper.getMicroServiceInstance("testService", "v1"); - Assert.assertEquals("1",dbMicroServiceFullInfo.getStatus() ); - microServiceWrapper.updateMicroServiceStatus("testService","v1","0"); - dbMicroServiceFullInfo=microServiceWrapper.getMicroServiceInstance("testService", "v1"); - Assert.assertEquals("0",dbMicroServiceFullInfo.getStatus() ); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + @Test + public void test_getMicroServiceFullInfo() { + + MicroServiceFullInfo microServiceFullInfo = buildMicroServiceFullInfo(); + try { + microServiceWrapper.saveMicroServiceInstance(microServiceFullInfo, false, "", ""); + MicroServiceFullInfo dbMicroServiceFullInfo = + microServiceWrapper.getMicroServiceInstance("testService", "v1"); + Assert.assertEquals(microServiceFullInfo, dbMicroServiceFullInfo); + } catch (Exception e) { + assert false : "throw exception means error occured!" + e.getMessage(); + } + } - - } - - - - @Test - public void test_deleteMicroService(){ - MicroServiceFullInfo microService = buildMicroServiceFullInfo2(); - try { - microServiceWrapper.saveMicroServiceInstance(microService, false, "", ""); - MicroServiceFullInfo dbMicroServiceFullInfo=microServiceWrapper.getMicroServiceInstance("testService2", "v1"); - Assert.assertNotNull(dbMicroServiceFullInfo); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + @Test + public void test_getAllMicroServiceInstances() { + MicroServiceFullInfo microService = buildMicroServiceFullInfo(); + MicroServiceFullInfo microService2 = buildMicroServiceFullInfo2(); + List<MicroServiceFullInfo> expected = new ArrayList<>(); + expected.add(microService); + expected.add(microService2); + Collections.sort(expected, microServiceComparator); + + try { + microServiceWrapper.saveMicroServiceInstance(microService, false, "", ""); + microServiceWrapper.saveMicroServiceInstance(microService2, false, "", ""); + + List<MicroServiceFullInfo> microServiceList = microServiceWrapper.getAllMicroServiceInstances(); + Collections.sort(microServiceList, microServiceComparator); + + Assert.assertEquals(expected, microServiceList); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } - try { - microServiceWrapper.deleteMicroService("testService2","v1"); - microServiceWrapper.getMicroServiceInstance("testService2", "v1"); + + @Test + public void test_updateMicroServiceStatus() { + MicroServiceFullInfo microService = buildMicroServiceFullInfo(); + + try { + microServiceWrapper.saveMicroServiceInstance(microService, false, "", ""); + MicroServiceFullInfo dbMicroServiceFullInfo = + microServiceWrapper.getMicroServiceInstance("testService", "v1"); + Assert.assertEquals("1", dbMicroServiceFullInfo.getStatus()); + microServiceWrapper.updateMicroServiceStatus("testService", "v1", "0"); + dbMicroServiceFullInfo = microServiceWrapper.getMicroServiceInstance("testService", "v1"); + Assert.assertEquals("0", dbMicroServiceFullInfo.getStatus()); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); + + + + @Test + public void test_deleteMicroService() { + MicroServiceFullInfo microService = buildMicroServiceFullInfo2(); + try { + microServiceWrapper.saveMicroServiceInstance(microService, false, "", ""); + MicroServiceFullInfo dbMicroServiceFullInfo = + microServiceWrapper.getMicroServiceInstance("testService2", "v1"); + Assert.assertNotNull(dbMicroServiceFullInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + microServiceWrapper.deleteMicroService("testService2", "v1"); + microServiceWrapper.getMicroServiceInstance("testService2", "v1"); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } } - } - - @Test - public void test_deleteMicroServiceInstance(){ - - - //添加多版本服务 - MicroServiceFullInfo microService4v2 = buildMicroServiceFullInfo4version2(); - try { - microServiceWrapper.saveMicroServiceInstance(microService4v2, false, "", ""); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + @Test + public void test_deleteMicroServiceInstance() { + + + // 添加多版本服务 + MicroServiceFullInfo microService4v2 = buildMicroServiceFullInfo4version2(); + try { + microServiceWrapper.saveMicroServiceInstance(microService4v2, false, "", ""); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + // 删除不存在实例 + try { + microServiceWrapper.deleteMicroServiceInstance("testService", "v2", "127.0.0.1", "8989"); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + // 删除其中一个实例 + microServiceWrapper.deleteMicroServiceInstance("testService", "v2", "10.74.148.87", "8080"); + MicroServiceFullInfo microService = microServiceWrapper.getMicroServiceInstance("testService", "v2"); + + Set<Node> nodeSet = new HashSet<Node>(); + nodeSet.add(new Node("10.74.148.86", "8080")); + Assert.assertEquals(nodeSet, microService.getNodes()); + + // 删除服务 + microServiceWrapper.deleteMicroServiceInstance("testService", "v2", "10.74.148.86", "8080"); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + microServiceWrapper.getMicroServiceInstance("testService", "v2"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + + } } - - //删除不存在实例 - try { - microServiceWrapper.deleteMicroServiceInstance("testService","v2","127.0.0.1","8989"); + + @Test + public void test_getAllVersion() { + try { + microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo(), false, "", ""); + microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo4version2(), false, "", ""); + Set<String> versionSet = new HashSet<String>(); + versionSet.add("v1"); + versionSet.add("v2"); + Assert.assertEquals(versionSet, microServiceWrapper.getAllVersion("testService")); + + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + try { + microServiceWrapper.deleteMicroService4AllVersion("testService"); + Assert.assertEquals(0, microServiceWrapper.getAllVersion("testService").size()); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + + } + } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); + + @Test + public void test_getAllMicroServiceKey() { + microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo(), false, "", ""); + microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo2(), false, "", ""); + Set<String> builder = new HashSet<String>(); + builder.add("testService"); + builder.add("testService2"); + Assert.assertEquals(builder, microServiceWrapper.getAllMicroServiceKey()); + + } - - try { - //删除其中一个实例 - microServiceWrapper.deleteMicroServiceInstance("testService","v2","10.74.148.87","8080"); - MicroServiceFullInfo microService =microServiceWrapper.getMicroServiceInstance("testService", "v2"); - - Set<Node> nodeSet=new HashSet<Node>(); - nodeSet.add(new Node("10.74.148.86","8080")); - Assert.assertEquals(nodeSet, microService.getNodes()); - - //删除服务 - microServiceWrapper.deleteMicroServiceInstance("testService","v2","10.74.148.86","8080"); + + private MicroServiceFullInfo buildMicroServiceFullInfo() { + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("HTTP"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88", "8080")); + microServiceFullInfo.setNodes(nodeSet); + + return microServiceFullInfo; } - catch(Exception e){ - Assert.fail("throw exception means error occured!" + e.getMessage()); + + private MicroServiceFullInfo buildMicroServiceFullInfo4version2() { + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService"); + microServiceFullInfo.setVersion("v2"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/testService/v1"); + microServiceFullInfo.setVisualRange("0"); + microServiceFullInfo.setProtocol("HTTP"); + microServiceFullInfo.setEnable_ssl(false); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.87", "8080")); + nodeSet.add(new Node("10.74.148.86", "8080")); + microServiceFullInfo.setNodes(nodeSet); + + return microServiceFullInfo; } - - try { - microServiceWrapper.getMicroServiceInstance("testService","v2"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - - } - } - - @Test - public void test_getAllVersion(){ - try { - microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo(), false, "", ""); - microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo4version2(), false, "", ""); - Set<String> versionSet=new HashSet<String>(); - versionSet.add("v1"); - versionSet.add("v2"); - Assert.assertEquals(versionSet,microServiceWrapper.getAllVersion("testService")); - - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + private MicroServiceFullInfo buildMicroServiceFullInfo2() { + MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); + microServiceFullInfo.setServiceName("testService2"); + microServiceFullInfo.setVersion("v1"); + microServiceFullInfo.setStatus("1"); + microServiceFullInfo.setUrl("/api/testService/v1"); + microServiceFullInfo.setVisualRange("1"); + microServiceFullInfo.setProtocol("REST"); + microServiceFullInfo.setEnable_ssl(true); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.89", "8080")); + microServiceFullInfo.setNodes(nodeSet); + + return microServiceFullInfo; } - try { - microServiceWrapper.deleteMicroService4AllVersion("testService"); - Assert.assertEquals(0,microServiceWrapper.getAllVersion("testService").size()); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - - } - - } - - @Test - public void test_getAllMicroServiceKey(){ - microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo(), false, "", ""); - microServiceWrapper.saveMicroServiceInstance(buildMicroServiceFullInfo2(), false, "", ""); - Set<String> builder = new HashSet<String>(); - builder.add("testService"); - builder.add("testService2"); - Assert.assertEquals(builder,microServiceWrapper.getAllMicroServiceKey()); - - - } - - private MicroServiceFullInfo buildMicroServiceFullInfo(){ - MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); - microServiceFullInfo.setServiceName("testService"); - microServiceFullInfo.setVersion("v1"); - microServiceFullInfo.setStatus("1"); - microServiceFullInfo.setUrl("/testService/v1"); - microServiceFullInfo.setVisualRange("0"); - microServiceFullInfo.setProtocol("HTTP"); - microServiceFullInfo.setEnable_ssl(false); - Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); - microServiceFullInfo.setNodes(nodeSet); - - return microServiceFullInfo; - } - - private MicroServiceFullInfo buildMicroServiceFullInfo4version2(){ - MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); - microServiceFullInfo.setServiceName("testService"); - microServiceFullInfo.setVersion("v2"); - microServiceFullInfo.setStatus("1"); - microServiceFullInfo.setUrl("/testService/v1"); - microServiceFullInfo.setVisualRange("0"); - microServiceFullInfo.setProtocol("HTTP"); - microServiceFullInfo.setEnable_ssl(false); - Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.87","8080")); - nodeSet.add(new Node("10.74.148.86","8080")); - microServiceFullInfo.setNodes(nodeSet); - - return microServiceFullInfo; - } - - private MicroServiceFullInfo buildMicroServiceFullInfo2(){ - MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); - microServiceFullInfo.setServiceName("testService2"); - microServiceFullInfo.setVersion("v1"); - microServiceFullInfo.setStatus("1"); - microServiceFullInfo.setUrl("/api/testService/v1"); - microServiceFullInfo.setVisualRange("1"); - microServiceFullInfo.setProtocol("REST"); - microServiceFullInfo.setEnable_ssl(true); - Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.89","8080")); - microServiceFullInfo.setNodes(nodeSet); - - return microServiceFullInfo; - } - - + + } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/ConsulTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/ConsulTest.java index fcec469..71e6a84 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/ConsulTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/ConsulTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend; @@ -24,9 +22,6 @@ import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.onap.msb.apiroute.wrapper.consulextend.CatalogClient; -import org.onap.msb.apiroute.wrapper.consulextend.Consul; -import org.onap.msb.apiroute.wrapper.consulextend.HealthClient; import org.onap.msb.apiroute.wrapper.consulextend.async.ConsulResponseCallback; import org.onap.msb.apiroute.wrapper.consulextend.async.OriginalConsulResponse; import org.onap.msb.apiroute.wrapper.consulextend.model.health.ServiceHealth; @@ -44,121 +39,109 @@ import com.orbitz.consul.option.CatalogOptions; import com.orbitz.consul.option.QueryOptions; @RunWith(PowerMockRunner.class) -@PrepareForTest({ Http.class }) -@PowerMockIgnore({ "javax.net.ssl.*" }) +@PrepareForTest({Http.class}) +@PowerMockIgnore({"javax.net.ssl.*"}) public class ConsulTest { - private static Consul consul10081; - private static Consul consul8500; - - private static final Logger LOGGER = LoggerFactory - .getLogger(ConsulTest.class); - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @BeforeClass - public static void setUpBeforeClass() throws Exception { - - Http http = PowerMockito.mock(Http.class); - - PowerMockito - .doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) - throws Throwable { - Object[] args = invocation.getArguments(); - ((ConsulResponseCallback) args[2]).onComplete(null); - return null; - } - }) - .when(http) - .asyncGet(Mockito.anyString(), - Mockito.any(TypeReference.class), - Mockito.any(ConsulResponseCallback.class)); - - // - PowerMockito.spy(Http.class); - PowerMockito.when(Http.getInstance()).thenReturn(http); - - // - consul10081 = Consul.builder().withHostAndPort("10.74.148.111", 10081) - .build(); - consul8500 = Consul.builder().withHostAndPort("10.74.148.111", 8500) - .build(); - } - - @Test - public void testcatalogClient() { - - ConsulResponseCallback<HttpEntity> callback = new ConsulResponseCallback<HttpEntity>() { - - @Override - public void onComplete( - ConsulResponse<HttpEntity> consulResponse) { - LOGGER.info("service list complete!"); - } - - @Override - public void onFailure(Throwable throwable) { - LOGGER.info("service list failure!"); - } - - @Override - public void onDelayComplete( - OriginalConsulResponse<HttpEntity> originalConsulResponse) { - // TODO Auto-generated method stub - LOGGER.info("service list complete!"); - } - - }; - - // 10081 - CatalogClient catalogclient10081 = consul10081.catalogClient(); - catalogclient10081.getServices(CatalogOptions.BLANK, QueryOptions.BLANK, callback); - - // 8500 - CatalogClient catalogclient8500 = consul8500.catalogClient(); - catalogclient8500.getServices(CatalogOptions.BLANK, QueryOptions.BLANK, callback); - } - - @Test - public void testhealthClient() { - - ConsulResponseCallback<List<ServiceHealth>> callback = new ConsulResponseCallback<List<ServiceHealth>>() { - - @Override - public void onComplete( - ConsulResponse<List<ServiceHealth>> consulResponse) { - LOGGER.info("health service complete!"); - - } - - @Override - public void onFailure(Throwable throwable) { - LOGGER.info("health service failure!"); - } - - @Override - public void onDelayComplete( - OriginalConsulResponse<List<ServiceHealth>> originalConsulResponse) { - // TODO Auto-generated method stub - LOGGER.info("health service complete!"); - } - - }; - - // 10081 - HealthClient healthClient10081 = consul10081.healthClient(); - healthClient10081.getAllServiceInstances("apigateway-default", CatalogOptions.BLANK, - QueryOptions.BLANK, callback); - - healthClient10081.getHealthyServiceInstances("apigateway-default", - CatalogOptions.BLANK, QueryOptions.BLANK, callback); - - // 8500 - HealthClient healthClient8500 = consul8500.healthClient(); - healthClient8500.getAllServiceInstances("apigateway-default", CatalogOptions.BLANK, - QueryOptions.BLANK, callback); - healthClient8500.getHealthyServiceInstances("apigateway-default", CatalogOptions.BLANK, - QueryOptions.BLANK, callback); - - } + private static Consul consul10081; + private static Consul consul8500; + + private static final Logger LOGGER = LoggerFactory.getLogger(ConsulTest.class); + + @SuppressWarnings({"unchecked", "rawtypes"}) + @BeforeClass + public static void setUpBeforeClass() throws Exception { + + Http http = PowerMockito.mock(Http.class); + + PowerMockito.doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + ((ConsulResponseCallback) args[2]).onComplete(null); + return null; + } + }).when(http).asyncGet(Mockito.anyString(), Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + // + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); + + // + consul10081 = Consul.builder().withHostAndPort("10.74.148.111", 10081).build(); + consul8500 = Consul.builder().withHostAndPort("10.74.148.111", 8500).build(); + } + + @Test + public void testcatalogClient() { + + ConsulResponseCallback<HttpEntity> callback = new ConsulResponseCallback<HttpEntity>() { + + @Override + public void onComplete(ConsulResponse<HttpEntity> consulResponse) { + LOGGER.info("service list complete!"); + } + + @Override + public void onFailure(Throwable throwable) { + LOGGER.info("service list failure!"); + } + + @Override + public void onDelayComplete(OriginalConsulResponse<HttpEntity> originalConsulResponse) { + // TODO Auto-generated method stub + LOGGER.info("service list complete!"); + } + + }; + + // 10081 + CatalogClient catalogclient10081 = consul10081.catalogClient(); + catalogclient10081.getServices(CatalogOptions.BLANK, QueryOptions.BLANK, callback); + + // 8500 + CatalogClient catalogclient8500 = consul8500.catalogClient(); + catalogclient8500.getServices(CatalogOptions.BLANK, QueryOptions.BLANK, callback); + } + + @Test + public void testhealthClient() { + + ConsulResponseCallback<List<ServiceHealth>> callback = new ConsulResponseCallback<List<ServiceHealth>>() { + + @Override + public void onComplete(ConsulResponse<List<ServiceHealth>> consulResponse) { + LOGGER.info("health service complete!"); + + } + + @Override + public void onFailure(Throwable throwable) { + LOGGER.info("health service failure!"); + } + + @Override + public void onDelayComplete(OriginalConsulResponse<List<ServiceHealth>> originalConsulResponse) { + // TODO Auto-generated method stub + LOGGER.info("health service complete!"); + } + + }; + + // 10081 + HealthClient healthClient10081 = consul10081.healthClient(); + healthClient10081.getAllServiceInstances("apigateway-default", CatalogOptions.BLANK, QueryOptions.BLANK, + callback); + + healthClient10081.getHealthyServiceInstances("apigateway-default", CatalogOptions.BLANK, QueryOptions.BLANK, + callback); + + // 8500 + HealthClient healthClient8500 = consul8500.healthClient(); + healthClient8500.getAllServiceInstances("apigateway-default", CatalogOptions.BLANK, QueryOptions.BLANK, + callback); + healthClient8500.getHealthyServiceInstances("apigateway-default", CatalogOptions.BLANK, QueryOptions.BLANK, + callback); + + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCacheTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCacheTest.java index f22af71..e62d536 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCacheTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServiceHealthCacheTest.java @@ -1,39 +1,34 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.cache; import org.junit.Assert; import org.junit.Test; import org.onap.msb.apiroute.wrapper.consulextend.Consul; -import org.onap.msb.apiroute.wrapper.consulextend.cache.ServiceHealthCache; import com.orbitz.consul.option.CatalogOptions; public class ServiceHealthCacheTest { - @Test - public void testnewCache() { - Consul consul = Consul.newClient(); - ServiceHealthCache cache1 = ServiceHealthCache.newCache( - consul.healthClient(), "huangleibo"); - Assert.assertNotNull(cache1); + @Test + public void testnewCache() { + Consul consul = Consul.newClient(); + ServiceHealthCache cache1 = ServiceHealthCache.newCache(consul.healthClient(), "huangleibo"); + Assert.assertNotNull(cache1); - ServiceHealthCache cache2 = ServiceHealthCache.newCache( - consul.healthClient(), "huangleibo", false, - CatalogOptions.BLANK, 10); - Assert.assertNotNull(cache2); - } + ServiceHealthCache cache2 = ServiceHealthCache.newCache(consul.healthClient(), "huangleibo", false, + CatalogOptions.BLANK, 10); + Assert.assertNotNull(cache2); + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCacheTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCacheTest.java index 32167ca..a5718a1 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCacheTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/cache/ServicesCatalogCacheTest.java @@ -1,30 +1,26 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.cache; import org.junit.Test; import org.onap.msb.apiroute.wrapper.consulextend.Consul; -import org.onap.msb.apiroute.wrapper.consulextend.cache.ServicesCatalogCache; public class ServicesCatalogCacheTest { - @Test - public void testnewCache() - { - Consul consul = Consul.newClient(); - ServicesCatalogCache cache = ServicesCatalogCache.newCache(consul.catalogClient()); - } + @Test + public void testnewCache() { + Consul consul = Consul.newClient(); + ServicesCatalogCache cache = ServicesCatalogCache.newCache(consul.catalogClient()); + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilterTest.java index 3daa261..c0cf337 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilterTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckServiceDataEmptyAndAutoStopWatchFilterTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -19,9 +17,6 @@ import java.math.BigInteger; import java.util.ArrayList; import java.util.List; - - - import org.junit.Assert; import org.junit.Test; import org.onap.msb.apiroute.wrapper.consulextend.Consul; @@ -36,33 +31,32 @@ import com.orbitz.consul.model.ConsulResponse; import com.orbitz.consul.model.health.ImmutableNode; public class CheckServiceDataEmptyAndAutoStopWatchFilterTest { - @Test - public void testfilter() - { - - - CheckServiceDataEmptyAndAutoStopWatchFilter filter = new CheckServiceDataEmptyAndAutoStopWatchFilter("huangleibo"); - - - List<ServiceHealth> list = new ArrayList<ServiceHealth>(); - - //id:huangleibo1,name:huangleibo,modifyIndex:1,createindex:1 - Service service0 = ImmutableService.builder().id("huangleibo1").port(0).address("") - .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); - ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder() - .service(service0) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); - - list.add(serviceHealth0); - ConsulResponse<List<ServiceHealth>> object = new ConsulResponse<List<ServiceHealth>>(list,1,true, BigInteger.valueOf(1)); - - //have service,return true - Assert.assertTrue(filter.filter(object)); - - //empty [],return false - list.clear(); - Assert.assertFalse(filter.filter(object)); - - } + @Test + public void testfilter() { + + + CheckServiceDataEmptyAndAutoStopWatchFilter filter = + new CheckServiceDataEmptyAndAutoStopWatchFilter("huangleibo"); + + + List<ServiceHealth> list = new ArrayList<ServiceHealth>(); + + // id:huangleibo1,name:huangleibo,modifyIndex:1,createindex:1 + Service service0 = ImmutableService.builder().id("huangleibo1").port(0).address("").service("huangleibo") + .addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder().service(service0) + .node(ImmutableNode.builder().node("").address("").build()).build(); + + list.add(serviceHealth0); + ConsulResponse<List<ServiceHealth>> object = + new ConsulResponse<List<ServiceHealth>>(list, 1, true, BigInteger.valueOf(1)); + + // have service,return true + Assert.assertTrue(filter.filter(object)); + + // empty [],return false + list.clear(); + Assert.assertFalse(filter.filter(object)); + + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilterTest.java index 0ee1e17..68f2fcf 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilterTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/CheckTagAndAutoStopWatchFilterTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -34,52 +32,47 @@ import com.orbitz.consul.model.health.ImmutableNode; public class CheckTagAndAutoStopWatchFilterTest { - @Test - public void testfilter() { - - CheckTagAndAutoStopWatchFilter filter = new CheckTagAndAutoStopWatchFilter("huangleibo"); - - - List<ServiceHealth> list = new ArrayList<ServiceHealth>(); - - //visual range:0,tags meet conditions - List<String> tags = new ArrayList<String>(); - tags.add("\"base\":{\"protocol\":\"REST\",\"is_manual\":\"true\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tags.add("\"ns\":{\"namespace\":\"nsName\"}"); - tags.add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); - - Service service0 = ImmutableService.builder().id("huangleibo1").port(0) - .address("").service("huangleibo").tags(tags).createIndex(1) - .modifyIndex(1).build(); - ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder() - .service(service0) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); - - list.add(serviceHealth0); - ConsulResponse<List<ServiceHealth>> object = new ConsulResponse<List<ServiceHealth>>(list,1,true,BigInteger.valueOf(1)); - - //visual range:0,tags meet conditions,return true - Assert.assertTrue(filter.filter(object)); - - //visual range:1,tags don't meet conditions - List<String> tags1 = new ArrayList<String>(); - tags1.add("\"base\":{\"protocol\":\"REST\",\"is_manual\":\"true\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tags1.add("\"ns\":{\"namespace\":\"nsName\"}"); - tags1.add("\"labels\":{\"visualRange\":\"1\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); - - Service service1 = ImmutableService.builder().id("huangleibo1").port(0) - .address("").service("huangleibo").tags(tags1).createIndex(1) - .modifyIndex(1).build(); - ServiceHealth serviceHealth1 = ImmutableServiceHealth.builder() - .service(service1) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); - list.clear(); - list.add(serviceHealth1); - - //visual range:1,tags don't meet conditions,return false - Assert.assertFalse(filter.filter(object)); - - } + @Test + public void testfilter() { + + CheckTagAndAutoStopWatchFilter filter = new CheckTagAndAutoStopWatchFilter("huangleibo"); + + + List<ServiceHealth> list = new ArrayList<ServiceHealth>(); + + // visual range:0,tags meet conditions + List<String> tags = new ArrayList<String>(); + tags.add("\"base\":{\"protocol\":\"REST\",\"is_manual\":\"true\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tags.add("\"ns\":{\"namespace\":\"nsName\"}"); + tags.add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + + Service service0 = ImmutableService.builder().id("huangleibo1").port(0).address("").service("huangleibo") + .tags(tags).createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder().service(service0) + .node(ImmutableNode.builder().node("").address("").build()).build(); + + list.add(serviceHealth0); + ConsulResponse<List<ServiceHealth>> object = + new ConsulResponse<List<ServiceHealth>>(list, 1, true, BigInteger.valueOf(1)); + + // visual range:0,tags meet conditions,return true + Assert.assertTrue(filter.filter(object)); + + // visual range:1,tags don't meet conditions + List<String> tags1 = new ArrayList<String>(); + tags1.add("\"base\":{\"protocol\":\"REST\",\"is_manual\":\"true\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tags1.add("\"ns\":{\"namespace\":\"nsName\"}"); + tags1.add("\"labels\":{\"visualRange\":\"1\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + + Service service1 = ImmutableService.builder().id("huangleibo1").port(0).address("").service("huangleibo") + .tags(tags1).createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth1 = ImmutableServiceHealth.builder().service(service1) + .node(ImmutableNode.builder().node("").address("").build()).build(); + list.clear(); + list.add(serviceHealth1); + + // visual range:1,tags don't meet conditions,return false + Assert.assertFalse(filter.filter(object)); + + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilterTest.java index a461fb9..2225eb2 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilterTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ConsulIndexFilterTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -20,38 +18,38 @@ import java.math.BigInteger; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.onap.msb.apiroute.wrapper.consulextend.expose.ConsulIndexFilter; import com.orbitz.consul.model.ConsulResponse; public class ConsulIndexFilterTest { - @BeforeClass + @BeforeClass public static void setUpBeforeClass() throws Exception { } - - @Test - public void testfilter() - { - ConsulIndexFilter<Integer> filter = new ConsulIndexFilter<Integer>(); - - int response = 1; - long lastContact= 1; - boolean knownLeader = true; - - ConsulResponse<Integer> object = new ConsulResponse<Integer>(response,lastContact,knownLeader,BigInteger.valueOf(1)); - - //index 1;the first time,return true - Assert.assertTrue(filter.filter(object)); - - - //index 1;same index,return false - Assert.assertFalse(filter.filter(object)); - - ConsulResponse<Integer> object1 = new ConsulResponse<Integer>(response,lastContact,knownLeader,BigInteger.valueOf(2)); - - //index 2;different index,return true - Assert.assertTrue(filter.filter(object1)); - - } + + @Test + public void testfilter() { + ConsulIndexFilter<Integer> filter = new ConsulIndexFilter<Integer>(); + + int response = 1; + long lastContact = 1; + boolean knownLeader = true; + + ConsulResponse<Integer> object = + new ConsulResponse<Integer>(response, lastContact, knownLeader, BigInteger.valueOf(1)); + + // index 1;the first time,return true + Assert.assertTrue(filter.filter(object)); + + + // index 1;same index,return false + Assert.assertFalse(filter.filter(object)); + + ConsulResponse<Integer> object1 = + new ConsulResponse<Integer>(response, lastContact, knownLeader, BigInteger.valueOf(2)); + + // index 2;different index,return true + Assert.assertTrue(filter.filter(object1)); + + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilterTest.java index 77465fb..a44f587 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilterTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/ServiceModifyIndexFilterTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -31,99 +29,94 @@ import com.orbitz.consul.model.ConsulResponse; import com.orbitz.consul.model.health.ImmutableNode; public class ServiceModifyIndexFilterTest { - - @Test - public void testfilter() - { - ServiceModifyIndexFilter filter = new ServiceModifyIndexFilter(); - - - List<ServiceHealth> list0 = new ArrayList<ServiceHealth>(); - - //id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 - Service service0 = ImmutableService.builder().id("huangleibo1").port(0).address("") - .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); - ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder() - .service(service0) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); - list0.add(serviceHealth0); - - ConsulResponse<List<ServiceHealth>> object0 = new ConsulResponse<List<ServiceHealth>>(list0,1,true,BigInteger.valueOf(1)); - - //list-size:1,id:huangleibo1,name:huangleibo,modifyIndex:1;the first time:return true - Assert.assertTrue(filter.filter(object0)); - - //list-size:1,id:huangleibo1,name:huangleibo,modifyIndex:1;same index:return false - Assert.assertFalse(filter.filter(object0)); - - ///////////////////////////////////////////////////////////////////////////////// - - List<ServiceHealth> list1 = new ArrayList<ServiceHealth>(); - - //id:huangleibo2,name:huangleibo,modifyIndex:1,createIndex:1 - Service service1 = ImmutableService.builder().id("huangleibo2").port(0).address("") - .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); - ServiceHealth serviceHealth1 = ImmutableServiceHealth.builder() - .service(service1) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); - - list1.add(serviceHealth0); - list1.add(serviceHealth1); - - ConsulResponse<List<ServiceHealth>> object1 = new ConsulResponse<List<ServiceHealth>>(list1,1,true,BigInteger.valueOf(1)); - - //list-size:2, - //id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 - //id:huangleibo2,name:huangleibo,modifyIndex:1,createIndex:1 - //size different,return true - Assert.assertTrue(filter.filter(object1)); - - ////////////////////////////////////////////////////////////////////////// - List<ServiceHealth> list2 = new ArrayList<ServiceHealth>(); - - //id:huangleibo3,name:huangleibo,modifyIndex:1,createIndex:1 - ImmutableService service2 = ImmutableService.builder().id("huangleibo3").port(0).address("") - .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); - ServiceHealth serviceHealth2 = ImmutableServiceHealth.builder() - .service(service2) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); - list2.add(serviceHealth0); - list2.add(serviceHealth2); - - ConsulResponse<List<ServiceHealth>> object2 = new ConsulResponse<List<ServiceHealth>>(list2,1,true,BigInteger.valueOf(1)); - - //list-size:2, - //id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 - //id:huangleibo3,name:huangleibo,modifyIndex:1,createIndex:1 - //instance id different,return true - Assert.assertTrue(filter.filter(object2)); - - - ////////////////////////////////////////////////////////////////////////// - List<ServiceHealth> list3 = new ArrayList<ServiceHealth>(); - - //edit modifyindex 1 to 2 - Service service3 = service2.withModifyIndex(2); - ServiceHealth serviceHealth3 = ImmutableServiceHealth.builder() - .service(service3) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); - list3.add(serviceHealth0); - list3.add(serviceHealth3); - - ConsulResponse<List<ServiceHealth>> object3 = new ConsulResponse<List<ServiceHealth>>(list3,1,true,BigInteger.valueOf(1)); - - //list-size:2, - //id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 - //id:huangleibo3,name:huangleibo,modifyIndex:2,createIndex:1 - //modifyIndex different,return true - Assert.assertTrue(filter.filter(object3)); - - //the same content,return false - Assert.assertFalse(filter.filter(object3)); - - } + + @Test + public void testfilter() { + ServiceModifyIndexFilter filter = new ServiceModifyIndexFilter(); + + + List<ServiceHealth> list0 = new ArrayList<ServiceHealth>(); + + // id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 + Service service0 = ImmutableService.builder().id("huangleibo1").port(0).address("").service("huangleibo") + .addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder().service(service0) + .node(ImmutableNode.builder().node("").address("").build()).build(); + list0.add(serviceHealth0); + + ConsulResponse<List<ServiceHealth>> object0 = + new ConsulResponse<List<ServiceHealth>>(list0, 1, true, BigInteger.valueOf(1)); + + // list-size:1,id:huangleibo1,name:huangleibo,modifyIndex:1;the first time:return true + Assert.assertTrue(filter.filter(object0)); + + // list-size:1,id:huangleibo1,name:huangleibo,modifyIndex:1;same index:return false + Assert.assertFalse(filter.filter(object0)); + + ///////////////////////////////////////////////////////////////////////////////// + + List<ServiceHealth> list1 = new ArrayList<ServiceHealth>(); + + // id:huangleibo2,name:huangleibo,modifyIndex:1,createIndex:1 + Service service1 = ImmutableService.builder().id("huangleibo2").port(0).address("").service("huangleibo") + .addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth1 = ImmutableServiceHealth.builder().service(service1) + .node(ImmutableNode.builder().node("").address("").build()).build(); + + list1.add(serviceHealth0); + list1.add(serviceHealth1); + + ConsulResponse<List<ServiceHealth>> object1 = + new ConsulResponse<List<ServiceHealth>>(list1, 1, true, BigInteger.valueOf(1)); + + // list-size:2, + // id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 + // id:huangleibo2,name:huangleibo,modifyIndex:1,createIndex:1 + // size different,return true + Assert.assertTrue(filter.filter(object1)); + + ////////////////////////////////////////////////////////////////////////// + List<ServiceHealth> list2 = new ArrayList<ServiceHealth>(); + + // id:huangleibo3,name:huangleibo,modifyIndex:1,createIndex:1 + ImmutableService service2 = ImmutableService.builder().id("huangleibo3").port(0).address("") + .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth2 = ImmutableServiceHealth.builder().service(service2) + .node(ImmutableNode.builder().node("").address("").build()).build(); + list2.add(serviceHealth0); + list2.add(serviceHealth2); + + ConsulResponse<List<ServiceHealth>> object2 = + new ConsulResponse<List<ServiceHealth>>(list2, 1, true, BigInteger.valueOf(1)); + + // list-size:2, + // id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 + // id:huangleibo3,name:huangleibo,modifyIndex:1,createIndex:1 + // instance id different,return true + Assert.assertTrue(filter.filter(object2)); + + + ////////////////////////////////////////////////////////////////////////// + List<ServiceHealth> list3 = new ArrayList<ServiceHealth>(); + + // edit modifyindex 1 to 2 + Service service3 = service2.withModifyIndex(2); + ServiceHealth serviceHealth3 = ImmutableServiceHealth.builder().service(service3) + .node(ImmutableNode.builder().node("").address("").build()).build(); + list3.add(serviceHealth0); + list3.add(serviceHealth3); + + ConsulResponse<List<ServiceHealth>> object3 = + new ConsulResponse<List<ServiceHealth>>(list3, 1, true, BigInteger.valueOf(1)); + + // list-size:2, + // id:huangleibo1,name:huangleibo,modifyIndex:1,createIndex:1 + // id:huangleibo3,name:huangleibo,modifyIndex:2,createIndex:1 + // modifyIndex different,return true + Assert.assertTrue(filter.filter(object3)); + + // the same content,return false + Assert.assertFalse(filter.filter(object3)); + + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTaskTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTaskTest.java index 50e2023..548639e 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTaskTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchCatalogServicesTaskTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -30,8 +28,6 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.onap.msb.apiroute.wrapper.consulextend.Consul; import org.onap.msb.apiroute.wrapper.consulextend.async.ConsulResponseCallback; -import org.onap.msb.apiroute.wrapper.consulextend.expose.WatchCatalogServicesTask; -import org.onap.msb.apiroute.wrapper.consulextend.expose.WatchTask; import org.onap.msb.apiroute.wrapper.consulextend.expose.WatchTask.Filter; import org.onap.msb.apiroute.wrapper.consulextend.util.Http; import org.powermock.api.mockito.PowerMockito; @@ -47,107 +43,95 @@ import com.orbitz.consul.option.CatalogOptions; import com.orbitz.consul.option.QueryOptions; @RunWith(PowerMockRunner.class) -@PrepareForTest({ Http.class }) -@PowerMockIgnore({ "javax.net.ssl.*" }) +@PrepareForTest({Http.class}) +@PowerMockIgnore({"javax.net.ssl.*"}) public class WatchCatalogServicesTaskTest { - private static final Logger LOGGER = LoggerFactory - .getLogger(WatchCatalogServicesTaskTest.class); - - private Consul consul; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Before - public void init() { - - Map<String, List<String>> catalogservices = new HashMap<String, List<String>>(); - String servicename = "huangleibo"; - List<String> tags = new ArrayList<String>(); - tags.add("1111"); - tags.add("2222"); - catalogservices.put(servicename, tags); - - long lastContact = 1; - boolean knownLeader = true; - BigInteger index = BigInteger.valueOf(1); - final ConsulResponse<Map<String, List<String>>> response = new ConsulResponse<Map<String, List<String>>>( - catalogservices, lastContact, knownLeader, index); - - // - Http http = PowerMockito.mock(Http.class); - - PowerMockito - .doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) - throws Throwable { - Object[] args = invocation.getArguments(); - ((ConsulResponseCallback) args[2]).onComplete(response); - return null; - } - }) - .when(http) - .asyncGet(Mockito.anyString(), - Mockito.any(TypeReference.class), - Mockito.any(ConsulResponseCallback.class)); - - // - PowerMockito.spy(Http.class); - PowerMockito.when(Http.getInstance()).thenReturn(http); - - consul = Consul.newClient(); - - WatchCatalogServicesTask task0 = new WatchCatalogServicesTask( - consul.catalogClient(), CatalogOptions.BLANK, - QueryOptions.BLANK, 10); - - WatchCatalogServicesTask task1 = new WatchCatalogServicesTask( - consul.catalogClient(), 10); - - WatchCatalogServicesTask task2 = new WatchCatalogServicesTask( - consul.catalogClient()); - - } - - public class StopHandler implements WatchTask.Handler<HttpEntity> - { - - private WatchCatalogServicesTask task; - - StopHandler(WatchCatalogServicesTask task) - { - this.task = task; - } - - @Override - public void handle(ConsulResponse<HttpEntity> object) { - // TODO Auto-generated method stub -// Map<String, List<String>> map = (Map<String, List<String>>)object.getResponse(); - LOGGER.debug("handler is here"); - task.stopWatch(); - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void teststartWatch() { - WatchCatalogServicesTask task0 = new WatchCatalogServicesTask( - consul.catalogClient(), CatalogOptions.BLANK, - QueryOptions.BLANK, 10); - - task0.addFilter(new Filter() { - @Override - public boolean filter(ConsulResponse object) { - // TODO Auto-generated method stub -// Map<String, List<String>> map = (Map<String, List<String>>)object.getResponse(); - LOGGER.debug("filter is here"); - return true; - } - - }); - - task0.addHandler(new StopHandler(task0)); - - task0.startWatch(); - } - + private static final Logger LOGGER = LoggerFactory.getLogger(WatchCatalogServicesTaskTest.class); + + private Consul consul; + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Before + public void init() { + + Map<String, List<String>> catalogservices = new HashMap<String, List<String>>(); + String servicename = "huangleibo"; + List<String> tags = new ArrayList<String>(); + tags.add("1111"); + tags.add("2222"); + catalogservices.put(servicename, tags); + + long lastContact = 1; + boolean knownLeader = true; + BigInteger index = BigInteger.valueOf(1); + final ConsulResponse<Map<String, List<String>>> response = + new ConsulResponse<Map<String, List<String>>>(catalogservices, lastContact, knownLeader, index); + + // + Http http = PowerMockito.mock(Http.class); + + PowerMockito.doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + ((ConsulResponseCallback) args[2]).onComplete(response); + return null; + } + }).when(http).asyncGet(Mockito.anyString(), Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + // + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); + + consul = Consul.newClient(); + + WatchCatalogServicesTask task0 = new WatchCatalogServicesTask(consul.catalogClient(), CatalogOptions.BLANK, + QueryOptions.BLANK, 10); + + WatchCatalogServicesTask task1 = new WatchCatalogServicesTask(consul.catalogClient(), 10); + + WatchCatalogServicesTask task2 = new WatchCatalogServicesTask(consul.catalogClient()); + + } + + public class StopHandler implements WatchTask.Handler<HttpEntity> { + + private WatchCatalogServicesTask task; + + StopHandler(WatchCatalogServicesTask task) { + this.task = task; + } + + @Override + public void handle(ConsulResponse<HttpEntity> object) { + // TODO Auto-generated method stub + // Map<String, List<String>> map = (Map<String, List<String>>)object.getResponse(); + LOGGER.debug("handler is here"); + task.stopWatch(); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void teststartWatch() { + WatchCatalogServicesTask task0 = new WatchCatalogServicesTask(consul.catalogClient(), CatalogOptions.BLANK, + QueryOptions.BLANK, 10); + + task0.addFilter(new Filter() { + @Override + public boolean filter(ConsulResponse object) { + // TODO Auto-generated method stub + // Map<String, List<String>> map = (Map<String, List<String>>)object.getResponse(); + LOGGER.debug("filter is here"); + return true; + } + + }); + + task0.addHandler(new StopHandler(task0)); + + task0.startWatch(); + } + } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTaskTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTaskTest.java index ae8fa3b..641c4c7 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTaskTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WatchServiceHealthTaskTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -49,123 +47,109 @@ import com.orbitz.consul.option.CatalogOptions; import com.orbitz.consul.option.QueryOptions; @RunWith(PowerMockRunner.class) -@PrepareForTest({ Http.class }) -@PowerMockIgnore({ "javax.net.ssl.*" }) +@PrepareForTest({Http.class}) +@PowerMockIgnore({"javax.net.ssl.*"}) public class WatchServiceHealthTaskTest { - private static final Logger LOGGER = LoggerFactory - .getLogger(WatchServiceHealthTaskTest.class); - - private Consul consul; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Before - public void init() { - - List<ServiceHealth> list = new ArrayList<ServiceHealth>(); - - Service service = ImmutableService.builder().id("").port(0).address("") - .service("huangleibo").addTags("").createIndex(1).modifyIndex(1).build(); - ServiceHealth serviceHealth = ImmutableServiceHealth.builder() - .service(service) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); - list.add(serviceHealth); - - long lastContact = 1; - boolean knownLeader = true; - BigInteger index = BigInteger.valueOf(1); - final ConsulResponse<List<ServiceHealth>> response = new ConsulResponse<List<ServiceHealth>>( - list, lastContact, knownLeader, index); - - // - Http http = PowerMockito.mock(Http.class); - - PowerMockito - .doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) - throws Throwable { - Object[] args = invocation.getArguments(); - ((ConsulResponseCallback) args[2]).onComplete(response); - return null; - } - }) - .when(http) - .asyncGet(Mockito.anyString(), - Mockito.any(TypeReference.class), - Mockito.any(ConsulResponseCallback.class)); - - // - PowerMockito.spy(Http.class); - PowerMockito.when(Http.getInstance()).thenReturn(http); - - } - - @Test - public void testgetServiceName() { - consul = Consul.newClient(); - - WatchServiceHealthTask task0 = new WatchServiceHealthTask( - consul.healthClient(), "huangleibo_task0", true, - CatalogOptions.BLANK, 10, QueryOptions.BLANK); - - LOGGER.info("service name:" + task0.getServiceName()); - - WatchServiceHealthTask task1 = new WatchServiceHealthTask( - consul.healthClient(), "huangleibo_task1", true, 10); - - LOGGER.debug("service name:" + task1.getServiceName()); - - WatchServiceHealthTask task2 = new WatchServiceHealthTask( - consul.healthClient(), "huangleibo_task2", 10); - - LOGGER.debug("service name:" + task2.getServiceName()); - - } - - public class StopHandler implements WatchTask.Handler<List<ServiceHealth>> - { - - private WatchServiceHealthTask task; - - StopHandler(WatchServiceHealthTask task) - { - this.task = task; - } - - @Override - public void handle(ConsulResponse<List<ServiceHealth>> object) { - // TODO Auto-generated method stub - List<ServiceHealth> list = (List<ServiceHealth>)object.getResponse(); - LOGGER.debug("handler:"+list.get(0).getService().getService()); - task.stopWatch(); - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void teststartWatch() { - Consul consul = Consul.newClient(); - String serviceName = "huangleibo"; - - WatchServiceHealthTask task0 = new WatchServiceHealthTask( - consul.healthClient(), serviceName, true, CatalogOptions.BLANK, - 10, QueryOptions.BLANK); - - task0.addFilter(new Filter() { - - @Override - public boolean filter(ConsulResponse object) { - // TODO Auto-generated method stub - List<ServiceHealth> list = (List<ServiceHealth>)object.getResponse(); - LOGGER.debug("filter:"+list.get(0).getService().getService()); - return true; - } - - }); - - task0.addHandler(new StopHandler(task0)); - - task0.startWatch(); - } + private static final Logger LOGGER = LoggerFactory.getLogger(WatchServiceHealthTaskTest.class); + + private Consul consul; + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Before + public void init() { + + List<ServiceHealth> list = new ArrayList<ServiceHealth>(); + + Service service = ImmutableService.builder().id("").port(0).address("").service("huangleibo").addTags("") + .createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth = ImmutableServiceHealth.builder().service(service) + .node(ImmutableNode.builder().node("").address("").build()).build(); + list.add(serviceHealth); + + long lastContact = 1; + boolean knownLeader = true; + BigInteger index = BigInteger.valueOf(1); + final ConsulResponse<List<ServiceHealth>> response = + new ConsulResponse<List<ServiceHealth>>(list, lastContact, knownLeader, index); + + // + Http http = PowerMockito.mock(Http.class); + + PowerMockito.doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + ((ConsulResponseCallback) args[2]).onComplete(response); + return null; + } + }).when(http).asyncGet(Mockito.anyString(), Mockito.any(TypeReference.class), + Mockito.any(ConsulResponseCallback.class)); + + // + PowerMockito.spy(Http.class); + PowerMockito.when(Http.getInstance()).thenReturn(http); + + } + + @Test + public void testgetServiceName() { + consul = Consul.newClient(); + + WatchServiceHealthTask task0 = new WatchServiceHealthTask(consul.healthClient(), "huangleibo_task0", true, + CatalogOptions.BLANK, 10, QueryOptions.BLANK); + + LOGGER.info("service name:" + task0.getServiceName()); + + WatchServiceHealthTask task1 = new WatchServiceHealthTask(consul.healthClient(), "huangleibo_task1", true, 10); + + LOGGER.debug("service name:" + task1.getServiceName()); + + WatchServiceHealthTask task2 = new WatchServiceHealthTask(consul.healthClient(), "huangleibo_task2", 10); + + LOGGER.debug("service name:" + task2.getServiceName()); + + } + + public class StopHandler implements WatchTask.Handler<List<ServiceHealth>> { + + private WatchServiceHealthTask task; + + StopHandler(WatchServiceHealthTask task) { + this.task = task; + } + + @Override + public void handle(ConsulResponse<List<ServiceHealth>> object) { + // TODO Auto-generated method stub + List<ServiceHealth> list = (List<ServiceHealth>) object.getResponse(); + LOGGER.debug("handler:" + list.get(0).getService().getService()); + task.stopWatch(); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void teststartWatch() { + Consul consul = Consul.newClient(); + String serviceName = "huangleibo"; + + WatchServiceHealthTask task0 = new WatchServiceHealthTask(consul.healthClient(), serviceName, true, + CatalogOptions.BLANK, 10, QueryOptions.BLANK); + + task0.addFilter(new Filter() { + + @Override + public boolean filter(ConsulResponse object) { + // TODO Auto-generated method stub + List<ServiceHealth> list = (List<ServiceHealth>) object.getResponse(); + LOGGER.debug("filter:" + list.get(0).getService().getService()); + return true; + } + + }); + + task0.addHandler(new StopHandler(task0)); + + task0.startWatch(); + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandlerTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandlerTest.java index 9c37213..1c46d33 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandlerTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/expose/WriteBufferHandlerTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.expose; @@ -31,31 +29,28 @@ import com.orbitz.consul.model.ConsulResponse; import com.orbitz.consul.model.health.ImmutableNode; public class WriteBufferHandlerTest { - @Test - public void testhandle() { - List<ServiceHealth> list = new ArrayList<ServiceHealth>(); + @Test + public void testhandle() { + List<ServiceHealth> list = new ArrayList<ServiceHealth>(); - // modifyIndex 1 - Service service0 = ImmutableService.builder().id("huangleibo1").port(0) - .address("").service("huangleibo").addTags("").createIndex(1) - .modifyIndex(1).build(); - ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder() - .service(service0) - .node(ImmutableNode.builder().node("").address("").build()) - .build(); + // modifyIndex 1 + Service service0 = ImmutableService.builder().id("huangleibo1").port(0).address("").service("huangleibo") + .addTags("").createIndex(1).modifyIndex(1).build(); + ServiceHealth serviceHealth0 = ImmutableServiceHealth.builder().service(service0) + .node(ImmutableNode.builder().node("").address("").build()).build(); - list.add(serviceHealth0); + list.add(serviceHealth0); - long lastContact = 1; - boolean knownLeader = true; - BigInteger index = BigInteger.valueOf(1); - ConsulResponse<List<ServiceHealth>> object = new ConsulResponse<List<ServiceHealth>>( - list, lastContact, knownLeader, index); + long lastContact = 1; + boolean knownLeader = true; + BigInteger index = BigInteger.valueOf(1); + ConsulResponse<List<ServiceHealth>> object = + new ConsulResponse<List<ServiceHealth>>(list, lastContact, knownLeader, index); - WriteBufferHandler<List<ServiceHealth>> handler = new WriteBufferHandler<List<ServiceHealth>>( - ServiceData.DataType.service); + WriteBufferHandler<List<ServiceHealth>> handler = + new WriteBufferHandler<List<ServiceHealth>>(ServiceData.DataType.service); - handler.handle(object); + handler.handle(object); - } + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealthTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealthTest.java index 8c1f675..787a008 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealthTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceHealthTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.model.health; @@ -26,44 +24,39 @@ import com.orbitz.consul.model.health.Node; public class ServiceHealthTest { - @Test - public void TestImmutableServiceHealth() { - Service service = ImmutableService.builder().id("").port(0).address("") - .service("huangleibo").addTags("").createIndex(1) - .modifyIndex(1).build(); - Node node = ImmutableNode.builder().node("").address("").build(); + @Test + public void TestImmutableServiceHealth() { + Service service = ImmutableService.builder().id("").port(0).address("").service("huangleibo").addTags("") + .createIndex(1).modifyIndex(1).build(); + Node node = ImmutableNode.builder().node("").address("").build(); - HealthCheck healthCheck0 = ImmutableHealthCheck.builder().checkId("") - .name("").node("").notes("").output("").serviceId("") - .serviceName("").status("").build(); - HealthCheck healthCheck1 = ImmutableHealthCheck.builder().checkId("") - .name("").node("").notes("").output("").serviceId("") - .serviceName("").status("").build(); - HealthCheck healthCheck2 = ImmutableHealthCheck.builder().checkId("") - .name("").node("").notes("").output("").serviceId("") - .serviceName("").status("").build(); + HealthCheck healthCheck0 = ImmutableHealthCheck.builder().checkId("").name("").node("").notes("").output("") + .serviceId("").serviceName("").status("").build(); + HealthCheck healthCheck1 = ImmutableHealthCheck.builder().checkId("").name("").node("").notes("").output("") + .serviceId("").serviceName("").status("").build(); + HealthCheck healthCheck2 = ImmutableHealthCheck.builder().checkId("").name("").node("").notes("").output("") + .serviceId("").serviceName("").status("").build(); - ImmutableServiceHealth serviceHealth0 = ImmutableServiceHealth - .builder().service(service).node(node).addChecks(healthCheck0) - .addChecks(healthCheck1, healthCheck2).build(); + ImmutableServiceHealth serviceHealth0 = ImmutableServiceHealth.builder().service(service).node(node) + .addChecks(healthCheck0).addChecks(healthCheck1, healthCheck2).build(); - Assert.assertNotNull(serviceHealth0.getNode()); - Assert.assertNotNull(serviceHealth0.getChecks()); - /* ############################################################### */ + Assert.assertNotNull(serviceHealth0.getNode()); + Assert.assertNotNull(serviceHealth0.getChecks()); + /* ############################################################### */ - ImmutableServiceHealth serviceHealth1 = serviceHealth0.withNode(node) - .withNode(ImmutableNode.builder().node("").address("").build()) - .withService(service).withService(ImmutableService.builder().id("").port(0).address("") - .service("huangleibo1111").addTags("").createIndex(1) - .modifyIndex(1).build()).withChecks(healthCheck0); - - Assert.assertFalse(serviceHealth1.equals(serviceHealth0)); - System.out.println(serviceHealth1.hashCode()); - - /* ############################################################### */ - - ImmutableServiceHealth serviceHealth2 = ImmutableServiceHealth.builder().from(serviceHealth1).build(); - Assert.assertTrue(serviceHealth1.equals(serviceHealth2)); - } + ImmutableServiceHealth serviceHealth1 = serviceHealth0.withNode(node) + .withNode(ImmutableNode.builder().node("").address("").build()) + .withService(service).withService(ImmutableService.builder().id("").port(0).address("") + .service("huangleibo1111").addTags("").createIndex(1).modifyIndex(1).build()) + .withChecks(healthCheck0); + + Assert.assertFalse(serviceHealth1.equals(serviceHealth0)); + System.out.println(serviceHealth1.hashCode()); + + /* ############################################################### */ + + ImmutableServiceHealth serviceHealth2 = ImmutableServiceHealth.builder().from(serviceHealth1).build(); + Assert.assertTrue(serviceHealth1.equals(serviceHealth2)); + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceTest.java index 42908bc..62724e5 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/model/health/ServiceTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.model.health; @@ -20,28 +18,24 @@ import org.junit.Test; public class ServiceTest { - @Test - public void testImmutableService() { - ImmutableService service0 = ImmutableService.builder() - .id("huangleibo_id").port(0).address("").service("huangleibo") - .addTags("111", "222").createIndex(1).modifyIndex(1).build(); - Assert.assertEquals("huangleibo_id", service0.getId()); - Assert.assertEquals(1, service0.getCreateIndex()); - Assert.assertEquals(1, service0.getModifyIndex()); + @Test + public void testImmutableService() { + ImmutableService service0 = ImmutableService.builder().id("huangleibo_id").port(0).address("") + .service("huangleibo").addTags("111", "222").createIndex(1).modifyIndex(1).build(); + Assert.assertEquals("huangleibo_id", service0.getId()); + Assert.assertEquals(1, service0.getCreateIndex()); + Assert.assertEquals(1, service0.getModifyIndex()); - ImmutableService service1 = service0.withId("huangleibo_id") - .withId("new_id").withService("huangleibo") - .withService("new_service").withTags("new_tags") - .withAddress("").withAddress("new_address").withPort(0) - .withPort(1).withCreateIndex(1).withCreateIndex(2) - .withModifyIndex(1).withModifyIndex(2); + ImmutableService service1 = service0.withId("huangleibo_id").withId("new_id").withService("huangleibo") + .withService("new_service").withTags("new_tags").withAddress("").withAddress("new_address") + .withPort(0).withPort(1).withCreateIndex(1).withCreateIndex(2).withModifyIndex(1) + .withModifyIndex(2); - Assert.assertFalse(service0.equals(service1)); + Assert.assertFalse(service0.equals(service1)); - System.out.println(service1.hashCode()); + System.out.println(service1.hashCode()); - ImmutableService service2 = ImmutableService.builder().from(service1) - .build(); - Assert.assertEquals("new_id", service2.getId()); - } + ImmutableService service2 = ImmutableService.builder().from(service1).build(); + Assert.assertEquals("new_id", service2.getId()); + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/util/HttpTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/util/HttpTest.java index acf72cc..086f0f0 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/util/HttpTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/consulextend/util/HttpTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.consulextend.util; @@ -28,7 +26,6 @@ import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import org.junit.Before; import org.junit.Test; -import org.onap.msb.apiroute.wrapper.consulextend.util.Http; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,57 +36,53 @@ import com.orbitz.consul.option.ImmutableQueryOptions; import com.orbitz.consul.option.QueryOptions; public class HttpTest { - private static final Logger LOGGER = LoggerFactory - .getLogger(HttpTest.class); - - @Before - public void init() { - - } - - @Test - public void testoptionsFrom() { - ImmutableCatalogOptions catalogs = ImmutableCatalogOptions.builder() - .build(); - catalogs = catalogs.withDatacenter("datacenter").withTag("tag"); - - BigInteger index = new BigInteger("1"); - ImmutableQueryOptions querys = QueryOptions.blockSeconds(10, index) - .build(); - querys = querys.withConsistencyMode(ConsistencyMode.STALE) - .withDatacenter("datacenter").withNear("near") - .withToken("taoken"); - String url = Http.optionsFrom(catalogs, querys); - LOGGER.info(url); - } - - @Test - public void testconsulResponse() { - - TypeReference<Map<String, List<String>>> TYPE_SERVICES_MAP = new TypeReference<Map<String, List<String>>>() {}; - - ProtocolVersion version = new ProtocolVersion("HTTP",1,1); - StatusLine status= new BasicStatusLine(version,200,"ok"); - BasicHttpResponse response = new BasicHttpResponse(status); - - response.setHeader("X-Consul-Index", "1"); - response.setHeader("X-Consul-Lastcontact", "1"); - response.setHeader("X-Consul-Knownleader", "true"); - - BasicHttpEntity entity = new BasicHttpEntity(); - InputStream content = HttpTest.class.getResourceAsStream("serviceslist.json"); - entity.setContent(content); - response.setEntity(entity); - - Http.consulResponse(TYPE_SERVICES_MAP, response); - - TypeReference<String> TYPE_SERVICES_MAP_STRING = new TypeReference<String>() {}; - InputStream content1 = HttpTest.class.getResourceAsStream("serviceslist.json"); - entity.setContent(content1); - - Http.consulResponse(TYPE_SERVICES_MAP_STRING, response); - - TypeReference<HttpEntity> TYPE_SERVICES_MAP_ENTITY = new TypeReference<HttpEntity>() {}; - Http.consulResponse(TYPE_SERVICES_MAP_ENTITY, response); - } + private static final Logger LOGGER = LoggerFactory.getLogger(HttpTest.class); + + @Before + public void init() { + + } + + @Test + public void testoptionsFrom() { + ImmutableCatalogOptions catalogs = ImmutableCatalogOptions.builder().build(); + catalogs = catalogs.withDatacenter("datacenter").withTag("tag"); + + BigInteger index = new BigInteger("1"); + ImmutableQueryOptions querys = QueryOptions.blockSeconds(10, index).build(); + querys = querys.withConsistencyMode(ConsistencyMode.STALE).withDatacenter("datacenter").withNear("near") + .withToken("taoken"); + String url = Http.optionsFrom(catalogs, querys); + LOGGER.info(url); + } + + @Test + public void testconsulResponse() { + + TypeReference<Map<String, List<String>>> TYPE_SERVICES_MAP = new TypeReference<Map<String, List<String>>>() {}; + + ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1); + StatusLine status = new BasicStatusLine(version, 200, "ok"); + BasicHttpResponse response = new BasicHttpResponse(status); + + response.setHeader("X-Consul-Index", "1"); + response.setHeader("X-Consul-Lastcontact", "1"); + response.setHeader("X-Consul-Knownleader", "true"); + + BasicHttpEntity entity = new BasicHttpEntity(); + InputStream content = HttpTest.class.getResourceAsStream("serviceslist.json"); + entity.setContent(content); + response.setEntity(entity); + + Http.consulResponse(TYPE_SERVICES_MAP, response); + + TypeReference<String> TYPE_SERVICES_MAP_STRING = new TypeReference<String>() {}; + InputStream content1 = HttpTest.class.getResourceAsStream("serviceslist.json"); + entity.setContent(content1); + + Http.consulResponse(TYPE_SERVICES_MAP_STRING, response); + + TypeReference<HttpEntity> TYPE_SERVICES_MAP_ENTITY = new TypeReference<HttpEntity>() {}; + Http.consulResponse(TYPE_SERVICES_MAP_ENTITY, response); + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/queue/QueueManagerTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/queue/QueueManagerTest.java index 1260c5f..931c09d 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/queue/QueueManagerTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/queue/QueueManagerTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.queue; @@ -55,139 +53,133 @@ import com.fiftyonred.mock_jedis.MockJedisPool; import com.orbitz.consul.model.health.ImmutableNode; @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RouteUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RouteUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class QueueManagerTest { - private static QueueManager queueManager; - - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - queueManager=QueueManager.getInstance(); - putInServiceListQueue(); - putInServiceQueue4Update(); - - } - - @Before - public void setUpBeforeTest() throws Exception { - final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); - PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); - PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); - - PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return mockJedisPool.getResource().keys((String) args[0]); - } - }); - } - - - - public void test_ServiceConsumer(){ - - //start ServiceListConsumer -// new Thread(new ServiceListConsumer(this),"ServiceListConsumerThread").start(); - - //start Service Consumer - int serviceQueneNum=RouteUtil.SERVICE_DATA_QUEUE_NUM; - for(int i=0;i<serviceQueneNum;i++){ - new Thread(new ServiceConsumer(i),"ServiceConsumerThread"+i).start(); + private static QueueManager queueManager; + + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + queueManager = QueueManager.getInstance(); + putInServiceListQueue(); + putInServiceQueue4Update(); + } - - } - - - public void test_ServiceListConsumer(){ - - //start ServiceListConsumer - new Thread(new ServiceListConsumer(),"ServiceListConsumerThread").start(); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + + @Before + public void setUpBeforeTest() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); } - putInServiceQueue4Delete(); - } - - - - private static void putInServiceListQueue(){ - ServiceData<HttpEntity> data=new ServiceData<HttpEntity>(); - data.setDataType(ServiceData.DataType.service_list); - - BasicHttpEntity entity = new BasicHttpEntity(); - InputStream content = HttpTest.class.getResourceAsStream("serviceslist.json"); - entity.setContent(content); - data.setData(entity); - - try { - queueManager.putIn(data); - } catch (Exception e) { - Assert.assertTrue(e instanceof InterruptedException); + + + + public void test_ServiceConsumer() { + + // start ServiceListConsumer + // new Thread(new ServiceListConsumer(this),"ServiceListConsumerThread").start(); + + // start Service Consumer + int serviceQueneNum = RouteUtil.SERVICE_DATA_QUEUE_NUM; + for (int i = 0; i < serviceQueneNum; i++) { + new Thread(new ServiceConsumer(i), "ServiceConsumerThread" + i).start(); + } + } - } - - private static void putInServiceQueue4Update(){ - ServiceData<List<ServiceHealth>> data=new ServiceData<List<ServiceHealth>>(); - data.setDataType(ServiceData.DataType.service); - data.setOperate(ServiceData.Operate.delete); - - List<String> tagList = new ArrayList<String>(); - tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tagList - .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); - tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); - - Service service = - ImmutableService.builder().id("id").port(8686).address("10.74.165.246").service("msbtest") - .addAllTags(tagList).createIndex(0).modifyIndex(0).build(); - ServiceHealth serviceHealth = - ImmutableServiceHealth.builder().service(service) - .node(ImmutableNode.builder().node("server").address("192.168.1.98").build()).build(); - List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); - serviceHealthList.add(serviceHealth); - - data.setData(serviceHealthList); - - try { - queueManager.putIn(data); - } catch (Exception e) { - Assert.assertTrue(e instanceof InterruptedException); + + + public void test_ServiceListConsumer() { + + // start ServiceListConsumer + new Thread(new ServiceListConsumer(), "ServiceListConsumerThread").start(); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + putInServiceQueue4Delete(); } - } - - private static void putInServiceQueue4Delete(){ - ServiceData<List<ServiceHealth>> data=new ServiceData<List<ServiceHealth>>(); - data.setDataType(ServiceData.DataType.service); - data.setOperate(ServiceData.Operate.update); - - List<String> tagList = new ArrayList<String>(); - tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tagList - .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); - tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); - - Service service = - ImmutableService.builder().id("id").port(8686).address("10.74.165.246").service("msbtest") - .addAllTags(tagList).createIndex(0).modifyIndex(0).build(); - ServiceHealth serviceHealth = - ImmutableServiceHealth.builder().service(service) - .node(ImmutableNode.builder().node("server").address("192.168.1.98").build()).build(); - List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); - serviceHealthList.add(serviceHealth); - - data.setData(serviceHealthList); - - try { - queueManager.putIn(data); - } catch (Exception e) { - Assert.assertTrue(e instanceof InterruptedException); + + + + private static void putInServiceListQueue() { + ServiceData<HttpEntity> data = new ServiceData<HttpEntity>(); + data.setDataType(ServiceData.DataType.service_list); + + BasicHttpEntity entity = new BasicHttpEntity(); + InputStream content = HttpTest.class.getResourceAsStream("serviceslist.json"); + entity.setContent(content); + data.setData(entity); + + try { + queueManager.putIn(data); + } catch (Exception e) { + Assert.assertTrue(e instanceof InterruptedException); + } + } + + private static void putInServiceQueue4Update() { + ServiceData<List<ServiceHealth>> data = new ServiceData<List<ServiceHealth>>(); + data.setDataType(ServiceData.DataType.service); + data.setOperate(ServiceData.Operate.delete); + + List<String> tagList = new ArrayList<String>(); + tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + + Service service = ImmutableService.builder().id("id").port(8686).address("10.74.165.246").service("msbtest") + .addAllTags(tagList).createIndex(0).modifyIndex(0).build(); + ServiceHealth serviceHealth = ImmutableServiceHealth.builder().service(service) + .node(ImmutableNode.builder().node("server").address("192.168.1.98").build()).build(); + List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); + serviceHealthList.add(serviceHealth); + + data.setData(serviceHealthList); + + try { + queueManager.putIn(data); + } catch (Exception e) { + Assert.assertTrue(e instanceof InterruptedException); + } } - } - - + + private static void putInServiceQueue4Delete() { + ServiceData<List<ServiceHealth>> data = new ServiceData<List<ServiceHealth>>(); + data.setDataType(ServiceData.DataType.service); + data.setOperate(ServiceData.Operate.update); + + List<String> tagList = new ArrayList<String>(); + tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + + Service service = ImmutableService.builder().id("id").port(8686).address("10.74.165.246").service("msbtest") + .addAllTags(tagList).createIndex(0).modifyIndex(0).build(); + ServiceHealth serviceHealth = ImmutableServiceHealth.builder().service(service) + .node(ImmutableNode.builder().node("server").address("192.168.1.98").build()).build(); + List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); + serviceHealthList.add(serviceHealth); + + data.setData(serviceHealthList); + + try { + queueManager.putIn(data); + } catch (Exception e) { + Assert.assertTrue(e instanceof InterruptedException); + } + } + + } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/ApiRouteServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/ApiRouteServiceTest.java index 70b8441..76ad8f8 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/ApiRouteServiceTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/ApiRouteServiceTest.java @@ -1,21 +1,29 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.service; -import com.fiftyonred.mock_jedis.MockJedisPool; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -23,32 +31,26 @@ import org.junit.runner.RunWith; import org.onap.msb.apiroute.api.ApiRouteInfo; import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; -import org.onap.msb.apiroute.wrapper.service.ApiRouteService; import org.onap.msb.apiroute.wrapper.util.JedisUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; +import com.fiftyonred.mock_jedis.MockJedisPool; -import static org.junit.Assert.*; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class ApiRouteServiceTest { private static ApiRouteService apiRouteService = null; private static Comparator<ApiRouteInfo> apiRouteComparator = null; + @BeforeClass - public static void setUp() throws Exception{ + public static void setUp() throws Exception { apiRouteService = ApiRouteService.getInstance(); apiRouteComparator = new Comparator<ApiRouteInfo>() { @Override @@ -61,11 +63,12 @@ public class ApiRouteServiceTest { } }; } + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -75,17 +78,18 @@ public class ApiRouteServiceTest { } }); } + @Test - public void testGetApiRouteInstance_key_not_exist(){ + public void testGetApiRouteInstance_key_not_exist() { try { assertNull(apiRouteService.getApiRouteInstance("msb:routing:api:notexistservice:v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetApiRouteInstance_key_exist(){ + public void testGetApiRouteInstance_key_exist() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("testapi"); apirouteInfo.setVersion("v1"); @@ -94,18 +98,18 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo, "msb:routing:api:testapi:v1"); assertEquals(apirouteInfo, apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveApiRouteService2Redis(){ + public void testSaveApiRouteService2Redis() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("testapi"); apirouteInfo.setVersion("v1"); @@ -114,18 +118,18 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo, "msb:routing:api:testapi:v1"); assertEquals(apirouteInfo, apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveApiRouteService2Redis2(){ + public void testSaveApiRouteService2Redis2() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("test26msb"); apirouteInfo.setVersion("v1"); @@ -134,18 +138,18 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.151.26","443")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.151.26", "443")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:test26msb:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo, "msb:routing:api:test26msb:v1"); assertEquals(apirouteInfo, apiRouteService.getApiRouteInstance("msb:routing:api:test26msb:v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteApiRouteService2Redis(){ + public void testDeleteApiRouteService2Redis() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("testapi"); apirouteInfo.setVersion("v1"); @@ -154,20 +158,20 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo, "msb:routing:api:testapi:v1"); assertNotNull(apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1")); apiRouteService.deleteApiRouteService2Redis("msb:routing:api:testapi:v1"); assertNull(apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testUpdateApiRouteStatus2Redis(){ + public void testUpdateApiRouteStatus2Redis() { ApiRouteInfo apirouteInfo = new ApiRouteInfo(); apirouteInfo.setServiceName("testapi"); apirouteInfo.setVersion("v1"); @@ -176,15 +180,15 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; apirouteInfo.setServers(servers); try { - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo, "msb:routing:api:testapi:v1"); assertEquals("1", apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1").getStatus()); - apiRouteService.updateApiRouteStatus2Redis("msb:routing:api:testapi:v1","0"); + apiRouteService.updateApiRouteStatus2Redis("msb:routing:api:testapi:v1", "0"); assertEquals("0", apiRouteService.getApiRouteInstance("msb:routing:api:testapi:v1").getStatus()); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @@ -198,7 +202,7 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(false); - apirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + apirouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); ApiRouteInfo apirouteInfo2 = new ApiRouteInfo(); apirouteInfo2.setServiceName("testapi"); @@ -208,10 +212,10 @@ public class ApiRouteServiceTest { apirouteInfo2.setUseOwnUpstream("0"); apirouteInfo2.setVisualRange("0");; apirouteInfo.setEnable_ssl(true); - apirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + apirouteInfo2.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8088")}); - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); - apiRouteService.saveApiRouteService2Redis(apirouteInfo2,"msb:routing:api:testapi:v2"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo, "msb:routing:api:testapi:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo2, "msb:routing:api:testapi:v2"); List<ApiRouteInfo> expected = new ArrayList<>(); expected.add(apirouteInfo); @@ -234,7 +238,7 @@ public class ApiRouteServiceTest { apirouteInfo.setUseOwnUpstream("0"); apirouteInfo.setVisualRange("0"); apirouteInfo.setEnable_ssl(false); - apirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + apirouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); ApiRouteInfo apirouteInfo2 = new ApiRouteInfo(); apirouteInfo2.setServiceName("testapi"); @@ -244,23 +248,23 @@ public class ApiRouteServiceTest { apirouteInfo2.setUseOwnUpstream("0"); apirouteInfo2.setVisualRange("0");; apirouteInfo.setEnable_ssl(true); - apirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); - apiRouteService.saveApiRouteService2Redis(apirouteInfo,"msb:routing:api:testapi:v1"); - apiRouteService.saveApiRouteService2Redis(apirouteInfo2,"msb:routing:api:testapi:v2"); + apirouteInfo2.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8088")}); + apiRouteService.saveApiRouteService2Redis(apirouteInfo, "msb:routing:api:testapi:v1"); + apiRouteService.saveApiRouteService2Redis(apirouteInfo2, "msb:routing:api:testapi:v2"); - assertEquals(2,apiRouteService.getMultiApiRouteInstances("msb:routing:api:testapi:*").size()); - assertEquals(2,apiRouteService.deleteMultiApiRouteService2Redis("msb:routing:api:testapi:*")); - assertEquals(0,apiRouteService.getMultiApiRouteInstances("msb:routing:api:testapi:*").size()); + assertEquals(2, apiRouteService.getMultiApiRouteInstances("msb:routing:api:testapi:*").size()); + assertEquals(2, apiRouteService.deleteMultiApiRouteService2Redis("msb:routing:api:testapi:*")); + assertEquals(0, apiRouteService.getMultiApiRouteInstances("msb:routing:api:testapi:*").size()); } @Test(expected = Exception.class) public void testUpdateApiRouteStatus2Redis_keyNotExist() throws Exception { - apiRouteService.updateApiRouteStatus2Redis("msb:routing:api:notexistservice:v1","0"); + apiRouteService.updateApiRouteStatus2Redis("msb:routing:api:notexistservice:v1", "0"); } @Test(expected = Exception.class) public void testSaveApiRouteService2Redis_null() throws Exception { - apiRouteService.saveApiRouteService2Redis(null,"msb:routing:api:null:v1"); + apiRouteService.saveApiRouteService2Redis(null, "msb:routing:api:null:v1"); } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/CustomRouteServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/CustomRouteServiceTest.java index 87c295f..1e11c78 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/CustomRouteServiceTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/CustomRouteServiceTest.java @@ -1,21 +1,29 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.service; -import com.fiftyonred.mock_jedis.MockJedisPool; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -23,32 +31,26 @@ import org.junit.runner.RunWith; import org.onap.msb.apiroute.api.CustomRouteInfo; import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; -import org.onap.msb.apiroute.wrapper.service.CustomRouteService; import org.onap.msb.apiroute.wrapper.util.JedisUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; +import com.fiftyonred.mock_jedis.MockJedisPool; -import static org.junit.Assert.*; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class CustomRouteServiceTest { private static CustomRouteService customRouteService = null; private static Comparator<CustomRouteInfo> customRouteComparator = null; + @BeforeClass - public static void setUp() throws Exception{ + public static void setUp() throws Exception { customRouteService = CustomRouteService.getInstance(); customRouteComparator = new Comparator<CustomRouteInfo>() { @Override @@ -59,11 +61,12 @@ public class CustomRouteServiceTest { } }; } + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -73,17 +76,18 @@ public class CustomRouteServiceTest { } }); } + @Test - public void testGetCustomRouteInstance_key_not_exist(){ + public void testGetCustomRouteInstance_key_not_exist() { try { assertNull(customRouteService.getCustomRouteInstance("msb:routing:custom:notexistservice:v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetCustomRouteInstance_key_exist(){ + public void testGetCustomRouteInstance_key_exist() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -91,18 +95,18 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; customrouteInfo.setServers(servers); try { customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); assertEquals(customrouteInfo, customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveCustomRouteService2Redis(){ + public void testSaveCustomRouteService2Redis() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -110,18 +114,18 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; customrouteInfo.setServers(servers); try { customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); assertEquals(customrouteInfo, customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveCustomRouteService2Redis_urlIsSlash(){ + public void testSaveCustomRouteService2Redis_urlIsSlash() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -129,19 +133,19 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; customrouteInfo.setServers(servers); try { customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); customrouteInfo.setUrl(""); assertEquals(customrouteInfo, customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteCustomRouteService2Redis(){ + public void testDeleteCustomRouteService2Redis() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -149,7 +153,7 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; customrouteInfo.setServers(servers); try { customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); @@ -157,12 +161,12 @@ public class CustomRouteServiceTest { customRouteService.deleteCustomRouteService2Redis("msb:routing:custom:testcustom"); assertNull(customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testUpdateCustomRouteStatus2Redis(){ + public void testUpdateCustomRouteStatus2Redis() { CustomRouteInfo customrouteInfo = new CustomRouteInfo(); customrouteInfo.setServiceName("testcustom"); customrouteInfo.setStatus("1"); @@ -170,7 +174,7 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; customrouteInfo.setServers(servers); try { customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); @@ -178,7 +182,7 @@ public class CustomRouteServiceTest { customRouteService.updateCustomRouteStatus2Redis("msb:routing:custom:testcustom", "0"); assertEquals("0", customRouteService.getCustomRouteInstance("msb:routing:custom:testcustom").getStatus()); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @@ -191,7 +195,7 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(false); - customrouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + customrouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); CustomRouteInfo customrouteInfo2 = new CustomRouteInfo(); customrouteInfo2.setServiceName("testcustom2"); @@ -200,7 +204,7 @@ public class CustomRouteServiceTest { customrouteInfo2.setUseOwnUpstream("0"); customrouteInfo2.setVisualRange("0");; customrouteInfo.setEnable_ssl(true); - customrouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + customrouteInfo2.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8088")}); customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); customRouteService.saveCustomRouteService2Redis(customrouteInfo2, "msb:routing:custom:testcustom2"); @@ -225,7 +229,7 @@ public class CustomRouteServiceTest { customrouteInfo.setUseOwnUpstream("0"); customrouteInfo.setVisualRange("0"); customrouteInfo.setEnable_ssl(false); - customrouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + customrouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); CustomRouteInfo customrouteInfo2 = new CustomRouteInfo(); customrouteInfo2.setServiceName("testcustom2"); @@ -234,12 +238,12 @@ public class CustomRouteServiceTest { customrouteInfo2.setUseOwnUpstream("0"); customrouteInfo2.setVisualRange("0");; customrouteInfo.setEnable_ssl(true); - customrouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + customrouteInfo2.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8088")}); customRouteService.saveCustomRouteService2Redis(customrouteInfo, "msb:routing:custom:testcustom"); customRouteService.saveCustomRouteService2Redis(customrouteInfo2, "msb:routing:custom:testcustom2"); - assertEquals(2,customRouteService.getMultiCustomRouteInstances("msb:routing:custom:*").size()); - assertEquals(2,customRouteService.deleteMultiCustomRouteService2Redis("msb:routing:custom:*")); + assertEquals(2, customRouteService.getMultiCustomRouteInstances("msb:routing:custom:*").size()); + assertEquals(2, customRouteService.deleteMultiCustomRouteService2Redis("msb:routing:custom:*")); assertEquals(0, customRouteService.getMultiCustomRouteInstances("msb:routing:custom:*").size()); } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/IuiRouteServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/IuiRouteServiceTest.java index bd4957e..213c3d6 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/IuiRouteServiceTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/IuiRouteServiceTest.java @@ -1,21 +1,29 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.service; -import com.fiftyonred.mock_jedis.MockJedisPool; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -23,32 +31,26 @@ import org.junit.runner.RunWith; import org.onap.msb.apiroute.api.IuiRouteInfo; import org.onap.msb.apiroute.api.RouteServer; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; -import org.onap.msb.apiroute.wrapper.service.IuiRouteService; import org.onap.msb.apiroute.wrapper.util.JedisUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; +import com.fiftyonred.mock_jedis.MockJedisPool; -import static org.junit.Assert.*; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class IuiRouteServiceTest { private static IuiRouteService iuiRouteService = null; private static Comparator<IuiRouteInfo> iuiRouteComparator = null; + @BeforeClass - public static void setUp() throws Exception{ + public static void setUp() throws Exception { iuiRouteService = IuiRouteService.getInstance(); iuiRouteComparator = new Comparator<IuiRouteInfo>() { @Override @@ -59,11 +61,12 @@ public class IuiRouteServiceTest { } }; } + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -73,17 +76,18 @@ public class IuiRouteServiceTest { } }); } + @Test - public void testGetIuiRouteInstance_key_not_exist(){ + public void testGetIuiRouteInstance_key_not_exist() { try { assertNull(iuiRouteService.getIuiRouteInstance("msb:routing:iui:notexistservice:v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetIuiRouteInstance_key_exist(){ + public void testGetIuiRouteInstance_key_exist() { IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); iuirouteInfo.setServiceName("testiui"); iuirouteInfo.setStatus("1"); @@ -91,18 +95,18 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; iuirouteInfo.setServers(servers); try { - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo, "msb:routing:iui:testiui"); assertEquals(iuirouteInfo, iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveIuiRouteService2Redis(){ + public void testSaveIuiRouteService2Redis() { IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); iuirouteInfo.setServiceName("testiui"); iuirouteInfo.setStatus("1"); @@ -110,18 +114,18 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; iuirouteInfo.setServers(servers); try { - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo, "msb:routing:iui:testiui"); assertEquals(iuirouteInfo, iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteIuiRouteService2Redis(){ + public void testDeleteIuiRouteService2Redis() { IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); iuirouteInfo.setServiceName("testiui"); iuirouteInfo.setStatus("1"); @@ -129,20 +133,20 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(false); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; iuirouteInfo.setServers(servers); try { - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo, "msb:routing:iui:testiui"); assertNotNull(iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui")); iuiRouteService.deleteIuiRouteService2Redis("msb:routing:iui:testiui"); assertNull(iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testUpdateIuiRouteStatus2Redis(){ + public void testUpdateIuiRouteStatus2Redis() { IuiRouteInfo iuirouteInfo = new IuiRouteInfo(); iuirouteInfo.setServiceName("testiui"); iuirouteInfo.setStatus("1"); @@ -150,15 +154,15 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(true); - RouteServer[] servers = new RouteServer[]{new RouteServer("10.74.148.88","8080")}; + RouteServer[] servers = new RouteServer[] {new RouteServer("10.74.148.88", "8080")}; iuirouteInfo.setServers(servers); try { - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo, "msb:routing:iui:testiui"); assertEquals("1", iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui").getStatus()); - iuiRouteService.updateIuiRouteStatus2Redis("msb:routing:iui:testiui","0"); + iuiRouteService.updateIuiRouteStatus2Redis("msb:routing:iui:testiui", "0"); assertEquals("0", iuiRouteService.getIuiRouteInstance("msb:routing:iui:testiui").getStatus()); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @@ -171,7 +175,7 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(false); - iuirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + iuirouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); IuiRouteInfo iuirouteInfo2 = new IuiRouteInfo(); iuirouteInfo2.setServiceName("testiui2"); @@ -180,10 +184,10 @@ public class IuiRouteServiceTest { iuirouteInfo2.setUseOwnUpstream("0"); iuirouteInfo2.setVisualRange("0");; iuirouteInfo.setEnable_ssl(true); - iuirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); + iuirouteInfo2.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8088")}); - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo2,"msb:routing:iui:testiui2"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo, "msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo2, "msb:routing:iui:testiui2"); List<IuiRouteInfo> expected = new ArrayList<>(); expected.add(iuirouteInfo); @@ -205,7 +209,7 @@ public class IuiRouteServiceTest { iuirouteInfo.setUseOwnUpstream("0"); iuirouteInfo.setVisualRange("0"); iuirouteInfo.setEnable_ssl(false); - iuirouteInfo.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8080")}); + iuirouteInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); IuiRouteInfo iuirouteInfo2 = new IuiRouteInfo(); iuirouteInfo2.setServiceName("testiui2"); @@ -214,23 +218,23 @@ public class IuiRouteServiceTest { iuirouteInfo2.setUseOwnUpstream("0"); iuirouteInfo2.setVisualRange("0");; iuirouteInfo.setEnable_ssl(true); - iuirouteInfo2.setServers(new RouteServer[]{new RouteServer("10.74.148.88","8088")}); - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo,"msb:routing:iui:testiui"); - iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo2,"msb:routing:iui:testiui2"); + iuirouteInfo2.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8088")}); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo, "msb:routing:iui:testiui"); + iuiRouteService.saveIuiRouteService2Redis(iuirouteInfo2, "msb:routing:iui:testiui2"); - assertEquals(2,iuiRouteService.getMultiIuiRouteInstances("msb:routing:iui:*").size()); - assertEquals(2,iuiRouteService.deleteMultiIuiRouteService2Redis("msb:routing:iui:*")); - assertEquals(0,iuiRouteService.getMultiIuiRouteInstances("msb:routing:iui:*").size()); + assertEquals(2, iuiRouteService.getMultiIuiRouteInstances("msb:routing:iui:*").size()); + assertEquals(2, iuiRouteService.deleteMultiIuiRouteService2Redis("msb:routing:iui:*")); + assertEquals(0, iuiRouteService.getMultiIuiRouteInstances("msb:routing:iui:*").size()); } @Test(expected = Exception.class) public void testUpdateIuiRouteStatus2Redis_keyNotExist() throws Exception { - iuiRouteService.updateIuiRouteStatus2Redis("msb:routing:iui:notexistservice","0"); + iuiRouteService.updateIuiRouteStatus2Redis("msb:routing:iui:notexistservice", "0"); } @Test(expected = Exception.class) public void testSaveIuiRouteService2Redis_null() throws Exception { - iuiRouteService.saveIuiRouteService2Redis(null,"msb:routing:iui:null"); + iuiRouteService.saveIuiRouteService2Redis(null, "msb:routing:iui:null"); } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullServiceTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullServiceTest.java index aa5db78..6e7200d 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullServiceTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/service/MicroServiceFullServiceTest.java @@ -1,21 +1,33 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.service; -import com.fiftyonred.mock_jedis.MockJedisPool; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.mockito.PowerMockito.when; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -23,31 +35,27 @@ import org.junit.runner.RunWith; import org.onap.msb.apiroute.api.MicroServiceFullInfo; import org.onap.msb.apiroute.api.Node; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; -import org.onap.msb.apiroute.wrapper.service.MicroServiceFullService; import org.onap.msb.apiroute.wrapper.util.JedisUtil; import org.onap.msb.apiroute.wrapper.util.MicroServiceUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.util.*; +import com.fiftyonred.mock_jedis.MockJedisPool; -import static org.junit.Assert.*; -import static org.powermock.api.mockito.PowerMockito.when; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,RedisAccessWrapper.class}) -@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({JedisUtil.class, RedisAccessWrapper.class}) +@PowerMockIgnore({"javax.management.*"}) public class MicroServiceFullServiceTest { private static MicroServiceFullService microServiceFullService = null; private static Comparator<MicroServiceFullInfo> serviceComparator = null; + @BeforeClass - public static void setUp() throws Exception{ + public static void setUp() throws Exception { microServiceFullService = MicroServiceFullService.getInstance(); serviceComparator = new Comparator<MicroServiceFullInfo>() { @Override @@ -60,11 +68,12 @@ public class MicroServiceFullServiceTest { } }; } + @Before public void setUpBeforeTest() throws Exception { final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { @@ -76,15 +85,16 @@ public class MicroServiceFullServiceTest { } @Test - public void testExistsMicroServiceInstance_notExist(){ + public void testExistsMicroServiceInstance_notExist() { try { assertFalse(microServiceFullService.existsMicroServiceInstance("notExist", "v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } + @Test - public void testExistsMicroServiceInstance_Exist(){ + public void testExistsMicroServiceInstance_Exist() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -94,20 +104,20 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); try { assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "v1")); microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); assertTrue(microServiceFullService.existsMicroServiceInstance("testService", "v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testSaveMicroServiceInfo2Redis(){ + public void testSaveMicroServiceInfo2Redis() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -117,7 +127,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); try { microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); @@ -125,12 +135,12 @@ public class MicroServiceFullServiceTest { assertEquals(microServiceFullInfo, actual); } catch (Exception e) { e.printStackTrace(); - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteMicroService(){ + public void testDeleteMicroService() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -140,21 +150,21 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); try { microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); assertTrue(microServiceFullService.existsMicroServiceInstance("testService", "v1")); - microServiceFullService.deleteMicroService("testService","v1"); + microServiceFullService.deleteMicroService("testService", "v1"); assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testUpdateMicroServiceStatus(){ + public void testUpdateMicroServiceStatus() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -164,20 +174,20 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); try { microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); - assertEquals("1", microServiceFullService.getMicroServiceInstance("testService","v1").getStatus()); + assertEquals("1", microServiceFullService.getMicroServiceInstance("testService", "v1").getStatus()); microServiceFullService.updateMicroServiceStatus("testService", "v1", "0"); assertEquals("0", microServiceFullService.getMicroServiceInstance("testService", "v1").getStatus()); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetAllMicroServiceKey(){ + public void testGetAllMicroServiceKey() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -187,7 +197,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); MicroServiceFullInfo microServiceFullInfo2 = new MicroServiceFullInfo(); @@ -199,7 +209,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo2.setProtocol("http"); microServiceFullInfo2.setEnable_ssl(false); Set<Node> nodeSet2 = new HashSet<>(); - nodeSet2.add(new Node("10.74.148.88","8081")); + nodeSet2.add(new Node("10.74.148.88", "8081")); microServiceFullInfo2.setNodes(nodeSet2); MicroServiceFullInfo microServiceFullInfo3 = new MicroServiceFullInfo(); @@ -211,7 +221,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo3.setProtocol("http"); microServiceFullInfo3.setEnable_ssl(false); Set<Node> nodeSet3 = new HashSet<>(); - nodeSet3.add(new Node("10.74.148.89","8080")); + nodeSet3.add(new Node("10.74.148.89", "8080")); microServiceFullInfo3.setNodes(nodeSet3); try { @@ -220,19 +230,19 @@ public class MicroServiceFullServiceTest { microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo3); Set<String> result = microServiceFullService.getAllMicroServiceKey(); - final Set<String> expected =new HashSet<String>(); + final Set<String> expected = new HashSet<String>(); expected.add("testService"); expected.add("testService2"); assertEquals(expected, result); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetAllVersionsOfTheService(){ + public void testGetAllVersionsOfTheService() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -242,7 +252,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); MicroServiceFullInfo microServiceFullInfo2 = new MicroServiceFullInfo(); @@ -254,7 +264,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo2.setProtocol("http"); microServiceFullInfo2.setEnable_ssl(false); Set<Node> nodeSet2 = new HashSet<>(); - nodeSet2.add(new Node("10.74.148.88","8081")); + nodeSet2.add(new Node("10.74.148.88", "8081")); microServiceFullInfo2.setNodes(nodeSet2); MicroServiceFullInfo microServiceFullInfo3 = new MicroServiceFullInfo(); @@ -266,7 +276,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo3.setProtocol("http"); microServiceFullInfo3.setEnable_ssl(false); Set<Node> nodeSet3 = new HashSet<>(); - nodeSet3.add(new Node("10.74.148.89","8080")); + nodeSet3.add(new Node("10.74.148.89", "8080")); microServiceFullInfo3.setNodes(nodeSet3); try { @@ -281,17 +291,17 @@ public class MicroServiceFullServiceTest { expected.add(microServiceFullInfo); expected.add(microServiceFullInfo3); - Collections.sort(expected,serviceComparator); - Collections.sort(result,serviceComparator); + Collections.sort(expected, serviceComparator); + Collections.sort(result, serviceComparator); assertEquals(expected, result); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testGetAllMicroServicesInstances(){ + public void testGetAllMicroServicesInstances() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -301,7 +311,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); MicroServiceFullInfo microServiceFullInfo2 = new MicroServiceFullInfo(); @@ -313,7 +323,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo2.setProtocol("http"); microServiceFullInfo2.setEnable_ssl(true); Set<Node> nodeSet2 = new HashSet<>(); - nodeSet2.add(new Node("10.74.148.89","8080")); + nodeSet2.add(new Node("10.74.148.89", "8080")); microServiceFullInfo2.setNodes(nodeSet2); try { @@ -325,17 +335,17 @@ public class MicroServiceFullServiceTest { expected.add(microServiceFullInfo2); List<MicroServiceFullInfo> result = microServiceFullService.getAllMicroServiceInstances(); Collections.sort(expected, serviceComparator); - Collections.sort(result,serviceComparator ); + Collections.sort(result, serviceComparator); assertEquals(expected, result); } catch (Exception e) { e.printStackTrace(); - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void testDeleteMultiMicroService(){ + public void testDeleteMultiMicroService() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion("v1"); @@ -345,7 +355,7 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); @@ -358,34 +368,36 @@ public class MicroServiceFullServiceTest { microServiceFullInfo3.setProtocol("http"); microServiceFullInfo3.setEnable_ssl(false); Set<Node> nodeSet3 = new HashSet<>(); - nodeSet3.add(new Node("10.74.148.89","8080")); + nodeSet3.add(new Node("10.74.148.89", "8080")); microServiceFullInfo3.setNodes(nodeSet3); try { microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo3); - //two versions of testservice exist - assertEquals(2,microServiceFullService.getAllVersionsOfTheService("testService").size()); - //delete all versions of testservice - long size = microServiceFullService.deleteMultiMicroService(MicroServiceUtil.getPrefixedKey("testService","*")); - //after delete,no version exist - assertEquals(0,microServiceFullService.getAllVersionsOfTheService("testService").size()); + // two versions of testservice exist + assertEquals(2, microServiceFullService.getAllVersionsOfTheService("testService").size()); + // delete all versions of testservice + long size = microServiceFullService + .deleteMultiMicroService(MicroServiceUtil.getPrefixedKey("testService", "*")); + // after delete,no version exist + assertEquals(0, microServiceFullService.getAllVersionsOfTheService("testService").size()); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } @Test - public void tesGetMicroServiceInstance_notExist(){ + public void tesGetMicroServiceInstance_notExist() { try { - assertNull(microServiceFullService.getMicroServiceInstance("notExist","v1")); + assertNull(microServiceFullService.getMicroServiceInstance("notExist", "v1")); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } + @Test - public void tesExistsGetUpdateDeleteMicroServiceStatus_versionNull(){ + public void tesExistsGetUpdateDeleteMicroServiceStatus_versionNull() { MicroServiceFullInfo microServiceFullInfo = new MicroServiceFullInfo(); microServiceFullInfo.setServiceName("testService"); microServiceFullInfo.setVersion(""); @@ -395,29 +407,29 @@ public class MicroServiceFullServiceTest { microServiceFullInfo.setProtocol("http"); microServiceFullInfo.setEnable_ssl(false); Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88","8080")); + nodeSet.add(new Node("10.74.148.88", "8080")); microServiceFullInfo.setNodes(nodeSet); try { - //test null + // test null assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "null")); microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); - assertEquals("1", microServiceFullService.getMicroServiceInstance("testService","null").getStatus()); + assertEquals("1", microServiceFullService.getMicroServiceInstance("testService", "null").getStatus()); microServiceFullService.updateMicroServiceStatus("testService", "null", "0"); assertEquals("0", microServiceFullService.getMicroServiceInstance("testService", "null").getStatus()); - microServiceFullService.deleteMicroService("testService","null"); + microServiceFullService.deleteMicroService("testService", "null"); assertFalse(microServiceFullService.existsMicroServiceInstance("testService", "null")); - //test String "null" + // test String "null" assertFalse(microServiceFullService.existsMicroServiceInstance("testService", null)); microServiceFullService.saveMicroServiceInfo2Redis(microServiceFullInfo); - assertEquals("1", microServiceFullService.getMicroServiceInstance("testService",null).getStatus()); + assertEquals("1", microServiceFullService.getMicroServiceInstance("testService", null).getStatus()); microServiceFullService.updateMicroServiceStatus("testService", null, "0"); assertEquals("0", microServiceFullService.getMicroServiceInstance("testService", null).getStatus()); - microServiceFullService.deleteMicroService("testService",null); + microServiceFullService.deleteMicroService("testService", null); assertFalse(microServiceFullService.existsMicroServiceInstance("testService", null)); } catch (Exception e) { - assert false:"throw exception means error occured!"+e.getMessage(); + assert false : "throw exception means error occured!" + e.getMessage(); } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListenerTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListenerTest.java index 1df3643..78fed80 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListenerTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/serviceListener/MicroServiceChangeListenerTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.serviceListener; @@ -39,7 +37,6 @@ import org.onap.msb.apiroute.wrapper.CustomRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.InitRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.IuiRouteServiceWrapper; import org.onap.msb.apiroute.wrapper.dao.RedisAccessWrapper; -import org.onap.msb.apiroute.wrapper.serviceListener.RouteNotify; import org.onap.msb.apiroute.wrapper.util.ConfigUtil; import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; import org.onap.msb.apiroute.wrapper.util.JedisUtil; @@ -49,633 +46,619 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fiftyonred.mock_jedis.MockJedisPool; + import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; -import com.fiftyonred.mock_jedis.MockJedisPool; - @RunWith(PowerMockRunner.class) -@PrepareForTest({JedisUtil.class,ConfigUtil.class,HttpClientUtil.class, RedisAccessWrapper.class,}) +@PrepareForTest({JedisUtil.class, ConfigUtil.class, HttpClientUtil.class, RedisAccessWrapper.class,}) @PowerMockIgnore({"javax.management.*"}) public class MicroServiceChangeListenerTest { - private static RouteNotify routeInstance; - private static ApiRouteServiceWrapper apiRouteServiceWrapper; - private static IuiRouteServiceWrapper iuiRouteServiceWrapper; - private static CustomRouteServiceWrapper customRouteServiceWrapper; - - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - InitRouteServiceWrapper.getInstance().registerServiceChangeListener(); - routeInstance=RouteNotify.getInstance(); - apiRouteServiceWrapper=ApiRouteServiceWrapper.getInstance(); - iuiRouteServiceWrapper=IuiRouteServiceWrapper.getInstance(); - customRouteServiceWrapper=CustomRouteServiceWrapper.getInstance(); - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); - ConfigUtil.getInstance().initRouteWay(); - } - - @Before - public void initReidsMock() throws Exception { - final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); - PowerMockito.mockStatic(JedisUtil.class); - JedisUtil jedisUtil=PowerMockito.mock(JedisUtil.class); - PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); - - PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return mockJedisPool.getResource().keys((String) args[0]); - } - }); - } - - @Test - public void test_noticeRouteListener4Update_api(){ - try { - routeInstance.noticeRouteListener4Update("apiTest-ns", "v1", buildMicroServiceFullInfo4API()); - ApiRouteInfo apiRouteInfo=apiRouteServiceWrapper.getApiRouteInstance("apiTest-ns", "v1", "host", "20081", "ip"); - - Assert.assertNotNull(apiRouteInfo); - Assert.assertEquals("1", apiRouteInfo.getStatus()); - - routeInstance.noticeUpdateStatusListener(buildMicroServiceFullInfo4API(),"0"); - apiRouteInfo=apiRouteServiceWrapper.getApiRouteInstance("apiTest-ns", "v1", "host", "20081", "ip"); - Assert.assertEquals("0", apiRouteInfo.getStatus()); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + private static RouteNotify routeInstance; + private static ApiRouteServiceWrapper apiRouteServiceWrapper; + private static IuiRouteServiceWrapper iuiRouteServiceWrapper; + private static CustomRouteServiceWrapper customRouteServiceWrapper; + + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + InitRouteServiceWrapper.getInstance().registerServiceChangeListener(); + routeInstance = RouteNotify.getInstance(); + apiRouteServiceWrapper = ApiRouteServiceWrapper.getInstance(); + iuiRouteServiceWrapper = IuiRouteServiceWrapper.getInstance(); + customRouteServiceWrapper = CustomRouteServiceWrapper.getInstance(); + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + ConfigUtil.getInstance().initRouteWay(); + } + + @Before + public void initReidsMock() throws Exception { + final JedisPool mockJedisPool = new MockJedisPool(new JedisPoolConfig(), "localhost"); + PowerMockito.mockStatic(JedisUtil.class); + JedisUtil jedisUtil = PowerMockito.mock(JedisUtil.class); + PowerMockito.when(jedisUtil.borrowJedisInstance()).thenReturn(mockJedisPool.getResource()); + + PowerMockito.replace(PowerMockito.method(RedisAccessWrapper.class, "filterKeys")).with(new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return mockJedisPool.getResource().keys((String) args[0]); + } + }); + } + + @Test + public void test_noticeRouteListener4Update_api() { + try { + routeInstance.noticeRouteListener4Update("apiTest-ns", "v1", buildMicroServiceFullInfo4API()); + ApiRouteInfo apiRouteInfo = + apiRouteServiceWrapper.getApiRouteInstance("apiTest-ns", "v1", "host", "20081", "ip"); + + Assert.assertNotNull(apiRouteInfo); + Assert.assertEquals("1", apiRouteInfo.getStatus()); + + routeInstance.noticeUpdateStatusListener(buildMicroServiceFullInfo4API(), "0"); + apiRouteInfo = apiRouteServiceWrapper.getApiRouteInstance("apiTest-ns", "v1", "host", "20081", "ip"); + Assert.assertEquals("0", apiRouteInfo.getStatus()); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } + + @Test + public void test_noticeRouteListener4Update_iui() { + try { + routeInstance.noticeRouteListener4Update("iuiTest-ns", "v1", buildMicroServiceFullInfo4IUI()); + IuiRouteInfo iuiRouteInfo = iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest-ns", "host", "20081", "ip"); + + Assert.assertNotNull(iuiRouteInfo); + Assert.assertEquals("1", iuiRouteInfo.getStatus()); + + routeInstance.noticeUpdateStatusListener(buildMicroServiceFullInfo4IUI(), "0"); + iuiRouteInfo = iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest-ns", "host", "20081", "ip"); + Assert.assertEquals("0", iuiRouteInfo.getStatus()); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } + + @Test + public void test_noticeRouteListener4Update_http() { + try { + routeInstance.noticeRouteListener4Update("httpTest-ns", "v1", buildMicroServiceFullInfo4HTTP()); + CustomRouteInfo customRouteInfo = + customRouteServiceWrapper.getCustomRouteInstance("/httpTest-ns", "host", "20081", "ip"); + Assert.assertNotNull(customRouteInfo); + Assert.assertEquals("1", customRouteInfo.getStatus()); + + routeInstance.noticeUpdateStatusListener(buildMicroServiceFullInfo4HTTP(), "0"); + customRouteInfo = customRouteServiceWrapper.getCustomRouteInstance("/httpTest-ns", "host", "20081", "ip"); + Assert.assertEquals("0", customRouteInfo.getStatus()); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } + + @Test + public void test_noticeRouteListener4Add_del_api() { + try { + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4API(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "20081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "apitest-ns", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "20081", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "apitest-ns", "", "domain"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + + } + + @Test + public void test_noticeRouteListener4Add_del_api_path() { + try { + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4API_path(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10081", "ip")); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10082", "ip")); + Assert.assertNotNull( + apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "host", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10081", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10082", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "host", "", "domain"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + @Test + public void test_noticeRouteListener4Add_del_api_mutiPort() { + try { + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4API_path(); + microServiceInfo.setPath(""); + microServiceInfo.setHost(""); + + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10081", "ip")); + Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10082", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "apitest", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10081", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10082", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "apitest", "", "domain"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + @Test + public void test_noticeRouteListener4Add_del_iui() { + try { + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4IUI(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "20081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "iuitest-ns", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "20081", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "iuitest-ns", "", "domain"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + } + + @Test + public void test_noticeRouteListener4Add_del_iui_path() { + try { + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4IUI_path(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10081", "ip")); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10082", "ip")); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "host", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10081", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10082", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "host", "", "domain"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + } - } - - @Test - public void test_noticeRouteListener4Update_iui(){ - try { - routeInstance.noticeRouteListener4Update("iuiTest-ns", "v1", buildMicroServiceFullInfo4IUI()); - IuiRouteInfo iuiRouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest-ns", "host", "20081", "ip"); - - Assert.assertNotNull(iuiRouteInfo); - Assert.assertEquals("1", iuiRouteInfo.getStatus()); - - routeInstance.noticeUpdateStatusListener(buildMicroServiceFullInfo4IUI(),"0"); - iuiRouteInfo=iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest-ns", "host", "20081", "ip"); - Assert.assertEquals("0", iuiRouteInfo.getStatus()); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + + @Test + public void test_noticeRouteListener4Add_del_iui_mutiPort() { + try { + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4IUI_path(); + microServiceInfo.setPath(""); + microServiceInfo.setHost(""); + + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10081", "ip")); + Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10082", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "iuitest", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10081", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10082", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/", "iuitest", "", "domain"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + } - } - - @Test - public void test_noticeRouteListener4Update_http(){ - try { - routeInstance.noticeRouteListener4Update("httpTest-ns", "v1", buildMicroServiceFullInfo4HTTP()); - CustomRouteInfo customRouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/httpTest-ns", "host", "20081", "ip"); - Assert.assertNotNull(customRouteInfo); - Assert.assertEquals("1", customRouteInfo.getStatus()); - - routeInstance.noticeUpdateStatusListener(buildMicroServiceFullInfo4HTTP(),"0"); - customRouteInfo=customRouteServiceWrapper.getCustomRouteInstance("/httpTest-ns", "host", "20081", "ip"); - Assert.assertEquals("0", customRouteInfo.getStatus()); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + @Test + public void test_noticeRouteListener4Add_del_http() { + try { + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4HTTP(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "20081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "httptest-ns", "", + "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "20081", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest", "httptest-ns", "", "domain"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + } - } - - @Test - public void test_noticeRouteListener4Add_del_api(){ - try { - MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4API(); - routeInstance.noticeRouteListener4Add(microServiceInfo); - Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "20081", "ip")); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "apitest-ns", "", "domain")); - - routeInstance.noticeRouteListener4Delete(microServiceInfo); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + @Test + public void test_noticeRouteListener4Add_del_http_path() { + try { + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4HTTP_path(); + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10082", "ip")); + Assert.assertNotNull( + customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "host", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10081", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10082", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "host", "", "domain"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + } - - try { - apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "20081", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "apitest-ns", "", "domain"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - - } - - @Test - public void test_noticeRouteListener4Add_del_api_path(){ - try { - MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4API_path(); - routeInstance.noticeRouteListener4Add(microServiceInfo); - Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10081", "ip")); - Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10082", "ip")); - Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "host", "", "domain")); - - routeInstance.noticeRouteListener4Delete(microServiceInfo); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + + @Test + public void test_noticeRouteListener4Add_del_http_mutiPort() { + try { + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4HTTP_path(); + microServiceInfo.setPath(""); + microServiceInfo.setHost(""); + + routeInstance.noticeRouteListener4Add(microServiceInfo); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10081", "ip")); + Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10082", "ip")); + Assert.assertNotNull( + customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "httptest", "", "domain")); + + routeInstance.noticeRouteListener4Delete(microServiceInfo); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10081", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10082", "ip"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + + try { + customRouteServiceWrapper.getCustomRouteInstance("/httpTest", "httptest", "", "domain"); + Assert.fail("should not process to here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof ExtendedNotFoundException); + } + } - - try { - apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10081", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "", "10082", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - apiRouteServiceWrapper.getApiRouteInstance("apiTest4Path", "v1", "host", "", "domain"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - } - - @Test - public void test_noticeRouteListener4Add_del_api_mutiPort(){ - try { - MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4API_path(); - microServiceInfo.setPath(""); - microServiceInfo.setHost(""); - - routeInstance.noticeRouteListener4Add(microServiceInfo); - Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10081", "ip")); - Assert.assertNotNull(apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10082", "ip")); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "apitest", "", "domain")); - - routeInstance.noticeRouteListener4Delete(microServiceInfo); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + + @Test + public void test_noticeRouteListener4Add_portal() { + try { + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn("127.0.0.1"); + ApiRouteAppConfig configuration = new ApiRouteAppConfig(); + + DiscoverInfo discoverInfo = new DiscoverInfo(); + discoverInfo.setEnabled(true); + discoverInfo.setIp("127.0.0.2"); + discoverInfo.setPort(10081); + configuration.setDiscoverInfo(discoverInfo); + ConfigUtil.getInstance().initDiscoverInfo(configuration); + + + PowerMockito.mockStatic(HttpClientUtil.class); + String publishUrl = + "http://127.0.0.1:10081/api/microservices/v1/services/portalTest/version/v1/allpublishaddress?namespace=&visualRange=0"; + String resultJson = + "[{\"domain\":\"opapi.openpalette.zte.com.cn\",\"port\":\"443\",\"publish_url\":\"/api\",\"visualRange\":\"0\",\"publish_protocol\":\"https\"},{\"ip\":\"10.74.165.246\",\"port\":\"443\",\"publish_url\":\"/opapi\",\"visualRange\":\"0\",\"publish_protocol\":\"https\"},{\"ip\":\"10.74.165.246\",\"port\":\"80\",\"publish_url\":\"/opapi\",\"visualRange\":\"0\",\"publish_protocol\":\"http\"}]"; + PowerMockito.when(HttpClientUtil.httpGet(publishUrl)).thenReturn(resultJson); + + MicroServiceFullInfo microServiceInfo = buildMicroServiceFullInfo4PORTAL(); + + routeInstance.noticeRouteListener4Add(microServiceInfo); + + CustomRouteInfo routeInfo_ip = + customRouteServiceWrapper.getCustomRouteInstance("/portalTest/v1", "", "10088", "ip"); + RouteServer[] servers_ip = new RouteServer[] {new RouteServer("10.74.148.99", "8080")}; + Assert.assertArrayEquals(servers_ip, routeInfo_ip.getServers()); + + CustomRouteInfo routeInfo_domain = + customRouteServiceWrapper.getCustomRouteInstance("/portalTest/v1", "host", "", "domain"); + RouteServer[] servers_domain = new RouteServer[] {new RouteServer("10.74.165.246", "443")}; + + Assert.assertArrayEquals(servers_domain, routeInfo_domain.getServers()); + + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + } + } - - try { - apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10081", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "", "10082", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - apiRouteServiceWrapper.getApiRouteInstance("apiTest", "v1", "apitest", "", "domain"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - } - - @Test - public void test_noticeRouteListener4Add_del_iui(){ - try { - MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4IUI(); - routeInstance.noticeRouteListener4Add(microServiceInfo); - Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "20081", "ip")); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "iuitest-ns", "", "domain")); - - routeInstance.noticeRouteListener4Delete(microServiceInfo); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + + private MicroServiceFullInfo buildMicroServiceFullInfo4API() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("apiTest-ns"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(false); + microServiceInfo.setPublish_port("20081"); + microServiceInfo.setProtocol("REST"); + microServiceInfo.setUrl("/api/apiTest/v1"); + microServiceInfo.setVisualRange("1"); + microServiceInfo.setStatus("1"); + microServiceInfo.setNamespace("ns"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88", "8080")); + nodes.add(new Node("10.74.148.89", "8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; } - - try { - iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "20081", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "iuitest-ns", "", "domain"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - } - - @Test - public void test_noticeRouteListener4Add_del_iui_path(){ - try { - MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4IUI_path(); - routeInstance.noticeRouteListener4Add(microServiceInfo); - Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10081", "ip")); - Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10082", "ip")); - Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "host", "", "domain")); - - routeInstance.noticeRouteListener4Delete(microServiceInfo); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + private MicroServiceFullInfo buildMicroServiceFullInfo4API_path() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("apiTest"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(true); + microServiceInfo.setHost("host"); + microServiceInfo.setPath("/api/apiTest4Path/v1"); + microServiceInfo.setPublish_port("10081|10082"); + microServiceInfo.setProtocol("REST"); + microServiceInfo.setUrl("/api/apiTest/v1"); + microServiceInfo.setVisualRange("0"); + microServiceInfo.setLb_policy("ip_hash"); + microServiceInfo.setStatus("1"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88", "8080")); + nodes.add(new Node("10.74.148.89", "8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; } - - try { - iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10081", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "", "10082", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest4Path", "host", "", "domain"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - } - - - @Test - public void test_noticeRouteListener4Add_del_iui_mutiPort(){ - try { - MicroServiceFullInfo microServiceInfo =buildMicroServiceFullInfo4IUI_path(); - microServiceInfo.setPath(""); - microServiceInfo.setHost(""); - - routeInstance.noticeRouteListener4Add(microServiceInfo); - Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10081", "ip")); - Assert.assertNotNull(iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10082", "ip")); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/", "iuitest", "", "domain")); - - routeInstance.noticeRouteListener4Delete(microServiceInfo); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + + private MicroServiceFullInfo buildMicroServiceFullInfo4PORTAL() { + + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("portalTest"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(true); + microServiceInfo.setHost("host"); + microServiceInfo.setPublish_port("10088"); + microServiceInfo.setProtocol("HTTP"); + microServiceInfo.setUrl("/portalTestUrl/v1"); + microServiceInfo.setVisualRange("0"); + microServiceInfo.setLb_policy("ip_hash"); + microServiceInfo.setStatus("1"); + microServiceInfo.setCustom(RouteUtil.CUSTOM_PORTAL); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.99", "8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; } - - try { - iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10081", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - iuiRouteServiceWrapper.getIuiRouteInstance("iuiTest", "", "10082", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - customRouteServiceWrapper.getCustomRouteInstance("/", "iuitest", "", "domain"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - } - - @Test - public void test_noticeRouteListener4Add_del_http(){ - try { - MicroServiceFullInfo microServiceInfo=buildMicroServiceFullInfo4HTTP(); - routeInstance.noticeRouteListener4Add(microServiceInfo); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "20081", "ip")); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "httptest-ns", "", "domain")); - - routeInstance.noticeRouteListener4Delete(microServiceInfo); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + private MicroServiceFullInfo buildMicroServiceFullInfo4IUI() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("iuiTest-ns"); + microServiceInfo.setNamespace("ns"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(false); + microServiceInfo.setPublish_port("20081"); + microServiceInfo.setProtocol("UI"); + microServiceInfo.setUrl("/iui/iuiTest"); + microServiceInfo.setVisualRange("1"); + microServiceInfo.setStatus("1"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88", "8080")); + nodes.add(new Node("10.74.148.89", "8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; } - - try { - customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "20081", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - customRouteServiceWrapper.getCustomRouteInstance("/httpTest", "httptest-ns", "", "domain"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - } - - @Test - public void test_noticeRouteListener4Add_del_http_path(){ - try { - MicroServiceFullInfo microServiceInfo=buildMicroServiceFullInfo4HTTP_path(); - routeInstance.noticeRouteListener4Add(microServiceInfo); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10081", "ip")); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10082", "ip")); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "host", "", "domain")); - - routeInstance.noticeRouteListener4Delete(microServiceInfo); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + private MicroServiceFullInfo buildMicroServiceFullInfo4IUI_path() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("iuiTest"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(true); + microServiceInfo.setHost("host"); + microServiceInfo.setProtocol("UI"); + microServiceInfo.setUrl("/iui/iuiTest"); + microServiceInfo.setLb_policy("ip_hash"); + microServiceInfo.setPublish_port("10081|10082"); + microServiceInfo.setPath("/iui/iuiTest4Path"); + microServiceInfo.setVisualRange("0"); + microServiceInfo.setStatus("1"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88", "8080")); + nodes.add(new Node("10.74.148.89", "8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; } - - try { - customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10081", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "", "10082", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - customRouteServiceWrapper.getCustomRouteInstance("/httpTest4Path", "host", "", "domain"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - } - - - @Test - public void test_noticeRouteListener4Add_del_http_mutiPort(){ - try { - MicroServiceFullInfo microServiceInfo=buildMicroServiceFullInfo4HTTP_path(); - microServiceInfo.setPath(""); - microServiceInfo.setHost(""); - - routeInstance.noticeRouteListener4Add(microServiceInfo); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10081", "ip")); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10082", "ip")); - Assert.assertNotNull(customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "httptest", "", "domain")); - - routeInstance.noticeRouteListener4Delete(microServiceInfo); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + private MicroServiceFullInfo buildMicroServiceFullInfo4HTTP() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("httpTest-ns"); + microServiceInfo.setNamespace("ns"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(false); + microServiceInfo.setPublish_port("20081"); + microServiceInfo.setProtocol("HTTP"); + microServiceInfo.setUrl("/httpTest"); + microServiceInfo.setVisualRange("1"); + microServiceInfo.setStatus("1"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88", "8080")); + nodes.add(new Node("10.74.148.89", "8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; } - - try { - customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10081", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - customRouteServiceWrapper.getCustomRouteInstance("/httpTest/v1", "", "10082", "ip"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - try { - customRouteServiceWrapper.getCustomRouteInstance("/httpTest", "httptest", "", "domain"); - Assert.fail("should not process to here."); - } - catch(Exception e){ - Assert.assertTrue(e instanceof ExtendedNotFoundException); - } - - } - - - @Test - public void test_noticeRouteListener4Add_portal(){ - try { - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn("127.0.0.1"); - ApiRouteAppConfig configuration=new ApiRouteAppConfig(); - - DiscoverInfo discoverInfo=new DiscoverInfo(); - discoverInfo.setEnabled(true); - discoverInfo.setIp("127.0.0.2"); - discoverInfo.setPort(10081); - configuration.setDiscoverInfo(discoverInfo); - ConfigUtil.getInstance().initDiscoverInfo(configuration); - - - PowerMockito.mockStatic(HttpClientUtil.class); - String publishUrl="http://127.0.0.1:10081/api/microservices/v1/services/portalTest/version/v1/allpublishaddress?namespace=&visualRange=0"; - String resultJson ="[{\"domain\":\"opapi.openpalette.zte.com.cn\",\"port\":\"443\",\"publish_url\":\"/api\",\"visualRange\":\"0\",\"publish_protocol\":\"https\"},{\"ip\":\"10.74.165.246\",\"port\":\"443\",\"publish_url\":\"/opapi\",\"visualRange\":\"0\",\"publish_protocol\":\"https\"},{\"ip\":\"10.74.165.246\",\"port\":\"80\",\"publish_url\":\"/opapi\",\"visualRange\":\"0\",\"publish_protocol\":\"http\"}]"; - PowerMockito.when(HttpClientUtil.httpGet(publishUrl)).thenReturn(resultJson); - - MicroServiceFullInfo microServiceInfo=buildMicroServiceFullInfo4PORTAL(); - - routeInstance.noticeRouteListener4Add(microServiceInfo); - - CustomRouteInfo routeInfo_ip=customRouteServiceWrapper.getCustomRouteInstance("/portalTest/v1", "", "10088", "ip"); - RouteServer[] servers_ip = new RouteServer[]{new RouteServer("10.74.148.99","8080")}; - Assert.assertArrayEquals(servers_ip, routeInfo_ip.getServers()); - - CustomRouteInfo routeInfo_domain=customRouteServiceWrapper.getCustomRouteInstance("/portalTest/v1", "host", "", "domain"); - RouteServer[] servers_domain = new RouteServer[]{new RouteServer("10.74.165.246","443")}; - - Assert.assertArrayEquals(servers_domain, routeInfo_domain.getServers()); - - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + + private MicroServiceFullInfo buildMicroServiceFullInfo4HTTP_path() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("httpTest"); + microServiceInfo.setVersion("v1"); + microServiceInfo.setEnable_ssl(true); + microServiceInfo.setHost("host"); + microServiceInfo.setPublish_port("20081"); + microServiceInfo.setProtocol("HTTP"); + microServiceInfo.setUrl("/httpTest"); + microServiceInfo.setVisualRange("0"); + microServiceInfo.setStatus("1"); + microServiceInfo.setLb_policy("ip_hash"); + microServiceInfo.setPublish_port("10081|10082"); + microServiceInfo.setPath("/httpTest4Path"); + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.148.88", "8080")); + nodes.add(new Node("10.74.148.89", "8080")); + microServiceInfo.setNodes(nodes); + + return microServiceInfo; } - - } - - - private MicroServiceFullInfo buildMicroServiceFullInfo4API(){ - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("apiTest-ns"); - microServiceInfo.setVersion("v1"); - microServiceInfo.setEnable_ssl(false); - microServiceInfo.setPublish_port("20081"); - microServiceInfo.setProtocol("REST"); - microServiceInfo.setUrl("/api/apiTest/v1"); - microServiceInfo.setVisualRange("1"); - microServiceInfo.setStatus("1"); - microServiceInfo.setNamespace("ns"); - Set<Node> nodes = new HashSet<Node>(); - nodes.add(new Node("10.74.148.88","8080")); - nodes.add(new Node("10.74.148.89","8080")); - microServiceInfo.setNodes(nodes); - - return microServiceInfo; - } - - private MicroServiceFullInfo buildMicroServiceFullInfo4API_path(){ - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("apiTest"); - microServiceInfo.setVersion("v1"); - microServiceInfo.setEnable_ssl(true); - microServiceInfo.setHost("host"); - microServiceInfo.setPath("/api/apiTest4Path/v1"); - microServiceInfo.setPublish_port("10081|10082"); - microServiceInfo.setProtocol("REST"); - microServiceInfo.setUrl("/api/apiTest/v1"); - microServiceInfo.setVisualRange("0"); - microServiceInfo.setLb_policy("ip_hash"); - microServiceInfo.setStatus("1"); - Set<Node> nodes = new HashSet<Node>(); - nodes.add(new Node("10.74.148.88","8080")); - nodes.add(new Node("10.74.148.89","8080")); - microServiceInfo.setNodes(nodes); - - return microServiceInfo; - } - - - private MicroServiceFullInfo buildMicroServiceFullInfo4PORTAL(){ - - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("portalTest"); - microServiceInfo.setVersion("v1"); - microServiceInfo.setEnable_ssl(true); - microServiceInfo.setHost("host"); - microServiceInfo.setPublish_port("10088"); - microServiceInfo.setProtocol("HTTP"); - microServiceInfo.setUrl("/portalTestUrl/v1"); - microServiceInfo.setVisualRange("0"); - microServiceInfo.setLb_policy("ip_hash"); - microServiceInfo.setStatus("1"); - microServiceInfo.setCustom(RouteUtil.CUSTOM_PORTAL); - Set<Node> nodes = new HashSet<Node>(); - nodes.add(new Node("10.74.148.99","8080")); - microServiceInfo.setNodes(nodes); - - return microServiceInfo; - } - - private MicroServiceFullInfo buildMicroServiceFullInfo4IUI(){ - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("iuiTest-ns"); - microServiceInfo.setNamespace("ns"); - microServiceInfo.setVersion("v1"); - microServiceInfo.setEnable_ssl(false); - microServiceInfo.setPublish_port("20081"); - microServiceInfo.setProtocol("UI"); - microServiceInfo.setUrl("/iui/iuiTest"); - microServiceInfo.setVisualRange("1"); - microServiceInfo.setStatus("1"); - Set<Node> nodes = new HashSet<Node>(); - nodes.add(new Node("10.74.148.88","8080")); - nodes.add(new Node("10.74.148.89","8080")); - microServiceInfo.setNodes(nodes); - - return microServiceInfo; - } - - private MicroServiceFullInfo buildMicroServiceFullInfo4IUI_path(){ - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("iuiTest"); - microServiceInfo.setVersion("v1"); - microServiceInfo.setEnable_ssl(true); - microServiceInfo.setHost("host"); - microServiceInfo.setProtocol("UI"); - microServiceInfo.setUrl("/iui/iuiTest"); - microServiceInfo.setLb_policy("ip_hash"); - microServiceInfo.setPublish_port("10081|10082"); - microServiceInfo.setPath("/iui/iuiTest4Path"); - microServiceInfo.setVisualRange("0"); - microServiceInfo.setStatus("1"); - Set<Node> nodes = new HashSet<Node>(); - nodes.add(new Node("10.74.148.88","8080")); - nodes.add(new Node("10.74.148.89","8080")); - microServiceInfo.setNodes(nodes); - - return microServiceInfo; - } - - private MicroServiceFullInfo buildMicroServiceFullInfo4HTTP(){ - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("httpTest-ns"); - microServiceInfo.setNamespace("ns"); - microServiceInfo.setVersion("v1"); - microServiceInfo.setEnable_ssl(false); - microServiceInfo.setPublish_port("20081"); - microServiceInfo.setProtocol("HTTP"); - microServiceInfo.setUrl("/httpTest"); - microServiceInfo.setVisualRange("1"); - microServiceInfo.setStatus("1"); - Set<Node> nodes = new HashSet<Node>(); - nodes.add(new Node("10.74.148.88","8080")); - nodes.add(new Node("10.74.148.89","8080")); - microServiceInfo.setNodes(nodes); - - return microServiceInfo; - } - - private MicroServiceFullInfo buildMicroServiceFullInfo4HTTP_path(){ - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("httpTest"); - microServiceInfo.setVersion("v1"); - microServiceInfo.setEnable_ssl(true); - microServiceInfo.setHost("host"); - microServiceInfo.setPublish_port("20081"); - microServiceInfo.setProtocol("HTTP"); - microServiceInfo.setUrl("/httpTest"); - microServiceInfo.setVisualRange("0"); - microServiceInfo.setStatus("1"); - microServiceInfo.setLb_policy("ip_hash"); - microServiceInfo.setPublish_port("10081|10082"); - microServiceInfo.setPath("/httpTest4Path"); - Set<Node> nodes = new HashSet<Node>(); - nodes.add(new Node("10.74.148.88","8080")); - nodes.add(new Node("10.74.148.89","8080")); - microServiceInfo.setNodes(nodes); - - return microServiceInfo; - } - - + + } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/CommonUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/CommonUtilTest.java index 07f2b86..6a3bfb7 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/CommonUtilTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/CommonUtilTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -20,57 +18,56 @@ import java.util.Set; import org.junit.Assert; import org.junit.Test; -import org.onap.msb.apiroute.wrapper.util.CommonUtil; public class CommonUtilTest { - - @Test - public void test_concat() { - Object[] str1 = new String[] {"test1", "test2"}; - Object[] str2 = new String[] {"test3"}; - Object[] str3 = CommonUtil.concat(str1, str2); - Assert.assertEquals(3, str3.length); - } + @Test + public void test_concat() { + Object[] str1 = new String[] {"test1", "test2"}; + Object[] str2 = new String[] {"test3"}; + Object[] str3 = CommonUtil.concat(str1, str2); - @Test - public void test_containStr() { - String value = "1"; - String array[] = {"1", "2"}; - Assert.assertTrue(CommonUtil.contain(array, value)); - Assert.assertFalse(CommonUtil.contain(array, "3")); - } + Assert.assertEquals(3, str3.length); + } - @Test - public void test_containArray() { - String value[] = {"0"}; - String array[] = {"1", "2"}; - String array2[] = {"2", "1"}; - Assert.assertFalse(CommonUtil.contain(array, value)); - Assert.assertTrue(CommonUtil.contain(array, array2)); - } + @Test + public void test_containStr() { + String value = "1"; + String array[] = {"1", "2"}; + Assert.assertTrue(CommonUtil.contain(array, value)); + Assert.assertFalse(CommonUtil.contain(array, "3")); + } - @Test - public void test_containStrArray() { - Assert.assertFalse(CommonUtil.contain("0,1,2", "3")); - Assert.assertTrue(CommonUtil.contain("0,1,2", "1")); - } + @Test + public void test_containArray() { + String value[] = {"0"}; + String array[] = {"1", "2"}; + String array2[] = {"2", "1"}; + Assert.assertFalse(CommonUtil.contain(array, value)); + Assert.assertTrue(CommonUtil.contain(array, array2)); + } - @Test - public void test_getDiffrent() { - Set<String> list1 = new HashSet<String>(); - list1.add("test1"); - list1.add("test2"); + @Test + public void test_containStrArray() { + Assert.assertFalse(CommonUtil.contain("0,1,2", "3")); + Assert.assertTrue(CommonUtil.contain("0,1,2", "1")); + } - Set<String> list2 = new HashSet<String>(); - list2.add("test2"); - list2.add("test3"); + @Test + public void test_getDiffrent() { + Set<String> list1 = new HashSet<String>(); + list1.add("test1"); + list1.add("test2"); - Set<String> diff = CommonUtil.getDiffrent(list1, list2); - Assert.assertEquals(1, diff.size()); - Assert.assertTrue(diff.contains("test3")); - } + Set<String> list2 = new HashSet<String>(); + list2.add("test2"); + list2.add("test3"); + + Set<String> diff = CommonUtil.getDiffrent(list1, list2); + Assert.assertEquals(1, diff.size()); + Assert.assertTrue(diff.contains("test3")); + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ConfigUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ConfigUtilTest.java index c32b6c0..51a06df 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ConfigUtilTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ConfigUtilTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -24,7 +22,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.onap.msb.apiroute.ApiRouteAppConfig; import org.onap.msb.apiroute.api.DiscoverInfo; -import org.onap.msb.apiroute.wrapper.util.ConfigUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -33,197 +30,196 @@ import org.powermock.modules.junit4.PowerMockRunner; @PrepareForTest({ConfigUtil.class}) public class ConfigUtilTest { - @Test - public void test_initRootPath() { - try { - ConfigUtil.getInstance().initRootPath(); - String iuiRootPath = ConfigUtil.getInstance().getIUI_ROOT_PATH(); - String apiRootPath = ConfigUtil.getInstance().getAPI_ROOT_PATH(); - Assert.assertEquals("iui", iuiRootPath); - Assert.assertEquals("api", apiRootPath); - } catch (Exception e) { - Assert.fail("throw exception means error occured!" + e.getMessage()); + @Test + public void test_initRootPath() { + try { + ConfigUtil.getInstance().initRootPath(); + String iuiRootPath = ConfigUtil.getInstance().getIUI_ROOT_PATH(); + String apiRootPath = ConfigUtil.getInstance().getAPI_ROOT_PATH(); + Assert.assertEquals("iui", iuiRootPath); + Assert.assertEquals("api", apiRootPath); + } catch (Exception e) { + Assert.fail("throw exception means error occured!" + e.getMessage()); + + } + + } + + @Test + public void test_initApiGatewayPort() { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("APIGATEWAY_EXPOSE_PORT")).thenReturn(null); + ConfigUtil.getInstance().initApiGatewayPort(); + Assert.assertEquals("80", ConfigUtil.getInstance().getServerPort()); + + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("APIGATEWAY_EXPOSE_PORT")).thenReturn("81"); + + ConfigUtil.getInstance().initApiGatewayPort(); + Assert.assertEquals("81", ConfigUtil.getInstance().getServerPort()); + } + + @Test + public void test_initRouteNameSpaceMatches() { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("APIGATEWAY_EXPOSE_PORT")).thenReturn(null); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertEquals("all", ConfigUtil.getInstance().getNamespaceMatches()); + + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("net"); + + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertEquals("net", ConfigUtil.getInstance().getNamespaceMatches()); + } + + @Test + public void test_initRouteLabelsMatches() { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn(null); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertEquals("0", ConfigUtil.getInstance().getVisualRangeMatches()); + Assert.assertEquals("net", ConfigUtil.getInstance().getNetwork_plane_typeMatches()); + Assert.assertTrue(ConfigUtil.getInstance().getLabelMapMatches().containsKey("custom-key")); + + + + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("visualRange:1,network_plane_type:net,custom:test"); + + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertEquals("1", ConfigUtil.getInstance().getVisualRangeMatches()); + Assert.assertEquals("net", ConfigUtil.getInstance().getNetwork_plane_typeMatches()); + Assert.assertTrue(ConfigUtil.getInstance().getLabelMapMatches().containsKey("custom")); + + } + + @Test + public void test_initRouteWay() { + PowerMockito.mockStatic(System.class); + + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); + ConfigUtil.getInstance().initRouteWay(); + String[] ip_routeWay = {"ip"}; + Assert.assertArrayEquals(ip_routeWay, ConfigUtil.getInstance().getRouteWay()); + + PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); + + ConfigUtil.getInstance().initRouteWay(); + String[] routeWay = {"ip", "domain"}; + Assert.assertArrayEquals(routeWay, ConfigUtil.getInstance().getRouteWay()); + } + + @Test + public void test_initDiscoverInfo() { + PowerMockito.mockStatic(System.class); + + + ApiRouteAppConfig configuration = new ApiRouteAppConfig(); + + DiscoverInfo discoverInfo = new DiscoverInfo(); + discoverInfo.setEnabled(true); + discoverInfo.setIp("127.0.0.1"); + discoverInfo.setPort(10081); + + configuration.setDiscoverInfo(discoverInfo); + PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn(null); + ConfigUtil.getInstance().initDiscoverInfo(configuration); + Assert.assertEquals("127.0.0.1:10081", ConfigUtil.getInstance().getDiscoverInfo().toString()); + + PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn("10.74.44.86"); + ConfigUtil.getInstance().initDiscoverInfo(configuration); + Assert.assertEquals("10.74.44.86:10081", ConfigUtil.getInstance().getDiscoverInfo().toString()); + } + + @Test + public void test_initNodeMeta() { + + // CONSUL_REGISTER_MODE not catalog + ConfigUtil util = ConfigUtil.getInstance(); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), ""); + + // CONSUL_REGISTER_MODE catalog + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_REGISTER_MODE")).thenReturn("agnet"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), ""); + + + // CONSUL_REGISTER_MODE catalog + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("CONSUL_REGISTER_MODE")).thenReturn("catalog"); + try { + Field visualRangeField = util.getClass().getDeclaredField("visualRangeMatches"); + visualRangeField.setAccessible(true); + + Field namespaceField = util.getClass().getDeclaredField("namespaceMatches"); + namespaceField.setAccessible(true); + + // 0:default; + visualRangeField.set(util, "0"); + namespaceField.set(util, "default"); + + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), "node-meta=external:true&node-meta=ns:default"); + + // 1:default; + visualRangeField.set(util, "1"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), "node-meta=internal:true&node-meta=ns:default"); + + // 0|1:default + visualRangeField.set(util, "0|1"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), "node-meta=ns:default"); + + // 0|1:all + namespaceField.set(util, "all"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), ""); + + /////////////////////////////////////////////////////////////////////////// + // 1:all + visualRangeField.set(util, "1"); + namespaceField.set(util, "all"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), "node-meta=internal:true"); + + // 1:! + namespaceField.set(util, "!default"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), "node-meta=internal:true"); + + // 1:& + namespaceField.set(util, "tenant1&tenant2"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), "node-meta=internal:true"); + + // 1:| + namespaceField.set(util, "tenant1|tenant2"); + util.initNodeMetaQueryParam(); + System.out.println(util.getNodeMetaQueryParam()); + Assert.assertEquals(util.getNodeMetaQueryParam(), "node-meta=internal:true"); + + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } - } - - @Test - public void test_initApiGatewayPort() { - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("APIGATEWAY_EXPOSE_PORT")).thenReturn(null); - ConfigUtil.getInstance().initApiGatewayPort(); - Assert.assertEquals("80", ConfigUtil.getInstance().getServerPort()); - - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("APIGATEWAY_EXPOSE_PORT")).thenReturn("81"); - - ConfigUtil.getInstance().initApiGatewayPort(); - Assert.assertEquals("81", ConfigUtil.getInstance().getServerPort()); - } - - @Test - public void test_initRouteNameSpaceMatches() { - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("APIGATEWAY_EXPOSE_PORT")).thenReturn(null); - ConfigUtil.getInstance().initRouteNameSpaceMatches(); - Assert.assertEquals("all", ConfigUtil.getInstance().getNamespaceMatches()); - - - PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("net"); - - ConfigUtil.getInstance().initRouteNameSpaceMatches(); - Assert.assertEquals("net", ConfigUtil.getInstance().getNamespaceMatches()); - } - - @Test - public void test_initRouteLabelsMatches() { - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn(null); - ConfigUtil.getInstance().initRouteLabelsMatches(); - Assert.assertEquals("0", ConfigUtil.getInstance().getVisualRangeMatches()); - Assert.assertEquals("net", ConfigUtil.getInstance().getNetwork_plane_typeMatches()); - Assert.assertTrue(ConfigUtil.getInstance().getLabelMapMatches().containsKey("custom-key")); - - - - - PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("visualRange:1,network_plane_type:net,custom:test"); - - ConfigUtil.getInstance().initRouteLabelsMatches(); - Assert.assertEquals("1", ConfigUtil.getInstance().getVisualRangeMatches()); - Assert.assertEquals("net", ConfigUtil.getInstance().getNetwork_plane_typeMatches()); - Assert.assertTrue(ConfigUtil.getInstance().getLabelMapMatches().containsKey("custom")); - - } - - @Test - public void test_initRouteWay() { - PowerMockito.mockStatic(System.class); - - PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn(null); - ConfigUtil.getInstance().initRouteWay(); - String[] ip_routeWay={"ip"}; - Assert.assertArrayEquals(ip_routeWay, ConfigUtil.getInstance().getRouteWay()); - - PowerMockito.when(System.getenv("ROUTE_WAY")).thenReturn("ip|domain"); - - ConfigUtil.getInstance().initRouteWay(); - String[] routeWay={"ip","domain"}; - Assert.assertArrayEquals(routeWay, ConfigUtil.getInstance().getRouteWay()); - } - - @Test - public void test_initDiscoverInfo() { - PowerMockito.mockStatic(System.class); - - - ApiRouteAppConfig configuration=new ApiRouteAppConfig(); - - DiscoverInfo discoverInfo=new DiscoverInfo(); - discoverInfo.setEnabled(true); - discoverInfo.setIp("127.0.0.1"); - discoverInfo.setPort(10081); - - configuration.setDiscoverInfo(discoverInfo); - PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn(null); - ConfigUtil.getInstance().initDiscoverInfo(configuration); - Assert.assertEquals("127.0.0.1:10081", ConfigUtil.getInstance().getDiscoverInfo().toString()); - - PowerMockito.when(System.getenv("SDCLIENT_IP")).thenReturn("10.74.44.86"); - ConfigUtil.getInstance().initDiscoverInfo(configuration); - Assert.assertEquals("10.74.44.86:10081", ConfigUtil.getInstance().getDiscoverInfo().toString()); - } - - @Test - public void test_initNodeMeta() { - - //CONSUL_REGISTER_MODE not catalog - ConfigUtil util=ConfigUtil.getInstance(); - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),""); - - //CONSUL_REGISTER_MODE catalog - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("CONSUL_REGISTER_MODE")).thenReturn("agnet"); - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),""); - - - //CONSUL_REGISTER_MODE catalog - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("CONSUL_REGISTER_MODE")).thenReturn("catalog"); - try { - Field visualRangeField=util.getClass().getDeclaredField("visualRangeMatches"); - visualRangeField.setAccessible(true); - - Field namespaceField = util.getClass().getDeclaredField("namespaceMatches"); - namespaceField.setAccessible(true); - - //0:default; - visualRangeField.set(util, "0"); - namespaceField.set(util, "default"); - - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=external:true&node-meta=ns:default"); - - //1:default; - visualRangeField.set(util, "1"); - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true&node-meta=ns:default"); - - //0|1:default - visualRangeField.set(util, "0|1"); - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=ns:default"); - - //0|1:all - namespaceField.set(util, "all"); - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),""); - - /////////////////////////////////////////////////////////////////////////// - //1:all - visualRangeField.set(util, "1"); - namespaceField.set(util, "all"); - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true"); - - //1:! - namespaceField.set(util, "!default"); - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true"); - - //1:& - namespaceField.set(util, "tenant1&tenant2"); - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true"); - - //1:| - namespaceField.set(util, "tenant1|tenant2"); - util.initNodeMetaQueryParam(); - System.out.println(util.getNodeMetaQueryParam()); - Assert.assertEquals(util.getNodeMetaQueryParam(),"node-meta=internal:true"); - - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtilTest.java index 61c19ad..338ab48 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtilTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/HttpClientUtilTest.java @@ -1,44 +1,33 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; -import java.io.IOException; - -import org.junit.Assert; import org.junit.Test; -import org.onap.msb.apiroute.wrapper.util.HttpClientUtil; public class HttpClientUtilTest { - - private String testIp="http://10.74.151.26:8500"; - - @Test - public void test_httpGet() { - /*try { - int result = HttpClientUtil.httpGetStatus(testIp); - if(result==200){ - Assert.assertEquals("Consul Agent", HttpClientUtil.httpGet(testIp)); - } - else{ - Assert.assertEquals(500, result); - } - - } catch (Exception e) { - Assert.assertTrue(e instanceof IOException); - }*/ - } + private String testIp = "http://10.74.151.26:8500"; + + @Test + public void test_httpGet() { + /* + * try { int result = HttpClientUtil.httpGetStatus(testIp); if(result==200){ + * Assert.assertEquals("Consul Agent", HttpClientUtil.httpGet(testIp)); } else{ + * Assert.assertEquals(500, result); } + * + * + * } catch (Exception e) { Assert.assertTrue(e instanceof IOException); } + */ + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtilTest.java index cff0b42..baf8b2a 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtilTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JacksonJsonUtilTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -21,74 +19,72 @@ import org.junit.Assert; import org.junit.Test; import org.onap.msb.apiroute.api.PublishFullAddress; import org.onap.msb.apiroute.api.RouteServer; -import org.onap.msb.apiroute.wrapper.util.JacksonJsonUtil; import com.fasterxml.jackson.core.type.TypeReference; public class JacksonJsonUtilTest { @Test - public void testBeanToJson(){ - try{ - RouteServer server=new RouteServer("127.0.0.1","80"); - String json=JacksonJsonUtil.beanToJson(server); - Assert.assertEquals("{\"ip\":\"127.0.0.1\",\"port\":\"80\",\"weight\":0}",json); - } - catch(Exception e){ + public void testBeanToJson() { + try { + RouteServer server = new RouteServer("127.0.0.1", "80"); + String json = JacksonJsonUtil.beanToJson(server); + Assert.assertEquals("{\"ip\":\"127.0.0.1\",\"port\":\"80\",\"weight\":0}", json); + } catch (Exception e) { Assert.fail("Exception" + e.getMessage()); } } - + @Test - public void testJsonToBean(){ - try{ - String json="{\"ip\":\"127.0.0.1\",\"port\":\"80\",\"weight\":0}"; - RouteServer server=(RouteServer) JacksonJsonUtil.jsonToBean(json, RouteServer.class); - Assert.assertEquals("127.0.0.1",server.getIp()); - Assert.assertEquals("80",server.getPort()); - } - catch(Exception e){ + public void testJsonToBean() { + try { + String json = "{\"ip\":\"127.0.0.1\",\"port\":\"80\",\"weight\":0}"; + RouteServer server = (RouteServer) JacksonJsonUtil.jsonToBean(json, RouteServer.class); + Assert.assertEquals("127.0.0.1", server.getIp()); + Assert.assertEquals("80", server.getPort()); + } catch (Exception e) { Assert.fail("Exception" + e.getMessage()); } } - - -// @Test -// public void testJsonToBean_Fail(){ -// try{ -// String json="{\"ip\":\"127.0.0.1\",\"port\":\"80\",\"weight\":0"; -// RouteServer server=(RouteServer) JacksonJsonUtil.jsonToBean(json, RouteServer.class); -// } -// catch(Exception e){ -// Assert.assertEquals("class org.onap.msb.apiroute.api.RouteServer JsonTobean faild",e.getMessage()); -// } -// } - + + + // @Test + // public void testJsonToBean_Fail(){ + // try{ + // String json="{\"ip\":\"127.0.0.1\",\"port\":\"80\",\"weight\":0"; + // RouteServer server=(RouteServer) JacksonJsonUtil.jsonToBean(json, RouteServer.class); + // } + // catch(Exception e){ + // Assert.assertEquals("class org.onap.msb.apiroute.api.RouteServer JsonTobean + // faild",e.getMessage()); + // } + // } + @Test - public void testJsonToListBean(){ - try{ - String resultJson="[{\"domain\": \"wudith.openpalette.zte.com.cn\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}," - + "{\"ip\": \"10.74.165.246\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}]"; - List<PublishFullAddress> publishFullAddressList = - JacksonJsonUtil.jsonToListBean(resultJson, new TypeReference<List<PublishFullAddress>>() {}); - Assert.assertEquals(2,publishFullAddressList.size()); - Assert.assertEquals("80",publishFullAddressList.get(0).getPort()); - } - catch(Exception e){ - Assert.fail("Exception" + e.getMessage()); - } + public void testJsonToListBean() { + try { + String resultJson = + "[{\"domain\": \"wudith.openpalette.zte.com.cn\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}," + + "{\"ip\": \"10.74.165.246\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}]"; + List<PublishFullAddress> publishFullAddressList = JacksonJsonUtil.jsonToListBean(resultJson, + new TypeReference<List<PublishFullAddress>>() {}); + Assert.assertEquals(2, publishFullAddressList.size()); + Assert.assertEquals("80", publishFullAddressList.get(0).getPort()); + } catch (Exception e) { + Assert.fail("Exception" + e.getMessage()); + } } - + @Test - public void testJsonToListBean_Fail(){ - try{ - String resultJson="[\"domain\": \"wudith.openpalette.zte.com.cn\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}," - + "{\"ip\": \"10.74.165.246\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}]"; - List<PublishFullAddress> publishFullAddressList = - JacksonJsonUtil.jsonToListBean(resultJson, new TypeReference<List<PublishFullAddress>>() {}); - } - catch(Exception e){ - Assert.assertTrue(e instanceof Exception); - } + public void testJsonToListBean_Fail() { + try { + String resultJson = + "[\"domain\": \"wudith.openpalette.zte.com.cn\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}," + + "{\"ip\": \"10.74.165.246\",\"port\": \"80\",\"publish_url\": \"/api/wudith/v1\",\"visualRange\": \"0\",\"publish_protocol\": \"http\"}]"; + List<PublishFullAddress> publishFullAddressList = JacksonJsonUtil.jsonToListBean(resultJson, + new TypeReference<List<PublishFullAddress>>() {}); + } catch (Exception e) { + Assert.assertTrue(e instanceof Exception); + } } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JedisUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JedisUtilTest.java index 91fbe32..0004aad 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JedisUtilTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/JedisUtilTest.java @@ -1,35 +1,32 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; import org.junit.Assert; import org.junit.Test; -import org.onap.msb.apiroute.wrapper.util.JedisUtil; import redis.clients.jedis.exceptions.JedisConnectionException; public class JedisUtilTest { - @Test - public void test_initialPool() { - try { - JedisUtil.borrowJedisInstance(); - - } catch (Exception e) { - Assert.assertTrue(e instanceof JedisConnectionException); - + @Test + public void test_initialPool() { + try { + JedisUtil.borrowJedisInstance(); + + } catch (Exception e) { + Assert.assertTrue(e instanceof JedisConnectionException); + + } } - } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtilTest.java index bede4ff..2b622a4 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtilTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/MicroServiceUtilTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -20,41 +18,38 @@ import javax.servlet.http.HttpServletRequest; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -import org.onap.msb.apiroute.wrapper.util.MicroServiceUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import redis.clients.jedis.Jedis; - @RunWith(PowerMockRunner.class) @PrepareForTest({HttpServletRequest.class}) public class MicroServiceUtilTest { - @Test - public void test_getPrefixedKey(){ - Assert.assertEquals("discover:microservices:test:v1",MicroServiceUtil.getPrefixedKey("test","v1")); - } - - @Test - public void test_getServiceKey(){ - Assert.assertEquals("discover:microservices:test:v1",MicroServiceUtil.getServiceKey("test","v1")); - } - - @Test - public void test_getRealIp(){ - HttpServletRequest request=PowerMockito.mock(HttpServletRequest.class); - PowerMockito.when(request.getHeader("X-Forwarded-For")).thenReturn("127.0.0.1"); - Assert.assertEquals("127.0.0.1",MicroServiceUtil.getRealIp(request)); - - PowerMockito.when(request.getHeader("X-Forwarded-For")).thenReturn(""); - PowerMockito.when(request.getHeader("X-Real-IP")).thenReturn("127.0.0.2"); - Assert.assertEquals("127.0.0.2",MicroServiceUtil.getRealIp(request)); - - PowerMockito.when(request.getHeader("X-Forwarded-For")).thenReturn(""); - PowerMockito.when(request.getHeader("X-Real-IP")).thenReturn(""); - PowerMockito.when(request.getRemoteAddr()).thenReturn("127.0.0.3"); - Assert.assertEquals("127.0.0.3",MicroServiceUtil.getRealIp(request)); - - } + @Test + public void test_getPrefixedKey() { + Assert.assertEquals("discover:microservices:test:v1", MicroServiceUtil.getPrefixedKey("test", "v1")); + } + + @Test + public void test_getServiceKey() { + Assert.assertEquals("discover:microservices:test:v1", MicroServiceUtil.getServiceKey("test", "v1")); + } + + @Test + public void test_getRealIp() { + HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class); + PowerMockito.when(request.getHeader("X-Forwarded-For")).thenReturn("127.0.0.1"); + Assert.assertEquals("127.0.0.1", MicroServiceUtil.getRealIp(request)); + + PowerMockito.when(request.getHeader("X-Forwarded-For")).thenReturn(""); + PowerMockito.when(request.getHeader("X-Real-IP")).thenReturn("127.0.0.2"); + Assert.assertEquals("127.0.0.2", MicroServiceUtil.getRealIp(request)); + + PowerMockito.when(request.getHeader("X-Forwarded-For")).thenReturn(""); + PowerMockito.when(request.getHeader("X-Real-IP")).thenReturn(""); + PowerMockito.when(request.getRemoteAddr()).thenReturn("127.0.0.3"); + Assert.assertEquals("127.0.0.3", MicroServiceUtil.getRealIp(request)); + + } } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtilTest.java index 2d5c5c5..76a0c7d 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtilTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RegExpTestUtilTest.java @@ -1,96 +1,94 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; import org.junit.Assert; import org.junit.Test; -import org.onap.msb.apiroute.wrapper.util.RegExpTestUtil; public class RegExpTestUtilTest { @Test - public void test_HostRegExpTest(){ + public void test_HostRegExpTest() { Assert.assertTrue(RegExpTestUtil.hostRegExpTest("127.0.0.1:8080")); Assert.assertFalse(RegExpTestUtil.hostRegExpTest("0.0.0.1:89")); } - - - + + + @Test - public void test_IpRegExpTest(){ + public void test_IpRegExpTest() { Assert.assertTrue(RegExpTestUtil.ipRegExpTest("127.0.0.1")); Assert.assertFalse(RegExpTestUtil.ipRegExpTest("127.0.0.1.5")); } - - - + + + @Test - public void test_PortRegExpTest(){ - Assert.assertTrue(RegExpTestUtil.portRegExpTest("80")); + public void test_PortRegExpTest() { + Assert.assertTrue(RegExpTestUtil.portRegExpTest("80")); Assert.assertFalse(RegExpTestUtil.portRegExpTest("898989")); } - - + + @Test - public void test_VersionRegExpTest(){ + public void test_VersionRegExpTest() { Assert.assertTrue(RegExpTestUtil.versionRegExpTest("v1")); Assert.assertFalse(RegExpTestUtil.versionRegExpTest("23")); } - - - + + + @Test - public void test_urlRegExpTest(){ + public void test_urlRegExpTest() { Assert.assertTrue(RegExpTestUtil.urlRegExpTest("/test")); Assert.assertTrue(RegExpTestUtil.urlRegExpTest("/")); Assert.assertFalse(RegExpTestUtil.urlRegExpTest("test")); } - - + + @Test - public void test_apiRouteUrlRegExpTest(){ + public void test_apiRouteUrlRegExpTest() { Assert.assertTrue(RegExpTestUtil.apiRouteUrlRegExpTest("/api/test/v1")); Assert.assertFalse(RegExpTestUtil.apiRouteUrlRegExpTest("/test")); } - - - + + + @Test - public void test_iuiRouteUrlRegExpTest(){ + public void test_iuiRouteUrlRegExpTest() { Assert.assertTrue(RegExpTestUtil.iuiRouteUrlRegExpTest("/iui/test")); Assert.assertFalse(RegExpTestUtil.iuiRouteUrlRegExpTest("/test")); - } - + } + @Test - public void test_apiServiceNameMatch4URL(){ - String[] apiServiceNameArray={"testApiName","v1"}; - Assert.assertArrayEquals(apiServiceNameArray, RegExpTestUtil.apiServiceNameMatch4URL("/api/testApiName/v1")); - - String[] apiServiceNameArray_noversion={"testApiName",""}; - Assert.assertArrayEquals(apiServiceNameArray_noversion, RegExpTestUtil.apiServiceNameMatch4URL("/api/testApiName")); - - Assert.assertNull(RegExpTestUtil.apiServiceNameMatch4URL("/apiw/name/v1")); + public void test_apiServiceNameMatch4URL() { + String[] apiServiceNameArray = {"testApiName", "v1"}; + Assert.assertArrayEquals(apiServiceNameArray, RegExpTestUtil.apiServiceNameMatch4URL("/api/testApiName/v1")); + + String[] apiServiceNameArray_noversion = {"testApiName", ""}; + Assert.assertArrayEquals(apiServiceNameArray_noversion, + RegExpTestUtil.apiServiceNameMatch4URL("/api/testApiName")); + + Assert.assertNull(RegExpTestUtil.apiServiceNameMatch4URL("/apiw/name/v1")); } - + @Test - public void test_iuiServiceNameMatch4URL(){ - String iuiServiceName="testIuiName"; - Assert.assertEquals(iuiServiceName, RegExpTestUtil.iuiServiceNameMatch4URL("/iui/testIuiName")); - - Assert.assertNull(RegExpTestUtil.iuiServiceNameMatch4URL("/api/name/v1")); + public void test_iuiServiceNameMatch4URL() { + String iuiServiceName = "testIuiName"; + Assert.assertEquals(iuiServiceName, RegExpTestUtil.iuiServiceNameMatch4URL("/iui/testIuiName")); + + Assert.assertNull(RegExpTestUtil.iuiServiceNameMatch4URL("/api/name/v1")); } - + } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RouteUtilTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RouteUtilTest.java index 08fcf6c..02fa9f3 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RouteUtilTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/RouteUtilTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -34,340 +32,344 @@ import org.powermock.modules.junit4.PowerMockRunner; @PrepareForTest({ConfigUtil.class}) public class RouteUtilTest { - @Test - public void test_getPrefixedKey() { - Assert.assertEquals("msb:routing:test:v1", RouteUtil.getPrefixedKey("", "test", "v1")); - Assert.assertEquals("msb:5656:test:v1", RouteUtil.getPrefixedKey("5656", "test", "v1")); + @Test + public void test_getPrefixedKey() { + Assert.assertEquals("msb:routing:test:v1", RouteUtil.getPrefixedKey("", "test", "v1")); + Assert.assertEquals("msb:5656:test:v1", RouteUtil.getPrefixedKey("5656", "test", "v1")); - } + } + + @Test + public void test_getPrefixedKey4Host() { + Assert.assertEquals("msb:host:test:v1", RouteUtil.getPrefixedKey4Host("test", "v1")); - @Test - public void test_getPrefixedKey4Host() { - Assert.assertEquals("msb:host:test:v1", RouteUtil.getPrefixedKey4Host("test", "v1")); + } - } + @Test + public void test_checkRouteWay() { + try { + RouteUtil.checkRouteWay("ipp"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } - @Test - public void test_checkRouteWay() { - try { - RouteUtil.checkRouteWay("ipp"); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); } - } + @Test + public void test_checkServiceNameAndVersion() { + try { + RouteUtil.checkServiceNameAndVersion("", "v1"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } - @Test - public void test_checkServiceNameAndVersion() { - try { - RouteUtil.checkServiceNameAndVersion("","v1"); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + try { + RouteUtil.checkServiceNameAndVersion("test", "ve1"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - - try { - RouteUtil.checkServiceNameAndVersion("test","ve1"); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_checkServiceStatus() { + try { + RouteUtil.checkServiceStatus("2"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - @Test - public void test_checkServiceStatus() { - try { - RouteUtil.checkServiceStatus("2"); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_checkRouterInfoFormat() { + RouteInfo routeInfo = new RouteInfo(); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - @Test - public void test_checkRouterInfoFormat() { - RouteInfo routeInfo=new RouteInfo(); - - try { - RouteUtil.checkRouterInfoFormat(routeInfo); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_checkMicroServiceInfoFormat() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo, ""); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkMicroServiceInfoFormat_ip() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88.22", "8080")); + microServiceInfo.setNodes(nodeSet); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo, ""); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - @Test - public void test_checkMicroServiceInfoFormat() { - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - - try { - RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,""); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_checkMicroServiceInfoFormat_port() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("10.74.148.88.22", "808770")); + microServiceInfo.setNodes(nodeSet); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo, ""); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - @Test - public void test_checkMicroServiceInfoFormat_ip() { - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("name"); - microServiceInfo.setProtocol("REST"); - Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88.22","8080")); - microServiceInfo.setNodes(nodeSet); - - try { - RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,""); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_checkMicroServiceInfoFormat_version() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("", "8089")); + microServiceInfo.setNodes(nodeSet); + microServiceInfo.setVersion("cv2"); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo, "10.74.55.36"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkMicroServiceInfoFormat_url() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("", "8089")); + microServiceInfo.setNodes(nodeSet); + microServiceInfo.setVersion("v2"); + microServiceInfo.setUrl("url"); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo, "10.74.55.36"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_checkMicroServiceInfoFormat_protocol() { + MicroServiceFullInfo microServiceInfo = new MicroServiceFullInfo(); + microServiceInfo.setServiceName("name"); + microServiceInfo.setProtocol("REST2"); + Set<Node> nodeSet = new HashSet<>(); + nodeSet.add(new Node("", "8089")); + microServiceInfo.setNodes(nodeSet); + microServiceInfo.setVersion("v2"); + microServiceInfo.setUrl("/url"); + + try { + RouteUtil.checkMicroServiceInfoFormat(microServiceInfo, "10.74.55.36"); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } + } + + @Test + public void test_getAPIRedisPrefixedKey() { + Assert.assertEquals("msb:20081:api:testApi:v1", + RouteUtil.getAPIRedisPrefixedKey("testApi", "v1", "testHost", "20081", "ip")); + Assert.assertEquals("msb:routing:api:testApi:v1", + RouteUtil.getAPIRedisPrefixedKey("testApi", "v1", "testHost", "", "ip")); + Assert.assertEquals("msb:host:testHost:api:testApi:v1", + RouteUtil.getAPIRedisPrefixedKey("testApi", "v1", "testHost", "20081", "domain")); + } + + @Test + public void test_getRedisPrefixedKey() { + Assert.assertEquals("msb:20081:custom:/testName/v1", RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, + "/testName/v1", "testHost", "20081", "ip")); + Assert.assertEquals("msb:routing:custom:/testName/v1", + RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, "/testName/v1", "testHost", "", "ip")); + Assert.assertEquals("msb:host:testHost:custom:/testName/v1", RouteUtil + .getRedisPrefixedKey(RouteUtil.CUSTOMROUTE, "/testName/v1", "testHost", "20081", "domain")); + + Assert.assertEquals("msb:20081:iui:testName", + RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE, "testName", "testHost", "20081", "ip")); + Assert.assertEquals("msb:routing:iui:testName", + RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE, "testName", "testHost", "", "ip")); + Assert.assertEquals("msb:host:testHost:iui:testName", + RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE, "testName", "testHost", "20081", "domain")); } - } - - @Test - public void test_checkMicroServiceInfoFormat_port() { - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("name"); - microServiceInfo.setProtocol("REST"); - Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("10.74.148.88.22","808770")); - microServiceInfo.setNodes(nodeSet); - - try { - RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,""); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_getMutiRedisKey() { + Assert.assertEquals("msb:[^h]*:api:*", RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, "ip")); + Assert.assertEquals("msb:[^h]*:iui:*", RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, "ip")); + Assert.assertEquals("msb:[^h]*:custom:*", RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, "ip")); + + Assert.assertEquals("msb:host:*:api:*", RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE, "domain")); + Assert.assertEquals("msb:host:*:iui:*", RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE, "domain")); + Assert.assertEquals("msb:host:*:custom:*", RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE, "domain")); } - } - - @Test - public void test_checkMicroServiceInfoFormat_version() { - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("name"); - microServiceInfo.setProtocol("REST"); - Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("","8089")); - microServiceInfo.setNodes(nodeSet); - microServiceInfo.setVersion("cv2"); - - try { - RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,"10.74.55.36"); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_getRouteNameByns() { + Assert.assertEquals("serviceName", RouteUtil.getRouteNameByns("serviceName", "")); + Assert.assertEquals("serviceName", RouteUtil.getRouteNameByns("serviceName-ns", "ns")); + Assert.assertEquals("serviceName-ns", RouteUtil.getRouteNameByns("serviceName-ns-ns", "ns")); + Assert.assertEquals("serviceName", RouteUtil.getRouteNameByns("serviceName", "default")); } - } - - @Test - public void test_checkMicroServiceInfoFormat_url() { - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("name"); - microServiceInfo.setProtocol("REST"); - Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("","8089")); - microServiceInfo.setNodes(nodeSet); - microServiceInfo.setVersion("v2"); - microServiceInfo.setUrl("url"); - - try { - RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,"10.74.55.36"); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_getVisualRangeByRouter() { + Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0|1")); + Assert.assertEquals("1", RouteUtil.getVisualRangeByRouter("1")); + Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0")); + + } - } - - @Test - public void test_checkMicroServiceInfoFormat_protocol() { - MicroServiceFullInfo microServiceInfo=new MicroServiceFullInfo(); - microServiceInfo.setServiceName("name"); - microServiceInfo.setProtocol("REST2"); - Set<Node> nodeSet = new HashSet<>(); - nodeSet.add(new Node("","8089")); - microServiceInfo.setNodes(nodeSet); - microServiceInfo.setVersion("v2"); - microServiceInfo.setUrl("/url"); - - try { - RouteUtil.checkMicroServiceInfoFormat(microServiceInfo,"10.74.55.36"); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_getVisualRangeByRouter_muti() { + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("lab1:val,visualRange:0|1"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0|1")); } - } - - @Test - public void test_getAPIRedisPrefixedKey() { - Assert.assertEquals("msb:20081:api:testApi:v1", RouteUtil.getAPIRedisPrefixedKey("testApi", "v1", "testHost","20081","ip")); - Assert.assertEquals("msb:routing:api:testApi:v1", RouteUtil.getAPIRedisPrefixedKey("testApi", "v1", "testHost","","ip")); - Assert.assertEquals("msb:host:testHost:api:testApi:v1", RouteUtil.getAPIRedisPrefixedKey("testApi", "v1", "testHost","20081","domain")); - } - - @Test - public void test_getRedisPrefixedKey() { - Assert.assertEquals("msb:20081:custom:/testName/v1", RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE,"/testName/v1", "testHost","20081","ip")); - Assert.assertEquals("msb:routing:custom:/testName/v1", RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE,"/testName/v1", "testHost","","ip")); - Assert.assertEquals("msb:host:testHost:custom:/testName/v1", RouteUtil.getRedisPrefixedKey(RouteUtil.CUSTOMROUTE,"/testName/v1", "testHost","20081","domain")); - - Assert.assertEquals("msb:20081:iui:testName", RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE,"testName", "testHost","20081","ip")); - Assert.assertEquals("msb:routing:iui:testName", RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE,"testName", "testHost","","ip")); - Assert.assertEquals("msb:host:testHost:iui:testName", RouteUtil.getRedisPrefixedKey(RouteUtil.IUIROUTE,"testName", "testHost","20081","domain")); - } - - @Test - public void test_getMutiRedisKey() { - Assert.assertEquals("msb:[^h]*:api:*", RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE,"ip")); - Assert.assertEquals("msb:[^h]*:iui:*", RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE,"ip")); - Assert.assertEquals("msb:[^h]*:custom:*", RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE,"ip")); - - Assert.assertEquals("msb:host:*:api:*", RouteUtil.getMutiRedisKey(RouteUtil.APIROUTE,"domain")); - Assert.assertEquals("msb:host:*:iui:*", RouteUtil.getMutiRedisKey(RouteUtil.IUIROUTE,"domain")); - Assert.assertEquals("msb:host:*:custom:*", RouteUtil.getMutiRedisKey(RouteUtil.CUSTOMROUTE,"domain")); - } - - @Test - public void test_getRouteNameByns() { - Assert.assertEquals("serviceName", RouteUtil.getRouteNameByns("serviceName","")); - Assert.assertEquals("serviceName", RouteUtil.getRouteNameByns("serviceName-ns","ns")); - Assert.assertEquals("serviceName-ns", RouteUtil.getRouteNameByns("serviceName-ns-ns","ns")); - Assert.assertEquals("serviceName", RouteUtil.getRouteNameByns("serviceName","default")); - } - - @Test - public void test_getVisualRangeByRouter(){ - Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0|1")); - Assert.assertEquals("1", RouteUtil.getVisualRangeByRouter("1")); - Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0")); - - - } - - @Test - public void test_getVisualRangeByRouter_muti(){ - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("lab1:val,visualRange:0|1"); - ConfigUtil.getInstance().initRouteLabelsMatches(); - Assert.assertEquals("0", RouteUtil.getVisualRangeByRouter("0|1")); - } - - @Test - public void test_checkRouterInfoFormat_url() { - RouteInfo routeInfo=new RouteInfo(); - routeInfo.setServiceName("name"); - routeInfo.setUrl("url"); - routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); - - try { - RouteUtil.checkRouterInfoFormat(routeInfo); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_checkRouterInfoFormat_url() { + RouteInfo routeInfo = new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("url"); + routeInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - @Test - public void test_checkRouterInfoFormat_visualRangeRange() { - RouteInfo routeInfo=new RouteInfo(); - routeInfo.setServiceName("name"); - routeInfo.setUrl("/url"); - routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); - routeInfo.setVisualRange("2"); - - try { - RouteUtil.checkRouterInfoFormat(routeInfo); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_checkRouterInfoFormat_visualRangeRange() { + RouteInfo routeInfo = new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); + routeInfo.setVisualRange("2"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - - @Test - public void test_checkRouterInfoFormat_controlRangeMatches() { - RouteInfo routeInfo=new RouteInfo(); - routeInfo.setServiceName("name"); - routeInfo.setUrl("/url"); - routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); - routeInfo.setVisualRange("0"); - routeInfo.setControl("3"); - - try { - RouteUtil.checkRouterInfoFormat(routeInfo); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + + @Test + public void test_checkRouterInfoFormat_controlRangeMatches() { + RouteInfo routeInfo = new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("3"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - @Test - public void test_checkRouterInfoFormat_statusRangeMatches() { - RouteInfo routeInfo=new RouteInfo(); - routeInfo.setServiceName("name"); - routeInfo.setUrl("/url"); - routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); - routeInfo.setVisualRange("0"); - routeInfo.setControl("0"); - routeInfo.setStatus("3"); - - try { - RouteUtil.checkRouterInfoFormat(routeInfo); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_checkRouterInfoFormat_statusRangeMatches() { + RouteInfo routeInfo = new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("0"); + routeInfo.setStatus("3"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - - @Test - public void test_checkRouterInfoFormat_useOwnUpstreamRangeMatches() { - RouteInfo routeInfo=new RouteInfo(); - routeInfo.setServiceName("name"); - routeInfo.setUrl("/url"); - routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88","8080")}); - routeInfo.setVisualRange("0"); - routeInfo.setControl("0"); - routeInfo.setStatus("0"); - routeInfo.setUseOwnUpstream("3"); - - try { - RouteUtil.checkRouterInfoFormat(routeInfo); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + + @Test + public void test_checkRouterInfoFormat_useOwnUpstreamRangeMatches() { + RouteInfo routeInfo = new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88", "8080")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("0"); + routeInfo.setStatus("0"); + routeInfo.setUseOwnUpstream("3"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - @Test - public void test_checkRouterInfoFormat_ip() { - RouteInfo routeInfo=new RouteInfo(); - routeInfo.setServiceName("name"); - routeInfo.setUrl("/url"); - routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88.6","8080")}); - routeInfo.setVisualRange("0"); - routeInfo.setControl("0"); - routeInfo.setStatus("0"); - routeInfo.setUseOwnUpstream("1"); - - try { - RouteUtil.checkRouterInfoFormat(routeInfo); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + @Test + public void test_checkRouterInfoFormat_ip() { + RouteInfo routeInfo = new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88.6", "8080")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("0"); + routeInfo.setStatus("0"); + routeInfo.setUseOwnUpstream("1"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - - @Test - public void test_checkRouterInfoFormat_port() { - RouteInfo routeInfo=new RouteInfo(); - routeInfo.setServiceName("name"); - routeInfo.setUrl("/url"); - routeInfo.setServers( new RouteServer[]{new RouteServer("10.74.148.88.6","757577")}); - routeInfo.setVisualRange("0"); - routeInfo.setControl("0"); - routeInfo.setStatus("0"); - routeInfo.setUseOwnUpstream("1"); - - try { - RouteUtil.checkRouterInfoFormat(routeInfo); - } catch (Exception e) { - Assert.assertTrue(e instanceof UnprocessableEntityException); + + + @Test + public void test_checkRouterInfoFormat_port() { + RouteInfo routeInfo = new RouteInfo(); + routeInfo.setServiceName("name"); + routeInfo.setUrl("/url"); + routeInfo.setServers(new RouteServer[] {new RouteServer("10.74.148.88.6", "757577")}); + routeInfo.setVisualRange("0"); + routeInfo.setControl("0"); + routeInfo.setStatus("0"); + routeInfo.setUseOwnUpstream("1"); + + try { + RouteUtil.checkRouterInfoFormat(routeInfo); + } catch (Exception e) { + Assert.assertTrue(e instanceof UnprocessableEntityException); + } } - } - - - - - } diff --git a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ServiceFilterTest.java b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ServiceFilterTest.java index 9c9d4b1..5759014 100644 --- a/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ServiceFilterTest.java +++ b/apiroute/apiroute-service/src/test/java/org/onap/msb/apiroute/wrapper/util/ServiceFilterTest.java @@ -1,17 +1,15 @@ /******************************************************************************* * Copyright 2016-2017 ZTE, Inc. and others. * - * 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 + * 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 + * 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. + * 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.onap.msb.apiroute.wrapper.util; @@ -45,180 +43,173 @@ public class ServiceFilterTest { - @Test - public void test_isNeedNotifyByNameSpace() { - - PowerMockito.mockStatic(System.class); - - PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("all"); - ConfigUtil.getInstance().initRouteNameSpaceMatches(); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("test")); // namespaceMatches:all - - PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("default"); - ConfigUtil.getInstance().initRouteNameSpaceMatches(); - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("test"));// namespaceMatches:default - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace(""));// namespaceMatches:default - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("default"));// namespaceMatches:default - - - PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("!default"); - ConfigUtil.getInstance().initRouteNameSpaceMatches(); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("test"));// namespaceMatches:!default - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace(""));// namespaceMatches:!default - - PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("ns|ns2"); - ConfigUtil.getInstance().initRouteNameSpaceMatches(); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns")); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns2")); - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns3")); - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("")); - - - PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("!ns&!ns2"); - ConfigUtil.getInstance().initRouteNameSpaceMatches(); - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns")); - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns2")); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns3")); - - } - - /* - * @Test public void test_isNeedNotifyByVisualRange(){ - * - * Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByVisualRange("0")); - * Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByVisualRange("1")); - * Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByVisualRange("0|1")); } - */ - - @Test - public void test_isNeedNotifyByProtocol() { - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByProtocol("HTTP")); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByProtocol("UI")); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByProtocol("REST")); - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByProtocol("TCP")); - } - - @Test - public void test_isNeedNotifyByNetwork_plane_typeMatches() { - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("network_plane_type:network"); - ConfigUtil.getInstance().initRouteLabelsMatches(); - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net")); - Assert.assertTrue(ServiceFilter.getInstance() - .isNeedNotifyByNetwork_plane_typeMatches("network")); - - PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("network_plane_type:net1|net2"); - ConfigUtil.getInstance().initRouteLabelsMatches(); - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net")); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net1")); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net2")); - - } - - @Test - public void test_isNeedNotifyByRouteLabels() { - Map<String, String> labelMap = new HashMap<String, String>(); - labelMap.put("lab1", "val1"); - - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("lab1:val,visualRange:1"); - ConfigUtil.getInstance().initRouteLabelsMatches(); - Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByRouteLabels(labelMap)); - - PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("lab1:val1"); - ConfigUtil.getInstance().initRouteLabelsMatches(); - Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByRouteLabels(labelMap)); - - } - - @Test - public void test_isFilterService() { - PowerMockito.mockStatic(System.class); - PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("ns1"); - ConfigUtil.getInstance().initRouteNameSpaceMatches(); - - PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn( - "visualRange:0,network_plane_type:net,customLabel:custom|custom2"); - ConfigUtil.getInstance().initRouteLabelsMatches(); - - List<String> tagList = new ArrayList<String>(); - tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tagList - .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); - tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); - Assert.assertTrue(ServiceFilter.getInstance().isFilterService(tagList)); - - tagList.clear(); - tagList.add("\"base\":{\"protocol\":\"TCP\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); - - tagList.clear(); - tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tagList.add("\"ns\":{\"namespace\":\"ns2\"}"); - Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); - - tagList.clear(); - tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); - tagList - .add("\"labels\":{\"visualRange\":\"1\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); - Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); - - tagList.clear(); - tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); - tagList - .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net2\",\"customLabel\":\"custom\"}"); - Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); - - tagList.clear(); - tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); - tagList - .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom3\"}"); - Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); - - } - - @Test - public void test_transMicroServiceInfoFromConsul() { - List<String> tagList = new ArrayList<String>(); - tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); - tagList - .add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); - tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); - - Service service = - ImmutableService.builder().id("id").port(8686).address("10.74.165.246").service("msbtest") - .addAllTags(tagList).createIndex(0).modifyIndex(0).build(); - ServiceHealth serviceHealth = - ImmutableServiceHealth.builder().service(service) - .node(ImmutableNode.builder().node("server").address("192.168.1.98").build()).build(); - List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); - serviceHealthList.add(serviceHealth); - - Map<String, MicroServiceFullInfo> serviceMap= ServiceFilter.getInstance().transMicroServiceInfoFromConsul(serviceHealthList); - Assert.assertTrue(serviceMap.containsKey("v1")); - - MicroServiceFullInfo microService=new MicroServiceFullInfo(); - microService.setServiceName("msbtest"); - microService.setVersion("v1"); - microService.setUrl("/api/msbtest/v1"); - microService.setProtocol("REST"); - microService.setVisualRange("0"); - microService.setNamespace("ns1"); - - Set<Node> nodes=new HashSet<Node>(); - nodes.add(new Node("10.74.165.246","8686")); - microService.setNodes(nodes); - - - - Assert.assertEquals(microService,serviceMap.get("v1")); - - - } + @Test + public void test_isNeedNotifyByNameSpace() { + + PowerMockito.mockStatic(System.class); + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("all"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("test")); // namespaceMatches:all + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("default"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("test"));// namespaceMatches:default + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace(""));// namespaceMatches:default + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("default"));// namespaceMatches:default + + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("!default"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("test"));// namespaceMatches:!default + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace(""));// namespaceMatches:!default + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("ns|ns2"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns2")); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns3")); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("")); + + + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("!ns&!ns2"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns")); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns2")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNameSpace("ns3")); + + } + + /* + * @Test public void test_isNeedNotifyByVisualRange(){ + * + * Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByVisualRange("0")); + * Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByVisualRange("1")); + * Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByVisualRange("0|1")); } + */ + + @Test + public void test_isNeedNotifyByProtocol() { + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByProtocol("HTTP")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByProtocol("UI")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByProtocol("REST")); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByProtocol("TCP")); + } + + @Test + public void test_isNeedNotifyByNetwork_plane_typeMatches() { + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("network_plane_type:network"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("network")); + + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("network_plane_type:net1|net2"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net1")); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByNetwork_plane_typeMatches("net2")); + + } + + @Test + public void test_isNeedNotifyByRouteLabels() { + Map<String, String> labelMap = new HashMap<String, String>(); + labelMap.put("lab1", "val1"); + + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("lab1:val,visualRange:1"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertFalse(ServiceFilter.getInstance().isNeedNotifyByRouteLabels(labelMap)); + + PowerMockito.when(System.getenv("ROUTE_LABELS")).thenReturn("lab1:val1"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + Assert.assertTrue(ServiceFilter.getInstance().isNeedNotifyByRouteLabels(labelMap)); + + } + + @Test + public void test_isFilterService() { + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv("NAMESPACE")).thenReturn("ns1"); + ConfigUtil.getInstance().initRouteNameSpaceMatches(); + + PowerMockito.when(System.getenv("ROUTE_LABELS")) + .thenReturn("visualRange:0,network_plane_type:net,customLabel:custom|custom2"); + ConfigUtil.getInstance().initRouteLabelsMatches(); + + List<String> tagList = new ArrayList<String>(); + tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + Assert.assertTrue(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"TCP\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns2\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + tagList.add("\"labels\":{\"visualRange\":\"1\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + tagList.add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net2\",\"customLabel\":\"custom\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + tagList.clear(); + tagList.add("\"base\":{\"protocol\":\"UI\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + tagList.add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom3\"}"); + Assert.assertFalse(ServiceFilter.getInstance().isFilterService(tagList)); + + } + + @Test + public void test_transMicroServiceInfoFromConsul() { + List<String> tagList = new ArrayList<String>(); + tagList.add("\"base\":{\"protocol\":\"REST\",\"version\":\"v1\",\"url\":\"/api/msbtest/v1\"}"); + tagList.add("\"labels\":{\"visualRange\":\"0\",\"network_plane_type\":\"net\",\"customLabel\":\"custom\"}"); + tagList.add("\"ns\":{\"namespace\":\"ns1\"}"); + + Service service = ImmutableService.builder().id("id").port(8686).address("10.74.165.246").service("msbtest") + .addAllTags(tagList).createIndex(0).modifyIndex(0).build(); + ServiceHealth serviceHealth = ImmutableServiceHealth.builder().service(service) + .node(ImmutableNode.builder().node("server").address("192.168.1.98").build()).build(); + List<ServiceHealth> serviceHealthList = new ArrayList<ServiceHealth>(); + serviceHealthList.add(serviceHealth); + + Map<String, MicroServiceFullInfo> serviceMap = + ServiceFilter.getInstance().transMicroServiceInfoFromConsul(serviceHealthList); + Assert.assertTrue(serviceMap.containsKey("v1")); + + MicroServiceFullInfo microService = new MicroServiceFullInfo(); + microService.setServiceName("msbtest"); + microService.setVersion("v1"); + microService.setUrl("/api/msbtest/v1"); + microService.setProtocol("REST"); + microService.setVisualRange("0"); + microService.setNamespace("ns1"); + + Set<Node> nodes = new HashSet<Node>(); + nodes.add(new Node("10.74.165.246", "8686")); + microService.setNodes(nodes); + + + + Assert.assertEquals(microService, serviceMap.get("v1")); + + + } |