forked from microsoft/kiota-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestInformation.java
More file actions
495 lines (452 loc) · 20.7 KB
/
RequestInformation.java
File metadata and controls
495 lines (452 loc) · 20.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
package com.microsoft.kiota;
import com.microsoft.kiota.serialization.Parsable;
import com.microsoft.kiota.serialization.SerializationWriter;
import com.microsoft.kiota.serialization.ValuedEnum;
import io.github.stduritemplate.StdUriTemplate;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.Scope;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
/** This class represents an abstract HTTP request. */
public class RequestInformation {
/** Creates a new instance of the request information class. */
public RequestInformation() { // Default constructor
}
/**
* Creates a new instance of the request information class.
* @param method The HTTP method for the request.
* @param urlTemplate The url template for the request.
* @param pathParameters The path parameters for the request.
*/
public RequestInformation(
@Nonnull final HttpMethod method,
@Nonnull final String urlTemplate,
@Nonnull final Map<String, Object> pathParameters) {
this.httpMethod = Objects.requireNonNull(method);
this.urlTemplate = Objects.requireNonNull(urlTemplate);
this.pathParameters = Objects.requireNonNull(pathParameters);
}
/**
* Configures the request information based on the request configuration and the query parameters getter.
* @param <T> The type of the request configuration.
* @param requestConfiguration The request configuration to apply to the request information.
* @param configurationFactory The factory to create the request configuration from.
*/
public <T extends BaseRequestConfiguration> void configure(
@Nullable final java.util.function.Consumer<T> requestConfiguration,
@Nonnull final java.util.function.Supplier<T> configurationFactory) {
configure(requestConfiguration, configurationFactory, null);
}
/**
* Configures the request information based on the request configuration and the query parameters getter.
* @param <T> The type of the request configuration.
* @param requestConfiguration The request configuration to apply to the request information.
* @param configurationFactory The factory to create the request configuration from.
* @param queryParametersGetter The function to get the query parameters from the request configuration.
*/
public <T extends BaseRequestConfiguration> void configure(
@Nullable final java.util.function.Consumer<T> requestConfiguration,
@Nonnull final java.util.function.Supplier<T> configurationFactory,
@Nullable final java.util.function.Function<T, QueryParameters> queryParametersGetter) {
Objects.requireNonNull(configurationFactory);
if (requestConfiguration == null) {
return;
}
final T requestConfig = configurationFactory.get();
requestConfiguration.accept(requestConfig);
if (queryParametersGetter != null) {
addQueryParameters(queryParametersGetter.apply(requestConfig));
}
headers.putAll(requestConfig.headers);
addRequestOptions(requestConfig.options);
}
/** The url template for the current request */
@Nullable public String urlTemplate;
/** The path parameters for the current request */
@Nullable public Map<String, Object> pathParameters = new HashMap<>();
private URI uri;
/** Gets the URI of the request.
* @throws URISyntaxException when the uri template is invalid.
* @throws IllegalStateException when the baseurl template parameter is missing from the path parameters.
* @return the URI of the request.
*/
@Nullable public URI getUri() throws URISyntaxException, IllegalStateException {
if (uri != null) {
return uri;
} else if (pathParameters.containsKey(RAW_URL_KEY)
&& pathParameters.get(RAW_URL_KEY) instanceof String) {
setUri(new URI((String) pathParameters.get(RAW_URL_KEY)));
return uri;
} else {
Objects.requireNonNull(urlTemplate);
Objects.requireNonNull(queryParameters);
if (!pathParameters.containsKey("baseurl")
&& urlTemplate.toLowerCase(Locale.ROOT).contains("{+baseurl}"))
throw new IllegalStateException(
"PathParameters must contain a value for \"baseurl\" for the url to be"
+ " built.");
Map<String, Object> params =
new HashMap<>(pathParameters.size() + queryParameters.size());
for (final Map.Entry<String, Object> pathParam : pathParameters.entrySet()) {
params.put(pathParam.getKey(), getSanitizedValues(pathParam.getValue()));
}
params.putAll(queryParameters);
return new URI(StdUriTemplate.expand(urlTemplate, params));
}
}
/**
* Sets the URI of the request.
* @param uri the URI of the request.
*/
public void setUri(@Nonnull final URI uri) {
this.uri = Objects.requireNonNull(uri);
if (queryParameters != null) {
queryParameters.clear();
}
if (pathParameters != null) {
pathParameters.clear();
}
}
static final String RAW_URL_KEY = "request-raw-url";
/** The HTTP method for the request */
@Nullable public HttpMethod httpMethod;
private HashMap<String, Object> queryParameters = new HashMap<>();
/**
* Adds query parameters to the request based on the object passed in and its fields.
* @param parameters The object to add the query parameters from.
*/
public void addQueryParameters(@Nullable final QueryParameters parameters) {
if (parameters == null) return;
Map<String, Object> params = parameters.toQueryParameters();
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
Object value = entry.getValue();
if (value != null) {
queryParameters.put(entry.getKey(), getSanitizedValues(value));
}
}
}
}
/**
* Adds query parameters to the request.
* @param name The name of the query parameter.
* @param value The value to add the query parameters.
*/
public void addQueryParameter(@Nonnull final String name, @Nullable final Object value) {
Objects.requireNonNull(name);
queryParameters.put(name, getSanitizedValues(value));
}
/**
* Removes a query parameter from the request.
* @param name The name of the query parameter to remove.
*/
public void removeQueryParameter(@Nonnull final String name) {
Objects.requireNonNull(name);
queryParameters.remove(name);
}
/**
* Gets the query parameters for the request.
* @return The query parameters for the request.
*/
@SuppressWarnings("unchecked")
@Nonnull public Map<String, Object> getQueryParameters() {
return (Map<String, Object>) queryParameters.clone();
}
/** The request headers */
@Nonnull public final RequestHeaders headers = new RequestHeaders();
/** The Request Body. */
@Nullable public InputStream content;
@Nonnull private final HashMap<String, RequestOption> requestOptions = new HashMap<>();
/**
* Gets the request options for this request. Options are unique by type. If an option of the same type is added twice, the last one wins.
* @return the request options for this request.
*/
@Nonnull public Collection<RequestOption> getRequestOptions() {
return requestOptions.values();
}
/**
* Adds request options to this request.
* @param options the request options to add.
*/
public void addRequestOptions(@Nullable final Collection<RequestOption> options) {
if (options == null || options.isEmpty()) return;
for (final RequestOption option : options) {
requestOptions.put(option.getClass().getCanonicalName(), option);
}
}
/**
* Removes a request option from this request.
* @param options the request option to remove.
*/
public void removeRequestOptions(@Nullable final RequestOption... options) {
if (options == null || options.length == 0) return;
for (final RequestOption option : options) {
requestOptions.remove(option.getClass().getCanonicalName());
}
}
/**
* Adds a response handler as a RequestOption.
* @param responseHandler the response handler to add to the request.
*/
public void setResponseHandler(@Nonnull ResponseHandler responseHandler) {
Objects.requireNonNull(responseHandler);
ResponseHandlerOption handlerOption = new ResponseHandlerOption();
handlerOption.setResponseHandler(responseHandler);
addRequestOptions(new ArrayList<>(Arrays.asList(handlerOption)));
}
@Nonnull private static final String BINARY_CONTENT_TYPE = "application/octet-stream";
@Nonnull private static final String CONTENT_TYPE_HEADER = "Content-Type";
/**
* Sets the request body to be a binary stream.
* @param value the binary stream
* @deprecated use {@link #setStreamContent(InputStream, String)} instead.
*/
@Deprecated
public void setStreamContent(@Nonnull final InputStream value) {
setStreamContent(value, BINARY_CONTENT_TYPE);
}
/**
* Sets the request body to be a binary stream.
* @param value the binary stream
* @param contentType the content type of the stream.
*/
public void setStreamContent(
@Nonnull final InputStream value, @Nonnull final String contentType) {
Objects.requireNonNull(value);
Objects.requireNonNull(contentType);
if (contentType.isEmpty()) {
throw new IllegalArgumentException("contentType cannot be empty");
}
this.content = value;
headers.tryAdd(CONTENT_TYPE_HEADER, contentType);
}
private static final String SERIALIZE_ERROR = "could not serialize payload";
private static final String SPAN_NAME = "setContentFromParsable";
private static final String OBSERVABILITY_TRACER_NAME = "com.microsoft.kiota";
/**
* Sets the request body from a model with the specified content type.
* @param values the models.
* @param contentType the content type.
* @param requestAdapter The adapter service to get the serialization writer from.
* @param <T> the model type.
*/
public <T extends Parsable> void setContentFromParsable(
@Nonnull final RequestAdapter requestAdapter,
@Nonnull final String contentType,
@Nonnull final T[] values) {
final Span span =
GlobalOpenTelemetry.getTracer(OBSERVABILITY_TRACER_NAME)
.spanBuilder(SPAN_NAME)
.startSpan();
try (final Scope scope = span.makeCurrent()) {
try (final SerializationWriter writer =
getSerializationWriter(requestAdapter, contentType, values)) {
headers.tryAdd(CONTENT_TYPE_HEADER, contentType);
if (values.length > 0) {
setRequestType(values[0], span);
}
writer.writeCollectionOfObjectValues(null, Arrays.asList(values));
this.content = writer.getSerializedContent();
} catch (IOException ex) {
final RuntimeException result = new RuntimeException(SERIALIZE_ERROR, ex);
span.recordException(result);
throw result;
}
} finally {
span.end();
}
}
/**
* Sets the request body from a model with the specified content type.
* @param value the model.
* @param contentType the content type.
* @param requestAdapter The adapter service to get the serialization writer from.
* @param <T> the model type.
*/
public <T extends Parsable> void setContentFromParsable(
@Nonnull final RequestAdapter requestAdapter,
@Nonnull final String contentType,
@Nonnull final T value) {
final Span span =
GlobalOpenTelemetry.getTracer(OBSERVABILITY_TRACER_NAME)
.spanBuilder(SPAN_NAME)
.startSpan();
try (final Scope scope = span.makeCurrent()) {
try (final SerializationWriter writer =
getSerializationWriter(requestAdapter, contentType, value)) {
String effectiveContentType = contentType;
if (value instanceof MultipartBody) {
final MultipartBody multipartBody = (MultipartBody) value;
effectiveContentType += "; boundary=" + multipartBody.getBoundary();
multipartBody.requestAdapter = requestAdapter;
}
headers.tryAdd(CONTENT_TYPE_HEADER, effectiveContentType);
setRequestType(value, span);
writer.writeObjectValue(null, value);
this.content = writer.getSerializedContent();
} catch (IOException ex) {
final RuntimeException result = new RuntimeException(SERIALIZE_ERROR, ex);
span.recordException(result);
throw result;
}
} finally {
span.end();
}
}
private void setRequestType(final Object result, final Span span) {
if (result == null) return;
if (span == null) return;
span.setAttribute("com.microsoft.kiota.request.type", result.getClass().getName());
}
private <T> SerializationWriter getSerializationWriter(
@Nonnull final RequestAdapter requestAdapter,
@Nonnull final String contentType,
@Nonnull final T value) {
Objects.requireNonNull(requestAdapter);
Objects.requireNonNull(value);
Objects.requireNonNull(contentType);
return requestAdapter.getSerializationWriterFactory().getSerializationWriter(contentType);
}
/**
* Sets the request body from a scalar value with the specified content type.
* @param value the scalar values to serialize.
* @param contentType the content type.
* @param requestAdapter The adapter service to get the serialization writer from.
* @param <T> the model type.
*/
public <T> void setContentFromScalar(
@Nonnull final RequestAdapter requestAdapter,
@Nonnull final String contentType,
@Nonnull final T value) {
final Span span =
GlobalOpenTelemetry.getTracer(OBSERVABILITY_TRACER_NAME)
.spanBuilder(SPAN_NAME)
.startSpan();
try (final Scope scope = span.makeCurrent()) {
try (final SerializationWriter writer =
getSerializationWriter(requestAdapter, contentType, value)) {
headers.tryAdd(CONTENT_TYPE_HEADER, contentType);
setRequestType(value, span);
final Class<?> valueClass = value.getClass();
if (valueClass.equals(String.class)) writer.writeStringValue(null, (String) value);
else if (valueClass.equals(Boolean.class))
writer.writeBooleanValue(null, (Boolean) value);
else if (valueClass.equals(Byte.class)) writer.writeByteValue(null, (Byte) value);
else if (valueClass.equals(Short.class))
writer.writeShortValue(null, (Short) value);
else if (valueClass.equals(BigDecimal.class))
writer.writeBigDecimalValue(null, (BigDecimal) value);
else if (valueClass.equals(Float.class))
writer.writeFloatValue(null, (Float) value);
else if (valueClass.equals(Long.class)) writer.writeLongValue(null, (Long) value);
else if (valueClass.equals(Integer.class))
writer.writeIntegerValue(null, (Integer) value);
else if (valueClass.equals(UUID.class)) writer.writeUUIDValue(null, (UUID) value);
else if (valueClass.equals(OffsetDateTime.class))
writer.writeOffsetDateTimeValue(null, (OffsetDateTime) value);
else if (valueClass.equals(LocalDate.class))
writer.writeLocalDateValue(null, (LocalDate) value);
else if (valueClass.equals(LocalTime.class))
writer.writeLocalTimeValue(null, (LocalTime) value);
else if (valueClass.equals(PeriodAndDuration.class))
writer.writePeriodAndDurationValue(null, (PeriodAndDuration) value);
else {
final RuntimeException result =
new RuntimeException(
"unknown type to serialize " + valueClass.getName());
span.recordException(result);
throw result;
}
this.content = writer.getSerializedContent();
} catch (IOException ex) {
final RuntimeException result = new RuntimeException(SERIALIZE_ERROR, ex);
span.recordException(result);
throw result;
}
} finally {
span.end();
}
}
/**
* Sets the request body from a scalar value with the specified content type.
* @param values the scalar values to serialize.
* @param contentType the content type.
* @param requestAdapter The adapter service to get the serialization writer from.
* @param <T> the model type.
*/
public <T> void setContentFromScalarCollection(
@Nonnull final RequestAdapter requestAdapter,
@Nonnull final String contentType,
@Nonnull final T[] values) {
final Span span =
GlobalOpenTelemetry.getTracer(OBSERVABILITY_TRACER_NAME)
.spanBuilder(SPAN_NAME)
.startSpan();
try (final Scope scope = span.makeCurrent()) {
try (final SerializationWriter writer =
getSerializationWriter(requestAdapter, contentType, values)) {
headers.tryAdd(CONTENT_TYPE_HEADER, contentType);
if (values.length > 0) setRequestType(values[0], span);
writer.writeCollectionOfPrimitiveValues(null, Arrays.asList(values));
this.content = writer.getSerializedContent();
} catch (IOException ex) {
final RuntimeException result = new RuntimeException(SERIALIZE_ERROR, ex);
span.recordException(result);
throw result;
}
} finally {
span.end();
}
}
private static Object getSanitizedValues(Object value) {
if (value == null) {
return null;
}
if (value.getClass().isArray()) {
final Object[] values = (Object[]) value;
if (values.length > 0) {
if (values[0].getClass().isArray()) {
throw new IllegalArgumentException("multidimensional arrays are not supported");
}
final ArrayList<String> result = new ArrayList<>();
for (final Object item : values) {
result.add(getSanitizedValues(item).toString());
}
return result;
}
return Arrays.asList(values);
} else if (value instanceof ValuedEnum) {
return ((ValuedEnum) value).getValue();
} else if (value instanceof UUID) {
return value.toString();
} else if (value instanceof OffsetDateTime) {
return ((OffsetDateTime) value).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
} else if (value instanceof LocalDate) {
return ((LocalDate) value).format(DateTimeFormatter.ISO_LOCAL_DATE);
} else if (value instanceof LocalTime) {
return ((LocalTime) value).format(DateTimeFormatter.ISO_LOCAL_TIME);
} else if (value instanceof PeriodAndDuration) {
return ((PeriodAndDuration) value).toString();
} else {
return value;
}
}
}