-
Notifications
You must be signed in to change notification settings - Fork 41
/
Api.java
678 lines (603 loc) · 27.1 KB
/
Api.java
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
/*
* Copyright (C) 2017-2022 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.xyz.hub.rest;
import static com.here.xyz.hub.rest.Api.HeaderValues.APPLICATION_GEO_JSON;
import static com.here.xyz.hub.rest.Api.HeaderValues.APPLICATION_JSON;
import static com.here.xyz.hub.rest.Api.HeaderValues.STREAM_ID;
import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_GATEWAY;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.GATEWAY_TIMEOUT;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_MODIFIED;
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.vertx.core.http.HttpHeaders.ACCEPT_ENCODING;
import static io.vertx.core.http.HttpHeaders.CONTENT_TYPE;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.here.xyz.hub.Service;
import com.here.xyz.hub.XYZHubRESTVerticle;
import com.here.xyz.hub.auth.JWTPayload;
import com.here.xyz.hub.connectors.models.Space.CacheProfile;
import com.here.xyz.hub.rest.ApiParam.Query;
import com.here.xyz.hub.task.FeatureTask;
import com.here.xyz.hub.task.SpaceTask;
import com.here.xyz.hub.task.Task;
import com.here.xyz.hub.task.TaskPipeline;
import com.here.xyz.hub.util.logging.AccessLog;
import com.here.xyz.models.geojson.implementation.FeatureCollection;
import com.here.xyz.models.hub.Space.Internal;
import com.here.xyz.models.hub.Space.Public;
import com.here.xyz.models.hub.Space.WithConnectors;
import com.here.xyz.responses.BinaryResponse;
import com.here.xyz.responses.CountResponse;
import com.here.xyz.responses.ErrorResponse;
import com.here.xyz.responses.HistoryStatisticsResponse;
import com.here.xyz.responses.NotModifiedResponse;
import com.here.xyz.responses.StatisticsResponse;
import com.here.xyz.responses.XyzError;
import com.here.xyz.responses.XyzResponse;
import com.here.xyz.responses.changesets.ChangesetCollection;
import com.here.xyz.responses.changesets.CompactChangeset;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.EncodeException;
import io.vertx.core.json.Json;
import io.vertx.core.json.jackson.DatabindCodec;
import io.vertx.ext.web.RoutingContext;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager.Log4jMarker;
public abstract class Api {
protected static final Logger logger = LogManager.getLogger();
public static final int MAX_SERVICE_RESPONSE_SIZE = (Service.configuration == null ? 0 : Service.configuration.MAX_SERVICE_RESPONSE_SIZE);
public static final int MAX_HTTP_RESPONSE_SIZE = (Service.configuration == null ? 0 :Service.configuration.MAX_HTTP_RESPONSE_SIZE);
public static final HttpResponseStatus RESPONSE_PAYLOAD_TOO_LARGE = new HttpResponseStatus(513, "Response payload too large");
public static final String RESPONSE_PAYLOAD_TOO_LARGE_MESSAGE =
"The response payload was too large. Please try to reduce the expected amount of data.";
public static final HttpResponseStatus CLIENT_CLOSED_REQUEST = new HttpResponseStatus(499, "Client closed request");
private static final String DEFAULT_GATEWAY_TIMEOUT_MESSAGE = "The storage connector exceeded the maximum time";
private static final String DEFAULT_BAD_GATEWAY_MESSAGE = "The storage connector failed to execute the request";
private static final String AUTHOR_HEADER = "Author";
/**
* Converts the given response into a {@link HttpException}.
*
* @param response the response to be converted.
* @return the {@link HttpException} that reflects the response best.
*/
public static HttpException responseToHttpException(final XyzResponse response) {
if (response instanceof ErrorResponse) {
return new HttpException(BAD_GATEWAY, ((ErrorResponse) response).getErrorMessage());
}
return new HttpException(BAD_GATEWAY, "Received invalid response of type '" + response.getClass().getSimpleName() + "'");
}
/**
* If an empty response should be sent, then this method will either send an empty response or an error response. If the response is an
* {@link ErrorResponse}, but an empty response was desired.
*
* @return true if a response was sent; false otherwise.
*/
private boolean sendEmptyResponse(final Task task) {
if (ApiResponseType.EMPTY == task.responseType) {
if (task instanceof FeatureTask) {
final FeatureTask featureTask = (FeatureTask) task;
if (featureTask.getResponse() instanceof ErrorResponse) {
final ErrorResponse errorResponse = (ErrorResponse) featureTask.getResponse();
// Note: This is only a warning as it is generally not our fault, so its no real error in the service.
logger.warn(task.getMarker(), "Received an error response: {}", errorResponse);
if (XyzError.TIMEOUT.equals(errorResponse.getError())) {
sendErrorResponse(task.context, GATEWAY_TIMEOUT, XyzError.TIMEOUT, DEFAULT_GATEWAY_TIMEOUT_MESSAGE);
} else {
sendErrorResponse(task.context, BAD_GATEWAY, errorResponse.getError(), DEFAULT_BAD_GATEWAY_MESSAGE);
}
return true;
}
}
task.context.response().setStatusCode(NO_CONTENT.code()).end();
return true;
}
return false;
}
/**
* Internally used to send a "Not Modified" response when appropriate. In any case this method will set the e-tag header, if the task
* response has generated an e-tag.
*
* @param task the task for which to generate the "Not Modified" response.
* @return true if a response has been send; false if not.
*/
private boolean sendNotModifiedResponseIfNoneMatch(final Task task) {
//If the task has an ETag, set it in the HTTP header.
if (task.getEtag() != null) {
final RoutingContext context = task.context;
final HttpServerResponse httpResponse = context.response();
final MultiMap httpHeaders = httpResponse.headers();
httpHeaders.add(HttpHeaders.ETAG, task.getEtag());
}
//If the ETag didn't change, or we got a NotModifiedResponse from upstream, return "Not Modified"
if (task.etagMatches() || task instanceof FeatureTask && ((FeatureTask<?, ?>) task).getResponse() instanceof NotModifiedResponse) {
sendResponse(task, NOT_MODIFIED, null, null);
return true;
}
return false;
}
/**
* Creates a response from the processed feature task and send it to the client.
*
* @param task the feature task that is finished processing and for which a response should be returned.
*/
void sendResponse(final FeatureTask task) {
if (sendEmptyResponse(task) || sendNotModifiedResponseIfNoneMatch(task)) {
return;
}
final XyzResponse response = task.getResponse();
if (response instanceof ErrorResponse) {
final ErrorResponse errorResponse = (ErrorResponse) response;
// Note: This is only a warning as it is generally not our fault, so its no real error in the service.
logger.warn(task.getMarker(), "Received an error response: {}", errorResponse);
if (XyzError.TIMEOUT.equals(errorResponse.getError())) {
sendErrorResponse(task.context, GATEWAY_TIMEOUT, XyzError.TIMEOUT, DEFAULT_GATEWAY_TIMEOUT_MESSAGE);
} else {
sendErrorResponse(task.context, BAD_GATEWAY, errorResponse.getError(), DEFAULT_BAD_GATEWAY_MESSAGE);
}
return;
}
if (task.responseType.binary && response instanceof BinaryResponse) {
sendBinaryResponse(task, ((BinaryResponse) response).getMimeType(), ((BinaryResponse) response).getBytes());
return;
}
else {
switch (task.responseType) {
case FEATURE_COLLECTION: {
if (response == null) {
sendGeoJsonResponse(task, new FeatureCollection().serialize());
return;
}
if (response instanceof FeatureCollection) {
// Warning: We need to use "toString()" here and NOT Json.encode, because in fact the feature collection may be an
// LazyParsedFeatureCollection and in that case only toString will work as intended!
sendGeoJsonResponse(task, response.serialize());
return;
}
break;
}
case FEATURE:
if (response == null) {
sendNotFoundJsonResponse(task);
return;
}
if (response instanceof FeatureCollection) {
try {
final FeatureCollection collection = (FeatureCollection) response;
if (collection.getFeatures() == null || collection.getFeatures().size() == 0) {
sendNotFoundJsonResponse(task);
return;
}
sendGeoJsonResponse(task, Json.encode(collection.getFeatures().get(0)));
}
catch (JsonProcessingException e) {
logger.error(task.getMarker(), "The service received an invalid response and is unable to serialize it.", e);
sendErrorResponse(task.context, INTERNAL_SERVER_ERROR, XyzError.EXCEPTION,
"The service received an invalid response and is unable to serialize it.");
}
return;
}
break;
case COUNT_RESPONSE:
if (response instanceof StatisticsResponse) {
XyzResponse transformedResponse = new CountResponse()
.withCount(((StatisticsResponse) response).getCount().getValue())
.withEstimated(((StatisticsResponse) response).getCount().getEstimated())
.withEtag(response.getEtag());
sendJsonResponse(task, Json.encode(transformedResponse));
return;
}
break;
case CHANGESET_COLLECTION:
if (response instanceof ChangesetCollection) {
sendJsonResponse(task, Json.encode(response));
return;
}
case COMPACT_CHANGESET:
if (response instanceof CompactChangeset) {
sendJsonResponse(task, Json.encode(response));
return;
}
case STATISTICS_RESPONSE:
if (response instanceof StatisticsResponse) {
sendJsonResponse(task, Json.encode(response));
return;
}
case HISTORY_STATISTICS_RESPONSE:
if (response instanceof HistoryStatisticsResponse) {
sendJsonResponse(task, Json.encode(response));
return;
}
case EMPTY:
sendEmptyResponse(task);
return;
default:
}
}
logger.warn(task.getMarker(), "Invalid response for request {}: {}, stack-trace: {}", task.responseType, response, new Exception());
sendErrorResponse(task.context, BAD_GATEWAY, XyzError.EXCEPTION,
"Received an invalid response from the storage connector, expected '" + task.responseType.name() + "', but received: '"
+ response.getClass().getSimpleName() + "'");
}
/**
* Helper method which returns the marker for the JSON writer depending on which parameters the user has access in the response. These
* output parameters are controlled by the task.view property and additionally by the accessConnectors
*
* @param view the view
* @return the type
*/
private Class<? extends Public> getViewType(final SpaceTask.View view) {
switch (view) {
case FULL:
return Internal.class;
case CONNECTOR_RIGHTS:
return WithConnectors.class;
default:
return Public.class;
}
}
/**
* Creates a response from the processed space task and send it to the client.
*
* @param task the space task that is finished processing and for which a response should be returned.
* @throws JsonProcessingException if serializing the content failed.
*/
void sendResponse(final SpaceTask<?> task) throws JsonProcessingException {
if (sendEmptyResponse(task) || sendNotModifiedResponseIfNoneMatch(task)) {
return;
}
final Class<?> view = getViewType(task.view);
switch (task.responseType) {
case SPACE: {
if (task.responseSpaces == null || task.responseSpaces.size() == 0) {
sendNotFoundResponse(task);
return;
}
final String geoJson = DatabindCodec.mapper().writerWithView(view).writeValueAsString(task.responseSpaces.get(0));
sendGeoJsonResponse(task, geoJson);
return;
}
case SPACE_LIST: {
if (task.responseSpaces == null || task.responseSpaces.size() == 0) {
sendJsonResponse(task, Json.encode(Collections.EMPTY_LIST));
return;
}
final String geoJson = DatabindCodec.mapper().writerWithView(view).writeValueAsString(task.responseSpaces);
sendJsonResponse(task, geoJson);
return;
}
default:
}
// Invalid response.
logger.error(task.getMarker(), "Invalid response for requested type {}: {}, stack-trace: {}", task.responseType,
task.responseSpaces, new Exception());
sendErrorResponse(task.context, INTERNAL_SERVER_ERROR, XyzError.EXCEPTION,
"Internally generated invalid response, expected: " + task.responseType);
}
/**
* Send an error response to the client when an exception occurred while processing a task.
*
* @param task the task for which to return an error response.
* @param e the exception that should be used to generate an {@link ErrorResponse}, if null an internal server error is returned.
*/
void sendErrorResponse(final Task task, final Throwable e) {
sendErrorResponse(task.context, e);
}
/**
* Send an error response to the client when an exception occurred while processing a task.
*
* @param context the context for which to return an error response.
* @param e the exception that should be used to generate an {@link ErrorResponse}, if null an internal server error is returned.
*/
protected void sendErrorResponse(final RoutingContext context, final Throwable e) {
if (e instanceof TaskPipeline.PipelineCancelledException)
return;
if (e instanceof HttpException) {
final HttpException httpException = (HttpException) e;
if (INTERNAL_SERVER_ERROR.code() != httpException.status.code()) {
XyzError error;
if (BAD_GATEWAY.code() == httpException.status.code()) {
error = XyzError.BAD_GATEWAY;
} else if (GATEWAY_TIMEOUT.code() == httpException.status.code()) {
error = XyzError.TIMEOUT;
} else if (BAD_REQUEST.code() == httpException.status.code()) {
error = XyzError.ILLEGAL_ARGUMENT;
} else {
error = XyzError.EXCEPTION;
}
//This is an exception sent by intention and nothing special, no need for stacktrace logging.
logger.warn("Error was handled by Api and will be sent as response: {}", httpException.status.code());
sendErrorResponse(context, httpException, error);
return;
}
}
//This is an exception that is not done by intention.
logger.error("Unintentional Error:", e);
XYZHubRESTVerticle.sendErrorResponse(context, e);
}
/**
* Send an error response to the client.
*
* @param context the routing context for which to return an error response.
* @param status the HTTP status code to set.
* @param error the error type that will become part of the {@link ErrorResponse}.
* @param errorMessage the error message that will become part of the {@link ErrorResponse}.
*/
private void sendErrorResponse(final RoutingContext context, final HttpResponseStatus status, final XyzError error,
final String errorMessage) {
context.response()
.putHeader(CONTENT_TYPE, APPLICATION_JSON)
.setStatusCode(status.code())
.setStatusMessage(status.reasonPhrase())
.end(new ErrorResponse()
.withStreamId(Api.Context.getMarker(context).getName())
.withError(error)
.withErrorMessage(errorMessage).serialize());
}
/**
* Send an error response to the client.
*
* @param context the routing context for which to return an error response.
* @param httpError the HTTPException with all information
* @param error the error type that will become part of the {@link ErrorResponse}.
*/
private void sendErrorResponse(final RoutingContext context, final HttpException httpError, final XyzError error) {
context.response()
.putHeader(CONTENT_TYPE, APPLICATION_JSON)
.setStatusCode(httpError.status.code())
.setStatusMessage(httpError.status.reasonPhrase())
.end(new ErrorResponse()
.withStreamId(Api.Context.getMarker(context).getName())
.withErrorDetails(httpError.errorDetails)
.withError(error)
.withErrorMessage(httpError.getMessage()).serialize());
}
/**
* Returns an "Not Found" response to the client with http status 404.
*
* @param task the task for which to return a Not Found response.
*/
private void sendNotFoundResponse(final Task task) {
task.context.response()
.setStatusCode(NOT_FOUND.code())
.putHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN)
.end(task.context.request().uri());
}
/**
* Returns an "Not Found" in json format response to the client with http status 404.
*
* @param task the task for which to return a Not Found response.
*/
private void sendNotFoundJsonResponse(final Task task) {
sendErrorResponse(task, new HttpException(NOT_FOUND, "The requested resource does not exist."));
}
/**
* Returns a response to the client with JSON content and status 200.
*
* @param task the task for which to return the JSON response.
*/
private void sendJsonResponse(final Task<?, ?> task, final String json) {
sendResponse(task, OK, APPLICATION_JSON, json.getBytes());
}
/**
* Returns a response to the client with GeoJSON content and status 200.
*
* @param task the task for which to return the GeoJSON response.
*/
private void sendGeoJsonResponse(final Task task, final String geoJson) {
sendResponse(task, OK, APPLICATION_GEO_JSON, geoJson.getBytes());
}
/**
* Returns a response to the client using the given mimeType as content-type with binary content and status 200.
*
* @param task
* @param mimeType
* @param bytes
*/
private void sendBinaryResponse(Task task, String mimeType, byte[] bytes) {
sendResponse(task, OK, mimeType, bytes);
}
protected long getMaxResponseLength(final RoutingContext context) {
long serviceSize = MAX_SERVICE_RESPONSE_SIZE > 0 ? MAX_SERVICE_RESPONSE_SIZE : Long.MAX_VALUE;
long httpSize = MAX_HTTP_RESPONSE_SIZE > 0 ? MAX_HTTP_RESPONSE_SIZE : Long.MAX_VALUE;
return XYZHttpContentCompressor.isCompressionEnabled(context.request().getHeader(ACCEPT_ENCODING)) ? serviceSize : httpSize;
}
private void sendResponse(final Task task, HttpResponseStatus status, String contentType, final byte[] response) {
HttpServerResponse httpResponse = task.context.response().setStatusCode(status.code());
CacheProfile cacheProfile = task.getCacheProfile();
if (cacheProfile.browserTTL > 0) {
httpResponse.putHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + (cacheProfile.browserTTL / 1000));
}
if (Service.configuration.INCLUDE_HEADERS_FOR_DECOMPRESSED_IO_SIZE){
RoutingContext context = task.context;
// the body is discarded already, but the request size is stored in the access log object
long requestSize = Context.getAccessLog(context).reqInfo.size;
long responseSize = response == null ? 0 : response.length;
context.response().putHeader(Service.configuration.DECOMPRESSED_INPUT_SIZE_HEADER_NAME, String.valueOf(requestSize));
context.response().putHeader(Service.configuration.DECOMPRESSED_OUTPUT_SIZE_HEADER_NAME, String.valueOf(responseSize));
}
if (response == null || response.length == 0) {
if (contentType != null)
httpResponse.putHeader(CONTENT_TYPE, contentType);
httpResponse.end();
} else if (response.length > getMaxResponseLength(task.context)) {
sendErrorResponse(task.context, new HttpException(RESPONSE_PAYLOAD_TOO_LARGE, RESPONSE_PAYLOAD_TOO_LARGE_MESSAGE));
} else {
httpResponse.putHeader(CONTENT_TYPE, contentType);
httpResponse.end(Buffer.buffer(response));
}
}
protected void sendResponse(RoutingContext context, HttpResponseStatus status, Object o) {
HttpServerResponse httpResponse = context.response().setStatusCode(status.code());
byte[] response;
try {
if(o instanceof ByteArrayOutputStream)
response = ((ByteArrayOutputStream) o).toByteArray();
else
response = Json.encode(o).getBytes();
} catch (EncodeException e) {
sendErrorResponse(context, new HttpException(INTERNAL_SERVER_ERROR, "Could not serialize response.", e));
return;
}
if (response.length == 0) {
httpResponse.setStatusCode(NO_CONTENT.code()).end();
} else if (response.length > getMaxResponseLength(context)) {
sendErrorResponse(context, new HttpException(RESPONSE_PAYLOAD_TOO_LARGE, RESPONSE_PAYLOAD_TOO_LARGE_MESSAGE));
} else {
httpResponse.putHeader(CONTENT_TYPE, APPLICATION_JSON);
httpResponse.end(Buffer.buffer(response));
}
}
public static class HeaderValues {
public static final String STREAM_ID = "Stream-Id";
public static final String STREAM_INFO = "Stream-Info";
public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security";
public static final String APPLICATION_GEO_JSON = "application/geo+json";
public static final String APPLICATION_JSON = "application/json";
public static final String APPLICATION_VND_MAPBOX_VECTOR_TILE = "application/vnd.mapbox-vector-tile";
public static final String APPLICATION_VND_HERE_FEATURE_MODIFICATION_LIST = "application/vnd.here.feature-modification-list";
public static final String APPLICATION_VND_HERE_CHANGESET_COLLECTION = "application/vnd.here.changeset-collection";
public static final String APPLICATION_VND_HERE_COMPACT_CHANGESET = "application/vnd.here.compact-changeset";
}
private static class XYZHttpContentCompressor extends HttpContentCompressor {
private static final XYZHttpContentCompressor instance = new XYZHttpContentCompressor();
static boolean isCompressionEnabled(String acceptEncoding) {
if (acceptEncoding == null) {
return false;
}
final ZlibWrapper wrapper = instance.determineWrapper(acceptEncoding);
return wrapper == ZlibWrapper.GZIP || wrapper == ZlibWrapper.ZLIB;
}
}
public static final class Context {
private static final String MARKER = "marker";
private static final String ACCESS_LOG = "accessLog";
private static final String JWT = "jwt";
private static final String QUERY_PARAMS = "queryParams";
/**
* Returns the log marker for the request.
* TODO move to {@link com.here.xyz.hub.util.logging.LogUtil}
* @return the marker or null, if no marker was found.
*/
public static Marker getMarker(RoutingContext context) {
if (context == null) {
return null;
}
Marker marker = context.get(MARKER);
if (marker == null) {
String sid = context.request().getHeader(STREAM_ID);
marker = new Log4jMarker( sid != null ? sid : STREAM_ID + "-null" );
context.put(MARKER, marker);
}
return marker;
}
/**
* Returns the access log object for this request.
* TODO move to {@link com.here.xyz.hub.util.logging.LogUtil}
* @param context the routing context.
* @return the access log object
*/
public static AccessLog getAccessLog(RoutingContext context) {
if (context == null) {
return null;
}
AccessLog accessLog = context.get(ACCESS_LOG);
if (accessLog == null) {
accessLog = new AccessLog();
context.put(ACCESS_LOG, accessLog);
}
return accessLog;
}
/**
* Returns the log marker for the request.
*
* @return the marker or null, if no marker was found.
*/
public static JWTPayload getJWT(RoutingContext context) {
if (context == null) {
return null;
}
JWTPayload payload = context.get(JWT);
if (payload == null && context.user() != null) {
payload = DatabindCodec.mapper().convertValue(context.user().principal(), JWTPayload.class);
context.put(JWT, payload);
}
return payload;
}
/**
* Returns the custom parsed query parameters.
*
* Temporary solution until https://github.com/vert-x3/issues/issues/380 is resolved.
*/
private static final String[] nonDecodeList = { Query.TAGS };
static MultiMap getQueryParameters(RoutingContext context) {
MultiMap queryParams = context.get(QUERY_PARAMS);
if (queryParams != null) {
return queryParams;
}
final MultiMap map = MultiMap.caseInsensitiveMultiMap();
String query = context.request().query();
if (query != null && query.length() > 0) {
String[] paramStrings = query.split("&");
for (String paramString : paramStrings) {
int eqDelimiter = paramString.indexOf("=");
if (eqDelimiter > 0) {
String key = paramString.substring(0, eqDelimiter);
boolean decode = !ArrayUtils.contains(nonDecodeList,key);
String rawValue = paramString.substring(eqDelimiter + 1);
if (rawValue.length() > 0) {
String[] values = rawValue.split(",");
Stream.of(values).forEach(v -> {
try {
map.add(key, (decode ? URLDecoder.decode(v, Charset.defaultCharset().name()) : v ));
} catch (UnsupportedEncodingException ignored) {
}
});
}
}
}
}
context.put(QUERY_PARAMS, map);
return map;
}
public static String getAuthor(RoutingContext context) {
if (Service.configuration.USE_AUTHOR_FROM_HEADER)
return context.request().getHeader(AUTHOR_HEADER);
return getJWT(context).aid;
}
}
}