forked from guacsec/trustify-da-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExhortApi.java
More file actions
703 lines (648 loc) · 26.7 KB
/
Copy pathExhortApi.java
File metadata and controls
703 lines (648 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
/*
* Copyright 2023-2025 Trustify Dependency Analytics Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.redhat.exhort.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.packageurl.MalformedPackageURLException;
import com.github.packageurl.PackageURL;
import com.redhat.exhort.Api;
import com.redhat.exhort.Provider;
import com.redhat.exhort.api.v4.AnalysisReport;
import com.redhat.exhort.image.ImageRef;
import com.redhat.exhort.image.ImageUtils;
import com.redhat.exhort.logging.LoggersFactory;
import com.redhat.exhort.tools.Ecosystem;
import com.redhat.exhort.utils.Environment;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMultipart;
import jakarta.mail.util.ByteArrayDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** Concrete implementation of the Exhort {@link Api} Service. */
public final class ExhortApi implements Api {
private static final String DEV_EXHORT_BACKEND_URL = "DEV_EXHORT_BACKEND_URL";
private static final String EXHORT_DEV_MODE = "EXHORT_DEV_MODE";
private static final String HTTP_VERSION_EXHORT_CLIENT = "HTTP_VERSION_EXHORT_CLIENT";
private static final String EXHORT_PROXY_URL = "EXHORT_PROXY_URL";
private static final Logger LOG = LoggersFactory.getLogger(ExhortApi.class.getName());
public static final String DEFAULT_ENDPOINT = "https://rhda.rhcloud.com";
public static final String DEFAULT_ENDPOINT_DEV = "https://exhort.stage.devshift.net";
public static final String RHDA_TOKEN_HEADER = "rhda-token";
public static final String RHDA_SOURCE_HEADER = "rhda-source";
public static final String RHDA_OPERATION_TYPE_HEADER = "rhda-operation-type";
public static final String EXHORT_REQUEST_ID_HEADER_NAME = "ex-request-id";
private final String endpoint;
public String getEndpoint() {
return endpoint;
}
/** Enum for identifying token environment variables and their corresponding request headers. */
private enum TokenProvider {
SNYK,
OSS_INDEX;
/**
* Get the expected environment variable name.
*
* @return i.e. EXHORT_SNYK_TOKEN
*/
String getVarName() {
return String.format("EXHORT_%s_TOKEN", this);
}
String getUserVarName() {
return String.format("EXHORT_%s_USER", this);
}
/**
* Get the expected request header name.
*
* @return i.e. ex-snyk-token
*/
String getHeaderName() {
return String.format("ex-%s-token", this.toString().replace("_", "-").toLowerCase());
}
String getUserHeaderName() {
return String.format("ex-%s-user", this.toString().replace("_", "-").toLowerCase());
}
}
private final HttpClient client;
private final ObjectMapper mapper;
private LocalDateTime startTime;
private LocalDateTime providerEndTime;
private LocalDateTime endTime;
public ExhortApi() {
this(createHttpClient());
}
/**
* Get the HTTP protocol Version set by client in environment variable, if not set, the default is
* HTTP Protocol Version 1.1
*
* @return i.e. HttpClient.Version.HTTP_1.1
*/
static HttpClient.Version getHttpVersion() {
var version = Environment.get(HTTP_VERSION_EXHORT_CLIENT);
return (version != null && version.contains("2"))
? HttpClient.Version.HTTP_2
: HttpClient.Version.HTTP_1_1;
}
ExhortApi(final HttpClient client) {
// // temp system property - as long as prod exhort url not implemented the multi-source v4
// endpoint, this
// property needs to be true
// System.setProperty("EXHORT_DEV_MODE","true");
commonHookBeginning(true);
this.client = client;
this.mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// Take default from config.properties in case client didn't override DEV MODE
if (Environment.get(EXHORT_DEV_MODE) == null) {
try {
InputStream exhortConfig =
this.getClass().getClassLoader().getResourceAsStream("config.properties");
if (exhortConfig == null) {
LOG.info(
"config.properties not found on the class path, fallback to default DEV MODE ="
+ " false");
System.setProperty(EXHORT_DEV_MODE, "false");
} else {
Properties properties = new Properties();
properties.load(exhortConfig);
System.setProperty(EXHORT_DEV_MODE, (String) properties.get(EXHORT_DEV_MODE));
}
} catch (IOException e) {
LOG.info(
String.format(
"Error loading config.properties , fallback to set default property DEV MODE ="
+ " false, Error message = %s",
e.getMessage()));
System.setProperty(EXHORT_DEV_MODE, "false");
}
}
this.endpoint = getExhortUrl();
}
public static HttpClient createHttpClient() {
HttpClient.Builder builder = HttpClient.newBuilder().version(getHttpVersion());
String proxyUrl = Environment.get(EXHORT_PROXY_URL);
if (proxyUrl != null && !proxyUrl.isBlank()) {
try {
URI proxyUri = URI.create(proxyUrl);
builder.proxy(
ProxySelector.of(new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort())));
} catch (IllegalArgumentException e) {
LOG.warning("Invalid EXHORT_PROXY_URL: " + proxyUrl + ", using direct connection");
}
}
return builder.build();
}
private String commonHookBeginning(boolean startOfApi) {
if (startOfApi) {
if (debugLoggingIsNeeded()) {
LOG.info("Start of exhort-java-api client");
LOG.info(String.format("Starting time of API: %s", LocalDateTime.now()));
}
} else {
if (Objects.isNull(getClientRequestId())) {
generateClientRequestId();
}
if (debugLoggingIsNeeded()) {
this.startTime = LocalDateTime.now();
LOG.info(String.format("Starting time: %s", this.startTime));
}
}
return getClientRequestId();
}
private static void generateClientRequestId() {
RequestManager.getInstance().addClientTraceIdToRequest(UUID.randomUUID().toString());
}
private static String getClientRequestId() {
return RequestManager.getInstance().getTraceIdOfRequest();
}
public String getExhortUrl() {
String endpoint;
if (Environment.getBoolean(EXHORT_DEV_MODE, false)) {
endpoint = Environment.get(DEV_EXHORT_BACKEND_URL, DEFAULT_ENDPOINT_DEV);
} else {
endpoint = DEFAULT_ENDPOINT;
}
if (debugLoggingIsNeeded()) {
LOG.info(
String.format(
"EXHORT_DEV_MODE=%s,DEV_EXHORT_BACKEND_URL=%s, Chosen Backend URL=%s ,"
+ " DEFAULT_ENDPOINT_DEV=%s , DEFAULT_ENDPOINT=%s",
Environment.getBoolean(EXHORT_DEV_MODE, false),
Environment.get(DEV_EXHORT_BACKEND_URL, DEFAULT_ENDPOINT_DEV),
endpoint,
DEFAULT_ENDPOINT_DEV,
DEFAULT_ENDPOINT));
}
return endpoint;
}
@Override
public CompletableFuture<MixedReport> stackAnalysisMixed(final String manifestFile)
throws IOException {
String exClientTraceId = commonHookBeginning(false);
return this.client
.sendAsync(
this.buildStackRequest(manifestFile, MediaType.MULTIPART_MIXED),
HttpResponse.BodyHandlers.ofByteArray())
.thenApply(
resp -> {
RequestManager.getInstance().addClientTraceIdToRequest(exClientTraceId);
if (debugLoggingIsNeeded()) {
logExhortRequestId(resp);
}
if (resp.statusCode() == 200) {
byte[] htmlPart = null;
AnalysisReport jsonPart = null;
var ds = new ByteArrayDataSource(resp.body(), MediaType.MULTIPART_MIXED.toString());
try {
var mp = new MimeMultipart(ds);
for (var i = 0; i < mp.getCount(); i++) {
if (Objects.isNull(htmlPart)
&& MediaType.TEXT_HTML
.toString()
.equals(mp.getBodyPart(i).getContentType())) {
htmlPart = mp.getBodyPart(i).getInputStream().readAllBytes();
}
if (Objects.isNull(jsonPart)
&& MediaType.APPLICATION_JSON
.toString()
.equals(mp.getBodyPart(i).getContentType())) {
jsonPart =
this.mapper.readValue(
mp.getBodyPart(i).getInputStream().readAllBytes(),
AnalysisReport.class);
}
}
} catch (IOException | MessagingException e) {
throw new RuntimeException(e);
}
commonHookAfterExhortResponse();
return new MixedReport(
Objects.requireNonNull(htmlPart), Objects.requireNonNull(jsonPart));
} else {
LOG.severe(
String.format(
"failed to invoke stackAnalysisMixed for getting the html and json reports,"
+ " Http Response Status=%s , received message from server= %s ",
resp.statusCode(), new String(resp.body())));
return new MixedReport();
}
});
}
@Override
public CompletableFuture<byte[]> stackAnalysisHtml(final String manifestFile) throws IOException {
String exClientTraceId = commonHookBeginning(false);
return this.client
.sendAsync(
this.buildStackRequest(manifestFile, MediaType.TEXT_HTML),
HttpResponse.BodyHandlers.ofByteArray())
.thenApply(
httpResponse -> {
RequestManager.getInstance().addClientTraceIdToRequest(exClientTraceId);
if (debugLoggingIsNeeded()) {
logExhortRequestId(httpResponse);
}
if (httpResponse.statusCode() != 200) {
LOG.severe(
String.format(
"failed to invoke stackAnalysis for getting the html report, Http Response"
+ " Status=%s , received message from server= %s ",
httpResponse.statusCode(), new String(httpResponse.body())));
}
commonHookAfterExhortResponse();
return httpResponse.body();
})
.exceptionally(
exception -> {
LOG.severe(
String.format(
"failed to invoke stackAnalysis for getting the html report, received"
+ " message= %s ",
exception.getMessage()));
// LOG.log(System.Logger.Level.ERROR, "Exception Entity", exception);
commonHookAfterExhortResponse();
return new byte[0];
});
}
@Override
public CompletableFuture<AnalysisReport> stackAnalysis(final String manifestFile)
throws IOException {
String exClientTraceId = commonHookBeginning(false);
return this.client
.sendAsync(
this.buildStackRequest(manifestFile, MediaType.APPLICATION_JSON),
HttpResponse.BodyHandlers.ofString())
// .thenApply(HttpResponse::body)
.thenApply(
response ->
getAnalysisReportFromResponse(response, "StackAnalysis", "json", exClientTraceId))
.exceptionally(
exception -> {
LOG.severe(
String.format(
"failed to invoke stackAnalysis for getting the json report, received"
+ " message= %s ",
exception.getMessage()));
// LOG.log(System.Logger.Level.ERROR, "Exception Entity", exception);
return new AnalysisReport();
});
}
private AnalysisReport getAnalysisReportFromResponse(
HttpResponse<String> response, String operation, String reportName, String exClientTraceId) {
RequestManager.getInstance().addClientTraceIdToRequest(exClientTraceId);
if (debugLoggingIsNeeded()) {
logExhortRequestId(response);
}
if (response.statusCode() == 200) {
if (debugLoggingIsNeeded()) {
LOG.info(
String.format(
"Response body received from exhort server : %s %s",
System.lineSeparator(), response.body()));
}
commonHookAfterExhortResponse();
try {
return this.mapper.readValue(response.body(), AnalysisReport.class);
} catch (JsonProcessingException e) {
throw new CompletionException(e);
}
} else {
LOG.severe(
String.format(
"failed to invoke %s for getting the %s report, Http Response Status=%s , received"
+ " message from server= %s ",
operation, reportName, response.statusCode(), response.body()));
return new AnalysisReport();
}
}
private static void logExhortRequestId(HttpResponse<?> response) {
Optional<String> headerExRequestId =
response.headers().allValues(EXHORT_REQUEST_ID_HEADER_NAME).stream().findFirst();
headerExRequestId.ifPresent(
value ->
LOG.info(
String.format(
"Unique Identifier associated with this request ( Received from Exhort Backend"
+ " ) - ex-request-id= : %s",
value)));
}
public static boolean debugLoggingIsNeeded() {
return Environment.getBoolean("EXHORT_DEBUG", false);
}
@Override
public CompletableFuture<AnalysisReport> componentAnalysis(
final String manifest, final byte[] manifestContent) throws IOException {
String exClientTraceId = commonHookBeginning(false);
var manifestPath = Path.of(manifest);
var provider = Ecosystem.getProvider(manifestPath);
var uri = URI.create(String.format("%s/api/v4/analysis", this.endpoint));
var content = provider.provideComponent();
commonHookAfterProviderCreatedSbomAndBeforeExhort();
return getAnalysisReportForComponent(uri, content, exClientTraceId);
}
private void commonHookAfterProviderCreatedSbomAndBeforeExhort() {
if (debugLoggingIsNeeded()) {
LOG.info("After Provider created sbom hook");
this.providerEndTime = LocalDateTime.now();
LOG.info(String.format("After Creating Sbom time: %s", this.startTime));
LOG.info(
String.format(
"Time took to create sbom file to be sent to exhort backend, in ms : %s, in seconds:"
+ " %s",
this.startTime.until(this.providerEndTime, ChronoUnit.MILLIS),
this.startTime.until(this.providerEndTime, ChronoUnit.MILLIS) / 1000F));
}
}
private void commonHookAfterExhortResponse() {
if (debugLoggingIsNeeded()) {
this.endTime = LocalDateTime.now();
LOG.info(String.format("After got response from exhort time: %s", this.endTime));
LOG.info(
String.format(
"Time took to get response from exhort backend, in ms: %s, in seconds: %s",
this.providerEndTime.until(this.endTime, ChronoUnit.MILLIS),
this.providerEndTime.until(this.endTime, ChronoUnit.MILLIS) / 1000F));
LOG.info(
String.format(
"Total time took for complete analysis, in ms: %s, in seconds: %s",
this.startTime.until(this.endTime, ChronoUnit.MILLIS),
this.startTime.until(this.endTime, ChronoUnit.MILLIS) / 1000F));
}
RequestManager.getInstance().removeClientTraceIdFromRequest();
}
@Override
public CompletableFuture<AnalysisReport> componentAnalysis(String manifestFile)
throws IOException {
String exClientTraceId = commonHookBeginning(false);
var manifestPath = Path.of(manifestFile);
var provider = Ecosystem.getProvider(manifestPath);
var uri = URI.create(String.format("%s/api/v4/analysis", this.endpoint));
var content = provider.provideComponent();
commonHookAfterProviderCreatedSbomAndBeforeExhort();
return getAnalysisReportForComponent(uri, content, exClientTraceId);
}
private CompletableFuture<AnalysisReport> getAnalysisReportForComponent(
URI uri, Provider.Content content, String exClientTraceId) {
return this.client
.sendAsync(
this.buildRequest(content, uri, MediaType.APPLICATION_JSON, "Component Analysis"),
HttpResponse.BodyHandlers.ofString())
// .thenApply(HttpResponse::body)
.thenApply(
response ->
getAnalysisReportFromResponse(
response, "Component Analysis", "json", exClientTraceId))
.exceptionally(
exception -> {
LOG.severe(
String.format(
"failed to invoke Component Analysis for getting the json report, received"
+ " message= %s ",
exception.getMessage()));
// LOG.log(System.Logger.Level.ERROR, "Exception Entity", exception);
return new AnalysisReport();
});
}
/**
* Build an HTTP request wrapper for sending to the Backend API for Stack Analysis only.
*
* @param manifestFile the path for the manifest file
* @param acceptType the type of requested content
* @return a HttpRequest ready to be sent to the Backend API
* @throws IOException when failed to load the manifest file
*/
private HttpRequest buildStackRequest(final String manifestFile, final MediaType acceptType)
throws IOException {
var manifestPath = Path.of(manifestFile);
var provider = Ecosystem.getProvider(manifestPath);
var uri = URI.create(String.format("%s/api/v4/analysis", this.endpoint));
var content = provider.provideStack();
commonHookAfterProviderCreatedSbomAndBeforeExhort();
return buildRequest(content, uri, acceptType, "Stack Analysis");
}
@Override
public CompletableFuture<Map<ImageRef, AnalysisReport>> imageAnalysis(
final Set<ImageRef> imageRefs) throws IOException {
return this.performBatchAnalysis(
() -> getBatchImageSboms(imageRefs),
MediaType.APPLICATION_JSON,
HttpResponse.BodyHandlers.ofString(),
this::getBatchImageAnalysisReports,
Collections::emptyMap,
"Image Analysis");
}
@Override
public CompletableFuture<byte[]> imageAnalysisHtml(Set<ImageRef> imageRefs) throws IOException {
return this.performBatchAnalysis(
() -> getBatchImageSboms(imageRefs),
MediaType.TEXT_HTML,
HttpResponse.BodyHandlers.ofByteArray(),
HttpResponse::body,
() -> new byte[0],
"Image Analysis");
}
Map<String, JsonNode> getBatchImageSboms(final Set<ImageRef> imageRefs) {
return imageRefs.parallelStream()
.map(
imageRef -> {
try {
return new AbstractMap.SimpleEntry<>(
imageRef.getPackageURL().canonicalize(),
ImageUtils.generateImageSBOM(imageRef));
} catch (IOException | MalformedPackageURLException ex) {
throw new RuntimeException(ex);
}
})
.collect(
Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));
}
Map<ImageRef, AnalysisReport> getBatchImageAnalysisReports(
final HttpResponse<String> httpResponse) {
if (httpResponse.statusCode() == 200) {
try {
Map<?, ?> reports = this.mapper.readValue(httpResponse.body(), Map.class);
return reports.entrySet().stream()
.collect(
Collectors.toMap(
e -> {
try {
return new ImageRef(new PackageURL(e.getKey().toString()));
} catch (MalformedPackageURLException ex) {
throw new RuntimeException(ex);
}
},
e -> mapper.convertValue(e.getValue(), AnalysisReport.class)));
} catch (JsonProcessingException e) {
throw new CompletionException(e);
}
} else {
return Collections.emptyMap();
}
}
<H, T> CompletableFuture<T> performBatchAnalysis(
final Supplier<Map<String, JsonNode>> sbomsGenerator,
final MediaType mediaType,
final HttpResponse.BodyHandler<H> responseBodyHandler,
final Function<HttpResponse<H>, T> responseGenerator,
final Supplier<T> exceptionResponseGenerator,
final String analysisName)
throws IOException {
String exClientTraceId = commonHookBeginning(false);
var uri = URI.create(String.format("%s/api/v4/batch-analysis", this.endpoint));
var sboms = sbomsGenerator.get();
var content =
new Provider.Content(
mapper.writeValueAsString(sboms).getBytes(StandardCharsets.UTF_8),
Api.CYCLONEDX_MEDIA_TYPE);
commonHookAfterProviderCreatedSbomAndBeforeExhort();
return this.client
.sendAsync(this.buildRequest(content, uri, mediaType, analysisName), responseBodyHandler)
.thenApply(
response ->
getBatchAnalysisReportsFromResponse(
response, responseGenerator, analysisName, "json", exClientTraceId))
.exceptionally(
exception -> {
LOG.severe(
String.format(
"failed to invoke %s for getting the json report, received message= %s ",
analysisName, exception.getMessage()));
commonHookAfterExhortResponse();
return exceptionResponseGenerator.get();
});
}
<H, T> T getBatchAnalysisReportsFromResponse(
final HttpResponse<H> response,
final Function<HttpResponse<H>, T> responseGenerator,
final String operation,
final String reportName,
final String exClientTraceId) {
RequestManager.getInstance().addClientTraceIdToRequest(exClientTraceId);
if (debugLoggingIsNeeded()) {
logExhortRequestId(response);
}
if (response.statusCode() == 200) {
if (debugLoggingIsNeeded()) {
LOG.info(
String.format(
"Response body received from exhort server : %s %s",
System.lineSeparator(), response.body()));
}
} else {
LOG.severe(
String.format(
"failed to invoke %s for getting the %s report, Http Response Status=%s , "
+ "received message from server= %s ",
operation, reportName, response.statusCode(), response.body()));
}
commonHookAfterExhortResponse();
return responseGenerator.apply(response);
}
/**
* Build an HTTP request for sending to the Backend API.
*
* @param content the {@link com.redhat.exhort.Provider.Content} info for the request body
* @param uri the {@link URI} for sending the request to
* @param acceptType value the Accept header in the request, indicating the required response type
* @return a HttpRequest ready to be sent to the Backend API
*/
private HttpRequest buildRequest(
final Provider.Content content,
final URI uri,
final MediaType acceptType,
final String analysisType) {
var request =
HttpRequest.newBuilder(uri)
.version(Version.HTTP_1_1)
.setHeader("Accept", acceptType.toString())
.setHeader("Content-Type", content.type)
.POST(HttpRequest.BodyPublishers.ofString(new String(content.buffer)));
// include tokens from environment variables of java properties as request headers
Stream.of(ExhortApi.TokenProvider.values())
.forEach(
p -> {
var envToken = Environment.get(p.getVarName());
if (Objects.nonNull(envToken)) {
request.setHeader(p.getHeaderName(), envToken);
} else {
var propToken = Environment.get(p.getVarName());
if (Objects.nonNull(propToken)) {
request.setHeader(p.getHeaderName(), propToken);
}
}
var envUser = Environment.get(p.getUserHeaderName());
if (Objects.nonNull(envUser)) {
request.setHeader(p.getUserHeaderName(), envUser);
} else {
var propUser = Environment.get(p.getUserVarName());
if (Objects.nonNull(propUser)) {
request.setHeader(p.getUserHeaderName(), propUser);
}
}
});
// set rhda-token
// Environment variable/property name = RHDA_TOKEN
String rhdaToken = calculateHeaderValue(RHDA_TOKEN_HEADER);
if (rhdaToken != null) {
request.setHeader(RHDA_TOKEN_HEADER, rhdaToken);
}
// set rhda-source ( extension/plugin id/name)
// Environment variable/property name = RHDA_SOURCE
String rhdaSource = calculateHeaderValue(RHDA_SOURCE_HEADER);
if (rhdaSource != null) {
request.setHeader(RHDA_SOURCE_HEADER, rhdaSource);
}
request.setHeader(RHDA_OPERATION_TYPE_HEADER, analysisType);
return request.build();
}
private String calculateHeaderValue(String headerName) {
String result;
result = calculateHeaderValueActual(headerName);
if (result == null) {
result = calculateHeaderValueActual(headerName.toUpperCase().replace("-", "_"));
}
return result;
}
private String calculateHeaderValueActual(String headerName) {
return Environment.get(headerName);
}
}