2 * ============LICENSE_START=======================================================
3 * dcaegen2-collectors-veshv
4 * ================================================================================
5 * Copyright (C) 2019 NOKIA
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=========================================================
20 package org.onap.dcae.collectors.veshv.utils.http
22 import arrow.core.Either
23 import org.onap.dcae.collectors.veshv.utils.logging.Logger
24 import reactor.core.publisher.Mono
25 import reactor.core.publisher.toMono
26 import reactor.netty.NettyOutbound
27 import reactor.netty.http.server.HttpServerResponse
28 import javax.json.Json
30 private val logger = Logger("org.onap.dcae.collectors.veshv.utils.http.netty")
32 fun HttpServerResponse.sendOrError(action: ()->Unit) = sendAndHandleErrors(
40 Json.createObjectBuilder().add("response", "Request accepted").build()
46 fun HttpServerResponse.sendAndHandleErrors(response: Mono<Response>) =
49 logger.withWarn { log("Error occurred. Sending .", it) }
50 errorResponse(it.localizedMessage).toMono()
53 sendResponse(it).then()
56 fun <A> HttpServerResponse.sendEitherErrorOrResponse(response: Either<A, Response>) =
58 is Either.Left -> sendResponse(errorResponse(response.a.toString())).then()
59 is Either.Right -> sendAndHandleErrors(Mono.just(response.b))
63 fun HttpServerResponse.sendResponse(response: Response): NettyOutbound {
64 val respWithStatus = status(response.status.number)
65 val responseContent = response.content
67 return respWithStatus.sendString(
68 Mono.just(responseContent.serializer.run { responseContent.value.show() })
72 private fun errorResponse(message: String?): Response =
74 HttpStatus.INTERNAL_SERVER_ERROR,
77 Json.createObjectBuilder().add("error", message).build()