2 * ============LICENSE_START=======================================================
3 * dcaegen2-collectors-veshv
4 * ================================================================================
5 * Copyright (C) 2018 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.simulators.xnf.impl
22 import arrow.effects.IO
23 import org.onap.dcae.collectors.veshv.domain.PayloadWireFrameMessage
24 import org.onap.dcae.collectors.veshv.utils.logging.Logger
25 import org.onap.dcae.collectors.veshv.ves.message.generator.api.MessageGenerator
26 import org.onap.dcae.collectors.veshv.ves.message.generator.api.MessageParameters
27 import org.onap.dcae.collectors.veshv.ves.message.generator.api.MessageType
28 import org.onap.ves.VesEventV5.VesEvent.CommonEventHeader.Domain
29 import ratpack.exec.Promise
30 import ratpack.handling.Chain
31 import ratpack.handling.Context
32 import ratpack.server.RatpackServer
33 import ratpack.server.ServerConfig
34 import reactor.core.publisher.Flux
35 import reactor.core.scheduler.Schedulers
36 import javax.json.Json
37 import javax.json.JsonArray
40 * @author Jakub Dudycz <jakub.dudycz@nokia.com>
43 internal class HttpServer(private val vesClient: XnfSimulator) {
45 fun start(port: Int): IO<RatpackServer> = IO {
46 RatpackServer.start { server ->
47 server.serverConfig(ServerConfig.embedded().port(port))
48 .handlers(this::configureHandlers)
52 private fun configureHandlers(chain: Chain) {
54 .post("simulator/sync") { ctx ->
55 createMessageFlux(ctx)
56 .map { vesClient.sendIo(it) }
57 .map { it.unsafeRunSync() }
58 .onError { handleException(it, ctx) }
59 .then { sendAcceptedResponse(ctx) }
61 .post("simulator/async") { ctx ->
62 createMessageFlux(ctx)
63 .map { vesClient.sendRx(it) }
64 .map { it.subscribeOn(Schedulers.elastic()).subscribe() }
65 .onError { handleException(it, ctx) }
66 .then { sendAcceptedResponse(ctx) }
70 private fun createMessageFlux(ctx: Context): Promise<Flux<PayloadWireFrameMessage>> {
71 return ctx.request.body
72 .map { Json.createReader(it.inputStream).readArray() }
73 .map { extractMessageParameters(it) }
74 .map { MessageGenerator.INSTANCE.createMessageFlux(it) }
77 private fun extractMessageParameters(request: JsonArray): List<MessageParameters> =
80 .map { it.asJsonObject() }
83 val domain = Domain.valueOf(it.getString("domain"))
84 val messageType = MessageType.valueOf(it.getString("messageType"))
85 val messagesAmount = it.getJsonNumber("messagesAmount").longValue()
86 MessageParameters(domain, messageType, messagesAmount)
88 } catch (e: Exception) {
89 throw ValidationException("Validating request body failed", e)
92 private fun sendAcceptedResponse(ctx: Context) {
95 .send(CONTENT_TYPE_APPLICATION_JSON, Json.createObjectBuilder()
96 .add("response", "Request accepted")
101 private fun handleException(t: Throwable, ctx: Context) {
102 logger.warn("Failed to process the request - ${t.localizedMessage}")
103 logger.debug("Exception thrown when processing the request", t)
105 .status(STATUS_BAD_REQUEST)
106 .send(CONTENT_TYPE_APPLICATION_JSON, Json.createObjectBuilder()
107 .add("response", "Request was not accepted")
108 .add("exception", t.localizedMessage)
114 private val logger = Logger(HttpServer::class)
115 const val STATUS_OK = 200
116 const val STATUS_BAD_REQUEST = 400
117 const val CONTENT_TYPE_APPLICATION_JSON = "application/json"
121 internal class ValidationException(message: String?, cause: Exception) : Exception(message, cause)