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.http.HttpVersion
26 import org.apache.http.message.BasicHttpResponse
27 import java.io.InputStream
29 /// Patch NPE in joshworks's Unirest HttpResponse::getBody when getRawBody is null
30 fun <T> patched(httpResponse: HttpResponse<T>) =
31 if (willGetBodyTriggerNPE(httpResponse)) HttpResponsePatch(httpResponse) else httpResponse
33 private fun <T> willGetBodyTriggerNPE(httpResponse: HttpResponse<T>) =
34 httpResponse.rawBody == null || httpResponse.rawBody.available() == 0
36 private val dummyHttpResponse = BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "ok")
39 * This class inherits HttpResponse to have compatible interface,
40 * but implementation is done through delegation to another
42 * For that, it's enough to pass dummy values to HttpResponse's
43 * constructor, as parent HttpResponse methods won't be used,
46 private class HttpResponsePatch<T>(private val delegatee: HttpResponse<T>) : HttpResponse<T>(
47 dummyHttpResponse, null, null
49 override fun getBody(): T? = if (willGetBodyTriggerNPE(delegatee)) null else delegatee.body
50 override fun getHeaders(): Headers? = delegatee.headers
51 override fun getStatus() = delegatee.status
52 override fun isSuccessful() = delegatee.isSuccessful
53 override fun getStatusText(): String? = delegatee.statusText
54 override fun getRawBody(): InputStream? = delegatee.rawBody