Skip to content

Commit 773052b

Browse files
author
wlanboy
committed
Refactor methods, added tests
1 parent 97a8ae3 commit 773052b

File tree

7 files changed

+1008
-38
lines changed

7 files changed

+1008
-38
lines changed

src/main/java/com/wlanboy/javahttpclient/client/ClientService.java

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@
1717
import org.springframework.http.HttpHeaders;
1818
import org.springframework.http.ResponseEntity;
1919
import org.springframework.stereotype.Service;
20-
import org.springframework.util.CollectionUtils;
21-
import org.springframework.util.MultiValueMap;
2220

2321
import com.wlanboy.javahttpclient.controller.JavaHttpRequest;
2422

@@ -40,15 +38,20 @@ public ClientService() {
4038

4139
public ResponseEntity<String> sendRequest(JavaHttpRequest requestData, HttpHeaders incomingHeaders) {
4240
try {
43-
HttpRequest.BodyPublisher bodyPublisher = (requestData.body() == null || requestData.body().isBlank())
44-
? HttpRequest.BodyPublishers.noBody()
45-
: HttpRequest.BodyPublishers.ofString(requestData.body());
41+
boolean hasBody = requestData.body() != null && !requestData.body().isBlank();
42+
43+
HttpRequest.BodyPublisher bodyPublisher = hasBody
44+
? HttpRequest.BodyPublishers.ofString(requestData.body())
45+
: HttpRequest.BodyPublishers.noBody();
4646

4747
HttpRequest.Builder builder = HttpRequest.newBuilder()
4848
.uri(URI.create(requestData.url()))
49+
.timeout(Duration.ofSeconds(30))
4950
.method(requestData.method().name(), bodyPublisher);
5051

51-
if (requestData.body() != null && !requestData.body().isBlank()) {
52+
if (hasBody && requestData.contentType() != null && !requestData.contentType().isBlank()) {
53+
builder.header("Content-Type", requestData.contentType());
54+
} else if (hasBody) {
5255
builder.header("Content-Type", "application/json");
5356
}
5457

@@ -74,9 +77,12 @@ public ResponseEntity<String> sendRequest(JavaHttpRequest requestData, HttpHeade
7477

7578
HttpResponse<String> response = client.send(builder.build(), BodyHandlers.ofString());
7679

77-
MultiValueMap<String, String> responseHeaders = CollectionUtils.toMultiValueMap(response.headers().map());
80+
HttpHeaders responseHeaders = new HttpHeaders();
81+
response.headers().map().forEach(responseHeaders::addAll);
7882

79-
return new ResponseEntity<>(response.body(), responseHeaders, response.statusCode());
83+
return ResponseEntity.status(response.statusCode())
84+
.headers(h -> h.addAll(responseHeaders))
85+
.body(response.body());
8086

8187
} catch (Exception e) {
8288
String errorDetail = formatErrorResponse(e);

src/main/java/com/wlanboy/javahttpclient/client/K8sDiagnosticService.java

Lines changed: 23 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,11 @@
1313
import java.net.Socket;
1414
import java.nio.file.Files;
1515
import java.nio.file.Paths;
16+
import java.time.Duration;
1617
import java.util.*;
1718

19+
import org.springframework.http.client.SimpleClientHttpRequestFactory;
20+
1821
@Service
1922
public class K8sDiagnosticService {
2023

@@ -30,7 +33,10 @@ public class K8sDiagnosticService {
3033
private volatile String k8sInitError = null;
3134

3235
public K8sDiagnosticService() {
33-
this.restTemplate = new RestTemplate();
36+
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
37+
factory.setConnectTimeout(Duration.ofSeconds(5));
38+
factory.setReadTimeout(Duration.ofSeconds(10));
39+
this.restTemplate = new RestTemplate(factory);
3440
initializeK8sClient();
3541
logger.info("K8s Diagnostic Service initialisiert (K8s API verfügbar: {}).", k8sInitialized);
3642
}
@@ -87,8 +93,8 @@ public Map<String, Object> getFullSidecarDetails() {
8793
String rawStats = restTemplate.getForObject(
8894
ENVOY_ADMIN_URL + "/stats?filter=.*(errors|5xx|timeout|retry|failed|reset|refused|overflow).*",
8995
String.class);
90-
Map<String, String> activeErrors = parseErrorStatsOnly(rawStats);
91-
health.put("activeErrorMetrics", parseErrorStatsOnly(rawStats));
96+
Map<String, String> activeErrors = parseStats(rawStats, true);
97+
health.put("activeErrorMetrics", activeErrors);
9298
health.put("errorCount", activeErrors.size());
9399
report.put("healthDiagnostics", health);
94100

@@ -100,27 +106,6 @@ public Map<String, Object> getFullSidecarDetails() {
100106
return report;
101107
}
102108

103-
private Map<String, String> parseErrorStatsOnly(String rawStats) {
104-
Map<String, String> errorMap = new TreeMap<>();
105-
if (rawStats != null) {
106-
rawStats.lines()
107-
.filter(line -> line.contains(":"))
108-
.forEach(line -> {
109-
int colonIndex = line.lastIndexOf(':');
110-
if (colonIndex > 0 && colonIndex < line.length() - 1) {
111-
String key = line.substring(0, colonIndex).trim();
112-
String val = line.substring(colonIndex + 1).trim();
113-
try {
114-
if (Long.parseLong(val) > 0) {
115-
errorMap.put(key, val);
116-
}
117-
} catch (NumberFormatException ignored) {
118-
}
119-
}
120-
});
121-
}
122-
return errorMap;
123-
}
124109

125110
private Map<String, Object> getEnvoyDetails() {
126111
Map<String, Object> envoy = new HashMap<>();
@@ -136,7 +121,7 @@ private Map<String, Object> getEnvoyDetails() {
136121
// Wichtige Netzwerk-Stats (Retries, Timeouts, 5xx Fehler)
137122
String stats = restTemplate.getForObject(
138123
ENVOY_ADMIN_URL + "/stats?filter=cluster.*.upstream_rq_(5xx|timeout|retry)", String.class);
139-
envoy.put("networkStats", parseStats(stats));
124+
envoy.put("networkStats", parseStats(stats, false));
140125

141126
} catch (Exception e) {
142127
envoy.put("error", "Envoy Admin API nicht erreichbar: " + e.getMessage());
@@ -178,16 +163,25 @@ private String summarizeClusters(String rawClusters) {
178163
return count + " aktive Upstream-Cluster-Einträge";
179164
}
180165

181-
private Map<String, String> parseStats(String rawStats) {
182-
Map<String, String> statsMap = new HashMap<>();
166+
private Map<String, String> parseStats(String rawStats, boolean onlyNonZero) {
167+
Map<String, String> statsMap = onlyNonZero ? new TreeMap<>() : new HashMap<>();
183168
if (rawStats != null) {
184169
rawStats.lines()
185170
.filter(line -> line.contains(":"))
186171
.forEach(line -> {
187172
int colonIndex = line.lastIndexOf(':');
188173
if (colonIndex > 0 && colonIndex < line.length() - 1) {
189-
statsMap.put(line.substring(0, colonIndex).trim(),
190-
line.substring(colonIndex + 1).trim());
174+
String key = line.substring(0, colonIndex).trim();
175+
String val = line.substring(colonIndex + 1).trim();
176+
if (onlyNonZero) {
177+
try {
178+
if (Long.parseLong(val) > 0) {
179+
statsMap.put(key, val);
180+
}
181+
} catch (NumberFormatException ignored) {}
182+
} else {
183+
statsMap.put(key, val);
184+
}
191185
}
192186
});
193187
}

src/main/java/com/wlanboy/javahttpclient/controller/JavaHttpRequest.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@ public record JavaHttpRequest(
1919
@NotNull(message = "HTTP Methode ist erforderlich")
2020
HttpMethod method,
2121

22-
@Schema(description = "Optionaler JSON Body", example = "{\"key\": \"value\"}")
22+
@Schema(description = "Optionaler Request Body", example = "{\"key\": \"value\"}")
2323
String body,
2424

25+
@Schema(description = "Content-Type des Bodys", example = "application/json")
26+
String contentType,
27+
2528
@Schema(description = "Header kopieren")
2629
boolean copyHeaders,
2730

0 commit comments

Comments
 (0)