Patch NPE in Unirest HttpResponse::getBody when getRawBody is null
[vid.git] / vid-app-common / src / main / java / org / onap / vid / client / UnirestPatch.kt
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.vid.client
22
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
28
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
32
33 private fun <T> willGetBodyTriggerNPE(httpResponse: HttpResponse<T>) =
34         httpResponse.rawBody == null || httpResponse.rawBody.available() == 0
35
36 private val dummyHttpResponse = BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "ok")
37
38 /**
39  * This class inherits HttpResponse to have compatible interface,
40  * but implementation is done through delegation to another
41  * instance.
42  * For that, it's enough to pass dummy values to HttpResponse's
43  * constructor, as parent HttpResponse methods won't be used,
44  * only overridden.
45  */
46 private class HttpResponsePatch<T>(private val delegatee: HttpResponse<T>) : HttpResponse<T>(
47         dummyHttpResponse, null, null
48 ) {
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
55 }