Skip to content

Commit 2866e4f

Browse files
committed
feat: (1)修复调用复杂度较高的warning问题
1 parent 4e2232a commit 2866e4f

File tree

2 files changed

+163
-103
lines changed

2 files changed

+163
-103
lines changed

volcengine-java-sdk-ark-runtime/src/main/java/com/volcengine/ark/runtime/interceptor/EncryptionInterceptor.java

Lines changed: 51 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@ private Response proceedWithEncryption(Chain chain, Request request, Map<String,
100100

101101
Response originalResponse = chain.proceed(encryptedRequest);
102102

103-
104103
// 处理失败响应
105104
if (!originalResponse.isSuccessful()) {
106105
return handleErrorResponse(originalResponse);
@@ -136,7 +135,6 @@ private Response proceedWithoutEncryption(Chain chain, Request request, Map<Stri
136135
return chain.proceed(modifiedRequest);
137136
}
138137

139-
140138
/**
141139
* 加密请求体内容
142140
*/
@@ -183,8 +181,7 @@ private Object processMessageContent(Object content, byte[] e2eKey, byte[] e2eNo
183181
if (content instanceof String) {
184182
// text
185183
return encryptStringWithKey(e2eKey, e2eNonce, (String) content);
186-
}
187-
else if (content instanceof Iterable) {
184+
} else if (content instanceof Iterable) {
188185
// multiParts
189186
List<Object> processedParts = new ArrayList<>();
190187
for (Object part : (Iterable<?>) content) {
@@ -197,8 +194,7 @@ else if (content instanceof Iterable) {
197194
}
198195
}
199196
return processedParts;
200-
}
201-
else {
197+
} else {
202198
throw new IOException("encryption is not supported for content type " + content.getClass().getSimpleName());
203199
}
204200
}
@@ -239,11 +235,9 @@ private void processImageUrl(Map<String, Object> imageUrl, byte[] e2eKey, byte[]
239235
if ("data".equals(scheme)) {
240236
// 加密data URL
241237
imageUrl.put("url", encryptStringWithKey(e2eKey, e2eNonce, url));
242-
}
243-
else if ("http".equals(scheme) || "https".equals(scheme)) {
238+
} else if ("http".equals(scheme) || "https".equals(scheme)) {
244239
System.err.println("encryption is not supported for image url, please use base64 image if you want encryption");
245-
}
246-
else {
240+
} else {
247241
throw new IOException("encryption is not supported for image url scheme " + scheme);
248242
}
249243

@@ -450,34 +444,60 @@ private String decryptStreamContent(byte[] key, byte[] nonce, String streamConte
450444
*/
451445
private Map<String, Object> decryptStreamChunk(byte[] key, byte[] nonce, Map<String, Object> chunkData) {
452446
try {
453-
if (chunkData.containsKey("choices") && chunkData.get("choices") instanceof List) {
454-
@SuppressWarnings("unchecked")
455-
List<Map<String, Object>> choices = (List<Map<String, Object>>) chunkData.get("choices");
456-
457-
for (Map<String, Object> choice : choices) {
458-
if (shouldDecryptStreamChoice(choice)) {
459-
String encryptedContent = getEncryptedContentFromStreamChoice(choice);
460-
if (encryptedContent != null && !encryptedContent.isEmpty()) {
461-
try {
462-
String decryptedContent = aesGcmDecryptBase64String(key, nonce, encryptedContent);
463-
@SuppressWarnings("unchecked")
464-
Map<String, Object> delta = (Map<String, Object>) choice.get("delta");
465-
delta.put("content", decryptedContent);
466-
} catch (Exception e) {
467-
@SuppressWarnings("unchecked")
468-
Map<String, Object> delta = (Map<String, Object>) choice.get("delta");
469-
delta.put("content", "");
470-
}
471-
}
472-
}
473-
}
447+
if (!hasValidChoices(chunkData)) {
448+
return chunkData;
474449
}
450+
451+
@SuppressWarnings("unchecked")
452+
List<Map<String, Object>> choices = (List<Map<String, Object>>) chunkData.get("choices");
453+
454+
for (Map<String, Object> choice : choices) {
455+
decryptStreamChoiceContent(key, nonce, choice);
456+
}
457+
475458
return chunkData;
476459
} catch (Exception e) {
477460
return chunkData;
478461
}
479462
}
480463

464+
/**
465+
* 检查chunk数据是否包含有效的choices
466+
*/
467+
private boolean hasValidChoices(Map<String, Object> chunkData) {
468+
return chunkData.containsKey("choices") && chunkData.get("choices") instanceof List;
469+
}
470+
471+
/**
472+
* 解密流式choice内容
473+
*/
474+
private void decryptStreamChoiceContent(byte[] key, byte[] nonce, Map<String, Object> choice) {
475+
if (!shouldDecryptStreamChoice(choice)) {
476+
return;
477+
}
478+
479+
String encryptedContent = getEncryptedContentFromStreamChoice(choice);
480+
if (encryptedContent == null || encryptedContent.isEmpty()) {
481+
return;
482+
}
483+
484+
try {
485+
String decryptedContent = aesGcmDecryptBase64String(key, nonce, encryptedContent);
486+
updateStreamChoiceContent(choice, decryptedContent);
487+
} catch (Exception e) {
488+
updateStreamChoiceContent(choice, "");
489+
}
490+
}
491+
492+
/**
493+
* 更新流式choice的内容
494+
*/
495+
private void updateStreamChoiceContent(Map<String, Object> choice, String content) {
496+
@SuppressWarnings("unchecked")
497+
Map<String, Object> delta = (Map<String, Object>) choice.get("delta");
498+
delta.put("content", content);
499+
}
500+
481501
/**
482502
* 判断是否为流式响应
483503
*/

volcengine-java-sdk-ark-runtime/src/main/java/com/volcengine/ark/runtime/service/CertificateManager.java

Lines changed: 112 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
import java.util.concurrent.ConcurrentHashMap;
2323
import java.util.regex.Pattern;
2424

25-
2625
public class CertificateManager {
2726
// 证书缓存
2827
private static final ConcurrentHashMap<String, ServerCertificateInfo> certificateCache = new ConcurrentHashMap<>();
@@ -52,8 +51,6 @@ public String getRingId() {
5251
public String getKeyId() {
5352
return keyId;
5453
}
55-
56-
5754
}
5855

5956
private static List<String> getDnsNamesFromExtension(Extension sanExtension) {
@@ -79,7 +76,6 @@ private static List<String> getDnsNamesFromExtension(Extension sanExtension) {
7976
* 检查内存缓存中是否存在证书
8077
*/
8178
public static boolean hasCertificateInCache(String ep) {
82-
// 假设有一个静态的ConcurrentHashMap来存储证书缓存
8379
return certificateCache.containsKey(ep);
8480
}
8581

@@ -93,7 +89,6 @@ public static ServerCertificateInfo getServerCertificateFromCache(String ep) {
9389
public static ServerCertificateInfo getServerCertificate(String apiKey, String baseUrl, String ep) throws IOException {
9490
// 首先检查内存缓存,用ep作为key
9591
if (hasCertificateInCache(ep)) {
96-
9792
return getServerCertificateFromCache(ep);
9893
}
9994

@@ -207,92 +202,139 @@ public static String loadCertificateLocally(String ep) throws IOException {
207202
return null;
208203
}
209204

210-
211205
/**
212-
* 使用API Key方式获取证书
206+
* 使用API Key方式获取证书 - 重构后降低复杂度
213207
*/
214208
public static String loadCertificateByApiKey(String baseUrl, String apiKey, String ep, boolean aiccEnabled) throws IOException {
215209
HttpURLConnection connection = null;
216210
try {
217-
// 修复URI构建问题
218-
String certificateUrl;
219-
if (baseUrl.endsWith("/")) {
220-
certificateUrl = baseUrl + "e2e/get/certificate";
221-
} else {
222-
certificateUrl = baseUrl + "/e2e/get/certificate";
211+
connection = createHttpConnection(baseUrl, apiKey);
212+
sendCertificateRequest(connection, ep, aiccEnabled);
213+
return processCertificateResponse(connection);
214+
} catch (IOException e) {
215+
throw e;
216+
} catch (Exception e) {
217+
String errMsg = "通过API Key获取证书失败: " + e.getMessage();
218+
throw new IOException(errMsg, e);
219+
} finally {
220+
if (connection != null) {
221+
connection.disconnect();
223222
}
223+
}
224+
}
224225

226+
/**
227+
* 创建HTTP连接
228+
*/
229+
private static HttpURLConnection createHttpConnection(String baseUrl, String apiKey) throws IOException {
230+
String certificateUrl = buildCertificateUrl(baseUrl);
231+
URL url = URI.create(certificateUrl).toURL();
232+
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
225233

226-
URL url = URI.create(certificateUrl).toURL();
227-
connection = (HttpURLConnection) url.openConnection();
234+
connection.setRequestMethod("POST");
235+
connection.setRequestProperty("Content-Type", "application/json");
236+
connection.setRequestProperty("Authorization", "Bearer " + apiKey);
237+
connection.setRequestProperty("X-Session-Token", "/e2e/get/certificate");
228238

229-
// 设置请求头
230-
connection.setRequestMethod("POST");
231-
connection.setRequestProperty("Content-Type", "application/json");
232-
connection.setRequestProperty("Authorization", "Bearer " + apiKey);
233-
connection.setRequestProperty("X-Session-Token", "/e2e/get/certificate");
239+
return connection;
240+
}
234241

235-
// 构建请求体
236-
Map<String, Object> requestBody = new HashMap<>();
237-
requestBody.put("model", ep);
238-
if (aiccEnabled) {
239-
requestBody.put("type", "AICCv0.1");
240-
}
241-
ObjectMapper mapper = new ObjectMapper();
242-
String jsonBody = mapper.writeValueAsString(requestBody);
242+
/**
243+
* 构建证书请求URL
244+
*/
245+
private static String buildCertificateUrl(String baseUrl) {
246+
if (baseUrl.endsWith("/")) {
247+
return baseUrl + "e2e/get/certificate";
248+
} else {
249+
return baseUrl + "/e2e/get/certificate";
250+
}
251+
}
252+
253+
/**
254+
* 发送证书请求
255+
*/
256+
private static void sendCertificateRequest(HttpURLConnection connection, String ep, boolean aiccEnabled) throws IOException {
257+
String jsonBody = buildRequestBody(ep, aiccEnabled);
243258

259+
connection.setDoOutput(true);
260+
try (OutputStream os = connection.getOutputStream()) {
261+
byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
262+
os.write(input, 0, input.length);
263+
}
264+
}
244265

245-
// 发送请求
246-
connection.setDoOutput(true);
247-
try (OutputStream os = connection.getOutputStream()) {
248-
byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
249-
os.write(input, 0, input.length);
250-
}
266+
/**
267+
* 构建请求体
268+
*/
269+
private static String buildRequestBody(String ep, boolean aiccEnabled) throws IOException {
270+
Map<String, Object> requestBody = new HashMap<>();
271+
requestBody.put("model", ep);
272+
if (aiccEnabled) {
273+
requestBody.put("type", "AICCv0.1");
274+
}
275+
ObjectMapper mapper = new ObjectMapper();
276+
return mapper.writeValueAsString(requestBody);
277+
}
251278

252-
// 处理响应
253-
int responseCode = connection.getResponseCode();
279+
/**
280+
* 处理证书响应
281+
*/
282+
private static String processCertificateResponse(HttpURLConnection connection) throws IOException {
283+
int responseCode = connection.getResponseCode();
254284

285+
if (!isSuccessfulResponse(responseCode)) {
286+
handleErrorResponse(connection, responseCode);
287+
}
255288

256-
if (responseCode >= 200 && responseCode < 300) {
257-
String responseBody = readResponseBody(connection);
289+
return extractCertificateFromResponse(connection);
290+
}
258291

292+
/**
293+
* 检查响应是否成功
294+
*/
295+
private static boolean isSuccessfulResponse(int responseCode) {
296+
return responseCode >= 200 && responseCode < 300;
297+
}
259298

260-
Map<String, Object> responseJson = mapper.readValue(
261-
responseBody,
262-
new TypeReference<HashMap<String, Object>>() {
263-
}
264-
);
299+
/**
300+
* 处理错误响应
301+
*/
302+
private static void handleErrorResponse(HttpURLConnection connection, int responseCode) throws IOException {
303+
String errorResponse = readErrorResponse(connection);
304+
String errorMsg = "证书请求失败,状态码: " + responseCode + ", 响应: " + errorResponse;
305+
throw new IOException(errorMsg);
306+
}
265307

266-
// 检查错误
267-
if (responseJson.containsKey("error")) {
268-
Object error = responseJson.get("error");
269-
String errorMsg = "获取证书失败: " + error;
270-
throw new IOException(errorMsg);
271-
}
308+
/**
309+
* 从响应中提取证书
310+
*/
311+
private static String extractCertificateFromResponse(HttpURLConnection connection) throws IOException {
312+
String responseBody = readResponseBody(connection);
313+
ObjectMapper mapper = new ObjectMapper();
272314

273-
if (responseJson.containsKey("Certificate")) {
274-
return (String) responseJson.get("Certificate");
275-
} else {
276-
String errorMsg = "响应中未找到Certificate字段";
277-
throw new IOException(errorMsg);
315+
Map<String, Object> responseJson = mapper.readValue(
316+
responseBody,
317+
new TypeReference<HashMap<String, Object>>() {
278318
}
279-
} else {
280-
String errorResponse = readErrorResponse(connection);
281-
String errorMsg = "证书请求失败,状态码: " + responseCode + ", 响应: " + errorResponse;
282-
throw new IOException(errorMsg);
283-
}
319+
);
284320

285-
} catch (Exception e) {
286-
if (e instanceof IOException) {
287-
throw (IOException) e;
288-
} else {
289-
String errMsg = "通过API Key获取证书失败: " + e.getMessage();
290-
throw new IOException(errMsg, e);
291-
}
292-
} finally {
293-
if (connection != null) {
294-
connection.disconnect();
295-
}
321+
validateResponse(responseJson);
322+
323+
if (responseJson.containsKey("Certificate")) {
324+
return (String) responseJson.get("Certificate");
325+
} else {
326+
throw new IOException("响应中未找到Certificate字段");
327+
}
328+
}
329+
330+
/**
331+
* 验证响应数据
332+
*/
333+
private static void validateResponse(Map<String, Object> responseJson) throws IOException {
334+
if (responseJson.containsKey("error")) {
335+
Object error = responseJson.get("error");
336+
String errorMsg = "获取证书失败: " + error;
337+
throw new IOException(errorMsg);
296338
}
297339
}
298340

@@ -342,7 +384,6 @@ public static void cacheServerCertificate(String cacheKey, PublicKey publicKey,
342384

343385
/**
344386
* 从PEM格式的X.509证书中提取公钥
345-
*
346387
*/
347388
public static PublicKey extractPublicKeyFromCertificate(String certificate) throws GeneralSecurityException {
348389
try {
@@ -422,5 +463,4 @@ public static String readErrorResponse(HttpURLConnection connection) throws IOEx
422463
return errorResponse.toString();
423464
}
424465
}
425-
426466
}

0 commit comments

Comments
 (0)