From e03505135d9816c8b6ea67a91a7e1f493e662b6f Mon Sep 17 00:00:00 2001
From: houzhongjian <houzhongyi@126.com>
Date: 星期三, 12 三月 2025 14:53:08 +0800
Subject: [PATCH] 修改Client封装方式

---
 iailab-plat-sdk/src/main/java/com/iailab/sdk/IailabPlatSdkMain.java                      |    3 
 iailab-plat-sdk/src/main/resources/auth.yaml                                             |   10 ++
 /dev/null                                                                                |    4 
 iailab-plat-sdk/pom.xml                                                                  |   10 +
 iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/client/dto/ApiDataQueryDTO.java        |   36 +++++++
 iailab-plat-sdk/src/main/java/com/iailab/sdk/util/http/IailabHttpUtils.java              |   12 -
 iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/factory/YamlPropertySourceFactory.java |   16 +++
 iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/client/IailabAuthClient.java           |   90 ++++++++++++++---
 iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/config/SdkAutoConfiguration.java       |   55 +++++++++-
 iailab-plat-sdk/src/test/java/com/iailab/sdk/IailabClientTest.java                       |   35 +++++-
 10 files changed, 226 insertions(+), 45 deletions(-)

diff --git a/iailab-plat-sdk/pom.xml b/iailab-plat-sdk/pom.xml
index e43ea81..372b7eb 100644
--- a/iailab-plat-sdk/pom.xml
+++ b/iailab-plat-sdk/pom.xml
@@ -42,8 +42,14 @@
             <artifactId>hibernate-validator</artifactId>
         </dependency>
         <dependency>
-            <groupId>com.iailab</groupId>
-            <artifactId>iailab-common-test</artifactId>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>4.13.2</version>
+            <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
diff --git a/iailab-plat-sdk/src/main/java/com/iailab/sdk/IailabPlatSdkMain.java b/iailab-plat-sdk/src/main/java/com/iailab/sdk/IailabPlatSdkMain.java
index 9b62bc7..ae4e07f 100644
--- a/iailab-plat-sdk/src/main/java/com/iailab/sdk/IailabPlatSdkMain.java
+++ b/iailab-plat-sdk/src/main/java/com/iailab/sdk/IailabPlatSdkMain.java
@@ -1,10 +1,13 @@
 package com.iailab.sdk;
 
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
 /**
  * 项目的主类
  *
  * @author iailab
  */
+@SpringBootApplication
 public class IailabPlatSdkMain {
 
     public static void main(String[] args) {
diff --git a/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/client/IailabAuthClient.java b/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/client/IailabAuthClient.java
index 17c088b..0a25789 100644
--- a/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/client/IailabAuthClient.java
+++ b/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/client/IailabAuthClient.java
@@ -1,18 +1,19 @@
 package com.iailab.sdk.auth.client;
 
 import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.iailab.sdk.auth.client.dto.ApiDataQueryDTO;
 import com.iailab.sdk.auth.client.dto.TokenDTO;
-import com.iailab.sdk.auth.config.AuthProperties;
+import com.iailab.sdk.auth.config.SdkAutoConfiguration;
 import com.iailab.sdk.auth.constants.SdkErrorCodeConstants;
 import com.iailab.sdk.util.http.IailabHttpUtils;
 import org.springframework.core.ParameterizedTypeReference;
 import org.springframework.http.*;
-import org.springframework.stereotype.Component;
-import org.springframework.stereotype.Service;
 import org.springframework.util.Assert;
 import org.springframework.util.Base64Utils;
 import org.springframework.util.ObjectUtils;
+import org.springframework.util.StringUtils;
 import org.springframework.web.client.RestTemplate;
 
 import java.nio.charset.StandardCharsets;
@@ -25,17 +26,28 @@
  * @Description
  * @createTime 2025年02月18日
  */
-@Component
-@Service
 public class IailabAuthClient {
 
     private static final RestTemplate restTemplate = new RestTemplate();
 
-    private static AuthProperties authProperties;
 
-    public static void setAuthProperties(AuthProperties properties) {
-        authProperties = properties;
-    }
+    /**
+     * 平台地址
+     */
+    public static String BASE_URL = SdkAutoConfiguration.BASE_URL;
+
+    /**
+     * 租户编号
+     */
+    public static Long TENANT_ID = SdkAutoConfiguration.TENANT_ID;
+
+    /**
+     * 客户端信息
+     */
+    private static String CLIENT_ID = SdkAutoConfiguration.CLIENT_ID;
+    private static String CLIENT_SECRET = SdkAutoConfiguration.CLIENT_SECRET;
+    private static String USERNAME = SdkAutoConfiguration.USERNAME;
+    private static String PASSWORD = SdkAutoConfiguration.PASSWORD;
 
     private static final String GRAND_TYPE = "password";
 
@@ -43,12 +55,22 @@
 
     private static final String CHARSET = "utf-8";
 
+    private static final IailabAuthClient iailabAuthClient = new IailabAuthClient();
+
+    public static IailabAuthClient getInstance() {
+        return iailabAuthClient;
+    }
+
+
     // 鉴权token
     public static String accessToken;
     // 刷新token
     public static String refreshToken;
     // 鉴权token过期时间
     public static Long expireTime;
+
+    private static final String RESP_CODE = "code";
+    private static final String RESP_DATA = "data";
 
     /**
      * 用户名密码方式获取平台token
@@ -60,12 +82,11 @@
         addClientHeader(headers);
         headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
         // 1.2 构建authenticate请求URL
-        // 1.2 构建authenticate请求URL
-        String authenticateUrl = authProperties.getBaseUrl() + "/system/oauth2/token?"
+        String authenticateUrl = BASE_URL + "/system/oauth2/token?"
                 // 密码模式的参数
                 + "&grant_type=" + GRAND_TYPE
-                + "&username=" + authProperties.getUsername()
-                + "&password=" + authProperties.getPassword()
+                + "&username=" + USERNAME
+                + "&password=" + PASSWORD
                 + "&scope=" + SCOPE;
         // 2. 执行请求
         ResponseEntity<Map<String, Object>> exchange = restTemplate.exchange(
@@ -102,7 +123,7 @@
         HttpHeaders headers = new HttpHeaders();
         addClientHeader(headers);
         // 1.2 构建authenticate请求URL
-        String authenticateUrl = authProperties.getBaseUrl() + "/system/auth/client-refresh-token?refreshToken=" + refreshToken+ "&clientId=" + authProperties.getClientId();
+        String authenticateUrl = BASE_URL + "/system/auth/client-refresh-token?refreshToken=" + refreshToken + "&clientId=" + CLIENT_ID;
         // 2. 执行请求
         ResponseEntity<Map<String, Object>> exchange = restTemplate.exchange(
                 authenticateUrl,
@@ -149,11 +170,11 @@
 
     private static void addClientHeader(HttpHeaders headers) {
         // client 拼接,需要 BASE64 编码
-        String client = authProperties.getClientId() + ":" + authProperties.getClientSecret();
+        String client = CLIENT_ID + ":" + CLIENT_SECRET;
         client = Base64Utils.encodeToString(client.getBytes(StandardCharsets.UTF_8));
         headers.add("Authorization", "Basic " + client);
         headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
-        headers.set("tenant-id", authProperties.getTenantId());
+        headers.set("tenant-id", TENANT_ID.toString());
     }
 
     // 统一处理响应
@@ -168,4 +189,41 @@
         return authTokenDTO;
     }
 
+    /**
+     * 查询计划chart (测试用)
+     * @param apiDataQueryDTO
+     * @return
+     * @throws Exception
+     */
+    public Map<String, Object> queryPlanChart(ApiDataQueryDTO apiDataQueryDTO) throws Exception {
+        Map<String, Object> data = new HashMap<>();
+        ObjectMapper objectMapper = new ObjectMapper();
+        String jsonString = objectMapper.writeValueAsString(apiDataQueryDTO);
+        String resp = IailabHttpUtils.doPost(BASE_URL + "/data/api/query-plans/chart", jsonString, "utf-8");
+        if (StringUtils.isEmpty(resp)) {
+            return data;
+        }
+        JSONObject jsonObject = JSON.parseObject(resp);
+        data = jsonObject.getJSONObject(RESP_DATA).toJavaObject(Map.class);
+        return data;
+    }
+
+    /**
+     * 查询多个测点当前值
+     *
+     * @param pointNos
+     * @return
+     */
+    public Map<String, Object> queryPointsRealValue(List<String> pointNos) throws Exception {
+        Map<String, Object> data = new HashMap<>();
+        String url = BASE_URL + "/data/api/query-points/real-value";
+        String resp = IailabHttpUtils.doPost(url, JSON.toJSONString(pointNos), "UTF-8");
+        if (StringUtils.isEmpty(resp)) {
+            return data;
+        }
+        JSONObject jsonObject = JSON.parseObject(resp);
+        data = jsonObject.getJSONObject(RESP_DATA).toJavaObject(Map.class);
+        return data;
+    }
+
 }
\ No newline at end of file
diff --git a/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/client/dto/ApiDataQueryDTO.java b/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/client/dto/ApiDataQueryDTO.java
new file mode 100644
index 0000000..cacade6
--- /dev/null
+++ b/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/client/dto/ApiDataQueryDTO.java
@@ -0,0 +1,36 @@
+package com.iailab.sdk.auth.client.dto;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import lombok.Data;
+
+import javax.validation.constraints.NotNull;
+import java.io.Serializable;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * @author PanZhibao
+ * @Description
+ * @createTime 2024年11月03日
+ */
+@Data
+public class ApiDataQueryDTO implements Serializable {
+    private static final long serialVersionUID = 1L;
+
+    @NotNull(message="itemNo不能为空")
+    private String itemNo;
+
+    @NotNull(message="itemNo不能为空")
+    private List<String> itemNos;
+
+    @NotNull(message="粒度不能为空")
+    private Integer granularity;
+
+    @NotNull(message="start不能为空")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date start;
+
+    @NotNull(message="end不能为空")
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date end;
+}
\ No newline at end of file
diff --git a/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/config/AuthProperties.java b/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/config/AuthProperties.java
deleted file mode 100644
index 08a8d60..0000000
--- a/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/config/AuthProperties.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.iailab.sdk.auth.config;
-
-import lombok.Data;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-
-@ConfigurationProperties(prefix = "iailab.token")
-@Data
-public class AuthProperties {
-    private String baseUrl;
-    private String tenantId;
-    private String username;
-    private String password;
-    private String clientId;
-    private String clientSecret;
-}
\ No newline at end of file
diff --git a/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/config/SdkAutoConfiguration.java b/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/config/SdkAutoConfiguration.java
index b9cf3fe..651da56 100644
--- a/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/config/SdkAutoConfiguration.java
+++ b/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/config/SdkAutoConfiguration.java
@@ -1,28 +1,67 @@
 package com.iailab.sdk.auth.config;
 
 import com.iailab.sdk.auth.client.IailabAuthClient;
+import com.iailab.sdk.auth.factory.YamlPropertySourceFactory;
 import com.iailab.sdk.util.http.IailabHttpUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
 import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
+import org.springframework.core.io.ClassPathResource;
 
 import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
 
 
 /**
  * SDK配置文件
  */
 @Configuration
-@EnableConfigurationProperties(AuthProperties.class)
+@PropertySource(
+        value = "classpath:auth.yaml",
+        factory = YamlPropertySourceFactory.class  // 使用自定义加载器
+)
 public class SdkAutoConfiguration {
-    private final AuthProperties authProperties;
+    @Value("${iailab.token.base-url}")
+    private String baseUrl;
 
-    public SdkAutoConfiguration(AuthProperties authProperties) {
-        this.authProperties = authProperties;
-    }
+    @Value("${iailab.token.tenant-id}")
+    public Long tenantId;
+
+    @Value("${iailab.token.client-id}")
+    public String clientId;
+
+    @Value("${iailab.token.client-secret}")
+    public String clientSecret;
+
+    @Value("${iailab.token.username}")
+    public String username;
+
+    @Value("${iailab.token.password}")
+    public String password;
+
+    public static String BASE_URL;
+
+    public static Long TENANT_ID;
+
+    public static String CLIENT_ID;
+
+    public static String CLIENT_SECRET;
+
+    public static String USERNAME;
+
+    public static String PASSWORD;
 
     @PostConstruct
-    public void init() {
-        IailabAuthClient.setAuthProperties(authProperties);
-        IailabHttpUtils.setAuthProperties(authProperties);
+    public void initUrl() {
+        BASE_URL = this.baseUrl;
+        TENANT_ID = this.tenantId;
+        CLIENT_ID = this.clientId;
+        CLIENT_SECRET = this.clientSecret;
+        USERNAME = this.username;
+        PASSWORD = this.password;
     }
 }
diff --git a/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/factory/YamlPropertySourceFactory.java b/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/factory/YamlPropertySourceFactory.java
new file mode 100644
index 0000000..fb057e7
--- /dev/null
+++ b/iailab-plat-sdk/src/main/java/com/iailab/sdk/auth/factory/YamlPropertySourceFactory.java
@@ -0,0 +1,16 @@
+package com.iailab.sdk.auth.factory;
+
+import org.springframework.boot.env.YamlPropertySourceLoader;
+import org.springframework.core.env.PropertySource;
+import org.springframework.core.io.support.EncodedResource;
+import org.springframework.core.io.support.PropertySourceFactory;
+
+import java.io.IOException;
+
+public class YamlPropertySourceFactory implements PropertySourceFactory {
+    @Override
+    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
+        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
+        return loader.load(resource.getResource().getFilename(), resource.getResource()).get(0);
+    }
+}
\ No newline at end of file
diff --git a/iailab-plat-sdk/src/main/java/com/iailab/sdk/util/http/IailabHttpUtils.java b/iailab-plat-sdk/src/main/java/com/iailab/sdk/util/http/IailabHttpUtils.java
index f59f119..ad149fb 100644
--- a/iailab-plat-sdk/src/main/java/com/iailab/sdk/util/http/IailabHttpUtils.java
+++ b/iailab-plat-sdk/src/main/java/com/iailab/sdk/util/http/IailabHttpUtils.java
@@ -1,7 +1,7 @@
 package com.iailab.sdk.util.http;
 
 import com.iailab.sdk.auth.client.IailabAuthClient;
-import com.iailab.sdk.auth.config.AuthProperties;
+import com.iailab.sdk.auth.config.SdkAutoConfiguration;
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.client.methods.HttpGet;
@@ -17,12 +17,6 @@
 
 
 public class IailabHttpUtils {
-
-    private static AuthProperties authProperties;
-
-    public static void setAuthProperties(AuthProperties properties) {
-        authProperties = properties;
-    }
 
     /**
      *
@@ -61,7 +55,7 @@
             httpGet.addHeader("Accept", "application/json");
             httpGet.addHeader("Content-Type", "application/json;charset=UTF-8");
             httpGet.addHeader("Authorization", "Bearer " + IailabAuthClient.accessToken);
-            httpGet.addHeader("Tenant-Id", String.valueOf(authProperties.getTenantId()));
+            httpGet.addHeader("Tenant-Id", SdkAutoConfiguration.TENANT_ID.toString());
             HttpResponse response = httpClient.execute(httpGet);
             if (response != null) {
                 HttpEntity resEntity = response.getEntity();
@@ -95,7 +89,7 @@
             httpPost.addHeader("Accept", "application/json");
             httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
             httpPost.addHeader("Authorization", "Bearer " + IailabAuthClient.accessToken);
-            httpPost.addHeader("Tenant-Id", String.valueOf(authProperties.getTenantId()));
+            httpPost.addHeader("Tenant-Id", SdkAutoConfiguration.TENANT_ID.toString());
             StringEntity stringEntity = new StringEntity(json);
             stringEntity.setContentEncoding("UTF-8");
             stringEntity.setContentType("application/json");
diff --git a/iailab-plat-sdk/src/main/resources/application.yaml b/iailab-plat-sdk/src/main/resources/application.yaml
deleted file mode 100644
index 6adf8aa..0000000
--- a/iailab-plat-sdk/src/main/resources/application.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
-#spring:
-#  application:
-#    name: sdk
-#
diff --git a/iailab-plat-sdk/src/main/resources/auth.yaml b/iailab-plat-sdk/src/main/resources/auth.yaml
new file mode 100644
index 0000000..4c59ca7
--- /dev/null
+++ b/iailab-plat-sdk/src/main/resources/auth.yaml
@@ -0,0 +1,10 @@
+# 平台配置项,设置当前项目所有自定义的配置,token中的配置需要事先在平台配置好
+iailab:
+  token:
+    base-url: http://172.16.8.100/admin-api #平台接口url,使用时需修改成真实的ip和端口
+    tenant-id: 172 #租户id
+    client-id: shasteel #租户OAuth2客户端id
+    client-secret: shasteel111111111111111 #租户OAuth2客户端密钥
+    username: shasteel #租户登录账号
+    password: 123456 #租户登录密码
+
diff --git a/iailab-plat-sdk/src/test/java/com/iailab/sdk/IailabClientTest.java b/iailab-plat-sdk/src/test/java/com/iailab/sdk/IailabClientTest.java
index 9ca7867..82fb308 100644
--- a/iailab-plat-sdk/src/test/java/com/iailab/sdk/IailabClientTest.java
+++ b/iailab-plat-sdk/src/test/java/com/iailab/sdk/IailabClientTest.java
@@ -1,12 +1,13 @@
 package com.iailab.sdk;
 
-import com.iailab.framework.test.core.ut.BaseMockitoUnitTest;
 import com.iailab.sdk.auth.client.IailabAuthClient;
-import com.iailab.sdk.auth.client.dto.TokenDTO;
-import com.iailab.sdk.auth.client.vo.AuthLoginReqVO;
-import org.junit.jupiter.api.Test;
+import com.iailab.sdk.auth.client.dto.ApiDataQueryDTO;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
 
-import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -18,7 +19,9 @@
  *
  * @author iailab
  */
-public class IailabClientTest extends BaseMockitoUnitTest {
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class IailabClientTest {
 
     @Test
     public void testLogin() {
@@ -44,5 +47,25 @@
         System.out.println(s);
     }
 
+    @Test
+    public void testQueryPlanChart() throws Exception {
+        ApiDataQueryDTO apiDataQueryDTO = new ApiDataQueryDTO();
+        List<String> itemNos = new ArrayList<>();
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        apiDataQueryDTO.setStart(sdf.parse("2024-06-11 07:24:00"));
+        apiDataQueryDTO.setEnd(sdf.parse("2024-06-13 00:00:00"));
+        itemNos.add("P0000100010");
+        apiDataQueryDTO.setItemNos(itemNos);
+        Map<String, Object> stringObjectMap = IailabAuthClient.getInstance().queryPlanChart(apiDataQueryDTO);
+        System.out.println(stringObjectMap);
+    }
+
+    @Test
+    public void testQueryPointsRealValue() throws Exception {
+        List<String> pointNos = new ArrayList<>();
+        pointNos.add("111");
+        Map<String, Object> stringObjectMap = IailabAuthClient.getInstance().queryPointsRealValue(pointNos);
+        System.out.println(stringObjectMap);
+    }
 
 }

--
Gitblit v1.9.3