2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.vid.client
23 import io.joshworks.restclient.http.Headers
24 import io.joshworks.restclient.http.HttpResponse
25 import org.apache.commons.io.IOUtils
26 import org.apache.http.HttpVersion
27 import org.apache.http.message.BasicHttpResponse
28 import java.io.InputStream
29 import java.nio.charset.StandardCharsets
31 /// Patch NPE in joshworks's Unirest HttpResponse::getBody when getRawBody is null
32 fun <T> patched(httpResponse: HttpResponse<T>) =
33 if (willGetBodyTriggerNPE(httpResponse)) HttpResponsePatch(httpResponse) else httpResponse
35 private fun <T> willGetBodyTriggerNPE(httpResponse: HttpResponse<T>) =
36 httpResponse.rawBody == null || httpResponse.rawBody.available() == 0
38 private val dummyHttpResponse = BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "ok")
40 fun extractRawAsString(response: HttpResponse<*>?): String {
42 if (response == null || response.rawBody==null) return ""
43 response.rawBody.reset()
44 return IOUtils.toString(response.rawBody, StandardCharsets.UTF_8.name())
45 } catch (e: Exception) {
52 * This class inherits HttpResponse to have compatible interface,
53 * but implementation is done through delegation to another
55 * For that, it's enough to pass dummy values to HttpResponse's
56 * constructor, as parent HttpResponse methods won't be used,
59 private class HttpResponsePatch<T>(private val delegatee: HttpResponse<T>) : HttpResponse<T>(
60 dummyHttpResponse, null, null
62 override fun getBody(): T? = if (willGetBodyTriggerNPE(delegatee)) null else delegatee.body
63 override fun getHeaders(): Headers? = delegatee.headers
64 override fun getStatus() = delegatee.status
65 override fun isSuccessful() = delegatee.isSuccessful
66 override fun getStatusText(): String? = delegatee.statusText
67 override fun getRawBody(): InputStream? = delegatee.rawBody