aboutsummaryrefslogtreecommitdiffstats
path: root/hv-collector-xnf-simulator/src/main/kotlin/org/onap/dcae/collectors/veshv/simulators/xnf/impl/HttpServer.kt
blob: 6346b648a740a564a299924b1f0e43b876285ee1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
 * ============LICENSE_START=======================================================
 * dcaegen2-collectors-veshv
 * ================================================================================
 * Copyright (C) 2018 NOKIA
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.dcae.collectors.veshv.simulators.xnf.impl

import arrow.effects.IO
import org.onap.dcae.collectors.veshv.domain.PayloadWireFrameMessage
import org.onap.dcae.collectors.veshv.simulators.xnf.config.MessageParameters
import org.onap.dcae.collectors.veshv.utils.logging.Logger
import ratpack.exec.Promise
import ratpack.handling.Chain
import ratpack.handling.Context
import ratpack.server.RatpackServer
import ratpack.server.ServerConfig
import reactor.core.publisher.Flux
import reactor.core.scheduler.Schedulers
import javax.json.Json
import javax.json.JsonObject

/**
 * @author Jakub Dudycz <jakub.dudycz@nokia.com>
 * @since June 2018
 */
internal class HttpServer(private val vesClient: XnfSimulator) {

    fun start(port: Int = DEFAULT_PORT): IO<RatpackServer> = IO {
        RatpackServer.start { server ->
            server.serverConfig(ServerConfig.embedded().port(port))
                    .handlers(this::configureHandlers)
        }
    }


    private fun configureHandlers(chain: Chain) {
        chain
                .post("simulator/sync") { ctx ->
                    createMessageFlux(ctx)
                            .map { vesClient.sendIo(it) }
                            .map { it.unsafeRunSync() }
                            .onError { handleException(it, ctx) }
                            .then { sendAcceptedResponse(ctx) }
                }
                .post("simulator/async") { ctx ->
                    createMessageFlux(ctx)
                            .map { vesClient.sendRx(it) }
                            .map { it.subscribeOn(Schedulers.elastic()).subscribe() }
                            .onError { handleException(it, ctx) }
                            .then { sendAcceptedResponse(ctx) }
                }
    }

    private fun createMessageFlux(ctx: Context): Promise<Flux<PayloadWireFrameMessage>> {
        return ctx.request.body
                .map { Json.createReader(it.inputStream).readObject() }
                .map { extractMessageParameters(it) }
                .map { MessageGeneratorImpl.INSTANCE.createMessageFlux(it) }
    }

    private fun sendAcceptedResponse(ctx: Context) {
        ctx.response
                .status(STATUS_OK)
                .send(CONTENT_TYPE_APPLICATION_JSON, Json.createObjectBuilder()
                        .add("response", "Request accepted")
                        .build()
                        .toString())
    }

    private fun handleException(t: Throwable, ctx: Context) {
        logger.warn("Failed to process the request - ${t.localizedMessage}")
        logger.debug("Exception thrown when processing the request", t)
        ctx.response
                .status(STATUS_BAD_REQUEST)
                .send(CONTENT_TYPE_APPLICATION_JSON, Json.createObjectBuilder()
                        .add("response", "Request was not accepted")
                        .add("exception", t.localizedMessage)
                        .build()
                        .toString())
    }

    private fun extractMessageParameters(request: JsonObject): MessageParameters =
            try {
                val commonEventHeader = MessageGeneratorImpl.INSTANCE
                        .parseCommonHeader(request.getJsonObject("commonEventHeader"))
                val messagesAmount = request.getJsonNumber("messagesAmount").longValue()
                MessageParameters(commonEventHeader, messagesAmount)
            } catch (e: Exception) {
                throw ValidationException("Validating request body failed", e)
            }


    companion object {
        private val logger = Logger(HttpServer::class)
        const val DEFAULT_PORT = 5000
        const val STATUS_OK = 200
        const val STATUS_BAD_REQUEST = 400
        const val CONTENT_TYPE_APPLICATION_JSON = "application/json"
    }
}

internal class ValidationException(message: String?, cause: Exception) : Exception(message, cause)