From 701348be1f74519bbbb47c6acadc04f217361853 Mon Sep 17 00:00:00 2001 From: HuangXin Date: Sat, 8 Mar 2025 10:32:40 +0800 Subject: [PATCH 1/7] =?UTF-8?q?OCT=20REM:=201.=20=E9=9B=86=E6=88=90?= =?UTF-8?q?=E7=AD=BE=E5=90=8D=E9=AA=8C=E8=AF=81=E5=8A=9F=E8=83=BD=202.=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=BC=82=E6=AD=A5=E6=89=A7=E8=A1=8C=E4=BB=BB?= =?UTF-8?q?=E5=8A=A1=E5=AE=8C=E6=88=90=E9=80=9A=E7=9F=A5=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 21 ++++++++++++++++++- .../com/cmcc/magent/config/MwCoreConfig.java | 19 +++++++++++++++++ .../interceptor/MwSignRequestInterceptor.java | 20 ++++++++++++++++++ .../magent/service/PlatformApiService.java | 3 +++ .../impl/MiddlewareManagerServiceImpl.java | 12 +++++++++++ src/main/resources/application.properties | 18 ++++++++++++++++ 6 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/cmcc/magent/config/MwCoreConfig.java create mode 100644 src/main/java/com/cmcc/magent/interceptor/MwSignRequestInterceptor.java diff --git a/pom.xml b/pom.xml index e11b84d..58f0ac5 100644 --- a/pom.xml +++ b/pom.xml @@ -29,6 +29,7 @@ 1.0.0 17 + 0.1.6-SNAPSHOT @@ -58,6 +59,11 @@ jacoco-maven-plugin 0.8.12 + + org.springframework.cloud + spring-cloud-starter-openfeign + 4.2.0 + org.springdoc springdoc-openapi-starter-webmvc-api @@ -143,7 +149,12 @@ com.cmcc.hy gzs-common-oss - 0.1.6-SNAPSHOT + ${gzs-common.version} + + + com.cmcc.hy + gzs-common-sign + ${gzs-common.version} net.logstash.logback @@ -181,6 +192,10 @@ org.springframework.boot spring-boot-starter-undertow + + org.springframework.cloud + spring-cloud-starter-openfeign + com.mybatis-flex mybatis-flex-spring-boot3-starter @@ -261,6 +276,10 @@ com.cmcc.hy gzs-common-oss + + com.cmcc.hy + gzs-common-sign + net.logstash.logback logstash-logback-encoder diff --git a/src/main/java/com/cmcc/magent/config/MwCoreConfig.java b/src/main/java/com/cmcc/magent/config/MwCoreConfig.java new file mode 100644 index 0000000..c4b3a74 --- /dev/null +++ b/src/main/java/com/cmcc/magent/config/MwCoreConfig.java @@ -0,0 +1,19 @@ +package com.cmcc.magent.config; + +import com.cmcc.hy.gzs.common.sign.autoconfigure.EnableSign; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.Configuration; + +@Configuration +@RefreshScope +@ConfigurationProperties(prefix = "mw.core") +@Data +@EnableSign +public class MwCoreConfig { + + private String innerClientId = "mw-open-82hsbmz8"; + + private String innerClientSecret = "98rnk8pz6j08fp6q"; +} diff --git a/src/main/java/com/cmcc/magent/interceptor/MwSignRequestInterceptor.java b/src/main/java/com/cmcc/magent/interceptor/MwSignRequestInterceptor.java new file mode 100644 index 0000000..eb500cb --- /dev/null +++ b/src/main/java/com/cmcc/magent/interceptor/MwSignRequestInterceptor.java @@ -0,0 +1,20 @@ +package com.cmcc.magent.interceptor; + +import com.cmcc.hy.gzs.common.feign.GzsSignRequestInterceptor; +import com.cmcc.magent.config.MwCoreConfig; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +public class MwSignRequestInterceptor implements GzsSignRequestInterceptor { + private final MwCoreConfig mwCoreProperties; + + @Override + public String getClientId() { + return "::";//mwCoreProperties.getInnerClientId(); + } + + @Override + public String getClientSecret() { + return "::";//mwCoreProperties.getInnerClientSecret(); + } +} diff --git a/src/main/java/com/cmcc/magent/service/PlatformApiService.java b/src/main/java/com/cmcc/magent/service/PlatformApiService.java index c4d21b6..93116b7 100644 --- a/src/main/java/com/cmcc/magent/service/PlatformApiService.java +++ b/src/main/java/com/cmcc/magent/service/PlatformApiService.java @@ -1,6 +1,8 @@ package com.cmcc.magent.service; +import com.cmcc.magent.interceptor.MwSignRequestInterceptor; import com.cmcc.magent.pojo.po.RegisterAgent; +import org.springframework.cloud.openfeign.FeignClient; import java.io.IOException; @@ -14,6 +16,7 @@ import java.io.IOException; * @version 1.0.0 * @since 2025-01-07 */ +@FeignClient(name = "/mw/agent", url = "/mw/agent", configuration = MwSignRequestInterceptor.class) public interface PlatformApiService { /** diff --git a/src/main/java/com/cmcc/magent/service/impl/MiddlewareManagerServiceImpl.java b/src/main/java/com/cmcc/magent/service/impl/MiddlewareManagerServiceImpl.java index c65a0ba..9c05b1b 100644 --- a/src/main/java/com/cmcc/magent/service/impl/MiddlewareManagerServiceImpl.java +++ b/src/main/java/com/cmcc/magent/service/impl/MiddlewareManagerServiceImpl.java @@ -320,6 +320,12 @@ public class MiddlewareManagerServiceImpl implements MiddlewareManagerService { } runCommand(workDir, command); log.info("---- Task {} Finished", data.getUid()); + }).whenComplete((v, t) -> { + if (t != null) { + log.error("---- Task {} Finished With Exception: {}", data.getUid(), t.getMessage()); + } else { + log.info("---- Task {} Finished: {}", data.getUid(), v); + } }); } @@ -397,6 +403,12 @@ public class MiddlewareManagerServiceImpl implements MiddlewareManagerService { runCommand(workDir, cmd); log.info("---- Task {} Finished", data.getUid()); + }).whenComplete((v, t) -> { + if (t != null) { + log.error("---- Task {} Finished With Exception: {}", data.getUid(), t.getMessage()); + } else { + log.info("---- Task {} Finished: {}", data.getUid(), v); + } }); } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 7f3be19..64ad2e5 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -81,3 +81,21 @@ thread.max-pool-size=10 thread.queue-capacity=25 thread.name-prefix=Async- +# Can support profiles, databases, or remote +gzs.sign.client-details-enabled=true +gzs.sign.client-details.'yj-xx-1234567'=1234567 +# Permission: Specifies the interface corresponding to client_id. If the default value is empty, there is no restriction. +gzs.sign.perm.'yj-yy-1234567'=/xx/xx,/xx/yy + +# default can be configured in the rule-group, for example, gzs.sign.rule-.yj.mode =0 +# [Optional] 1: strict mode, 0: common mode (default) +gzs.sign.rule.default.mode=0 +# [Optional] Mandatory check list (In any mode, the following interfaces require check) +gzs.sign.rule.default.required-list=POST:/xxx/xx,*:/xxx/yy/** +# [Optional] Optional check list (In any mode, the following interfaces can be checked) +gzs.sign.rule.default.optional-list=GET:/xxx/xx,*:/xxx/yy/* + +# [Optional] If base64 encoding is used, you can configure whether base64 encoding for url security is required in the signature algorithm based on different client_id. The default value is true +#gzs.sign.base64-url-safe.def = true +#gzs.sign.base64-url-safe.'as-xx-1234567' = false + From 8223e294bd90357f97755692858f53fe0eb47dff Mon Sep 17 00:00:00 2001 From: HuangXin Date: Sat, 8 Mar 2025 10:34:50 +0800 Subject: [PATCH 2/7] =?UTF-8?q?OCT=20REM:=201.=20=E5=90=AF=E7=94=A8?= =?UTF-8?q?=E7=AD=BE=E5=90=8D=E9=AA=8C=E8=AF=81=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/cmcc/magent/config/MwCoreConfig.java | 21 ++++++++++++++++ .../interceptor/MwSignRequestInterceptor.java | 24 +++++++++++++++++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/cmcc/magent/config/MwCoreConfig.java b/src/main/java/com/cmcc/magent/config/MwCoreConfig.java index c4b3a74..a2c84af 100644 --- a/src/main/java/com/cmcc/magent/config/MwCoreConfig.java +++ b/src/main/java/com/cmcc/magent/config/MwCoreConfig.java @@ -6,6 +6,17 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Configuration; +/** + * MwCoreConfig类用于配置与中间件核心相关的属性。 + * + *

该类包含客户端ID和客户端密钥,用于与GZS服务进行身份验证。

+ * + *

该配置类会在Spring容器启动时加载,并支持动态刷新配置。

+ * + * @author huangxin@cmhi.chinamobile.com + * @version 1.0.0 + * @since 2025-03-07 + */ @Configuration @RefreshScope @ConfigurationProperties(prefix = "mw.core") @@ -13,7 +24,17 @@ import org.springframework.context.annotation.Configuration; @EnableSign public class MwCoreConfig { + /** + * 内部客户端ID。 + * + *

默认为"mw-open-82hsbmz8",可通过配置文件进行覆盖。

+ */ private String innerClientId = "mw-open-82hsbmz8"; + /** + * 内部客户端密钥。 + * + *

默认为"98rnk8pz6j08fp6q",可通过配置文件进行覆盖。

+ */ private String innerClientSecret = "98rnk8pz6j08fp6q"; } diff --git a/src/main/java/com/cmcc/magent/interceptor/MwSignRequestInterceptor.java b/src/main/java/com/cmcc/magent/interceptor/MwSignRequestInterceptor.java index eb500cb..645a6a6 100644 --- a/src/main/java/com/cmcc/magent/interceptor/MwSignRequestInterceptor.java +++ b/src/main/java/com/cmcc/magent/interceptor/MwSignRequestInterceptor.java @@ -4,17 +4,37 @@ import com.cmcc.hy.gzs.common.feign.GzsSignRequestInterceptor; import com.cmcc.magent.config.MwCoreConfig; import lombok.RequiredArgsConstructor; +/** + * MwSignRequestInterceptor类实现了GzsSignRequestInterceptor接口。 + * + *

该类用于拦截请求并提供客户端ID和客户端密钥,用于与GZS服务的身份验证。

+ * + * @author huangxin@cmhi.chinamobile.com + * @version 1.0.0 + * @since 2025-03-07 + */ @RequiredArgsConstructor public class MwSignRequestInterceptor implements GzsSignRequestInterceptor { + private final MwCoreConfig mwCoreProperties; + /** + * 获取客户端ID。 + * + * @return 客户端ID + */ @Override public String getClientId() { - return "::";//mwCoreProperties.getInnerClientId(); + return mwCoreProperties.getInnerClientId(); } + /** + * 获取客户端密钥。 + * + * @return 客户端密钥 + */ @Override public String getClientSecret() { - return "::";//mwCoreProperties.getInnerClientSecret(); + return mwCoreProperties.getInnerClientSecret(); } } From 0c35416d7dcf6a64e17dbfe3ab8bf056630bbc6a Mon Sep 17 00:00:00 2001 From: HuangXin Date: Sat, 8 Mar 2025 11:31:55 +0800 Subject: [PATCH 3/7] =?UTF-8?q?OCT=20REM:=201.=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=BC=82=E6=AD=A5=E6=A8=A1=E5=BC=8F=E4=B8=8B=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E9=83=A8=E7=BD=B2=E5=91=BD=E4=BB=A4=E6=89=A7?= =?UTF-8?q?=E8=A1=8C=E7=BB=93=E6=9E=9C=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../magent/service/PlatformApiService.java | 17 +++++-- .../impl/MiddlewareManagerServiceImpl.java | 10 +++- .../service/impl/PlatformApiServiceImpl.java | 50 +++++++++++++++++-- src/main/resources/application.properties | 2 +- 4 files changed, 68 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/cmcc/magent/service/PlatformApiService.java b/src/main/java/com/cmcc/magent/service/PlatformApiService.java index 93116b7..5b42cf5 100644 --- a/src/main/java/com/cmcc/magent/service/PlatformApiService.java +++ b/src/main/java/com/cmcc/magent/service/PlatformApiService.java @@ -4,8 +4,6 @@ import com.cmcc.magent.interceptor.MwSignRequestInterceptor; import com.cmcc.magent.pojo.po.RegisterAgent; import org.springframework.cloud.openfeign.FeignClient; -import java.io.IOException; - /** * PlatformApiService 接口定义了与平台 API 通信的核心服务功能。 *

@@ -27,7 +25,18 @@ public interface PlatformApiService { * * @param agent 包含代理注册信息的 {@link RegisterAgent} 对象 * @return 平台返回的结果,通常为一个 JSON 格式的字符串 - * @throws IOException 如果在处理 JSON 时发生错误 */ - String registerAgent(RegisterAgent agent) throws IOException; + String registerAgent(RegisterAgent agent); + + /** + * 回报部署任务结果。 + *

+ * 该方法用于想平台报告部署任务执行的结果。 + *

+ * + * @param deploymentId 部署任务ID + * @param status 部署任务执行结果:0(部署中),1(正常),2(不正常) + * @return 平台返回的结果,通常为一个 JSON 格式的字符串 + */ + String responseDeploymentResult(String deploymentId, int status); } diff --git a/src/main/java/com/cmcc/magent/service/impl/MiddlewareManagerServiceImpl.java b/src/main/java/com/cmcc/magent/service/impl/MiddlewareManagerServiceImpl.java index 9c05b1b..c217831 100644 --- a/src/main/java/com/cmcc/magent/service/impl/MiddlewareManagerServiceImpl.java +++ b/src/main/java/com/cmcc/magent/service/impl/MiddlewareManagerServiceImpl.java @@ -14,6 +14,7 @@ import com.cmcc.magent.misc.JsonUtils; import com.cmcc.magent.pojo.entry.MiddlewareData; import com.cmcc.magent.pojo.po.RemoteFileDetails; import com.cmcc.magent.service.MiddlewareManagerService; +import com.cmcc.magent.service.PlatformApiService; import com.fasterxml.jackson.core.JsonProcessingException; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; @@ -62,6 +63,9 @@ public class MiddlewareManagerServiceImpl implements MiddlewareManagerService { @Resource private OssFactory ossFactory; + @Resource + private PlatformApiService platformApiService; + /** * 根据命令获取对应的文件名。 * @@ -322,9 +326,10 @@ public class MiddlewareManagerServiceImpl implements MiddlewareManagerService { log.info("---- Task {} Finished", data.getUid()); }).whenComplete((v, t) -> { if (t != null) { + platformApiService.responseDeploymentResult(data.getUid(), 2); log.error("---- Task {} Finished With Exception: {}", data.getUid(), t.getMessage()); } else { - log.info("---- Task {} Finished: {}", data.getUid(), v); + log.info("---- Task {} Finished: {}", data.getUid(), platformApiService.responseDeploymentResult(data.getUid(), 1)); } }); } @@ -405,9 +410,10 @@ public class MiddlewareManagerServiceImpl implements MiddlewareManagerService { log.info("---- Task {} Finished", data.getUid()); }).whenComplete((v, t) -> { if (t != null) { + platformApiService.responseDeploymentResult(data.getUid(), 2); log.error("---- Task {} Finished With Exception: {}", data.getUid(), t.getMessage()); } else { - log.info("---- Task {} Finished: {}", data.getUid(), v); + log.info("---- Task {} Finished: {}", data.getUid(), platformApiService.responseDeploymentResult(data.getUid(), 1)); } }); } diff --git a/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java b/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java index 0933ae9..56e7471 100644 --- a/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java +++ b/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java @@ -6,9 +6,12 @@ import com.cmcc.magent.misc.JsonUtils; import com.cmcc.magent.pojo.po.RegisterAgent; import com.cmcc.magent.service.PlatformApiService; import jakarta.annotation.Resource; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; /** * PlatformApiServiceImpl 是 {@link PlatformApiService} 的具体实现类。 @@ -26,6 +29,7 @@ import java.io.IOException; * @since 2025 -01-07 */ @Service +@Slf4j public class PlatformApiServiceImpl implements PlatformApiService { @Resource private PlatformServiceConfig platformServiceConfig; @@ -39,11 +43,49 @@ public class PlatformApiServiceImpl implements PlatformApiService { * * @param agent 包含代理注册信息的 {@link RegisterAgent} 实例 * @return 平台返回的注册结果,通常为 JSON 格式的字符串 - * @throws IOException IO 异常 */ @Override - public String registerAgent(RegisterAgent agent) throws IOException { - String reqString = JsonUtils.getJson(agent); - return HttpClientUtils.postJson(platformServiceConfig + "/register", null, reqString, null); + public String registerAgent(RegisterAgent agent) { + + String result = ""; + + try { + String reqString = JsonUtils.getJson(agent); + result = HttpClientUtils.postJson(platformServiceConfig + "/register", null, reqString, null); + } catch (IOException e) { + log.error("Register agent client {} exception: {}", agent.getDeviceId(), e.getMessage()); + } + + return result; + } + + /** + * 回报部署任务结果。 + *

+ * 该方法用于想平台报告部署任务执行的结果。 + *

+ * + * @param deploymentId 部署任务ID + * @param status 部署任务执行结果:0(部署中),1(正常),2(不正常) + * @return 平台返回的结果,通常为一个 JSON 格式的字符串 + */ + @Override + public String responseDeploymentResult(String deploymentId, int status) { + Map headers = new HashMap<>(4); + headers.put("Content-Type", "application/x-www-form-urlencoded"); + + Map params = new HashMap<>(4); + params.put("deploymentId", deploymentId); + params.put("status", String.valueOf(status)); + + String result = ""; + + try { + result = HttpClientUtils.post(platformServiceConfig + "/innerapi/instance/update-status", headers, params, null); + } catch (IOException e) { + log.error("Report deployment {} result exception: {}", deploymentId, e.getMessage()); + } + + return result; } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 64ad2e5..05d77dc 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -67,7 +67,7 @@ protocol.crypto-type=0 # Platform Service # Manager Platform URL -service.platform-url=http://xajhuang.com:1300 +service.platform-url=https://172.21.44.35:50443/mw/core # APPID service.platform-appid=appid # cluster name From e74124c7eee32c5c14c919a18b6453cc091aa559 Mon Sep 17 00:00:00 2001 From: HuangXin Date: Mon, 10 Mar 2025 10:50:25 +0800 Subject: [PATCH 4/7] =?UTF-8?q?OCT=20REM:=201.=20=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E6=9C=8D=E5=8A=A1=E6=8E=A5=E5=8F=A3=E7=AD=BE?= =?UTF-8?q?=E5=90=8D=E8=81=94=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 17 ++++- .../magent/MiddlewareAgentApplication.java | 4 ++ .../com/cmcc/magent/config/MwCoreConfig.java | 6 +- .../magent/service/PlatformApiService.java | 40 ++++++----- .../service/impl/PlatformApiServiceImpl.java | 72 +++++++------------ src/main/resources/application.properties | 8 +-- .../magent/misc/ProtocolJsonUtilsTest.java | 1 + .../impl/ResourceUsageServiceImplTest.java | 3 + src/test/resources/application.properties | 4 +- 9 files changed, 85 insertions(+), 70 deletions(-) diff --git a/pom.xml b/pom.xml index 58f0ac5..2764994 100644 --- a/pom.xml +++ b/pom.xml @@ -29,7 +29,7 @@ 1.0.0 17 - 0.1.6-SNAPSHOT + 0.1.7-SNAPSHOT @@ -64,6 +64,11 @@ spring-cloud-starter-openfeign 4.2.0
+ + io.github.openfeign + feign-okhttp + 13.5 + org.springdoc springdoc-openapi-starter-webmvc-api @@ -195,6 +200,16 @@ org.springframework.cloud spring-cloud-starter-openfeign + + + commons-fileupload + commons-fileupload + + + + + io.github.openfeign + feign-okhttp com.mybatis-flex diff --git a/src/main/java/com/cmcc/magent/MiddlewareAgentApplication.java b/src/main/java/com/cmcc/magent/MiddlewareAgentApplication.java index fc3ad19..5e2b620 100644 --- a/src/main/java/com/cmcc/magent/MiddlewareAgentApplication.java +++ b/src/main/java/com/cmcc/magent/MiddlewareAgentApplication.java @@ -1,7 +1,9 @@ package com.cmcc.magent; +import com.cmcc.hy.gzs.common.sign.autoconfigure.EnableSign; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.scheduling.annotation.EnableScheduling; /** @@ -28,6 +30,8 @@ import org.springframework.scheduling.annotation.EnableScheduling; */ @SpringBootApplication @EnableScheduling +@EnableFeignClients +@EnableSign public class MiddlewareAgentApplication { /** diff --git a/src/main/java/com/cmcc/magent/config/MwCoreConfig.java b/src/main/java/com/cmcc/magent/config/MwCoreConfig.java index a2c84af..1e076e0 100644 --- a/src/main/java/com/cmcc/magent/config/MwCoreConfig.java +++ b/src/main/java/com/cmcc/magent/config/MwCoreConfig.java @@ -5,6 +5,7 @@ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; /** * MwCoreConfig类用于配置与中间件核心相关的属性。 @@ -17,11 +18,10 @@ import org.springframework.context.annotation.Configuration; * @version 1.0.0 * @since 2025-03-07 */ -@Configuration +@Component @RefreshScope -@ConfigurationProperties(prefix = "mw.core") +@ConfigurationProperties(prefix = "mw.agent") @Data -@EnableSign public class MwCoreConfig { /** diff --git a/src/main/java/com/cmcc/magent/service/PlatformApiService.java b/src/main/java/com/cmcc/magent/service/PlatformApiService.java index 5b42cf5..15d222e 100644 --- a/src/main/java/com/cmcc/magent/service/PlatformApiService.java +++ b/src/main/java/com/cmcc/magent/service/PlatformApiService.java @@ -1,8 +1,13 @@ package com.cmcc.magent.service; +import com.cmcc.hy.gzs.common.result.Result; import com.cmcc.magent.interceptor.MwSignRequestInterceptor; import com.cmcc.magent.pojo.po.RegisterAgent; import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; /** * PlatformApiService 接口定义了与平台 API 通信的核心服务功能。 @@ -14,29 +19,32 @@ import org.springframework.cloud.openfeign.FeignClient; * @version 1.0.0 * @since 2025-01-07 */ -@FeignClient(name = "/mw/agent", url = "/mw/agent", configuration = MwSignRequestInterceptor.class) +@FeignClient(name = "agent-portal-feign", + url = "${service.platform-url}", + path = "/mw/core", + configuration = MwSignRequestInterceptor.class) public interface PlatformApiService { /** - * 注册代理(Agent)。 - *

- * 该方法用于将代理实例注册到平台,并返回平台生成的响应结果。 - *

+ * 注册代理。 * - * @param agent 包含代理注册信息的 {@link RegisterAgent} 对象 - * @return 平台返回的结果,通常为一个 JSON 格式的字符串 + * @param agent 要注册的代理信息,包含代理的相关属性。 + * @return 返回一个 {@link Result} 对象,包含注册结果的状态和消息。 */ - String registerAgent(RegisterAgent agent); + @PostMapping(path = "/register", consumes = MediaType.APPLICATION_JSON_VALUE) + Result registerAgent(@RequestBody RegisterAgent agent); + /** - * 回报部署任务结果。 - *

- * 该方法用于想平台报告部署任务执行的结果。 - *

+ * 响应部署结果。 + * + *

该方法用于更新指定部署的状态,服务器将根据传入的状态信息进行相应处理。

+ * + * @param deploymentId 部署的唯一标识符,用于指定需要更新状态的部署。 + * @param status 部署状态,整数类型,表示当前部署的状态,如成功、失败等。 + * @return 返回一个 {@link Result} 对象,包含操作结果的状态和相关信息。 * - * @param deploymentId 部署任务ID - * @param status 部署任务执行结果:0(部署中),1(正常),2(不正常) - * @return 平台返回的结果,通常为一个 JSON 格式的字符串 */ - String responseDeploymentResult(String deploymentId, int status); + @PostMapping(path = "/innerapi/instance/update-status", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + Result responseDeploymentResult(@RequestParam("deploymentId") String deploymentId, @RequestParam("status") Integer status); } diff --git a/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java b/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java index 56e7471..229ba62 100644 --- a/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java +++ b/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java @@ -1,17 +1,13 @@ package com.cmcc.magent.service.impl; -import com.cmcc.magent.config.PlatformServiceConfig; -import com.cmcc.magent.misc.HttpClientUtils; -import com.cmcc.magent.misc.JsonUtils; +import com.cmcc.hy.gzs.common.result.Result; import com.cmcc.magent.pojo.po.RegisterAgent; import com.cmcc.magent.service.PlatformApiService; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; /** * PlatformApiServiceImpl 是 {@link PlatformApiService} 的具体实现类。 @@ -30,62 +26,48 @@ import java.util.Map; */ @Service @Slf4j -public class PlatformApiServiceImpl implements PlatformApiService { +public class PlatformApiServiceImpl { @Resource - private PlatformServiceConfig platformServiceConfig; + private PlatformApiService platformApiService; /** - * 注册代理(Agent)。 - *

- * 通过向平台 API 提供的注册接口("/register")发送 POST 请求,完成代理的注册操作。 - * 请求体为转换为 JSON 格式的 {@link RegisterAgent} 对象。 - *

+ * 注册代理。 * - * @param agent 包含代理注册信息的 {@link RegisterAgent} 实例 - * @return 平台返回的注册结果,通常为 JSON 格式的字符串 + * @param agent 要注册的代理信息,包含代理的相关属性。 + * @return 返回一个 {@link Result} 对象,包含注册结果的状态和消息。 */ - @Override - public String registerAgent(RegisterAgent agent) { - - String result = ""; + public Result registerAgent(@RequestBody RegisterAgent agent) { + Result s = null; try { - String reqString = JsonUtils.getJson(agent); - result = HttpClientUtils.postJson(platformServiceConfig + "/register", null, reqString, null); - } catch (IOException e) { + s = platformApiService.registerAgent(agent); + } catch (Exception e) { log.error("Register agent client {} exception: {}", agent.getDeviceId(), e.getMessage()); } - return result; + return s; } /** - * 回报部署任务结果。 - *

- * 该方法用于想平台报告部署任务执行的结果。 - *

+ * 响应部署结果。 + * + *

该方法用于更新指定部署的状态,服务器将根据传入的状态信息进行相应处理。

+ * + * @param deploymentId 部署的唯一标识符,用于指定需要更新状态的部署。 + * @param status 部署状态,整数类型,表示当前部署的状态,如成功、失败等。 + * @return 返回一个 {@link Result} 对象,包含操作结果的状态和相关信息。 * - * @param deploymentId 部署任务ID - * @param status 部署任务执行结果:0(部署中),1(正常),2(不正常) - * @return 平台返回的结果,通常为一个 JSON 格式的字符串 */ - @Override - public String responseDeploymentResult(String deploymentId, int status) { - Map headers = new HashMap<>(4); - headers.put("Content-Type", "application/x-www-form-urlencoded"); - - Map params = new HashMap<>(4); - params.put("deploymentId", deploymentId); - params.put("status", String.valueOf(status)); - - String result = ""; + public Result responseDeploymentResult(@RequestParam("deploymentId") String deploymentId, + @RequestParam("status") Integer status) { + Result s = null; try { - result = HttpClientUtils.post(platformServiceConfig + "/innerapi/instance/update-status", headers, params, null); - } catch (IOException e) { - log.error("Report deployment {} result exception: {}", deploymentId, e.getMessage()); + s = platformApiService.responseDeploymentResult(deploymentId, status); + } catch (Exception e) { + log.error("Register agent client {} exception: {}", deploymentId, e.getMessage()); } - return result; + return s; } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 05d77dc..4e450ea 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -83,17 +83,17 @@ thread.name-prefix=Async- # Can support profiles, databases, or remote gzs.sign.client-details-enabled=true -gzs.sign.client-details.'yj-xx-1234567'=1234567 +gzs.sign.client-details.'mw-open-82hsbmz8'=98rnk8pz6j08fp6q # Permission: Specifies the interface corresponding to client_id. If the default value is empty, there is no restriction. -gzs.sign.perm.'yj-yy-1234567'=/xx/xx,/xx/yy +#gzs.sign.perm.'yj-yy-1234567'=/xx/xx,/xx/yy # default can be configured in the rule-group, for example, gzs.sign.rule-.yj.mode =0 # [Optional] 1: strict mode, 0: common mode (default) -gzs.sign.rule.default.mode=0 +#gzs.sign.rule.default.mode=0 # [Optional] Mandatory check list (In any mode, the following interfaces require check) gzs.sign.rule.default.required-list=POST:/xxx/xx,*:/xxx/yy/** # [Optional] Optional check list (In any mode, the following interfaces can be checked) -gzs.sign.rule.default.optional-list=GET:/xxx/xx,*:/xxx/yy/* +#gzs.sign.rule.default.optional-list=GET:/xxx/xx,*:/xxx/yy/* # [Optional] If base64 encoding is used, you can configure whether base64 encoding for url security is required in the signature algorithm based on different client_id. The default value is true #gzs.sign.base64-url-safe.def = true diff --git a/src/test/java/com/cmcc/magent/misc/ProtocolJsonUtilsTest.java b/src/test/java/com/cmcc/magent/misc/ProtocolJsonUtilsTest.java index b81e464..a3f0936 100644 --- a/src/test/java/com/cmcc/magent/misc/ProtocolJsonUtilsTest.java +++ b/src/test/java/com/cmcc/magent/misc/ProtocolJsonUtilsTest.java @@ -48,6 +48,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; */ @SpringBootTest @DisplayName("ProtocolJsonUtils 测试类") +@SuppressWarnings("unchecked") public class ProtocolJsonUtilsTest { private ProtocolResp protocolResp; diff --git a/src/test/java/com/cmcc/magent/service/impl/ResourceUsageServiceImplTest.java b/src/test/java/com/cmcc/magent/service/impl/ResourceUsageServiceImplTest.java index a1e94b9..e6f4b98 100644 --- a/src/test/java/com/cmcc/magent/service/impl/ResourceUsageServiceImplTest.java +++ b/src/test/java/com/cmcc/magent/service/impl/ResourceUsageServiceImplTest.java @@ -82,6 +82,7 @@ public class ResourceUsageServiceImplTest { resourceUsageService.performTask(); + @SuppressWarnings("unchecked") CircularQueue resourceUsageQueue = (CircularQueue) ReflectionTestUtils.getField(resourceUsageService, "resourceUsageQueue"); assertNotNull(resourceUsageQueue, "Resource usage queue should not be null"); @@ -109,6 +110,7 @@ public class ResourceUsageServiceImplTest { resourceUsageService.performTask(); + @SuppressWarnings("unchecked") CircularQueue resourceUsageQueue = (CircularQueue) ReflectionTestUtils.getField(resourceUsageService, "resourceUsageQueue"); @@ -137,6 +139,7 @@ public class ResourceUsageServiceImplTest { resourceUsageService.performTask(); + @SuppressWarnings("unchecked") CircularQueue resourceUsageQueue = (CircularQueue) ReflectionTestUtils.getField(resourceUsageService, "resourceUsageQueue"); assertNotNull(resourceUsageQueue, "Resource usage queue should not be null"); diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 78440e4..616c4d4 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -56,7 +56,7 @@ protocol.crypto-type=0 # Platform Service # Manager Platform URL -service.platform-url=http://xajhuang.com:1300 +service.platform-url=http://xajhuang.com:3006/post # APPID service.platform-appid=appid # cluster name @@ -70,3 +70,5 @@ thread.max-pool-size=10 thread.queue-capacity=25 thread.name-prefix=Async- +gzs.sign.client-details-enabled=true +gzs.sign.client-details.'mw-open-82hsbmz8'=98rnk8pz6j08fp6q \ No newline at end of file From 0294b571fc2a9ac0fd9b7121e31c85ca1b5cfcf7 Mon Sep 17 00:00:00 2001 From: HuangXin Date: Mon, 10 Mar 2025 10:51:00 +0800 Subject: [PATCH 5/7] =?UTF-8?q?OCT=20REM:=201.=20=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=20PlatformApiServiceImpl=20=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../impl/PlatformApiServiceImplTest.java | 155 ++++++++---------- 1 file changed, 71 insertions(+), 84 deletions(-) diff --git a/src/test/java/com/cmcc/magent/service/impl/PlatformApiServiceImplTest.java b/src/test/java/com/cmcc/magent/service/impl/PlatformApiServiceImplTest.java index 5a7178a..f69880b 100644 --- a/src/test/java/com/cmcc/magent/service/impl/PlatformApiServiceImplTest.java +++ b/src/test/java/com/cmcc/magent/service/impl/PlatformApiServiceImplTest.java @@ -1,122 +1,109 @@ package com.cmcc.magent.service.impl; -import com.cmcc.magent.config.PlatformServiceConfig; -import com.cmcc.magent.misc.HttpClientUtils; -import com.cmcc.magent.misc.JsonUtils; +import com.cmcc.hy.gzs.common.result.Result; import com.cmcc.magent.pojo.po.RegisterAgent; -import jakarta.annotation.Resource; -import org.junit.jupiter.api.AfterEach; +import com.cmcc.magent.service.PlatformApiService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.mockito.MockedStatic; -import org.mockito.Mockito; +import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.springframework.boot.test.context.SpringBootTest; -import java.io.IOException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mockStatic; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; /** - * 单元测试类 {@code PlatformApiServiceImplTest} 用于测试 {@link PlatformApiServiceImpl} 的功能。 + * PlatformApiServiceImplTest 类用于测试 {@link PlatformApiServiceImpl} 的功能。 *

- * 测试的主要目标是确保 {@link PlatformApiServiceImpl#registerAgent(RegisterAgent)} 方法能够正常工作, + * 该测试类包含多个单元测试,验证与 {@link PlatformApiService} 相关的方法的正确性。 *

* - *

测试中使用了 {@code MockWebServer} 来模拟 HTTP 请求和响应,避免依赖实际的外部服务。

- * - *

主要验证内容包括:

- *
    - *
  • 是否正确构造了 HTTP 请求(如方法和路径)。
  • - *
  • 是否正确处理了 HTTP 响应并返回预期结果。
  • - *
- * - *

依赖注入说明:

- *
    - *
  • 通过 {@code @Resource} 注入被测试的 {@code PlatformApiServiceImpl}。
  • - *
  • 通过 {@code @Autowired} 注入 {@code WebClient.Builder},用于生成测试时专用的 {@code WebClient}。
  • - *
- * * @author huangxin@cmhi.chinamobile.com * @version 1.0.0 - * @since 2025-01-14 + * @since 2025-03-07 */ -@SpringBootTest -@DisplayName("平台服务接口") +@DisplayName("平台访问接口测试") public class PlatformApiServiceImplTest { - /** - * 被测试的服务类 {@link PlatformApiServiceImpl}。 - */ - @Resource - private PlatformApiServiceImpl platformApiService; + @Mock + private PlatformApiService platformApiService; - @Resource - private PlatformServiceConfig platformServiceConfig; - - private MockedStatic platformMock; - - private MockedStatic jsonMock; + @InjectMocks + private PlatformApiServiceImpl platformApiServiceimpl; /** - * 在每个测试前进行设置。 - * 创建 HttpClient 和响应的 Mock 对象,并初始化 Mockito。 - * + * 在每个测试之前初始化 Mockito 注解。 */ @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); - platformMock = mockStatic(HttpClientUtils.class, Mockito.CALLS_REAL_METHODS); - jsonMock = mockStatic(JsonUtils.class); } /** - * 在每个测试后清理资源。 - */ - @AfterEach - public void tearDown() { - platformMock.close(); - jsonMock.close(); - } - - /** - * 测试 {@link PlatformApiServiceImpl#registerAgent(RegisterAgent)} 方法。 - * - *

验证以下内容:

- *
    - *
  • 是否正确发送了 HTTP POST 请求到指定路径(如 {@code /register})。
  • - *
  • 是否正确处理了 HTTP 响应并返回预期的结果。
  • - *
- * - *

测试流程:

- *
    - *
  1. 设置 MockWebServer 的响应内容为 {@code {"message": "Hello, World!"}}。
  2. - *
  3. 使用测试数据(如 {@link RegisterAgent} 对象)调用 {@code registerAgent} 方法。
  4. - *
  5. 验证返回值是否等于设置的响应内容。
  6. - *
  7. 验证发送的请求是否符合预期(如方法为 POST,路径为 /register)。
  8. - *
+ * 测试在成功执行情况下,调用 responseDeploymentResult 方法返回结果。 * */ @Test - @DisplayName("设备注册接口测试") - void testFetchData() throws IOException { - // 准备模拟的 HTTP 响应 - String mockResponse = "Mocked Response"; + @DisplayName("部署结果响应成功") + public void responseDeploymentResult_SuccessfulExecution_ReturnsResult() { + String deploymentId = "12345"; + Integer status = 1; + Result expectedResponse = Result.success("Deployment updated successfully"); - final RegisterAgent agent = RegisterAgent.builder().deviceId("123542535").build(); + when(platformApiService.responseDeploymentResult(deploymentId, status)).thenReturn(expectedResponse); - jsonMock.when(() -> JsonUtils.getJson(any(Object.class))).thenReturn(mockResponse); + Result actualResponse = platformApiServiceimpl.responseDeploymentResult(deploymentId, status); - platformMock.when(() -> HttpClientUtils.postJson(platformServiceConfig + "/register", null, mockResponse, null)).thenReturn( - "Mocked Response"); + assertNotNull(actualResponse); + assertEquals(expectedResponse, actualResponse); + } - // 调用被测试方法 - final String result = platformApiService.registerAgent(agent); + /** + * 测试在调用 responseDeploymentResult 方法时抛出异常,返回 null。 + * + * @throws RuntimeException 可能抛出的异常 + */ + @Test + @DisplayName("部署结果响应异常") + public void responseDeploymentResult_ExceptionThrown_ReturnsNull() { + String deploymentId = "12345"; + Integer status = 1; - // 验证结果 - assertThat(result).isEqualTo(mockResponse); + when(platformApiService.responseDeploymentResult(deploymentId, status)).thenThrow(new RuntimeException("Service exception")); + + assertThrows(RuntimeException.class, () -> platformApiService.responseDeploymentResult(deploymentId, status)); + } + + /** + * 测试在成功注册情况下,调用 registerAgent 方法返回成功结果。 + * + */ + @Test + @DisplayName("注册代理成功") + public void registerAgent_SuccessfulRegistration_ReturnsSuccessResult() { + RegisterAgent agent = new RegisterAgent("1234567890"); + Result expected = Result.success("Registration successful"); + when(platformApiService.registerAgent(agent)).thenReturn(expected); + + Result actual = platformApiService.registerAgent(agent); + + assertEquals(expected, actual); + } + + /** + * 测试在调用 registerAgent 方法时抛出异常,返回 null。 + * + * @throws RuntimeException 可能抛出的异常 + */ + @Test + @DisplayName("注册代理异常") + public void registerAgent_ExceptionThrown_ReturnsNull() { + RegisterAgent agent = new RegisterAgent("1234567890"); + when(platformApiService.registerAgent(agent)).thenThrow(new RuntimeException("Registration failedxxxx")); + + assertThrows(RuntimeException.class, () -> platformApiService.registerAgent(agent)); } } From 45a9daa9cbdcf6b6a24058c85bc9683788db215c Mon Sep 17 00:00:00 2001 From: HuangXin Date: Mon, 10 Mar 2025 14:07:10 +0800 Subject: [PATCH 6/7] =?UTF-8?q?OCT=20REM:=201.=20=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=20PlatformApiService=20=E6=9C=8D=E5=8A=A1=20?= =?UTF-8?q?2.=20=E5=88=A0=E6=8E=89=E5=A4=9A=E4=BD=99=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E5=88=9D=E5=A7=8B=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/cmcc/magent/config/MwCoreConfig.java | 2 - .../PlatformApiFeignClientService.java | 52 ++++++++++++++ .../magent/service/PlatformApiService.java | 15 +--- .../service/impl/PlatformApiServiceImpl.java | 22 +++--- src/main/resources/db/agent.mv.db | Bin 20480 -> 0 bytes .../impl/PlatformApiServiceImplTest.java | 66 ++++++++++++++---- 6 files changed, 116 insertions(+), 41 deletions(-) create mode 100644 src/main/java/com/cmcc/magent/service/PlatformApiFeignClientService.java delete mode 100644 src/main/resources/db/agent.mv.db diff --git a/src/main/java/com/cmcc/magent/config/MwCoreConfig.java b/src/main/java/com/cmcc/magent/config/MwCoreConfig.java index 1e076e0..00df396 100644 --- a/src/main/java/com/cmcc/magent/config/MwCoreConfig.java +++ b/src/main/java/com/cmcc/magent/config/MwCoreConfig.java @@ -1,10 +1,8 @@ package com.cmcc.magent.config; -import com.cmcc.hy.gzs.common.sign.autoconfigure.EnableSign; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; /** diff --git a/src/main/java/com/cmcc/magent/service/PlatformApiFeignClientService.java b/src/main/java/com/cmcc/magent/service/PlatformApiFeignClientService.java new file mode 100644 index 0000000..d00b00c --- /dev/null +++ b/src/main/java/com/cmcc/magent/service/PlatformApiFeignClientService.java @@ -0,0 +1,52 @@ +package com.cmcc.magent.service; + +import com.cmcc.hy.gzs.common.result.Result; +import com.cmcc.magent.interceptor.MwSignRequestInterceptor; +import com.cmcc.magent.pojo.po.RegisterAgent; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * PlatformApiFeignClientService 接口定义了与平台 API 通信的核心服务功能。 + *

+ * 该接口包含与平台交互的关键操作,具体实现类负责与平台进行数据交互。 + *

+ * + * @author huangxin@cmhi.chinamobile.com + * @version 1.0.0 + * @since 2025-03-10 + */ +@FeignClient(name = "agent-portal-feign", + url = "${service.platform-url}", + path = "/mw/core", + configuration = MwSignRequestInterceptor.class) +public interface PlatformApiFeignClientService { + + /** + * 注册代理。 + * + * @param agent 要注册的代理信息,包含代理的相关属性。 + * @return 返回一个 {@link Result} 对象,包含注册结果的状态和消息。 + */ + @PostMapping(path = "/register", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + Result registerAgentFeign(@RequestBody RegisterAgent agent); + + + /** + * 响应部署结果。 + * + *

该方法用于更新指定部署的状态,服务器将根据传入的状态信息进行相应处理。

+ * + * @param deploymentId 部署的唯一标识符,用于指定需要更新状态的部署。 + * @param status 部署状态,整数类型,表示当前部署的状态,如成功、失败等。 + * @return 返回一个 {@link Result} 对象,包含操作结果的状态和相关信息。 + * + */ + @PostMapping(path = "/innerapi/instance/update-status", + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + Result responseDeploymentResultFeign(@RequestParam("deploymentId") String deploymentId, @RequestParam("status") Integer status); +} diff --git a/src/main/java/com/cmcc/magent/service/PlatformApiService.java b/src/main/java/com/cmcc/magent/service/PlatformApiService.java index 15d222e..ae3fe26 100644 --- a/src/main/java/com/cmcc/magent/service/PlatformApiService.java +++ b/src/main/java/com/cmcc/magent/service/PlatformApiService.java @@ -1,13 +1,8 @@ package com.cmcc.magent.service; import com.cmcc.hy.gzs.common.result.Result; -import com.cmcc.magent.interceptor.MwSignRequestInterceptor; import com.cmcc.magent.pojo.po.RegisterAgent; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; /** * PlatformApiService 接口定义了与平台 API 通信的核心服务功能。 @@ -19,22 +14,15 @@ import org.springframework.web.bind.annotation.RequestParam; * @version 1.0.0 * @since 2025-01-07 */ -@FeignClient(name = "agent-portal-feign", - url = "${service.platform-url}", - path = "/mw/core", - configuration = MwSignRequestInterceptor.class) public interface PlatformApiService { - /** * 注册代理。 * * @param agent 要注册的代理信息,包含代理的相关属性。 * @return 返回一个 {@link Result} 对象,包含注册结果的状态和消息。 */ - @PostMapping(path = "/register", consumes = MediaType.APPLICATION_JSON_VALUE) Result registerAgent(@RequestBody RegisterAgent agent); - /** * 响应部署结果。 * @@ -45,6 +33,5 @@ public interface PlatformApiService { * @return 返回一个 {@link Result} 对象,包含操作结果的状态和相关信息。 * */ - @PostMapping(path = "/innerapi/instance/update-status", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) - Result responseDeploymentResult(@RequestParam("deploymentId") String deploymentId, @RequestParam("status") Integer status); + Result responseDeploymentResult(String deploymentId, Integer status); } diff --git a/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java b/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java index 229ba62..64135c4 100644 --- a/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java +++ b/src/main/java/com/cmcc/magent/service/impl/PlatformApiServiceImpl.java @@ -2,15 +2,14 @@ package com.cmcc.magent.service.impl; import com.cmcc.hy.gzs.common.result.Result; import com.cmcc.magent.pojo.po.RegisterAgent; +import com.cmcc.magent.service.PlatformApiFeignClientService; import com.cmcc.magent.service.PlatformApiService; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; /** - * PlatformApiServiceImpl 是 {@link PlatformApiService} 的具体实现类。 + * PlatformApiServiceImpl 是 {@link PlatformApiFeignClientService} 的具体实现类。 *

* 该类使用 与平台 API 进行交互,提供了注册代理的功能。 *

@@ -26,9 +25,9 @@ import org.springframework.web.bind.annotation.RequestParam; */ @Service @Slf4j -public class PlatformApiServiceImpl { +public class PlatformApiServiceImpl implements PlatformApiService { @Resource - private PlatformApiService platformApiService; + private PlatformApiFeignClientService platformApiServiceFeign; /** * 注册代理。 @@ -36,11 +35,12 @@ public class PlatformApiServiceImpl { * @param agent 要注册的代理信息,包含代理的相关属性。 * @return 返回一个 {@link Result} 对象,包含注册结果的状态和消息。 */ - public Result registerAgent(@RequestBody RegisterAgent agent) { + @Override + public Result registerAgent(RegisterAgent agent) { Result s = null; try { - s = platformApiService.registerAgent(agent); + s = platformApiServiceFeign.registerAgentFeign(agent); } catch (Exception e) { log.error("Register agent client {} exception: {}", agent.getDeviceId(), e.getMessage()); } @@ -58,14 +58,14 @@ public class PlatformApiServiceImpl { * @return 返回一个 {@link Result} 对象,包含操作结果的状态和相关信息。 * */ - public Result responseDeploymentResult(@RequestParam("deploymentId") String deploymentId, - @RequestParam("status") Integer status) { + @Override + public Result responseDeploymentResult(String deploymentId, Integer status) { Result s = null; try { - s = platformApiService.responseDeploymentResult(deploymentId, status); + s = platformApiServiceFeign.responseDeploymentResultFeign(deploymentId, status); } catch (Exception e) { - log.error("Register agent client {} exception: {}", deploymentId, e.getMessage()); + log.error("Response deployment {} result exception: {}", deploymentId, e.getMessage()); } return s; diff --git a/src/main/resources/db/agent.mv.db b/src/main/resources/db/agent.mv.db deleted file mode 100644 index 81e605269f5d9f8f01f3fa34999296440fc9efd5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 20480 zcmeHP%WfOV6=lXh6?_0eeu>zK5Ip;n-A3iInId{VBDf0^0RH>?(I%Z1FA58}Kw4mgk zv&mU+G=ye;pH1DTY*H|Z#;{4f?UeWv2nYlO0s;YnfIvVXAP^7;2m}NI0s(=5K;XSV z;3&@fC&d#X_ZKrD#>U2kmODjEF+AD7*7hDZGl> ztx6MB4^iXTLX{`gmeoSpRxyiO#hQh79h>=vV|u#ony%~VyXdIcIzqeHw2ADSp5wp) z^NH@dn(8Z9r?O%wo})OfBU7R%4raD0+tg*A@5-vj9O}x7yo-wEdbM!}-9HIDEFW}B zwc}Q$TdvfKC+Jgr7onYhWg-_##nMrwjI828t%9>(B?< z?RmQ#-N1YpvpEM>&&n5s{~qOXB%+3V=04-X}H2@-D3?RH@q%bVEN2{k&JPTbvS z42^c)4cBrqq9bIFrqx!0P$!U*``=g5i8%|ePe-*s3 zo9<}n_fB7F08>ED*T9qb`NRg!ruO8O4ycs)9hKO|s{2RdS9Pz-0EFgfiPt0Ue!|vr zz{IWxeFt7F58!;*8-k5~|CL@Sy3sLwct0=Mh!#e5gJ_sVW%vwdpJ1uoY{J*kwW{?> z%PQ6%?JYfYm0+i%GT-h%VA1&N8V~M#d^)i`_C{tk4PJXqb>xKE?frY`&dwl;Ht}bk zh%|2&0AN^63w>6#ju1u%mD+LRVXJE$cX=GUk3QLHMm;`iR_hP}&<`pniB6-dUAWrS zvIyeS)uAtldi%TR-p)@X2;C4>)`*u7h0E|sG+I`(7(~l?5A%yb=Lrw@ct5DxC|8~& z+An&$2cw(D6HKED5tWCP7AnI8Q*D&2OZO-G)sPiO@$o(0EFAacRz9V=Oig1yG&UR6<(8^x zYqqS}wnf2L5TbuS!I6B~#KQLsBGFawI*CaT=3UO8V{XdOEe4+Tz?cPoh2D8nCII?|GX6 zoz3HLN5Y-@g%mR3cr~n&OEO}b>-V0sN1Po8toUWY2X-7>tHW`~lieKWzcggaMnIMo zs#7;4%Y?|e^Wpg!tfP&1b9h#q&fcFHlO~)(Gug|HT=#rz58aD`?Efb6kVflu!KVez zKKBrF56y&!K;1(wFNaR55v32Dl(DUwF{LMlY({>r@{DrN3`I$Lrb+mAlpJ8}k=w!I zVfZ7aNu%p<>>2Q29;8zH|Ag%2K`Q<2FL@S|{>!85%w~iwfxw4_z+(QrVl};Ec#3Wt z?lor92~*o~)Jw(^I*V{Y{_lQuK#Scaap((De~4R&4zA%4lK-@u{#z=2E0u|-q)a>` zX5y(VV??t=CZ0Jn@eGrRXSGZ`d1T_L^3G^-ntw|2gXd?Eu(7=7Z3r_+*zmip%wYop<5Z0sG3X6K`&Z;mWE0S*JdY5_hlg92r{djMntCRHpuHdwNKaap$?3IcOU3WH~%OJeF?r-p)W0{RzhEzOL#(GT0}tTOFrEd`jXI> zuF}`8Nnd)N`9~V`C9V)96(!2AT&*kFAAq`ar9Q-!sJZm?O^}POmdo(httLrSvVqqA zXXoEHQX8?Bgs;?)ejh0`c=j)<7qhClLKA986fbK?W|&ARVamk|uClKhTBISx(oA8l zCe2kEJkyUbS7|6HPD%Yp!rNSwBDU#~@DOwv93Q$kkZ4jr28rf7p;YtNNUHgBDAn9} zSX-j`;`HqiSj@lY3HAJ6)7y~$gHC!4iS!B+QU1TIB?by-pdSYLKfI)2{hzCPm&C%@ zWg07sfd&8y;fl`Q_!1}pH^w){H8LTPHFsb=kQoxqu5nXXe##Lk$3itY48}Jx2 zedf7uDH5!clD>n~`)d>uu6@MUZg5TAWLdp - * 该测试类包含多个单元测试,验证与 {@link PlatformApiService} 相关的方法的正确性。 + * 该测试类包含多个单元测试,验证与 {@link PlatformApiFeignClientService} 相关的方法的正确性。 *

* * @author huangxin@cmhi.chinamobile.com @@ -29,17 +37,39 @@ import static org.mockito.Mockito.when; public class PlatformApiServiceImplTest { @Mock - private PlatformApiService platformApiService; + private PlatformApiFeignClientService platformApiServiceFeign; @InjectMocks - private PlatformApiServiceImpl platformApiServiceimpl; + private PlatformApiServiceImpl platformApiService; + + private Logger logger; /** * 在每个测试之前初始化 Mockito 注解。 */ @BeforeEach - public void setUp() { + public void setUp() throws NoSuchFieldException, IllegalAccessException { MockitoAnnotations.openMocks(this); + + logger = mock(Logger.class); + + // 获取 MyService 的 Class 对象 + Class clazz = PlatformApiServiceImpl.class; + // 获取 log 字段 + Field logField = clazz.getDeclaredField("log"); + // 设置字段可访问 + logField.setAccessible(true); + // 获取 Unsafe 实例 + Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + Unsafe unsafe = (Unsafe) unsafeField.get(null); + // 获取 log 字段的偏移量 + long offset = unsafe.staticFieldOffset(logField); + // 获取 log 字段所属的类对象 + Object base = unsafe.staticFieldBase(logField); + + // 使用 Unsafe 修改 log 字段的值 + unsafe.putObject(base, offset, logger); } /** @@ -53,9 +83,9 @@ public class PlatformApiServiceImplTest { Integer status = 1; Result expectedResponse = Result.success("Deployment updated successfully"); - when(platformApiService.responseDeploymentResult(deploymentId, status)).thenReturn(expectedResponse); + when(platformApiServiceFeign.responseDeploymentResultFeign(deploymentId, status)).thenReturn(expectedResponse); - Result actualResponse = platformApiServiceimpl.responseDeploymentResult(deploymentId, status); + Result actualResponse = platformApiService.responseDeploymentResult(deploymentId, status); assertNotNull(actualResponse); assertEquals(expectedResponse, actualResponse); @@ -69,12 +99,16 @@ public class PlatformApiServiceImplTest { @Test @DisplayName("部署结果响应异常") public void responseDeploymentResult_ExceptionThrown_ReturnsNull() { - String deploymentId = "12345"; - Integer status = 1; + String deploymentId = "12345"; + Integer status = 1; + Exception e = new RuntimeException("Service exception"); - when(platformApiService.responseDeploymentResult(deploymentId, status)).thenThrow(new RuntimeException("Service exception")); + when(platformApiServiceFeign.responseDeploymentResultFeign(deploymentId, status)).thenThrow(e); - assertThrows(RuntimeException.class, () -> platformApiService.responseDeploymentResult(deploymentId, status)); + Result ret = platformApiService.responseDeploymentResult(deploymentId, status); + + assertNull(ret); + verify(logger).error(eq("Response deployment {} result exception: {}"), eq("12345"), eq(e.getMessage())); } /** @@ -86,7 +120,7 @@ public class PlatformApiServiceImplTest { public void registerAgent_SuccessfulRegistration_ReturnsSuccessResult() { RegisterAgent agent = new RegisterAgent("1234567890"); Result expected = Result.success("Registration successful"); - when(platformApiService.registerAgent(agent)).thenReturn(expected); + when(platformApiServiceFeign.registerAgentFeign(agent)).thenReturn(expected); Result actual = platformApiService.registerAgent(agent); @@ -102,8 +136,12 @@ public class PlatformApiServiceImplTest { @DisplayName("注册代理异常") public void registerAgent_ExceptionThrown_ReturnsNull() { RegisterAgent agent = new RegisterAgent("1234567890"); - when(platformApiService.registerAgent(agent)).thenThrow(new RuntimeException("Registration failedxxxx")); + Exception e = new RuntimeException("Registration failedxxxx"); + when(platformApiServiceFeign.registerAgentFeign(agent)).thenThrow(e); - assertThrows(RuntimeException.class, () -> platformApiService.registerAgent(agent)); + Result ret = platformApiService.registerAgent(agent); + + assertNull(ret); + verify(logger).error(eq("Register agent client {} exception: {}"), eq("1234567890"), eq(e.getMessage())); } } From 639bb2976221a6d6f18f699ff37abf37a75ccdfc Mon Sep 17 00:00:00 2001 From: HuangXin Date: Mon, 10 Mar 2025 14:07:40 +0800 Subject: [PATCH 7/7] =?UTF-8?q?OCT=20REM:=201.=20=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A3=80=E6=9F=A5=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/cmcc/magent/service/impl/PlatformApiServiceImplTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/com/cmcc/magent/service/impl/PlatformApiServiceImplTest.java b/src/test/java/com/cmcc/magent/service/impl/PlatformApiServiceImplTest.java index cf1c731..c01d97b 100644 --- a/src/test/java/com/cmcc/magent/service/impl/PlatformApiServiceImplTest.java +++ b/src/test/java/com/cmcc/magent/service/impl/PlatformApiServiceImplTest.java @@ -3,7 +3,6 @@ package com.cmcc.magent.service.impl; import com.cmcc.hy.gzs.common.result.Result; import com.cmcc.magent.pojo.po.RegisterAgent; import com.cmcc.magent.service.PlatformApiFeignClientService; -import com.cmcc.magent.service.PlatformApiService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test;