diff options
Diffstat (limited to 'ms/blueprintsprocessor/modules/commons/rest-lib')
14 files changed, 383 insertions, 254 deletions
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt index 182d5defa..9e1be36a7 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt @@ -35,19 +35,16 @@ open class BluePrintRestLibConfiguration * Exposed Dependency Service by this Rest Lib Module */ fun BluePrintDependencyService.restLibPropertyService(): BluePrintRestLibPropertyService = - instance(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) - + instance(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) fun BluePrintDependencyService.restClientService(selector: String): BlueprintWebClientService { return restLibPropertyService().blueprintWebClientService(selector) } - fun BluePrintDependencyService.restClientService(jsonNode: JsonNode): BlueprintWebClientService { return restLibPropertyService().blueprintWebClientService(jsonNode) } - class RestLibConstants { companion object { const val SERVICE_BLUEPRINT_REST_LIB_PROPERTY = "blueprint-rest-lib-property-service" diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt index ea32a1635..4c18f81ab 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt @@ -35,11 +35,13 @@ open class SSLRestClientProperties : RestClientProperties() { // FIXME("Define basic auth userName and password properties") open class SSLBasicAuthRestClientProperties : SSLRestClientProperties() { + var basicAuth: BasicAuthRestClientProperties? = null } // FIXME("Define token properties") open class SSLTokenAuthRestClientProperties : SSLRestClientProperties() { + var tokenAuth: TokenAuthRestClientProperties? = null } diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt index a3da44f61..429931377 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt @@ -129,9 +129,9 @@ open class SSLRestClientPropertiesBuilder : RestClientPropertiesBuilder() { } open class SSLBasicAuthRestClientPropertiesBuilder : SSLRestClientPropertiesBuilder() { - //TODO() + // TODO() } open class SSLTokenAuthRestClientPropertiesBuilder : SSLRestClientPropertiesBuilder() { - //TODO() -}
\ No newline at end of file + // TODO() +} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/filters/RestServerLoggingWebFilter.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/filters/RestServerLoggingWebFilter.kt index 5aaee24de..5b6691eff 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/filters/RestServerLoggingWebFilter.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/filters/RestServerLoggingWebFilter.kt @@ -24,15 +24,15 @@ import org.springframework.web.server.WebFilterChain import reactor.core.publisher.Mono import reactor.util.context.Context - open class RestServerLoggingWebFilter : WebFilter { override fun filter(serverWebExchange: ServerWebExchange, webFilterChain: WebFilterChain): Mono<Void> { val loggingService = RestLoggerService() loggingService.entering(serverWebExchange.request) val filterChain = webFilterChain.filter(serverWebExchange).subscriberContext( - Context.of(MDCContext, MDCContext())) + Context.of(MDCContext, MDCContext()) + ) loggingService.exiting(serverWebExchange.request, serverWebExchange.response) return filterChain } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt index 9ce3beab6..540b3d9ad 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt @@ -21,37 +21,42 @@ import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import java.nio.charset.Charset -import java.util.* +import java.util.Base64 -class BasicAuthRestClientService(private val restClientProperties: - BasicAuthRestClientProperties) : +class BasicAuthRestClientService( + private val restClientProperties: + BasicAuthRestClientProperties +) : BlueprintWebClientService { override fun defaultHeaders(): Map<String, String> { - val encodedCredentials = setBasicAuth(restClientProperties.username, - restClientProperties.password) + val encodedCredentials = setBasicAuth( + restClientProperties.username, + restClientProperties.password + ) return mapOf( HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials") + HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials" + ) } override fun host(uri: String): String { return restClientProperties.url + uri } - override fun convertToBasicHeaders(headers: Map<String, String>): - Array<BasicHeader> { + Array<BasicHeader> { val customHeaders: MutableMap<String, String> = headers.toMutableMap() - //inject additionalHeaders + // inject additionalHeaders customHeaders.putAll(verifyAdditionalHeaders(restClientProperties)) if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { val encodedCredentials = setBasicAuth( restClientProperties.username, - restClientProperties.password) + restClientProperties.password + ) customHeaders[HttpHeaders.AUTHORIZATION] = "Basic $encodedCredentials" } @@ -61,7 +66,7 @@ class BasicAuthRestClientService(private val restClientProperties: private fun setBasicAuth(username: String, password: String): String { val credentialsString = "$username:$password" return Base64.getEncoder().encodeToString( - credentialsString.toByteArray(Charset.defaultCharset())) + credentialsString.toByteArray(Charset.defaultCharset()) + ) } - } diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt index 84ba7d414..8f528a2ef 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt @@ -20,7 +20,14 @@ package org.onap.ccsdk.cds.blueprintsprocessor.rest.service import com.fasterxml.jackson.databind.JsonNode import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.rest.* +import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.PolicyManagerRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLBasicAuthRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLTokenAuthRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.TokenAuthRestClientProperties import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.stereotype.Service @@ -43,7 +50,7 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic open fun blueprintWebClientService(jsonNode: JsonNode): BlueprintWebClientService { val service = preInterceptor?.getInstance(jsonNode) - ?: blueprintWebClientService(restClientProperties(jsonNode)) + ?: blueprintWebClientService(restClientProperties(jsonNode)) return postInterceptor?.getInstance(jsonNode, service) ?: service } @@ -58,7 +65,8 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic fun restClientProperties(prefix: String): RestClientProperties { val type = bluePrintPropertiesService.propertyBeanType( - "$prefix.type", String::class.java) + "$prefix.type", String::class.java + ) return when (type) { RestLibConstants.TYPE_BASIC_AUTH -> { basicAuthRestClientProperties(prefix) @@ -80,8 +88,10 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic policyManagerRestClientProperties(prefix) } else -> { - throw BluePrintProcessorException("Rest adaptor($type) is" + - " not supported") + throw BluePrintProcessorException( + "Rest adaptor($type) is" + + " not supported" + ) } } } @@ -111,7 +121,8 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic } else -> { throw BluePrintProcessorException( - "Rest adaptor($type) is not supported") + "Rest adaptor($type) is not supported" + ) } } } @@ -138,24 +149,28 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic private fun tokenRestClientProperties(prefix: String): TokenAuthRestClientProperties { return bluePrintPropertiesService.propertyBeanType( - prefix, TokenAuthRestClientProperties::class.java) + prefix, TokenAuthRestClientProperties::class.java + ) } private fun basicAuthRestClientProperties(prefix: String): BasicAuthRestClientProperties { return bluePrintPropertiesService.propertyBeanType( - prefix, BasicAuthRestClientProperties::class.java) + prefix, BasicAuthRestClientProperties::class.java + ) } private fun sslBasicAuthRestClientProperties(prefix: String): SSLRestClientProperties { val sslProps: SSLBasicAuthRestClientProperties = - bluePrintPropertiesService.propertyBeanType( - prefix, SSLBasicAuthRestClientProperties::class.java) + bluePrintPropertiesService.propertyBeanType( + prefix, SSLBasicAuthRestClientProperties::class.java + ) val basicProps: BasicAuthRestClientProperties = - bluePrintPropertiesService.propertyBeanType( - prefix, BasicAuthRestClientProperties::class.java) + bluePrintPropertiesService.propertyBeanType( + prefix, BasicAuthRestClientProperties::class.java + ) sslProps.basicAuth = basicProps return sslProps } @@ -164,11 +179,15 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic SSLRestClientProperties { val sslProps: SSLTokenAuthRestClientProperties = - bluePrintPropertiesService.propertyBeanType(prefix, - SSLTokenAuthRestClientProperties::class.java) + bluePrintPropertiesService.propertyBeanType( + prefix, + SSLTokenAuthRestClientProperties::class.java + ) val basicProps: TokenAuthRestClientProperties = - bluePrintPropertiesService.propertyBeanType(prefix, - TokenAuthRestClientProperties::class.java) + bluePrintPropertiesService.propertyBeanType( + prefix, + TokenAuthRestClientProperties::class.java + ) sslProps.tokenAuth = basicProps return sslProps } @@ -176,13 +195,15 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic private fun sslNoAuthRestClientProperties(prefix: String): SSLRestClientProperties { return bluePrintPropertiesService.propertyBeanType( - prefix, SSLRestClientProperties::class.java) + prefix, SSLRestClientProperties::class.java + ) } private fun policyManagerRestClientProperties(prefix: String): PolicyManagerRestClientProperties { return bluePrintPropertiesService.propertyBeanType( - prefix, PolicyManagerRestClientProperties::class.java) + prefix, PolicyManagerRestClientProperties::class.java + ) } interface PreInterceptor { @@ -197,5 +218,3 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic fun getInstance(selector: String, service: BlueprintWebClientService): BlueprintWebClientService } } - - diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt index 3e31bf9ec..3c8d92c26 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt @@ -23,7 +23,12 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.apache.commons.io.IOUtils import org.apache.http.client.ClientProtocolException -import org.apache.http.client.methods.* +import org.apache.http.client.methods.HttpDelete +import org.apache.http.client.methods.HttpGet +import org.apache.http.client.methods.HttpPatch +import org.apache.http.client.methods.HttpPost +import org.apache.http.client.methods.HttpPut +import org.apache.http.client.methods.HttpUriRequest import org.apache.http.entity.StringEntity import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.HttpClients @@ -57,8 +62,12 @@ interface BlueprintWebClientService { /** High performance non blocking Retry function, If execution block [block] throws BluePrintRetryException * exception then this will perform wait and retrigger accoring to times [times] with delay [delay] */ - suspend fun <T> retry(times: Int = 1, initialDelay: Long = 0, delay: Long = 1000, - block: suspend (Int) -> T): T { + suspend fun <T> retry( + times: Int = 1, + initialDelay: Long = 0, + delay: Long = 1000, + block: suspend (Int) -> T + ): T { val exceptionBlock = { e: Exception -> if (e !is BluePrintRetryException) { throw e @@ -71,8 +80,12 @@ interface BlueprintWebClientService { return this.exchangeResource(methodType, path, request, defaultHeaders()) } - fun exchangeResource(methodType: String, path: String, request: String, - headers: Map<String, String>): WebClientResponse<String> { + fun exchangeResource( + methodType: String, + path: String, + request: String, + headers: Map<String, String> + ): WebClientResponse<String> { /** * TODO: Basic headers in the implementations of this client do not get added * in blocking version, whereas in NB version defaultHeaders get added. @@ -86,11 +99,12 @@ interface BlueprintWebClientService { HttpMethod.PUT -> put(path, request, convertedHeaders, String::class.java) HttpMethod.PATCH -> patch(path, request, convertedHeaders, String::class.java) else -> throw BluePrintProcessorException( - "Unsupported methodType($methodType) attempted on path($path)") + "Unsupported methodType($methodType) attempted on path($path)" + ) } } - //TODO: convert to multi-map + // TODO: convert to multi-map fun convertToBasicHeaders(headers: Map<String, String>): Array<BasicHeader> { return headers.map { BasicHeader(it.key, it.value) }.toTypedArray() } @@ -145,8 +159,10 @@ interface BlueprintWebClientService { @Throws(IOException::class, ClientProtocolException::class) private fun <T> performCallAndExtractTypedWebClientResponse( - httpUriRequest: HttpUriRequest, responseType: Class<T>): - WebClientResponse<T> { + httpUriRequest: HttpUriRequest, + responseType: Class<T> + ): + WebClientResponse<T> { val httpResponse = httpClient().execute(httpUriRequest) val statusCode = httpResponse.statusLine.statusCode httpResponse.entity.content.use { @@ -164,7 +180,7 @@ interface BlueprintWebClientService { } suspend fun <T> getNB(path: String, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>): - WebClientResponse<T> = withContext(Dispatchers.IO) { + WebClientResponse<T> = withContext(Dispatchers.IO) { get(path, additionalHeaders!!, responseType) } @@ -176,8 +192,12 @@ interface BlueprintWebClientService { return postNB(path, request, additionalHeaders, String::class.java) } - suspend fun <T> postNB(path: String, request: Any, additionalHeaders: Array<BasicHeader>?, - responseType: Class<T>): WebClientResponse<T> = withContext(Dispatchers.IO) { + suspend fun <T> postNB( + path: String, + request: Any, + additionalHeaders: Array<BasicHeader>?, + responseType: Class<T> + ): WebClientResponse<T> = withContext(Dispatchers.IO) { post(path, request, additionalHeaders!!, responseType) } @@ -185,14 +205,20 @@ interface BlueprintWebClientService { return putNB(path, request, null, String::class.java) } - suspend fun putNB(path: String, request: Any, - additionalHeaders: Array<BasicHeader>?): WebClientResponse<String> { + suspend fun putNB( + path: String, + request: Any, + additionalHeaders: Array<BasicHeader>? + ): WebClientResponse<String> { return putNB(path, request, additionalHeaders, String::class.java) } - suspend fun <T> putNB(path: String, request: Any, - additionalHeaders: Array<BasicHeader>?, - responseType: Class<T>): WebClientResponse<T> = withContext(Dispatchers.IO) { + suspend fun <T> putNB( + path: String, + request: Any, + additionalHeaders: Array<BasicHeader>?, + responseType: Class<T> + ): WebClientResponse<T> = withContext(Dispatchers.IO) { put(path, request, additionalHeaders!!, responseType) } @@ -201,36 +227,42 @@ interface BlueprintWebClientService { } suspend fun <T> deleteNB(path: String, additionalHeaders: Array<BasicHeader>?): - WebClientResponse<String> { + WebClientResponse<String> { return deleteNB(path, additionalHeaders, String::class.java) } suspend fun <T> deleteNB(path: String, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>): - WebClientResponse<T> = withContext(Dispatchers.IO) { + WebClientResponse<T> = withContext(Dispatchers.IO) { delete(path, additionalHeaders!!, responseType) } suspend fun <T> patchNB(path: String, request: Any, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>): - WebClientResponse<T> = withContext(Dispatchers.IO) { + WebClientResponse<T> = withContext(Dispatchers.IO) { patch(path, request, additionalHeaders!!, responseType) } suspend fun exchangeNB(methodType: String, path: String, request: Any): WebClientResponse<String> { - return exchangeNB(methodType, path, request, hashMapOf(), - String::class.java) + return exchangeNB( + methodType, path, request, hashMapOf(), + String::class.java + ) } suspend fun exchangeNB(methodType: String, path: String, request: Any, additionalHeaders: Map<String, String>?): - WebClientResponse<String> { + WebClientResponse<String> { return exchangeNB(methodType, path, request, additionalHeaders, String::class.java) } - suspend fun <T> exchangeNB(methodType: String, path: String, request: Any, - additionalHeaders: Map<String, String>?, - responseType: Class<T>): WebClientResponse<T> { + suspend fun <T> exchangeNB( + methodType: String, + path: String, + request: Any, + additionalHeaders: Map<String, String>?, + responseType: Class<T> + ): WebClientResponse<T> { - //TODO: possible inconsistency - //NOTE: this basic headers function is different from non-blocking + // TODO: possible inconsistency + // NOTE: this basic headers function is different from non-blocking val convertedHeaders: Array<BasicHeader> = basicHeaders(additionalHeaders!!) return when (HttpMethod.resolve(methodType)) { HttpMethod.GET -> getNB(path, convertedHeaders, responseType) @@ -259,7 +291,7 @@ interface BlueprintWebClientService { } private fun basicHeaders(headers: Map<String, String>?): - Array<BasicHeader> { + Array<BasicHeader> { val basicHeaders = mutableListOf<BasicHeader>() defaultHeaders().forEach { (name, value) -> basicHeaders.add(BasicHeader(name, value)) @@ -278,18 +310,18 @@ interface BlueprintWebClientService { .build() } - //TODO maybe there could be cases where we care about return headers? + // TODO maybe there could be cases where we care about return headers? data class WebClientResponse<T>(val status: Int, val body: T) fun verifyAdditionalHeaders(restClientProperties: RestClientProperties): Map<String, String> { val customHeaders: MutableMap<String, String> = mutableMapOf() - //Extract additionalHeaders from the requestProperties and - //throw an error if HttpHeaders.AUTHORIZATION key (headers are case-insensitive) + // Extract additionalHeaders from the requestProperties and + // throw an error if HttpHeaders.AUTHORIZATION key (headers are case-insensitive) restClientProperties.additionalHeaders?.let { if (it.keys.map { k -> k.toLowerCase().trim() }.contains(HttpHeaders.AUTHORIZATION.toLowerCase())) { val errMsg = "Error in definition of endpoint ${restClientProperties.url}." + - " User-supplied \"additionalHeaders\" cannot contain AUTHORIZATION header with" + - " auth-type \"${RestLibConstants.TYPE_BASIC_AUTH}\"" + " User-supplied \"additionalHeaders\" cannot contain AUTHORIZATION header with" + + " auth-type \"${RestLibConstants.TYPE_BASIC_AUTH}\"" WebClientUtils.log.error(errMsg) throw BluePrintProcessorException(errMsg) } else { diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt index 969de836c..dbb98f849 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt @@ -16,7 +16,13 @@ package org.onap.ccsdk.cds.blueprintsprocessor.rest.service -import kotlinx.coroutines.* +import kotlinx.coroutines.AbstractCoroutine +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.InternalCoroutinesApi +import kotlinx.coroutines.handleCoroutineException +import kotlinx.coroutines.newCoroutineContext import kotlinx.coroutines.reactor.ReactorContext import kotlinx.coroutines.reactor.asCoroutineContext import org.apache.http.message.BasicHeader @@ -37,7 +43,7 @@ import java.net.InetAddress import java.time.ZoneOffset import java.time.ZonedDateTime import java.time.format.DateTimeFormatter -import java.util.* +import java.util.UUID import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext @@ -89,17 +95,19 @@ class RestLoggerService { } } - /** Used in Rest controller API methods to populate MDC context to nested coroutines from reactor web filter context. */ @UseExperimental(InternalCoroutinesApi::class) -fun <T> monoMdc(context: CoroutineContext = EmptyCoroutineContext, - block: suspend CoroutineScope.() -> T?): Mono<T> = Mono.create { sink -> +fun <T> monoMdc( + context: CoroutineContext = EmptyCoroutineContext, + block: suspend CoroutineScope.() -> T? +): Mono<T> = Mono.create { sink -> val reactorContext = (context[ReactorContext]?.context?.putAll(sink.currentContext()) - ?: sink.currentContext()).asCoroutineContext() + ?: sink.currentContext()).asCoroutineContext() /** Populate MDC context only if present in Reactor Context */ - val newContext = if (!reactorContext.context.isEmpty - && reactorContext.context.hasKey(MDCContext)) { + val newContext = if (!reactorContext.context.isEmpty && + reactorContext.context.hasKey(MDCContext) + ) { val mdcContext = reactorContext.context.get<MDCContext>(MDCContext) GlobalScope.newCoroutineContext(context + reactorContext + mdcContext) } else GlobalScope.newCoroutineContext(context + reactorContext) @@ -111,9 +119,10 @@ fun <T> monoMdc(context: CoroutineContext = EmptyCoroutineContext, @InternalCoroutinesApi class MonoMDCCoroutine<in T>( - parentContext: CoroutineContext, - private val sink: MonoSink<T> + parentContext: CoroutineContext, + private val sink: MonoSink<T> ) : AbstractCoroutine<T>(parentContext, true), Disposable { + private var disposed = false override fun onCompleted(value: T) { diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLRestClientService.kt index 0ef1757e2..86e3ced06 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLRestClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLRestClientService.kt @@ -17,6 +17,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.rest.service +import org.apache.http.conn.ssl.NoopHostnameVerifier import org.apache.http.conn.ssl.SSLConnectionSocketFactory import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.HttpClients @@ -32,7 +33,6 @@ import java.io.File import java.io.FileInputStream import java.security.KeyStore import java.security.cert.X509Certificate -import org.apache.http.conn.ssl.NoopHostnameVerifier class SSLRestClientService(private val restClientProperties: SSLRestClientProperties) : BlueprintWebClientService { @@ -44,8 +44,8 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper } private fun getAuthService(): BlueprintWebClientService? { - //type,url and additional headers don't get carried over to TokenAuthRestClientProperties from SSLTokenAuthRestClientProperties - //set them in auth obj to be consistent. TODO: refactor + // type,url and additional headers don't get carried over to TokenAuthRestClientProperties from SSLTokenAuthRestClientProperties + // set them in auth obj to be consistent. TODO: refactor return when (restClientProperties) { is SSLBasicAuthRestClientProperties -> { val basicAuthProps = restClientProperties.basicAuth!! @@ -62,7 +62,7 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper TokenAuthRestClientService(token) } else -> { - //Returns null for No auth + // Returns null for No auth null } } @@ -74,7 +74,8 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper } return mapOf( HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE) + HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE + ) } override fun host(uri: String): String { @@ -104,7 +105,7 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper } sslContext.loadTrustMaterial(File(sslTrust), sslTrustPwd.toCharArray(), acceptingTrustStrategy) - var csf : SSLConnectionSocketFactory + var csf: SSLConnectionSocketFactory if (sslTrustIgnoreHostname) { csf = SSLConnectionSocketFactory(sslContext.build(), NoopHostnameVerifier()) } else { @@ -123,14 +124,16 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper override fun convertToBasicHeaders(headers: Map<String, String>): Array<BasicHeader> { val mergedDefaultAndSuppliedHeaders = defaultHeaders().plus(headers) - //During the initialization, getAuthService() sets the auth variable. - //If it's not null, then we have an authentication mechanism. - //If null - indicates no-auth used + // During the initialization, getAuthService() sets the auth variable. + // If it's not null, then we have an authentication mechanism. + // If null - indicates no-auth used if (auth != null) { return auth!!.convertToBasicHeaders(mergedDefaultAndSuppliedHeaders) } - //inject additionalHeaders - return super.convertToBasicHeaders(mergedDefaultAndSuppliedHeaders - .plus(verifyAdditionalHeaders(restClientProperties))) + // inject additionalHeaders + return super.convertToBasicHeaders( + mergedDefaultAndSuppliedHeaders + .plus(verifyAdditionalHeaders(restClientProperties)) + ) } } diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt index 73b534143..57702f8ac 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt @@ -21,21 +21,24 @@ import org.onap.ccsdk.cds.blueprintsprocessor.rest.TokenAuthRestClientProperties import org.springframework.http.HttpHeaders import org.springframework.http.MediaType -class TokenAuthRestClientService(private val restClientProperties: - TokenAuthRestClientProperties) : +class TokenAuthRestClientService( + private val restClientProperties: + TokenAuthRestClientProperties +) : BlueprintWebClientService { override fun defaultHeaders(): Map<String, String> { return mapOf( HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.AUTHORIZATION to restClientProperties.token!!) + HttpHeaders.AUTHORIZATION to restClientProperties.token!! + ) } override fun convertToBasicHeaders(headers: Map<String, String>): - Array<BasicHeader> { + Array<BasicHeader> { val customHeaders: MutableMap<String, String> = headers.toMutableMap() - //inject additionalHeaders + // inject additionalHeaders customHeaders.putAll(verifyAdditionalHeaders(restClientProperties)) if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { customHeaders[HttpHeaders.AUTHORIZATION] = restClientProperties.token!! diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt index 42006569f..ff4d54730 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt @@ -32,4 +32,4 @@ class WebClientUtils { fun logResponse(): HttpResponseInterceptor = HttpResponseInterceptor { response, _ -> log.info("Response status(${response.statusLine.statusCode} - ${response.statusLine.reasonPhrase})") } } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt index 1e4518a8c..53047d4a8 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt @@ -41,50 +41,59 @@ import kotlin.test.assertFailsWith import kotlin.test.assertNotNull @RunWith(SpringRunner::class) -@ContextConfiguration(classes = [BluePrintRestLibConfiguration::class, BluePrintPropertyConfiguration::class, - BluePrintPropertiesService::class]) -@TestPropertySource(properties = -["blueprintsprocessor.restclient.sample.type=basic-auth", - "blueprintsprocessor.restclient.sample.url=http://localhost:8080", - "blueprintsprocessor.restclient.sample.userId=sampleuser", - "blueprintsprocessor.restclient.sslbasic.type=ssl-basic-auth", - "blueprintsprocessor.restclient.sslbasic.url=https://localhost:8443", - "blueprintsprocessor.restclient.sslbasic.username=admin", - "blueprintsprocessor.restclient.sslbasic.password=cds", - "blueprintsprocessor.restclient.sslbasic.keyStoreInstance=PKCS12", - "blueprintsprocessor.restclient.sslbasic.sslTrust=src/test/resources/keystore.p12", - "blueprintsprocessor.restclient.sslbasic.sslTrustPassword=changeit", - "blueprintsprocessor.restclient.ssltoken.type=ssl-token-auth", - "blueprintsprocessor.restclient.ssltoken.url=https://localhost:8443", - "blueprintsprocessor.restclient.ssltoken.token=72178473kjshdkjgvbsdkjv903274908", - "blueprintsprocessor.restclient.ssltoken.keyStoreInstance=PKCS12", - "blueprintsprocessor.restclient.ssltoken.sslTrust=src/test/resources/keystore.p12", - "blueprintsprocessor.restclient.ssltoken.sslTrustPassword=changeit", - "blueprintsprocessor.restclient.ssl.type=ssl-no-auth", - "blueprintsprocessor.restclient.ssl.url=https://localhost:8443", - "blueprintsprocessor.restclient.ssl.keyStoreInstance=PKCS12", - "blueprintsprocessor.restclient.ssl.sslTrust=src/test/resources/keystore.p12", - "blueprintsprocessor.restclient.ssl.sslTrustPassword=changeit", - "blueprintsprocessor.restclient.ssl.sslKey=src/test/resources/keystore.p12", - "blueprintsprocessor.restclient.ssl.sslKeyPassword=changeit" -]) +@ContextConfiguration( + classes = [BluePrintRestLibConfiguration::class, BluePrintPropertyConfiguration::class, + BluePrintPropertiesService::class] +) +@TestPropertySource( + properties = + ["blueprintsprocessor.restclient.sample.type=basic-auth", + "blueprintsprocessor.restclient.sample.url=http://localhost:8080", + "blueprintsprocessor.restclient.sample.userId=sampleuser", + "blueprintsprocessor.restclient.sslbasic.type=ssl-basic-auth", + "blueprintsprocessor.restclient.sslbasic.url=https://localhost:8443", + "blueprintsprocessor.restclient.sslbasic.username=admin", + "blueprintsprocessor.restclient.sslbasic.password=cds", + "blueprintsprocessor.restclient.sslbasic.keyStoreInstance=PKCS12", + "blueprintsprocessor.restclient.sslbasic.sslTrust=src/test/resources/keystore.p12", + "blueprintsprocessor.restclient.sslbasic.sslTrustPassword=changeit", + "blueprintsprocessor.restclient.ssltoken.type=ssl-token-auth", + "blueprintsprocessor.restclient.ssltoken.url=https://localhost:8443", + "blueprintsprocessor.restclient.ssltoken.token=72178473kjshdkjgvbsdkjv903274908", + "blueprintsprocessor.restclient.ssltoken.keyStoreInstance=PKCS12", + "blueprintsprocessor.restclient.ssltoken.sslTrust=src/test/resources/keystore.p12", + "blueprintsprocessor.restclient.ssltoken.sslTrustPassword=changeit", + "blueprintsprocessor.restclient.ssl.type=ssl-no-auth", + "blueprintsprocessor.restclient.ssl.url=https://localhost:8443", + "blueprintsprocessor.restclient.ssl.keyStoreInstance=PKCS12", + "blueprintsprocessor.restclient.ssl.sslTrust=src/test/resources/keystore.p12", + "blueprintsprocessor.restclient.ssl.sslTrustPassword=changeit", + "blueprintsprocessor.restclient.ssl.sslKey=src/test/resources/keystore.p12", + "blueprintsprocessor.restclient.ssl.sslKeyPassword=changeit" + ] +) class BluePrintRestLibPropertyServiceTest { + @Autowired lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService @Test fun testRestClientProperties() { val properties = bluePrintRestLibPropertyService.restClientProperties( - "blueprintsprocessor.restclient.sample") + "blueprintsprocessor.restclient.sample" + ) assertNotNull(properties, "failed to create property bean") - assertNotNull(properties.url, "failed to get url property in" + - " property bean") + assertNotNull( + properties.url, "failed to get url property in" + + " property bean" + ) } @Test fun testSSLBasicProperties() { val properties = bluePrintRestLibPropertyService.restClientProperties( - "blueprintsprocessor.restclient.sslbasic") + "blueprintsprocessor.restclient.sslbasic" + ) assertNotNull(properties, "failed to create property bean") val p: SSLBasicAuthRestClientProperties = properties as SSLBasicAuthRestClientProperties @@ -99,7 +108,8 @@ class BluePrintRestLibPropertyServiceTest { @Test fun testSSLTokenProperties() { val properties = bluePrintRestLibPropertyService.restClientProperties( - "blueprintsprocessor.restclient.ssltoken") + "blueprintsprocessor.restclient.ssltoken" + ) assertNotNull(properties, "failed to create property bean") val p: SSLTokenAuthRestClientProperties = @@ -114,7 +124,8 @@ class BluePrintRestLibPropertyServiceTest { @Test fun testSSLNoAuthProperties() { val properties = bluePrintRestLibPropertyService.restClientProperties( - "blueprintsprocessor.restclient.ssl") + "blueprintsprocessor.restclient.ssl" + ) assertNotNull(properties, "failed to create property bean") val p: SSLRestClientProperties = @@ -127,12 +138,12 @@ class BluePrintRestLibPropertyServiceTest { assertEquals(p.sslKeyPassword, "changeit") } - @Test fun testSSLBasicPropertiesAsJson() { val actualObj: JsonNode = defaultMapper.readTree(sslBasicAuthEndpointWithHeadersField()) val properties = bluePrintRestLibPropertyService.restClientProperties( - actualObj) + actualObj + ) assertNotNull(properties, "failed to create property bean") val p: SSLBasicAuthRestClientProperties = properties as SSLBasicAuthRestClientProperties @@ -166,7 +177,8 @@ class BluePrintRestLibPropertyServiceTest { fun testSSLNoAuthPropertiesAsJson() { val actualObj: JsonNode = defaultMapper.readTree(sslNoAuthEndpointWithHeadersField()) val properties = bluePrintRestLibPropertyService.restClientProperties( - actualObj) + actualObj + ) assertNotNull(properties, "failed to create property bean") val p: SSLRestClientProperties = @@ -185,8 +197,10 @@ class BluePrintRestLibPropertyServiceTest { fun testBlueprintWebClientService() { val blueprintWebClientService = bluePrintRestLibPropertyService .blueprintWebClientService("sample") - assertNotNull(blueprintWebClientService, - "failed to create blueprintWebClientService") + assertNotNull( + blueprintWebClientService, + "failed to create blueprintWebClientService" + ) } @Test @@ -197,7 +211,7 @@ class BluePrintRestLibPropertyServiceTest { assertNotNull(blueprintWebClientService, "failed to create blueprintWebClientService") } - //pass the result of $typeEndpointWithHeadersField() output with and without headers to compare. + // pass the result of $typeEndpointWithHeadersField() output with and without headers to compare. private fun validateHeadersDidNotChangeWithEmptyAdditionalHeaders(noHeaders: String, withHeaders: String) { val parsedObj: JsonNode = defaultMapper.readTree(noHeaders) val bpWebClientService = @@ -208,7 +222,7 @@ class BluePrintRestLibPropertyServiceTest { val bpWebClientServiceWithHeaders = bluePrintRestLibPropertyService.blueprintWebClientService(parsedObjWithHeaders) val extractedHeadersWithAdditionalHeaders = bpWebClientServiceWithHeaders.convertToBasicHeaders(mapOf()) - //Array<BasicHeader<>> -> Map<String,String> + // Array<BasicHeader<>> -> Map<String,String> val headersMap = extractedHeaders.map { it.name to it.value }.toMap() val additionalHeadersMap = extractedHeadersWithAdditionalHeaders.map { it.name to it.value }.toMap() assertEquals(headersMap, additionalHeadersMap) @@ -256,18 +270,20 @@ class BluePrintRestLibPropertyServiceTest { val bpWebClientService = bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf()) - assertEquals(MediaType.APPLICATION_XML.toString(), - extractedHeaders.filter { it.name == HttpHeaders.CONTENT_TYPE }[0].value!!) + assertEquals( + MediaType.APPLICATION_XML.toString(), + extractedHeaders.filter { it.name == HttpHeaders.CONTENT_TYPE }[0].value!! + ) } @Test fun `BasicAuth WebClientService additionalHeaders can overwrite default Content-Type`() { - //default content type is application/json + // default content type is application/json val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(contentTypeAdditionalHeader) additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) } - //called from within "assertFailsWith(exceptionClass = BluePrintProcessorException::class) {" + // called from within "assertFailsWith(exceptionClass = BluePrintProcessorException::class) {" private fun attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson: String) { val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson) val bpWebClientService = @@ -281,7 +297,7 @@ class BluePrintRestLibPropertyServiceTest { val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(additionalHeadersWithAuth) attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) } - //spec says headers are case insensitive... + // spec says headers are case insensitive... assertFailsWith(exceptionClass = BluePrintProcessorException::class) { val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) @@ -309,7 +325,7 @@ class BluePrintRestLibPropertyServiceTest { @Test fun `TokenAuth WebClientService additionalHeaders can overwrite default Content-Type`() { - //default content type is application/json + // default content type is application/json val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(contentTypeAdditionalHeader) additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) } @@ -320,14 +336,14 @@ class BluePrintRestLibPropertyServiceTest { val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(additionalHeadersWithAuth) attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) } - //spec says headers are case insensitive... + // spec says headers are case insensitive... assertFailsWith(exceptionClass = BluePrintProcessorException::class) { val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) } } - //TESTS FOR SSL BASIC AUTH headers + // TESTS FOR SSL BASIC AUTH headers @Test fun `SSLBasicAuth WebClientService with empty additionalHeaders does not modify headers`() { val endPointJson = sslBasicAuthEndpointWithHeadersField() @@ -349,7 +365,7 @@ class BluePrintRestLibPropertyServiceTest { @Test fun `SSLBasicAuth WebClientService additionalHeaders can overwrite default Content-Type`() { - //default content type is application/json + // default content type is application/json val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(contentTypeAdditionalHeader) additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) } @@ -360,14 +376,14 @@ class BluePrintRestLibPropertyServiceTest { val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(additionalHeadersWithAuth) attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) } - //spec says headers are case insensitive... + // spec says headers are case insensitive... assertFailsWith(exceptionClass = BluePrintProcessorException::class) { val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) } } - //SSL-NO-AUTH headers tests + // SSL-NO-AUTH headers tests @Test fun `SSLNoAuth WebClientService with empty additionalHeaders does not modify headers`() { val endPointJson = sslNoAuthEndpointWithHeadersField() @@ -389,7 +405,7 @@ class BluePrintRestLibPropertyServiceTest { @Test fun `SSLNoAuth WebClientService additionalHeaders can overwrite default Content-Type`() { - //default content type is application/json + // default content type is application/json val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(contentTypeAdditionalHeader) additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) } @@ -400,7 +416,7 @@ class BluePrintRestLibPropertyServiceTest { val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(additionalHeadersWithAuth) attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) } - //spec says headers are case insensitive... + // spec says headers are case insensitive... assertFailsWith(exceptionClass = BluePrintProcessorException::class) { val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) @@ -412,12 +428,15 @@ class BluePrintRestLibPropertyServiceTest { val expectedTokenAuthDefaultHeaders = mapOf<String, String>( "Content-Type" to "application/json", "Accept" to "application/json", - "Authorization" to "72178473kjshdkjgvbsdkjv903274908") + "Authorization" to "72178473kjshdkjgvbsdkjv903274908" + ) - val endPointWithHeadersJsonWithBasicAuthHeader = basicAuthEndpointWithHeadersField(""", + val endPointWithHeadersJsonWithBasicAuthHeader = basicAuthEndpointWithHeadersField( + """, "additionalHeaders" : { "authorization": "Basic aGF2ZTphbmljZWRheQo=" - }""".trimIndent()) + }""".trimIndent() + ) private fun sslTokenAuthEndpointWithHeadersField(headers: String = ""): String = """{ @@ -455,7 +474,7 @@ class BluePrintRestLibPropertyServiceTest { "sslKeyPassword" : "changeit"$headers }""".trimIndent() - //Don't forget to supply "," as the first char to make valid JSON + // Don't forget to supply "," as the first char to make valid JSON private fun basicAuthEndpointWithHeadersField(headers: String = ""): String = """{ "type": "basic-auth", @@ -496,4 +515,3 @@ class BluePrintRestLibPropertyServiceTest { }""".trimIndent() } } - diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt index 15133fa8a..f82fc6124 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt @@ -24,7 +24,7 @@ import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import kotlin.test.assertNotNull class RestClientPropertiesDSLTest { - + @Test fun testBasicAuthRestClientProperties() { val properties = BluePrintTypes.dslBasicAuthRestClientProperties { @@ -56,4 +56,4 @@ class RestClientPropertiesDSLTest { } assertNotNull(properties, "failed to get dslSSLRestClientProperties") } -}
\ No newline at end of file +} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt index 05f32904a..fa357e1fe 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt @@ -48,45 +48,56 @@ import org.springframework.security.web.server.SecurityWebFilterChain import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner -import org.springframework.web.bind.annotation.* +import org.springframework.web.bind.annotation.DeleteMapping +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PatchMapping +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.PutMapping +import org.springframework.web.bind.annotation.RequestHeader +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController import kotlin.test.assertEquals import kotlin.test.assertNotNull @RunWith(SpringRunner::class) @EnableAutoConfiguration(exclude = [DataSourceAutoConfiguration::class]) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@ContextConfiguration(classes = [BluePrintRestLibConfiguration::class, SampleController::class, - SecurityConfiguration::class, - BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]) -@TestPropertySource(properties = -[ - "server.port=8443", - "server.ssl.enabled=true", - "server.ssl.key-store=classpath:keystore.p12", - "server.ssl.key-store-password=changeit", - "server.ssl.keyStoreType=PKCS12", - "server.ssl.keyAlias=tomcat", - "blueprintsprocessor.restclient.sample.type=basic-auth", - "blueprintsprocessor.restclient.sample.url=http://127.0.0.1:8081", - "blueprintsprocessor.restclient.sample.username=admin", - "blueprintsprocessor.restclient.sample.password=jans", - "blueprintsprocessor.restclient.test.type=ssl-basic-auth", - "blueprintsprocessor.restclient.test.url=https://localhost:8443", - "blueprintsprocessor.restclient.test.username=admin", - "blueprintsprocessor.restclient.test.password=jans", - "blueprintsprocessor.restclient.test.keyStoreInstance=PKCS12", - "blueprintsprocessor.restclient.test.sslTrust=src/test/resources/keystore.p12", - "blueprintsprocessor.restclient.test.sslTrustPassword=changeit" -]) +@ContextConfiguration( + classes = [BluePrintRestLibConfiguration::class, SampleController::class, + SecurityConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class] +) +@TestPropertySource( + properties = + [ + "server.port=8443", + "server.ssl.enabled=true", + "server.ssl.key-store=classpath:keystore.p12", + "server.ssl.key-store-password=changeit", + "server.ssl.keyStoreType=PKCS12", + "server.ssl.keyAlias=tomcat", + "blueprintsprocessor.restclient.sample.type=basic-auth", + "blueprintsprocessor.restclient.sample.url=http://127.0.0.1:8081", + "blueprintsprocessor.restclient.sample.username=admin", + "blueprintsprocessor.restclient.sample.password=jans", + "blueprintsprocessor.restclient.test.type=ssl-basic-auth", + "blueprintsprocessor.restclient.test.url=https://localhost:8443", + "blueprintsprocessor.restclient.test.username=admin", + "blueprintsprocessor.restclient.test.password=jans", + "blueprintsprocessor.restclient.test.keyStoreInstance=PKCS12", + "blueprintsprocessor.restclient.test.sslTrust=src/test/resources/keystore.p12", + "blueprintsprocessor.restclient.test.sslTrustPassword=changeit" + ] +) class RestClientServiceTest { @Autowired lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService @Autowired - lateinit var httpHandler : HttpHandler + lateinit var httpHandler: HttpHandler - lateinit var http : WebServer + lateinit var http: WebServer fun localPort() = http.port @@ -106,21 +117,26 @@ class RestClientServiceTest { @Test fun testPatch() { val restClientService = bluePrintRestLibPropertyService - .blueprintWebClientService("sample") + .blueprintWebClientService("sample") val response = restClientService.exchangeResource( - HttpMethod.PATCH.name, "/sample/name", "") - assertEquals("Patch request successful", response.body, - "failed to get patch response") + HttpMethod.PATCH.name, "/sample/name", "" + ) + assertEquals( + "Patch request successful", response.body, + "failed to get patch response" + ) } @Test fun testBaseAuth() { val restClientService = bluePrintRestLibPropertyService - .blueprintWebClientService("sample") + .blueprintWebClientService("sample") val headers = mutableMapOf<String, String>() headers["X-Transaction-Id"] = "1234" - val response = restClientService.exchangeResource(HttpMethod.GET.name, - "/sample/name", "") + val response = restClientService.exchangeResource( + HttpMethod.GET.name, + "/sample/name", "" + ) assertNotNull(response.body, "failed to get response") } @@ -135,12 +151,15 @@ class RestClientServiceTest { val mapper = ObjectMapper() val actualObj: JsonNode = mapper.readTree(json) val restClientService = bluePrintRestLibPropertyService - .blueprintWebClientService(actualObj) - lateinit var res:String + .blueprintWebClientService(actualObj) + lateinit var res: String runBlocking { val get = async(start = CoroutineStart.LAZY) { - restClientService.exchangeNB(HttpMethod.GET.name, - "/sample/basic", "").body} + restClientService.exchangeNB( + HttpMethod.GET.name, + "/sample/basic", "" + ).body + } get.start() res = get.await() } @@ -151,7 +170,7 @@ class RestClientServiceTest { @Test fun testSampleAaiReq() { val restClientService = bluePrintRestLibPropertyService - .blueprintWebClientService("test") + .blueprintWebClientService("test") val headers = mutableMapOf<String, String>() headers["X-TransactionId"] = "9999" headers["X-FromAppId"] = "AAI" @@ -171,34 +190,52 @@ class RestClientServiceTest { lateinit var res6: String runBlocking { val get1 = async(start = CoroutineStart.LAZY) { - restClientService.exchangeNB(HttpMethod.GET.name, - "/sample/aai/v14/business/customers", "", headers, - Customer::class.java).body} + restClientService.exchangeNB( + HttpMethod.GET.name, + "/sample/aai/v14/business/customers", "", headers, + Customer::class.java + ).body + } val get2 = async(start = CoroutineStart.LAZY) { - restClientService.exchangeNB(HttpMethod.GET.name, - "/sample/aai/v14/business/customers", "", headers, - Customer::class.java).body} + restClientService.exchangeNB( + HttpMethod.GET.name, + "/sample/aai/v14/business/customers", "", headers, + Customer::class.java + ).body + } val post = async(start = CoroutineStart.LAZY) { - restClientService.exchangeNB(HttpMethod.POST.name, - "/sample/aai/v14/business/customers", post1, headers, - String::class.java).body} + restClientService.exchangeNB( + HttpMethod.POST.name, + "/sample/aai/v14/business/customers", post1, headers, + String::class.java + ).body + } val put = async(start = CoroutineStart.LAZY) { - restClientService.exchangeNB(HttpMethod.PUT.name, - "/sample/aai/v14/business/customers", post1, headers, - String::class.java).body} + restClientService.exchangeNB( + HttpMethod.PUT.name, + "/sample/aai/v14/business/customers", post1, headers, + String::class.java + ).body + } val patch = async(start = CoroutineStart.LAZY) { - restClientService.exchangeNB(HttpMethod.PATCH.name, - "/sample/aai/v14/business/customers", post1, headers, - String::class.java).body} + restClientService.exchangeNB( + HttpMethod.PATCH.name, + "/sample/aai/v14/business/customers", post1, headers, + String::class.java + ).body + } val delete = async(start = CoroutineStart.LAZY) { - restClientService.exchangeNB(HttpMethod.DELETE.name, - "/sample/aai/v14/business/customers", "", headers, - String::class.java).body} + restClientService.exchangeNB( + HttpMethod.DELETE.name, + "/sample/aai/v14/business/customers", "", headers, + String::class.java + ).body + } get1.start() get2.start() @@ -246,13 +283,13 @@ open class SampleController { @GetMapping("/basic") fun getBasic(): String = "Basic request arrived successfully" - @GetMapping("/aai/v14/business/customers") fun getAaiCustomers( - @RequestHeader(name = "X-TransactionId", required = true) - transId: String, - @RequestHeader(name = "X-FromAppId", required = true) - appId: String) : String { + @RequestHeader(name = "X-TransactionId", required = true) + transId: String, + @RequestHeader(name = "X-FromAppId", required = true) + appId: String + ): String { if (transId != "9999" || appId != "AAI") { return "" } @@ -266,23 +303,24 @@ open class SampleController { @PostMapping("/aai/v14/business/customers") fun postAaiCustomers( - @RequestHeader(name = "X-TransactionId", required = true) - transId: String, - @RequestHeader(name = "X-FromAppId", required = true) - appId: String) : String { + @RequestHeader(name = "X-TransactionId", required = true) + transId: String, + @RequestHeader(name = "X-FromAppId", required = true) + appId: String + ): String { if (transId != "9999" || appId != "AAI") { return "" } return "The message is successfully posted" } - @PutMapping("/aai/v14/business/customers") fun putAaiCustomers( - @RequestHeader(name = "X-TransactionId", required = true) - transId: String, - @RequestHeader(name = "X-FromAppId", required = true) - appId: String) : String { + @RequestHeader(name = "X-TransactionId", required = true) + transId: String, + @RequestHeader(name = "X-FromAppId", required = true) + appId: String + ): String { if (transId != "9999" || appId != "AAI") { return "" } @@ -291,10 +329,11 @@ open class SampleController { @PatchMapping("/aai/v14/business/customers") fun patchAaiCustomers( - @RequestHeader(name = "X-TransactionId", required = true) - transId: String, - @RequestHeader(name = "X-FromAppId", required = true) - appId: String) : String { + @RequestHeader(name = "X-TransactionId", required = true) + transId: String, + @RequestHeader(name = "X-FromAppId", required = true) + appId: String + ): String { if (transId != "9999" || appId != "AAI") { return "" } @@ -303,10 +342,11 @@ open class SampleController { @DeleteMapping("/aai/v14/business/customers") fun deleteAaiCustomers( - @RequestHeader(name = "X-TransactionId", required = true) - transId: String, - @RequestHeader(name = "X-FromAppId", required = true) - appId: String) : String { + @RequestHeader(name = "X-TransactionId", required = true) + transId: String, + @RequestHeader(name = "X-FromAppId", required = true) + appId: String + ): String { if (transId != "9999" || appId != "AAI") { return "" } @@ -323,20 +363,20 @@ open class SecurityConfiguration { @Bean open fun userDetailsService(): MapReactiveUserDetailsService { val user: UserDetails = User.withDefaultPasswordEncoder() - .username("admin") - .password("jans") - .roles("USER") - .build() + .username("admin") + .password("jans") + .roles("USER") + .build() return MapReactiveUserDetailsService(user) } @Bean open fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http - .csrf().disable() - .authorizeExchange().anyExchange().authenticated() - .and().httpBasic() - .and().build() + .csrf().disable() + .authorizeExchange().anyExchange().authenticated() + .and().httpBasic() + .and().build() } } @@ -344,7 +384,8 @@ open class SecurityConfiguration { * Data class required for response */ data class Customer( - val id: String, - val name: String, - val type: String, - val resource: String) + val id: String, + val name: String, + val type: String, + val resource: String +) |