Fixed MSB Registration Failure 43/114143/5
authorGuangrongFu <fu.guangrong@zte.com.cn>
Thu, 22 Oct 2020 08:56:16 +0000 (16:56 +0800)
committerGuangrongFu <fu.guangrong@zte.com.cn>
Thu, 22 Oct 2020 09:28:30 +0000 (17:28 +0800)
Issue-ID: HOLMES-368

Change-Id: I9a5b3275e7c58265992796bff3033acfa7b595db
Signed-off-by: GuangrongFu <fu.guangrong@zte.com.cn>
holmes-actions/pom.xml
holmes-actions/src/main/java/org/onap/holmes/common/config/MicroServiceConfig.java
holmes-actions/src/main/java/org/onap/holmes/common/utils/JerseyClient.java [new file with mode: 0644]
holmes-actions/src/main/java/org/onap/holmes/common/utils/MSBRegisterUtil.java [deleted file]
holmes-actions/src/main/java/org/onap/holmes/common/utils/MsbRegister.java [new file with mode: 0644]
holmes-actions/src/test/java/org/onap/holmes/common/config/MicroServiceConfigTest.java
holmes-actions/src/test/java/org/onap/holmes/common/engine/dao/EngineEntityMapperTest.java
holmes-actions/src/test/java/org/onap/holmes/common/utils/JerseyClientTest.java [new file with mode: 0644]
holmes-actions/src/test/java/org/onap/holmes/common/utils/MSBRegisterUtilTest.java [deleted file]
holmes-actions/src/test/java/org/onap/holmes/common/utils/MsbRegisterTest.java [new file with mode: 0644]
pom.xml

index ca1310f..60ba3b7 100644 (file)
@@ -12,7 +12,7 @@
     <parent>\r
         <groupId>org.onap.holmes.common</groupId>\r
         <artifactId>holmes-common-parent</artifactId>\r
-        <version>1.3.1-SNAPSHOT</version>\r
+        <version>1.3.2-SNAPSHOT</version>\r
     </parent>\r
 \r
     <name>holmes-common-service</name>\r
index 33bd1d2..7cbbb3e 100644 (file)
@@ -35,6 +35,8 @@ public class MicroServiceConfig {
     final static public String CONFIG_BINDING_SERVICE = "CONFIG_BINDING_SERVICE";\r
     final static public String DOCKER_HOST = "DOCKER_HOST";\r
     final static public String MSB_ADDR = "MSB_ADDR";\r
+    final static public String MSB_IAG_SERVICE_HOST = "MSB_IAG_SERVICE_HOST";\r
+    final static public String MSB_IAG_SERVICE_PORT = "MSB_IAG_SERVICE_PORT";\r
     final static public Pattern IP_REG = Pattern.compile("(http(s)?://)?(\\d+\\.\\d+\\.\\d+\\.\\d+)(:(\\d+))?");\r
     final static public String AAI_HOSTNAME = "aai.onap";\r
 \r
@@ -105,7 +107,7 @@ public class MicroServiceConfig {
     }\r
 \r
     public static String[] getMsbIpAndPort() {\r
-        return split(getEnv(MSB_ADDR));\r
+        return new String[] {getEnv(MSB_IAG_SERVICE_HOST), getEnv(MSB_IAG_SERVICE_PORT)};\r
     }\r
 \r
     public static String[] getMicroServiceIpAndPort() {\r
@@ -124,7 +126,7 @@ public class MicroServiceConfig {
         return serviceAddrInfo;\r
     }\r
 \r
-    private static boolean isIpAddress(String info) {\r
+    public static boolean isIpAddress(String info) {\r
         return IP_REG.matcher(info).matches();\r
     }\r
 \r
diff --git a/holmes-actions/src/main/java/org/onap/holmes/common/utils/JerseyClient.java b/holmes-actions/src/main/java/org/onap/holmes/common/utils/JerseyClient.java
new file mode 100644 (file)
index 0000000..2d770ad
--- /dev/null
@@ -0,0 +1,75 @@
+/**
+ * Copyright 2020 ZTE Corporation.
+ * <p>
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.holmes.common.utils;
+
+import org.glassfish.jersey.client.ClientConfig;
+import org.jvnet.hk2.annotations.Service;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.PostConstruct;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.X509Certificate;
+
+@Service
+public class JerseyClient {
+    private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
+    public static final String PROTOCOL_HTTP = "http";
+    public static final String PROTOCOL_HTTPS = "https";
+    private SSLContext sslcontext = null;
+
+    @PostConstruct
+    private void init() {
+        try {
+            sslcontext = SSLContext.getInstance("TLS");
+            sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
+                public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
+                }
+
+                public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
+                }
+
+                public X509Certificate[] getAcceptedIssuers() {
+                    return new X509Certificate[0];
+                }
+            }}, new java.security.SecureRandom());
+        } catch (NoSuchAlgorithmException | KeyManagementException e) {
+            logger.error("Failed to initialize the SSLContext instance!", e);
+        }
+    }
+
+    public Client httpClient() {
+        return ClientBuilder.newClient(new ClientConfig());
+    }
+
+    public Client httpsClient() {
+        return ClientBuilder.newBuilder()
+                .sslContext(sslcontext)
+                .hostnameVerifier((s1, s2) -> true)
+                .build();
+    }
+
+    public Client client(boolean isHttps) {
+        return isHttps ? httpsClient() : httpClient();
+    }
+}
diff --git a/holmes-actions/src/main/java/org/onap/holmes/common/utils/MSBRegisterUtil.java b/holmes-actions/src/main/java/org/onap/holmes/common/utils/MSBRegisterUtil.java
deleted file mode 100644 (file)
index a849ab8..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/**\r
- * Copyright 2017-2020 ZTE Corporation.\r
- * <p>\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * <p>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p>\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-package org.onap.holmes.common.utils;\r
-\r
-import lombok.extern.slf4j.Slf4j;\r
-import org.jvnet.hk2.annotations.Service;\r
-import org.onap.holmes.common.config.MicroServiceConfig;\r
-import org.onap.holmes.common.exception.CorrelationException;\r
-import org.onap.msb.sdk.discovery.common.RouteException;\r
-import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo;\r
-import org.onap.msb.sdk.discovery.entity.MicroServiceInfo;\r
-import org.onap.msb.sdk.httpclient.msb.MSBServiceClient;\r
-\r
-@Slf4j\r
-@Service\r
-public class MSBRegisterUtil {\r
-\r
-    public void register2Msb(MicroServiceInfo msinfo) throws CorrelationException {\r
-        String[] msbAddrInfo = MicroServiceConfig.getMsbIpAndPort();\r
-        MSBServiceClient msbClient = new MSBServiceClient(msbAddrInfo[0],\r
-                Integer.parseInt(msbAddrInfo[1]));\r
-\r
-        log.info("Start to register Holmes Service to MSB...");\r
-        MicroServiceFullInfo microServiceFullInfo = null;\r
-        int retry = 0;\r
-        while (null == microServiceFullInfo && retry < 20) {\r
-            log.info("Holmes Service Registration. Retry: " + retry);\r
-            retry++;\r
-            try {\r
-                microServiceFullInfo = msbClient.registerMicroServiceInfo(msinfo, false);\r
-            } catch (RouteException e) {\r
-\r
-            }\r
-\r
-            if (null == microServiceFullInfo) {\r
-                log.warn("Failed to register the service to MSB. Sleep 30s and try again.");\r
-                threadSleep(30000);\r
-            } else {\r
-                log.info("Registration succeeded!");\r
-                break;\r
-            }\r
-        }\r
-\r
-        if (null == microServiceFullInfo) {\r
-            throw new CorrelationException("Failed to register the service to MSB!");\r
-        }\r
-\r
-        log.info("Service registration completed.");\r
-    }\r
-\r
-    private void threadSleep(int second) {\r
-        log.info("Start sleeping...");\r
-        try {\r
-            Thread.sleep(second);\r
-        } catch (InterruptedException error) {\r
-            log.error("thread sleep error message:" + error.getMessage(), error);\r
-            Thread.currentThread().interrupt();\r
-        }\r
-        log.info("Wake up.");\r
-    }\r
-}
\ No newline at end of file
diff --git a/holmes-actions/src/main/java/org/onap/holmes/common/utils/MsbRegister.java b/holmes-actions/src/main/java/org/onap/holmes/common/utils/MsbRegister.java
new file mode 100644 (file)
index 0000000..caff931
--- /dev/null
@@ -0,0 +1,108 @@
+/**
+ * Copyright 2017-2020 ZTE Corporation.
+ * <p>
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.holmes.common.utils;
+
+import org.apache.commons.lang3.StringUtils;
+import org.eclipse.jetty.http.HttpStatus;
+import org.jvnet.hk2.annotations.Service;
+import org.onap.holmes.common.config.MicroServiceConfig;
+import org.onap.holmes.common.exception.CorrelationException;
+import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo;
+import org.onap.msb.sdk.discovery.entity.MicroServiceInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.inject.Inject;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.concurrent.TimeUnit;
+
+import static org.onap.holmes.common.utils.JerseyClient.PROTOCOL_HTTP;
+import static org.onap.holmes.common.utils.JerseyClient.PROTOCOL_HTTPS;
+
+@Service
+public class MsbRegister {
+    private static final Logger log = LoggerFactory.getLogger(MsbRegister.class);
+
+    private JerseyClient jerseyClient;
+
+    @Inject
+    public MsbRegister(JerseyClient jerseyClient) {
+        this.jerseyClient = jerseyClient;
+    }
+
+    public void register2Msb(MicroServiceInfo msinfo) throws CorrelationException {
+        String[] msbAddrInfo = MicroServiceConfig.getMsbIpAndPort();
+        boolean isHttpsEnabled = StringUtils.isNotBlank(msbAddrInfo[1])
+                && msbAddrInfo[1].equals("443");
+
+        Client client = jerseyClient.client(isHttpsEnabled);
+        WebTarget target = client.target(String.format("%s://%s:%s/api/microservices/v1/services",
+                isHttpsEnabled ? PROTOCOL_HTTPS : PROTOCOL_HTTP, msbAddrInfo[0], msbAddrInfo[1]));
+
+        log.info("Start to register Holmes Service to MSB...");
+
+        MicroServiceFullInfo microServiceFullInfo = null;
+        int retry = 0;
+        int interval = 5;
+        while (null == microServiceFullInfo && retry < 20) {
+            log.info("Holmes Service Registration. Retry: " + retry++);
+
+            Response response = target.queryParam("createOrUpdate", true)
+                    .request(MediaType.APPLICATION_JSON)
+                    .post(Entity.entity(msinfo, MediaType.APPLICATION_JSON));
+
+            if (response != null) {
+                String ret = response.readEntity(String.class);
+                int statusCode = response.getStatus();
+                log.info(String.format("=========MSB REG=========\nStatus Code: %d\nInformation: %s", statusCode, ret));
+                if (HttpStatus.isSuccess(statusCode)) {
+                    microServiceFullInfo = GsonUtil.jsonToBean(ret, MicroServiceFullInfo.class);
+                }
+            }
+
+            if (null == microServiceFullInfo) {
+                log.warn(String.format("Failed to register the service to MSB. Sleep %ds and try again.", interval));
+                threadSleep(TimeUnit.SECONDS.toSeconds(interval));
+                interval += 5;
+            } else {
+                log.info("Registration succeeded!");
+                break;
+            }
+        }
+
+        if (null == microServiceFullInfo) {
+            throw new CorrelationException("Failed to register the service to MSB!");
+        }
+
+        log.info("Service registration completed.");
+    }
+
+    private void threadSleep(long second) {
+        log.info("Start sleeping...");
+        try {
+            TimeUnit.SECONDS.sleep(second);
+        } catch (InterruptedException error) {
+            log.error("thread sleep error message:" + error.getMessage(), error);
+            Thread.currentThread().interrupt();
+        }
+        log.info("Wake up.");
+    }
+}
\ No newline at end of file
index a87ba67..fbc22e5 100644 (file)
@@ -43,23 +43,27 @@ public class MicroServiceConfigTest {
 \r
     @Test\r
     public void getMsbServerAddrTest() {\r
-        System.setProperty(MSB_ADDR, "test:80");\r
-        assertThat("http://test:80", equalTo(getMsbServerAddrWithHttpPrefix()));\r
-        System.clearProperty(MicroServiceConfig.MSB_ADDR);\r
+        System.setProperty(MSB_IAG_SERVICE_HOST, "test");\r
+        System.setProperty(MSB_IAG_SERVICE_PORT, "443");\r
+        assertThat("http://test:443", equalTo(getMsbServerAddrWithHttpPrefix()));\r
+        System.clearProperty(MicroServiceConfig.MSB_IAG_SERVICE_PORT);\r
+        System.clearProperty(MicroServiceConfig.MSB_IAG_SERVICE_HOST);\r
     }\r
 \r
     @Test\r
     public void getMsbServerIpTest() {\r
-        System.setProperty(MSB_ADDR, "10.54.23.79:80");\r
+        System.setProperty(MSB_IAG_SERVICE_HOST, "10.54.23.79");\r
+        System.setProperty(MSB_IAG_SERVICE_PORT, "443");\r
         System.setProperty(HOSTNAME, "rule-mgmt");\r
         PowerMock.mockStaticPartial(MicroServiceConfig.class, "getServiceConfigInfoFromCBS", String.class);\r
         EasyMock.expect(MicroServiceConfig.getServiceConfigInfoFromCBS(System.getProperty(HOSTNAME)))\r
-                .andReturn("{\"msb.hostname\": \"10.54.23.79:80\"}").times(2);\r
+                .andReturn("{\"msb.hostname\": \"10.54.23.79:443\"}").times(2);\r
         PowerMock.replayAll();\r
         assertThat("10.54.23.79", equalTo(getMsbIpAndPort()[0]));\r
-        assertThat("80", equalTo(getMsbIpAndPort()[1]));\r
+        assertThat("443", equalTo(getMsbIpAndPort()[1]));\r
         System.clearProperty(MicroServiceConfig.HOSTNAME);\r
-        System.clearProperty(MSB_ADDR);\r
+        System.clearProperty(MicroServiceConfig.MSB_IAG_SERVICE_PORT);\r
+        System.clearProperty(MicroServiceConfig.MSB_IAG_SERVICE_HOST);\r
     }\r
 \r
     @Test\r
@@ -159,7 +163,8 @@ public class MicroServiceConfigTest {
 \r
     @Ignore\r
     public void getMsbAddrInfo_msb_registered() throws Exception {\r
-        System.setProperty(MSB_ADDR, "10.74.5.8:1545");\r
+        System.setProperty(MSB_IAG_SERVICE_HOST, "10.74.5.8");\r
+        System.setProperty(MSB_IAG_SERVICE_PORT, "1545");\r
         System.setProperty(HOSTNAME, "rule-mgmt");\r
         PowerMock.mockStaticPartial(MicroServiceConfig.class, "getServiceConfigInfoFromCBS", String.class);\r
         EasyMock.expect(MicroServiceConfig.getServiceConfigInfoFromCBS(System.getProperty(HOSTNAME)))\r
@@ -173,12 +178,14 @@ public class MicroServiceConfigTest {
         assertThat(msbInfo[1], equalTo("5432"));\r
 \r
         System.clearProperty(HOSTNAME);\r
-        System.clearProperty(MSB_ADDR);\r
+        System.clearProperty(MSB_IAG_SERVICE_PORT);\r
+        System.clearProperty(MSB_IAG_SERVICE_HOST);\r
     }\r
 \r
     @Ignore\r
     public void getMsbAddrInfo_msb_not_registered() throws Exception {\r
-        System.setProperty(MSB_ADDR, "10.74.5.8:1545");\r
+        System.setProperty(MSB_IAG_SERVICE_HOST, "10.74.5.8");\r
+        System.setProperty(MSB_IAG_SERVICE_PORT, "1545");\r
         System.setProperty(HOSTNAME, "rule-mgmt");\r
         PowerMock.mockStaticPartial(MicroServiceConfig.class, "getServiceConfigInfoFromCBS", String.class);\r
         EasyMock.expect(MicroServiceConfig.getServiceConfigInfoFromCBS(System.getProperty(HOSTNAME)))\r
@@ -192,7 +199,8 @@ public class MicroServiceConfigTest {
         assertThat(msbInfo[1], equalTo("1545"));\r
 \r
         System.clearProperty(HOSTNAME);\r
-        System.clearProperty(MSB_ADDR);\r
+        System.clearProperty(MSB_IAG_SERVICE_PORT);\r
+        System.clearProperty(MSB_IAG_SERVICE_HOST);\r
     }\r
 \r
     @Test\r
@@ -249,7 +257,7 @@ public class MicroServiceConfigTest {
         assertThat(msbInfo[0], equalTo(ip));\r
         assertThat(msbInfo[1], equalTo(port));\r
 \r
-        System.clearProperty(MSB_ADDR);\r
+        System.clearProperty(HOSTNAME);\r
     }\r
 \r
     @Test\r
@@ -268,7 +276,7 @@ public class MicroServiceConfigTest {
         assertThat(msbInfo[0], equalTo(ip));\r
         assertThat(msbInfo[1], equalTo("80"));\r
 \r
-        System.clearProperty(MSB_ADDR);\r
+        System.clearProperty(HOSTNAME);\r
     }\r
 \r
     @Test\r
@@ -287,7 +295,7 @@ public class MicroServiceConfigTest {
         assertThat(msbInfo[0], equalTo(ip));\r
         assertThat(msbInfo[1], equalTo("80"));\r
 \r
-        System.clearProperty(MSB_ADDR);\r
+        System.clearProperty(HOSTNAME);\r
     }\r
 \r
     @Test\r
@@ -307,7 +315,7 @@ public class MicroServiceConfigTest {
         assertThat(msbInfo[0], equalTo(ip));\r
         assertThat(msbInfo[1], equalTo(port));\r
 \r
-        System.clearProperty(MSB_ADDR);\r
+        System.clearProperty(HOSTNAME);\r
     }\r
 \r
     @Test\r
@@ -342,7 +350,7 @@ public class MicroServiceConfigTest {
 \r
     @Test\r
     public void isValidIpAddress_invalid_ip_with_port() throws Exception {\r
-        boolean res = WhiteboxImpl.invokeMethod(MicroServiceConfig.class, "isIpAddress", "holmes-rule-mgmt:80");\r
+        boolean res = WhiteboxImpl.invokeMethod(MicroServiceConfig.class, "isIpAddress", "holmes-rule-mgmt:443");\r
         assertThat(res, is(false));\r
     }\r
 \r
@@ -354,7 +362,7 @@ public class MicroServiceConfigTest {
 \r
     @Test\r
     public void isValidIpAddress_invalid_ip_with_port_with_https_prefix() throws Exception {\r
-        boolean res = WhiteboxImpl.invokeMethod(MicroServiceConfig.class, "isIpAddress", "https://holmes-rule-mgmt:80");\r
+        boolean res = WhiteboxImpl.invokeMethod(MicroServiceConfig.class, "isIpAddress", "https://holmes-rule-mgmt:443");\r
         assertThat(res, is(false));\r
     }\r
 }
\ No newline at end of file
index ad684da..99b14ab 100644 (file)
@@ -23,18 +23,12 @@ import org.powermock.api.easymock.PowerMock;
 import org.powermock.core.classloader.annotations.PrepareForTest;
 import org.powermock.modules.junit4.PowerMockRunner;
 
-import java.io.InputStream;
-import java.io.Reader;
-import java.math.BigDecimal;
-import java.net.URL;
-import java.sql.*;
-import java.util.Calendar;
-import java.util.Map;
+import java.sql.ResultSet;
 
 import static org.easymock.EasyMock.expect;
 import static org.hamcrest.core.Is.is;
 import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertThat;
 
 @RunWith(PowerMockRunner.class)
 @PrepareForTest({ResultSet.class})
diff --git a/holmes-actions/src/test/java/org/onap/holmes/common/utils/JerseyClientTest.java b/holmes-actions/src/test/java/org/onap/holmes/common/utils/JerseyClientTest.java
new file mode 100644 (file)
index 0000000..6c95ccb
--- /dev/null
@@ -0,0 +1,47 @@
+/**
+ * Copyright 2020 ZTE Corporation.
+ * <p>
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.holmes.common.utils;
+
+import org.junit.Test;
+import org.powermock.reflect.internal.WhiteboxImpl;
+
+public class JerseyClientTest {
+
+    private JerseyClient jerseyClient = new JerseyClient();
+
+    @Test
+    public void http() {
+        jerseyClient.httpClient();
+    }
+
+    @Test
+    public void https() throws Exception {
+        WhiteboxImpl.invokeMethod(jerseyClient, "init");
+        jerseyClient.httpsClient();
+    }
+
+    @Test
+    public void clientHttp() {
+        jerseyClient.client(false);
+    }
+
+    @Test
+    public void clientHttps() throws Exception {
+        WhiteboxImpl.invokeMethod(jerseyClient, "init");
+        jerseyClient.client(true);
+    }
+}
\ No newline at end of file
diff --git a/holmes-actions/src/test/java/org/onap/holmes/common/utils/MSBRegisterUtilTest.java b/holmes-actions/src/test/java/org/onap/holmes/common/utils/MSBRegisterUtilTest.java
deleted file mode 100644 (file)
index e6b6f9d..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-/**\r
- * Copyright 2017-2020 ZTE Corporation.\r
- * <p>\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * <p>\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * <p>\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-package org.onap.holmes.common.utils;\r
-\r
-import org.easymock.EasyMock;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.onap.holmes.common.config.MicroServiceConfig;\r
-import org.onap.holmes.common.exception.CorrelationException;\r
-import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo;\r
-import org.onap.msb.sdk.discovery.entity.MicroServiceInfo;\r
-import org.onap.msb.sdk.httpclient.msb.MSBServiceClient;\r
-import org.powermock.api.easymock.PowerMock;\r
-import org.powermock.core.classloader.annotations.PowerMockIgnore;\r
-import org.powermock.core.classloader.annotations.PrepareForTest;\r
-import org.powermock.modules.junit4.PowerMockRunner;\r
-\r
-@PrepareForTest({MicroServiceConfig.class, MSBServiceClient.class, MSBRegisterUtil.class})\r
-@PowerMockIgnore({"javax.ws.*"})\r
-@RunWith(PowerMockRunner.class)\r
-public class MSBRegisterUtilTest {\r
-\r
-    private MSBRegisterUtil msbRegisterUtil = new MSBRegisterUtil();\r
-\r
-    @Test\r
-    public void test_register2Msb_normal() throws Exception {\r
-        MicroServiceInfo msi = new MicroServiceInfo();\r
-        String[] msbAddrInfo = {"127.0.0.1", "80"};\r
-\r
-        PowerMock.mockStatic(MicroServiceConfig.class);\r
-        EasyMock.expect(MicroServiceConfig.getMsbIpAndPort()).andReturn(msbAddrInfo);\r
-\r
-        MSBServiceClient client = PowerMock.createMock(MSBServiceClient.class);\r
-        PowerMock.expectNew(MSBServiceClient.class, msbAddrInfo[0], Integer.parseInt(msbAddrInfo[1])).andReturn(client);\r
-\r
-        EasyMock.expect(client.registerMicroServiceInfo(msi, false)).andReturn(null);\r
-\r
-        EasyMock.expect(client.registerMicroServiceInfo(msi, false)).andReturn(new MicroServiceFullInfo());\r
-\r
-        PowerMock.replayAll();\r
-\r
-        try {\r
-            msbRegisterUtil.register2Msb(msi);\r
-        } catch (CorrelationException e) {\r
-            // Do nothing\r
-        }\r
-\r
-        PowerMock.verifyAll();\r
-    }\r
-}
\ No newline at end of file
diff --git a/holmes-actions/src/test/java/org/onap/holmes/common/utils/MsbRegisterTest.java b/holmes-actions/src/test/java/org/onap/holmes/common/utils/MsbRegisterTest.java
new file mode 100644 (file)
index 0000000..0637586
--- /dev/null
@@ -0,0 +1,93 @@
+/**
+ * Copyright 2017-2020 ZTE Corporation.
+ * <p>
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.holmes.common.utils;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.holmes.common.config.MicroServiceConfig;
+import org.onap.holmes.common.exception.CorrelationException;
+import org.onap.msb.sdk.discovery.entity.MicroServiceInfo;
+import org.powermock.api.easymock.PowerMock;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import static org.easymock.EasyMock.expect;
+import static org.powermock.api.easymock.PowerMock.createMock;
+
+@PrepareForTest({MicroServiceConfig.class})
+@RunWith(PowerMockRunner.class)
+public class MsbRegisterTest {
+    @Test
+    public void test_register2Msb_normal() {
+        MicroServiceInfo msi = new MicroServiceInfo();
+        String[] msbAddrInfo = {"127.0.0.1", "80"};
+
+        PowerMock.mockStatic(MicroServiceConfig.class);
+        expect(MicroServiceConfig.getMsbIpAndPort()).andReturn(msbAddrInfo);
+
+        JerseyClient mockedJerseyClient = createMock(JerseyClient.class);
+
+        Client mockedClient = createMock(Client.class);
+        expect(mockedJerseyClient.client(false)).andReturn(mockedClient);
+
+        WebTarget mockedWebTarget = createMock(WebTarget.class);
+        expect(mockedClient.target("http://127.0.0.1:80/api/microservices/v1/services")).andReturn(mockedWebTarget);
+
+
+        expect(mockedWebTarget.queryParam("createOrUpdate", true)).andReturn(mockedWebTarget).times(2);
+
+        Invocation.Builder mockedBuilder = createMock(Invocation.Builder.class);
+        expect(mockedWebTarget.request(MediaType.APPLICATION_JSON)).andReturn(mockedBuilder).times(2);
+
+        Response mockedResponse = createMock(Response.class);
+        expect(mockedBuilder.post(Entity.entity(msi, MediaType.APPLICATION_JSON)))
+                .andReturn(mockedResponse);
+        expect(mockedResponse.getStatus()).andReturn(300);
+
+        expect(mockedBuilder.post(Entity.entity(msi, MediaType.APPLICATION_JSON)))
+                .andReturn(mockedResponse);
+        expect(mockedResponse.getStatus()).andReturn(201);
+        expect(mockedResponse.readEntity(String.class)).andReturn("Error");
+        expect(mockedResponse.readEntity(String.class)).andReturn("{\"serviceName\":\"holmes-engine-mgmt\"," +
+                "\"version\":\"v1\",\"url\":\"/api/holmes-engine-mgmt/v1\",\"protocol\":\"REST\"," +
+                "\"visualRange\":\"0|1\",\"lb_policy\":\"\",\"publish_port\":\"\",\"namespace\":\"\"," +
+                "\"network_plane_type\":\"\",\"host\":\"\",\"path\":\"/api/holmes-engine-mgmt/v1\"," +
+                "\"enable_ssl\":true,\"nodes\":[{\"ip\":\"127.0.0.1\",\"port\":\"9102\",\"checkType\":\"\"," +
+                "\"checkUrl\":\"\",\"tls_skip_verify\":true,\"ha_role\":\"\",\"nodeId\":\"_v1_holmes-engine-mgmt_127.0.0.1_9102\"," +
+                "\"status\":\"passing\"}],\"metadata\":[],\"labels\":[],\"status\":\"1\",\"is_manual\":false}");
+
+
+        MsbRegister msbRegister = new MsbRegister(mockedJerseyClient);
+
+        PowerMock.replayAll();
+
+        try {
+            msbRegister.register2Msb(msi);
+        } catch (CorrelationException e) {
+            // Do nothing
+        }
+
+        PowerMock.verifyAll();
+    }
+}
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 04098f7..d01e18e 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -20,7 +20,7 @@
     <artifactId>holmes-common-parent</artifactId>\r
     <packaging>pom</packaging>\r
 \r
-    <version>1.3.1-SNAPSHOT</version>\r
+    <version>1.3.2-SNAPSHOT</version>\r
     <name>holmes-common</name>\r
     <modules>\r
         <module>holmes-actions</module>\r