No Business logic change, just the code format.
Competible with IntelliJ: https://github.com/pinterest/ktlint#option-3
To format run: mvn process-sources -P format
Issue-ID: CCSDK-1947
Signed-off-by: Singal, Kapil (ks220y) <ks220y@att.com>
Change-Id: Ic9e9209fb7023d77f434693ad5a01229f8d09331
--- /dev/null
+[*.{kt, kts}]
+# Comma-separated list of rules to disable (Since 0.34.0)
+# Note that rules in any ruleset other than the standard ruleset will need to be prefixed
+# by the ruleset identifier.
+disabled_rules = import-ordering
\ No newline at end of file
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
<artifactId>configs-api</artifactId>
</dependency>
- <dependency>
+ <dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
<artifactId>health-api</artifactId>
<version>0.7.0-SNAPSHOT</version>
@ConditionalOnProperty(name = ["blueprintsprocessor.grpcEnable"], havingValue = "true")
@Component
-open class BlueprintGRPCServer(private val bluePrintProcessingGRPCHandler: BluePrintProcessingGRPCHandler,
- private val bluePrintManagementGRPCHandler: BluePrintManagementGRPCHandler,
- private val authInterceptor: BasicAuthServerInterceptor)
- : ApplicationListener<ContextRefreshedEvent> {
+open class BlueprintGRPCServer(
+ private val bluePrintProcessingGRPCHandler: BluePrintProcessingGRPCHandler,
+ private val bluePrintManagementGRPCHandler: BluePrintManagementGRPCHandler,
+ private val authInterceptor: BasicAuthServerInterceptor
+) :
+ ApplicationListener<ContextRefreshedEvent> {
private val log = logger(BlueprintGRPCServer::class)
try {
log.info("Starting Blueprint Processor GRPC Starting..")
val server = ServerBuilder
- .forPort(grpcPort!!)
- .intercept(GrpcServerLoggingInterceptor())
- .intercept(authInterceptor)
- .addService(bluePrintProcessingGRPCHandler)
- .addService(bluePrintManagementGRPCHandler)
- .build()
+ .forPort(grpcPort!!)
+ .intercept(GrpcServerLoggingInterceptor())
+ .intercept(authInterceptor)
+ .addService(bluePrintProcessingGRPCHandler)
+ .addService(bluePrintManagementGRPCHandler)
+ .build()
server.start()
log.info("Blueprint Processor GRPC server started and ready to serve on port({})...", server.port)
override fun customize(serverFactory: NettyReactiveWebServerFactory) {
serverFactory.port = httpPort!!
}
-}
\ No newline at end of file
+}
* @author Brinda Santh
*/
@Configuration
-//@EnableSwagger2WebFlux
+// @EnableSwagger2WebFlux
open class SwaggerConfig {
@Bean
open fun api(): Docket {
return Docket(DocumentationType.SWAGGER_2)
- .select()
- .apis(RequestHandlerSelectors.withClassAnnotation(Api::class.java))
- .paths(PathSelectors.any())
- .build()
- .apiInfo(apiInfo())
+ .select()
+ .apis(RequestHandlerSelectors.withClassAnnotation(Api::class.java))
+ .paths(PathSelectors.any())
+ .build()
+ .apiInfo(apiInfo())
}
private fun apiInfo(): ApiInfo {
return ApiInfo(
- "CDS Blueprints Processor APIs",
- "Provide APIs to interact with CBA, their resolved resources and templates, and stored resource configurations.",
- "0.7.0",
- null,
- Contact("CCSDK Team", "www.onap.org", "onap-discuss@lists.onap.org"),
- "Apache 2.0",
- "http://www.apache.org/licenses/LICENSE-2.0",
- emptyList())
+ "CDS Blueprints Processor APIs",
+ "Provide APIs to interact with CBA, their resolved resources and templates, and stored resource configurations.",
+ "0.7.0",
+ null,
+ Contact("CCSDK Team", "www.onap.org", "onap-discuss@lists.onap.org"),
+ "Apache 2.0",
+ "http://www.apache.org/licenses/LICENSE-2.0",
+ emptyList()
+ )
}
-}
\ No newline at end of file
+}
* @author Brinda Santh
*/
@Configuration
-open class WebConfig(private val authenticationManager: AuthenticationManager,
- private val securityContextRepository: SecurityContextRepository) : WebFluxConfigurer {
+open class WebConfig(
+ private val authenticationManager: AuthenticationManager,
+ private val securityContextRepository: SecurityContextRepository
+) : WebFluxConfigurer {
override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
registry.addResourceHandler("/swagger-ui.html**")
- .addResourceLocations("classpath:/META-INF/resources/")
+ .addResourceLocations("classpath:/META-INF/resources/")
registry.addResourceHandler("/webjars/**")
- .addResourceLocations("classpath:/META-INF/resources/webjars/")
+ .addResourceLocations("classpath:/META-INF/resources/webjars/")
}
override fun addCorsMappings(corsRegistry: CorsRegistry) {
corsRegistry.addMapping("/**")
- .allowedOrigins("*")
- .allowedMethods("*")
- .allowedHeaders("*")
- .maxAge(3600)
+ .allowedOrigins("*")
+ .allowedMethods("*")
+ .allowedHeaders("*")
+ .maxAge(3600)
}
@Bean
open fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http.csrf().disable()
- .formLogin().disable()
- .httpBasic().disable()
- .authenticationManager(authenticationManager)
- .securityContextRepository(securityContextRepository!!)
- .authorizeExchange()
- .pathMatchers(HttpMethod.OPTIONS).permitAll()
- .anyExchange().authenticated()
- .and().build()
+ .formLogin().disable()
+ .httpBasic().disable()
+ .authenticationManager(authenticationManager)
+ .securityContextRepository(securityContextRepository!!)
+ .authorizeExchange()
+ .pathMatchers(HttpMethod.OPTIONS).permitAll()
+ .anyExchange().authenticated()
+ .and().build()
}
}
* @version 1.0
*/
@Component
-open class BluePrintCustomIndicator(private val bluePrintProcessorHealthCheck: BluePrintProcessorHealthCheck)
- : AbstractHealthIndicator() {
+open class BluePrintCustomIndicator(private val bluePrintProcessorHealthCheck: BluePrintProcessorHealthCheck) :
+ AbstractHealthIndicator() {
@Throws(Exception::class)
override fun doHealthCheck(builder: Health.Builder) {
}
builder.withDetail("Services", result?.checks)
}
-
-
}
import reactor.core.publisher.Mono
@Configuration
-open class AuthenticationManager(private val authenticationProvider: AuthenticationProvider)
- : ReactiveAuthenticationManager {
+open class AuthenticationManager(private val authenticationProvider: AuthenticationProvider) :
+ ReactiveAuthenticationManager {
override fun authenticate(authentication: Authentication): Mono<Authentication> {
try {
} catch (e: AuthenticationException) {
return Mono.error(e)
}
-
}
-}
\ No newline at end of file
+}
*/
package org.onap.ccsdk.cds.blueprintsprocessor.security
-import io.grpc.*
+import io.grpc.Metadata
+import io.grpc.ServerCall
+import io.grpc.ServerCallHandler
+import io.grpc.ServerInterceptor
+import io.grpc.Status
import org.onap.ccsdk.cds.controllerblueprints.core.logger
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Component
import java.nio.charset.StandardCharsets
-import java.util.*
+import java.util.Base64
@Component
-class BasicAuthServerInterceptor(private val authenticationManager: AuthenticationManager)
- : ServerInterceptor {
+class BasicAuthServerInterceptor(private val authenticationManager: AuthenticationManager) :
+ ServerInterceptor {
private val log = logger(BasicAuthServerInterceptor::class)
override fun <ReqT, RespT> interceptCall(
- call: ServerCall<ReqT, RespT>,
- headers: Metadata,
- next: ServerCallHandler<ReqT, RespT>): ServerCall.Listener<ReqT> {
+ call: ServerCall<ReqT, RespT>,
+ headers: Metadata,
+ next: ServerCallHandler<ReqT, RespT>
+ ): ServerCall.Listener<ReqT> {
val authHeader = headers.get(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER))
if (authHeader.isNullOrEmpty()) {
throw Status.UNAUTHENTICATED.withDescription("Missing required authentication")
- .asRuntimeException()
+ .asRuntimeException()
}
try {
log.info("Authentication success: {}", authResult)
SecurityContextHolder.getContext().authentication = authResult
-
} catch (e: AuthenticationException) {
SecurityContextHolder.clearContext()
private fun decodeBasicAuth(authHeader: String): Array<String> {
val basicAuth: String
try {
- basicAuth = String(Base64.getDecoder().decode(authHeader.substring(6).toByteArray(StandardCharsets.UTF_8)),
- StandardCharsets.UTF_8)
+ basicAuth = String(
+ Base64.getDecoder().decode(authHeader.substring(6).toByteArray(StandardCharsets.UTF_8)),
+ StandardCharsets.UTF_8
+ )
} catch (e: IllegalArgumentException) {
throw BadCredentialsException("Failed to decode basic authentication token")
} catch (e: IndexOutOfBoundsException) {
return arrayOf(basicAuth.substring(0, delim), basicAuth.substring(delim + 1))
}
-}
\ No newline at end of file
+}
@Bean
open fun inMemoryUserService(): UserDetailsService {
- val user = User(username, password,
- listOf(SimpleGrantedAuthority("USER")))
+ val user = User(
+ username, password,
+ listOf(SimpleGrantedAuthority("USER"))
+ )
return InMemoryUserDetailsManager(user)
}
provider.setUserDetailsService(inMemoryUserService())
return provider
}
-}
\ No newline at end of file
+}
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
import java.nio.charset.StandardCharsets
-import java.util.*
+import java.util.Base64
@Component
-class SecurityContextRepository(private val authenticationManager: AuthenticationManager)
- : ServerSecurityContextRepository {
+class SecurityContextRepository(private val authenticationManager: AuthenticationManager) :
+ ServerSecurityContextRepository {
override fun save(swe: ServerWebExchange, sc: SecurityContext): Mono<Void> {
throw UnsupportedOperationException("Not supported.")
val password = tokens[1]
val auth = UsernamePasswordAuthenticationToken(username, password)
return this.authenticationManager!!.authenticate(auth)
- .map { SecurityContextImpl(it) }
+ .map { SecurityContextImpl(it) }
} else {
return Mono.empty()
}
private fun decodeBasicAuth(authHeader: String): Array<String> {
val basicAuth: String
try {
- basicAuth = String(Base64.getDecoder().decode(authHeader.substring(6).toByteArray(StandardCharsets.UTF_8)),
- StandardCharsets.UTF_8)
+ basicAuth = String(
+ Base64.getDecoder().decode(authHeader.substring(6).toByteArray(StandardCharsets.UTF_8)),
+ StandardCharsets.UTF_8
+ )
} catch (e: IllegalArgumentException) {
throw BadCredentialsException("Failed to decode basic authentication token")
} catch (e: IndexOutOfBoundsException) {
return arrayOf(basicAuth.substring(0, delim), basicAuth.substring(delim + 1))
}
-}
\ No newline at end of file
+}
private fun expandJstlSpec(jstlSpec: JsonNode): String {
val extendedJstlSpec = updateObjectNodes(jstlSpec, "*", ".")
return extendedJstlSpec.toString()
- // Handle the "?" as a prefix to literal/non-quoted values
- .replace("\"\\?([^\"]+)\"".toRegex(), "$1")
- // Also, remove the quotes added by Jackson for key and value of the wildcard matcher
- .replace("\"([.*])\"".toRegex(), "$1")
+ // Handle the "?" as a prefix to literal/non-quoted values
+ .replace("\"\\?([^\"]+)\"".toRegex(), "$1")
+ // Also, remove the quotes added by Jackson for key and value of the wildcard matcher
+ .replace("\"([.*])\"".toRegex(), "$1")
}
/**
}
return flatJoinTo(StringBuilder(), path).toString()
}
-}
\ No newline at end of file
+}
import org.yaml.snakeyaml.nodes.Tag
@JsonInclude(JsonInclude.Include.NON_EMPTY)
-data class ProcessDefinition(val name: String, val request: JsonNode, val expectedResponse: JsonNode? = null,
- val responseNormalizerSpec: JsonNode? = null)
+data class ProcessDefinition(
+ val name: String,
+ val request: JsonNode,
+ val expectedResponse: JsonNode? = null,
+ val responseNormalizerSpec: JsonNode? = null
+)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
-data class RequestDefinition(val method: String,
- @JsonDeserialize(using = PathDeserializer::class)
- val path: String,
- val headers: Map<String, String> = emptyMap(),
- val body: JsonNode? = null)
+data class RequestDefinition(
+ val method: String,
+ @JsonDeserialize(using = PathDeserializer::class)
+ val path: String,
+ val headers: Map<String, String> = emptyMap(),
+ val body: JsonNode? = null
+)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
data class ResponseDefinition(val status: Int = 200, val body: JsonNode? = null) {
+
companion object {
val DEFAULT_RESPONSE = ResponseDefinition()
}
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
-data class ExpectationDefinition(val request: RequestDefinition,
- val response: ResponseDefinition = ResponseDefinition.DEFAULT_RESPONSE)
+data class ExpectationDefinition(
+ val request: RequestDefinition,
+ val response: ResponseDefinition = ResponseDefinition.DEFAULT_RESPONSE
+)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
data class ServiceDefinition(val selector: String, val expectations: List<ExpectationDefinition>)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
-data class UatDefinition(val processes: List<ProcessDefinition>,
- @JsonAlias("external-services")
- val externalServices: List<ServiceDefinition> = emptyList()) {
+data class UatDefinition(
+ val processes: List<ProcessDefinition>,
+ @JsonAlias("external-services")
+ val externalServices: List<ServiceDefinition> = emptyList()
+) {
fun dump(mapper: ObjectMapper, excludedProperties: List<String> = emptyList()): String {
val uatAsMap: Map<String, Any> = mapper.convertValue(this)
companion object {
fun load(mapper: ObjectMapper, spec: String): UatDefinition =
- mapper.convertValue(Yaml().load(spec), UatDefinition::class.java)
-
+ mapper.convertValue(Yaml().load(spec), UatDefinition::class.java)
}
}
*/
@Component
class UatExecutor(
- private val environment: ConfigurableEnvironment,
- private val restClientFactory: BluePrintRestLibPropertyService,
- private val mapper: ObjectMapper
+ private val environment: ConfigurableEnvironment,
+ private val restClientFactory: BluePrintRestLibPropertyService,
+ private val mapper: ObjectMapper
) {
companion object {
fun execute(uat: UatDefinition, cbaBytes: ByteArray): UatDefinition {
val defaultHeaders = listOf(BasicHeader(HttpHeaders.AUTHORIZATION, clientAuthToken()))
val httpClient = HttpClientBuilder.create()
- .setDefaultHeaders(defaultHeaders)
- .build()
+ .setDefaultHeaders(defaultHeaders)
+ .build()
// Only if externalServices are defined
val mockInterceptor = MockPreInterceptor()
// Always defined and used, whatever the case
try {
// Configure mocked external services and save their expected requests for further validation
val requestsPerClient = uat.externalServices.associateBy(
- { service ->
- createRestClientMock(service.expectations).also { restClient ->
- // side-effect: register restClient to override real instance
- mockInterceptor.registerMock(service.selector, restClient)
- }
- },
- { service -> service.expectations.map { it.request } }
+ { service ->
+ createRestClientMock(service.expectations).also { restClient ->
+ // side-effect: register restClient to override real instance
+ mockInterceptor.registerMock(service.selector, restClient)
+ }
+ },
+ { service -> service.expectations.map { it.request } }
)
val newProcesses = httpClient.use { client ->
uat.processes.map { process ->
log.info("Executing process '${process.name}'")
val responseNormalizer = JsonNormalizer.getNormalizer(mapper, process.responseNormalizerSpec)
- val actualResponse = processBlueprint(client, process.request,
- process.expectedResponse, responseNormalizer)
+ val actualResponse = processBlueprint(
+ client, process.request,
+ process.expectedResponse, responseNormalizer
+ )
ProcessDefinition(process.name, process.request, actualResponse, process.responseNormalizerSpec)
}
}
for ((mockClient, requests) in requestsPerClient) {
requests.forEach { request ->
verify(mockClient, atLeastOnce()).exchangeResource(
- eq(request.method),
- eq(request.path),
- argThat { assertJsonEquals(request.body, this) },
- argThat(RequiredMapEntriesMatcher(request.headers)))
+ eq(request.method),
+ eq(request.path),
+ argThat { assertJsonEquals(request.body, this) },
+ argThat(RequiredMapEntriesMatcher(request.headers))
+ )
}
// Don't mind the invocations to the overloaded exchangeResource(String, String, String)
verify(mockClient, atLeast(0)).exchangeResource(any(), any(), any())
}
val newExternalServices = spyInterceptor.getSpies()
- .map(SpyService::asServiceDefinition)
+ .map(SpyService::asServiceDefinition)
return UatDefinition(newProcesses, newExternalServices)
} finally {
}
}
- private fun createRestClientMock(restExpectations: List<ExpectationDefinition>)
- : BlueprintWebClientService {
+ private fun createRestClientMock(restExpectations: List<ExpectationDefinition>):
+ BlueprintWebClientService {
val restClient = mock<BlueprintWebClientService>(
- defaultAnswer = Answers.RETURNS_SMART_NULLS,
- // our custom verboseLogging handler
- invocationListeners = arrayOf(mockLoggingListener)
+ defaultAnswer = Answers.RETURNS_SMART_NULLS,
+ // our custom verboseLogging handler
+ invocationListeners = arrayOf(mockLoggingListener)
)
// Delegates to overloaded exchangeResource(String, String, String, Map<String, String>)
whenever(restClient.exchangeResource(any(), any(), any()))
- .thenAnswer { invocation ->
- val method = invocation.arguments[0] as String
- val path = invocation.arguments[1] as String
- val request = invocation.arguments[2] as String
- restClient.exchangeResource(method, path, request, emptyMap())
- }
+ .thenAnswer { invocation ->
+ val method = invocation.arguments[0] as String
+ val path = invocation.arguments[1] as String
+ val request = invocation.arguments[2] as String
+ restClient.exchangeResource(method, path, request, emptyMap())
+ }
for (expectation in restExpectations) {
- whenever(restClient.exchangeResource(
+ whenever(
+ restClient.exchangeResource(
eq(expectation.request.method),
eq(expectation.request.path),
any(),
- any()))
- .thenReturn(WebClientResponse(expectation.response.status, expectation.response.body.toString()))
+ any()
+ )
+ )
+ .thenReturn(WebClientResponse(expectation.response.status, expectation.response.body.toString()))
}
return restClient
}
@Throws(AssertionError::class)
private fun uploadBlueprint(client: HttpClient, cbaBytes: ByteArray) {
val multipartEntity = MultipartEntityBuilder.create()
- .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
- .addBinaryBody("file", cbaBytes, ContentType.DEFAULT_BINARY, "cba.zip")
- .build()
+ .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
+ .addBinaryBody("file", cbaBytes, ContentType.DEFAULT_BINARY, "cba.zip")
+ .build()
val request = HttpPost("$baseUrl/api/v1/blueprint-model/publish").apply {
entity = multipartEntity
}
}
@Throws(AssertionError::class)
- private fun processBlueprint(client: HttpClient, requestBody: JsonNode,
- expectedResponse: JsonNode?, responseNormalizer: (String) -> String): JsonNode {
+ private fun processBlueprint(
+ client: HttpClient,
+ requestBody: JsonNode,
+ expectedResponse: JsonNode?,
+ responseNormalizer: (String) -> String
+ ): JsonNode {
val stringEntity = StringEntity(mapper.writeValueAsString(requestBody), ContentType.APPLICATION_JSON)
val request = HttpPost("$baseUrl/api/v1/execution-service/process").apply {
entity = stringEntity
}
private fun localServerPort(): Int =
- (environment.getProperty("local.server.port")
- ?: environment.getRequiredProperty("blueprint.httpPort")).toInt()
+ (environment.getProperty("local.server.port")
+ ?: environment.getRequiredProperty("blueprint.httpPort")).toInt()
private fun clientAuthToken(): String {
val username = environment.getRequiredProperty("security.user.name")
}
override fun getInstance(selector: String): BlueprintWebClientService? =
- mocks[selector]
+ mocks[selector]
fun registerMock(selector: String, client: BlueprintWebClientService) {
mocks[selector] = client
}
fun getSpies(): List<SpyService> =
- spies.values.toList()
+ spies.values.toList()
}
- private class SpyService(private val mapper: ObjectMapper,
- val selector: String,
- private val realService: BlueprintWebClientService) :
- BlueprintWebClientService by realService {
+ private class SpyService(
+ private val mapper: ObjectMapper,
+ val selector: String,
+ private val realService: BlueprintWebClientService
+ ) :
+ BlueprintWebClientService by realService {
private val expectations: MutableList<ExpectationDefinition> = mutableListOf()
override fun exchangeResource(methodType: String, path: String, request: String): WebClientResponse<String> =
- exchangeResource(methodType, path, request, DEFAULT_HEADERS)
-
- override fun exchangeResource(methodType: String, path: String, request: String,
- headers: Map<String, String>): WebClientResponse<String> {
+ exchangeResource(methodType, path, request, DEFAULT_HEADERS)
+
+ override fun exchangeResource(
+ methodType: String,
+ path: String,
+ request: String,
+ headers: Map<String, String>
+ ): WebClientResponse<String> {
val requestDefinition = RequestDefinition(methodType, path, headers, toJson(request))
val realAnswer = realService.exchangeResource(methodType, path, request, headers)
val responseBody = when {
}
fun asServiceDefinition() =
- ServiceDefinition(selector, expectations)
+ ServiceDefinition(selector, expectations)
private fun toJson(str: String): JsonNode? {
return when {
companion object {
private val DEFAULT_HEADERS = mapOf(
- HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE,
- HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE
+ HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE,
+ HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE
)
}
}
-}
\ No newline at end of file
+}
@PostMapping("/spy", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE], produces = ["text/vnd.yaml"])
@PreAuthorize("hasRole('USER')")
@Suppress("BlockingMethodInNonBlockingContext")
- open fun spy(@RequestPart("cba") cbaFile: FilePart,
- @RequestPart("uat", required = false) uatFile: FilePart?): String = runBlocking {
+ open fun spy(
+ @RequestPart("cba") cbaFile: FilePart,
+ @RequestPart("uat", required = false) uatFile: FilePart?
+ ): String = runBlocking {
val tempFile = createTempFile()
setContextColor(COLOR_SERVICES)
try {
// Fields that can be safely ignored from BPP response, and can be omitted on the UAT specification.
private val FIELDS_TO_EXCLUDE = listOf("timestamp")
}
-}
\ No newline at end of file
+}
import org.slf4j.Marker
-class ColorMarker internal constructor(private val dlg: Marker) : Marker by dlg
\ No newline at end of file
+class ColorMarker internal constructor(private val dlg: Marker) : Marker by dlg
}
fun markerOf(color: String): ColorMarker =
- ColorMarker(MarkerFactory.getMarker(color))
+ ColorMarker(MarkerFactory.getMarker(color))
}
}
override fun getDiscriminatingValue(e: ILoggingEvent): String =
- (e.marker as? ColorMarker)?.name
- ?: e.mdcPropertyMap?.get(MDC_COLOR_KEY)
- ?: defaultValue
-}
\ No newline at end of file
+ (e.marker as? ColorMarker)?.name
+ ?: e.mdcPropertyMap?.get(MDC_COLOR_KEY)
+ ?: defaultValue
+}
@RunWith(SpringRunner::class)
// Also set blueprintsprocessor.httpPort=0
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-@ContextConfiguration(initializers = [
- WorkingFoldersInitializer::class,
- TestSecuritySettings.ServerContextInitializer::class
-])
+@ContextConfiguration(
+ initializers = [
+ WorkingFoldersInitializer::class,
+ TestSecuritySettings.ServerContextInitializer::class
+ ]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
abstract class BaseUatTest {
companion object {
const val UAT_BLUEPRINTS_BASE_DIR = "../../../components/model-catalog/blueprint-model/uat-blueprints"
}
-}
\ No newline at end of file
+}
// Only one runner can be configured with jUnit 4. We had to replace the SpringRunner by equivalent jUnit rules.
// See more on https://docs.spring.io/autorepo/docs/spring-framework/current/spring-framework-reference/testing.html#testcontext-junit4-rules
@RunWith(Parameterized::class)
-class BlueprintsAcceptanceTest(@Suppress("unused") private val blueprintName: String, // readable test description
- private val rootFs: FileSystem) : BaseUatTest() {
+class BlueprintsAcceptanceTest(
+ @Suppress("unused") private val blueprintName: String, // readable test description
+ private val rootFs: FileSystem
+) : BaseUatTest() {
companion object {
@JvmStatic
fun scanUatEmpoweredBlueprints(): List<Array<Any>> {
return (File(UAT_BLUEPRINTS_BASE_DIR)
- .listFiles { file -> file.isDirectory && File(file, UAT_SPECIFICATION_FILE).isFile }
- ?: throw RuntimeException("Failed to scan $UAT_BLUEPRINTS_BASE_DIR"))
- .map { file ->
- arrayOf(
- file.nameWithoutExtension,
- FileSystems.newFileSystem(file.canonicalFile.toPath(), null)
- )
- }
+ .listFiles { file -> file.isDirectory && File(file, UAT_SPECIFICATION_FILE).isFile }
+ ?: throw RuntimeException("Failed to scan $UAT_BLUEPRINTS_BASE_DIR"))
+ .map { file ->
+ arrayOf(
+ file.nameWithoutExtension,
+ FileSystems.newFileSystem(file.canonicalFile.toPath(), null)
+ )
+ }
}
}
uatExecutor.execute(uatSpec, cbaBytes)
}
}
-}
\ No newline at end of file
+}
import java.io.File
import java.io.IOException
-import java.nio.file.*
-import java.nio.file.attribute.*
+import java.nio.file.FileVisitResult
+import java.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.SimpleFileVisitor
+import java.nio.file.attribute.BasicFileAttributes
import javax.annotation.PreDestroy
class ExtendedTemporaryFolder {
private const val authPassword = "Heisenberg"
fun clientAuthToken() =
- "Basic " + Base64Utils.encodeToString("$authUsername:$authPassword".toByteArray())
+ "Basic " + Base64Utils.encodeToString("$authUsername:$authPassword".toByteArray())
}
class ServerContextInitializer : ApplicationContextInitializer<ConfigurableApplicationContext> {
override fun initialize(context: ConfigurableApplicationContext) {
- TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context,
- "security.user.name=$authUsername",
- "security.user.password={noop}$authPassword"
+ TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
+ context,
+ "security.user.name=$authUsername",
+ "security.user.password={noop}$authPassword"
)
}
}
}
private fun inlinedPropertySource(): MutableMap<String, Any> =
- (environment.propertySources[INLINED_PROPERTIES_PROPERTY_SOURCE_NAME] as MapPropertySource).source
+ (environment.propertySources[INLINED_PROPERTIES_PROPERTY_SOURCE_NAME] as MapPropertySource).source
@LocalServerPort
var localServerPort: Int = 0
@BeforeTest
fun setupHttpClient() {
- val defaultHeaders = listOf(BasicHeader(org.apache.http.HttpHeaders.AUTHORIZATION,
- TestSecuritySettings.clientAuthToken()))
+ val defaultHeaders = listOf(
+ BasicHeader(
+ org.apache.http.HttpHeaders.AUTHORIZATION,
+ TestSecuritySettings.clientAuthToken()
+ )
+ )
httpClient = HttpClientBuilder.create()
- .setDefaultHeaders(defaultHeaders)
- .build()
+ .setDefaultHeaders(defaultHeaders)
+ .build()
}
@Test
// GIVEN
val cbaBytes = compressToBytes(BLUEPRINT_BASE_DIR)
val multipartEntity = MultipartEntityBuilder.create()
- .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
- .addBinaryBody("cba", cbaBytes, ContentType.DEFAULT_BINARY, "cba.zip")
- .build()
+ .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
+ .addBinaryBody("cba", cbaBytes, ContentType.DEFAULT_BINARY, "cba.zip")
+ .build()
val request = HttpPost("$baseUrl/api/v1/uat/verify").apply {
entity = multipartEntity
}
val cbaBytes = compressToBytes(BLUEPRINT_BASE_DIR)
val multipartEntity = MultipartEntityBuilder.create()
- .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
- .addBinaryBody("cba", cbaBytes, ContentType.DEFAULT_BINARY, "cba.zip")
- .addBinaryBody("uat", bareUatBytes, ContentType.DEFAULT_BINARY, "uat.yaml")
- .build()
+ .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
+ .addBinaryBody("cba", cbaBytes, ContentType.DEFAULT_BINARY, "cba.zip")
+ .addBinaryBody("uat", bareUatBytes, ContentType.DEFAULT_BINARY, "uat.yaml")
+ .build()
val request = HttpPost("$baseUrl/api/v1/uat/spy").apply {
entity = multipartEntity
}
}
private fun createMockServer(service: ServiceDefinition): WireMockServer {
- val mockServer = WireMockServer(wireMockConfig()
+ val mockServer = WireMockServer(
+ wireMockConfig()
.dynamicPort()
.notifier(MarkedSlf4jNotifier(wireMockMarker))
)
}
val responseDefinitionBuilder: ResponseDefinitionBuilder = aResponse()
- .withStatus(response.status)
+ .withStatus(response.status)
if (response.body != null) {
responseDefinitionBuilder.withBody(mapper.writeValueAsBytes(response.body))
- .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
}
mappingBuilder.willReturn(responseDefinitionBuilder)
val selector = service.selector
val httpPort = mockServer.port()
val properties = mapOf(
- "blueprintsprocessor.restclient.$selector.type" to "basic-auth",
- "blueprintsprocessor.restclient.$selector.url" to "http://localhost:$httpPort/",
- // TODO credentials should be validated
- "blueprintsprocessor.restclient.$selector.username" to "admin",
- "blueprintsprocessor.restclient.$selector.password" to "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U"
+ "blueprintsprocessor.restclient.$selector.type" to "basic-auth",
+ "blueprintsprocessor.restclient.$selector.url" to "http://localhost:$httpPort/",
+ // TODO credentials should be validated
+ "blueprintsprocessor.restclient.$selector.username" to "admin",
+ "blueprintsprocessor.restclient.$selector.password" to "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U"
)
setProperties(properties)
}
val map: Map<String, Any> = Yaml().load(yaml)
return mapper.writeValueAsString(map)
}
-}
\ No newline at end of file
+}
override fun initialize(context: ConfigurableApplicationContext) {
val tempFolder = ExtendedTemporaryFolder()
val properties = listOf("Deploy", "Archive", "Working")
- .map { "blueprintsprocessor.blueprint${it}Path=${tempFolder.newFolder(it)}" }
- .toTypedArray()
+ .map { "blueprintsprocessor.blueprint${it}Path=${tempFolder.newFolder(it)}" }
+ .toTypedArray()
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, *properties)
// Expose tempFolder as a bean so it can be accessed via DI
registerSingleton(context, "tempFolder", ExtendedTemporaryFolder::class.java, tempFolder)
}
@Suppress("SameParameterValue")
- private fun <T> registerSingleton(context: ConfigurableApplicationContext,
- beanName: String, beanClass: Class<T>, instance: T) {
+ private fun <T> registerSingleton(
+ context: ConfigurableApplicationContext,
+ beanName: String,
+ beanClass: Class<T>,
+ instance: T
+ ) {
val builder = BeanDefinitionBuilder.genericBeanDefinition(beanClass) { instance }
(context.beanFactory as BeanDefinitionRegistry).registerBeanDefinition(beanName, builder.beanDefinition)
}
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
+import org.onap.ccsdk.cds.controllerblueprints.core.isNullOrMissing
+import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
+import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.stereotype.Component
import java.net.URI
import java.net.URLEncoder
-import java.util.*
+import java.util.NoSuchElementException
/**
* ComponentRemoteAnsibleExecutor
*/
@Component("component-remote-ansible-executor")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ComponentRemoteAnsibleExecutor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService,
- private val mapper: ObjectMapper)
- : AbstractComponentFunction() {
+open class ComponentRemoteAnsibleExecutor(
+ private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService,
+ private val mapper: ObjectMapper
+) :
+ AbstractComponentFunction() {
// HTTP related constants
private val HTTP_SUCCESS = 200..202
if (jtId.isNotEmpty()) {
runJobTemplateOnAWX(restClientService, jobTemplateName, jtId, workflowURIPrefix)
} else {
- val message = "Workflow/Job template ${jobTemplateName} does not exists"
+ val message = "Workflow/Job template $jobTemplateName does not exists"
log.error(message)
setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, message)
}
}
}
-
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
val message = "Error in ComponentRemoteAnsibleExecutor : ${runtimeException.message}"
log.error(message, runtimeException)
/**
* Finds the job template ID based on the job template name provided in the request
*/
- private fun lookupJobTemplateIDByName(awxClient: BlueprintWebClientService, job_template_name: String?,
- workflowPrefix : String) : String {
- val encodedJTName = URI(null, null,
- "/api/v2/${workflowPrefix}job_templates/${job_template_name}/",
- null, null).rawPath
+ private fun lookupJobTemplateIDByName(
+ awxClient: BlueprintWebClientService,
+ job_template_name: String?,
+ workflowPrefix: String
+ ): String {
+ val encodedJTName = URI(
+ null, null,
+ "/api/v2/${workflowPrefix}job_templates/$job_template_name/",
+ null, null
+ ).rawPath
// Get Job Template details by name
var response = awxClient.exchangeResource(GET, encodedJTName, "")
* its execution. Finally, it retrieves the job results via the stdout api.
* The status and output attributes are populated in the process.
*/
- private fun runJobTemplateOnAWX(awxClient: BlueprintWebClientService, job_template_name: String?, jtId: String,
- workflowPrefix : String) {
- setNodeOutputProperties("preparing".asJsonPrimitive(), "".asJsonPrimitive(), "".asJsonPrimitive())
+ private fun runJobTemplateOnAWX(
+ awxClient: BlueprintWebClientService,
+ job_template_name: String?,
+ jtId: String,
+ workflowPrefix: String
+ ) {
+ setNodeOutputProperties("preparing".asJsonPrimitive(), "".asJsonPrimitive(), "".asJsonPrimitive())
// Get Job Template requirements
- var response = awxClient.exchangeResource(GET, "/api/v2/${workflowPrefix}job_templates/${jtId}/launch/", "")
+ var response = awxClient.exchangeResource(GET, "/api/v2/${workflowPrefix}job_templates/$jtId/launch/", "")
// FIXME: handle non-successful SC
val jtLaunchReqs: JsonNode = mapper.readTree(response.body)
val payload = prepareLaunchPayload(awxClient, jtLaunchReqs, workflowPrefix.isNotBlank())
// Launch the job for the targeted template
var jtLaunched: JsonNode = JacksonUtils.objectMapper.createObjectNode()
- response = awxClient.exchangeResource(POST, "/api/v2/${workflowPrefix}job_templates/${jtId}/launch/", payload)
+ response = awxClient.exchangeResource(POST, "/api/v2/${workflowPrefix}job_templates/$jtId/launch/", payload)
if (response.status in HTTP_SUCCESS) {
jtLaunched = mapper.readTree(response.body)
val fieldsIgnored: JsonNode = jtLaunched.at("/ignored_fields")
var jobStatus = "unknown"
var jobEndTime = "null"
while (jobEndTime == "null") {
- response = awxClient.exchangeResource(GET, "/api/v2/${workflowPrefix}jobs/${jobId}/", "")
+ response = awxClient.exchangeResource(GET, "/api/v2/${workflowPrefix}jobs/$jobId/", "")
val jobLaunched: JsonNode = mapper.readTree(response.body)
jobStatus = jobLaunched.at("/status").asText()
jobEndTime = jobLaunched.at("/finished").asText()
log.info("Execution of job template $job_template_name in job #$jobId finished with status ($jobStatus) for requestId $processId")
populateJobRunResponse(awxClient, jobId, workflowPrefix, jobStatus)
-
} else {
// The job template requirements were not fulfilled with the values passed in. The message below will
// provide more information via the response, like the ignored_fields, or variables_needed_to_start,
* Extracts the output from either a job stdout call OR collects the workflow run output, as well as the artifacts
* and populate the component corresponding output properties
*/
- private fun populateJobRunResponse(awxClient: BlueprintWebClientService, jobId: String, workflowPrefix: String,
- jobStatus: String) {
+ private fun populateJobRunResponse(
+ awxClient: BlueprintWebClientService,
+ jobId: String,
+ workflowPrefix: String,
+ jobStatus: String
+ ) {
val collectedResponses = StringBuilder(4096)
val artifacts: MutableMap<String, JsonNode> = mutableMapOf()
collectJobIdsRelatedToJobRun(awxClient, jobId, workflowPrefix).forEach { aJobId ->
// Collect the response text from the corresponding jobIds
- var response = awxClient.exchangeResource(GET, "/api/v2/jobs/${aJobId}/stdout/?format=txt", "", plainTextHeaders)
+ var response = awxClient.exchangeResource(GET, "/api/v2/jobs/$aJobId/stdout/?format=txt", "", plainTextHeaders)
if (response.status in HTTP_SUCCESS) {
val jobOutput = response.body
collectedResponses
- .append("Output for Job $aJobId :" + System.lineSeparator())
- .append(jobOutput)
- .append(System.lineSeparator())
- log.info("Response for job ${aJobId}: \n ${jobOutput} \n")
+ .append("Output for Job $aJobId :" + System.lineSeparator())
+ .append(jobOutput)
+ .append(System.lineSeparator())
+ log.info("Response for job $aJobId: \n $jobOutput \n")
} else {
- log.warn("Could not gather response for job ${aJobId}. Status=${response.status}")
+ log.warn("Could not gather response for job $aJobId. Status=${response.status}")
}
// Collect artifacts variables from each job and gather them up in one json node
- response = awxClient.exchangeResource(GET, "/api/v2/jobs/${aJobId}/", "")
+ response = awxClient.exchangeResource(GET, "/api/v2/jobs/$aJobId/", "")
if (response.status in HTTP_SUCCESS) {
val jobArtifacts = mapper.readTree(response.body).at("/artifacts")
if (jobArtifacts != null) {
}
}
- log.info("Artifacts for job ${jobId}: \n $artifacts \n")
+ log.info("Artifacts for job $jobId: \n $artifacts \n")
setNodeOutputProperties(jobStatus.asJsonPrimitive(), collectedResponses.toString().asJsonPrimitive(), artifacts.asJsonNode())
}
var jobIds: Array<String>
if (workflowPrefix.isNotEmpty()) {
- var response = awxClient.exchangeResource(GET, "/api/v2/${workflowPrefix}jobs/${jobId}/workflow_nodes/", "")
+ var response = awxClient.exchangeResource(GET, "/api/v2/${workflowPrefix}jobs/$jobId/workflow_nodes/", "")
val jobDetails = mapper.readTree(response.body).at("/results")
// gather up job Id of all actual job nodes that ran during the workflow
* by applying the overrides that were provided
* and allowed by the template definition flags in jtLaunchReqs
*/
- private fun prepareLaunchPayload(awxClient: BlueprintWebClientService, jtLaunchReqs: JsonNode,
- isWorkflow : Boolean): String {
+ private fun prepareLaunchPayload(
+ awxClient: BlueprintWebClientService,
+ jtLaunchReqs: JsonNode,
+ isWorkflow: Boolean
+ ): String {
val payload = JacksonUtils.objectMapper.createObjectNode()
// Parameter defaults
payload.set(INPUT_INVENTORY, inventoryKeyId)
}
- payload.set("extra_vars", extraArgs)
+ payload.set("extra_vars", extraArgs)
return payload.asJsonString(false)
}
/**
* Utility function to set the output properties and errors of the executor node, in cas of errors
*/
- private fun setNodeOutputErrors(status: String, message: String, artifacts: JsonNode = "".asJsonPrimitive() ) {
+ private fun setNodeOutputErrors(status: String, message: String, artifacts: JsonNode = "".asJsonPrimitive()) {
setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message.asJsonPrimitive())
setAttribute(ATTRIBUTE_EXEC_CMD_ARTIFACTS, artifacts)
webClientService.exchangeResource("GET", "/api/v2/inventories/?name=Demo+Inventory", "")
} returns WebClientResponse(200, getInventory())
every {
- webClientService.exchangeResource("POST", "/api/v2/job_templates/$jtId/launch/",
- """{"inventory":1,"extra_vars":{"site_id":"3 - Belmont","tor_group":"vEPC"}}""")
+ webClientService.exchangeResource(
+ "POST", "/api/v2/job_templates/$jtId/launch/",
+ """{"inventory":1,"extra_vars":{"site_id":"3 - Belmont","tor_group":"vEPC"}}"""
+ )
} returns WebClientResponse(201, newJobTemplateLaunch(jtId, jobId))
every {
webClientService.exchangeResource("GET", "/api/v2/jobs/$jobId/", "")
} returnsMany listOf(
- WebClientResponse(200, getJobStatus1(jtId, jobId)),
- WebClientResponse(200, getJobStatus2(jtId, jobId)),
- WebClientResponse(200, getJobStatus3(jtId, jobId)),
- WebClientResponse(200, getJobStatus4(jtId, jobId))
+ WebClientResponse(200, getJobStatus1(jtId, jobId)),
+ WebClientResponse(200, getJobStatus2(jtId, jobId)),
+ WebClientResponse(200, getJobStatus3(jtId, jobId)),
+ WebClientResponse(200, getJobStatus4(jtId, jobId))
)
every {
- webClientService.exchangeResource("GET", "/api/v2/jobs/$jobId/stdout/?format=txt", "",
- mapOf("Accept" to "text/plain"))
+ webClientService.exchangeResource(
+ "GET", "/api/v2/jobs/$jobId/stdout/?format=txt", "",
+ mapOf("Accept" to "text/plain")
+ )
} returns WebClientResponse(200, getReport())
val selector = mapper.readTree(endpointSelector)
val bluePrintRestLibPropertyService = mockk<BluePrintRestLibPropertyService>()
awxRemoteExecutor.checkDelay = 1
val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
- "payload/requests/sample-remote-ansible-request.json",
- ExecutionServiceInput::class.java)!!
+ "payload/requests/sample-remote-ansible-request.json",
+ ExecutionServiceInput::class.java
+ )!!
val bluePrintRuntimeService = createBlueprintRuntimeService(awxRemoteExecutor, executionServiceInput)
awxRemoteExecutor.checkDelay = 1
val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
- "payload/requests/remote-ansible-request-full.json",
- ExecutionServiceInput::class.java)!!
+ "payload/requests/remote-ansible-request-full.json",
+ ExecutionServiceInput::class.java
+ )!!
val bluePrintRuntimeService = createBlueprintRuntimeService(awxRemoteExecutor, executionServiceInput)
webClientService.exchangeResource("GET", "/api/v2/inventories/?name=Demo+Inventory", "")
} returns WebClientResponse(200, getInventory())
every {
- webClientService.exchangeResource("POST", "/api/v2/job_templates/$jtId/launch/",
- """{"limit":"123","tags":"some-tag","skip_tags":"some-skip-tag","inventory":1,"extra_vars":{"site_id":"3 - Belmont","tor_group":"vEPC"}}""")
+ webClientService.exchangeResource(
+ "POST", "/api/v2/job_templates/$jtId/launch/",
+ """{"limit":"123","tags":"some-tag","skip_tags":"some-skip-tag","inventory":1,"extra_vars":{"site_id":"3 - Belmont","tor_group":"vEPC"}}"""
+ )
} returns WebClientResponse(500, "")
val selector = mapper.readTree(endpointSelector)
val bluePrintRestLibPropertyService = mockk<BluePrintRestLibPropertyService>()
awxRemoteExecutor.checkDelay = 1
val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
- "payload/requests/remote-ansible-request-full.json",
- ExecutionServiceInput::class.java)!!
+ "payload/requests/remote-ansible-request-full.json",
+ ExecutionServiceInput::class.java
+ )!!
val bluePrintRuntimeService = createBlueprintRuntimeService(awxRemoteExecutor, executionServiceInput)
assertEquals(1, errors.size)
}
- private fun createBlueprintRuntimeService(awxRemoteExecutor: ComponentRemoteAnsibleExecutor, executionServiceInput: ExecutionServiceInput): BluePrintRuntimeService<MutableMap<String, JsonNode>> {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("123456-1000",
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/remote_ansible")
+ private fun createBlueprintRuntimeService(
+ awxRemoteExecutor: ComponentRemoteAnsibleExecutor,
+ executionServiceInput: ExecutionServiceInput
+ ): BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "123456-1000",
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/remote_ansible"
+ )
awxRemoteExecutor.bluePrintRuntimeService = bluePrintRuntimeService
val workflowName = executionServiceInput.actionIdentifiers.actionName
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentScriptExecutor
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
-
import org.slf4j.LoggerFactory
open class TestCliScriptFunction : AbstractScriptComponentFunction() {
}
}
-
open class Check : AbstractScriptComponentFunction() {
private val log = LoggerFactory.getLogger(AbstractScriptComponentFunction::class.java)!!
@ComponentScan
@EnableConfigurationProperties
@ConditionalOnProperty(name = ["blueprintsprocessor.cliExecutor.enabled"], havingValue = "true")
-open class CliExecutorConfiguration
\ No newline at end of file
+open class CliExecutorConfiguration
fun AbstractComponentFunction.getSshClientService(cliDeviceInfo: JsonNode): BlueprintSshClientService {
return BluePrintDependencyService.sshClientService(cliDeviceInfo)
}
-
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [CliExecutorConfiguration::class,
- ExecutionServiceConfiguration::class,
- BluePrintSshLibConfiguration::class, BluePrintScriptsServiceImpl::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDependencyService::class])
+@ContextConfiguration(
+ classes = [CliExecutorConfiguration::class,
+ ExecutionServiceConfiguration::class,
+ BluePrintSshLibConfiguration::class, BluePrintScriptsServiceImpl::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDependencyService::class]
+)
@DirtiesContext
@TestPropertySource(properties = [], locations = ["classpath:application-test.properties"])
class ComponentCliExecutorTest {
operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive()
operationInputs[ComponentScriptExecutor.INPUT_SCRIPT_TYPE] = BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive()
operationInputs[ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE] =
- "internal.scripts.TestCliScriptFunction".asJsonPrimitive()
+ "internal.scripts.TestCliScriptFunction".asJsonPrimitive()
val stepInputData = StepData().apply {
name = "activate-cli"
val blueprintContext = mockk<BluePrintContext>()
every { bluePrintRuntime.bluePrintContext() } returns blueprintContext
every {
- bluePrintRuntime.resolveNodeTemplateInterfaceOperationInputs("activate-cli",
- "interfaceName", "operationName")
+ bluePrintRuntime.resolveNodeTemplateInterfaceOperationInputs(
+ "activate-cli",
+ "interfaceName", "operationName"
+ )
} returns operationInputs
val operationOutputs = hashMapOf<String, JsonNode>()
every {
- bluePrintRuntime.resolveNodeTemplateInterfaceOperationOutputs("activate-cli",
- "interfaceName", "operationName")
+ bluePrintRuntime.resolveNodeTemplateInterfaceOperationOutputs(
+ "activate-cli",
+ "interfaceName", "operationName"
+ )
} returns operationOutputs
componentScriptExecutor.applyNB(executionServiceInput)
}
}
-}
\ No newline at end of file
+}
import org.xmlunit.diff.ComparisonType
import org.xmlunit.diff.Diff
-
/**
* ComponentConfigSnapshotsExecutor
*
@Component("component-config-snapshots-executor")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
open class ComponentConfigSnapshotsExecutor(private val cfgSnapshotService: ResourceConfigSnapshotService) :
- AbstractComponentFunction() {
+ AbstractComponentFunction() {
companion object {
private val log = LoggerFactory.getLogger(ComponentConfigSnapshotsExecutor::class.java)
when (operation) {
OPERATION_FETCH -> fetchConfigurationSnapshot(resourceId, resourceType, status)
OPERATION_STORE -> storeConfigurationSnapshot(snapshot, resourceId, resourceType, status)
- OPERATION_DIFF -> compareConfigurationSnapshot(resourceId, resourceType, contentType)
+ OPERATION_DIFF -> compareConfigurationSnapshot(resourceId, resourceType, contentType)
- else -> setNodeOutputErrors(OUTPUT_STATUS_ERROR,
- "Operation parameter must be fetch, store or diff")
+ else -> setNodeOutputErrors(
+ OUTPUT_STATUS_ERROR,
+ "Operation parameter must be fetch, store or diff"
+ )
}
}
/**
* Fetch a configuration snapshot, for resource identified by ID/type, of type status (RUNNING by default)
*/
- private suspend fun fetchConfigurationSnapshot(resourceId: String, resourceType: String,
- status : ResourceConfigSnapshot.Status = RUNNING) {
+ private suspend fun fetchConfigurationSnapshot(
+ resourceId: String,
+ resourceType: String,
+ status: ResourceConfigSnapshot.Status = RUNNING
+ ) {
try {
val cfgSnapshotValue = cfgSnapshotService.findByResourceIdAndResourceTypeAndStatus(resourceId, resourceType, status)
setNodeOutputProperties(OUTPUT_STATUS_SUCCESS, cfgSnapshotValue)
- } catch (er : NoSuchElementException) {
+ } catch (er: NoSuchElementException) {
val message = "No Resource config snapshot identified by resourceId={$resourceId}, " +
"resourceType={$resourceType} does not exists"
setNodeOutputErrors(OUTPUT_STATUS_ERROR, message)
/**
* Store a configuration snapshot, for resource identified by ID/type, of type status (RUNNING by default)
*/
- private suspend fun storeConfigurationSnapshot(cfgSnapshotValue : String, resourceId: String, resourceType: String,
- status : ResourceConfigSnapshot.Status = RUNNING) {
+ private suspend fun storeConfigurationSnapshot(
+ cfgSnapshotValue: String,
+ resourceId: String,
+ resourceType: String,
+ status: ResourceConfigSnapshot.Status = RUNNING
+ ) {
if (cfgSnapshotValue.isNotEmpty()) {
val cfgSnapshotSaved = cfgSnapshotService.write(cfgSnapshotValue, resourceId, resourceType, status)
- setNodeOutputProperties(OUTPUT_STATUS_SUCCESS, cfgSnapshotSaved.config_snapshot ?: "" )
+ setNodeOutputProperties(OUTPUT_STATUS_SUCCESS, cfgSnapshotSaved.config_snapshot ?: "")
} else {
val message = "Could not store config snapshot identified by resourceId={$resourceId},resourceType={$resourceType} does not exists"
setNodeOutputErrors(OUTPUT_STATUS_ERROR, message)
/**
* Compare two configs (RUNNING vs CANDIDATE) for resource identified by ID/type, using the specified contentType
*/
- private suspend fun compareConfigurationSnapshot(resourceId: String, resourceType: String, contentType : String) {
+ private suspend fun compareConfigurationSnapshot(resourceId: String, resourceType: String, contentType: String) {
val cfgRunning = cfgSnapshotService.findByResourceIdAndResourceTypeAndStatus(resourceId, resourceType, RUNNING)
val cfgCandidate = cfgSnapshotService.findByResourceIdAndResourceTypeAndStatus(resourceId, resourceType, CANDIDATE)
}
DIFF_XML -> {
val myDiff = DiffBuilder
- .compare(Input.fromString(cfgRunning))
- .withTest(Input.fromString(cfgCandidate))
- .checkForSimilar()
- .ignoreComments()
- .ignoreWhitespace()
- .normalizeWhitespace()
- .build()
+ .compare(Input.fromString(cfgRunning))
+ .withTest(Input.fromString(cfgCandidate))
+ .checkForSimilar()
+ .ignoreComments()
+ .ignoreWhitespace()
+ .normalizeWhitespace()
+ .build()
setNodeOutputProperties(OUTPUT_STATUS_SUCCESS, formatXmlDifferences(myDiff))
}
/**
* Formats XmlUnit differences into xml-patch like response (RFC5261)
*/
- private fun formatXmlDifferences(differences : Diff) : String {
+ private fun formatXmlDifferences(differences: Diff): String {
val output = StringBuilder()
- output.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
- "<diff>")
+ output.append(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<diff>"
+ )
val diffIterator = differences.getDifferences().iterator()
while (diffIterator.hasNext()) {
when (aDiff.type) {
ComparisonType.ATTR_VALUE -> {
output.append("<replace sel=\"").append(aDiff.testDetails.xPath).append("\">")
- .append(aDiff.testDetails.value)
- .append("</replace>")
+ .append(aDiff.testDetails.value)
+ .append("</replace>")
}
ComparisonType.TEXT_VALUE -> {
output.append("<replace sel=\"").append(aDiff.testDetails.xPath).append("\">")
- .append(aDiff.testDetails.value)
- .append("</replace>")
+ .append(aDiff.testDetails.value)
+ .append("</replace>")
}
ComparisonType.CHILD_LOOKUP -> {
output.append("<add sel=\"").append(aDiff.testDetails.parentXPath).append("\">")
- .append(formatNode(aDiff.testDetails.target))
- .append("</add>")
+ .append(formatNode(aDiff.testDetails.target))
+ .append("</add>")
}
ComparisonType.CHILD_NODELIST_LENGTH -> {
// Ignored; will be processed in the CHILD_LOOKUP case
if (node.hasChildNodes()) {
val nodes = node.childNodes
for (index in 1..nodes.length) {
- val child = nodes.item(index-1)
+ val child = nodes.item(index - 1)
if (child.nodeType == Node.TEXT_NODE || child.nodeType == Node.COMMENT_NODE) {
output.append(child.nodeValue)
} else {
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
/**
* ResourceConfigSnapshot model
fun findByResourceIdAndResourceTypeAndStatus(
resourceId: String,
resourceType: String,
- status : ResourceConfigSnapshot.Status): ResourceConfigSnapshot?
+ status: ResourceConfigSnapshot.Status
+ ): ResourceConfigSnapshot?
@Transactional
fun deleteByResourceIdAndResourceTypeAndStatus(
resourceId: String,
resourceType: String,
- status : ResourceConfigSnapshot.Status)
+ status: ResourceConfigSnapshot.Status
+ )
}
import org.slf4j.LoggerFactory
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.UUID
/**
* ResourceConfigSnapshot managing service.
private val log = LoggerFactory.getLogger(ResourceConfigSnapshotService::class.toString())
- suspend fun findByResourceIdAndResourceTypeAndStatus(resourceId: String, resourceType: String,
- status : ResourceConfigSnapshot.Status = RUNNING): String =
- withContext(Dispatchers.IO) {
- repository.findByResourceIdAndResourceTypeAndStatus(resourceId, resourceType, status)
- ?.config_snapshot ?: Strings.EMPTY
- }
+ suspend fun findByResourceIdAndResourceTypeAndStatus(
+ resourceId: String,
+ resourceType: String,
+ status: ResourceConfigSnapshot.Status = RUNNING
+ ): String =
+ withContext(Dispatchers.IO) {
+ repository.findByResourceIdAndResourceTypeAndStatus(resourceId, resourceType, status)
+ ?.config_snapshot ?: Strings.EMPTY
+ }
- suspend fun write(snapshot: String, resId: String, resType: String,
- status: ResourceConfigSnapshot.Status = RUNNING) : ResourceConfigSnapshot =
- withContext(Dispatchers.IO) {
+ suspend fun write(
+ snapshot: String,
+ resId: String,
+ resType: String,
+ status: ResourceConfigSnapshot.Status = RUNNING
+ ): ResourceConfigSnapshot =
+ withContext(Dispatchers.IO) {
- val resourceConfigSnapshotEntry = ResourceConfigSnapshot()
- resourceConfigSnapshotEntry.id = UUID.randomUUID().toString()
- resourceConfigSnapshotEntry.resourceId = resId
- resourceConfigSnapshotEntry.resourceType = resType
- resourceConfigSnapshotEntry.status = status
- resourceConfigSnapshotEntry.config_snapshot = snapshot
+ val resourceConfigSnapshotEntry = ResourceConfigSnapshot()
+ resourceConfigSnapshotEntry.id = UUID.randomUUID().toString()
+ resourceConfigSnapshotEntry.resourceId = resId
+ resourceConfigSnapshotEntry.resourceType = resType
+ resourceConfigSnapshotEntry.status = status
+ resourceConfigSnapshotEntry.config_snapshot = snapshot
- // Overwrite configuration snapshot entry of resId/resType
- if (resId.isNotEmpty() && resType.isNotEmpty()) {
- repository.findByResourceIdAndResourceTypeAndStatus(resId, resType, status)?.
- let {
- log.info("Overwriting configuration snapshot entry for resourceId=($resId), " +
- "resourceType=($resType), status=($status)")
- repository.deleteByResourceIdAndResourceTypeAndStatus(resId, resType, status)
- }
- }
- var storedSnapshot: ResourceConfigSnapshot
- try {
- storedSnapshot = repository.saveAndFlush(resourceConfigSnapshotEntry)
- log.info("Stored configuration snapshot for resourceId=($resId), " +
+ // Overwrite configuration snapshot entry of resId/resType
+ if (resId.isNotEmpty() && resType.isNotEmpty()) {
+ repository.findByResourceIdAndResourceTypeAndStatus(resId, resType, status)
+ ?.let {
+ log.info(
+ "Overwriting configuration snapshot entry for resourceId=($resId), " +
+ "resourceType=($resType), status=($status)"
+ )
+ repository.deleteByResourceIdAndResourceTypeAndStatus(resId, resType, status)
+ }
+ }
+ var storedSnapshot: ResourceConfigSnapshot
+ try {
+ storedSnapshot = repository.saveAndFlush(resourceConfigSnapshotEntry)
+ log.info(
+ "Stored configuration snapshot for resourceId=($resId), " +
"resourceType=($resType), status=($status), " +
- "dated=(${storedSnapshot.createdDate})")
- } catch (ex: DataIntegrityViolationException) {
- throw BluePrintException("Failed to store configuration snapshot entry.", ex)
- }
- storedSnapshot
+ "dated=(${storedSnapshot.createdDate})"
+ )
+ } catch (ex: DataIntegrityViolationException) {
+ throw BluePrintException("Failed to store configuration snapshot entry.", ex)
}
+ storedSnapshot
+ }
}
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [ResourceConfigSnapshotService::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class,
- BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class])
+@ContextConfiguration(
+ classes = [ResourceConfigSnapshotService::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class,
+ BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
@EnableAutoConfiguration
class ComponentConfigSnapshotsExecutorTest {
@Autowired
- lateinit var cfgSnapshotService : ResourceConfigSnapshotService
- lateinit var cfgSnapshotComponent : ComponentConfigSnapshotsExecutor
- private var bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("123456-1000",
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts")
+ lateinit var cfgSnapshotService: ResourceConfigSnapshotService
+ lateinit var cfgSnapshotComponent: ComponentConfigSnapshotsExecutor
+ private var bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "123456-1000",
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts"
+ )
private val resourceId = "1"
private val resourceType = "ServiceInstance"
props[ComponentConfigSnapshotsExecutor.INPUT_RESOURCE_ID] = resourceId.asJsonPrimitive()
props[ComponentConfigSnapshotsExecutor.INPUT_RESOURCE_TYPE] = resourceType.asJsonPrimitive()
-
cfgSnapshotComponent.operationInputs = props
cfgSnapshotComponent.bluePrintRuntimeService = bluePrintRuntimeService
cfgSnapshotComponent.nodeTemplateName = nodeTemplateName
cfgSnapshotComponent.processNB(executionRequest)
} catch (e: BluePrintProcessorException) {
- kotlin.test.assertEquals("Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
- e.message)
+ kotlin.test.assertEquals(
+ "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
+ e.message
+ )
return@runBlocking
}
// then; we should get success and the TEST1 payload in our output properties
- assertEquals(ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_STATUS))
- assertEquals(snapshotConfig.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT))
+ assertEquals(
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS
+ )
+ )
+ assertEquals(
+ snapshotConfig.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT
+ )
+ )
}
}
try {
val resId = "121111"
val resType = "PNF"
- cfgSnapshotService.write(snapshotConfig, resId, resType, ResourceConfigSnapshot.Status.CANDIDATE)
+ cfgSnapshotService.write(snapshotConfig, resId, resType, ResourceConfigSnapshot.Status.CANDIDATE)
prepareRequestProperties(OPERATION_FETCH, resId, resType, ResourceConfigSnapshot.Status.CANDIDATE.name)
cfgSnapshotComponent.processNB(executionRequest)
} catch (e: BluePrintProcessorException) {
- kotlin.test.assertEquals("Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
- e.message)
+ kotlin.test.assertEquals(
+ "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
+ e.message
+ )
return@runBlocking
}
// then; we should get success and the TEST payload in our output properties
- assertEquals(ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_STATUS))
- assertEquals(snapshotConfig.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT))
+ assertEquals(
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS
+ )
+ )
+ assertEquals(
+ snapshotConfig.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT
+ )
+ )
}
}
prepareRequestProperties(OPERATION_STORE, resId, resType, snapshotConfig)
cfgSnapshotComponent.processNB(executionRequest)
-
} catch (e: BluePrintProcessorException) {
- kotlin.test.assertEquals("Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
- e.message)
+ kotlin.test.assertEquals(
+ "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
+ e.message
+ )
return@runBlocking
}
// then; we should get success and the PAYLOAD payload in our output properties
- assertEquals(ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_STATUS))
- assertEquals(snapshotConfig.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT))
+ assertEquals(
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS
+ )
+ )
+ assertEquals(
+ snapshotConfig.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT
+ )
+ )
}
}
runBlocking {
// when; asking for unknown resource Id/ resource Type combo; should get an error response
try {
- prepareRequestProperties(OPERATION_FETCH, "asdasd", "PNF", ResourceConfigSnapshot.Status.RUNNING.name)
+ prepareRequestProperties(OPERATION_FETCH, "asdasd", "PNF", ResourceConfigSnapshot.Status.RUNNING.name)
cfgSnapshotComponent.processNB(executionRequest)
-
} catch (e: BluePrintProcessorException) {
- kotlin.test.assertEquals("Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
- e.message)
+ kotlin.test.assertEquals(
+ "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
+ e.message
+ )
return@runBlocking
}
- assertEquals(ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_STATUS))
+ assertEquals(
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS
+ )
+ )
}
}
runBlocking {
// when; asking for unknown operation update; should get an error response
try {
- prepareRequestProperties("update", "asdasd", "PNF", ResourceConfigSnapshot.Status.RUNNING.name)
+ prepareRequestProperties("update", "asdasd", "PNF", ResourceConfigSnapshot.Status.RUNNING.name)
cfgSnapshotComponent.processNB(executionRequest)
-
} catch (e: BluePrintProcessorException) {
- kotlin.test.assertEquals("Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
- e.message)
+ kotlin.test.assertEquals(
+ "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
+ e.message
+ )
return@runBlocking
}
// then; we should get error in our output properties
- assertTrue( bluePrintRuntimeService.getBluePrintError().errors.size == 1 )
- assertEquals(ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_ERROR.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_STATUS))
+ assertTrue(bluePrintRuntimeService.getBluePrintError().errors.size == 1)
+ assertEquals(
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_ERROR.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS
+ )
+ )
val msg = "Operation parameter must be fetch, store or diff"
- assertEquals(msg.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_MESSAGE))
+ assertEquals(
+ msg.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_MESSAGE
+ )
+ )
}
}
try {
val resId = "121111"
val resType = "PNF"
- cfgSnapshotService.write("snapshotConfig", resId, resType, ResourceConfigSnapshot.Status.CANDIDATE)
- prepareRequestProperties(OPERATION_DIFF, resId, resType, "YANG")
+ cfgSnapshotService.write("snapshotConfig", resId, resType, ResourceConfigSnapshot.Status.CANDIDATE)
+ prepareRequestProperties(OPERATION_DIFF, resId, resType, "YANG")
cfgSnapshotComponent.processNB(executionRequest)
-
} catch (e: BluePrintProcessorException) {
- kotlin.test.assertEquals("Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
- e.message)
+ kotlin.test.assertEquals(
+ "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.",
+ e.message
+ )
return@runBlocking
}
// then; we should get error in our output properties
- assertEquals(ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_ERROR.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_STATUS))
+ assertEquals(
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_ERROR.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS
+ )
+ )
val message = "Could not compare config snapshots for type YANG"
- assertEquals(message.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_MESSAGE))
+ assertEquals(
+ message.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_MESSAGE
+ )
+ )
}
}
prepareRequestProperties(OPERATION_DIFF, resId, resType, DIFF_JSON)
cfgSnapshotComponent.processNB(executionRequest)
-
} catch (e: BluePrintProcessorException) {
- kotlin.test.assertEquals("Can't proceed with the cfg snapshot diff: provide resource-id and resource-type.",
- e.message)
+ kotlin.test.assertEquals(
+ "Can't proceed with the cfg snapshot diff: provide resource-id and resource-type.",
+ e.message
+ )
return@runBlocking
}
// then; we should get success
- assertTrue( bluePrintRuntimeService.getBluePrintError().errors.size == 0 )
- assertEquals(ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_STATUS))
+ assertTrue(bluePrintRuntimeService.getBluePrintError().errors.size == 0)
+ assertEquals(
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS
+ )
+ )
// then; we should get JSON-patches differences in our response property
- val diffJson = "[{\"op\":\"add\",\"path\":\"/system-uptime-information/last-configured-time/new-child-object\",\"value\":{\"property\":\"value\"}}," +
- "{\"op\":\"replace\",\"path\":\"/system-uptime-information/system-booted-time/time-length\",\"value\":\"14:52:54\"}," +
- "{\"op\":\"replace\",\"path\":\"/system-uptime-information/time-source\",\"value\":\" DNS CLOCK \"}," +
- "{\"op\":\"add\",\"path\":\"/system-uptime-information/uptime-information/load-average-10\",\"value\":\"0.05\"}]"
- assertEquals(diffJson.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT))
+ val diffJson =
+ "[{\"op\":\"add\",\"path\":\"/system-uptime-information/last-configured-time/new-child-object\",\"value\":{\"property\":\"value\"}}," +
+ "{\"op\":\"replace\",\"path\":\"/system-uptime-information/system-booted-time/time-length\",\"value\":\"14:52:54\"}," +
+ "{\"op\":\"replace\",\"path\":\"/system-uptime-information/time-source\",\"value\":\" DNS CLOCK \"}," +
+ "{\"op\":\"add\",\"path\":\"/system-uptime-information/uptime-information/load-average-10\",\"value\":\"0.05\"}]"
+ assertEquals(
+ diffJson.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT
+ )
+ )
}
}
prepareRequestProperties(OPERATION_DIFF, resId, resType, DIFF_XML)
cfgSnapshotComponent.processNB(executionRequest)
-
} catch (e: BluePrintProcessorException) {
- kotlin.test.assertEquals("Can't proceed with the cfg snapshot diff: provide resource-id and resource-type.",
- e.message)
+ kotlin.test.assertEquals(
+ "Can't proceed with the cfg snapshot diff: provide resource-id and resource-type.",
+ e.message
+ )
return@runBlocking
}
// then; we should get success
- assertTrue( bluePrintRuntimeService.getBluePrintError().errors.size == 0 )
- assertEquals(ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_STATUS))
+ assertTrue(bluePrintRuntimeService.getBluePrintError().errors.size == 0)
+ assertEquals(
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_STATUS
+ )
+ )
// then; we should get XML-patches differences in our response property
val diffXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<replace sel=\"/output[1]/interface-information[1]/traffic-statistics[1]/output-packets[1]/text()[1]\">2828828</replace>" +
"<add sel=\"/output[1]/interface-information[1]/physical-interface[1]\"><interface-name>TEGig400-int01</interface-name></add>" +
"</diff>"
- assertEquals(diffXml.asJsonPrimitive(),
- bluePrintRuntimeService.getNodeTemplateAttributeValue(nodeTemplateName,
- ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT)) }
+ assertEquals(
+ diffXml.asJsonPrimitive(),
+ bluePrintRuntimeService.getNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ComponentConfigSnapshotsExecutor.OUTPUT_SNAPSHOT
+ )
+ )
+ }
}
- private fun preparePayload(filename : String, resId : String, resType : String, status: ResourceConfigSnapshot.Status) {
+ private fun preparePayload(filename: String, resId: String, resType: String, status: ResourceConfigSnapshot.Status) {
runBlocking {
cfgSnapshotService.write(JacksonUtils.getClassPathFileContent("payload/requests/$filename"), resId, resType, status)
}
}
- private fun prepareRequestProperties (oper : String, resId : String, resType : String, optional: String = "") {
+ private fun prepareRequestProperties(oper: String, resId: String, resType: String, optional: String = "") {
cfgSnapshotComponent.operationInputs[ComponentConfigSnapshotsExecutor.INPUT_OPERATION] = oper.asJsonPrimitive()
cfgSnapshotComponent.operationInputs[ComponentConfigSnapshotsExecutor.INPUT_RESOURCE_ID] = resId.asJsonPrimitive()
cfgSnapshotComponent.operationInputs[ComponentConfigSnapshotsExecutor.INPUT_RESOURCE_TYPE] = resType.asJsonPrimitive()
cfgSnapshotComponent.operationInputs[ComponentConfigSnapshotsExecutor.INPUT_DIFF_CONTENT_TYPE] = "".asJsonPrimitive()
cfgSnapshotComponent.operationInputs[ComponentConfigSnapshotsExecutor.INPUT_RESOURCE_SNAPSHOT] = "".asJsonPrimitive()
cfgSnapshotComponent.operationInputs[ComponentConfigSnapshotsExecutor.INPUT_RESOURCE_STATUS] =
- ResourceConfigSnapshot.Status.RUNNING.name.asJsonPrimitive()
+ ResourceConfigSnapshot.Status.RUNNING.name.asJsonPrimitive()
when (oper) {
OPERATION_DIFF ->
every {
cfgRepository.findByResourceIdAndResourceTypeAndStatus(any(), any(), any())
} returns null
- val res = cfgService.write( configSnapshot, resourceId, resourceType, resourceStatus)
+ val res = cfgService.write(configSnapshot, resourceId, resourceType, resourceStatus)
assertEquals(tr, res)
}
}
every {
cfgRepository.deleteByResourceIdAndResourceTypeAndStatus(any(), any(), any())
} returns Unit
- val res = cfgService.write( configSnapshot, resourceId, resourceType)
+ val res = cfgService.write(configSnapshot, resourceId, resourceType)
verify {
cfgRepository.deleteByResourceIdAndResourceTypeAndStatus(eq(resourceId), eq(resourceType), eq(resourceStatus))
}
this.processorContext = context
/** Get the State service to update in store */
this.messagePrioritizationStateService = BluePrintDependencyService
- .messagePrioritizationStateService()
-
+ .messagePrioritizationStateService()
}
-
-}
\ No newline at end of file
+}
@ComponentScan
open class MessagePrioritizationConfiguration
-
object MessagePrioritizationConstants {
const val SOURCE_INPUT = "source-prioritization-input"
const val SINK_OUTPUT = "sink-prioritization-output"
const val SINK_EXPIRED = "sink-prioritization-expired"
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.logger
open class MessagePrioritizationConsumer(
- private val bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService) {
+ private val bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService
+) {
private val log = logger(MessagePrioritizationConsumer::class)
open fun consumerService(selector: String): BlueprintMessageConsumerService {
return bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService(selector)
+ .blueprintMessageConsumerService(selector)
}
- open fun kafkaStreamConsumerFunction(prioritizationConfiguration: PrioritizationConfiguration)
- : KafkaStreamConsumerFunction {
+ open fun kafkaStreamConsumerFunction(prioritizationConfiguration: PrioritizationConfiguration):
+ KafkaStreamConsumerFunction {
return object : KafkaStreamConsumerFunction {
- override suspend fun createTopology(messageConsumerProperties: MessageConsumerProperties,
- additionalConfig: Map<String, Any>?): Topology {
+ override suspend fun createTopology(
+ messageConsumerProperties: MessageConsumerProperties,
+ additionalConfig: Map<String, Any>?
+ ): Topology {
val topology = Topology()
val kafkaStreamsBasicAuthConsumerProperties = messageConsumerProperties
topology.addSource(MessagePrioritizationConstants.SOURCE_INPUT, *topics.toTypedArray())
- topology.addProcessor(MessagePrioritizationConstants.PROCESSOR_PRIORITIZE,
- bluePrintProcessorSupplier<ByteArray, ByteArray>(MessagePrioritizationConstants.PROCESSOR_PRIORITIZE,
- prioritizationConfiguration),
- MessagePrioritizationConstants.SOURCE_INPUT)
-
- topology.addProcessor(MessagePrioritizationConstants.PROCESSOR_AGGREGATE,
- bluePrintProcessorSupplier<String, String>(MessagePrioritizationConstants.PROCESSOR_AGGREGATE,
- prioritizationConfiguration),
- MessagePrioritizationConstants.PROCESSOR_PRIORITIZE)
-
- topology.addProcessor(MessagePrioritizationConstants.PROCESSOR_OUTPUT,
- bluePrintProcessorSupplier<String, String>(MessagePrioritizationConstants.PROCESSOR_OUTPUT,
- prioritizationConfiguration),
- MessagePrioritizationConstants.PROCESSOR_AGGREGATE)
-
- topology.addSink(MessagePrioritizationConstants.SINK_EXPIRED,
- prioritizationConfiguration.expiredTopic,
- Serdes.String().serializer(), MessagePrioritizationSerde().serializer(),
- MessagePrioritizationConstants.PROCESSOR_PRIORITIZE)
-
- /** To receive completed and error messages */
- topology.addSink(MessagePrioritizationConstants.SINK_OUTPUT,
- prioritizationConfiguration.outputTopic,
- Serdes.String().serializer(), MessagePrioritizationSerde().serializer(),
+ topology.addProcessor(
+ MessagePrioritizationConstants.PROCESSOR_PRIORITIZE,
+ bluePrintProcessorSupplier<ByteArray, ByteArray>(
MessagePrioritizationConstants.PROCESSOR_PRIORITIZE,
+ prioritizationConfiguration
+ ),
+ MessagePrioritizationConstants.SOURCE_INPUT
+ )
+
+ topology.addProcessor(
+ MessagePrioritizationConstants.PROCESSOR_AGGREGATE,
+ bluePrintProcessorSupplier<String, String>(
MessagePrioritizationConstants.PROCESSOR_AGGREGATE,
- MessagePrioritizationConstants.PROCESSOR_OUTPUT)
+ prioritizationConfiguration
+ ),
+ MessagePrioritizationConstants.PROCESSOR_PRIORITIZE
+ )
+
+ topology.addProcessor(
+ MessagePrioritizationConstants.PROCESSOR_OUTPUT,
+ bluePrintProcessorSupplier<String, String>(
+ MessagePrioritizationConstants.PROCESSOR_OUTPUT,
+ prioritizationConfiguration
+ ),
+ MessagePrioritizationConstants.PROCESSOR_AGGREGATE
+ )
+
+ topology.addSink(
+ MessagePrioritizationConstants.SINK_EXPIRED,
+ prioritizationConfiguration.expiredTopic,
+ Serdes.String().serializer(), MessagePrioritizationSerde().serializer(),
+ MessagePrioritizationConstants.PROCESSOR_PRIORITIZE
+ )
+
+ /** To receive completed and error messages */
+ topology.addSink(
+ MessagePrioritizationConstants.SINK_OUTPUT,
+ prioritizationConfiguration.outputTopic,
+ Serdes.String().serializer(), MessagePrioritizationSerde().serializer(),
+ MessagePrioritizationConstants.PROCESSOR_PRIORITIZE,
+ MessagePrioritizationConstants.PROCESSOR_AGGREGATE,
+ MessagePrioritizationConstants.PROCESSOR_OUTPUT
+ )
// Output will be sent to the group-output topic from Processor API
return topology
streamingConsumerService.shutDown()
}
}
-}
\ No newline at end of file
+}
var state: String? = null
}
-data class CorrelationCheckResponse(var message: String? = null,
- var correlated: Boolean = false)
+data class CorrelationCheckResponse(
+ var message: String? = null,
+ var correlated: Boolean = false
+)
data class TypeCorrelationKey(val type: String, val correlationId: String)
-
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService
-
/**
* Register the MessagePrioritizationStateService and exposed dependency
*/
fun BluePrintDependencyService.messagePrioritizationStateService(): MessagePrioritizationStateService =
- instance(MessagePrioritizationStateService::class)
+ instance(MessagePrioritizationStateService::class)
/**
* Expose messagePrioritizationStateService to AbstractComponentFunction
*/
fun AbstractComponentFunction.messagePrioritizationStateService() =
- BluePrintDependencyService.messagePrioritizationStateService()
+ BluePrintDependencyService.messagePrioritizationStateService()
/**
* MessagePrioritization correlation extensions
*/
fun MessagePrioritization.toFormatedCorrelation(): String {
val ascendingKey = this.correlationId!!.split(",")
- .map { it.trim() }.sorted().joinToString(",")
+ .map { it.trim() }.sorted().joinToString(",")
return ascendingKey
}
fun MessagePrioritization.toTypeNCorrelation(): TypeCorrelationKey {
val ascendingKey = this.correlationId!!.split(",")
- .map { it.trim() }.sorted().joinToString(",")
+ .map { it.trim() }.sorted().joinToString(",")
return TypeCorrelationKey(this.type, ascendingKey)
}
import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.service.MessagePrioritizationStateService
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.monoMdc
import org.springframework.http.MediaType
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.GetMapping
+import org.springframework.web.bind.annotation.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(value = ["/api/v1/message-prioritization"])
@ResponseBody
fun ping(): String = "Success"
-
@GetMapping(path = ["/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
fun messagePrioritization(@PathVariable(value = "id") id: String) = monoMdc {
messagePrioritizationStateService.getMessage(id)
}
- @PostMapping(path = ["/"], produces = [MediaType.APPLICATION_JSON_VALUE],
- consumes = [MediaType.APPLICATION_JSON_VALUE])
+ @PostMapping(
+ path = ["/"], produces = [MediaType.APPLICATION_JSON_VALUE],
+ consumes = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
fun saveMessagePrioritization(@RequestBody messagePrioritization: MessagePrioritization) = monoMdc {
messagePrioritizationStateService.saveMessage(messagePrioritization)
}
- @PostMapping(path = ["/update-state"], produces = [MediaType.APPLICATION_JSON_VALUE],
- consumes = [MediaType.APPLICATION_JSON_VALUE])
+ @PostMapping(
+ path = ["/update-state"], produces = [MediaType.APPLICATION_JSON_VALUE],
+ consumes = [MediaType.APPLICATION_JSON_VALUE]
+ )
fun updateMessagePrioritizationState(@RequestBody updateMessageState: UpdateStateRequest) =
- monoMdc {
- messagePrioritizationStateService.setMessageState(updateMessageState.id,
- updateMessageState.state!!)
- }
-}
\ No newline at end of file
+ monoMdc {
+ messagePrioritizationStateService.setMessageState(
+ updateMessageState.id,
+ updateMessageState.state!!
+ )
+ }
+}
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import org.springframework.data.jpa.repository.config.EnableJpaAuditing
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
@EnableJpaAuditing
@EntityListeners(AuditingEntityListener::class)
@Table(name = "MESSAGE_PRIORITIZATION")
@Proxy(lazy = false)
open class MessagePrioritization {
+
@Id
@Column(name = "message_id", length = 50)
lateinit var id: String
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "expiry_date", nullable = false)
var expiryDate: Date? = null
-}
\ No newline at end of file
+}
+++ /dev/null
-/*
- * Copyright © 2018-2019 AT&T Intellectual Property.
- *
- * 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.
- */
-
-package org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db
-
-import org.springframework.data.domain.Pageable
-import org.springframework.data.jpa.repository.JpaRepository
-import org.springframework.data.jpa.repository.Modifying
-import org.springframework.data.jpa.repository.Query
-import org.springframework.stereotype.Repository
-import org.springframework.transaction.annotation.Transactional
-import java.util.*
-
-@Repository
-@Transactional(readOnly = true)
-interface PrioritizationMessageRepository : JpaRepository<MessagePrioritization, String> {
-
- @Query("FROM MessagePrioritization pm WHERE pm.group = :group ORDER BY pm.createdDate asc")
- fun findByGroup(group: String, count: Pageable): List<MessagePrioritization>?
-
- @Query("FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
- "ORDER BY pm.createdDate asc")
- fun findByGroupAndStateIn(group: String, states: List<String>, count: Pageable): List<MessagePrioritization>?
-
- @Query("FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
- "ORDER BY pm.updatedDate asc")
- fun findByGroupAndStateInOrderByUpdatedDate(group: String, states: List<String>, count: Pageable)
- : List<MessagePrioritization>?
-
- @Query("FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
- "AND pm.expiryDate > :expiryCheckDate ORDER BY pm.createdDate asc")
- fun findByGroupAndStateInAndNotExpiredDate(group: String, states: List<String>, expiryCheckDate: Date,
- count: Pageable): List<MessagePrioritization>?
-
- @Query("FROM MessagePrioritization pm WHERE pm.state in :states " +
- "AND pm.expiryDate < :expiryCheckDate ORDER BY pm.createdDate asc")
- fun findByStateInAndExpiredDate(states: List<String>, expiryCheckDate: Date,
- count: Pageable): List<MessagePrioritization>?
-
- @Query("FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
- "AND pm.expiryDate < :expiryCheckDate ORDER BY pm.createdDate asc")
- fun findByGroupAndStateInAndExpiredDate(group: String, states: List<String>, expiryCheckDate: Date,
- count: Pageable): List<MessagePrioritization>?
-
- @Query("FROM MessagePrioritization pm WHERE pm.group = :group " +
- "AND pm.expiryDate < :expiryCheckDate ORDER BY pm.createdDate asc")
- fun findByByGroupAndExpiredDate(group: String, expiryCheckDate: Date, count: Pageable): List<MessagePrioritization>?
-
- @Query("FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
- "AND pm.correlationId = :correlationId ORDER BY pm.createdDate asc")
- fun findByGroupAndCorrelationId(group: String, states: List<String>, correlationId: String)
- : List<MessagePrioritization>?
-
- @Query("FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
- "AND pm.type in :types AND pm.correlationId = :correlationId ORDER BY pm.createdDate asc")
- fun findByGroupAndTypesAndCorrelationId(group: String, states: List<String>, types: List<String>,
- correlationId: String): List<MessagePrioritization>?
-
- @Modifying
- @Transactional
- @Query("UPDATE MessagePrioritization SET state = :state, updatedDate = :currentDate " +
- "WHERE id = :id")
- fun setStateForMessageId(id: String, state: String, currentDate: Date): Int
-
- @Modifying
- @Transactional
- @Query("UPDATE MessagePrioritization SET priority = :priority, updatedDate = :currentDate " +
- "WHERE id = :id")
- fun setPriorityForMessageId(id: String, priority: String, currentDate: Date): Int
-
- @Modifying
- @Transactional
- @Query("UPDATE MessagePrioritization SET state = :state, updatedDate = :currentDate " +
- "WHERE id IN :ids")
- fun setStateForMessageIds(ids: List<String>, state: String, currentDate: Date): Int
-
- @Modifying
- @Transactional
- @Query("UPDATE MessagePrioritization SET priority = :priority, updatedDate = :currentDate " +
- "WHERE id IN :ids")
- fun setPriorityForMessageIds(ids: List<String>, priority: String, currentDate: Date): Int
-
- @Modifying
- @Transactional
- @Query("UPDATE MessagePrioritization SET state = :state, error = :error, updatedDate = :currentDate " +
- "WHERE id = :id")
- fun setStateAndErrorForMessageId(id: String, state: String, error: String, currentDate: Date): Int
-
- @Modifying
- @Transactional
- @Query("UPDATE MessagePrioritization SET state = :state, " +
- "aggregatedMessageIds = :aggregatedMessageIds, updatedDate = :currentDate WHERE id = :id")
- fun setStateAndAggregatedMessageIds(id: String, state: String, aggregatedMessageIds: String, currentDate: Date): Int
-
- @Modifying
- @Transactional
- @Query("DELETE FROM MessagePrioritization pm WHERE pm.group = :group")
- fun deleteGroup(group: String)
-
- @Modifying
- @Transactional
- @Query("DELETE FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state IN :states")
- fun deleteGroupAndStateIn(group: String, states: List<String>)
-}
-
--- /dev/null
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * 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.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db
+
+import org.springframework.data.domain.Pageable
+import org.springframework.data.jpa.repository.JpaRepository
+import org.springframework.data.jpa.repository.Modifying
+import org.springframework.data.jpa.repository.Query
+import org.springframework.stereotype.Repository
+import org.springframework.transaction.annotation.Transactional
+import java.util.Date
+
+@Repository
+@Transactional(readOnly = true)
+interface PrioritizationMessageRepository : JpaRepository<MessagePrioritization, String> {
+
+ @Query("FROM MessagePrioritization pm WHERE pm.group = :group ORDER BY pm.createdDate asc")
+ fun findByGroup(group: String, count: Pageable): List<MessagePrioritization>?
+
+ @Query(
+ "FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
+ "ORDER BY pm.createdDate asc"
+ )
+ fun findByGroupAndStateIn(group: String, states: List<String>, count: Pageable): List<MessagePrioritization>?
+
+ @Query(
+ "FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
+ "ORDER BY pm.updatedDate asc"
+ )
+ fun findByGroupAndStateInOrderByUpdatedDate(group: String, states: List<String>, count: Pageable):
+ List<MessagePrioritization>?
+
+ @Query(
+ "FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
+ "AND pm.expiryDate > :expiryCheckDate ORDER BY pm.createdDate asc"
+ )
+ fun findByGroupAndStateInAndNotExpiredDate(
+ group: String,
+ states: List<String>,
+ expiryCheckDate: Date,
+ count: Pageable
+ ): List<MessagePrioritization>?
+
+ @Query(
+ "FROM MessagePrioritization pm WHERE pm.state in :states " +
+ "AND pm.expiryDate < :expiryCheckDate ORDER BY pm.createdDate asc"
+ )
+ fun findByStateInAndExpiredDate(
+ states: List<String>,
+ expiryCheckDate: Date,
+ count: Pageable
+ ): List<MessagePrioritization>?
+
+ @Query(
+ "FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
+ "AND pm.expiryDate < :expiryCheckDate ORDER BY pm.createdDate asc"
+ )
+ fun findByGroupAndStateInAndExpiredDate(
+ group: String,
+ states: List<String>,
+ expiryCheckDate: Date,
+ count: Pageable
+ ): List<MessagePrioritization>?
+
+ @Query(
+ "FROM MessagePrioritization pm WHERE pm.group = :group " +
+ "AND pm.expiryDate < :expiryCheckDate ORDER BY pm.createdDate asc"
+ )
+ fun findByByGroupAndExpiredDate(group: String, expiryCheckDate: Date, count: Pageable): List<MessagePrioritization>?
+
+ @Query(
+ "FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
+ "AND pm.correlationId = :correlationId ORDER BY pm.createdDate asc"
+ )
+ fun findByGroupAndCorrelationId(group: String, states: List<String>, correlationId: String):
+ List<MessagePrioritization>?
+
+ @Query(
+ "FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state in :states " +
+ "AND pm.type in :types AND pm.correlationId = :correlationId ORDER BY pm.createdDate asc"
+ )
+ fun findByGroupAndTypesAndCorrelationId(
+ group: String,
+ states: List<String>,
+ types: List<String>,
+ correlationId: String
+ ): List<MessagePrioritization>?
+
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE MessagePrioritization SET state = :state, updatedDate = :currentDate " +
+ "WHERE id = :id"
+ )
+ fun setStateForMessageId(id: String, state: String, currentDate: Date): Int
+
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE MessagePrioritization SET priority = :priority, updatedDate = :currentDate " +
+ "WHERE id = :id"
+ )
+ fun setPriorityForMessageId(id: String, priority: String, currentDate: Date): Int
+
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE MessagePrioritization SET state = :state, updatedDate = :currentDate " +
+ "WHERE id IN :ids"
+ )
+ fun setStateForMessageIds(ids: List<String>, state: String, currentDate: Date): Int
+
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE MessagePrioritization SET priority = :priority, updatedDate = :currentDate " +
+ "WHERE id IN :ids"
+ )
+ fun setPriorityForMessageIds(ids: List<String>, priority: String, currentDate: Date): Int
+
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE MessagePrioritization SET state = :state, error = :error, updatedDate = :currentDate " +
+ "WHERE id = :id"
+ )
+ fun setStateAndErrorForMessageId(id: String, state: String, error: String, currentDate: Date): Int
+
+ @Modifying
+ @Transactional
+ @Query(
+ "UPDATE MessagePrioritization SET state = :state, " +
+ "aggregatedMessageIds = :aggregatedMessageIds, updatedDate = :currentDate WHERE id = :id"
+ )
+ fun setStateAndAggregatedMessageIds(id: String, state: String, aggregatedMessageIds: String, currentDate: Date): Int
+
+ @Modifying
+ @Transactional
+ @Query("DELETE FROM MessagePrioritization pm WHERE pm.group = :group")
+ fun deleteGroup(group: String)
+
+ @Modifying
+ @Transactional
+ @Query("DELETE FROM MessagePrioritization pm WHERE pm.group = :group AND pm.state IN :states")
+ fun deleteGroupAndStateIn(group: String, states: List<String>)
+}
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
-import java.util.*
+import java.util.Date
interface MessagePrioritizationStateService {
suspend fun getExpiryEligibleMessages(count: Int): List<MessagePrioritization>?
- suspend fun getMessageForStatesNotExpiredIn(group: String, states: List<String>, count: Int)
- : List<MessagePrioritization>?
+ suspend fun getMessageForStatesNotExpiredIn(group: String, states: List<String>, count: Int):
+ List<MessagePrioritization>?
- suspend fun getMessageForStatesExpired(group: String, states: List<String>, count: Int)
- : List<MessagePrioritization>?
+ suspend fun getMessageForStatesExpired(group: String, states: List<String>, count: Int):
+ List<MessagePrioritization>?
suspend fun getExpiredMessages(group: String, expiryDate: Date, count: Int): List<MessagePrioritization>?
- suspend fun getCorrelatedMessages(group: String, states: List<String>, types: List<String>?,
- correlationIds: String): List<MessagePrioritization>?
+ suspend fun getCorrelatedMessages(
+ group: String,
+ states: List<String>,
+ types: List<String>?,
+ correlationIds: String
+ ): List<MessagePrioritization>?
suspend fun updateMessagesState(ids: List<String>, state: String)
@Service
open class MessagePrioritizationStateServiceImpl(
- private val prioritizationMessageRepository: PrioritizationMessageRepository)
- : MessagePrioritizationStateService {
+ private val prioritizationMessageRepository: PrioritizationMessageRepository
+) :
+ MessagePrioritizationStateService {
private val log = logger(MessagePrioritizationStateServiceImpl::class)
override suspend fun getMessage(id: String): MessagePrioritization {
return prioritizationMessageRepository.findById(id).orElseGet(null)
- ?: throw BluePrintProcessorException("couldn't find message for id($id)")
+ ?: throw BluePrintProcessorException("couldn't find message for id($id)")
}
override suspend fun getMessages(ids: List<String>): List<MessagePrioritization>? {
override suspend fun getExpiryEligibleMessages(count: Int): List<MessagePrioritization>? {
return prioritizationMessageRepository
- .findByStateInAndExpiredDate(arrayListOf(MessageState.NEW.name, MessageState.WAIT.name),
- Date(), PageRequest.of(0, count))
- }
-
- override suspend fun getMessageForStatesNotExpiredIn(group: String, states: List<String>, count: Int)
- : List<MessagePrioritization>? {
- return prioritizationMessageRepository.findByGroupAndStateInAndNotExpiredDate(group,
- states, Date(), PageRequest.of(0, count))
- }
-
- override suspend fun getMessageForStatesExpired(group: String, states: List<String>, count: Int)
- : List<MessagePrioritization>? {
- return prioritizationMessageRepository.findByGroupAndStateInAndExpiredDate(group,
- states, Date(), PageRequest.of(0, count))
- }
-
- override suspend fun getExpiredMessages(group: String, expiryDate: Date, count: Int)
- : List<MessagePrioritization>? {
- return prioritizationMessageRepository.findByByGroupAndExpiredDate(group,
- expiryDate, PageRequest.of(0, count))
- }
-
- override suspend fun getCorrelatedMessages(group: String, states: List<String>, types: List<String>?,
- correlationIds: String): List<MessagePrioritization>? {
+ .findByStateInAndExpiredDate(
+ arrayListOf(MessageState.NEW.name, MessageState.WAIT.name),
+ Date(), PageRequest.of(0, count)
+ )
+ }
+
+ override suspend fun getMessageForStatesNotExpiredIn(group: String, states: List<String>, count: Int):
+ List<MessagePrioritization>? {
+ return prioritizationMessageRepository.findByGroupAndStateInAndNotExpiredDate(
+ group,
+ states, Date(), PageRequest.of(0, count)
+ )
+ }
+
+ override suspend fun getMessageForStatesExpired(group: String, states: List<String>, count: Int):
+ List<MessagePrioritization>? {
+ return prioritizationMessageRepository.findByGroupAndStateInAndExpiredDate(
+ group,
+ states, Date(), PageRequest.of(0, count)
+ )
+ }
+
+ override suspend fun getExpiredMessages(group: String, expiryDate: Date, count: Int):
+ List<MessagePrioritization>? {
+ return prioritizationMessageRepository.findByByGroupAndExpiredDate(
+ group,
+ expiryDate, PageRequest.of(0, count)
+ )
+ }
+
+ override suspend fun getCorrelatedMessages(
+ group: String,
+ states: List<String>,
+ types: List<String>?,
+ correlationIds: String
+ ): List<MessagePrioritization>? {
return if (!types.isNullOrEmpty()) {
prioritizationMessageRepository.findByGroupAndTypesAndCorrelationId(group, states, types, correlationIds)
} else {
}
override suspend fun deleteExpiredMessage(group: String, retentionDays: Int) {
- return prioritizationMessageRepository.deleteGroupAndStateIn(group,
- arrayListOf(MessageState.EXPIRED.name))
+ return prioritizationMessageRepository.deleteGroupAndStateIn(
+ group,
+ arrayListOf(MessageState.EXPIRED.name)
+ )
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.MessageState
import org.onap.ccsdk.cds.controllerblueprints.core.logger
-
open class MessageAggregateProcessor : AbstractMessagePrioritizeProcessor<String, String>() {
private val log = logger(MessageAggregateProcessor::class)
storeMessages.forEach { messagePrioritization ->
try {
/** Update the data store */
- messagePrioritizationStateService.setMessageStateANdError(messagePrioritization.id,
- MessageState.ERROR.name, error)
+ messagePrioritizationStateService.setMessageStateANdError(
+ messagePrioritization.id,
+ MessageState.ERROR.name, error
+ )
/** Publish to Error topic */
- this.processorContext.forward(messagePrioritization.id, messagePrioritization,
- To.child(MessagePrioritizationConstants.SINK_OUTPUT))
+ this.processorContext.forward(
+ messagePrioritization.id, messagePrioritization,
+ To.child(MessagePrioritizationConstants.SINK_OUTPUT)
+ )
} catch (sendException: Exception) {
- log.error("failed to update/publish error message(${messagePrioritization.id}) : " +
- "${sendException.message}", e)
+ log.error(
+ "failed to update/publish error message(${messagePrioritization.id}) : " +
+ "${sendException.message}", e
+ )
}
-
}
}
}
processorContext.forward(id, id, To.child(MessagePrioritizationConstants.PROCESSOR_OUTPUT))
}
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.MessageState
import org.onap.ccsdk.cds.controllerblueprints.core.logger
-
open class MessageOutputProcessor : AbstractMessagePrioritizeProcessor<String, String>() {
private val log = logger(MessageOutputProcessor::class)
val message = messagePrioritizationStateService.updateMessageState(value, MessageState.COMPLETED.name)
processorContext.forward(message.id, message, To.child(MessagePrioritizationConstants.SINK_OUTPUT))
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.message.kafka.AbstractBluePrintMessagePunctuator
import org.onap.ccsdk.cds.controllerblueprints.core.logger
-
-class MessagePriorityExpiryPunctuator(private val messagePrioritizationStateService: MessagePrioritizationStateService)
- : AbstractBluePrintMessagePunctuator() {
+class MessagePriorityExpiryPunctuator(private val messagePrioritizationStateService: MessagePrioritizationStateService) :
+ AbstractBluePrintMessagePunctuator() {
private val log = logger(MessagePriorityExpiryPunctuator::class)
lateinit var configuration: PrioritizationConfiguration
override suspend fun punctuateNB(timestamp: Long) {
- log.info("**** executing expiry punctuator applicationId(${processorContext.applicationId()}), " +
- "taskId(${processorContext.taskId()})")
+ log.info(
+ "**** executing expiry punctuator applicationId(${processorContext.applicationId()}), " +
+ "taskId(${processorContext.taskId()})"
+ )
val expiryConfiguration = configuration.expiryConfiguration
val fetchMessages = messagePrioritizationStateService
- .getExpiryEligibleMessages(expiryConfiguration.maxPollRecord)
+ .getExpiryEligibleMessages(expiryConfiguration.maxPollRecord)
val expiredIds = fetchMessages?.map { it.id }
if (expiredIds != null && expiredIds.isNotEmpty()) {
messagePrioritizationStateService.updateMessagesState(expiredIds, MessageState.EXPIRED.name)
fetchMessages.forEach { expired ->
- processorContext.forward(expired.id, expired,
- To.child(MessagePrioritizationConstants.SINK_EXPIRED))
+ processorContext.forward(
+ expired.id, expired,
+ To.child(MessagePrioritizationConstants.SINK_EXPIRED)
+ )
}
}
}
}
-class MessagePriorityCleanPunctuator(private val messagePrioritizationStateService: MessagePrioritizationStateService)
- : AbstractBluePrintMessagePunctuator() {
+class MessagePriorityCleanPunctuator(private val messagePrioritizationStateService: MessagePrioritizationStateService) :
+ AbstractBluePrintMessagePunctuator() {
private val log = logger(MessagePriorityCleanPunctuator::class)
lateinit var configuration: PrioritizationConfiguration
override suspend fun punctuateNB(timestamp: Long) {
- log.info("**** executing clean punctuator applicationId(${processorContext.applicationId()}), " +
- "taskId(${processorContext.taskId()})")
- //TODO
+ log.info(
+ "**** executing clean punctuator applicationId(${processorContext.applicationId()}), " +
+ "taskId(${processorContext.taskId()})"
+ )
+ // TODO
}
-}
\ No newline at end of file
+}
return object : Deserializer<MessagePrioritization> {
override fun deserialize(topic: String, data: ByteArray): MessagePrioritization {
return JacksonUtils.readValue(String(data), MessagePrioritization::class.java)
- ?: throw BluePrintProcessorException("failed to convert")
+ ?: throw BluePrintProcessorException("failed to convert")
}
override fun configure(configs: MutableMap<String, *>?, isKey: Boolean) {
}
}
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.logger
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import java.time.Duration
-import java.util.*
-
+import java.util.UUID
open class MessagePrioritizeProcessor : AbstractMessagePrioritizeProcessor<ByteArray, ByteArray>() {
override suspend fun processNB(key: ByteArray, value: ByteArray) {
log.info("***** received in prioritize processor key(${String(key)})")
val messagePrioritize = JacksonUtils.readValue(String(value), MessagePrioritization::class.java)
- ?: throw BluePrintProcessorException("failed to convert")
+ ?: throw BluePrintProcessorException("failed to convert")
try {
// Save the Message
messagePrioritizationStateService.saveMessage(messagePrioritize)
messagePrioritize.error = "failed in Prioritize message(${messagePrioritize.id}) : ${e.message}"
log.error(messagePrioritize.error)
/** Update the data store */
- messagePrioritizationStateService.setMessageStateANdError(messagePrioritize.id, MessageState.ERROR.name,
- messagePrioritize.error!!)
+ messagePrioritizationStateService.setMessageStateANdError(
+ messagePrioritize.id, MessageState.ERROR.name,
+ messagePrioritize.error!!
+ )
/** Publish to Output topic */
- this.processorContext.forward(messagePrioritize.id, messagePrioritize,
- To.child(MessagePrioritizationConstants.SINK_OUTPUT))
+ this.processorContext.forward(
+ messagePrioritize.id, messagePrioritize,
+ To.child(MessagePrioritizationConstants.SINK_OUTPUT)
+ )
}
}
}
override fun close() {
- log.info("closing prioritization processor applicationId(${processorContext.applicationId()}), " +
- "taskId(${processorContext.taskId()})")
+ log.info(
+ "closing prioritization processor applicationId(${processorContext.applicationId()}), " +
+ "taskId(${processorContext.taskId()})"
+ )
expiryCancellable.cancel()
cleanCancellable.cancel()
}
expiryPunctuator.processorContext = processorContext
expiryPunctuator.configuration = prioritizationConfiguration
val expiryConfiguration = prioritizationConfiguration.expiryConfiguration
- expiryCancellable = processorContext.schedule(Duration.ofMillis(expiryConfiguration.frequencyMilli),
- PunctuationType.WALL_CLOCK_TIME, expiryPunctuator)
+ expiryCancellable = processorContext.schedule(
+ Duration.ofMillis(expiryConfiguration.frequencyMilli),
+ PunctuationType.WALL_CLOCK_TIME, expiryPunctuator
+ )
log.info("Expiry punctuator setup complete with frequency(${expiryConfiguration.frequencyMilli})mSec")
}
cleanPunctuator.processorContext = processorContext
cleanPunctuator.configuration = prioritizationConfiguration
val cleanConfiguration = prioritizationConfiguration.cleanConfiguration
- cleanCancellable = processorContext.schedule(Duration.ofDays(cleanConfiguration.expiredRecordsHoldDays.toLong()),
- PunctuationType.WALL_CLOCK_TIME, cleanPunctuator)
- log.info("Clean punctuator setup complete with expiry " +
- "hold(${cleanConfiguration.expiredRecordsHoldDays})days")
+ cleanCancellable = processorContext.schedule(
+ Duration.ofDays(cleanConfiguration.expiredRecordsHoldDays.toLong()),
+ PunctuationType.WALL_CLOCK_TIME, cleanPunctuator
+ )
+ log.info(
+ "Clean punctuator setup complete with expiry " +
+ "hold(${cleanConfiguration.expiredRecordsHoldDays})days"
+ )
}
open suspend fun handleCorrelationAndNextStep(messagePrioritization: MessagePrioritization) {
val group = messagePrioritization.group
val correlationId = messagePrioritization.correlationId!!
val types = getGroupCorrelationTypes(messagePrioritization)
- log.info("checking correlation for message($id), group($group), types($types), " +
- "correlation id($correlationId)")
+ log.info(
+ "checking correlation for message($id), group($group), types($types), " +
+ "correlation id($correlationId)"
+ )
/** Get all previously received messages from database for group and optional types and correlation Id */
- val waitingCorrelatedStoreMessages = messagePrioritizationStateService.getCorrelatedMessages(group,
- arrayListOf(MessageState.NEW.name, MessageState.WAIT.name), types, correlationId)
+ val waitingCorrelatedStoreMessages = messagePrioritizationStateService.getCorrelatedMessages(
+ group,
+ arrayListOf(MessageState.NEW.name, MessageState.WAIT.name), types, correlationId
+ )
/** If multiple records found, then check correlation */
if (!waitingCorrelatedStoreMessages.isNullOrEmpty() && waitingCorrelatedStoreMessages.size > 1) {
/** Check all correlation satisfies */
val correlationResults = MessageCorrelationUtils
- .correlatedMessagesWithTypes(waitingCorrelatedStoreMessages, types)
+ .correlatedMessagesWithTypes(waitingCorrelatedStoreMessages, types)
if (correlationResults.correlated) {
/** Correlation satisfied */
val correlatedIds = waitingCorrelatedStoreMessages.map { it.id }.joinToString(",")
/** Send only correlated ids to next processor */
- this.processorContext.forward(UUID.randomUUID().toString(), correlatedIds,
- To.child(MessagePrioritizationConstants.PROCESSOR_AGGREGATE))
+ this.processorContext.forward(
+ UUID.randomUUID().toString(), correlatedIds,
+ To.child(MessagePrioritizationConstants.PROCESSOR_AGGREGATE)
+ )
} else {
/** Correlation not satisfied */
log.trace("correlation not matched : ${correlationResults.message}")
} else {
// No Correlation check needed, simply forward to next processor.
messagePrioritizationStateService.setMessageState(messagePrioritization.id, MessageState.PRIORITIZED.name)
- this.processorContext.forward(messagePrioritization.id, messagePrioritization.id,
- To.child(MessagePrioritizationConstants.PROCESSOR_AGGREGATE))
+ this.processorContext.forward(
+ messagePrioritization.id, messagePrioritization.id,
+ To.child(MessagePrioritizationConstants.PROCESSOR_AGGREGATE)
+ )
}
}
open fun getGroupCorrelationTypes(messagePrioritization: MessagePrioritization): List<String>? {
return null
}
-}
\ No newline at end of file
+}
}
/** Assumption is message is of same group and checking for required types **/
- fun correlatedMessagesWithTypes(collectedMessages: List<MessagePrioritization>, types: List<String>?)
- : CorrelationCheckResponse {
+ fun correlatedMessagesWithTypes(collectedMessages: List<MessagePrioritization>, types: List<String>?):
+ CorrelationCheckResponse {
return if (!types.isNullOrEmpty() && collectedMessages.size > 1) {
val copyTypes = types.toTypedArray().copyOf().toMutableList()
val filteredMessage = collectedMessages.filter {
- !it.correlationId.isNullOrBlank()
- && types.contains(it.type)
+ !it.correlationId.isNullOrBlank() &&
+ types.contains(it.type)
}
var correlatedKeys: MutableSet<String> = mutableSetOf()
if (filteredMessage.isNotEmpty()) {
return correlatedMessages(collectedMessages)
}
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.PrioritizationConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.ShutDownConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.MessagePrioritization
-import java.util.*
+import java.util.Calendar
+import java.util.Date
+import java.util.UUID
object MessagePrioritizationSample {
fun sampleMessages(groupName: String, messageState: String, count: Int): List<MessagePrioritization> {
val messages: MutableList<MessagePrioritization> = arrayListOf()
repeat(count) {
- val backPressureMessage = createMessage(groupName, messageState,
- "sample-type", null)
+ val backPressureMessage = createMessage(
+ groupName, messageState,
+ "sample-type", null
+ )
messages.add(backPressureMessage)
}
return messages
fun sampleMessageWithSameCorrelation(groupName: String, messageState: String, count: Int): List<MessagePrioritization> {
val messages: MutableList<MessagePrioritization> = arrayListOf()
repeat(count) {
- val backPressureMessage = createMessage(groupName, messageState, "sample-type",
- "key1=value1,key2=value2")
+ val backPressureMessage = createMessage(
+ groupName, messageState, "sample-type",
+ "key1=value1,key2=value2"
+ )
messages.add(backPressureMessage)
}
return messages
}
- fun sampleMessageWithDifferentTypeSameCorrelation(groupName: String, messageState: String,
- count: Int): List<MessagePrioritization> {
+ fun sampleMessageWithDifferentTypeSameCorrelation(
+ groupName: String,
+ messageState: String,
+ count: Int
+ ): List<MessagePrioritization> {
val messages: MutableList<MessagePrioritization> = arrayListOf()
repeat(count) {
- val backPressureMessage = createMessage(groupName, messageState, "type-$it",
- "key1=value1,key2=value2")
+ val backPressureMessage = createMessage(
+ groupName, messageState, "type-$it",
+ "key1=value1,key2=value2"
+ )
messages.add(backPressureMessage)
}
return messages
}
- fun createMessage(groupName: String, messageState: String, messageType: String,
- messageCorrelationId: String?): MessagePrioritization {
+ fun createMessage(
+ groupName: String,
+ messageState: String,
+ messageType: String,
+ messageCorrelationId: String?
+ ): MessagePrioritization {
return MessagePrioritization().apply {
id = UUID.randomUUID().toString()
expiryDate = currentDatePlusDays(3)
}
}
-}
\ No newline at end of file
+}
object MessageProcessorUtils {
- fun <K, V> bluePrintProcessorSupplier(name: String, prioritizationConfiguration: PrioritizationConfiguration)
- : ProcessorSupplier<K, V> {
+ fun <K, V> bluePrintProcessorSupplier(name: String, prioritizationConfiguration: PrioritizationConfiguration):
+ ProcessorSupplier<K, V> {
return ProcessorSupplier<K, V> {
// Dynamically resolve the Prioritization Processor
val processorInstance = BluePrintDependencyService.instance<AbstractMessagePrioritizeProcessor<K, V>>(name)
processorInstance
}
}
-
-}
\ No newline at end of file
+}
import kotlin.test.Test
import kotlin.test.assertNotNull
-
@RunWith(SpringRunner::class)
@DataJpaTest
@DirtiesContext
-@ContextConfiguration(classes = [BluePrintMessageLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class,
- MessagePrioritizationConfiguration::class, TestDatabaseConfiguration::class])
-@TestPropertySource(properties =
-[
- "spring.jpa.show-sql=true",
- "spring.jpa.properties.hibernate.show_sql=true",
- "spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl",
-
- "blueprintsprocessor.messageconsumer.prioritize-input.type=kafka-streams-basic-auth",
- "blueprintsprocessor.messageconsumer.prioritize-input.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageconsumer.prioritize-input.applicationId=test-prioritize-application",
- "blueprintsprocessor.messageconsumer.prioritize-input.topic=prioritize-input-topic",
-
- // To send initial test message
- "blueprintsprocessor.messageproducer.prioritize-input.type=kafka-basic-auth",
- "blueprintsprocessor.messageproducer.prioritize-input.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageproducer.prioritize-input.topic=prioritize-input-topic"
-])
+@ContextConfiguration(
+ classes = [BluePrintMessageLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class,
+ MessagePrioritizationConfiguration::class, TestDatabaseConfiguration::class]
+)
+@TestPropertySource(
+ properties =
+ [
+ "spring.jpa.show-sql=true",
+ "spring.jpa.properties.hibernate.show_sql=true",
+ "spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl",
+
+ "blueprintsprocessor.messageconsumer.prioritize-input.type=kafka-streams-basic-auth",
+ "blueprintsprocessor.messageconsumer.prioritize-input.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageconsumer.prioritize-input.applicationId=test-prioritize-application",
+ "blueprintsprocessor.messageconsumer.prioritize-input.topic=prioritize-input-topic",
+
+ // To send initial test message
+ "blueprintsprocessor.messageproducer.prioritize-input.type=kafka-basic-auth",
+ "blueprintsprocessor.messageproducer.prioritize-input.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageproducer.prioritize-input.topic=prioritize-input-topic"
+ ]
+)
open class MessagePrioritizationConsumerTest {
@Autowired
assertNotNull(prioritizationMessageRepository, "failed to get prioritizationMessageRepository")
val messagePrioritizationService: MessagePrioritizationStateService = BluePrintDependencyService
- .instance(MessagePrioritizationStateService::class)
+ .instance(MessagePrioritizationStateService::class)
assertNotNull(messagePrioritizationService, "failed to get messagePrioritizationService")
MessagePrioritizationSample.sampleMessages(MessageState.NEW.name, 1).forEach {
val configuration = MessagePrioritizationSample.samplePrioritizationConfiguration()
val streamingConsumerService = bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService(configuration.inputTopicSelector)
+ .blueprintMessageConsumerService(configuration.inputTopicSelector)
assertNotNull(streamingConsumerService, "failed to get blueprintMessageConsumerService")
val spyStreamingConsumerService = spyk(streamingConsumerService)
val messagePrioritizationConsumer = MessagePrioritizationConsumer(bluePrintMessageLibPropertyService)
val spyMessagePrioritizationConsumer = spyk(messagePrioritizationConsumer)
-
// Test Topology
val kafkaStreamConsumerFunction = spyMessagePrioritizationConsumer.kafkaStreamConsumerFunction(configuration)
val messageConsumerProperties = bluePrintMessageLibPropertyService
- .messageConsumerProperties("blueprintsprocessor.messageconsumer.prioritize-input")
+ .messageConsumerProperties("blueprintsprocessor.messageconsumer.prioritize-input")
val topology = kafkaStreamConsumerFunction.createTopology(messageConsumerProperties, null)
assertNotNull(topology, "failed to get create topology")
}
/** Integration Kafka Testing, Enable and use this test case only for local desktop testing with real kafka broker */
- //@Test
+ // @Test
fun testMessagePrioritizationConsumer() {
runBlocking {
val messagePrioritizationConsumer = MessagePrioritizationConsumer(bluePrintMessageLibPropertyService)
/** Send sample message with every 1 sec */
val blueprintMessageProducerService = bluePrintMessageLibPropertyService
- .blueprintMessageProducerService("prioritize-input") as KafkaBasicAuthMessageProducerService
+ .blueprintMessageProducerService("prioritize-input") as KafkaBasicAuthMessageProducerService
launch {
- MessagePrioritizationSample.sampleMessages(MessageState.NEW.name, 2).forEach {
+ MessagePrioritizationSample.sampleMessages(MessageState.NEW.name, 2).forEach {
delay(100)
val headers: MutableMap<String, String> = hashMapOf()
headers["id"] = it.id
- blueprintMessageProducerService.sendMessageNB(message = it.asJsonString(false),
- headers = headers)
+ blueprintMessageProducerService.sendMessageNB(
+ message = it.asJsonString(false),
+ headers = headers
+ )
}
MessagePrioritizationSample
- .sampleMessageWithSameCorrelation("same-group", MessageState.NEW.name, 2)
- .forEach {
- delay(100)
- val headers: MutableMap<String, String> = hashMapOf()
- headers["id"] = it.id
- blueprintMessageProducerService.sendMessageNB(message = it.asJsonString(false),
- headers = headers)
- }
+ .sampleMessageWithSameCorrelation("same-group", MessageState.NEW.name, 2)
+ .forEach {
+ delay(100)
+ val headers: MutableMap<String, String> = hashMapOf()
+ headers["id"] = it.id
+ blueprintMessageProducerService.sendMessageNB(
+ message = it.asJsonString(false),
+ headers = headers
+ )
+ }
MessagePrioritizationSample
- .sampleMessageWithDifferentTypeSameCorrelation("group-typed", MessageState.NEW.name, 3)
- .forEach {
- delay(2000)
- val headers: MutableMap<String, String> = hashMapOf()
- headers["id"] = it.id
- blueprintMessageProducerService.sendMessageNB(message = it.asJsonString(false),
- headers = headers)
- }
+ .sampleMessageWithDifferentTypeSameCorrelation("group-typed", MessageState.NEW.name, 3)
+ .forEach {
+ delay(2000)
+ val headers: MutableMap<String, String> = hashMapOf()
+ headers["id"] = it.id
+ blueprintMessageProducerService.sendMessageNB(
+ message = it.asJsonString(false),
+ headers = headers
+ )
+ }
}
delay(10000)
messagePrioritizationConsumer.shutDown()
}
}
-}
\ No newline at end of file
+}
@Service(MessagePrioritizationConstants.PROCESSOR_PRIORITIZE)
open class TestMessagePrioritizeProcessor : MessagePrioritizeProcessor() {
+
override fun getGroupCorrelationTypes(messagePrioritization: MessagePrioritization): List<String>? {
return when (messagePrioritization.group) {
"group-typed" -> arrayListOf("type-0", "type-1", "type-2")
open class DefaultMessageAggregateProcessor() : MessageAggregateProcessor()
@Service(MessagePrioritizationConstants.PROCESSOR_OUTPUT)
-open class DefaultMessageOutputProcessor : MessageOutputProcessor()
\ No newline at end of file
+open class DefaultMessageOutputProcessor : MessageOutputProcessor()
@Test
fun testCorrelationKeysReordered() {
- val message1 = MessagePrioritizationSample.createMessage("sample-group", MessageState.NEW.name,
- "type-0", "key1=value1,key2=value2")
- val message2 = MessagePrioritizationSample.createMessage("sample-group", MessageState.NEW.name,
- "type-0", "key2=value2,key1=value1")
+ val message1 = MessagePrioritizationSample.createMessage(
+ "sample-group", MessageState.NEW.name,
+ "type-0", "key1=value1,key2=value2"
+ )
+ val message2 = MessagePrioritizationSample.createMessage(
+ "sample-group", MessageState.NEW.name,
+ "type-0", "key2=value2,key1=value1"
+ )
val multipleMessages: MutableList<MessagePrioritization> = arrayListOf()
multipleMessages.add(message1)
/** With Types **/
/* Assumption is Same group with different types */
val differentTypesWithSameCorrelationMessages = MessagePrioritizationSample
- .sampleMessageWithDifferentTypeSameCorrelation("sample-group", MessageState.NEW.name, 3)
+ .sampleMessageWithDifferentTypeSameCorrelation("sample-group", MessageState.NEW.name, 3)
val differentTypesWithSameCorrelationMessagesResponse = MessageCorrelationUtils.correlatedMessagesWithTypes(
- differentTypesWithSameCorrelationMessages,
- arrayListOf("type-0", "type-1", "type-2"))
- assertTrue(differentTypesWithSameCorrelationMessagesResponse.correlated,
- "failed to correlate differentTypesWithSameCorrelationMessagesResponse")
+ differentTypesWithSameCorrelationMessages,
+ arrayListOf("type-0", "type-1", "type-2")
+ )
+ assertTrue(
+ differentTypesWithSameCorrelationMessagesResponse.correlated,
+ "failed to correlate differentTypesWithSameCorrelationMessagesResponse"
+ )
/* Assumption is Same group with different types and one missing expected types,
In this case type-3 message is missing */
val differentTypesWithSameCorrelationMessagesResWithMissingType = MessageCorrelationUtils.correlatedMessagesWithTypes(
- differentTypesWithSameCorrelationMessages,
- arrayListOf("type-0", "type-1", "type-2", "type-3"))
- assertTrue(!differentTypesWithSameCorrelationMessagesResWithMissingType.correlated,
- "failed to correlate differentTypesWithSameCorrelationMessagesResWithMissingType")
+ differentTypesWithSameCorrelationMessages,
+ arrayListOf("type-0", "type-1", "type-2", "type-3")
+ )
+ assertTrue(
+ !differentTypesWithSameCorrelationMessagesResWithMissingType.correlated,
+ "failed to correlate differentTypesWithSameCorrelationMessagesResWithMissingType"
+ )
}
@Test
/** With ignoring Types */
/** Assumption is only one message received */
val withSameCorrelationOneMessages = MessagePrioritizationSample
- .sampleMessageWithSameCorrelation("sample-group", MessageState.NEW.name, 1)
+ .sampleMessageWithSameCorrelation("sample-group", MessageState.NEW.name, 1)
val withSameCorrelationOneMessagesResp = MessageCorrelationUtils.correlatedMessagesWithTypes(
- withSameCorrelationOneMessages, null)
- assertTrue(!withSameCorrelationOneMessagesResp.correlated,
- "failed to correlate withSameCorrelationMessagesResp")
+ withSameCorrelationOneMessages, null
+ )
+ assertTrue(
+ !withSameCorrelationOneMessagesResp.correlated,
+ "failed to correlate withSameCorrelationMessagesResp"
+ )
/** Assumption is two message received for same group with same correlation */
val withSameCorrelationMessages = MessagePrioritizationSample
- .sampleMessageWithSameCorrelation("sample-group", MessageState.NEW.name, 2)
+ .sampleMessageWithSameCorrelation("sample-group", MessageState.NEW.name, 2)
val withSameCorrelationMessagesResp = MessageCorrelationUtils.correlatedMessagesWithTypes(
- withSameCorrelationMessages, null)
- assertTrue(withSameCorrelationMessagesResp.correlated,
- "failed to correlate withSameCorrelationMessagesResp")
+ withSameCorrelationMessages, null
+ )
+ assertTrue(
+ withSameCorrelationMessagesResp.correlated,
+ "failed to correlate withSameCorrelationMessagesResp"
+ )
}
@Test
fun differentTypesWithDifferentCorrelationMessage() {
/** Assumption is two message received for same group with different expected types and different correlation */
- val message1 = MessagePrioritizationSample.createMessage("sample-group", MessageState.NEW.name,
- "type-0", "key1=value1,key2=value2")
- val message2 = MessagePrioritizationSample.createMessage("sample-group", MessageState.NEW.name,
- "type-1", "key1=value1,key2=value3")
+ val message1 = MessagePrioritizationSample.createMessage(
+ "sample-group", MessageState.NEW.name,
+ "type-0", "key1=value1,key2=value2"
+ )
+ val message2 = MessagePrioritizationSample.createMessage(
+ "sample-group", MessageState.NEW.name,
+ "type-1", "key1=value1,key2=value3"
+ )
val differentTypesWithDifferentCorrelationMessage: MutableList<MessagePrioritization> = arrayListOf()
differentTypesWithDifferentCorrelationMessage.add(message1)
differentTypesWithDifferentCorrelationMessage.add(message2)
val differentTypesWithDifferentCorrelationMessageResp = MessageCorrelationUtils.correlatedMessagesWithTypes(
- differentTypesWithDifferentCorrelationMessage,
- arrayListOf("type-0", "type-1"))
- assertTrue(!differentTypesWithDifferentCorrelationMessageResp.correlated,
- "failed to correlate differentTypesWithDifferentCorrelationMessageResp")
+ differentTypesWithDifferentCorrelationMessage,
+ arrayListOf("type-0", "type-1")
+ )
+ assertTrue(
+ !differentTypesWithDifferentCorrelationMessageResp.correlated,
+ "failed to correlate differentTypesWithDifferentCorrelationMessageResp"
+ )
}
-}
\ No newline at end of file
+}
@Component("component-netconf-executor")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ComponentNetconfExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService)
- : AbstractComponentFunction() {
+open class ComponentNetconfExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService) :
+ AbstractComponentFunction() {
companion object {
const val SCRIPT_TYPE = "script-type"
}
scriptComponent = componentFunctionScriptingService
- .scriptInstance<AbstractScriptComponentFunction>(this, scriptType,
- scriptClassReference, scriptDependencies)
-
+ .scriptInstance<AbstractScriptComponentFunction>(
+ this, scriptType,
+ scriptClassReference, scriptDependencies
+ )
checkNotNull(scriptComponent) { "failed to get netconf script component" }
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
bluePrintRuntimeService.getBluePrintError()
- .addError("Failed in ComponentNetconfExecutor : ${runtimeException.message}")
-
+ .addError("Failed in ComponentNetconfExecutor : ${runtimeException.message}")
}
-}
\ No newline at end of file
+}
import org.springframework.stereotype.Service
@Service("json-parser-service")
-class JsonParserService {
-
-}
\ No newline at end of file
+class JsonParserService
@Deprecated("Methods defined as extension function of AbstractComponentFunction")
abstract class NetconfComponentFunction : AbstractScriptComponentFunction() {
- @Deprecated(" Use resourceResolutionService method directly",
- replaceWith = ReplaceWith("resourceResolutionService()",
- "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.resourceResolutionService"))
+ @Deprecated(
+ " Use resourceResolutionService method directly",
+ replaceWith = ReplaceWith(
+ "resourceResolutionService()",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.resourceResolutionService"
+ )
+ )
open fun resourceResolutionService(): ResourceResolutionService =
- functionDependencyInstanceAsType(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
+ functionDependencyInstanceAsType(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
// Called from python script
- @Deprecated(" Use netconfDeviceInfo method directly",
- replaceWith = ReplaceWith("netconfDeviceInfo(requirementName)",
- "org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.netconfDeviceInfo"))
+ @Deprecated(
+ " Use netconfDeviceInfo method directly",
+ replaceWith = ReplaceWith(
+ "netconfDeviceInfo(requirementName)",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.netconfDeviceInfo"
+ )
+ )
fun initializeNetconfConnection(requirementName: String): NetconfDevice {
val deviceInfo = netconfDeviceInfo(requirementName)
return NetconfDevice(deviceInfo)
}
- @Deprecated(" Use artifactContent method directly",
- replaceWith = ReplaceWith("artifactContent(artifactName)",
- "org.onap.ccsdk.cds.blueprintsprocessor.services.execution.artifactContent"))
+ @Deprecated(
+ " Use artifactContent method directly",
+ replaceWith = ReplaceWith(
+ "artifactContent(artifactName)",
+ "org.onap.ccsdk.cds.blueprintsprocessor.services.execution.artifactContent"
+ )
+ )
fun generateMessage(artifactName: String): String {
return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName)
}
- @Deprecated(" Use storedContentFromResolvedArtifact method directly",
- replaceWith = ReplaceWith("storedContentFromResolvedArtifact(resolutionKey, artifactName)",
- "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.storedContentFromResolvedArtifact"))
+ @Deprecated(
+ " Use storedContentFromResolvedArtifact method directly",
+ replaceWith = ReplaceWith(
+ "storedContentFromResolvedArtifact(resolutionKey, artifactName)",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.storedContentFromResolvedArtifact"
+ )
+ )
fun resolveFromDatabase(resolutionKey: String, artifactName: String): String = runBlocking {
resourceResolutionService().resolveFromDatabase(bluePrintRuntimeService, artifactName, resolutionKey)
}
- @Deprecated(" Use contentFromResolvedArtifact method directly",
- replaceWith = ReplaceWith("resolveAndGenerateMessage(artifactPrefix)",
- "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.resolveAndGenerateMessage"))
+ @Deprecated(
+ " Use contentFromResolvedArtifact method directly",
+ replaceWith = ReplaceWith(
+ "resolveAndGenerateMessage(artifactPrefix)",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.resolveAndGenerateMessage"
+ )
+ )
fun resolveAndGenerateMessage(artifactPrefix: String): String = runBlocking {
- resourceResolutionService().resolveResources(bluePrintRuntimeService, nodeTemplateName,
- artifactPrefix, mapOf())
+ resourceResolutionService().resolveResources(
+ bluePrintRuntimeService, nodeTemplateName,
+ artifactPrefix, mapOf()
+ )
}
-}
\ No newline at end of file
+}
netconfSession = NetconfSessionImpl(deviceInfo, netconfRpcService)
netconfRpcService.setNetconfSession(netconfSession)
}
-}
\ No newline at end of file
+}
@ComponentScan
@EnableConfigurationProperties
@ConditionalOnProperty(name = ["blueprintsprocessor.netconfExecutor.enabled"], havingValue = "true")
-open class NetconfExecutorConfiguration
\ No newline at end of file
+open class NetconfExecutorConfiguration
* Register the Netconf module exposed dependency
*/
fun BluePrintDependencyService.netconfClientService(): ResourceResolutionService =
- instance(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
-
+ instance(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
fun AbstractComponentFunction.netconfDevice(requirementName: String): NetconfDevice {
val deviceInfo = netconfDeviceInfo(requirementName)
val requirement = blueprintContext.nodeTemplateRequirement(nodeTemplateName, requirementName)
- val capabilityProperties = bluePrintRuntimeService.resolveNodeTemplateCapabilityProperties(requirement
- .node!!, requirement.capability!!)
+ val capabilityProperties = bluePrintRuntimeService.resolveNodeTemplateCapabilityProperties(
+ requirement
+ .node!!, requirement.capability!!
+ )
return netconfDeviceInfo(capabilityProperties)
}
/**
* Blocking Methods called from Jython Scripts
- */
\ No newline at end of file
+ */
override fun toString(): String {
return "$ipAddress:$port"
}
- //TODO: should this be a data class instead? Is anything using the JSON serdes?
+
+ // TODO: should this be a data class instead? Is anything using the JSON serdes?
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
constructor(cause: Throwable) : super(cause)
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus
-data class DeviceResponse(var status: String? = null,
- var errorMessage: String? = null,
- var responseMessage: String? = null,
- var requestMessage: String? = null) {
+data class DeviceResponse(
+ var status: String? = null,
+ var errorMessage: String? = null,
+ var responseMessage: String? = null,
+ var requestMessage: String? = null
+) {
fun isSuccess(): Boolean {
return this.status == RpcStatus.SUCCESS && this.errorMessage.isNullOrEmpty()
}
}
-
/**
* Creates an event of a given type and for the specified subject and the current time.
*
* @param messageId id of the message related to the event
* @param deviceInfo device of event
*/
-class NetconfReceivedEvent(val type: Type,
- val messagePayload: String = "",
- val messageId: String = "",
- val deviceInfo: DeviceInfo) {
+class NetconfReceivedEvent(
+ val type: Type,
+ val messagePayload: String = "",
+ val messageId: String = "",
+ val deviceInfo: DeviceInfo
+) {
enum class Type {
DEVICE_REPLY,
DEVICE_ERROR,
SESSION_CLOSED
}
-}
\ No newline at end of file
+}
* @param editDefaultOperation, default set to none. Valid values: merge, replace, create, delete, none
* @return Device response
*/
- fun editConfig(messageContent: String, configTarget: String = NetconfDatastore.CANDIDATE.datastore,
- editDefaultOperation: String = ModifyAction.NONE.action): DeviceResponse
+ fun editConfig(
+ messageContent: String,
+ configTarget: String = NetconfDatastore.CANDIDATE.datastore,
+ editDefaultOperation: String = ModifyAction.NONE.action
+ ): DeviceResponse
/**
* Invoke custom RPC as provided as input.
* If unspecified, the confirm timeout defaults to 600 seconds.
* @return Device response
*/
- fun commit(confirmed: Boolean = false, confirmTimeout: Int = 60, persist: String = "",
- persistId: String = ""): DeviceResponse
+ fun commit(
+ confirmed: Boolean = false,
+ confirmTimeout: Int = 60,
+ persist: String = "",
+ persistId: String = ""
+ ): DeviceResponse
/**
* Cancels an ongoing confirmed commit. If the <persist-id> parameter is not given,
* @return Device response
*/
fun get(filter: String): DeviceResponse
-}
\ No newline at end of file
+}
*/
fun connect()
-
/**
* Disconnect netconf session
*/
* @return Network capabilities as strings in a Set.
*/
fun getDeviceCapabilitiesSet(): Set<String>
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcMessageUtils
import org.slf4j.LoggerFactory
-import java.io.*
-import java.nio.charset.*
-import java.util.concurrent.*
+import java.io.BufferedReader
+import java.io.IOException
+import java.io.InputStream
+import java.io.InputStreamReader
+import java.io.OutputStream
+import java.io.OutputStreamWriter
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.CancellationException
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.ExecutionException
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.TimeoutException
-class NetconfDeviceCommunicator(private var inputStream: InputStream,
- private var out: OutputStream,
- private val deviceInfo: DeviceInfo,
- private val sessionListener: NetconfSessionListener,
- private var replies: MutableMap<String, CompletableFuture<String>>) : Thread() {
+class NetconfDeviceCommunicator(
+ private var inputStream: InputStream,
+ private var out: OutputStream,
+ private val deviceInfo: DeviceInfo,
+ private val sessionListener: NetconfSessionListener,
+ private var replies: MutableMap<String, CompletableFuture<String>>
+) : Thread() {
private val log = LoggerFactory.getLogger(NetconfDeviceCommunicator::class.java)
private var state = NetconfMessageState.NO_MATCHING_PATTERN
if (deviceReply == RpcMessageUtils.END_PATTERN) {
socketClosed = true
bufferReader.close()
- sessionListener.accept(NetconfReceivedEvent(
- NetconfReceivedEvent.Type.DEVICE_UNREGISTERED,
- deviceInfo = deviceInfo))
+ sessionListener.accept(
+ NetconfReceivedEvent(
+ NetconfReceivedEvent.Type.DEVICE_UNREGISTERED,
+ deviceInfo = deviceInfo
+ )
+ )
} else {
deviceReply = deviceReply.replace(RpcMessageUtils.END_PATTERN, "")
receivedMessage(deviceReply)
if (!NetconfMessageUtils.validateChunkedFraming(deviceReply)) {
log.debug("$deviceInfo: Received badly framed message $deviceReply")
socketClosed = true
- sessionListener.accept(NetconfReceivedEvent(
- NetconfReceivedEvent.Type.DEVICE_ERROR,
- deviceInfo = deviceInfo))
+ sessionListener.accept(
+ NetconfReceivedEvent(
+ NetconfReceivedEvent.Type.DEVICE_ERROR,
+ deviceInfo = deviceInfo
+ )
+ )
} else {
deviceReply = deviceReply.replace(RpcMessageUtils.MSGLEN_REGEX_PATTERN.toRegex(), "")
deviceReply = deviceReply.replace(NetconfMessageUtils.CHUNKED_END_REGEX_PATTERN.toRegex(), "")
}
}
}
-
} catch (e: IOException) {
log.warn("$deviceInfo: Fail while reading from channel", e)
- sessionListener.accept(NetconfReceivedEvent(
- NetconfReceivedEvent.Type.DEVICE_ERROR,
- deviceInfo = deviceInfo))
+ sessionListener.accept(
+ NetconfReceivedEvent(
+ NetconfReceivedEvent.Type.DEVICE_ERROR,
+ deviceInfo = deviceInfo
+ )
+ )
}
-
}
/**
* State machine for the Netconf message parser
*/
internal enum class NetconfMessageState {
+
NO_MATCHING_PATTERN {
override fun evaluateChar(c: Char): NetconfMessageState {
return when (c) {
log.error("$deviceInfo: Failed to send message : \n $request", e)
future.completeExceptionally(e)
}
-
}
return future
}
private fun receivedMessage(deviceReply: String) {
- if (deviceReply.contains(RpcMessageUtils.RPC_REPLY) || deviceReply.contains(RpcMessageUtils.RPC_ERROR)
- || deviceReply.contains(RpcMessageUtils.HELLO)) {
- log.info("$deviceInfo: Received message with messageId: {} \n $deviceReply",
- NetconfMessageUtils.getMsgId(deviceReply))
-
+ if (deviceReply.contains(RpcMessageUtils.RPC_REPLY) || deviceReply.contains(RpcMessageUtils.RPC_ERROR) ||
+ deviceReply.contains(RpcMessageUtils.HELLO)
+ ) {
+ log.info(
+ "$deviceInfo: Received message with messageId: {} \n $deviceReply",
+ NetconfMessageUtils.getMsgId(deviceReply)
+ )
} else {
log.error("$deviceInfo: Invalid message received: \n $deviceReply")
}
- sessionListener.accept(NetconfReceivedEvent(
- NetconfReceivedEvent.Type.DEVICE_REPLY,
- deviceReply,
- NetconfMessageUtils.getMsgId(deviceReply),
- deviceInfo))
+ sessionListener.accept(
+ NetconfReceivedEvent(
+ NetconfReceivedEvent.Type.DEVICE_REPLY,
+ deviceReply,
+ NetconfMessageUtils.getMsgId(deviceReply),
+ deviceInfo
+ )
+ )
}
/**
* @throws TimeoutException if the wait timed outStream
*/
internal fun getFutureFromSendMessage(
- fut: CompletableFuture<String>, timeout: Long, timeUnit: TimeUnit): String {
+ fut: CompletableFuture<String>,
+ timeout: Long,
+ timeUnit: TimeUnit
+ ): String {
return fut.get(timeout, timeUnit)
}
}
package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core
-import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.*
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceResponse
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfException
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfRpcService
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfSession
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus
import org.slf4j.LoggerFactory
override fun invokeRpc(rpc: String): DeviceResponse {
var output = DeviceResponse()
- //Attempt to extract the message-id field from the <rpc call
+ // Attempt to extract the message-id field from the <rpc call
val updatedMessageId = messageIdInteger.getAndIncrement().toString()
val origMessageId = NetconfMessageUtils.getMsgId(rpc)
log.info("$deviceInfo: invokeRpc: updating rpc original message-id:($origMessageId) to messageId($updatedMessageId)")
return output
}
- override fun editConfig(messageContent: String, configTarget: String,
- editDefaultOperation: String): DeviceResponse {
+ override fun editConfig(
+ messageContent: String,
+ configTarget: String,
+ editDefaultOperation: String
+ ): DeviceResponse {
var response = DeviceResponse()
val messageId = messageIdInteger.getAndIncrement().toString()
log.info("$deviceInfo: editConfig: messageId($messageId)")
response.requestMessage = request
val rpcResponse = netconfSession.asyncRpc(request, messageId).get(responseTimeout.toLong(), TimeUnit.SECONDS)
- //TODO catch TimeoutException and ExecutionException
+ // TODO catch TimeoutException and ExecutionException
if (!NetconfMessageUtils.checkReply(rpcResponse)) {
log.error("RPC response didn't pass validation... $rpcResponse")
throw NetconfException(rpcResponse)
import org.apache.sshd.client.channel.ClientChannel
import org.apache.sshd.client.session.ClientSession
import org.apache.sshd.common.FactoryManager
-import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.*
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfException
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfRpcService
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfSession
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfSessionListener
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcMessageUtils
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus
import org.slf4j.LoggerFactory
import java.io.IOException
-import java.util.*
-import java.util.concurrent.*
+import java.util.Collections
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.ExecutionException
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.TimeoutException
class NetconfSessionImpl(private val deviceInfo: DeviceInfo, private val rpcService: NetconfRpcService) :
NetconfSession {
override fun connect() {
try {
- log.info("$deviceInfo: Connecting to Netconf Device with timeouts C:${deviceInfo.connectTimeout}, " +
- "R:${deviceInfo.replyTimeout}, I:${deviceInfo.idleTimeout}")
+ log.info(
+ "$deviceInfo: Connecting to Netconf Device with timeouts C:${deviceInfo.connectTimeout}, " +
+ "R:${deviceInfo.replyTimeout}, I:${deviceInfo.idleTimeout}"
+ )
startConnection()
log.info("$deviceInfo: Connected to Netconf Device")
} catch (e: NetconfException) {
override fun disconnect() {
var retryNum = 3
- while(rpcService.closeSession(false).status
- .equals(RpcStatus.FAILURE, true) &&retryNum>0) {
+ while (rpcService.closeSession(false).status
+ .equals(RpcStatus.FAILURE, true) && retryNum > 0
+ ) {
log.error("disconnect: graceful disconnect failed, retrying $retryNum times...")
- retryNum--;
+ retryNum--
}
- //if we can't close the session, try to force terminate.
- if(retryNum == 0) {
+ // if we can't close the session, try to force terminate.
+ if (retryNum == 0) {
log.error("disconnect: trying to force-terminate the session.")
rpcService.closeSession(true)
}
checkAndReestablish()
try {
- return streamHandler.getFutureFromSendMessage(streamHandler.sendMessage(formattedRequest, messageId),
- replyTimeout.toLong(), TimeUnit.SECONDS)
+ return streamHandler.getFutureFromSendMessage(
+ streamHandler.sendMessage(formattedRequest, messageId),
+ replyTimeout.toLong(), TimeUnit.SECONDS
+ )
} catch (e: InterruptedException) {
throw NetconfException("$deviceInfo: Interrupted while waiting for reply for request: $formattedRequest", e)
} catch (e: TimeoutException) {
- throw NetconfException("$deviceInfo: Timed out while waiting for reply for request $formattedRequest after $replyTimeout sec.",
- e)
+ throw NetconfException(
+ "$deviceInfo: Timed out while waiting for reply for request $formattedRequest after $replyTimeout sec.",
+ e
+ )
} catch (e: ExecutionException) {
log.warn("$deviceInfo: Closing session($sessionId) due to unexpected Error", e)
try {
} catch (e: Exception) {
throw NetconfException("$deviceInfo: Failed to establish SSH session", e)
}
-
}
- //Needed to unit test connect method interacting with client.start in startClient() below
+ // Needed to unit test connect method interacting with client.start in startClient() below
private fun setupNewSSHClient() {
client = SshClient.setUpDefaultClient()
}
private fun authSession() {
session.addPasswordIdentity(deviceInfo.password)
session.auth().verify(connectionTimeout, TimeUnit.SECONDS)
- val event = session.waitFor(ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
- ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED), 0)
+ val event = session.waitFor(
+ ImmutableSet.of(
+ ClientSession.ClientSessionEvent.WAIT_AUTH,
+ ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED
+ ), 0
+ )
if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
throw NetconfException("$deviceInfo: Failed to authenticate session.")
}
private fun setupHandler() {
val sessionListener: NetconfSessionListener = NetconfSessionListenerImpl(this)
- streamHandler = NetconfDeviceCommunicator(channel.invertedOut, channel.invertedIn, deviceInfo,
- sessionListener, replies)
+ streamHandler = NetconfDeviceCommunicator(
+ channel.invertedOut, channel.invertedIn, deviceInfo,
+ sessionListener, replies
+ )
exchangeHelloMessage()
}
}
val capabilityMatcher = NetconfMessageUtils.CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse)
- while (capabilityMatcher.find()) { //TODO: refactor to add unit test easily for device capability accumulation.
+ while (capabilityMatcher.find()) { // TODO: refactor to add unit test easily for device capability accumulation.
deviceCapabilities.add(capabilityMatcher.group(1))
}
}
* internal function for accessing errorReplies for testing.
*/
internal fun getErrorReplies() = errorReplies
+
internal fun clearErrorReplies() = errorReplies.clear()
internal fun clearReplies() = replies.clear()
- internal fun setClient(client: SshClient) { this.client = client }
- internal fun setSession(session: ClientSession) { this.session = session }
- internal fun setChannel(channel: ClientChannel) { this.channel = channel }
+ internal fun setClient(client: SshClient) {
+ this.client = client
+ }
+
+ internal fun setSession(session: ClientSession) {
+ this.session = session
+ }
+
+ internal fun setChannel(channel: ClientChannel) {
+ this.channel = channel
+ }
}
*/
internal class NetconfSessionListenerImpl(private val session: NetconfSessionImpl) : NetconfSessionListener {
+
override fun accept(event: NetconfReceivedEvent) {
when (event.type) {
NetconfReceivedEvent.Type.DEVICE_UNREGISTERED -> session.disconnect()
NetconfReceivedEvent.Type.DEVICE_REPLY -> session.addDeviceReply(event.messageId, event.messagePayload)
}
}
-}
\ No newline at end of file
+}
import javax.xml.parsers.DocumentBuilderFactory
import kotlin.text.Charsets.UTF_8
-
class NetconfMessageUtils {
companion object {
return rpc.toString()
}
- fun editConfig(messageId: String, configType: String, defaultOperation: String?,
- newConfiguration: String): String {
+ fun editConfig(
+ messageId: String,
+ configType: String,
+ defaultOperation: String?,
+ newConfiguration: String
+ ): String {
val request = StringBuilder()
request.append("<edit-config>").append(NEW_LINE)
request.append(RpcMessageUtils.TARGET_OPEN).append(NEW_LINE)
return doWrappedRpc(messageId, request.toString())
}
- fun commit(messageId: String, confirmed: Boolean, confirmTimeout: Int, persist: String,
- persistId: String): String {
+ fun commit(
+ messageId: String,
+ confirmed: Boolean,
+ confirmTimeout: Int,
+ persist: String,
+ persistId: String
+ ): String {
if (!persist.isEmpty() && !persistId.isEmpty()) {
- throw NetconfException("Can't proceed <commit> with both persist($persist) and " +
- "persistId($persistId) specified. Only one should be specified.")
+ throw NetconfException(
+ "Can't proceed <commit> with both persist($persist) and " +
+ "persistId($persistId) specified. Only one should be specified."
+ )
}
if (confirmed && !persistId.isEmpty()) {
- throw NetconfException("Can't proceed <commit> with both confirmed flag and " +
- "persistId($persistId) specified. Only one should be specified.")
+ throw NetconfException(
+ "Can't proceed <commit> with both confirmed flag and " +
+ "persistId($persistId) specified. Only one should be specified."
+ )
}
val request = StringBuilder()
fun closeSession(messageId: String, force: Boolean): String {
val request = StringBuilder()
- //TODO: kill-session without session-id is a cisco-only variant.
- //will fail on JUNIPER device.
- //netconf RFC for kill-session requires session-id
- //Cisco can accept <kill-session/> for current session
- //or <kill-session><session-id>####</session-id></kill-session>
- //as long as session ID is not the same as the current session.
-
- //Juniperhttps://www.juniper.net/documentation/en_US/junos/topics/task/operational/netconf-session-terminating.html
- //will accept only with session-id
+ // TODO: kill-session without session-id is a cisco-only variant.
+ // will fail on JUNIPER device.
+ // netconf RFC for kill-session requires session-id
+ // Cisco can accept <kill-session/> for current session
+ // or <kill-session><session-id>####</session-id></kill-session>
+ // as long as session ID is not the same as the current session.
+
+ // Juniperhttps://www.juniper.net/documentation/en_US/junos/topics/task/operational/netconf-session-terminating.html
+ // will accept only with session-id
if (force) {
request.append("<kill-session/>")
} else {
} catch (e: Exception) {
return false
}
-
}
fun getMsgId(message: String): String {
if (!message.startsWith(RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH)) {
// chunk encode message
message =
- (RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH + message.toByteArray(UTF_8).size + RpcMessageUtils.NEW_LINE + message + RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH
- + RpcMessageUtils.NEW_LINE)
+ (RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH + message.toByteArray(UTF_8).size + RpcMessageUtils.NEW_LINE + message + RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH +
+ RpcMessageUtils.NEW_LINE)
}
return message
}
if (request.startsWith(RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH)) {
request =
request.split("<".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] + RpcMessageUtils.XML_HEADER + request.substring(
- request.split("<".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].length)
+ request.split("<".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].length
+ )
} else {
request = RpcMessageUtils.XML_HEADER + "\n" + request
}
var request = request
if (request.contains(RpcMessageUtils.MESSAGE_ID_STRING)) {
request =
- request.replaceFirst((RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.NUMBER_BETWEEN_QUOTES_MATCHER).toRegex(),
- RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.QUOTE + messageId + RpcMessageUtils.QUOTE)
+ request.replaceFirst(
+ (RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.NUMBER_BETWEEN_QUOTES_MATCHER).toRegex(),
+ RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.QUOTE + messageId + RpcMessageUtils.QUOTE
+ )
} else if (!request.contains(RpcMessageUtils.MESSAGE_ID_STRING) && !request.contains(
- RpcMessageUtils.HELLO)) {
- request = request.replaceFirst(RpcMessageUtils.END_OF_RPC_OPEN_TAG.toRegex(),
- RpcMessageUtils.QUOTE_SPACE + RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.QUOTE + messageId + RpcMessageUtils.QUOTE + ">")
+ RpcMessageUtils.HELLO
+ )
+ ) {
+ request = request.replaceFirst(
+ RpcMessageUtils.END_OF_RPC_OPEN_TAG.toRegex(),
+ RpcMessageUtils.QUOTE_SPACE + RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.QUOTE + messageId + RpcMessageUtils.QUOTE + ">"
+ )
}
return updateRequestLength(request)
}
fun updateRequestLength(request: String): String {
if (request.contains(NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH + NEW_LINE)) {
val oldLen =
- Integer.parseInt(request.split(RpcMessageUtils.HASH.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1].split(
- NEW_LINE.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[0])
+ Integer.parseInt(
+ request.split(RpcMessageUtils.HASH.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1].split(
+ NEW_LINE.toRegex()
+ ).dropLastWhile({ it.isEmpty() }).toTypedArray()[0]
+ )
val rpcWithEnding = request.substring(request.indexOf('<'))
val firstBlock =
request.split(RpcMessageUtils.MSGLEN_REGEX_PATTERN.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1].split(
- (NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH + NEW_LINE).toRegex()).dropLastWhile(
+ (NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH + NEW_LINE).toRegex()
+ ).dropLastWhile(
{ it.isEmpty() }).toTypedArray()[0]
var newLen = 0
newLen = firstBlock.toByteArray(UTF_8).size
} else false
}
}
-
}
coEvery { blueprintJythonService.jythonComponentInstance(any(), any()) } returns mockAbstractScriptComponentFunction
- val componentFunctionScriptingService = ComponentFunctionScriptingService(applicationContext,
- blueprintJythonService)
+ val componentFunctionScriptingService = ComponentFunctionScriptingService(
+ applicationContext,
+ blueprintJythonService
+ )
val componentNetconfExecutor = ComponentNetconfExecutor(componentFunctionScriptingService)
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("requests/sample-activate-request.json",
- ExecutionServiceInput::class.java)!!
+ val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
+ "requests/sample-activate-request.json",
+ ExecutionServiceInput::class.java
+ )!!
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val assignmentParams = """{
"ipAddress" : "127.0.0.1",
""".trimIndent()
bluePrintRuntimeService.assignInputs(json.asJsonType())
- bluePrintRuntimeService.setNodeTemplateAttributeValue("resource-assignment", "assignment-params",
- JacksonUtils.jsonNode(assignmentParams))
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ "resource-assignment", "assignment-params",
+ JacksonUtils.jsonNode(assignmentParams)
+ )
componentNetconfExecutor.bluePrintRuntimeService = bluePrintRuntimeService
- //TODO("Set Attribute properties")
+ // TODO("Set Attribute properties")
val stepMetaData: MutableMap<String, JsonNode> = hashMapOf()
stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-netconf")
stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentNetconfExecutor")
}
}
}
-
package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api
-
import org.junit.Test
import kotlin.test.assertEquals
@Test
fun testToString() {
- val di: DeviceInfo = DeviceInfo().apply {
- username = "username"
- password = "password"
- ipAddress = "localhost"
- port = 2224
- connectTimeout = 10
- }
+ val di: DeviceInfo = DeviceInfo().apply {
+ username = "username"
+ password = "password"
+ ipAddress = "localhost"
+ port = 2224
+ connectTimeout = 10
+ }
assertEquals("localhost:2224", di.toString())
}
-}
\ No newline at end of file
+}
val dr: DeviceResponse = genUnsuccessfulEmptyDeviceResponse()
assertFalse(dr.isSuccess())
- //case 2: Success, but with error message
+ // case 2: Success, but with error message
val dr2: DeviceResponse = genUnsuccessfulEmptyDeviceResponse()
dr2.errorMessage = "Some error message."
assertFalse(dr2.isSuccess())
}
- //helper function to generate a device response
+ // helper function to generate a device response
private fun genSuccessfulEmptyDeviceResponse(): DeviceResponse {
return DeviceResponse().apply {
status = RpcStatus.SUCCESS
requestMessage = ""
}
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core
-import io.mockk.*
+import io.mockk.CapturingSlot
+import io.mockk.Runs
+import io.mockk.every
+import io.mockk.just
+import io.mockk.mockk
+import io.mockk.spyk
+import io.mockk.verify
import org.junit.Before
import org.junit.Test
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
-import java.nio.charset.*
-import java.util.concurrent.*
-import java.util.regex.*
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.ConcurrentHashMap
+import java.util.regex.Pattern
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
private lateinit var replies: MutableMap<String, CompletableFuture<String>>
private val endPatternCharArray: List<Int> = stringToCharArray(RpcMessageUtils.END_PATTERN)
-
companion object {
private val chunkedEnding = "\n##\n"
- //using example from section 4.2 of RFC6242 (https://tools.ietf.org/html/rfc6242#section-4.2)
+ // using example from section 4.2 of RFC6242 (https://tools.ietf.org/html/rfc6242#section-4.2)
private val validChunkedEncodedMsg = """
|
|#4
val communicator: NetconfDeviceCommunicator =
NetconfDeviceCommunicator(mockInputStream, mockOutputStream, genDeviceInfo(), netconfSessionListener, replies)
communicator.join()
- //verify
+ // verify
verify { mockInputStream.read(any(), any(), any()) }
}
@Test
fun `NetconfDeviceCommunicator unregisters device on END_PATTERN`() {
- //The reader will generate RpcMessageUtils.END_PATTERN "]]>]]>" which tells Netconf
- //to unregister the device.
- //we want to capture the slot to return the value as inputStreamReader will pass a char array
- //create a slot where NetconfReceivedEvent will be placed to further verify Type.DEVICE_UNREGISTERED
+ // The reader will generate RpcMessageUtils.END_PATTERN "]]>]]>" which tells Netconf
+ // to unregister the device.
+ // we want to capture the slot to return the value as inputStreamReader will pass a char array
+ // create a slot where NetconfReceivedEvent will be placed to further verify Type.DEVICE_UNREGISTERED
val eventSlot = CapturingSlot<NetconfReceivedEvent>()
every { netconfSessionListener.accept(event = capture(eventSlot)) } just Runs
stubInputStream = RpcMessageUtils.END_PATTERN.byteInputStream(StandardCharsets.UTF_8)
val inputStreamSpy = spyk(stubInputStream)
- //RUN the test
- val communicator = NetconfDeviceCommunicator(inputStreamSpy, mockOutputStream,
- genDeviceInfo(), netconfSessionListener, replies)
+ // RUN the test
+ val communicator = NetconfDeviceCommunicator(
+ inputStreamSpy, mockOutputStream,
+ genDeviceInfo(), netconfSessionListener, replies
+ )
communicator.join()
- //Verify
+ // Verify
verify { inputStreamSpy.close() }
assertTrue { eventSlot.isCaptured }
assertEquals(NetconfReceivedEvent.Type.DEVICE_UNREGISTERED, eventSlot.captured.type)
stubInputStream = "".byteInputStream(StandardCharsets.UTF_8)
val inputStreamSpy = spyk(stubInputStream)
every { inputStreamSpy.read(any(), any(), any()) } returns 1 andThenThrows IOException("Fake IO Exception")
- //RUN THE TEST
- val communicator = NetconfDeviceCommunicator(inputStreamSpy, mockOutputStream,
- genDeviceInfo(), netconfSessionListener, replies)
+ // RUN THE TEST
+ val communicator = NetconfDeviceCommunicator(
+ inputStreamSpy, mockOutputStream,
+ genDeviceInfo(), netconfSessionListener, replies
+ )
communicator.join()
- //Verify
+ // Verify
assertTrue { eventSlot.isCaptured }
assertEquals(genDeviceInfo(), eventSlot.captured.deviceInfo)
assertEquals(NetconfReceivedEvent.Type.DEVICE_ERROR, eventSlot.captured.type)
val payload = "<rpc-reply>blah</rpc-reply>"
stubInputStream = "$payload${RpcMessageUtils.END_PATTERN}".byteInputStream(StandardCharsets.UTF_8)
every { netconfSessionListener.accept(event = capture(eventSlot)) } just Runs
- //RUN the test
- val communicator = NetconfDeviceCommunicator(stubInputStream, mockOutputStream,
- genDeviceInfo(), netconfSessionListener, replies)
+ // RUN the test
+ val communicator = NetconfDeviceCommunicator(
+ stubInputStream, mockOutputStream,
+ genDeviceInfo(), netconfSessionListener, replies
+ )
communicator.join()
- //Verify
- verify(exactly = 0) { mockInputStream.close() } //make sure the reader is not closed as this could cause problems
+ // Verify
+ verify(exactly = 0) { mockInputStream.close() } // make sure the reader is not closed as this could cause problems
assertTrue { eventSlot.isCaptured }
- //eventually, sessionListener is called with message type DEVICE_REPLY
+ // eventually, sessionListener is called with message type DEVICE_REPLY
assertEquals(NetconfReceivedEvent.Type.DEVICE_REPLY, eventSlot.captured.type)
assertEquals(payload, eventSlot.captured.messagePayload)
}
every { netconfSessionListener.accept(event = capture(eventSlot)) } just Runs
stubInputStream = payloadWithChunkedEnding.byteInputStream(StandardCharsets.UTF_8)
- //we have to ensure that the input stream is processed, so need to create a spy object.
+ // we have to ensure that the input stream is processed, so need to create a spy object.
val inputStreamSpy = spyk(stubInputStream)
- //RUN the test
- val communicator = NetconfDeviceCommunicator(inputStreamSpy, mockOutputStream, genDeviceInfo(),
- netconfSessionListener, replies)
+ // RUN the test
+ val communicator = NetconfDeviceCommunicator(
+ inputStreamSpy, mockOutputStream, genDeviceInfo(),
+ netconfSessionListener, replies
+ )
communicator.join()
- //Verify
- verify(exactly = 0) { inputStreamSpy.close() } //make sure the reader is not closed as this could cause problems
+ // Verify
+ verify(exactly = 0) { inputStreamSpy.close() } // make sure the reader is not closed as this could cause problems
assertTrue { eventSlot.isCaptured }
- //eventually, sessionListener is called with message type DEVICE_REPLY
+ // eventually, sessionListener is called with message type DEVICE_REPLY
assertEquals(NetconfReceivedEvent.Type.DEVICE_ERROR, eventSlot.captured.type)
assertEquals("", eventSlot.captured.messagePayload)
}
stubInputStream = validChunkedEncodedMsg.byteInputStream(StandardCharsets.UTF_8)
val inputStreamSpy = spyk(stubInputStream)
every { netconfSessionListener.accept(event = capture(eventSlot)) } just Runs
- //RUN the test
+ // RUN the test
NetconfDeviceCommunicator(inputStreamSpy, mockOutputStream, genDeviceInfo(), netconfSessionListener, replies).join()
- //Verify
- verify(exactly = 0) { inputStreamSpy.close() } //make sure the reader is not closed as this could cause problems
+ // Verify
+ verify(exactly = 0) { inputStreamSpy.close() } // make sure the reader is not closed as this could cause problems
assertTrue { eventSlot.isCaptured }
- //eventually, sessionListener is called with message type DEVICE_REPLY
+ // eventually, sessionListener is called with message type DEVICE_REPLY
assertEquals(NetconfReceivedEvent.Type.DEVICE_REPLY, eventSlot.captured.type)
- assertEquals("""
+ assertEquals(
+ """
<rpc message-id="102"
xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<close-session/>
</rpc>
- """.trimIndent(), eventSlot.captured.messagePayload)
+ """.trimIndent(), eventSlot.captured.messagePayload
+ )
}
@Test
- //test to ensure that we have a valid test message to be then used in the case of chunked message
+ // test to ensure that we have a valid test message to be then used in the case of chunked message
// validation code path
fun `chunked sample is validated by the chunked response regex`() {
val test1 = "\n#10\nblah\n##\n"
}
@Test
- //Verify that our test sample passes the second pattern for chunked size
+ // Verify that our test sample passes the second pattern for chunked size
fun `chunkSizeMatcher pattern finds matches in chunkedMessageSample`() {
val sizePattern = Pattern.compile("\\n#([1-9][0-9]*)\\n")
val matcher = sizePattern.matcher(validChunkedEncodedMsg)
fun `sendMessage writes the request to NetconfDeviceCommunicator Writer`() {
val msgPayload = "some text"
val msgId = "100"
- stubInputStream = "".byteInputStream(StandardCharsets.UTF_8) //no data available in the stream...
+ stubInputStream = "".byteInputStream(StandardCharsets.UTF_8) // no data available in the stream...
every { mockOutputStream.write(any(), any(), any()) } just Runs
every { mockOutputStream.write(msgPayload.toByteArray(Charsets.UTF_8)) } just Runs
every { mockOutputStream.flush() } just Runs
- //Run the command
+ // Run the command
val communicator = NetconfDeviceCommunicator(
stubInputStream, mockOutputStream,
- genDeviceInfo(), netconfSessionListener, replies)
+ genDeviceInfo(), netconfSessionListener, replies
+ )
val completableFuture = communicator.sendMessage(msgPayload, msgId)
communicator.join()
- //verify
+ // verify
verify { mockOutputStream.write(any(), any(), any()) }
verify { mockOutputStream.flush() }
assertFalse { completableFuture.isCompletedExceptionally }
fun `sendMessage on IOError returns completed exceptionally future`() {
val msgPayload = "some text"
val msgId = "100"
- every { mockOutputStream.write(any(), any(), any()) } throws IOException("Some IO error occurred!")
- stubInputStream = "".byteInputStream(StandardCharsets.UTF_8) //no data available in the stream...
- //Run the command
+ every { mockOutputStream.write(any(), any(), any()) } throws IOException("Some IO error occurred!")
+ stubInputStream = "".byteInputStream(StandardCharsets.UTF_8) // no data available in the stream...
+ // Run the command
val communicator = NetconfDeviceCommunicator(
stubInputStream, mockOutputStream,
- genDeviceInfo(), netconfSessionListener, replies)
+ genDeviceInfo(), netconfSessionListener, replies
+ )
val completableFuture = communicator.sendMessage(msgPayload, msgId)
- //verify
+ // verify
verify { mockOutputStream.write(any(), any(), any()) }
verify(exactly = 0) { mockOutputStream.flush() }
assertTrue { completableFuture.isCompletedExceptionally }
port = 4567
}
}
-
}
@Test
fun `NO_MATCHING_PATTERN transitions`() {
- assertEquals(NetconfMessageState.FIRST_BRACKET,
- NetconfMessageState.NO_MATCHING_PATTERN.evaluateChar(']'))
- assertEquals(NetconfMessageState.FIRST_LF,
- NetconfMessageState.NO_MATCHING_PATTERN.evaluateChar('\n'))
-
- charList.minus(listOf(']','\n')).forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.NO_MATCHING_PATTERN.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.FIRST_BRACKET,
+ NetconfMessageState.NO_MATCHING_PATTERN.evaluateChar(']')
+ )
+ assertEquals(
+ NetconfMessageState.FIRST_LF,
+ NetconfMessageState.NO_MATCHING_PATTERN.evaluateChar('\n')
+ )
+
+ charList.minus(listOf(']', '\n')).forEach {
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.NO_MATCHING_PATTERN.evaluateChar(it)
+ )
}
}
@Test
fun `FIRST_BRACKET transitions`() {
- assertEquals(NetconfMessageState.SECOND_BRACKET,
- NetconfMessageState.FIRST_BRACKET.evaluateChar(']'))
+ assertEquals(
+ NetconfMessageState.SECOND_BRACKET,
+ NetconfMessageState.FIRST_BRACKET.evaluateChar(']')
+ )
- charList.minus( ']').forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.FIRST_BRACKET.evaluateChar(it))
+ charList.minus(']').forEach {
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.FIRST_BRACKET.evaluateChar(it)
+ )
}
}
@Test
fun `SECOND_BRACKET transitions`() {
- assertEquals(NetconfMessageState.FIRST_BIGGER,
- NetconfMessageState.SECOND_BRACKET.evaluateChar('>'))
+ assertEquals(
+ NetconfMessageState.FIRST_BIGGER,
+ NetconfMessageState.SECOND_BRACKET.evaluateChar('>')
+ )
charList.minus('>').forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.SECOND_BRACKET.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.SECOND_BRACKET.evaluateChar(it)
+ )
}
}
@Test
fun `FIRST_BIGGER transitions`() {
- assertEquals(NetconfMessageState.THIRD_BRACKET,
- NetconfMessageState.FIRST_BIGGER.evaluateChar(']'))
+ assertEquals(
+ NetconfMessageState.THIRD_BRACKET,
+ NetconfMessageState.FIRST_BIGGER.evaluateChar(']')
+ )
charList.minus(']').forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.FIRST_BIGGER.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.FIRST_BIGGER.evaluateChar(it)
+ )
}
}
@Test
fun `THIRD_BRACKET transitions`() {
- assertEquals(NetconfMessageState.ENDING_BIGGER,
- NetconfMessageState.THIRD_BRACKET.evaluateChar(']'))
+ assertEquals(
+ NetconfMessageState.ENDING_BIGGER,
+ NetconfMessageState.THIRD_BRACKET.evaluateChar(']')
+ )
charList.minus(']').forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.THIRD_BRACKET.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.THIRD_BRACKET.evaluateChar(it)
+ )
}
}
@Test
fun `ENDING_BIGGER transitions`() {
- assertEquals(NetconfMessageState.END_PATTERN,
- NetconfMessageState.ENDING_BIGGER.evaluateChar('>'))
+ assertEquals(
+ NetconfMessageState.END_PATTERN,
+ NetconfMessageState.ENDING_BIGGER.evaluateChar('>')
+ )
charList.minus('>').forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.ENDING_BIGGER.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.ENDING_BIGGER.evaluateChar(it)
+ )
}
}
@Test
fun `FIRST_LF transitions`() {
- assertEquals(NetconfMessageState.FIRST_HASH,
- NetconfMessageState.FIRST_LF.evaluateChar('#'))
- assertEquals(NetconfMessageState.FIRST_BRACKET,
- NetconfMessageState.FIRST_LF.evaluateChar(']'))
- assertEquals(NetconfMessageState.FIRST_LF,
- NetconfMessageState.FIRST_LF.evaluateChar('\n'))
+ assertEquals(
+ NetconfMessageState.FIRST_HASH,
+ NetconfMessageState.FIRST_LF.evaluateChar('#')
+ )
+ assertEquals(
+ NetconfMessageState.FIRST_BRACKET,
+ NetconfMessageState.FIRST_LF.evaluateChar(']')
+ )
+ assertEquals(
+ NetconfMessageState.FIRST_LF,
+ NetconfMessageState.FIRST_LF.evaluateChar('\n')
+ )
charList.minus(listOf('#', ']', '\n')).forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.FIRST_LF.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.FIRST_LF.evaluateChar(it)
+ )
}
}
@Test
fun `FIRST_HASH transitions`() {
- assertEquals(NetconfMessageState.SECOND_HASH,
- NetconfMessageState.FIRST_HASH.evaluateChar('#'))
+ assertEquals(
+ NetconfMessageState.SECOND_HASH,
+ NetconfMessageState.FIRST_HASH.evaluateChar('#')
+ )
charList.minus('#').forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.FIRST_HASH.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.FIRST_HASH.evaluateChar(it)
+ )
}
}
@Test
fun `SECOND_HASH transitions`() {
- assertEquals(NetconfMessageState.END_CHUNKED_PATTERN,
- NetconfMessageState.SECOND_HASH.evaluateChar('\n'))
-
- charList.minus( '\n').forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.SECOND_HASH.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.END_CHUNKED_PATTERN,
+ NetconfMessageState.SECOND_HASH.evaluateChar('\n')
+ )
+
+ charList.minus('\n').forEach {
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.SECOND_HASH.evaluateChar(it)
+ )
}
}
@Test
fun `END_CHUNKED_PATTERN transitions`() {
charList.forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.END_CHUNKED_PATTERN.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.END_CHUNKED_PATTERN.evaluateChar(it)
+ )
}
}
@Test
fun `END_PATTERN transitions`() {
charList.forEach {
- assertEquals(NetconfMessageState.NO_MATCHING_PATTERN,
- NetconfMessageState.END_PATTERN.evaluateChar(it))
+ assertEquals(
+ NetconfMessageState.NO_MATCHING_PATTERN,
+ NetconfMessageState.END_PATTERN.evaluateChar(it)
+ )
}
}
-
}
import io.mockk.mockk
import io.mockk.spyk
import org.junit.Before
-
import org.junit.Test
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceResponse
companion object {
private const val someString = "someString"
private const val replyStr = "this is a reply"
- private val failedDeviceResponse = DeviceResponse(status = RpcStatus.FAILURE,
- requestMessage = "request message", responseMessage = replyStr) //responseMessage will be null in this POJO
- private val successfulDeviceResponse = DeviceResponse(status = RpcStatus.SUCCESS,
- requestMessage = "request message", responseMessage = replyStr) //responseMessage will be null in this POJO
- //but will be set later from mockSession
+ private val failedDeviceResponse = DeviceResponse(
+ status = RpcStatus.FAILURE,
+ requestMessage = "request message", responseMessage = replyStr
+ ) // responseMessage will be null in this POJO
+ private val successfulDeviceResponse = DeviceResponse(
+ status = RpcStatus.SUCCESS,
+ requestMessage = "request message", responseMessage = replyStr
+ ) // responseMessage will be null in this POJO
+ // but will be set later from mockSession
private const val msgId = "100"
private const val timeout = 5
private val deviceInfo: DeviceInfo = DeviceInfo().apply {
assertTrue { rpcResult.errorMessage!!.contains("failed in 'closeSession' command") }
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core
-import io.mockk.*
+import io.mockk.CapturingSlot
+import io.mockk.Runs
+import io.mockk.every
+import io.mockk.just
+import io.mockk.mockk
+import io.mockk.spyk
+import io.mockk.verify
import org.apache.sshd.client.SshClient
import org.apache.sshd.client.channel.ChannelSubsystem
import org.apache.sshd.client.channel.ClientChannel
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
-import java.nio.charset.*
-import java.util.concurrent.*
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.ExecutionException
+import java.util.concurrent.TimeoutException
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
verify { session["startClient"]() }
}
- //look for NetconfException being thrown when cannot connect
+ // look for NetconfException being thrown when cannot connect
@Test
fun `connect throws NetconfException on error`() {
val errMsg = "$deviceInfo: Failed to establish SSH session"
@Test
fun `disconnect without force option for rpcService succeeds`() {
- //rpcService.closeSession succeeds with status not RpcStatus.FAILURE
+ // rpcService.closeSession succeeds with status not RpcStatus.FAILURE
every { rpcService.closeSession(false) } returns SUCCESSFUL_DEVICE_RESPONSE
every { mockClientSession.close() } just Runs
every { mockSshClient.close() } just Runs
netconfSessionSpy.setSession(mockClientSession)
netconfSessionSpy.setClient(mockSshClient)
netconfSessionSpy.setChannel(mockClientChannel)
- //RUN
+ // RUN
netconfSessionSpy.disconnect()
- //make sure that rpcService.close session is not called again.
+ // make sure that rpcService.close session is not called again.
verify(exactly = 0) { rpcService.closeSession(true) }
verify { mockClientSession.close() }
verify { mockSshClient.close() }
@Test
fun `disconnect with force option for rpcService succeeds`() {
- //rpcService.closeSession succeeds with status not RpcStatus.FAILURE
+ // rpcService.closeSession succeeds with status not RpcStatus.FAILURE
val netconfSessionSpy = spyk(netconfSession, recordPrivateCalls = true)
every { rpcService.closeSession(any()) } returns
- FAILED_DEVICE_RESPONSE andThen SUCCESSFUL_DEVICE_RESPONSE
+ FAILED_DEVICE_RESPONSE andThen SUCCESSFUL_DEVICE_RESPONSE
every { mockClientSession.close() } just Runs
every { mockSshClient.close() } just Runs
every { mockClientChannel.close() } just Runs
netconfSessionSpy.setSession(mockClientSession)
netconfSessionSpy.setClient(mockSshClient)
netconfSessionSpy.setChannel(mockClientChannel)
- //RUN
+ // RUN
netconfSessionSpy.disconnect()
- //VERIFY
+ // VERIFY
verify(exactly = 2) { rpcService.closeSession(any()) }
verify { mockClientSession.close() }
verify { mockSshClient.close() }
verify { mockClientChannel.close() }
-
}
@Test
every { mockSshClient.isClosed } returns true
netconfSessionSpy.setClient(mockSshClient)
every { netconfSessionSpy["startConnection"]() as Unit } just Runs
- //Call method
+ // Call method
netconfSessionSpy.checkAndReestablish()
- //Verify
+ // Verify
verify { netconfSessionSpy.clearReplies() }
verify { netconfSessionSpy["startConnection"]() }
}
every { netconfSessionSpy["startSession"]() as Unit } just Runs
netconfSessionSpy.setClient(mockSshClient)
netconfSessionSpy.setSession(mockClientSession)
- //Call method
+ // Call method
netconfSessionSpy.checkAndReestablish()
- //Verify
+ // Verify
verify { netconfSessionSpy.clearReplies() }
verify { netconfSessionSpy["startSession"]() }
}
netconfSessionSpy.setClient(mockSshClient)
netconfSessionSpy.setSession(mockClientSession)
netconfSessionSpy.setChannel(mockClientChannel)
- //Call method
+ // Call method
netconfSessionSpy.checkAndReestablish()
- //Verify
+ // Verify
verify { netconfSessionSpy.clearReplies() }
verify { netconfSessionSpy["openChannel"]() }
}
-
@Test
fun `syncRpc runs normally`() {
val netconfSessionSpy = spyk(netconfSession)
val futureRet: CompletableFuture<String> = CompletableFuture.completedFuture(futureMsg)
- //test the case where SSH connection did not need to be re-established.
- //put an existing item into the replies
+ // test the case where SSH connection did not need to be re-established.
+ // put an existing item into the replies
netconfSessionSpy.getReplies()["somekey"] = CompletableFuture.completedFuture("${futureMsg}2")
every { netconfCommunicator.sendMessage(any(), any()) } returns futureRet
every { netconfCommunicator.getFutureFromSendMessage(any(), any(), any()) } returns futureRet.get()
every { netconfSessionSpy.checkAndReestablish() } just Runs
- //call the method
+ // call the method
assertEquals(futureMsg, netconfSessionSpy.syncRpc("0", "0"))
- //make sure the replies didn't change
+ // make sure the replies didn't change
assertTrue {
netconfSessionSpy.getReplies().size == 1 &&
- netconfSessionSpy.getReplies().containsKey("somekey")
+ netconfSessionSpy.getReplies().containsKey("somekey")
}
verify(exactly = 0) { netconfSessionSpy.clearReplies() }
}
-
@Test
fun `syncRpc still succeeds and replies are cleared on client disconnect`() {
val netconfSessionSpy = spyk(netconfSession, recordPrivateCalls = true)
val futureRet: CompletableFuture<String> = CompletableFuture.completedFuture(futureMsg)
- //put an item into the replies
+ // put an item into the replies
netconfSessionSpy.getReplies()["somekey"] = CompletableFuture.completedFuture("${futureMsg}2")
- //tests the case where SSH session needs to be re-established.
+ // tests the case where SSH session needs to be re-established.
every { netconfCommunicator.sendMessage(any(), any()) } returns futureRet
every { netconfSessionSpy["startClient"]() as Unit } just Runs
every { netconfCommunicator.getFutureFromSendMessage(any(), any(), any()) } returns futureRet.get()
every { mockSshClient.isClosed } returns true
netconfSessionSpy.setClient(mockSshClient)
- //call the method
+ // call the method
assertEquals(futureMsg, netconfSessionSpy.syncRpc("0", "0"))
- //make sure the replies got cleared out
+ // make sure the replies got cleared out
assertTrue { netconfSessionSpy.getReplies().isEmpty() }
verify(exactly = 1) { netconfSessionSpy.clearReplies() }
}
- //Test for handling CompletableFuture.get returns InterruptedException inside NetconfDeviceCommunicator
+ // Test for handling CompletableFuture.get returns InterruptedException inside NetconfDeviceCommunicator
@Test
fun `syncRpc throws NetconfException if InterruptedException is caught`() {
val expectedExceptionMsg = "$deviceInfo: Interrupted while waiting for reply for request: $formattedRequest"
every { netconfCommunicator.sendMessage(any(), any()) } returns futureRet
every { netconfCommunicator.getFutureFromSendMessage(any(), any(), any()) } throws InterruptedException("interrupted")
every { netconfSessionSpy.checkAndReestablish() } just Runs
- //call the method
+ // call the method
netconfSessionSpy.syncRpc("0", "0")
}
}
@Test
fun `syncRpc throws NetconfException if TimeoutException is caught`() {
- val expectedExceptionMsg = "$deviceInfo: Timed out while waiting for reply for request $formattedRequest after ${deviceInfo.replyTimeout} sec."
+ val expectedExceptionMsg =
+ "$deviceInfo: Timed out while waiting for reply for request $formattedRequest after ${deviceInfo.replyTimeout} sec."
assertFailsWith(exceptionClass = NetconfException::class, message = expectedExceptionMsg) {
val netconfSessionSpy = spyk(netconfSession)
val futureRet: CompletableFuture<String> = CompletableFuture.completedFuture(futureMsg)
every { netconfCommunicator.sendMessage(any(), any()) } returns futureRet
every { netconfCommunicator.getFutureFromSendMessage(any(), any(), any()) } throws TimeoutException("timed out")
every { netconfSessionSpy.checkAndReestablish() } just Runs
- //call the method
+ // call the method
netconfSessionSpy.syncRpc("0", "0")
}
}
val futureRet: CompletableFuture<String> = CompletableFuture.completedFuture(futureMsg)
every { netconfCommunicator.sendMessage(any(), any()) } returns futureRet
every { netconfCommunicator.getFutureFromSendMessage(any(), any(), any()) } throws
- ExecutionException("exec exception", Exception("nested exception"))
+ ExecutionException("exec exception", Exception("nested exception"))
every { netconfSessionSpy["close"]() as Unit } just Runs
every { netconfSessionSpy.checkAndReestablish() } just Runs
netconfSessionSpy.setSession(mockClientSession)
- //call the method
+ // call the method
netconfSessionSpy.syncRpc("0", "0")
}
}
val futureRet: CompletableFuture<String> = CompletableFuture.completedFuture(futureMsg)
every { netconfCommunicator.sendMessage(any(), any()) } returns futureRet
every { netconfCommunicator.getFutureFromSendMessage(any(), any(), any()) } throws
- ExecutionException("exec exception", Exception("nested exception"))
+ ExecutionException("exec exception", Exception("nested exception"))
every { netconfSessionSpy["close"]() as Unit } throws IOException("got an IO exception")
every { netconfSessionSpy.checkAndReestablish() } just Runs
- //call the method
+ // call the method
netconfSessionSpy.syncRpc("0", "0")
- //make sure replies are cleared...
+ // make sure replies are cleared...
verify(exactly = 1) { netconfSessionSpy.clearReplies() }
verify(exactly = 1) { netconfSessionSpy.clearErrorReplies() }
}
every { netconfSessionSpy.checkAndReestablish() } just Runs
val futureRet: CompletableFuture<String> = CompletableFuture.completedFuture(futureMsg)
every { netconfCommunicator.sendMessage(any(), any()) } returns futureRet
- //run the method
+ // run the method
val rpcResultFuture = netconfSessionSpy.asyncRpc("0", "0")
every { netconfSessionSpy.checkAndReestablish() } just Runs
- //make sure the future gets resolved
+ // make sure the future gets resolved
assertTrue { rpcResultFuture.get() == futureMsg }
- //make sure that clearReplies wasn't called (reestablishConnection check)
+ // make sure that clearReplies wasn't called (reestablishConnection check)
verify(exactly = 0) { netconfSessionSpy.clearReplies() }
}
throw Exception("blah")
}
every { netconfCommunicator.sendMessage(any(), any()) } returns futureRet
- //run the method
+ // run the method
val rpcResultFuture = netconfSessionSpy.asyncRpc("0", "0")
every { netconfSessionSpy.checkAndReestablish() } just Runs
val e = assertFailsWith(exceptionClass = ExecutionException::class, message = futureMsg) {
fun `startSession tries to connect to user supplied device`() {
every { mockSshClient.start() } just Runs
every { mockSshClient.properties } returns hashMapOf<String, Any>()
- //setup slots to capture values from the invocations
+ // setup slots to capture values from the invocations
val userSlot = CapturingSlot<String>()
val ipSlot = CapturingSlot<String>()
val portSlot = CapturingSlot<Int>()
- //create a future that succeeded
+ // create a future that succeeded
val succeededFuture = DefaultConnectFuture(Any(), Any())
succeededFuture.value = mockClientSession
every { mockSshClient.connect(capture(userSlot), capture(ipSlot), capture(portSlot)) } returns succeededFuture
every { netconfSessionSpy["authSession"]() as Unit } just Runs
every { netconfSessionSpy["setupNewSSHClient"]() as Unit } just Runs
netconfSessionSpy.setClient(mockSshClient)
- //RUN
+ // RUN
netconfSessionSpy.connect()
- //Verify
+ // Verify
verify { mockSshClient.connect(deviceInfo.username, deviceInfo.ipAddress, deviceInfo.port) }
assertEquals(deviceInfo.username, userSlot.captured)
assertEquals(deviceInfo.ipAddress, ipSlot.captured)
@Test
fun `authSession throws exception if ClientSession is not AUTHED`() {
assertFailsWith(exceptionClass = NetconfException::class) {
- //after client session connects,
+ // after client session connects,
every { mockSshClient.start() } just Runs
every { mockSshClient.properties } returns hashMapOf<String, Any>()
val succeededAuthFuture = DefaultAuthFuture(Any(), Any())
- succeededAuthFuture.value = true //AuthFuture's value is Boolean
+ succeededAuthFuture.value = true // AuthFuture's value is Boolean
val passSlot = CapturingSlot<String>()
every { mockClientSession.addPasswordIdentity(capture(passSlot)) } just Runs
every { mockClientSession.auth() } returns succeededAuthFuture
succeededSessionFuture.value = mockClientSession
every { mockSshClient.connect(deviceInfo.username, deviceInfo.ipAddress, deviceInfo.port) } returns succeededSessionFuture
every { mockClientSession.waitFor(any(), any()) } returns
- setOf(ClientSession.ClientSessionEvent.WAIT_AUTH, ClientSession.ClientSessionEvent.CLOSED)
+ setOf(ClientSession.ClientSessionEvent.WAIT_AUTH, ClientSession.ClientSessionEvent.CLOSED)
val netconfSessionSpy = spyk(netconfSession, recordPrivateCalls = true)
every { netconfSessionSpy["setupNewSSHClient"]() as Unit } just Runs
netconfSessionSpy.setClient(mockSshClient)
- //RUN
+ // RUN
netconfSessionSpy.connect()
}
}
- //common mock initializer for more weird tests.
- private fun setupOpenChannelMocks(): Unit {
+ // common mock initializer for more weird tests.
+ private fun setupOpenChannelMocks() {
every { mockSshClient.start() } just Runs
every { mockSshClient.properties } returns hashMapOf<String, Any>()
val succeededAuthFuture = DefaultAuthFuture(Any(), Any())
- succeededAuthFuture.value = true //AuthFuture's value is Boolean
+ succeededAuthFuture.value = true // AuthFuture's value is Boolean
val passSlot = CapturingSlot<String>()
every { mockClientSession.addPasswordIdentity(capture(passSlot)) } just Runs
every { mockClientSession.auth() } returns succeededAuthFuture
succeededSessionFuture.value = mockClientSession
every { mockSshClient.connect(deviceInfo.username, deviceInfo.ipAddress, deviceInfo.port) } returns succeededSessionFuture
every { mockClientSession.waitFor(any(), any()) } returns
- setOf(ClientSession.ClientSessionEvent.WAIT_AUTH,
- ClientSession.ClientSessionEvent.CLOSED,
- ClientSession.ClientSessionEvent.AUTHED)
+ setOf(
+ ClientSession.ClientSessionEvent.WAIT_AUTH,
+ ClientSession.ClientSessionEvent.CLOSED,
+ ClientSession.ClientSessionEvent.AUTHED
+ )
every { mockClientSession.createSubsystemChannel(any()) } returns mockSubsystem
every { mockClientChannel.invertedOut } returns sampleInputStream
@Test
fun `authSession opensChannel if ClientSession is AUTHED and session can be opened`() {
- //after client session connects, make sure the client receives authentication
+ // after client session connects, make sure the client receives authentication
setupOpenChannelMocks()
val channelFuture = DefaultOpenFuture(Any(), Any())
channelFuture.value = true
every { netconfSessionSpy["setupNewSSHClient"]() as Unit } just Runs
every { netconfSessionSpy["setupHandler"]() as Unit } just Runs
netconfSessionSpy.setClient(mockSshClient)
- //Run
+ // Run
netconfSessionSpy.connect()
- //Verify
+ // Verify
verify { mockSubsystem.open() }
}
-
@Test
fun `authSession throws NetconfException if ClientSession is AUTHED but channelFuture timed out or not open`() {
assertFailsWith(exceptionClass = NetconfException::class) {
- //after client session connects, make sure the client receives authentication
+ // after client session connects, make sure the client receives authentication
setupOpenChannelMocks()
val channelFuture = DefaultOpenFuture(Any(), Any())
every { mockSubsystem.open() } returns channelFuture
every { netconfSessionSpy["setupNewSSHClient"]() as Unit } just Runs
every { netconfSessionSpy["setupHandler"]() as Unit } just Runs
netconfSessionSpy.setClient(mockSshClient)
- //Run
+ // Run
netconfSessionSpy.connect()
- //Verify
+ // Verify
verify { mockSubsystem.open() }
}
}
-
@Test
fun `disconnect closes session, channel, and client`() {
every { rpcService.closeSession(false) } returns SUCCESSFUL_DEVICE_RESPONSE
netconfSessionSpy.setChannel(mockClientChannel)
netconfSessionSpy.setClient(mockSshClient)
netconfSessionSpy.setSession(mockClientSession)
- //RUN
+ // RUN
netconfSessionSpy.disconnect()
- //VERIFY
+ // VERIFY
verify { mockClientSession.close() }
verify { mockClientChannel.close() }
verify { mockSshClient.close() }
}
@Test
- fun `disconnect wraps IOException if channel doesn't close`() { //this test is equivalent to others
+ fun `disconnect wraps IOException if channel doesn't close`() { // this test is equivalent to others
every { rpcService.closeSession(false) } returns SUCCESSFUL_DEVICE_RESPONSE
every { mockClientSession.close() } just Runs
every { mockClientChannel.close() } throws IOException("channel doesn't want to close!")
netconfSessionSpy.setChannel(mockClientChannel)
netconfSessionSpy.setClient(mockSshClient)
netconfSessionSpy.setSession(mockClientSession)
- //RUN
+ // RUN
netconfSessionSpy.disconnect()
- //VERIFY
+ // VERIFY
verify { mockClientSession.close() }
}
}
package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core
-import org.junit.Test
import io.mockk.every
import io.mockk.mockk
import io.mockk.verifyAll
import org.junit.Before
+import org.junit.Test
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo
import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfReceivedEvent
class NetconfSessionListenerImplTest {
- //Note: mockk's verifyAll is akin to verify with verifyNoMoreInteractions in Mockito
+ // Note: mockk's verifyAll is akin to verify with verifyNoMoreInteractions in Mockito
private val netconSession = mockk<NetconfSessionImpl>()
@Before
}
@Test
- //NetconfReceivedEvent wth DEVICE_UNREGISTERED TYPE should call disconnect() on the NetconfSession
+ // NetconfReceivedEvent wth DEVICE_UNREGISTERED TYPE should call disconnect() on the NetconfSession
fun deviceUnregisteredMessageShouldCallSessionDisconnect() {
val netconfSessionListener = NetconfSessionListenerImpl(netconSession)
val event: NetconfReceivedEvent = genEventByType(NetconfReceivedEvent.Type.DEVICE_UNREGISTERED)
}
@Test
- //NetconfReceivedEvent wth SESSION_CLOSED TYPE should ALSO call disconnect() on the NetconfSession
+ // NetconfReceivedEvent wth SESSION_CLOSED TYPE should ALSO call disconnect() on the NetconfSession
fun sessionClosedMessageShouldCallSesionDisconnect() {
val netconfSessionListener = NetconfSessionListenerImpl(netconSession)
val event: NetconfReceivedEvent = genEventByType(NetconfReceivedEvent.Type.SESSION_CLOSED)
}
@Test
- //NetconfReceivedEvent wth DEVICE_ERROR TYPE should call addDeviceErrorReply() on the NetconfSession
- //with the event message payload
+ // NetconfReceivedEvent wth DEVICE_ERROR TYPE should call addDeviceErrorReply() on the NetconfSession
+ // with the event message payload
fun deviceErrorMessageShouldCallAddDeviceErrorReply() {
val netconfSessionListener = NetconfSessionListenerImpl(netconSession)
val event: NetconfReceivedEvent = genEventByType(NetconfReceivedEvent.Type.DEVICE_ERROR)
}
@Test
- //NetconfReceivedEvent wth DEVICE_REPLY TYPE should call addDeviceReply(messageId, payload) on the NetconfSession
+ // NetconfReceivedEvent wth DEVICE_REPLY TYPE should call addDeviceReply(messageId, payload) on the NetconfSession
fun deviceReplyMessageShouldCallAddDeviceReply() {
val netconfSessionListener = NetconfSessionListenerImpl(netconSession)
val event: NetconfReceivedEvent = genEventByType(NetconfReceivedEvent.Type.DEVICE_REPLY)
/**
* Helper to generate {@link NetconfReceivedEvent} object based on the {@link NetconfReceivedEvent.Type}
- * @param type {@link NetconfReceivedEvent.Type} of event
+ * @param type {@link NetconfReceivedEvent.Type} of event
*/
private fun genEventByType(type: NetconfReceivedEvent.Type): NetconfReceivedEvent {
return NetconfReceivedEvent(
- type,
- "messagePayload",
- "messageId",
- DeviceInfo()
+ type,
+ "messagePayload",
+ "messageId",
+ DeviceInfo()
)
}
-}
\ No newline at end of file
+}
@Test
fun `test getConfig with filterContent parameter null`() {
- val outcome = NetconfMessageUtils.getConfig("customMessageId", "customConfigType",null)
+ val outcome = NetconfMessageUtils.getConfig("customMessageId", "customConfigType", null)
val expectation = JacksonUtils.getClassPathFileContent("netconf-messages/getConfig-response-filterContent-null.xml")
assertEquals("getConfig return was not correct", expectation, outcome)
}
@Test
fun `test editConfig with all parameters present`() {
- val outcome = NetconfMessageUtils.editConfig("customMessageId", "customConfigType", "customDefaultOperation",
- "customNewConfiguration")
+ val outcome = NetconfMessageUtils.editConfig(
+ "customMessageId", "customConfigType", "customDefaultOperation",
+ "customNewConfiguration"
+ )
val expectation = JacksonUtils.getClassPathFileContent("netconf-messages/editConfig-response-all-parameters.xml")
assertEquals("editConfig return was not correct", expectation, outcome)
}
@Test
fun `test editConfig with defaultOperation parameter null`() {
- val outcome = NetconfMessageUtils.editConfig("customMessageId", "customConfigType", null,
- "customNewConfiguration")
+ val outcome = NetconfMessageUtils.editConfig(
+ "customMessageId", "customConfigType", null,
+ "customNewConfiguration"
+ )
val expectation = JacksonUtils.getClassPathFileContent("netconf-messages/editConfig-response-defaultOperation-null.xml")
assertEquals("editConfig return was not correct", expectation, outcome)
}
@Test
fun `test commit with confirmed true, persistId empty and persist empty`() {
val outcome = NetconfMessageUtils.commit("customMessageId", true, 1, "", "")
- val expectation = JacksonUtils.getClassPathFileContent("netconf-messages/commit-response-confirmed-true-and-persistId-empty-and-persist-empty.xml")
+ val expectation =
+ JacksonUtils.getClassPathFileContent("netconf-messages/commit-response-confirmed-true-and-persistId-empty-and-persist-empty.xml")
assertEquals("commit return was not correct", expectation, outcome)
}
@Test
fun `test commit with confirmed false, persistId non-empty and persist empty`() {
val outcome = NetconfMessageUtils.commit("customMessageId", false, 1, "", "customPersistId")
- val expectation = JacksonUtils.getClassPathFileContent("netconf-messages/commit-response-confirmed-false-and-persistId-empty-and-persist-not-empty.xml")
+ val expectation =
+ JacksonUtils.getClassPathFileContent("netconf-messages/commit-response-confirmed-false-and-persistId-empty-and-persist-not-empty.xml")
assertEquals("commit return was not correct", expectation, outcome)
}
@Test
fun `test commit with confirmed false, persistId empty and persist non-empty`() {
val outcome = NetconfMessageUtils.commit("customMessageId", false, 1, "customPersist", "")
- val expectation = JacksonUtils.getClassPathFileContent("netconf-messages/commit-response-confirmed-false-and-persistId-not-empty-and-persist-empty.xml")
+ val expectation =
+ JacksonUtils.getClassPathFileContent("netconf-messages/commit-response-confirmed-false-and-persistId-not-empty-and-persist-empty.xml")
assertEquals("commit return was not correct", expectation, outcome)
}
assertEquals("closeSession return was not correct", expectation, outcome)
}
- //TODO validateRPCXML
+ // TODO validateRPCXML
@Test
fun `test getMsgId with valid message`() {
assertEquals("getMsgId return was not correct", expectation, outcome)
}
-//TODO validateChunkedFraming
-
+ // TODO validateChunkedFraming
}
@Test
fun getConfig() {
- val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
- + "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
- + "<get-config><source><candidate/></source><filter type=\"subtree\">Test-Filter-Content</filter>"
- + "</get-config></rpc>")
+ val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<get-config><source><candidate/></source><filter type=\"subtree\">Test-Filter-Content</filter>" +
+ "</get-config></rpc>")
val messageId = "Test-Message-ID"
val configType = NetconfDatastore.CANDIDATE.datastore
val filterContent = "Test-Filter-Content"
val result =
- NetconfMessageUtils.getConfig(messageId, configType, filterContent).replace("[\n\r\t]".toRegex(), "")
+ NetconfMessageUtils.getConfig(messageId, configType, filterContent).replace("[\n\r\t]".toRegex(), "")
assertTrue(NetconfMessageUtils.validateRPCXML(result))
Assert.assertEquals(checkString, result)
}
-
@Test
fun editConfig() {
- val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
- + "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
- + "<edit-config><target><candidate/></target><default-operation>Test-Default-Operation</default-operation>"
- + "<config xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">Test-Filter-Content</config></edit-config></rpc>")
+ val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<edit-config><target><candidate/></target><default-operation>Test-Default-Operation</default-operation>" +
+ "<config xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">Test-Filter-Content</config></edit-config></rpc>")
val messageId = "Test-Message-ID"
val configType = NetconfDatastore.CANDIDATE.datastore
val defaultOperation = "Test-Default-Operation"
val result =
- NetconfMessageUtils.editConfig(messageId, configType, defaultOperation, filterContent).replace("[\n\r\t]".toRegex(), "")
+ NetconfMessageUtils.editConfig(messageId, configType, defaultOperation, filterContent).replace("[\n\r\t]".toRegex(), "")
assertTrue(NetconfMessageUtils.validateRPCXML(result))
Assert.assertEquals(checkString, result)
@Test
fun validate() {
- val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
- + "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
- + "<validate><source><candidate/></source></validate></rpc>")
+ val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<validate><source><candidate/></source></validate></rpc>")
val messageId = "Test-Message-ID"
val configType = NetconfDatastore.CANDIDATE.datastore
@Test
fun cancelCommit() {
val checkString =
- ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
- "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
- "<cancel-commit>" +
- "<persist-id>1234</persist-id>" +
- "</cancel-commit></rpc>")
+ ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<cancel-commit>" +
+ "<persist-id>1234</persist-id>" +
+ "</cancel-commit></rpc>")
val messageId = "Test-Message-ID"
val cancelCommitPersistId =
- NetconfMessageUtils.cancelCommit(messageId, "1234").replace("[\n\r\t]".toRegex(), "")
+ NetconfMessageUtils.cancelCommit(messageId, "1234").replace("[\n\r\t]".toRegex(), "")
assertTrue(NetconfMessageUtils.validateRPCXML(cancelCommitPersistId))
Assert.assertEquals(checkString, cancelCommitPersistId)
@Test
fun cancelCommitNoPersistId() {
val checkString =
- ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
- "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
- "<cancel-commit>" +
- "</cancel-commit></rpc>")
+ ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<cancel-commit>" +
+ "</cancel-commit></rpc>")
val messageId = "Test-Message-ID"
@Test
fun commit() {
- val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
- + "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
- + "<commit></commit></rpc>")
+ val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<commit></commit></rpc>")
val messageId = "Test-Message-ID"
val commit = NetconfMessageUtils.commit(messageId, false, 0, "", "").replace("[\n\r\t]".toRegex(), "")
val commitWithPersistButNotConfirmed =
- NetconfMessageUtils.commit(messageId, false, 0, "1234", "").replace("[\n\r\t]".toRegex(), "")
+ NetconfMessageUtils.commit(messageId, false, 0, "1234", "").replace("[\n\r\t]".toRegex(), "")
assertTrue(NetconfMessageUtils.validateRPCXML(commit))
Assert.assertEquals(checkString, commit)
Assert.assertEquals(checkString, commitWithPersistButNotConfirmed)
-
}
@Test
fun commitPersistId() {
val checkString =
- ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
- "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
- "<commit>" +
- "<persist-id>1234</persist-id>" +
- "</commit></rpc>")
+ ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<commit>" +
+ "<persist-id>1234</persist-id>" +
+ "</commit></rpc>")
val messageId = "Test-Message-ID"
try {
NetconfMessageUtils.commit(messageId, true, 30, "", "1234").replace("[\n\r\t]".toRegex(), "")
} catch (e: NetconfException) {
- Assert.assertEquals("Can't proceed <commit> with both confirmed flag and persistId(1234) specified. Only one should be specified.",
- e.message)
+ Assert.assertEquals(
+ "Can't proceed <commit> with both confirmed flag and persistId(1234) specified. Only one should be specified.",
+ e.message
+ )
return
}
@Test
fun commitPersist() {
val checkString =
- ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
- "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
- "<commit>" +
- "<confirmed/>" +
- "<confirm-timeout>30</confirm-timeout>" +
- "<persist>1234</persist>" +
- "</commit></rpc>")
+ ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<commit>" +
+ "<confirmed/>" +
+ "<confirm-timeout>30</confirm-timeout>" +
+ "<persist>1234</persist>" +
+ "</commit></rpc>")
val messageId = "Test-Message-ID"
try {
NetconfMessageUtils.commit(messageId, false, 30, "1234", "1234").replace("[\n\r\t]".toRegex(), "")
} catch (e: NetconfException) {
- Assert.assertEquals("Can't proceed <commit> with both persist(1234) and persistId(1234) specified. Only one should be specified.",
- e.message)
+ Assert.assertEquals(
+ "Can't proceed <commit> with both persist(1234) and persistId(1234) specified. Only one should be specified.",
+ e.message
+ )
return
}
fail()
@Test
fun unlock() {
- val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
- + "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
- + "<unlock><target><candidate/></target></unlock></rpc>")
+ val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<unlock><target><candidate/></target></unlock></rpc>")
val messageId = "Test-Message-ID"
val configType = NetconfDatastore.CANDIDATE.datastore
@Test
fun deleteConfig() {
- val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
- + "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
- + "<delete-config><target><candidate/></target></delete-config></rpc>")
+ val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<delete-config><target><candidate/></target></delete-config></rpc>")
val messageId = "Test-Message-ID"
val netconfTargetConfig = NetconfDatastore.CANDIDATE.datastore
@Test
fun discardChanges() {
- val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
- + "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
- + "<discard-changes/></rpc>")
+ val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<discard-changes/></rpc>")
val messageId = "Test-Message-ID"
@Test
fun lock() {
- val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
- + "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
- + "<lock><target><candidate/></target></lock></rpc>")
+ val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<rpc message-id=\"Test-Message-ID\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
+ "<lock><target><candidate/></target></lock></rpc>")
val messageId = "Test-Message-ID"
val configType = NetconfDatastore.CANDIDATE.datastore
@Test
fun createHelloString() {
- val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?><hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"> "
- +"<capabilities> <capability>hi</capability> <capability>hello</capability> </capabilities></hello>]]>]]>")
+ val checkString = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?><hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"> " +
+ "<capabilities> <capability>hi</capability> <capability>hello</capability> </capabilities></hello>]]>]]>")
val capability = listOf<String>("hi", "hello")
}
@Test
- fun formatRPCRequest(){
+ fun formatRPCRequest() {
val checkString = ("#199" +
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"> <capabilities> <capability>hi</capability> <capability>hello</capability> </capabilities></hello>" +
"##")
- val request = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?><hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"> "
- +"<capabilities> <capability>hi</capability> <capability>hello</capability> </capabilities></hello>]]>]]>")
+ val request = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?><hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"> " +
+ "<capabilities> <capability>hi</capability> <capability>hello</capability> </capabilities></hello>]]>]]>")
val messageId = "Test-Message-ID"
- val capabilities = setOf<String>("hi", "hello","urn:ietf:params:netconf:base:1.1")
+ val capabilities = setOf<String>("hi", "hello", "urn:ietf:params:netconf:base:1.1")
- val result = NetconfMessageUtils.formatRPCRequest(request,messageId,capabilities).replace("[\n\r\t]".toRegex(), "")
+ val result = NetconfMessageUtils.formatRPCRequest(request, messageId, capabilities).replace("[\n\r\t]".toRegex(), "")
Assert.assertEquals(checkString, result)
}
println("Don't fear \"[Fatal Error] :1:1: Content is not allowed in prolog.\" TODO: adjust logging for NetconfMessageUtils")
assertFalse { NetconfMessageUtils.validateRPCXML("really bad XML ~~~input") }
}
-
}
@Component("component-jython-executor")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ComponentJythonExecutor(private var applicationContext: ApplicationContext,
- private val blueprintJythonService: BlueprintJythonService) : AbstractComponentFunction() {
+open class ComponentJythonExecutor(
+ private var applicationContext: ApplicationContext,
+ private val blueprintJythonService: BlueprintJythonService
+) : AbstractComponentFunction() {
private val log = LoggerFactory.getLogger(ComponentJythonExecutor::class.java)
// Invoke Jython Component Script
componentFunction.executeScript(executionServiceInput)
-
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
bluePrintRuntimeService.getBluePrintError()
- .addError("Failed in ComponentJythonExecutor : ${runtimeException.message}")
+ .addError("Failed in ComponentJythonExecutor : ${runtimeException.message}")
}
private fun populateJythonComponentInstance() {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
val operationAssignment: OperationAssignment = bluePrintContext
- .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
+ .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
val artifactName: String = operationAssignment.implementation?.primary
- ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
+ ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
val pythonFileName = artifactDefinition.file
- ?: throw BluePrintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)")
+ ?: throw BluePrintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)")
val pythonClassName = FilenameUtils.getBaseName(pythonFileName)
checkNotEmpty(content) { "artifact ($artifactName) content is empty" }
val instanceDependenciesNode: ArrayNode = operationInputs[PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES] as? ArrayNode
- ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})")
+ ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})")
val jythonInstance: MutableMap<String, Any> = hashMapOf()
jythonInstance["log"] = LoggerFactory.getLogger(pythonClassName)
componentFunction.workflowName = workflowName
componentFunction.scriptType = BluePrintConstants.SCRIPT_JYTHON
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor
import com.fasterxml.jackson.databind.JsonNode
-import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
+import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
@ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
@Component("component-remote-python-executor")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ComponentRemotePythonExecutor(private val remoteScriptExecutionService: RemoteScriptExecutionService)
- : AbstractComponentFunction() {
+open class ComponentRemotePythonExecutor(private val remoteScriptExecutionService: RemoteScriptExecutionService) : AbstractComponentFunction() {
private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
// If packages are defined, then install in remote server
if (packages != null) {
- val prepareEnvInput = PrepareRemoteEnvInput(requestId = processId,
- remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName,
- blueprintVersion = blueprintVersion),
+ val prepareEnvInput = PrepareRemoteEnvInput(
+ requestId = processId,
+ remoteIdentifier = RemoteIdentifier(
+ blueprintName = blueprintName,
+ blueprintVersion = blueprintVersion
+ ),
packages = packages
)
val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
val remoteExecutionInput = RemoteScriptExecutionInput(
- requestId = processId,
- remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
- command = scriptCommand,
- properties = properties)
+ requestId = processId,
+ remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
+ command = scriptCommand,
+ properties = properties
+ )
val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
if (remoteExecutionOutput.status != StatusType.SUCCESS) {
setNodeOutputErrors(remoteExecutionOutput.status.name, logs, remoteExecutionOutput.payload)
} else {
- setNodeOutputProperties(remoteExecutionOutput.status.name.asJsonPrimitive(), logs,
- remoteExecutionOutput.payload)
+ setNodeOutputProperties(
+ remoteExecutionOutput.status.name.asJsonPrimitive(), logs,
+ remoteExecutionOutput.payload
+ )
}
}
} catch (e: Exception) {
/**
* Utility function to set the output properties and errors of the executor node, in cas of errors
*/
- private fun setNodeOutputErrors(status: String, message: JsonNode, artifacts: JsonNode = "".asJsonPrimitive() ) {
+ private fun setNodeOutputErrors(status: String, message: JsonNode, artifacts: JsonNode = "".asJsonPrimitive()) {
setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
log.info("Executor status : $status")
setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
/** Component Extensions **/
fun BluePrintTypes.nodeTypeComponentRemotePythonExecutor(): NodeType {
- return nodeType(id = "component-remote-python-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
- description = "This is Remote Python Execution Component.") {
-
- attribute(ComponentRemotePythonExecutor.ATTRIBUTE_PREPARE_ENV_LOG, BluePrintConstants.DATA_TYPE_STRING,
- false)
- attribute(ComponentRemotePythonExecutor.ATTRIBUTE_EXEC_CMD_LOG, BluePrintConstants.DATA_TYPE_LIST,
- false) {
+ return nodeType(
+ id = "component-remote-python-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
+ description = "This is Remote Python Execution Component."
+ ) {
+
+ attribute(
+ ComponentRemotePythonExecutor.ATTRIBUTE_PREPARE_ENV_LOG, BluePrintConstants.DATA_TYPE_STRING,
+ false
+ )
+ attribute(
+ ComponentRemotePythonExecutor.ATTRIBUTE_EXEC_CMD_LOG, BluePrintConstants.DATA_TYPE_LIST,
+ false
+ ) {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
- attribute(ComponentRemotePythonExecutor.ATTRIBUTE_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON,
- false)
+ attribute(
+ ComponentRemotePythonExecutor.ATTRIBUTE_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON,
+ false
+ )
operation("ComponentRemotePythonExecutor", "ComponentRemotePythonExecutor Operation") {
inputs {
- property(ComponentRemotePythonExecutor.INPUT_ENDPOINT_SELECTOR, BluePrintConstants.DATA_TYPE_STRING,
- false, "Remote Container or Server selector name.") {
+ property(
+ ComponentRemotePythonExecutor.INPUT_ENDPOINT_SELECTOR, BluePrintConstants.DATA_TYPE_STRING,
+ false, "Remote Container or Server selector name."
+ ) {
defaultValue(ComponentRemotePythonExecutor.DEFAULT_SELECTOR)
}
- property(ComponentRemotePythonExecutor.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
- false, "Dynamic Json Content or DSL Json reference.")
-
- property(ComponentRemotePythonExecutor.INPUT_ARGUMENT_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
- false, "Argument Json Content or DSL Json reference.")
-
- property(ComponentRemotePythonExecutor.INPUT_COMMAND, BluePrintConstants.DATA_TYPE_STRING,
- true, "Command to execute.")
-
- property(ComponentRemotePythonExecutor.INPUT_PACKAGES, BluePrintConstants.DATA_TYPE_LIST,
- false, "Packages to install based on type.") {
+ property(
+ ComponentRemotePythonExecutor.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
+ false, "Dynamic Json Content or DSL Json reference."
+ )
+
+ property(
+ ComponentRemotePythonExecutor.INPUT_ARGUMENT_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
+ false, "Argument Json Content or DSL Json reference."
+ )
+
+ property(
+ ComponentRemotePythonExecutor.INPUT_COMMAND, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Command to execute."
+ )
+
+ property(
+ ComponentRemotePythonExecutor.INPUT_PACKAGES, BluePrintConstants.DATA_TYPE_LIST,
+ false, "Packages to install based on type."
+ ) {
entrySchema("dt-system-packages")
}
}
}
fun BluePrintTypes.dataTypeDtSystemPackages(): DataType {
- return dataType(id = "dt-system-packages", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT,
- description = "This represent System Package Data Type") {
+ return dataType(
+ id = "dt-system-packages", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT,
+ description = "This represent System Package Data Type"
+ ) {
property("type", BluePrintConstants.DATA_TYPE_LIST, true, "") {
constrain {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
/** Component Builder */
-fun BluePrintTypes.nodeTemplateComponentRemotePythonExecutor(id: String,
- description: String,
- block: ComponentRemotePythonExecutorNodeTemplateBuilder.() -> Unit)
- : NodeTemplate {
+fun BluePrintTypes.nodeTemplateComponentRemotePythonExecutor(
+ id: String,
+ description: String,
+ block: ComponentRemotePythonExecutorNodeTemplateBuilder.() -> Unit
+):
+ NodeTemplate {
return ComponentRemotePythonExecutorNodeTemplateBuilder(id, description).apply(block).build()
}
}
class ComponentRemotePythonExecutorNodeTemplateBuilder(id: String, description: String) :
- AbstractNodeTemplateOperationImplBuilder<PropertiesAssignmentBuilder, ComponentRemotePythonExecutorNodeTemplateBuilder.InputsBuilder,
- ComponentRemotePythonExecutorNodeTemplateBuilder.OutputsBuilder>(id, "component-remote-python-executor",
- "ComponentRemotePythonExecutor", description) {
+ AbstractNodeTemplateOperationImplBuilder<PropertiesAssignmentBuilder, ComponentRemotePythonExecutorNodeTemplateBuilder.InputsBuilder,
+ ComponentRemotePythonExecutorNodeTemplateBuilder.OutputsBuilder>(
+ id, "component-remote-python-executor",
+ "ComponentRemotePythonExecutor", description
+ ) {
class InputsBuilder : PropertiesAssignmentBuilder() {
}
class OutputsBuilder : PropertiesAssignmentBuilder()
-
-}
\ No newline at end of file
+}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
throw BluePrintException("Not Implemented required")
}
-
-}
\ No newline at end of file
+}
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [PythonExecutorConfiguration::class, PythonExecutorProperty::class,
- ComponentJythonExecutor::class, MockInstanceConfiguration::class])
-@TestPropertySource(properties =
-["blueprints.processor.functions.python.executor.modulePaths=./../../../../components/scripts/python/ccsdk_blueprints",
- "blueprints.processor.functions.python.executor.executionPath=./../../../../components/scripts/python/ccsdk_blueprints"])
+@ContextConfiguration(
+ classes = [PythonExecutorConfiguration::class, PythonExecutorProperty::class,
+ ComponentJythonExecutor::class, MockInstanceConfiguration::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprints.processor.functions.python.executor.modulePaths=./../../../../components/scripts/python/ccsdk_blueprints",
+ "blueprints.processor.functions.python.executor.executionPath=./../../../../components/scripts/python/ccsdk_blueprints"]
+)
class ComponentJythonExecutorTest {
@Autowired
fun testPythonComponentInjection() {
runBlocking {
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("payload/requests/sample-activate-request.json",
- ExecutionServiceInput::class.java)!!
+ val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
+ "payload/requests/sample-activate-request.json",
+ ExecutionServiceInput::class.java
+ )!!
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val stepMetaData: MutableMap<String, JsonNode> = hashMapOf()
stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-jython")
executionServiceInput.stepData = stepInputData
componentJythonExecutor.applyNB(executionServiceInput)
}
-
}
-}
\ No newline at end of file
+}
@Test
fun testNodeTypeComponentRemotePythonExecutor() {
val nodeType = BluePrintTypes.nodeTypeComponentRemotePythonExecutor()
- //println(nodeType.asJsonString(true))
+ // println(nodeType.asJsonString(true))
assertNotNull(nodeType, "failed to generate nodeTypeComponentRemotePythonExecutor")
}
@Test
fun testNodeTemplateComponentRemotePythonExecutor() {
- val nodeTemplate = BluePrintTypes.nodeTemplateComponentRemotePythonExecutor("test-nodetemplate",
- "test nodetemplate") {
+ val nodeTemplate = BluePrintTypes.nodeTemplateComponentRemotePythonExecutor(
+ "test-nodetemplate",
+ "test nodetemplate"
+ ) {
definedOperation("test operation") {
inputs {
endpointSelector("remote-container")
command("python sample.py")
- dynamicProperties("""{
+ dynamicProperties(
+ """{
"prop1" : "1234",
"prop2" : true,
"prop3" : 23
- }""".trimIndent())
+ }""".trimIndent()
+ )
argumentProperties("""["one", "two"]""")
packages {
type("pip")
}
}
}
- //println(nodeTemplate.asJsonString(true))
+ // println(nodeTemplate.asJsonString(true))
assertNotNull(nodeTemplate, "failed to generate nodeTemplateComponentRemotePythonExecutor")
}
-}
\ No newline at end of file
+}
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import org.junit.Test
-import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionOutput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
-
class ComponentRemotePythonExecutorTest {
@Test
val componentRemotePythonExecutor = ComponentRemotePythonExecutor(remoteScriptExecutionService)
val executionServiceInput =
- JacksonUtils.readValueFromClassPathFile("payload/requests/sample-remote-python-request.json",
- ExecutionServiceInput::class.java)!!
-
+ JacksonUtils.readValueFromClassPathFile(
+ "payload/requests/sample-remote-python-request.json",
+ ExecutionServiceInput::class.java
+ )!!
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("123456-1000",
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "123456-1000",
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts"
+ )
/** Load Workflow Inputs */
- bluePrintRuntimeService.assignWorkflowInputs("execute-remote-python",
- executionServiceInput.payload.get("execute-remote-python-request"))
+ bluePrintRuntimeService.assignWorkflowInputs(
+ "execute-remote-python",
+ executionServiceInput.payload.get("execute-remote-python-request")
+ )
val stepMetaData: MutableMap<String, JsonNode> = hashMapOf()
stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "execute-remote-python")
val stepMetaData: MutableMap<String, JsonNode> = hashMapOf()
stepMetaData.putJsonElement(
- BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE,
- "execute-remote-python")
+ BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE,
+ "execute-remote-python"
+ )
stepMetaData.putJsonElement(
- BluePrintConstants.PROPERTY_CURRENT_INTERFACE,
- "ComponentRemotePythonExecutor")
+ BluePrintConstants.PROPERTY_CURRENT_INTERFACE,
+ "ComponentRemotePythonExecutor"
+ )
stepMetaData.putJsonElement(
- BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process")
+ BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process"
+ )
val mapper = ObjectMapper()
val rootNode = mapper.createObjectNode()
val operationalInputs: MutableMap<String, JsonNode> = hashMapOf()
operationalInputs.putJsonElement(
- BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE,
- "execute-remote-python")
+ BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE,
+ "execute-remote-python"
+ )
operationalInputs.putJsonElement(
- BluePrintConstants.PROPERTY_CURRENT_INTERFACE,
- "ComponentRemotePythonExecutor")
+ BluePrintConstants.PROPERTY_CURRENT_INTERFACE,
+ "ComponentRemotePythonExecutor"
+ )
operationalInputs.putJsonElement(
- BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process")
+ BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process"
+ )
operationalInputs.putJsonElement("endpoint-selector", "aai")
operationalInputs.putJsonElement("dynamic-properties", rootNode)
operationalInputs.putJsonElement("command", "./run.sh")
every {
svc.resolveNodeTemplateInterfaceOperationInputs(
- "execute-remote-python",
- "ComponentRemotePythonExecutor", "process")
+ "execute-remote-python",
+ "ComponentRemotePythonExecutor", "process"
+ )
} returns operationalInputs
val stepInputData = StepData().apply {
}
val executionServiceInput = JacksonUtils
- .readValueFromClassPathFile(
- "payload/requests/sample-remote-python-request.json",
- ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile(
+ "payload/requests/sample-remote-python-request.json",
+ ExecutionServiceInput::class.java
+ )!!
executionServiceInput.stepData = stepInputData
val operationOutputs = hashMapOf<String, JsonNode>()
every {
svc.resolveNodeTemplateInterfaceOperationOutputs(
- "execute-remote-python",
- "ComponentRemotePythonExecutor", "process")
+ "execute-remote-python",
+ "ComponentRemotePythonExecutor", "process"
+ )
} returns operationOutputs
val bluePrintRuntimeService = BluePrintMetadataUtils
- .getBluePrintRuntime("123456-1000",
- "./../../../../components/model-" +
- "catalog/blueprint-model/test-blueprint/" +
- "remote_scripts")
+ .getBluePrintRuntime(
+ "123456-1000",
+ "./../../../../components/model-" +
+ "catalog/blueprint-model/test-blueprint/" +
+ "remote_scripts"
+ )
every {
svc.resolveNodeTemplateArtifactDefinition(
- "execute-remote-python", "component-script")
+ "execute-remote-python", "component-script"
+ )
} returns bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(
- "execute-remote-python", "component-script")
+ "execute-remote-python", "component-script"
+ )
every {
svc.setNodeTemplateAttributeValue(
- "execute-remote-python", "prepare-environment-logs",
- "prepared successfully".asJsonPrimitive())
+ "execute-remote-python", "prepare-environment-logs",
+ "prepared successfully".asJsonPrimitive()
+ )
} returns Unit
every {
svc.setNodeTemplateAttributeValue(
- "execute-remote-python",
- "execute-command-logs", "N/A".asJsonPrimitive())
+ "execute-remote-python",
+ "execute-command-logs", "N/A".asJsonPrimitive()
+ )
} returns Unit
every {
svc.setNodeTemplateAttributeValue(
- "execute-remote-python",
- "execute-command-logs",
- "processed successfully".asJsonPrimitive())
+ "execute-remote-python",
+ "execute-command-logs",
+ "processed successfully".asJsonPrimitive()
+ )
} returns Unit
every {
}
override suspend fun close() {
-
}
}
@Configuration
open class MockInstanceConfiguration {
+
@Bean(name = ["json-parser-service", "netconf-rpc-service"])
open fun createComponentFunction(): MockJythonService {
return MockJythonService()
}
}
-class MockJythonService {
-
-}
\ No newline at end of file
+class MockJythonService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService
-class ResourceAssignmentRuntimeService(private var id: String, private var bluePrintContext: BluePrintContext)
- : DefaultBluePrintRuntimeService(id, bluePrintContext) {
+class ResourceAssignmentRuntimeService(private var id: String, private var bluePrintContext: BluePrintContext) :
+ DefaultBluePrintRuntimeService(id, bluePrintContext) {
private lateinit var resolutionId: String
private var resourceStore: MutableMap<String, JsonNode> = hashMapOf()
fun getResolutionStore(key: String): JsonNode {
return resourceStore[key]
- ?: throw BluePrintProcessorException("failed to get execution property ($key)")
+ ?: throw BluePrintProcessorException("failed to get execution property ($key)")
}
fun checkResolutionStore(key: String): Boolean {
fun getDictionaryStore(key: String): JsonNode {
return resourceStore["dictionary-$key"]
- ?: throw BluePrintProcessorException("failed to get execution property (dictionary-$key)")
+ ?: throw BluePrintProcessorException("failed to get execution property (dictionary-$key)")
}
fun checkDictionaryStore(key: String): Boolean {
fun getDoubleFromDictionaryStore(key: String): Double? {
return getResolutionStore("dictionary-$key").asDouble()
}
-
}
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
/** Resource Definition DSL **/
-fun BluePrintTypes.resourceDefinitions(block: ResourceDefinitionsBuilder.() -> Unit)
- : MutableMap<String, ResourceDefinition> {
+fun BluePrintTypes.resourceDefinitions(block: ResourceDefinitionsBuilder.() -> Unit):
+ MutableMap<String, ResourceDefinition> {
return ResourceDefinitionsBuilder().apply(block).build()
}
-fun BluePrintTypes.resourceDefinition(name: String, description: String,
- block: ResourceDefinitionBuilder.() -> Unit): ResourceDefinition {
+fun BluePrintTypes.resourceDefinition(
+ name: String,
+ description: String,
+ block: ResourceDefinitionBuilder.() -> Unit
+): ResourceDefinition {
return ResourceDefinitionBuilder(name, description).apply(block).build()
}
/** Resource Mapping DSL **/
-fun BluePrintTypes.resourceAssignments(block: ResourceAssignmentsBuilder.() -> Unit)
- : MutableMap<String, ResourceAssignment> {
+fun BluePrintTypes.resourceAssignments(block: ResourceAssignmentsBuilder.() -> Unit):
+ MutableMap<String, ResourceAssignment> {
return ResourceAssignmentsBuilder().apply(block).build()
}
-fun BluePrintTypes.resourceAssignment(name: String, dictionaryName: String, dictionarySource: String,
- block: ResourceAssignmentBuilder.() -> Unit): ResourceAssignment {
+fun BluePrintTypes.resourceAssignment(
+ name: String,
+ dictionaryName: String,
+ dictionarySource: String,
+ block: ResourceAssignmentBuilder.() -> Unit
+): ResourceAssignment {
return ResourceAssignmentBuilder(name, dictionaryName, dictionarySource).apply(block).build()
}
class ResourceDefinitionsBuilder() {
private val resourceDefinitions: MutableMap<String, ResourceDefinition> = hashMapOf()
- fun resourceDefinition(name: String, description: String,
- block: ResourceDefinitionBuilder.() -> Unit) {
+ fun resourceDefinition(
+ name: String,
+ description: String,
+ block: ResourceDefinitionBuilder.() -> Unit
+ ) {
val resourceDefinition = ResourceDefinitionBuilder(name, description).apply(block).build()
resourceDefinitions[resourceDefinition.name] = resourceDefinition
}
resourceDefinition.property = PropertyDefinitionBuilder(name, type, required, description).build()
}
- fun property(type: String, required: Boolean,
- block: PropertyDefinitionBuilder.() -> Unit) {
+ fun property(
+ type: String,
+ required: Boolean,
+ block: PropertyDefinitionBuilder.() -> Unit
+ ) {
resourceDefinition.property = PropertyDefinitionBuilder(name, type, required, description).apply(block).build()
}
class ResourceAssignmentsBuilder() {
private val resourceAssignments: MutableMap<String, ResourceAssignment> = hashMapOf()
- fun resourceAssignment(name: String, dictionaryName: String, dictionarySource: String,
- block: ResourceAssignmentBuilder.() -> Unit) {
+ fun resourceAssignment(
+ name: String,
+ dictionaryName: String,
+ dictionarySource: String,
+ block: ResourceAssignmentBuilder.() -> Unit
+ ) {
val resourceAssignment = ResourceAssignmentBuilder(name, dictionaryName, dictionarySource).apply(block).build()
resourceAssignments[resourceAssignment.name] = resourceAssignment
}
}
}
-class ResourceAssignmentBuilder(private val name: String, private val dictionaryName: String,
- private val dictionarySource: String) {
+class ResourceAssignmentBuilder(
+ private val name: String,
+ private val dictionaryName: String,
+ private val dictionarySource: String
+) {
+
private val resourceAssignment = ResourceAssignment()
fun inputParameter(inputParameter: Boolean) {
resourceAssignment.property = PropertyDefinitionBuilder(name, type, required, description).build()
}
- fun property(type: String, required: Boolean, description: String? = "",
- block: PropertyDefinitionBuilder.() -> Unit) {
+ fun property(
+ type: String,
+ required: Boolean,
+ description: String? = "",
+ block: PropertyDefinitionBuilder.() -> Unit
+ ) {
resourceAssignment.property = PropertyDefinitionBuilder(name, type, required, description).apply(block).build()
}
fun sourceInput(block: SourceInputNodeTemplateBuilder.() -> Unit) {
resourceAssignment.dictionarySourceDefinition = SourceInputNodeTemplateBuilder(dictionarySource, "")
- .apply(block).build()
+ .apply(block).build()
}
fun sourceDefault(block: SourceDefaultNodeTemplateBuilder.() -> Unit) {
resourceAssignment.dictionarySourceDefinition = SourceDefaultNodeTemplateBuilder(dictionarySource, "")
- .apply(block).build()
+ .apply(block).build()
}
fun sourceDb(block: SourceDbNodeTemplateBuilder.() -> Unit) {
resourceAssignment.dictionarySourceDefinition = SourceDbNodeTemplateBuilder(dictionarySource, "")
- .apply(block).build()
+ .apply(block).build()
}
fun sourceRest(block: SourceRestNodeTemplateBuilder.() -> Unit) {
resourceAssignment.dictionarySourceDefinition = SourceRestNodeTemplateBuilder(dictionarySource, "")
- .apply(block).build()
+ .apply(block).build()
}
fun sourceCapability(block: SourceCapabilityNodeTemplateBuilder.() -> Unit) {
resourceAssignment.dictionarySourceDefinition = SourceCapabilityNodeTemplateBuilder(dictionarySource, "")
- .apply(block).build()
+ .apply(block).build()
}
fun dependencies(dependencies: MutableList<String>) {
resourceAssignment.dictionarySource = dictionarySource
return resourceAssignment
}
-}
\ No newline at end of file
+}
@Component("component-resource-resolution")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
open class ResourceResolutionComponent(private val resourceResolutionService: ResourceResolutionService) :
- AbstractComponentFunction() {
- companion object{
+ AbstractComponentFunction() {
+
+ companion object {
const val INPUT_REQUEST_ID = "request-id"
const val INPUT_RESOURCE_ID = "resource-id"
const val INPUT_ACTION_NAME = "action-name"
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
val occurrence = getOptionalOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE)?.asInt() ?: 1
- val resolutionKey = getOptionalOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY)?.returnNullIfMissing()?.textValue() ?: ""
+ val resolutionKey =
+ getOptionalOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY)?.returnNullIfMissing()?.textValue() ?: ""
val storeResult = getOptionalOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT)?.asBoolean() ?: false
- val resourceId = getOptionalOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID)?.returnNullIfMissing()?.textValue() ?: ""
+ val resourceId =
+ getOptionalOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID)?.returnNullIfMissing()?.textValue() ?: ""
- val resourceType = getOptionalOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE)?.returnNullIfMissing()?.textValue() ?: ""
+ val resourceType =
+ getOptionalOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE)?.returnNullIfMissing()?.textValue() ?: ""
val properties: MutableMap<String, Any> = mutableMapOf()
properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] = storeResult
val jsonResponse = JsonNodeFactory.instance.objectNode()
// Initialize Output Attribute to empty JSON
- bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName,
- ResourceResolutionConstants.OUTPUT_ASSIGNMENT_PARAMS, jsonResponse)
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ResourceResolutionConstants.OUTPUT_ASSIGNMENT_PARAMS, jsonResponse
+ )
// validate inputs if we need to store the resource and template resolution.
if (storeResult) {
} else if ((resourceType.isNotEmpty() && resourceId.isEmpty()) || (resourceType.isEmpty() && resourceId.isNotEmpty())) {
throw BluePrintProcessorException("Can't proceed with the resolution: both resource-id and resource-type should be provided, one of them is missing.")
} else if (resourceType.isEmpty() && resourceId.isEmpty() && resolutionKey.isEmpty()) {
- throw BluePrintProcessorException("Can't proceed with the resolution: can't persist resolution without a correlation key. " +
- "Either provide a resolution-key OR combination of resource-id and resource-type OR set `storeResult` to false.")
+ throw BluePrintProcessorException(
+ "Can't proceed with the resolution: can't persist resolution without a correlation key. " +
+ "Either provide a resolution-key OR combination of resource-id and resource-type OR set `storeResult` to false."
+ )
}
}
for (j in 1..occurrence) {
properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] = j
- val response = resourceResolutionService.resolveResources(bluePrintRuntimeService,
- nodeTemplateName,
- artifactPrefixNames,
- properties)
+ val response = resourceResolutionService.resolveResources(
+ bluePrintRuntimeService,
+ nodeTemplateName,
+ artifactPrefixNames,
+ properties
+ )
// provide indexed result in output if we have multiple resolution
if (occurrence != 1) {
} else {
jsonResponse.setAll(response.asObjectNode())
}
-
}
// Set Output Attributes with resolved value
- bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName,
- ResourceResolutionConstants.OUTPUT_ASSIGNMENT_PARAMS, jsonResponse)
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ nodeTemplateName,
+ ResourceResolutionConstants.OUTPUT_ASSIGNMENT_PARAMS, jsonResponse
+ )
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
bluePrintRuntimeService.getBluePrintError().addError(runtimeException.message!!)
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution
import com.fasterxml.jackson.databind.JsonNode
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
import org.onap.ccsdk.cds.controllerblueprints.core.dsl.AbstractNodeTemplateOperationImplBuilder
import org.onap.ccsdk.cds.controllerblueprints.core.dsl.PropertiesAssignmentBuilder
import org.onap.ccsdk.cds.controllerblueprints.core.dsl.nodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
/** Component Extensions **/
fun BluePrintTypes.nodeTypeComponentResourceResolution(): NodeType {
- return nodeType(id = "component-resource-resolution", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
- description = "Resource Assignment Component") {
-
- attribute(ResourceResolutionComponent.ATTRIBUTE_ASSIGNMENT_PARAM, BluePrintConstants.DATA_TYPE_STRING,
- true)
- attribute(ResourceResolutionComponent.ATTRIBUTE_STATUS, BluePrintConstants.DATA_TYPE_STRING,
- true)
+ return nodeType(
+ id = "component-resource-resolution", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
+ description = "Resource Assignment Component"
+ ) {
+
+ attribute(
+ ResourceResolutionComponent.ATTRIBUTE_ASSIGNMENT_PARAM, BluePrintConstants.DATA_TYPE_STRING,
+ true
+ )
+ attribute(
+ ResourceResolutionComponent.ATTRIBUTE_STATUS, BluePrintConstants.DATA_TYPE_STRING,
+ true
+ )
operation("ResourceResolutionComponent", "ResourceResolutionComponent Operation") {
inputs {
- property(ResourceResolutionComponent.INPUT_REQUEST_ID, BluePrintConstants.DATA_TYPE_STRING,
- true, "Request Id, Unique Id for the request.")
-
- property(ResourceResolutionComponent.INPUT_RESOURCE_ID, BluePrintConstants.DATA_TYPE_STRING,
- false, "Resource Id.")
-
- property(ResourceResolutionComponent.INPUT_ACTION_NAME, BluePrintConstants.DATA_TYPE_STRING,
- false, "Action Name of the process")
-
- property(ResourceResolutionComponent.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
- false, "Dynamic Json Content or DSL Json reference.")
-
- property(ResourceResolutionComponent.INPUT_RESOLUTION_KEY, BluePrintConstants.DATA_TYPE_STRING,
- false, "Key for service instance related correlation.")
-
- property(ResourceResolutionComponent.INPUT_OCCURRENCE, BluePrintConstants.DATA_TYPE_INTEGER,
- false, "Number of time to perform the resolution.") {
+ property(
+ ResourceResolutionComponent.INPUT_REQUEST_ID, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Request Id, Unique Id for the request."
+ )
+
+ property(
+ ResourceResolutionComponent.INPUT_RESOURCE_ID, BluePrintConstants.DATA_TYPE_STRING,
+ false, "Resource Id."
+ )
+
+ property(
+ ResourceResolutionComponent.INPUT_ACTION_NAME, BluePrintConstants.DATA_TYPE_STRING,
+ false, "Action Name of the process"
+ )
+
+ property(
+ ResourceResolutionComponent.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
+ false, "Dynamic Json Content or DSL Json reference."
+ )
+
+ property(
+ ResourceResolutionComponent.INPUT_RESOLUTION_KEY, BluePrintConstants.DATA_TYPE_STRING,
+ false, "Key for service instance related correlation."
+ )
+
+ property(
+ ResourceResolutionComponent.INPUT_OCCURRENCE, BluePrintConstants.DATA_TYPE_INTEGER,
+ false, "Number of time to perform the resolution."
+ ) {
defaultValue(1)
}
- property(ResourceResolutionComponent.INPUT_STORE_RESULT, BluePrintConstants.DATA_TYPE_BOOLEAN,
- false, "Whether or not to store the output.")
+ property(
+ ResourceResolutionComponent.INPUT_STORE_RESULT, BluePrintConstants.DATA_TYPE_BOOLEAN,
+ false, "Whether or not to store the output."
+ )
- property(ResourceResolutionComponent.INPUT_RESOURCE_TYPE, BluePrintConstants.DATA_TYPE_STRING,
- false, "Request type.")
+ property(
+ ResourceResolutionComponent.INPUT_RESOURCE_TYPE, BluePrintConstants.DATA_TYPE_STRING,
+ false, "Request type."
+ )
- property(ResourceResolutionComponent.INPUT_ARTIFACT_PREFIX_NAMES, BluePrintConstants.DATA_TYPE_LIST,
- true, "Template , Resource Assignment Artifact Prefix names") {
+ property(
+ ResourceResolutionComponent.INPUT_ARTIFACT_PREFIX_NAMES, BluePrintConstants.DATA_TYPE_LIST,
+ true, "Template , Resource Assignment Artifact Prefix names"
+ ) {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
}
outputs {
- property(ResourceResolutionComponent.OUTPUT_RESOURCE_ASSIGNMENT_PARAMS, BluePrintConstants.DATA_TYPE_STRING,
- true, "Output Response")
- property(ResourceResolutionComponent.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING,
- true, "Status of the Component Execution ( success or failure )")
+ property(
+ ResourceResolutionComponent.OUTPUT_RESOURCE_ASSIGNMENT_PARAMS, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Output Response"
+ )
+ property(
+ ResourceResolutionComponent.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Status of the Component Execution ( success or failure )"
+ )
}
}
}
}
/** Component Builder */
-fun BluePrintTypes.nodeTemplateComponentResourceResolution(id: String,
- description: String,
- block: ComponentResourceResolutionNodeTemplateBuilder.() -> Unit)
- : NodeTemplate {
+fun BluePrintTypes.nodeTemplateComponentResourceResolution(
+ id: String,
+ description: String,
+ block: ComponentResourceResolutionNodeTemplateBuilder.() -> Unit
+):
+ NodeTemplate {
return ComponentResourceResolutionNodeTemplateBuilder(id, description).apply(block).build()
}
class ComponentResourceResolutionNodeTemplateBuilder(id: String, description: String) :
- AbstractNodeTemplateOperationImplBuilder<PropertiesAssignmentBuilder,
- ComponentResourceResolutionNodeTemplateBuilder.InputsBuilder,
- ComponentResourceResolutionNodeTemplateBuilder.OutputsBuilder>(id, "component-script-executor",
- "ComponentResourceResolution",
- description) {
+ AbstractNodeTemplateOperationImplBuilder<PropertiesAssignmentBuilder,
+ ComponentResourceResolutionNodeTemplateBuilder.InputsBuilder,
+ ComponentResourceResolutionNodeTemplateBuilder.OutputsBuilder>(
+ id, "component-script-executor",
+ "ComponentResourceResolution",
+ description
+ ) {
class InputsBuilder : PropertiesAssignmentBuilder() {
fun artifactPrefixNames(artifactPrefixNames: String) = artifactPrefixNames(artifactPrefixNames.jsonAsJsonType())
fun artifactPrefixNames(artifactPrefixNameList: List<String>) =
- artifactPrefixNames(artifactPrefixNameList.asJsonString())
+ artifactPrefixNames(artifactPrefixNameList.asJsonString())
fun artifactPrefixNames(artifactPrefixNames: JsonNode) {
property(ResourceResolutionComponent.INPUT_ARTIFACT_PREFIX_NAMES, artifactPrefixNames)
}
fun resourceAssignmentParams(resourceAssignmentParams: String) =
- resourceAssignmentParams(resourceAssignmentParams.asJsonType())
+ resourceAssignmentParams(resourceAssignmentParams.asJsonType())
fun resourceAssignmentParams(resourceAssignmentParams: JsonNode) {
property(ResourceResolutionComponent.OUTPUT_RESOURCE_ASSIGNMENT_PARAMS, resourceAssignmentParams)
}
}
-}
\ No newline at end of file
+}
@Configuration
@ComponentScan
open class ResourceResolutionConfiguration
-
-
object ResourceResolutionConstants {
- const val SERVICE_RESOURCE_RESOLUTION = "resource-resolution-service"
- const val PREFIX_RESOURCE_RESOLUTION_PROCESSOR = "rr-processor-"
- const val INPUT_ARTIFACT_PREFIX_NAMES = "artifact-prefix-names"
- const val OUTPUT_ASSIGNMENT_PARAMS = "assignment-params"
- const val FILE_NAME_RESOURCE_DEFINITION_TYPES = "resources_definition_types.json"
- const val RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY = "resolution-key"
- const val RESOURCE_RESOLUTION_INPUT_STORE_RESULT = "store-result"
- const val RESOURCE_RESOLUTION_INPUT_OCCURRENCE = "occurrence"
- const val RESOURCE_RESOLUTION_INPUT_RESOURCE_ID = "resource-id"
- const val RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE = "resource-type"
- const val RESOURCE_RESOLUTION_LOG_PROTECTED_METADATA = "log-protect"
-}
\ No newline at end of file
+ const val SERVICE_RESOURCE_RESOLUTION = "resource-resolution-service"
+ const val PREFIX_RESOURCE_RESOLUTION_PROCESSOR = "rr-processor-"
+ const val INPUT_ARTIFACT_PREFIX_NAMES = "artifact-prefix-names"
+ const val OUTPUT_ASSIGNMENT_PARAMS = "assignment-params"
+ const val FILE_NAME_RESOURCE_DEFINITION_TYPES = "resources_definition_types.json"
+ const val RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY = "resolution-key"
+ const val RESOURCE_RESOLUTION_INPUT_STORE_RESULT = "store-result"
+ const val RESOURCE_RESOLUTION_INPUT_OCCURRENCE = "occurrence"
+ const val RESOURCE_RESOLUTION_INPUT_RESOURCE_ID = "resource-id"
+ const val RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE = "resource-type"
+ const val RESOURCE_RESOLUTION_LOG_PROTECTED_METADATA = "log-protect"
+}
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService
-
/**
* Register the Resolution module exposed dependency
*/
fun BluePrintDependencyService.resourceResolutionService(): ResourceResolutionService =
- instance(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
-
+ instance(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
-suspend fun AbstractComponentFunction.storedContentFromResolvedArtifactNB(resolutionKey: String,
- artifactName: String): String {
+suspend fun AbstractComponentFunction.storedContentFromResolvedArtifactNB(
+ resolutionKey: String,
+ artifactName: String
+): String {
return BluePrintDependencyService.resourceResolutionService()
- .resolveFromDatabase(bluePrintRuntimeService, artifactName, resolutionKey)
+ .resolveFromDatabase(bluePrintRuntimeService, artifactName, resolutionKey)
}
/**
*/
suspend fun AbstractComponentFunction.contentFromResolvedArtifactNB(artifactPrefix: String): String {
return BluePrintDependencyService.resourceResolutionService()
- .resolveResources(bluePrintRuntimeService, nodeTemplateName, artifactPrefix, mapOf())
+ .resolveResources(bluePrintRuntimeService, nodeTemplateName, artifactPrefix, mapOf())
}
-
/**
* Blocking Methods called from Jython Scripts
*/
-fun AbstractComponentFunction.storedContentFromResolvedArtifact(resolutionKey: String, artifactName: String)
- : String = runBlocking {
+fun AbstractComponentFunction.storedContentFromResolvedArtifact(resolutionKey: String, artifactName: String):
+ String = runBlocking {
storedContentFromResolvedArtifactNB(resolutionKey, artifactName)
}
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceDefinitionUtils.createResourceAssignments
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintTemplateService
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.UUID
interface ResourceResolutionService {
fun registeredResourceSources(): List<String>
- suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String,
- resolutionKey: String): String
-
- suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
- artifactNames: List<String>, properties: Map<String, Any>): MutableMap<String, String>
-
- suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
- artifactPrefix: String, properties: Map<String, Any>): String
+ suspend fun resolveFromDatabase(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ artifactTemplate: String,
+ resolutionKey: String
+ ): String
+
+ suspend fun resolveResources(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ nodeTemplateName: String,
+ artifactNames: List<String>,
+ properties: Map<String, Any>
+ ): MutableMap<String, String>
+
+ suspend fun resolveResources(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ nodeTemplateName: String,
+ artifactPrefix: String,
+ properties: Map<String, Any>
+ ): String
/** Resolve resources for all the sources defined in a particular resource Definition[resolveDefinition]
* with other [resourceDefinitions] dependencies for the sources [sources]
* Used to get the same resource values from multiple sources. **/
- suspend fun resolveResourceDefinition(blueprintRuntimeService: BluePrintRuntimeService<*>,
- resourceDefinitions: MutableMap<String, ResourceDefinition>,
- resolveDefinition: String, sources: List<String>)
- : MutableMap<String, JsonNode>
-
- suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
- resourceDefinitions: MutableMap<String, ResourceDefinition>,
- resourceAssignments: MutableList<ResourceAssignment>,
- artifactPrefix: String,
- properties: Map<String, Any>)
+ suspend fun resolveResourceDefinition(
+ blueprintRuntimeService: BluePrintRuntimeService<*>,
+ resourceDefinitions: MutableMap<String, ResourceDefinition>,
+ resolveDefinition: String,
+ sources: List<String>
+ ):
+ MutableMap<String, JsonNode>
+
+ suspend fun resolveResourceAssignments(
+ blueprintRuntimeService: BluePrintRuntimeService<*>,
+ resourceDefinitions: MutableMap<String, ResourceDefinition>,
+ resourceAssignments: MutableList<ResourceAssignment>,
+ artifactPrefix: String,
+ properties: Map<String, Any>
+ )
}
@Service(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
-open class ResourceResolutionServiceImpl(private var applicationContext: ApplicationContext,
- private var templateResolutionDBService: TemplateResolutionService,
- private var blueprintTemplateService: BluePrintTemplateService,
- private var resourceResolutionDBService: ResourceResolutionDBService) :
- ResourceResolutionService {
+open class ResourceResolutionServiceImpl(
+ private var applicationContext: ApplicationContext,
+ private var templateResolutionDBService: TemplateResolutionService,
+ private var blueprintTemplateService: BluePrintTemplateService,
+ private var resourceResolutionDBService: ResourceResolutionDBService
+) :
+ ResourceResolutionService {
private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java)
override fun registeredResourceSources(): List<String> {
return applicationContext.getBeanNamesForType(ResourceAssignmentProcessor::class.java)
- .filter { it.startsWith(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
- .map { it.substringAfter(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
+ .filter { it.startsWith(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
+ .map { it.substringAfter(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
}
- override suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- artifactTemplate: String,
- resolutionKey: String): String {
+ override suspend fun resolveFromDatabase(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ artifactTemplate: String,
+ resolutionKey: String
+ ): String {
return templateResolutionDBService.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
- bluePrintRuntimeService,
- artifactTemplate,
- resolutionKey)
+ bluePrintRuntimeService,
+ artifactTemplate,
+ resolutionKey
+ )
}
- override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
- artifactNames: List<String>,
- properties: Map<String, Any>): MutableMap<String, String> {
+ override suspend fun resolveResources(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ nodeTemplateName: String,
+ artifactNames: List<String>,
+ properties: Map<String, Any>
+ ): MutableMap<String, String> {
val resourceAssignmentRuntimeService =
- ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService, artifactNames.toString())
+ ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService, artifactNames.toString())
val resolvedParams: MutableMap<String, String> = hashMapOf()
artifactNames.forEach { artifactName ->
- val resolvedContent = resolveResources(resourceAssignmentRuntimeService, nodeTemplateName,
- artifactName, properties)
+ val resolvedContent = resolveResources(
+ resourceAssignmentRuntimeService, nodeTemplateName,
+ artifactName, properties
+ )
resolvedParams[artifactName] = resolvedContent
}
return resolvedParams
}
-
- override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
- artifactPrefix: String, properties: Map<String, Any>): String {
+ override suspend fun resolveResources(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ nodeTemplateName: String,
+ artifactPrefix: String,
+ properties: Map<String, Any>
+ ): String {
// Velocity Artifact Definition Name
val artifactTemplate = "$artifactPrefix-template"
log.info("Resolving resource for template artifact($artifactTemplate) with resource assignment artifact($artifactMapping)")
val resourceAssignmentContent =
- bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping)
+ bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping)
val resourceAssignments: MutableList<ResourceAssignment> =
- JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java)
- as? MutableList<ResourceAssignment>
- ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions")
+ JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java)
+ as? MutableList<ResourceAssignment>
+ ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions")
if (isToStore(properties)) {
val existingResourceResolution = isNewResolution(bluePrintRuntimeService, properties, artifactPrefix)
if (existingResourceResolution.isNotEmpty()) {
- updateResourceAssignmentWithExisting(bluePrintRuntimeService as ResourceAssignmentRuntimeService,
- existingResourceResolution, resourceAssignments)
+ updateResourceAssignmentWithExisting(
+ bluePrintRuntimeService as ResourceAssignmentRuntimeService,
+ existingResourceResolution, resourceAssignments
+ )
}
}
// Get the Resource Dictionary Name
val resourceDefinitions: MutableMap<String, ResourceDefinition> = ResourceAssignmentUtils
- .resourceDefinitions(bluePrintRuntimeService.bluePrintContext().rootPath)
+ .resourceDefinitions(bluePrintRuntimeService.bluePrintContext().rootPath)
// Resolve resources
- resolveResourceAssignments(bluePrintRuntimeService,
- resourceDefinitions,
- resourceAssignments,
- artifactPrefix,
- properties)
+ resolveResourceAssignments(
+ bluePrintRuntimeService,
+ resourceDefinitions,
+ resourceAssignments,
+ artifactPrefix,
+ properties
+ )
val resolvedParamJsonContent =
- ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList())
+ ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList())
- resolvedContent = blueprintTemplateService.generateContent(bluePrintRuntimeService, nodeTemplateName,
- artifactTemplate, resolvedParamJsonContent, false,
- mutableMapOf(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE to
- properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive()))
+ resolvedContent = blueprintTemplateService.generateContent(
+ bluePrintRuntimeService, nodeTemplateName,
+ artifactTemplate, resolvedParamJsonContent, false,
+ mutableMapOf(
+ ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE to
+ properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive()
+ )
+ )
if (isToStore(properties)) {
templateResolutionDBService.write(properties, resolvedContent, bluePrintRuntimeService, artifactPrefix)
return resolvedContent
}
- override suspend fun resolveResourceDefinition(blueprintRuntimeService: BluePrintRuntimeService<*>,
- resourceDefinitions: MutableMap<String, ResourceDefinition>,
- resolveDefinition: String, sources: List<String>)
- : MutableMap<String, JsonNode> {
+ override suspend fun resolveResourceDefinition(
+ blueprintRuntimeService: BluePrintRuntimeService<*>,
+ resourceDefinitions: MutableMap<String, ResourceDefinition>,
+ resolveDefinition: String,
+ sources: List<String>
+ ):
+ MutableMap<String, JsonNode> {
// Populate Dummy Resource Assignments
val resourceAssignments = createResourceAssignments(resourceDefinitions, resolveDefinition, sources)
- resolveResourceAssignments(blueprintRuntimeService, resourceDefinitions, resourceAssignments,
- UUID.randomUUID().toString(), hashMapOf())
+ resolveResourceAssignments(
+ blueprintRuntimeService, resourceDefinitions, resourceAssignments,
+ UUID.randomUUID().toString(), hashMapOf()
+ )
// Get the data from Resource Assignments
return ResourceAssignmentUtils.generateResourceForAssignments(resourceAssignments)
* name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the
* request.
*/
- override suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
- resourceDefinitions: MutableMap<String, ResourceDefinition>,
- resourceAssignments: MutableList<ResourceAssignment>,
- artifactPrefix: String,
- properties: Map<String, Any>) {
+ override suspend fun resolveResourceAssignments(
+ blueprintRuntimeService: BluePrintRuntimeService<*>,
+ resourceDefinitions: MutableMap<String, ResourceDefinition>,
+ resourceAssignments: MutableList<ResourceAssignment>,
+ artifactPrefix: String,
+ properties: Map<String, Any>
+ ) {
val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
bulkSequenced.forEach { batchResourceAssignments ->
// Execute Non Dependent Assignments in parallel ( ie asynchronously )
val deferred = batchResourceAssignments
- .filter { it.name != "*" && it.name != "start" }
- .filter { it.status != BluePrintConstants.STATUS_SUCCESS }
- .map { resourceAssignment ->
- async {
- val dictionaryName = resourceAssignment.dictionaryName
- val dictionarySource = resourceAssignment.dictionarySource
-
- val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
-
- val resourceAssignmentProcessor =
- applicationContext.getBean(processorName) as? ResourceAssignmentProcessor
- ?: throw BluePrintProcessorException("failed to get resource processor ($processorName) " +
- "for resource assignment(${resourceAssignment.name})")
- try {
- // Set BluePrint Runtime Service
- resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
- // Set Resource Dictionaries
- resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
- // Invoke Apply Method
- resourceAssignmentProcessor.applyNB(resourceAssignment)
-
- if (isToStore(properties)) {
- resourceResolutionDBService.write(properties,
- blueprintRuntimeService,
- artifactPrefix,
- resourceAssignment)
- log.info("Resource resolution saved into database successfully : (${resourceAssignment.name})")
- }
-
- // Set errors from RA
- blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError())
- } catch (e: RuntimeException) {
- log.error("Fail in processing ${resourceAssignment.name}", e)
- throw BluePrintProcessorException(e)
+ .filter { it.name != "*" && it.name != "start" }
+ .filter { it.status != BluePrintConstants.STATUS_SUCCESS }
+ .map { resourceAssignment ->
+ async {
+ val dictionaryName = resourceAssignment.dictionaryName
+ val dictionarySource = resourceAssignment.dictionarySource
+
+ val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
+
+ val resourceAssignmentProcessor =
+ applicationContext.getBean(processorName) as? ResourceAssignmentProcessor
+ ?: throw BluePrintProcessorException(
+ "failed to get resource processor ($processorName) " +
+ "for resource assignment(${resourceAssignment.name})"
+ )
+ try {
+ // Set BluePrint Runtime Service
+ resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
+ // Set Resource Dictionaries
+ resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
+ // Invoke Apply Method
+ resourceAssignmentProcessor.applyNB(resourceAssignment)
+
+ if (isToStore(properties)) {
+ resourceResolutionDBService.write(
+ properties,
+ blueprintRuntimeService,
+ artifactPrefix,
+ resourceAssignment
+ )
+ log.info("Resource resolution saved into database successfully : (${resourceAssignment.name})")
}
+
+ // Set errors from RA
+ blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError())
+ } catch (e: RuntimeException) {
+ log.error("Fail in processing ${resourceAssignment.name}", e)
+ throw BluePrintProcessorException(e)
}
}
+ }
log.debug("Resolving (${deferred.size})resources parallel.")
deferred.awaitAll()
}
}
-
}
/**
* If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can
* derive the default input processor.
*/
- private fun processorName(dictionaryName: String, dictionarySource: String,
- resourceDefinitions: MutableMap<String, ResourceDefinition>): String {
+ private fun processorName(
+ dictionaryName: String,
+ dictionarySource: String,
+ resourceDefinitions: MutableMap<String, ResourceDefinition>
+ ): String {
val processorName: String = when (dictionarySource) {
"input" -> {
"${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input"
}
else -> {
val resourceDefinition = resourceDefinitions[dictionaryName]
- ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
+ ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
val resourceSource = resourceDefinition.sources[dictionarySource]
- ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
+ ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type)
}
}
return processorName
-
}
// Check whether to store or not the resolution of resource and template
private fun isToStore(properties: Map<String, Any>): Boolean {
- return properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT)
- && properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean
+ return properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT) &&
+ properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean
}
// Check whether resolution already exist in the database for the specified resolution-key or resourceId/resourceType
- private suspend fun isNewResolution(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- properties: Map<String, Any>,
- artifactPrefix: String): List<ResourceResolution> {
+ private suspend fun isNewResolution(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ properties: Map<String, Any>,
+ artifactPrefix: String
+ ): List<ResourceResolution> {
val occurrence = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] as Int
val resolutionKey = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] as String
val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String
if (resolutionKey.isNotEmpty()) {
val existingResourceAssignments =
- resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
- bluePrintRuntimeService,
- resolutionKey,
- occurrence,
- artifactPrefix)
+ resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
+ bluePrintRuntimeService,
+ resolutionKey,
+ occurrence,
+ artifactPrefix
+ )
if (existingResourceAssignments.isNotEmpty()) {
- log.info("Resolution with resolutionKey=($resolutionKey) already exist - will resolve all resources not already resolved.",
- resolutionKey)
+ log.info(
+ "Resolution with resolutionKey=($resolutionKey) already exist - will resolve all resources not already resolved.",
+ resolutionKey
+ )
}
return existingResourceAssignments
} else if (resourceId.isNotEmpty() && resourceType.isNotEmpty()) {
val existingResourceAssignments =
- resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
- bluePrintRuntimeService,
- resourceId,
- resourceType,
-
- occurrence,
- artifactPrefix)
+ resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
+ bluePrintRuntimeService,
+ resourceId,
+ resourceType,
+
+ occurrence,
+ artifactPrefix
+ )
if (existingResourceAssignments.isNotEmpty()) {
- log.info("Resolution with resourceId=($resourceId) and resourceType=($resourceType) already exist - will resolve " +
- "all resources not already resolved.")
+ log.info(
+ "Resolution with resourceId=($resourceId) and resourceType=($resourceType) already exist - will resolve " +
+ "all resources not already resolved."
+ )
}
return existingResourceAssignments
}
}
// Update the resource assignment list with the status of the resource that have already been resolved
- private fun updateResourceAssignmentWithExisting(raRuntimeService : ResourceAssignmentRuntimeService,
- resourceResolutionList: List<ResourceResolution>,
- resourceAssignmentList: MutableList<ResourceAssignment>) {
+ private fun updateResourceAssignmentWithExisting(
+ raRuntimeService: ResourceAssignmentRuntimeService,
+ resourceResolutionList: List<ResourceResolution>,
+ resourceAssignmentList: MutableList<ResourceAssignment>
+ ) {
resourceResolutionList.forEach { resourceResolution ->
if (resourceResolution.status == BluePrintConstants.STATUS_SUCCESS) {
resourceAssignmentList.forEach {
// Comparision between what we have in the database vs what we have to assign.
private fun compareOne(resourceResolution: ResourceResolution, resourceAssignment: ResourceAssignment): Boolean {
- return (resourceResolution.name == resourceAssignment.name
- && resourceResolution.dictionaryName == resourceAssignment.dictionaryName
- && resourceResolution.dictionarySource == resourceAssignment.dictionarySource
- && resourceResolution.dictionaryVersion == resourceAssignment.version)
+ return (resourceResolution.name == resourceAssignment.name &&
+ resourceResolution.dictionaryName == resourceAssignment.dictionaryName &&
+ resourceResolution.dictionarySource == resourceAssignment.dictionarySource &&
+ resourceResolution.dictionaryVersion == resourceAssignment.version)
}
- private fun exposeOccurrencePropertyInResourceAssignments(raRuntimeService: ResourceAssignmentRuntimeService,
- properties: Map<String, Any>) {
- raRuntimeService.putResolutionStore(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE,
- properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive())
+ private fun exposeOccurrencePropertyInResourceAssignments(
+ raRuntimeService: ResourceAssignmentRuntimeService,
+ properties: Map<String, Any>
+ ) {
+ raRuntimeService.putResolutionStore(
+ ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE,
+ properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive()
+ )
}
}
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentScriptExecutor
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
import org.onap.ccsdk.cds.controllerblueprints.core.dsl.AbstractNodeTemplatePropertyImplBuilder
import kotlin.reflect.KClass
fun BluePrintTypes.nodeTypeSourceInput(): NodeType {
- return nodeType(id = "source-input", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
- description = "This is Input Resource Source Node Type") {}
+ return nodeType(
+ id = "source-input", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
+ description = "This is Input Resource Source Node Type"
+ ) {}
}
fun BluePrintTypes.nodeTypeSourceDefault(): NodeType {
- return nodeType(id = "source-default", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
- description = "This is Default Resource Source Node Type") {}
+ return nodeType(
+ id = "source-default", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
+ description = "This is Default Resource Source Node Type"
+ ) {}
}
fun BluePrintTypes.nodeTypeSourceDb(): NodeType {
- return nodeType(id = "source-db", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
- description = "This is Database Resource Source Node Type") {
- property("type", BluePrintConstants.DATA_TYPE_STRING,
- true, "") {
+ return nodeType(
+ id = "source-db", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
+ description = "This is Database Resource Source Node Type"
+ ) {
+ property(
+ "type", BluePrintConstants.DATA_TYPE_STRING,
+ true, ""
+ ) {
defaultValue("SQL".asJsonPrimitive())
constrain {
validValues(arrayListOf("SQL".asJsonPrimitive(), "PLSQL".asJsonPrimitive()))
}
}
- property("endpoint-selector", BluePrintConstants.DATA_TYPE_STRING,
- false, "")
- property("query", BluePrintConstants.DATA_TYPE_STRING,
- true, "")
- property("input-key-mapping", BluePrintConstants.DATA_TYPE_MAP,
- true, "") {
+ property(
+ "endpoint-selector", BluePrintConstants.DATA_TYPE_STRING,
+ false, ""
+ )
+ property(
+ "query", BluePrintConstants.DATA_TYPE_STRING,
+ true, ""
+ )
+ property(
+ "input-key-mapping", BluePrintConstants.DATA_TYPE_MAP,
+ true, ""
+ ) {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
- property("output-key-mapping", BluePrintConstants.DATA_TYPE_MAP,
- false, "") {
+ property(
+ "output-key-mapping", BluePrintConstants.DATA_TYPE_MAP,
+ false, ""
+ ) {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
- property("key-dependencies", BluePrintConstants.DATA_TYPE_LIST,
- true, "Resource Resolution dependency dictionary names.") {
+ property(
+ "key-dependencies", BluePrintConstants.DATA_TYPE_LIST,
+ true, "Resource Resolution dependency dictionary names."
+ ) {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
}
}
fun BluePrintTypes.nodeTypeSourceRest(): NodeType {
- return nodeType(id = "source-rest", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
- description = "This is Rest Resource Source Node Type") {
- property("type", BluePrintConstants.DATA_TYPE_STRING,
- true, "") {
+ return nodeType(
+ id = "source-rest", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
+ description = "This is Rest Resource Source Node Type"
+ ) {
+ property(
+ "type", BluePrintConstants.DATA_TYPE_STRING,
+ true, ""
+ ) {
defaultValue("JSON".asJsonPrimitive())
constrain {
validValues(arrayListOf("JSON".asJsonPrimitive(), "XML".asJsonPrimitive()))
}
}
- property("verb", BluePrintConstants.DATA_TYPE_STRING,
- true, "") {
+ property(
+ "verb", BluePrintConstants.DATA_TYPE_STRING,
+ true, ""
+ ) {
defaultValue("GET".asJsonPrimitive())
constrain {
- validValues(arrayListOf("GET".asJsonPrimitive(), "POST".asJsonPrimitive(),
- "DELETE".asJsonPrimitive(), "PUT".asJsonPrimitive()))
+ validValues(
+ arrayListOf(
+ "GET".asJsonPrimitive(), "POST".asJsonPrimitive(),
+ "DELETE".asJsonPrimitive(), "PUT".asJsonPrimitive()
+ )
+ )
}
}
- property("payload", BluePrintConstants.DATA_TYPE_STRING,
- false, "") {
+ property(
+ "payload", BluePrintConstants.DATA_TYPE_STRING,
+ false, ""
+ ) {
defaultValue("".asJsonPrimitive())
}
- property("endpoint-selector", BluePrintConstants.DATA_TYPE_STRING,
- false, "")
- property("url-path", BluePrintConstants.DATA_TYPE_STRING,
- true, "")
- property("path", BluePrintConstants.DATA_TYPE_STRING,
- true, "")
- property("expression-type", BluePrintConstants.DATA_TYPE_STRING,
- false, "") {
+ property(
+ "endpoint-selector", BluePrintConstants.DATA_TYPE_STRING,
+ false, ""
+ )
+ property(
+ "url-path", BluePrintConstants.DATA_TYPE_STRING,
+ true, ""
+ )
+ property(
+ "path", BluePrintConstants.DATA_TYPE_STRING,
+ true, ""
+ )
+ property(
+ "expression-type", BluePrintConstants.DATA_TYPE_STRING,
+ false, ""
+ ) {
defaultValue("JSON_PATH".asJsonPrimitive())
constrain {
validValues(arrayListOf("JSON_PATH".asJsonPrimitive(), "JSON_POINTER".asJsonPrimitive()))
}
}
- property("input-key-mapping", BluePrintConstants.DATA_TYPE_MAP,
- true, "") {
+ property(
+ "input-key-mapping", BluePrintConstants.DATA_TYPE_MAP,
+ true, ""
+ ) {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
- property("output-key-mapping", BluePrintConstants.DATA_TYPE_MAP,
- false, "") {
+ property(
+ "output-key-mapping", BluePrintConstants.DATA_TYPE_MAP,
+ false, ""
+ ) {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
- property("key-dependencies", BluePrintConstants.DATA_TYPE_LIST,
- true, "Resource Resolution dependency dictionary names.") {
+ property(
+ "key-dependencies", BluePrintConstants.DATA_TYPE_LIST,
+ true, "Resource Resolution dependency dictionary names."
+ ) {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
}
}
fun BluePrintTypes.nodeTypeSourceCapability(): NodeType {
- return nodeType(id = "source-capability", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
- description = "This is Component Resource Source Node Type") {
- property(ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BluePrintConstants.DATA_TYPE_STRING,
- true, "Request Id, Unique Id for the request.") {
+ return nodeType(
+ id = "source-capability", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
+ description = "This is Component Resource Source Node Type"
+ ) {
+ property(
+ ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Request Id, Unique Id for the request."
+ ) {
defaultValue(BluePrintConstants.SCRIPT_KOTLIN)
constrain {
- validValues(arrayListOf(BluePrintConstants.SCRIPT_KOTLIN.asJsonPrimitive(),
+ validValues(
+ arrayListOf(
+ BluePrintConstants.SCRIPT_KOTLIN.asJsonPrimitive(),
BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive(),
- BluePrintConstants.SCRIPT_JYTHON.asJsonPrimitive()))
+ BluePrintConstants.SCRIPT_JYTHON.asJsonPrimitive()
+ )
+ )
}
}
- property(ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BluePrintConstants.DATA_TYPE_STRING,
- true, "Kotlin Script class name or jython script name.")
- property("key-dependencies", BluePrintConstants.DATA_TYPE_LIST,
- true, "Resource Resolution dependency dictionary names.") {
+ property(
+ ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Kotlin Script class name or jython script name."
+ )
+ property(
+ "key-dependencies", BluePrintConstants.DATA_TYPE_LIST,
+ true, "Resource Resolution dependency dictionary names."
+ ) {
entrySchema(BluePrintConstants.DATA_TYPE_STRING)
}
}
}
/** Node Template Source Input **/
-fun BluePrintTypes.nodeTemplateSourceInput(id: String, description: String,
- block: SourceInputNodeTemplateBuilder.() -> Unit): NodeTemplate {
+fun BluePrintTypes.nodeTemplateSourceInput(
+ id: String,
+ description: String,
+ block: SourceInputNodeTemplateBuilder.() -> Unit
+): NodeTemplate {
return SourceInputNodeTemplateBuilder(id, description).apply(block).build()
}
class SourceInputNodeTemplateBuilder(id: String, description: String) :
- AbstractNodeTemplatePropertyImplBuilder<PropertiesAssignmentBuilder>(id,
- "source-input", description)
+ AbstractNodeTemplatePropertyImplBuilder<PropertiesAssignmentBuilder>(
+ id,
+ "source-input", description
+ )
/** Node Template Source Default **/
-fun BluePrintTypes.nodeTemplateSourceDefault(id: String, description: String,
- block: SourceDefaultNodeTemplateBuilder.() -> Unit): NodeTemplate {
+fun BluePrintTypes.nodeTemplateSourceDefault(
+ id: String,
+ description: String,
+ block: SourceDefaultNodeTemplateBuilder.() -> Unit
+): NodeTemplate {
return SourceDefaultNodeTemplateBuilder(id, description).apply(block).build()
}
class SourceDefaultNodeTemplateBuilder(id: String, description: String) :
- AbstractNodeTemplatePropertyImplBuilder<PropertiesAssignmentBuilder>(id,
- "source-default", description)
+ AbstractNodeTemplatePropertyImplBuilder<PropertiesAssignmentBuilder>(
+ id,
+ "source-default", description
+ )
/** Node Template Source DB **/
-fun BluePrintTypes.nodeTemplateSourceDb(id: String, description: String,
- block: SourceDbNodeTemplateBuilder.() -> Unit): NodeTemplate {
+fun BluePrintTypes.nodeTemplateSourceDb(
+ id: String,
+ description: String,
+ block: SourceDbNodeTemplateBuilder.() -> Unit
+): NodeTemplate {
return SourceDbNodeTemplateBuilder(id, description).apply(block).build()
}
class SourceDbNodeTemplateBuilder(id: String, description: String) :
- AbstractNodeTemplatePropertyImplBuilder<SourceDbNodeTemplateBuilder.PropertiesBuilder>(id,
- "source-db", description) {
+ AbstractNodeTemplatePropertyImplBuilder<SourceDbNodeTemplateBuilder.PropertiesBuilder>(
+ id,
+ "source-db", description
+ ) {
class PropertiesBuilder : PropertiesAssignmentBuilder() {
fun type(type: String) = type(type.asJsonPrimitive())
}
}
-
/** Node Template Source Rest **/
-fun BluePrintTypes.nodeTemplateSourceRest(id: String, description: String,
- block: SourceRestNodeTemplateBuilder.() -> Unit): NodeTemplate {
+fun BluePrintTypes.nodeTemplateSourceRest(
+ id: String,
+ description: String,
+ block: SourceRestNodeTemplateBuilder.() -> Unit
+): NodeTemplate {
return SourceRestNodeTemplateBuilder(id, description).apply(block).build()
}
class SourceRestNodeTemplateBuilder(id: String, description: String) :
- AbstractNodeTemplatePropertyImplBuilder<SourceRestNodeTemplateBuilder.PropertiesBuilder>(id,
- "source-rest", description) {
+ AbstractNodeTemplatePropertyImplBuilder<SourceRestNodeTemplateBuilder.PropertiesBuilder>(
+ id,
+ "source-rest", description
+ ) {
class PropertiesBuilder : PropertiesAssignmentBuilder() {
fun type(type: String) = type(type.asJsonPrimitive())
}
/** Node Template Source Rest **/
-fun BluePrintTypes.nodeTemplateSourceCapability(id: String, description: String,
- block: SourceCapabilityNodeTemplateBuilder.() -> Unit): NodeTemplate {
+fun BluePrintTypes.nodeTemplateSourceCapability(
+ id: String,
+ description: String,
+ block: SourceCapabilityNodeTemplateBuilder.() -> Unit
+): NodeTemplate {
return SourceCapabilityNodeTemplateBuilder(id, description).apply(block).build()
}
class SourceCapabilityNodeTemplateBuilder(id: String, description: String) :
- AbstractNodeTemplatePropertyImplBuilder<SourceCapabilityNodeTemplateBuilder.PropertiesBuilder>(id,
- "source-capability", description) {
+ AbstractNodeTemplatePropertyImplBuilder<SourceCapabilityNodeTemplateBuilder.PropertiesBuilder>(
+ id,
+ "source-capability", description
+ ) {
class PropertiesBuilder : PropertiesAssignmentBuilder() {
fun type(type: String) = type(type.asJsonPrimitive())
property("key-dependencies", keyDependencies)
}
}
-}
\ No newline at end of file
+}
var instanceDependencies: List<String>? = null
@get:JsonProperty("key-dependencies")
lateinit var keyDependencies: MutableList<String>
-}
\ No newline at end of file
+}
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
@EntityListeners(AuditingEntityListener::class)
@Entity
@Column(name = "status", nullable = false)
var status: String? = null
- @get:ApiModelProperty(value = "Resolution Key uniquely identifying the resolution of a given artifact within a CBA.",
- required = true)
+ @get:ApiModelProperty(
+ value = "Resolution Key uniquely identifying the resolution of a given artifact within a CBA.",
+ required = true
+ )
@Column(name = "resolution_key", nullable = false)
var resolutionKey: String? = null
@Column(name = "resource_id", nullable = false)
var resourceId: String? = null
- @get:ApiModelProperty(value = "If resolution occurred multiple time, this field provides the index.",
- required = true)
+ @get:ApiModelProperty(
+ value = "If resolution occurred multiple time, this field provides the index.",
+ required = true
+ )
@Column(name = "occurrence", nullable = false)
var occurrence: Int = 0
@Column(name = "dictionary_name", nullable = false)
var dictionaryName: String? = null
- @get:ApiModelProperty(value = "Source associated with the data dictionary used for the resolution.",
- required = true)
+ @get:ApiModelProperty(
+ value = "Source associated with the data dictionary used for the resolution.",
+ required = true
+ )
@Column(name = "dictionary_status", nullable = false)
var dictionarySource: String? = null
import org.slf4j.LoggerFactory
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.UUID
@Service
class ResourceResolutionDBService(private val resourceResolutionRepository: ResourceResolutionRepository) {
private val log = LoggerFactory.getLogger(ResourceResolutionDBService::class.toString())
suspend fun findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
- bluePrintRuntimeService: BluePrintRuntimeService<*>, key: String,
- occurrence: Int, artifactPrefix: String): List<ResourceResolution> {
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ key: String,
+ occurrence: Int,
+ artifactPrefix: String
+ ): List<ResourceResolution> {
return try {
val metadata = bluePrintRuntimeService.bluePrintContext().metadata!!
blueprintVersion,
artifactPrefix,
key,
- occurrence)
+ occurrence
+ )
} catch (e: EmptyResultDataAccessException) {
emptyList()
}
}
suspend fun findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
- bluePrintRuntimeService: BluePrintRuntimeService<*>, resourceId: String,
- resourceType: String, occurrence: Int,
- artifactPrefix: String): List<ResourceResolution> {
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ resourceId: String,
+ resourceType: String,
+ occurrence: Int,
+ artifactPrefix: String
+ ): List<ResourceResolution> {
return try {
val metadata = bluePrintRuntimeService.bluePrintContext().metadata!!
artifactPrefix,
resourceId,
resourceType,
- occurrence)
+ occurrence
+ )
} catch (e: EmptyResultDataAccessException) {
emptyList()
}
}
- suspend fun readValue(blueprintName: String,
- blueprintVersion: String,
- artifactPrefix: String,
- resolutionKey: String,
- name: String): ResourceResolution = withContext(Dispatchers.IO) {
+ suspend fun readValue(
+ blueprintName: String,
+ blueprintVersion: String,
+ artifactPrefix: String,
+ resolutionKey: String,
+ name: String
+ ): ResourceResolution = withContext(Dispatchers.IO) {
resourceResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndName(
resolutionKey,
blueprintName,
blueprintVersion,
artifactPrefix,
- name)
+ name
+ )
}
- suspend fun readWithResolutionKey(blueprintName: String,
- blueprintVersion: String,
- artifactPrefix: String,
- resolutionKey: String): List<ResourceResolution> = withContext(Dispatchers.IO) {
+ suspend fun readWithResolutionKey(
+ blueprintName: String,
+ blueprintVersion: String,
+ artifactPrefix: String,
+ resolutionKey: String
+ ): List<ResourceResolution> = withContext(Dispatchers.IO) {
resourceResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
resolutionKey,
blueprintName,
blueprintVersion,
- artifactPrefix)
+ artifactPrefix
+ )
}
- suspend fun readWithResourceIdAndResourceType(blueprintName: String,
- blueprintVersion: String,
- resourceId: String,
- resourceType: String): List<ResourceResolution> =
+ suspend fun readWithResourceIdAndResourceType(
+ blueprintName: String,
+ blueprintVersion: String,
+ resourceId: String,
+ resourceType: String
+ ): List<ResourceResolution> =
withContext(Dispatchers.IO) {
resourceResolutionRepository.findByBlueprintNameAndBlueprintVersionAndResourceIdAndResourceType(
blueprintName,
blueprintVersion,
resourceId,
- resourceType)
+ resourceType
+ )
}
- suspend fun write(properties: Map<String, Any>,
- bluePrintRuntimeService: BluePrintRuntimeService<*>,
- artifactPrefix: String,
- resourceAssignment: ResourceAssignment): ResourceResolution = withContext(Dispatchers.IO) {
+ suspend fun write(
+ properties: Map<String, Any>,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ artifactPrefix: String,
+ resourceAssignment: ResourceAssignment
+ ): ResourceResolution = withContext(Dispatchers.IO) {
val metadata = bluePrintRuntimeService.bluePrintContext().metadata!!
val resourceType = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] as String
val occurrence = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] as Int
- write(blueprintName,
+ write(
+ blueprintName,
blueprintVersion,
resolutionKey,
resourceId,
resourceType,
artifactPrefix,
resourceAssignment,
- occurrence)
+ occurrence
+ )
}
- suspend fun write(blueprintName: String,
- blueprintVersion: String,
- resolutionKey: String,
- resourceId: String,
- resourceType: String,
- artifactPrefix: String,
- resourceAssignment: ResourceAssignment,
- occurrence: Int = 0): ResourceResolution = withContext(Dispatchers.IO) {
+ suspend fun write(
+ blueprintName: String,
+ blueprintVersion: String,
+ resolutionKey: String,
+ resourceId: String,
+ resourceType: String,
+ artifactPrefix: String,
+ resourceAssignment: ResourceAssignment,
+ occurrence: Int = 0
+ ): ResourceResolution = withContext(Dispatchers.IO) {
val resourceResolution = ResourceResolution()
resourceResolution.id = UUID.randomUUID().toString()
throw BluePrintException("Failed to store resource resolution result.", ex)
}
}
-}
\ No newline at end of file
+}
interface ResourceResolutionRepository : JpaRepository<ResourceResolution, String> {
- fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndName(key: String,
- blueprintName: String?,
- blueprintVersion: String?,
- artifactName: String,
- name: String): ResourceResolution
+ fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndName(
+ key: String,
+ blueprintName: String?,
+ blueprintVersion: String?,
+ artifactName: String,
+ name: String
+ ): ResourceResolution
- fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(resolutionKey: String,
- blueprintName: String,
- blueprintVersion: String,
- artifactPrefix: String): List<ResourceResolution>
+ fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
+ resolutionKey: String,
+ blueprintName: String,
+ blueprintVersion: String,
+ artifactPrefix: String
+ ): List<ResourceResolution>
- fun findByBlueprintNameAndBlueprintVersionAndResourceIdAndResourceType(blueprintName: String,
- blueprintVersion: String,
- resourceId: String,
- resourceType: String): List<ResourceResolution>
+ fun findByBlueprintNameAndBlueprintVersionAndResourceIdAndResourceType(
+ blueprintName: String,
+ blueprintVersion: String,
+ resourceId: String,
+ resourceType: String
+ ): List<ResourceResolution>
fun findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
blueprintName: String?,
blueprintVersion: String?,
artifactName: String,
resolutionKey: String,
- occurrence: Int): List<ResourceResolution>
+ occurrence: Int
+ ): List<ResourceResolution>
fun findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
blueprintName: String?,
artifactName: String,
resourceId: String,
resourceType: String,
- occurrence: Int): List<ResourceResolution>
-}
\ No newline at end of file
+ occurrence: Int
+ ): List<ResourceResolution>
+}
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
@EntityListeners(AuditingEntityListener::class)
@Entity
@Column(name = "result", nullable = false)
var result: String? = null
- @get:ApiModelProperty(value = "Resolution Key uniquely identifying the resolution of a given artifact within a CBA.",
- required = true)
+ @get:ApiModelProperty(
+ value = "Resolution Key uniquely identifying the resolution of a given artifact within a CBA.",
+ required = true
+ )
@Column(name = "resolution_key", nullable = false)
var resolutionKey: String? = null
@Column(name = "resource_id", nullable = false)
var resourceId: String? = null
- @get:ApiModelProperty(value = "If resolution occurred multiple time, this field provides the index.",
- required = true)
+ @get:ApiModelProperty(
+ value = "If resolution occurred multiple time, this field provides the index.",
+ required = true
+ )
@Column(name = "occurrence", nullable = false)
var occurrence: Int = 1
blueprintName: String?,
blueprintVersion: String?,
artifactName: String,
- occurrence: Int): TemplateResolution ?
+ occurrence: Int
+ ): TemplateResolution?
fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
key: String,
blueprintName: String?,
blueprintVersion: String?,
artifactName: String,
- occurrence: Int): TemplateResolution ?
+ occurrence: Int
+ ): TemplateResolution?
@Transactional
fun deleteByResourceIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
blueprintName: String?,
blueprintVersion: String?,
artifactName: String,
- occurrence: Int)
+ occurrence: Int
+ )
@Transactional
fun deleteByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
blueprintName: String?,
blueprintVersion: String?,
artifactName: String,
- occurrence: Int)
+ occurrence: Int
+ )
}
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.UUID
@Service
class TemplateResolutionService(private val templateResolutionRepository: TemplateResolutionRepository) {
suspend fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
bluePrintRuntimeService: BluePrintRuntimeService<*>,
artifactPrefix: String,
- resolutionKey: String): String =
+ resolutionKey: String
+ ): String =
withContext(Dispatchers.IO) {
val metadata = bluePrintRuntimeService.bluePrintContext().metadata!!
val blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION]!!
val blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME]!!
- findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(blueprintName,
+ findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
+ blueprintName,
blueprintVersion,
artifactPrefix,
- resolutionKey)
+ resolutionKey
+ )
}
- suspend fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(blueprintName: String,
- blueprintVersion: String,
- artifactPrefix: String,
- resolutionKey: String,
- occurrence: Int = 1): String =
+ suspend fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
+ blueprintName: String,
+ blueprintVersion: String,
+ artifactPrefix: String,
+ resolutionKey: String,
+ occurrence: Int = 1
+ ): String =
withContext(Dispatchers.IO) {
templateResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
blueprintName,
blueprintVersion,
artifactPrefix,
- occurrence)?.result ?: throw EmptyResultDataAccessException(1)
+ occurrence
+ )?.result ?: throw EmptyResultDataAccessException(1)
}
- suspend fun findByResoureIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactName(blueprintName: String,
- blueprintVersion: String,
- artifactPrefix: String,
- resourceId: String,
- resourceType: String,
- occurrence: Int = 1): String =
+ suspend fun findByResoureIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactName(
+ blueprintName: String,
+ blueprintVersion: String,
+ artifactPrefix: String,
+ resourceId: String,
+ resourceType: String,
+ occurrence: Int = 1
+ ): String =
withContext(Dispatchers.IO) {
templateResolutionRepository.findByResourceIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
blueprintName,
blueprintVersion,
artifactPrefix,
- occurrence)?.result!!
+ occurrence
+ )?.result!!
}
- suspend fun write(properties: Map<String, Any>,
- result: String, bluePrintRuntimeService: BluePrintRuntimeService<*>,
- artifactPrefix: String): TemplateResolution = withContext(Dispatchers.IO) {
+ suspend fun write(
+ properties: Map<String, Any>,
+ result: String,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ artifactPrefix: String
+ ): TemplateResolution = withContext(Dispatchers.IO) {
val metadata = bluePrintRuntimeService.bluePrintContext().metadata!!
val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String
val resourceType = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] as String
val occurrence = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] as Int
- write(blueprintName,
+ write(
+ blueprintName,
blueprintVersion,
artifactPrefix,
result,
occurrence,
resolutionKey,
resourceId,
- resourceType)
+ resourceType
+ )
}
- suspend fun write(blueprintName: String, blueprintVersion: String, artifactPrefix: String,
- template: String, occurrence: Int = 1, resolutionKey: String = "", resourceId: String = "",
- resourceType: String = ""): TemplateResolution =
+ suspend fun write(
+ blueprintName: String,
+ blueprintVersion: String,
+ artifactPrefix: String,
+ template: String,
+ occurrence: Int = 1,
+ resolutionKey: String = "",
+ resourceId: String = "",
+ resourceType: String = ""
+ ): TemplateResolution =
withContext(Dispatchers.IO) {
val resourceResolutionResult = TemplateResolution()
// Overwrite template resolution-key of resourceId/resourceType already existant
if (resolutionKey.isNotEmpty()) {
templateResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- resolutionKey, blueprintName, blueprintVersion, artifactPrefix, occurrence)?.let {
- log.info("Overwriting template resolution for blueprintName=($blueprintVersion), blueprintVersion=($blueprintName), " +
- "artifactName=($artifactPrefix) and resolutionKey=($resolutionKey)")
+ resolutionKey, blueprintName, blueprintVersion, artifactPrefix, occurrence
+ )?.let {
+ log.info(
+ "Overwriting template resolution for blueprintName=($blueprintVersion), blueprintVersion=($blueprintName), " +
+ "artifactName=($artifactPrefix) and resolutionKey=($resolutionKey)"
+ )
templateResolutionRepository.deleteByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
resolutionKey,
blueprintName,
blueprintVersion,
artifactPrefix,
- occurrence)
+ occurrence
+ )
}
} else if (resourceId.isNotEmpty() && resourceType.isNotEmpty()) {
templateResolutionRepository.findByResourceIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- resourceId, resourceType, blueprintName, blueprintVersion, artifactPrefix, occurrence)?.let {
- log.info("Overwriting template resolution for blueprintName=($blueprintVersion), blueprintVersion=($blueprintName), " +
- "artifactName=($artifactPrefix), resourceId=($resourceId) and resourceType=($resourceType)")
+ resourceId, resourceType, blueprintName, blueprintVersion, artifactPrefix, occurrence
+ )?.let {
+ log.info(
+ "Overwriting template resolution for blueprintName=($blueprintVersion), blueprintVersion=($blueprintName), " +
+ "artifactName=($artifactPrefix), resourceId=($resourceId) and resourceType=($resourceType)"
+ )
templateResolutionRepository.deleteByResourceIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
resourceId,
resourceType,
blueprintName,
blueprintVersion,
artifactPrefix,
- occurrence)
+ occurrence
+ )
}
}
try {
- log.info("Writing out template_resolution result: bpName: $blueprintName bpVer $blueprintVersion resKey:$resolutionKey" +
- " (resourceId: $resourceId resourceType: $resourceType) occurrence:$occurrence")
+ log.info(
+ "Writing out template_resolution result: bpName: $blueprintName bpVer $blueprintVersion resKey:$resolutionKey" +
+ " (resourceId: $resourceId resourceType: $resourceType) occurrence:$occurrence"
+ )
templateResolutionRepository.saveAndFlush(resourceResolutionResult)
} catch (ex: DataIntegrityViolationException) {
- log.error("Error writing out template_resolution result: bpName: $blueprintName bpVer $blueprintVersion resKey:$resolutionKey" +
- " (resourceId: $resourceId resourceType: $resourceType) occurrence:$occurrence error: {}", ex.message)
+ log.error(
+ "Error writing out template_resolution result: bpName: $blueprintName bpVer $blueprintVersion resKey:$resolutionKey" +
+ " (resourceId: $resourceId resourceType: $resourceType) occurrence:$occurrence error: {}", ex.message
+ )
throw BluePrintException("Failed to store resource api result.", ex)
}
}
ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, runtimeException.message)
}
- suspend fun scriptInstance(scriptType: String, scriptClassReference: String, instanceDependencies: List<String>)
- : ResourceAssignmentProcessor {
+ suspend fun scriptInstance(scriptType: String, scriptClassReference: String, instanceDependencies: List<String>):
+ ResourceAssignmentProcessor {
log.info(
"creating resource resolution of script type($scriptType), reference name($scriptClassReference) and" +
return scriptComponent
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor
import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService
-import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertySevice
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDBLibGenericService
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.HashMap
/**
* DatabaseResourceAssignmentProcessor
@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-db")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
open class DatabaseResourceAssignmentProcessor(
- private val bluePrintDBLibPropertySevice: BluePrintDBLibPropertySevice,
+ private val bluePrintDBLibPropertyService: BluePrintDBLibPropertyService,
private val primaryDBLibGenericService: PrimaryDBLibGenericService
) : ResourceAssignmentProcessor() {
"failed to get input-key-mappings for $dName under $dSource properties"
}
- logger.info("DatabaseResource ($dSource) dictionary information: " +
- "Query:($sql), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})")
+ logger.info(
+ "DatabaseResource ($dSource) dictionary information: " +
+ "Query:($sql), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
+ )
val jdbcTemplate = blueprintDBLibService(sourceProperties)
val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping))
private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): BluePrintDBLibGenericService {
return if (isNotEmpty(sourceProperties.endpointSelector)) {
val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
- bluePrintDBLibPropertySevice.JdbcTemplate(dbPropertiesJson)
+ bluePrintDBLibPropertyService.JdbcTemplate(dbPropertiesJson)
} else {
primaryDBLibGenericService
}
-
}
@Throws(BluePrintProcessorException::class)
checkNotEmpty(resourceAssignment.dictionaryName) {
"resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
}
- check(resourceAssignment.dictionarySource in getListOfDBSources())
- {
+ check(resourceAssignment.dictionarySource in getListOfDBSources()) {
"resource assignment source is not ${ResourceDictionaryConstants.PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}"
}
}
- //placeholder to get the list of DB sources.
- //TODO: This will be replaced with a DB
+ // placeholder to get the list of DB sources.
+ // TODO: This will be replaced with a DB
private fun getListOfDBSources(): Array<String> = arrayOf(ResourceDictionaryConstants.PROCESSOR_DB)
private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
}
-
}
override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
override suspend fun processNB(resourceAssignment: ResourceAssignment) {
try {
- if (isNotEmpty(resourceAssignment.name)) {
- setFromInput(resourceAssignment)
+ if (isNotEmpty(resourceAssignment.name) && !setFromInput(resourceAssignment)) {
+ setFromKeyDependencies(resourceAssignment)
}
// Check the value has populated for mandatory case
ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
}
}
+ // usecase: where input data attribute doesn't match with resourceName, and needs an alternate mapping provided under key-dependencies.
+ private fun setFromKeyDependencies(resourceAssignment: ResourceAssignment) {
+ val dName = resourceAssignment.dictionaryName!!
+ val dSource = resourceAssignment.dictionarySource!!
+ val resourceDefinition = resourceDefinition(dName)
+
+ /** Check Resource Assignment has the source definitions, If not get from Resource Definition **/
+ val resourceSource = resourceAssignment.dictionarySourceDefinition
+ ?: resourceDefinition?.sources?.get(dSource)
+ ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
+ val resourceSourceProperties = checkNotNull(resourceSource.properties) {
+ "failed to get source properties for $dName "
+ }
+ val sourceProperties =
+ JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java)
+
+ val keyDependency = checkNotNull(sourceProperties.keyDependencies) {
+ "failed to get input-key-mappings for $dName under $dSource properties"
+ }
+ // keyDependency = service-instance.service-instance-id
+ setFromInputKeyDependencies(keyDependency, resourceAssignment); // New API which picks arrtibute from Input
+ }
+
override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
}
-}
\ No newline at end of file
+}
import org.apache.commons.collections.MapUtils
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode
+import org.onap.ccsdk.cds.controllerblueprints.core.isNullOrMissing
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
import org.slf4j.LoggerFactory
-import java.util.*
+import java.util.HashMap
abstract class ResourceAssignmentProcessor : BlueprintFunctionNode<ResourceAssignment, Boolean> {
try {
val value = raRuntimeService.getInputValue(resourceAssignment.name)
if (!value.isNullOrMissing()) {
- log.debug("For Resource:(${resourceAssignment.name}) found value:({}) in input-data.",
- ResourceAssignmentUtils.getValueToLog(resourceAssignment.property?.metadata, value))
+ log.debug(
+ "For Resource:(${resourceAssignment.name}) found value:({}) in input-data.",
+ ResourceAssignmentUtils.getValueToLog(resourceAssignment.property?.metadata, value)
+ )
ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
return true
}
return false
}
+ open fun setFromInputKeyDependencies(keys: MutableList<String>, resourceAssignment: ResourceAssignment): Boolean {
+ try {
+ for (dependencyKey in keys) {
+ var value = raRuntimeService.getInputValue(dependencyKey)
+ if (!value.isNullOrMissing()) {
+ log.debug(
+ "For Resource:(${resourceAssignment.name}) found value:({}) in input-data under: ($dependencyKey).",
+ ResourceAssignmentUtils.getValueToLog(resourceAssignment.property?.metadata, value)
+ )
+ ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
+ return true
+ }
+ }
+ } catch (e: BluePrintProcessorException) {
+ // NoOp - couldn't find value from input
+ }
+ return false
+ }
+
open fun resourceDefinition(name: String): ResourceDefinition? {
return if (resourceDictionaries.containsKey(name)) resourceDictionaries[name] else null
}
if (valueToResolve.isEmpty() || !valueToResolve.contains("$")) {
return valueToResolve
}
- //TODO("Optimize to JSON Node directly without velocity").asJsonNode().toString()
+ // TODO("Optimize to JSON Node directly without velocity").asJsonNode().toString()
return BluePrintVelocityTemplateService.generateContent(valueToResolve, keyMapping.asJsonNode().toString())
}
fun addError(error: String) {
raRuntimeService.getBluePrintError().addError(error)
}
-}
\ No newline at end of file
+}
resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
- logger.info("RestResource ($dSource) dictionary information: " +
- "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})")
+ logger.info(
+ "RestResource ($dSource) dictionary information: " +
+ "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
+ )
val requestHeaders = sourceProperties.headers
logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
// Get the Rest Client Service
@Throws(BluePrintProcessorException::class)
private fun populateResource(
- resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
- restResponse: String, path: String
+ resourceAssignment: ResourceAssignment,
+ sourceProperties: RestResourceSource,
+ restResponse: String,
+ path: String
) {
val dName = resourceAssignment.dictionaryName
val dSource = resourceAssignment.dictionarySource
override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
}
-
}
import com.fasterxml.jackson.databind.node.TextNode
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
+import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
+import org.onap.ccsdk.cds.controllerblueprints.core.isComplexType
+import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
+import org.onap.ccsdk.cds.controllerblueprints.core.isNullOrMissing
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
+import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonReactorUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
import org.slf4j.LoggerFactory
-import java.util.*
+import java.util.Date
class ResourceAssignmentUtils {
companion object {
@Throws(BluePrintProcessorException::class)
fun setResourceDataValue(
resourceAssignment: ResourceAssignment,
- raRuntimeService: ResourceAssignmentRuntimeService, value: Any?
+ raRuntimeService: ResourceAssignmentRuntimeService,
+ value: Any?
) {
// TODO("See if Validation is needed in future with respect to conversion and Types")
return setResourceDataValue(resourceAssignment, raRuntimeService, value.asJsonType())
@Throws(BluePrintProcessorException::class)
fun setResourceDataValue(
resourceAssignment: ResourceAssignment,
- raRuntimeService: ResourceAssignmentRuntimeService, value: JsonNode
+ raRuntimeService: ResourceAssignmentRuntimeService,
+ value: JsonNode
) {
val resourceProp = checkNotNull(resourceAssignment.property) {
"Failed in setting resource value for resource mapping $resourceAssignment"
private fun setResourceValue(
resourceAssignment: ResourceAssignment,
- raRuntimeService: ResourceAssignmentRuntimeService, value: JsonNode
+ raRuntimeService: ResourceAssignmentRuntimeService,
+ value: JsonNode
) {
// TODO("See if Validation is needed wrt to type before storing")
raRuntimeService.putResolutionStore(resourceAssignment.name, value)
@Throws(BluePrintProcessorException::class)
fun getPropertyType(
- raRuntimeService: ResourceAssignmentRuntimeService, dataTypeName: String,
+ raRuntimeService: ResourceAssignmentRuntimeService,
+ dataTypeName: String,
propertyName: String
): String {
lateinit var type: String
@Throws(BluePrintProcessorException::class)
fun parseResponseNode(
- responseNode: JsonNode, resourceAssignment: ResourceAssignment,
- raRuntimeService: ResourceAssignmentRuntimeService, outputKeyMapping: MutableMap<String, String>
+ responseNode: JsonNode,
+ resourceAssignment: ResourceAssignment,
+ raRuntimeService: ResourceAssignmentRuntimeService,
+ outputKeyMapping: MutableMap<String, String>
): JsonNode {
val metadata = resourceAssignment.property!!.metadata
try {
}
private fun parseResponseNodeForCollection(
- responseNode: JsonNode, resourceAssignment: ResourceAssignment,
+ responseNode: JsonNode,
+ resourceAssignment: ResourceAssignment,
raRuntimeService: ResourceAssignmentRuntimeService,
outputKeyMapping: MutableMap<String, String>
): JsonNode {
}
private fun parseSingleElementOfArrayResponseNode(
- entrySchemaType: String, outputKeyMapping: MutableMap<String, String>,
+ entrySchemaType: String,
+ outputKeyMapping: MutableMap<String, String>,
raRuntimeService: ResourceAssignmentRuntimeService,
- responseNode: JsonNode, metadata: MutableMap<String, String>?
+ responseNode: JsonNode,
+ metadata: MutableMap<String, String>?
): ObjectNode {
val outputKeyMappingHasOnlyOneElement = checkIfOutputKeyMappingProvideOneElement(outputKeyMapping)
when (entrySchemaType) {
}
private fun parseObjectResponseNode(
- entrySchemaType: String, outputKeyMapping: MutableMap<String, String>,
- responseArrayNode: MutableMap<String, JsonNode>, metadata: MutableMap<String, String>?
+ entrySchemaType: String,
+ outputKeyMapping: MutableMap<String, String>,
+ responseArrayNode: MutableMap<String, JsonNode>,
+ metadata: MutableMap<String, String>?
): ObjectNode {
val outputKeyMappingHasOnlyOneElement = checkIfOutputKeyMappingProvideOneElement(outputKeyMapping)
if (outputKeyMappingHasOnlyOneElement) {
}
private fun parseSingleElementNodeWithOneOutputKeyMapping(
- responseSingleJsonNode: JsonNode, outputKeyMappingKey:
- String, outputKeyMappingValue: String, type: String, metadata: MutableMap<String, String>?
+ responseSingleJsonNode: JsonNode,
+ outputKeyMappingKey:
+ String,
+ outputKeyMappingValue: String,
+ type: String,
+ metadata: MutableMap<String, String>?
): ObjectNode {
val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
private fun parseSingleElementNodeWithAllOutputKeyMapping(
responseSingleJsonNode: JsonNode,
outputKeyMapping: MutableMap<String, String>,
- type: String, metadata: MutableMap<String, String>?
+ type: String,
+ metadata: MutableMap<String, String>?
): ObjectNode {
val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
outputKeyMapping.map {
private fun parseObjectResponseNodeWithOneOutputKeyMapping(
responseArrayNode: MutableMap<String, JsonNode>,
- outputKeyMappingKey: String, outputKeyMappingValue: String,
- type: String, metadata: MutableMap<String, String>?
+ outputKeyMappingKey: String,
+ outputKeyMappingValue: String,
+ type: String,
+ metadata: MutableMap<String, String>?
): ObjectNode {
val objectNode = JacksonUtils.objectMapper.createObjectNode()
val responseSingleJsonNode = responseArrayNode.filterKeys { key ->
}
private fun parseResponseNodeForComplexType(
- responseNode: JsonNode, resourceAssignment: ResourceAssignment,
+ responseNode: JsonNode,
+ resourceAssignment: ResourceAssignment,
raRuntimeService: ResourceAssignmentRuntimeService,
outputKeyMapping: MutableMap<String, String>
): JsonNode {
}
private fun checkOutputKeyMappingAllElementsInDataTypeProperties(
- dataTypeName: String, outputKeyMapping: MutableMap<String, String>,
+ dataTypeName: String,
+ outputKeyMapping: MutableMap<String, String>,
raRuntimeService: ResourceAssignmentRuntimeService
): Boolean {
val dataTypeProps = raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties
return checkProtected
}
}
-}
\ No newline at end of file
+}
}
/** Create a processing resource assignments for the resource definition */
- fun createResourceAssignments(resourceDefinitions: MutableMap<String, ResourceDefinition>,
- resolveDefinition: String, sources: List<String>)
- : MutableList<ResourceAssignment> {
+ fun createResourceAssignments(
+ resourceDefinitions: MutableMap<String, ResourceDefinition>,
+ resolveDefinition: String,
+ sources: List<String>
+ ):
+ MutableList<ResourceAssignment> {
/** Check if resolve definition is defined in the resource definition Map */
val resourceDefinition = resourceDefinitions[resolveDefinition]
- ?: throw BluePrintProcessorException("failed to get resolve definition($resolveDefinition)")
+ ?: throw BluePrintProcessorException("failed to get resolve definition($resolveDefinition)")
val resourceAssignments: MutableList<ResourceAssignment> = arrayListOf()
/** Get the dependency property fields for the the resource definition to resolve */
val definitionDependencies = definitionDependencies(resourceDefinition, sources)
definitionDependencies.forEach { definitionDependencyName ->
val definitionDependency = resourceDefinitions[definitionDependencyName]
- ?: throw BluePrintProcessorException("failed to get dependency definition($definitionDependencyName)")
+ ?: throw BluePrintProcessorException("failed to get dependency definition($definitionDependencyName)")
val resourceAssignment = ResourceAssignment().apply {
name = definitionDependency.name
dictionarySourceDefinition = source
// Clone the PropertyDefinition, otherwise property value will be overridden
property = JacksonUtils
- .readValue(resourceDefinition.property.asJsonString(), PropertyDefinition::class.java)
+ .readValue(resourceDefinition.property.asJsonString(), PropertyDefinition::class.java)
val keyDependenciesExists = source.properties?.containsKey("key-dependencies") ?: false
if (keyDependenciesExists) {
dependencies = source.properties!!["key-dependencies"]!!.asListOfString().toMutableList()
// Populate Resource Definition's dependencies as Input Resource Assignment
return resourceAssignments
}
-}
\ No newline at end of file
+}
@Test
fun testResourceDefinitionDSL() {
- val testResourceDefinition = BluePrintTypes.resourceDefinition("service-instance-id",
- "VFW Service Instance Name") {
+ val testResourceDefinition = BluePrintTypes.resourceDefinition(
+ "service-instance-id",
+ "VFW Service Instance Name"
+ ) {
tags("service-instance-name, vfw, resources")
updatedBy("brindasanth@onap.com")
property("string", true)
}
}
}
- //println(resourceDefinition.asJsonString(true))
+ // println(resourceDefinition.asJsonString(true))
assertNotNull(testResourceDefinition, "failed to generate testResourceDefinition")
val testResourceDefinitions = BluePrintTypes.resourceDefinitions {
@Test
fun testResourceAssignment() {
- val testResourceAssignment = BluePrintTypes.resourceAssignment("instance-name",
- "service-instance-name", "odl-mdsal") {
+ val testResourceAssignment = BluePrintTypes.resourceAssignment(
+ "instance-name",
+ "service-instance-name", "odl-mdsal"
+ ) {
inputParameter(true)
property("string", true)
dependencies(arrayListOf("service-instance-id"))
}
- //println(resourceAssignment.asJsonString(true))
+ // println(resourceAssignment.asJsonString(true))
assertNotNull(testResourceAssignment, "failed to generate resourceAssignment")
val testResourceAssignments = BluePrintTypes.resourceAssignments {
resourceAssignment(testResourceAssignment)
- resourceAssignment("instance-name1",
- "service-instance-name", "odl-mdsal") {
+ resourceAssignment(
+ "instance-name1",
+ "service-instance-name", "odl-mdsal"
+ ) {
inputParameter(true)
property("string", true)
dependencies(arrayListOf("service-instance-id"))
}
}
- //println(testResourceAssignments.asJsonString(true))
+ // println(testResourceAssignments.asJsonString(true))
assertNotNull(testResourceAssignments, "failed to generate testResourceAssignments")
assertEquals(2, testResourceAssignments.size, "testResourceAssignments size doesn't match")
}
-}
\ No newline at end of file
+}
@Test
fun testNodeTypeComponentResourceResolution() {
val nodeType = BluePrintTypes.nodeTypeComponentResourceResolution()
- //println(nodeType.asJsonString(true))
+ // println(nodeType.asJsonString(true))
assertNotNull(nodeType, "failed to generate nodeTypeComponentResourceResolution")
}
resourceType("vnf")
storeResult(false)
artifactPrefixNames(arrayListOf("template1", "template2"))
- dynamicProperties("""{
+ dynamicProperties(
+ """{
"prop1" : "1234",
"prop2" : true,
"prop3" : 23
- }""".trimIndent())
+ }""".trimIndent()
+ )
}
outputs {
resourceAssignmentParams(getAttribute("assignment-params"))
}
}
}
- //println(nodeTemplate.asJsonString(true))
+ // println(nodeTemplate.asJsonString(true))
assertNotNull(nodeTemplate, "failed to generate nodeTemplateComponentResourceResolution")
}
-}
\ No newline at end of file
+}
private val executionRequest = ExecutionServiceInput()
-
@Before
fun setup() {
try {
resourceResolutionComponent.processNB(executionRequest)
} catch (e: BluePrintProcessorException) {
- assertEquals("Can't proceed with the resolution: either provide resolution-key OR combination of resource-id and resource-type.",
- e.message)
+ assertEquals(
+ "Can't proceed with the resolution: either provide resolution-key OR combination of resource-id and resource-type.",
+ e.message
+ )
return@runBlocking
}
fail()
try {
resourceResolutionComponent.processNB(executionRequest)
} catch (e: BluePrintProcessorException) {
- assertEquals("Can't proceed with the resolution: both resource-id and resource-type should be provided, one of them is missing.",
- e.message)
+ assertEquals(
+ "Can't proceed with the resolution: both resource-id and resource-type should be provided, one of them is missing.",
+ e.message
+ )
return@runBlocking
}
fail()
try {
resourceResolutionComponent.processNB(executionRequest)
} catch (e: BluePrintProcessorException) {
- assertEquals("Can't proceed with the resolution: can't persist resolution without a correlation key. " +
- "Either provide a resolution-key OR combination of resource-id and resource-type OR set `storeResult` to false.",
- e.message)
+ assertEquals(
+ "Can't proceed with the resolution: can't persist resolution without a correlation key. " +
+ "Either provide a resolution-key OR combination of resource-id and resource-type OR set `storeResult` to false.",
+ e.message
+ )
return@runBlocking
}
fail()
properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] = occurrence
coEvery {
- resourceResolutionService.resolveResources(any(),
- any(),
- any<List<String>>(),
- any<MutableMap<String, Any>>())
+ resourceResolutionService.resolveResources(
+ any(),
+ any(),
+ any<List<String>>(),
+ any<MutableMap<String, Any>>()
+ )
} returns mutableMapOf()
-
runBlocking {
resourceResolutionComponent.processNB(executionRequest)
}
-// FIXME add verification
-// coVerify {
-// resourceResolutionService.resolveResources(eq(bluePrintRuntimeService),
-// eq(nodeTemplateName), eq(artifactNames), eq(properties))
-// }
+ // FIXME add verification
+ // coVerify {
+ // resourceResolutionService.resolveResources(eq(bluePrintRuntimeService),
+ // eq(nodeTemplateName), eq(artifactNames), eq(properties))
+ // }
}
@Test
assertEquals(1, blueprintError.errors.size)
}
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.PayloadUtils
import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.*
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.CapabilityResourceResolutionProcessor
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.DatabaseResourceAssignmentProcessor
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.DefaultResourceResolutionProcessor
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.InputResourceResolutionProcessor
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.MockCapabilityScriptRA
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.RestResourceResolutionProcessor
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError
* @author Brinda Santh DATE : 8/15/2018
*/
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [ResourceResolutionServiceImpl::class,
- InputResourceResolutionProcessor::class, DefaultResourceResolutionProcessor::class,
- DatabaseResourceAssignmentProcessor::class, RestResourceResolutionProcessor::class,
- CapabilityResourceResolutionProcessor::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class,
- BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class])
+@ContextConfiguration(
+ classes = [ResourceResolutionServiceImpl::class,
+ InputResourceResolutionProcessor::class, DefaultResourceResolutionProcessor::class,
+ DatabaseResourceAssignmentProcessor::class, RestResourceResolutionProcessor::class,
+ CapabilityResourceResolutionProcessor::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class,
+ BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
@EnableAutoConfiguration
fun testRegisteredSource() {
val sources = resourceResolutionService.registeredResourceSources()
assertNotNull(sources, "failed to get registered sources")
- assertTrue(sources.containsAll(arrayListOf("source-input", "source-default", "source-db",
- "source-rest", "source-capability")), "failed to get registered sources : $sources")
+ assertTrue(
+ sources.containsAll(
+ arrayListOf(
+ "source-input", "source-default", "source-db",
+ "source-rest", "source-capability"
+ )
+ ), "failed to get registered sources : $sources"
+ )
}
@Test
Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService)
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput =
- JacksonUtils.readValueFromClassPathFile("payload/requests/sample-resourceresolution-request.json",
- ExecutionServiceInput::class.java)!!
-
+ JacksonUtils.readValueFromClassPathFile(
+ "payload/requests/sample-resourceresolution-request.json",
+ ExecutionServiceInput::class.java
+ )!!
val resourceAssignmentRuntimeService =
- ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService,
- "testResolveResource")
-
+ ResourceAssignmentUtils.transformToRARuntimeService(
+ bluePrintRuntimeService,
+ "testResolveResource"
+ )
// Prepare Inputs
- PayloadUtils.prepareInputsFromWorkflowPayload(bluePrintRuntimeService,
- executionServiceInput.payload,
- "resource-assignment")
-
- resourceResolutionService.resolveResources(resourceAssignmentRuntimeService,
- "resource-assignment",
- "baseconfig",
- props)
-
+ PayloadUtils.prepareInputsFromWorkflowPayload(
+ bluePrintRuntimeService,
+ executionServiceInput.payload,
+ "resource-assignment"
+ )
+
+ resourceResolutionService.resolveResources(
+ resourceAssignmentRuntimeService,
+ "resource-assignment",
+ "baseconfig",
+ props
+ )
}
}
runBlocking {
Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService)
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput =
- JacksonUtils.readValueFromClassPathFile("payload/requests/sample-resourceresolution-request.json",
- ExecutionServiceInput::class.java)!!
+ JacksonUtils.readValueFromClassPathFile(
+ "payload/requests/sample-resourceresolution-request.json",
+ ExecutionServiceInput::class.java
+ )!!
val artefactNames = listOf("baseconfig", "another")
// Prepare Inputs
- PayloadUtils.prepareInputsFromWorkflowPayload(bluePrintRuntimeService,
- executionServiceInput.payload,
- "resource-assignment")
-
- resourceResolutionService.resolveResources(bluePrintRuntimeService,
- "resource-assignment",
- artefactNames,
- props)
+ PayloadUtils.prepareInputsFromWorkflowPayload(
+ bluePrintRuntimeService,
+ executionServiceInput.payload,
+ "resource-assignment"
+ )
+
+ resourceResolutionService.resolveResources(
+ bluePrintRuntimeService,
+ "resource-assignment",
+ artefactNames,
+ props
+ )
}
-
}
@Test
runBlocking {
Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService)
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput =
- JacksonUtils.readValueFromClassPathFile("payload/requests/sample-resourceresolution-request.json",
- ExecutionServiceInput::class.java)!!
+ JacksonUtils.readValueFromClassPathFile(
+ "payload/requests/sample-resourceresolution-request.json",
+ ExecutionServiceInput::class.java
+ )!!
val resourceAssignmentRuntimeService =
- ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService,
- "testResolveResourcesWithMappingAndTemplate")
+ ResourceAssignmentUtils.transformToRARuntimeService(
+ bluePrintRuntimeService,
+ "testResolveResourcesWithMappingAndTemplate"
+ )
val artifactPrefix = "another"
// Prepare Inputs
- PayloadUtils.prepareInputsFromWorkflowPayload(bluePrintRuntimeService,
- executionServiceInput.payload,
- "resource-assignment")
-
- resourceResolutionService.resolveResources(resourceAssignmentRuntimeService,
- "resource-assignment",
- artifactPrefix,
- props)
+ PayloadUtils.prepareInputsFromWorkflowPayload(
+ bluePrintRuntimeService,
+ executionServiceInput.payload,
+ "resource-assignment"
+ )
+
+ resourceResolutionService.resolveResources(
+ resourceAssignmentRuntimeService,
+ "resource-assignment",
+ artifactPrefix,
+ props
+ )
}
}
-
@Test
fun testResolveResourcesWithResourceIdAndResourceType() {
runBlocking {
Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService)
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput =
- JacksonUtils.readValueFromClassPathFile("payload/requests/sample-resourceresolution-request.json",
- ExecutionServiceInput::class.java)!!
+ JacksonUtils.readValueFromClassPathFile(
+ "payload/requests/sample-resourceresolution-request.json",
+ ExecutionServiceInput::class.java
+ )!!
val resourceAssignmentRuntimeService =
- ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService,
- "testResolveResourcesWithMappingAndTemplate")
+ ResourceAssignmentUtils.transformToRARuntimeService(
+ bluePrintRuntimeService,
+ "testResolveResourcesWithMappingAndTemplate"
+ )
val artifactPrefix = "another"
// Prepare Inputs
- PayloadUtils.prepareInputsFromWorkflowPayload(bluePrintRuntimeService,
- executionServiceInput.payload,
- "resource-assignment")
-
- resourceResolutionService.resolveResources(resourceAssignmentRuntimeService,
- "resource-assignment",
- artifactPrefix,
- props)
+ PayloadUtils.prepareInputsFromWorkflowPayload(
+ bluePrintRuntimeService,
+ executionServiceInput.payload,
+ "resource-assignment"
+ )
+
+ resourceResolutionService.resolveResources(
+ resourceAssignmentRuntimeService,
+ "resource-assignment",
+ artifactPrefix,
+ props
+ )
}
}
val raRuntimeService = mockk<ResourceAssignmentRuntimeService>()
every { raRuntimeService.bluePrintContext() } returns mockk<BluePrintContext>()
every { raRuntimeService.getBluePrintError() } returns BluePrintError()
- every { raRuntimeService.setBluePrintError(any())} returns Unit
+ every { raRuntimeService.setBluePrintError(any()) } returns Unit
every { raRuntimeService.getInputValue("device-id") } returns "123456".asJsonPrimitive()
every { raRuntimeService.putResolutionStore(any(), any()) } returns Unit
val sources = arrayListOf<String>("sdno", "sdnc")
val resourceResolutionService = ResourceResolutionServiceImpl(applicationContext, mockk(), mockk(), mockk())
- val resolvedResources = resourceResolutionService.resolveResourceDefinition(raRuntimeService,
- resourceDefinitions, "port-speed", sources)
+ val resolvedResources = resourceResolutionService.resolveResourceDefinition(
+ raRuntimeService,
+ resourceDefinitions, "port-speed", sources
+ )
assertNotNull(resolvedResources, "failed to resolve the resources")
}
}
@Test
fun testNodeTypeSourceInput() {
val nodeType = BluePrintTypes.nodeTypeSourceInput()
- //println(nodeType.asJsonString(true))
+ // println(nodeType.asJsonString(true))
assertNotNull(nodeType, "failed to generate nodeTypeSourceInput")
}
@Test
fun testNodeTypeSourceDefault() {
val nodeType = BluePrintTypes.nodeTypeSourceDefault()
- //println(nodeType.asJsonString(true))
+ // println(nodeType.asJsonString(true))
assertNotNull(nodeType, "failed to generate nodeTypeSourceDefault")
}
@Test
fun testNodeTypeSourceDb() {
val nodeType = BluePrintTypes.nodeTypeSourceDb()
- //println(nodeType.asJsonString(true))
+ // println(nodeType.asJsonString(true))
assertNotNull(nodeType, "failed to generate nodeTypeSourceDb")
}
@Test
fun testNodeTypeSourceRest() {
val nodeType = BluePrintTypes.nodeTypeSourceRest()
- //println(nodeType.asJsonString(true))
+ // println(nodeType.asJsonString(true))
assertNotNull(nodeType, "failed to generate nodeTypeSourceRest")
}
@Test
fun testNodeTypeSourceCapability() {
val nodeType = BluePrintTypes.nodeTypeSourceCapability()
- //println(nodeType.asJsonString(true))
+ // println(nodeType.asJsonString(true))
assertNotNull(nodeType, "failed to generate nodeTypeSourceCapability")
}
@Test
fun testNodeTemplateSourceInput() {
val nodeTemplate = BluePrintTypes.nodeTemplateSourceInput("InputSystem", "") {
-
}
- //println(nodeTemplate.asJsonString(true))
+ // println(nodeTemplate.asJsonString(true))
assertNotNull(nodeTemplate, "failed to generate nodeTemplateSourceInput")
}
@Test
fun testNodeTemplateSourceDefault() {
val nodeTemplate = BluePrintTypes.nodeTemplateSourceDefault("DefaultSystem", "") {
-
}
- //println(nodeTemplate.asJsonString(true))
+ // println(nodeTemplate.asJsonString(true))
assertNotNull(nodeTemplate, "failed to generate nodeTemplateSourceDefault")
}
keyDependencies(arrayListOf("name"))
}
}
- //println(nodeTemplate.asJsonString(true))
+ // println(nodeTemplate.asJsonString(true))
assertNotNull(nodeTemplate, "failed to generate nodeTemplateSourceDb")
}
keyDependencies(arrayListOf("name"))
}
}
- //println(nodeTemplate.asJsonString(true))
+ // println(nodeTemplate.asJsonString(true))
assertNotNull(nodeTemplate, "failed to generate nodeTemplateSourceRest")
}
keyDependencies(arrayListOf("name"))
}
}
- //println(nodeTemplate.asJsonString(true))
+ // println(nodeTemplate.asJsonString(true))
assertNotNull(nodeTemplate, "failed to generate nodeTemplateSourceCapability")
}
-}
\ No newline at end of file
+}
val list = listOf(rr1, rr2)
every {
resourceResolutionRepository.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
- any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any()
+ )
} returns list
runBlocking {
val res =
resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
- bluePrintRuntimeService, resolutionKey, occurrence, artifactPrefix)
+ bluePrintRuntimeService, resolutionKey, occurrence, artifactPrefix
+ )
assertEquals(2, res.size)
}
fun findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrenceTestException() {
every {
resourceResolutionRepository.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
- any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any()
+ )
} throws EmptyResultDataAccessException(1)
runBlocking {
val res =
resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
- bluePrintRuntimeService, resolutionKey, occurrence, artifactPrefix)
+ bluePrintRuntimeService, resolutionKey, occurrence, artifactPrefix
+ )
assert(res.isEmpty())
}
val list = listOf(rr1, rr2)
every {
resourceResolutionRepository.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
- any(), any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any(), any()
+ )
} returns list
runBlocking {
val res =
resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
- bluePrintRuntimeService, resourceId, resourceType, occurrence, artifactPrefix)
+ bluePrintRuntimeService, resourceId, resourceType, occurrence, artifactPrefix
+ )
assertEquals(2, res.size)
}
fun findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrenceTestException() {
every {
resourceResolutionRepository.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
- any(), any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any(), any()
+ )
} throws EmptyResultDataAccessException(1)
runBlocking {
val res =
resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
- bluePrintRuntimeService, resourceId, resourceType, occurrence, artifactPrefix)
+ bluePrintRuntimeService, resourceId, resourceType, occurrence, artifactPrefix
+ )
assert(res.isEmpty())
}
rr.value = "testValue"
every {
resourceResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndName(
- any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any()
+ )
} returns rr
runBlocking {
val res =
resourceResolutionDBService.readValue(
- blueprintName, blueprintVersion, artifactPrefix, resolutionKey, "bob")
+ blueprintName, blueprintVersion, artifactPrefix, resolutionKey, "bob"
+ )
assertEquals(rr.name, res.name)
assertEquals(rr.value, res.value)
val list = listOf(rr1, rr2)
every {
resourceResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
- any(), any(), any(), any())
+ any(), any(), any(), any()
+ )
} returns list
runBlocking {
val res =
resourceResolutionDBService.readWithResolutionKey(
- blueprintName, blueprintVersion, artifactPrefix, resolutionKey)
+ blueprintName, blueprintVersion, artifactPrefix, resolutionKey
+ )
assertEquals(2, res.size)
}
}
val list = listOf(rr1, rr2)
every {
resourceResolutionRepository.findByBlueprintNameAndBlueprintVersionAndResourceIdAndResourceType(
- any(), any(), any(), any())
+ any(), any(), any(), any()
+ )
} returns list
runBlocking {
val res =
resourceResolutionDBService.readWithResourceIdAndResourceType(
- blueprintName, blueprintVersion, resourceId, resourceType)
+ blueprintName, blueprintVersion, resourceId, resourceType
+ )
assertEquals(2, res.size)
}
}
runBlocking {
val res =
resourceResolutionDBService.write(
- props, bluePrintRuntimeService, artifactPrefix, resourceAssignment)
+ props, bluePrintRuntimeService, artifactPrefix, resourceAssignment
+ )
assertEquals(resourceResolution, res)
}
}
-}
\ No newline at end of file
+}
runBlocking {
every {
templateResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any()
+ )
} returns tr
val res =
templateResolutionService.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
- bluePrintRuntimeService, artifactPrefix, resolutionKey)
+ bluePrintRuntimeService, artifactPrefix, resolutionKey
+ )
assertEquals(tr.result, res)
}
}
runBlocking {
every {
templateResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any()
+ )
} returns tr
templateResolutionService.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
- bluePrintRuntimeService, artifactPrefix, resolutionKey)
+ bluePrintRuntimeService, artifactPrefix, resolutionKey
+ )
}
}
every { templateResolutionRepository.saveAndFlush(any<TemplateResolution>()) } returns tr
every {
templateResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any()
+ )
} returns null
val res = templateResolutionService.write(props, result, bluePrintRuntimeService, artifactPrefix)
assertEquals(tr, res)
every { templateResolutionRepository.saveAndFlush(any<TemplateResolution>()) } returns tr
every {
templateResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any()
+ )
} returns tr
every {
templateResolutionRepository.deleteByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any()
+ )
} returns Unit
val res = templateResolutionService.write(props, result, bluePrintRuntimeService, artifactPrefix)
verify {
templateResolutionRepository.deleteByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- eq(resolutionKey), eq(blueprintName), eq(blueprintVersion), eq(artifactPrefix), eq(occurrence))
+ eq(resolutionKey), eq(blueprintName), eq(blueprintVersion), eq(artifactPrefix), eq(occurrence)
+ )
}
assertEquals(tr, res)
}
every { templateResolutionRepository.saveAndFlush(any<TemplateResolution>()) } returns tr
every {
templateResolutionRepository.findByResourceIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- any(), any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any(), any()
+ )
} returns tr
every {
templateResolutionRepository.deleteByResourceIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- any(), any(), any(), any(), any(), any())
+ any(), any(), any(), any(), any(), any()
+ )
} returns Unit
val res = templateResolutionService.write(props, result, bluePrintRuntimeService, artifactPrefix)
verify {
templateResolutionRepository.deleteByResourceIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactNameAndOccurrence(
- eq(resourceId), eq(resourceType), eq(blueprintName), eq(blueprintVersion), eq(artifactPrefix), eq(occurrence))
+ eq(resourceId), eq(resourceType), eq(blueprintName), eq(blueprintVersion), eq(artifactPrefix), eq(occurrence)
+ )
}
assertEquals(tr, res)
}
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
class MockBluePrintRestLibPropertyService(bluePrintProperties: BluePrintPropertiesService) :
- BluePrintRestLibPropertyService(bluePrintProperties) {
+ BluePrintRestLibPropertyService(bluePrintProperties) {
- fun mockBlueprintWebClientService (selector: String):
+ fun mockBlueprintWebClientService(selector: String):
MockBlueprintWebClientService {
val prefix = "blueprintsprocessor.restclient.$selector"
val restClientProperties = restClientProperties(prefix)
MockBlueprintWebClientService {
return MockBlueprintWebClientService(restClientProperties)
}
-}
\ No newline at end of file
+}
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import java.nio.charset.Charset
-import java.util.*
+import java.util.Base64
-class MockBlueprintWebClientService(private var restClientProperties: RestClientProperties): BlueprintWebClientService {
+class MockBlueprintWebClientService(private var restClientProperties: RestClientProperties) : BlueprintWebClientService {
private var mockServer: ClientAndServer
private var port: String = if (restClientProperties.url.split(":")[2].isEmpty()) "8080"
- else restClientProperties.url.split(":")[2]
+ else restClientProperties.url.split(":")[2]
private var headers: Map<String, String>
init {
- mockServer = ClientAndServer.startClientAndServer(port.toInt())
- headers = defaultHeaders()
+ mockServer = ClientAndServer.startClientAndServer(port.toInt())
+ headers = defaultHeaders()
// Create expected requests and responses
setRequest("GET", "/aai/v14/network/generic-vnfs/generic-vnf/123456")
- setRequest("GET", "/config/GENERIC-RESOURCE-API:services/service/10/service-data/vnfs/vnf/123456/" +
- "vnf-data/vnf-topology/vnf-parameters-data/param/vnf_name")
- setRequestWithPayload("PUT", "/query",
- "{\r\n\"start\": \"\\/nodes\\/vf-modules?vf-module-name=vf-module-name\",\r\n\"query\": \"\\/query\\/related-to?startingNodeType=vf-module&relatedToNodeType=generic-vnf\"\r\n}")
+ setRequest(
+ "GET", "/config/GENERIC-RESOURCE-API:services/service/10/service-data/vnfs/vnf/123456/" +
+ "vnf-data/vnf-topology/vnf-parameters-data/param/vnf_name"
+ )
+ setRequestWithPayload(
+ "PUT", "/query",
+ "{\r\n\"start\": \"\\/nodes\\/vf-modules?vf-module-name=vf-module-name\",\r\n\"query\": \"\\/query\\/related-to?startingNodeType=vf-module&relatedToNodeType=generic-vnf\"\r\n}"
+ )
}
override fun defaultHeaders(): Map<String, String> {
val encodedCredentials = this.setBasicAuth("admin", "aaiTest")
return mapOf(
- HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE,
- HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE,
- HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials")
+ HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE,
+ HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE,
+ HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials"
+ )
}
override fun host(uri: String): String {
else -> {
"Get response"
}
-
}
- mockServer.`when`(request().withHeaders(Header(HttpHeaders.AUTHORIZATION, headers[HttpHeaders.AUTHORIZATION]))
- .withMethod(method)
- .withPath(path)
+ mockServer.`when`(
+ request().withHeaders(Header(HttpHeaders.AUTHORIZATION, headers[HttpHeaders.AUTHORIZATION]))
+ .withMethod(method)
+ .withPath(path)
).respond(response().withStatusCode(200).withBody("{\"aai-resource\":\"$requestResponse\"}"))
}
else -> {
"Get response"
}
-
}
- mockServer.`when`(request().withHeaders(Header(HttpHeaders.AUTHORIZATION, headers[HttpHeaders.AUTHORIZATION]))
+ mockServer.`when`(
+ request().withHeaders(Header(HttpHeaders.AUTHORIZATION, headers[HttpHeaders.AUTHORIZATION]))
.withMethod(method)
.withPath(path)
.withQueryStringParameter("format", "resource")
private fun setBasicAuth(username: String, password: String): String {
val credentialsString = "$username:$password"
return Base64.getEncoder().encodeToString(
- credentialsString.toByteArray(Charset.defaultCharset()))
+ credentialsString.toByteArray(Charset.defaultCharset())
+ )
}
}
@Bean(name = ["MariaDatabaseConfiguration", "MySqlDatabaseConfiguration", "PrimaryDatabaseConfiguration"])
open fun createDatabaseConfiguration(): BluePrintDBLibGenericService {
- return mockk<BluePrintDBLibGenericService>()
+ return mockk<BluePrintDBLibGenericService>()
}
}
every { bluePrintValidatorService.validateBluePrints(any<BluePrintRuntimeService<*>>()) } returns true
return bluePrintValidatorService
}
-
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.slf4j.LoggerFactory
-import java.util.*
+import java.util.HashMap
-class MockRestResourceResolutionProcessor(private val blueprintRestLibPropertyService:
- MockBluePrintRestLibPropertyService) : ResourceAssignmentProcessor() {
+class MockRestResourceResolutionProcessor(
+ private val blueprintRestLibPropertyService:
+ MockBluePrintRestLibPropertyService
+) : ResourceAssignmentProcessor() {
private val logger = LoggerFactory.getLogger(MockRestResourceResolutionProcessor::class.java)
resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
- logger.info("MockRestResource ($dSource) dictionary information: " +
- "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})")
+ logger.info(
+ "MockRestResource ($dSource) dictionary information: " +
+ "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
+ )
// Get the Rest Client Service
val restClientService = blueprintWebClientService(executionRequest)
populateResource(executionRequest, sourceProperties, responseBody, path)
restClientService.tearDown()
} else {
- val errMsg = "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
+ val errMsg =
+ "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
logger.warn(errMsg)
throw BluePrintProcessorException(errMsg)
}
}
@Throws(BluePrintProcessorException::class)
- private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource,
- restResponse: String, path: String) {
+ private fun populateResource(
+ resourceAssignment: ResourceAssignment,
+ sourceProperties: RestResourceSource,
+ restResponse: String,
+ path: String
+ ) {
val type = nullToEmpty(resourceAssignment.property?.type)
lateinit var entrySchemaType: String
}
}
-open class MockCapabilityService {
-
-}
+open class MockCapabilityService
open class MockCapabilityScriptRA : ResourceAssignmentProcessor() {
val log = logger(MockCapabilityScriptRA::class)
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ResourceAssignment) {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertySevice
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock.MockBlueprintProcessorCatalogServiceImpl
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DatabaseResourceAssignmentProcessor::class, BluePrintPropertyConfiguration::class,
- BluePrintPropertiesService::class, BluePrintDBLibPropertySevice::class, BluePrintDBLibConfiguration::class,
- BluePrintCoreConfiguration::class, MockDatabaseConfiguration::class, MockBlueprintProcessorCatalogServiceImpl::class,
- BluePrintPropertiesService::class, PrimaryDatabaseConfiguration::class])
+@ContextConfiguration(
+ classes = [DatabaseResourceAssignmentProcessor::class, BluePrintPropertyConfiguration::class,
+ BluePrintPropertiesService::class, BluePrintDBLibPropertyService::class, BluePrintDBLibConfiguration::class,
+ BluePrintCoreConfiguration::class, MockDatabaseConfiguration::class, MockBlueprintProcessorCatalogServiceImpl::class,
+ BluePrintPropertiesService::class, PrimaryDatabaseConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class DatabaseResourceResolutionProcessorTest {
fun `test database resource resolution processor db`() {
runBlocking {
val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext)
databaseResourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
databaseResourceAssignmentProcessor.resourceDictionaries = ResourceAssignmentUtils
- .resourceDefinitions(bluePrintContext.rootPath)
+ .resourceDefinitions(bluePrintContext.rootPath)
val resourceAssignment = ResourceAssignment().apply {
name = "service-instance-id"
assertNotNull(processorName, "couldn't get Database resource assignment processor name")
}
}
-}
\ No newline at end of file
+}
fun `test default resource resolution`() {
runBlocking {
val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext)
println(processorName)
}
}
-}
\ No newline at end of file
+}
runBlocking {
val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val resourceAssignmentRuntimeService = spyk(ResourceAssignmentRuntimeService("1234", bluePrintContext))
// mocking input for resource resolution
val textNode: JsonNode = TextNode("any value")
- every {resourceAssignmentRuntimeService.getInputValue("rr-name") } returns textNode
+ every { resourceAssignmentRuntimeService.getInputValue("rr-name") } returns textNode
inputResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService
inputResourceResolutionProcessor.resourceDictionaries = ResourceAssignmentUtils.resourceDefinitions(bluePrintContext.rootPath)
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [MockRestResourceResolutionProcessor::class, MockBluePrintRestLibPropertyService::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, RestClientProperties::class])
+@ContextConfiguration(
+ classes = [MockRestResourceResolutionProcessor::class, MockBluePrintRestLibPropertyService::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, RestClientProperties::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class RestResourceResolutionProcessorTest {
+
@Autowired
lateinit var bluePrintRestLibPropertyService: MockBluePrintRestLibPropertyService
private lateinit var restResourceResolutionProcessor: MockRestResourceResolutionProcessor
@BeforeTest
- fun init(){
+ fun init() {
restResourceResolutionProcessor = MockRestResourceResolutionProcessor(bluePrintRestLibPropertyService)
}
fun `test rest resource resolution`() {
runBlocking {
val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext)
restResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService
restResourceResolutionProcessor.resourceDictionaries = ResourceAssignmentUtils
- .resourceDefinitions(bluePrintContext.rootPath)
+ .resourceDefinitions(bluePrintContext.rootPath)
val scriptPropertyInstances: MutableMap<String, Any> = mutableMapOf()
scriptPropertyInstances["mock-service1"] = MockCapabilityService()
fun `test rest aai get resource resolution`() {
runBlocking {
val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext)
restResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService
restResourceResolutionProcessor.resourceDictionaries = ResourceAssignmentUtils
- .resourceDefinitions(bluePrintContext.rootPath)
+ .resourceDefinitions(bluePrintContext.rootPath)
val scriptPropertyInstances: MutableMap<String, Any> = mutableMapOf()
scriptPropertyInstances["mock-service1"] = MockCapabilityService()
fun `test rest aai put resource resolution`() {
runBlocking {
val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext)
restResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService
restResourceResolutionProcessor.resourceDictionaries = ResourceAssignmentUtils
- .resourceDefinitions(bluePrintContext.rootPath)
+ .resourceDefinitions(bluePrintContext.rootPath)
val scriptPropertyInstances: MutableMap<String, Any> = mutableMapOf()
scriptPropertyInstances["mock-service1"] = MockCapabilityService()
fun setup() {
val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
- "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
resourceAssignmentRuntimeService = spyk(ResourceAssignmentRuntimeService("1234", bluePrintContext))
- //Init input map and expected values for tests
+ // Init input map and expected values for tests
initInputMapAndExpectedValuesForPrimitiveType()
initInputMapAndExpectedValuesForCollection()
initInputMapAndExpectedValuesForComplexType()
@Test
fun `generateResourceDataForAssignments - positive test`() {
- //given a valid resource assignment
+ // given a valid resource assignment
val validResourceAssignment = createResourceAssignmentForTest("valid_value")
- //and a list containing that resource assignment
+ // and a list containing that resource assignment
val resourceAssignmentList = listOf<ResourceAssignment>(validResourceAssignment)
- //when the values of the resources are evaluated
+ // when the values of the resources are evaluated
val outcome = ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignmentList)
- //then the assignment should produce a valid result
+ // then the assignment should produce a valid result
val expected = "{\n" + " \"pnf-id\" : \"valid_value\"\n" + "}"
- assertEquals(expected, outcome.replace("\r\n","\n"), "unexpected outcome generated")
+ assertEquals(expected, outcome.replace("\r\n", "\n"), "unexpected outcome generated")
}
@Test
fun `generateResourceDataForAssignments - resource without value is not resolved as null`() {
- //given a valid resource assignment
+ // given a valid resource assignment
val resourceAssignmentWithNullValue = createResourceAssignmentForTest(null)
- //and a list containing that resource assignment
+ // and a list containing that resource assignment
val resourceAssignmentList = listOf<ResourceAssignment>(resourceAssignmentWithNullValue)
- //when the values of the resources are evaluated
+ // when the values of the resources are evaluated
val outcome = ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignmentList)
- //then the assignment should produce a valid result
+ // then the assignment should produce a valid result
val expected = "{\n" + " \"pnf-id\" : \"\${pnf-id}\"\n" + "}"
- assertEquals(expected, outcome.replace("\r\n","\n"), "unexpected outcome generated")
-
+ assertEquals(expected, outcome.replace("\r\n", "\n"), "unexpected outcome generated")
}
private fun createResourceAssignmentForTest(resourceValue: String?): ResourceAssignment {
}
@Test
- fun parseResponseNodeTestForPrimitivesTypes(){
- var outcome = prepareResponseNodeForTest("sample-value", "string", "",
- inputMapToTestPrimitiveTypeWithValue)
+ fun parseResponseNodeTestForPrimitivesTypes() {
+ var outcome = prepareResponseNodeForTest(
+ "sample-value", "string", "",
+ inputMapToTestPrimitiveTypeWithValue
+ )
assertEquals(expectedValueToTestPrimitiveType, outcome, "Unexpected outcome returned for primitive type of simple String")
- outcome = prepareResponseNodeForTest("sample-key-value", "string", "",
- inputMapToTestPrimitiveTypeWithKeyValue)
+ outcome = prepareResponseNodeForTest(
+ "sample-key-value", "string", "",
+ inputMapToTestPrimitiveTypeWithKeyValue
+ )
assertEquals(expectedValueToTestPrimitiveType, outcome, "Unexpected outcome returned for primitive type of key-value String")
}
@Test
- fun parseResponseNodeTestForCollectionsOfString(){
- var outcome = prepareResponseNodeForTest("listOfString", "list",
- "string", inputMapToTestCollectionOfPrimitiveType)
+ fun parseResponseNodeTestForCollectionsOfString() {
+ var outcome = prepareResponseNodeForTest(
+ "listOfString", "list",
+ "string", inputMapToTestCollectionOfPrimitiveType
+ )
assertEquals(expectedValueToTesCollectionOfPrimitiveType, outcome, "unexpected outcome returned for list of String")
- outcome = prepareResponseNodeForTest("mapOfString", "map", "string",
- inputMapToTestCollectionOfPrimitiveType)
+ outcome = prepareResponseNodeForTest(
+ "mapOfString", "map", "string",
+ inputMapToTestCollectionOfPrimitiveType
+ )
assertEquals(expectedValueToTesCollectionOfPrimitiveType, outcome, "unexpected outcome returned for map of String")
}
@Test
- fun parseResponseNodeTestForCollectionsOfComplexType(){
- var outcome = prepareResponseNodeForTest("listOfMyDataTypeWithOneOutputKeyMapping", "list",
- "ip-address", inputMapToTestCollectionOfComplexTypeWithOneOutputKeyMapping)
+ fun parseResponseNodeTestForCollectionsOfComplexType() {
+ var outcome = prepareResponseNodeForTest(
+ "listOfMyDataTypeWithOneOutputKeyMapping", "list",
+ "ip-address", inputMapToTestCollectionOfComplexTypeWithOneOutputKeyMapping
+ )
assertEquals(expectedValueToTestCollectionOfComplexTypeWithOneOutputKeyMapping, outcome, "unexpected outcome returned for list of String")
- outcome = prepareResponseNodeForTest("listOfMyDataTypeWithAllOutputKeyMapping", "list",
- "ip-address", inputMapToTestCollectionOfComplexTypeWithAllOutputKeyMapping)
+ outcome = prepareResponseNodeForTest(
+ "listOfMyDataTypeWithAllOutputKeyMapping", "list",
+ "ip-address", inputMapToTestCollectionOfComplexTypeWithAllOutputKeyMapping
+ )
assertEquals(expectedValueToTestCollectionOfComplexTypeWithAllOutputKeyMapping, outcome, "unexpected outcome returned for list of String")
}
@Test
- fun `parseResponseNodeTestForComplexType find one output key mapping`(){
- val outcome = prepareResponseNodeForTest("complexTypeOneKeys", "host",
- "", inputMapToTestComplexTypeWithOneOutputKeyMapping)
+ fun `parseResponseNodeTestForComplexType find one output key mapping`() {
+ val outcome = prepareResponseNodeForTest(
+ "complexTypeOneKeys", "host",
+ "", inputMapToTestComplexTypeWithOneOutputKeyMapping
+ )
assertEquals(expectedValueToTestComplexTypeWithOneOutputKeyMapping, outcome, "Unexpected outcome returned for complex type")
}
@Test
- fun `parseResponseNodeTestForComplexType find all output key mapping`(){
- val outcome = prepareResponseNodeForTest("complexTypeAllKeys", "host",
- "", inputMapToTestComplexTypeWithAllOutputKeyMapping)
+ fun `parseResponseNodeTestForComplexType find all output key mapping`() {
+ val outcome = prepareResponseNodeForTest(
+ "complexTypeAllKeys", "host",
+ "", inputMapToTestComplexTypeWithAllOutputKeyMapping
+ )
assertEquals(expectedValueToTestComplexTypeWithAllOutputKeyMapping, outcome, "Unexpected outcome returned for complex type")
}
private fun initInputMapAndExpectedValuesForPrimitiveType() {
inputMapToTestPrimitiveTypeWithValue = "1.2.3.1".asJsonType()
val keyValue = mutableMapOf<String, String>()
- keyValue["value"]= "1.2.3.1"
+ keyValue["value"] = "1.2.3.1"
inputMapToTestPrimitiveTypeWithKeyValue = keyValue.asJsonType()
expectedValueToTestPrimitiveType = TextNode("1.2.3.1")
}
- private fun initInputMapAndExpectedValuesForCollection(){
+ private fun initInputMapAndExpectedValuesForCollection() {
val listOfIps = arrayListOf("1.2.3.1", "1.2.3.2", "1.2.3.3")
val arrayNodeForList1 = JacksonUtils.objectMapper.createArrayNode()
listOfIps.forEach {
}
inputMapToTestCollectionOfPrimitiveType = arrayNodeForList1
- expectedValueToTesCollectionOfPrimitiveType = arrayListOf(ExpectedResponseIp("1.2.3.1"),
- ExpectedResponseIp( "1.2.3.2"), ExpectedResponseIp("1.2.3.3")).asJsonType()
-
+ expectedValueToTesCollectionOfPrimitiveType = arrayListOf(
+ ExpectedResponseIp("1.2.3.1"),
+ ExpectedResponseIp("1.2.3.2"), ExpectedResponseIp("1.2.3.3")
+ ).asJsonType()
- val listOfIpAddresses = arrayListOf(IpAddress("1111", "1.2.3.1").asJsonType(),
- IpAddress("2222", "1.2.3.2").asJsonType(), IpAddress("3333", "1.2.3.3").asJsonType())
+ val listOfIpAddresses = arrayListOf(
+ IpAddress("1111", "1.2.3.1").asJsonType(),
+ IpAddress("2222", "1.2.3.2").asJsonType(), IpAddress("3333", "1.2.3.3").asJsonType()
+ )
val arrayNodeForList2 = JacksonUtils.objectMapper.createArrayNode()
listOfIpAddresses.forEach {
val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
arrayNodeForList3.add(childNode)
inputMapToTestCollectionOfComplexTypeWithAllOutputKeyMapping = arrayNodeForList3
- expectedValueToTestCollectionOfComplexTypeWithOneOutputKeyMapping = arrayListOf(ExpectedResponseIpAddress(IpAddress("1111", "1.2.3.1")),
- ExpectedResponseIpAddress(IpAddress("2222", "1.2.3.2")), ExpectedResponseIpAddress(
- IpAddress("3333", "1.2.3.3"))).asJsonType()
- expectedValueToTestCollectionOfComplexTypeWithAllOutputKeyMapping = arrayListOf(IpAddress("1111", "1.2.3.1"),
- IpAddress("2222", "1.2.3.2"),
- IpAddress("3333", "1.2.3.3")).asJsonType()
+ expectedValueToTestCollectionOfComplexTypeWithOneOutputKeyMapping = arrayListOf(
+ ExpectedResponseIpAddress(IpAddress("1111", "1.2.3.1")),
+ ExpectedResponseIpAddress(IpAddress("2222", "1.2.3.2")), ExpectedResponseIpAddress(
+ IpAddress("3333", "1.2.3.3")
+ )
+ ).asJsonType()
+ expectedValueToTestCollectionOfComplexTypeWithAllOutputKeyMapping = arrayListOf(
+ IpAddress("1111", "1.2.3.1"),
+ IpAddress("2222", "1.2.3.2"),
+ IpAddress("3333", "1.2.3.3")
+ ).asJsonType()
}
- private fun initInputMapAndExpectedValuesForComplexType(){
+ private fun initInputMapAndExpectedValuesForComplexType() {
val mapOfComplexType = mutableMapOf<String, JsonNode>()
mapOfComplexType["value"] = Host("my-ipAddress", IpAddress("1111", "1.2.3.1")).asJsonType()
mapOfComplexType["port"] = "8888".asJsonType()
inputMapToTestComplexTypeWithOneOutputKeyMapping = mapOfComplexType.asJsonType()
val objectNode = JacksonUtils.objectMapper.createObjectNode()
- expectedValueToTestComplexTypeWithOneOutputKeyMapping = objectNode.set("host", Host("my-ipAddress", IpAddress("1111", "1.2.3.1")).asJsonType())
+ expectedValueToTestComplexTypeWithOneOutputKeyMapping =
+ objectNode.set("host", Host("my-ipAddress", IpAddress("1111", "1.2.3.1")).asJsonType())
val childNode1 = JacksonUtils.objectMapper.createObjectNode()
childNode1.set("name", "my-ipAddress".asJsonPrimitive())
expectedValueToTestComplexTypeWithAllOutputKeyMapping = childNode2
}
- private fun prepareResponseNodeForTest(dictionary_source: String, sourceType: String, entrySchema: String,
- response: Any): JsonNode {
+ private fun prepareResponseNodeForTest(
+ dictionary_source: String,
+ sourceType: String,
+ entrySchema: String,
+ response: Any
+ ): JsonNode {
val resourceAssignment = when (sourceType) {
"list", "map" -> {
when (dictionary_source) {
"sample-key-value", "sample-value" -> {
- //Primary Type
- if (dictionary_source=="sample-key-value")
+ // Primary Type
+ if (dictionary_source == "sample-key-value")
outputMapping["sample-ip"] = "value"
}
"listOfString", "mapOfString" -> {
- //List of string
+ // List of string
outputMapping["ip"] = "value"
}
"listOfMyDataTypeWithOneOutputKeyMapping", "listOfMyDataTypeWithAllOutputKeyMapping" -> {
- //List or map of complex Type
+ // List or map of complex Type
if (dictionary_source == "listOfMyDataTypeWithOneOutputKeyMapping")
outputMapping["ipAddress"] = "value"
else {
}
}
else -> {
- //Complex Type
+ // Complex Type
if (dictionary_source == "complexTypeOneKeys")
outputMapping["host"] = "value"
else {
outputMapping["name"] = "name"
outputMapping["ipAddress"] = "ipAddress"
}
-
}
}
return outputMapping
}
-}
\ No newline at end of file
+}
* limitations under the License.
*/
@file:Suppress("unused")
+
package internal.scripts
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
}
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
- //val webClientService = restClientService("odlparent")
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ // val webClientService = restClientService("odlparent")
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
addError("failed in restconf execution : ${runtimeException.message}")
}
-
}
/**
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
-
@Configuration
@ComponentScan
@EnableConfigurationProperties
@ConditionalOnProperty(name = ["blueprintsprocessor.restconfEnabled"], havingValue = "true")
-open class RestconfExecutorConfiguration
\ No newline at end of file
+open class RestconfExecutorConfiguration
* Generic Mount function
*/
-suspend fun AbstractScriptComponentFunction.restconfMountDevice(webClientService: BlueprintWebClientService,
- deviceId: String,
- payload: Any,
- headers: Map<String, String> = mutableMapOf("Content-Type" to "application/xml")) {
+suspend fun AbstractScriptComponentFunction.restconfMountDevice(
+ webClientService: BlueprintWebClientService,
+ deviceId: String,
+ payload: Any,
+ headers: Map<String, String> = mutableMapOf("Content-Type" to "application/xml")
+) {
val mountUrl = "restconf/config/network-topology:network-topology/topology/topology-netconf/node/$deviceId"
log.info("sending mount request, url: $mountUrl")
/**
* Generic Configure function
*/
-suspend fun AbstractScriptComponentFunction.restconfApplyDeviceConfig(webClientService: BlueprintWebClientService,
- deviceId: String, configletResourcePath: String,
- configletToApply: Any,
- additionalHeaders: Map<String, String > = mutableMapOf("Content-Type" to "application/yang.patch+xml")) {
+suspend fun AbstractScriptComponentFunction.restconfApplyDeviceConfig(
+ webClientService: BlueprintWebClientService,
+ deviceId: String,
+ configletResourcePath: String,
+ configletToApply: Any,
+ additionalHeaders: Map<String, String> = mutableMapOf("Content-Type" to "application/yang.patch+xml")
+) {
log.debug("headers: $additionalHeaders")
log.info("configuring device: $deviceId, Configlet: $configletToApply")
val applyConfigUrl = "restconf/config/network-topology:network-topology/topology/topology-netconf/node/" +
"$deviceId/$configletResourcePath"
- val result:Any = webClientService.exchangeResource("PATCH", applyConfigUrl, configletToApply as String, additionalHeaders)
+ val result: Any = webClientService.exchangeResource("PATCH", applyConfigUrl, configletToApply as String, additionalHeaders)
log.info("Configuration application result: $result")
}
-
-suspend fun AbstractScriptComponentFunction.restconfDeviceConfig(webClientService: BlueprintWebClientService,
- deviceId: String, configletResourcePath: String)
- : BlueprintWebClientService.WebClientResponse<String> {
+suspend fun AbstractScriptComponentFunction.restconfDeviceConfig(
+ webClientService: BlueprintWebClientService,
+ deviceId: String,
+ configletResourcePath: String
+):
+ BlueprintWebClientService.WebClientResponse<String> {
val configPathUrl = "restconf/config/network-topology:network-topology/topology/topology-netconf/node/" +
"$deviceId/$configletResourcePath"
/**
* Generic UnMount function
*/
-suspend fun AbstractScriptComponentFunction.restconfUnMountDevice(webClientService: BlueprintWebClientService,
- deviceId: String, payload: String) {
+suspend fun AbstractScriptComponentFunction.restconfUnMountDevice(
+ webClientService: BlueprintWebClientService,
+ deviceId: String,
+ payload: String
+) {
val unMountUrl = "restconf/config/network-topology:network-topology/topology/topology-netconf/node/$deviceId"
log.info("sending unMount request, url: $unMountUrl")
webClientService.exchangeResource("DELETE", unMountUrl, "")
-}
\ No newline at end of file
+}
operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive()
operationInputs[ComponentScriptExecutor.INPUT_SCRIPT_TYPE] = BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive()
operationInputs[ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE] =
- "internal.scripts.TestRestconfConfigure".asJsonPrimitive()
+ "internal.scripts.TestRestconfConfigure".asJsonPrimitive()
val stepInputData = StepData().apply {
name = "activate-restconf"
val blueprintContext = mockk<BluePrintContext>()
every { bluePrintRuntime.bluePrintContext() } returns blueprintContext
every {
- bluePrintRuntime.resolveNodeTemplateInterfaceOperationInputs("activate-restconf",
- "interfaceName", "operationName")
+ bluePrintRuntime.resolveNodeTemplateInterfaceOperationInputs(
+ "activate-restconf",
+ "interfaceName", "operationName"
+ )
} returns operationInputs
val operationOutputs = hashMapOf<String, JsonNode>()
every {
- bluePrintRuntime.resolveNodeTemplateInterfaceOperationOutputs("activate-restconf",
- "interfaceName", "operationName")
+ bluePrintRuntime.resolveNodeTemplateInterfaceOperationOutputs(
+ "activate-restconf",
+ "interfaceName", "operationName"
+ )
} returns operationOutputs
componentScriptExecutor.applyNB(executionServiceInput)
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.db
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertySevice
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDBLibGenericService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService
import org.springframework.boot.context.properties.EnableConfigurationProperties
@Bean("primary-database-properties")
open fun getPrimaryProperties(): PrimaryDataSourceProperties {
- return bluePrintPropertiesService.propertyBeanType(DBLibConstants.PREFIX_DB,
- PrimaryDataSourceProperties::class.java)
+ return bluePrintPropertiesService.propertyBeanType(
+ DBLibConstants.PREFIX_DB,
+ PrimaryDataSourceProperties::class.java
+ )
}
}
/**
* Exposed Dependency Service by this SSH Lib Module
*/
-fun BluePrintDependencyService.dbLibPropertyService(): BluePrintDBLibPropertySevice =
- instance(BluePrintDBLibPropertySevice::class)
+fun BluePrintDependencyService.dbLibPropertyService(): BluePrintDBLibPropertyService =
+ instance(BluePrintDBLibPropertyService::class)
fun BluePrintDependencyService.primaryDBLibGenericService(): BluePrintDBLibGenericService =
- instance(PrimaryDBLibGenericService::class)
-
+ instance(PrimaryDBLibGenericService::class)
class DBLibConstants {
companion object {
const val PREFIX_DB: String = "blueprintsprocessor.db"
- //list of database
+ // list of database
const val MARIA_DB: String = "maria-db"
const val PRIMARY_DB: String = "processor-db"
const val MYSQL_DB: String = "mysql-db"
const val ORACLE_DB: String = "oracle-db"
const val POSTGRES_DB: String = "postgres-db"
- //List of database drivers
+ // List of database drivers
const val DRIVER_MARIA_DB = "org.mariadb.jdbc.Driver"
const val DRIVER_MYSQL_DB = "com.mysql.jdbc.Driver"
const val DRIVER_ORACLE_DB = "oracle.jdbc.driver.OracleDriver"
package org.onap.ccsdk.cds.blueprintsprocessor.db
-
open class DBDataSourceProperties {
lateinit var url: String
lateinit var username: String
open lateinit var driverClassName: String
}
-open class PrimaryDataSourceProperties: DBDataSourceProperties() {
+open class PrimaryDataSourceProperties : DBDataSourceProperties() {
lateinit var hibernateHbm2ddlAuto: String
lateinit var hibernateDDLAuto: String
lateinit var hibernateNamingStrategy: String
lateinit var hibernateDialect: String
}
-open class MariaDataSourceProperties: DBDataSourceProperties() {
+open class MariaDataSourceProperties : DBDataSourceProperties() {
lateinit var hibernateHbm2ddlAuto: String
lateinit var hibernateDDLAuto: String
lateinit var hibernateNamingStrategy: String
override var driverClassName = DBLibConstants.DRIVER_MARIA_DB
}
-open class MySqlDataSourceProperties: DBDataSourceProperties() {
+open class MySqlDataSourceProperties : DBDataSourceProperties() {
lateinit var hibernateHbm2ddlAuto: String
lateinit var hibernateDDLAuto: String
lateinit var hibernateNamingStrategy: String
fun update(sql: String, params: Map<String, Any>): Int
}
-abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate)
- : BluePrintDBLibGenericService {
+abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate) :
+ BluePrintDBLibGenericService {
override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate {
return namedParameterJdbcTemplate
override fun update(sql: String, params: Map<String, Any>): Int {
return namedParameterJdbcTemplate.update(sql, params)
}
-}
\ No newline at end of file
+}
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.db.*
+import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService
+import org.onap.ccsdk.cds.blueprintsprocessor.db.DBDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.DBLibConstants
+import org.onap.ccsdk.cds.blueprintsprocessor.db.MariaDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.MySqlDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.stereotype.Service
@Service
-class BluePrintDBLibPropertySevice(private var bluePrintPropertiesService: BluePrintPropertiesService) {
+class BluePrintDBLibPropertyService(private var bluePrintPropertiesService: BluePrintPropertiesService) {
fun JdbcTemplate(jsonNode: JsonNode): BluePrintDBLibGenericService {
val dBConnetionProperties = dBDataSourceProperties(jsonNode)
private fun primaryDBConnectionProperties(prefix: String): PrimaryDataSourceProperties {
return bluePrintPropertiesService.propertyBeanType(prefix, PrimaryDataSourceProperties::class.java)
}
-
-}
\ No newline at end of file
+}
fun mariaNamedParameterJdbcTemplate(mariaDataSource: DataSource): NamedParameterJdbcTemplate {
return NamedParameterJdbcTemplate(mariaDataSource)
}
-}
\ No newline at end of file
+}
fun mySqlNamedParameterJdbcTemplate(mySqlDataSource: DataSource): NamedParameterJdbcTemplate {
return NamedParameterJdbcTemplate(mySqlDataSource)
}
-
-
}
import org.springframework.stereotype.Service
@Service
-open class PrimaryDBLibGenericService(primaryNamedParameterJdbcTemplate: NamedParameterJdbcTemplate)
- : AbstractDBLibGenericService(primaryNamedParameterJdbcTemplate) {
-
-}
\ No newline at end of file
+open class PrimaryDBLibGenericService(primaryNamedParameterJdbcTemplate: NamedParameterJdbcTemplate) :
+ AbstractDBLibGenericService(primaryNamedParameterJdbcTemplate)
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter
import org.springframework.transaction.PlatformTransactionManager
-import java.util.*
+import java.util.HashMap
import javax.sql.DataSource
@Configuration
-@ConditionalOnProperty(name = ["blueprintsprocessor.db.primary.defaultConfig"], havingValue = "true",
- matchIfMissing = true)
+@ConditionalOnProperty(
+ name = ["blueprintsprocessor.db.primary.defaultConfig"], havingValue = "true",
+ matchIfMissing = true
+)
@ComponentScan
@EnableJpaRepositories(
- basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.*",
- "org.onap.ccsdk.cds.controllerblueprints.*"],
- entityManagerFactoryRef = "primaryEntityManager",
- transactionManagerRef = "primaryTransactionManager"
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.*",
+ "org.onap.ccsdk.cds.controllerblueprints.*"],
+ entityManagerFactoryRef = "primaryEntityManager",
+ transactionManagerRef = "primaryTransactionManager"
)
@EnableJpaAuditing
open class PrimaryDatabaseConfiguration(private val primaryDataSourceProperties: PrimaryDataSourceProperties) {
+
private val log = LoggerFactory.getLogger(PrimaryDatabaseConfiguration::class.java)!!
@Bean("primaryEntityManager")
open fun primaryEntityManager(): LocalContainerEntityManagerFactoryBean {
val em = LocalContainerEntityManagerFactoryBean()
em.dataSource = primaryDataSource()
- em.setPackagesToScan("org.onap.ccsdk.cds.blueprintsprocessor.*",
- "org.onap.ccsdk.cds.controllerblueprints.*")
+ em.setPackagesToScan(
+ "org.onap.ccsdk.cds.blueprintsprocessor.*",
+ "org.onap.ccsdk.cds.controllerblueprints.*"
+ )
em.jpaVendorAdapter = HibernateJpaVendorAdapter()
val properties = HashMap<String, Any>()
properties["hibernate.hbm2ddl.auto"] = primaryDataSourceProperties.hibernateHbm2ddlAuto
open fun primaryNamedParameterJdbcTemplate(primaryDataSource: DataSource): NamedParameterJdbcTemplate {
return NamedParameterJdbcTemplate(primaryDataSource)
}
-
-}
\ No newline at end of file
+}
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.CascadeType
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.FetchType
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.OneToOne
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
+import javax.persistence.UniqueConstraint
/**
* Provide BlueprintModel Entity
@Table(name = "BLUEPRINT_MODEL", uniqueConstraints = [UniqueConstraint(columnNames = ["artifact_name", "artifact_version"])])
@Proxy(lazy = false)
class BlueprintModel : Serializable {
+
@Id
@Column(name = "blueprint_model_id")
var id: String? = null
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import java.util.Objects
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.JoinColumn
+import javax.persistence.Lob
+import javax.persistence.OneToOne
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
/**
* Provide Blueprint Model Content Entity
return false
}
val blueprintModelContent = o as BlueprintModelContent?
- return (id == blueprintModelContent!!.id && name == blueprintModelContent.name
- && contentType == blueprintModelContent.contentType)
+ return (id == blueprintModelContent!!.id && name == blueprintModelContent.name &&
+ contentType == blueprintModelContent.contentType)
}
override fun hashCode(): Int {
private const val serialVersionUID = 1L
}
-
}
import com.fasterxml.jackson.annotation.JsonTypeName
import org.springframework.data.annotation.LastModifiedDate
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
/**
* Provide Blueprint Model Search Entity
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelContent
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
-import java.util.*
+import java.util.Optional
/**
* @param <T> Model
* @param contentType contentType
* @return B?
*/
- fun findTopByBlueprintModelAndContentType(blueprintModel: BlueprintModel, contentType: String)
- : BlueprintModelContent?
+ fun findTopByBlueprintModelAndContentType(blueprintModel: BlueprintModel, contentType: String):
+ BlueprintModelContent?
/**
* This is a findByBlueprintModelAndContentType method
* @param contentType contentType
* @return List<B>
*/
- fun findByBlueprintModelAndContentType(blueprintModel: BlueprintModel, contentType: String)
- : List<BlueprintModelContent>
+ fun findByBlueprintModelAndContentType(blueprintModel: BlueprintModel, contentType: String):
+ List<BlueprintModelContent>
/**
* This is a findByBlueprintModel method
* @param name name
* @return B?
*/
- fun findByBlueprintModelAndContentTypeAndName(blueprintModel: BlueprintModel,
- contentType: String, name: String): BlueprintModelContent?
+ fun findByBlueprintModelAndContentTypeAndName(
+ blueprintModel: BlueprintModel,
+ contentType: String,
+ name: String
+ ): BlueprintModelContent?
/**
* This is a deleteByMdeleteByBlueprintModelodelName method
* @param id id
*/
override fun deleteById(@NotNull id: String)
-
}
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
-import java.util.*
+import java.util.Optional
import javax.transaction.Transactional
/**
* @param id id
*/
override fun deleteById(@NotNull id: String)
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch
import org.springframework.data.domain.Page
-import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
* @return Optional<BlueprintModelSearch>
</BlueprintModelSearch>
*/
- fun findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(updatedBy: String, tags: String, artifactName: String, artifactVersion: String,
- artifactType: String): List<BlueprintModelSearch>
-
+ fun findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(
+ updatedBy: String,
+ tags: String,
+ artifactName: String,
+ artifactVersion: String,
+ artifactType: String
+ ): List<BlueprintModelSearch>
/**
* This is a findby some attributes method
* @param pageRequest
* @return Page<BlueprintModelSearch>
*/
- fun findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(updatedBy: String, tags: String, artifactName: String, artifactVersion: String,
- artifactType: String,pageRequest: Pageable): Page<BlueprintModelSearch>
-
-
-
-
+ fun findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(
+ updatedBy: String,
+ tags: String,
+ artifactName: String,
+ artifactVersion: String,
+ artifactType: String,
+ pageRequest: Pageable
+ ): Page<BlueprintModelSearch>
}
package org.onap.ccsdk.cds.blueprintsprocessor.db.primary.service
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
+import org.onap.ccsdk.cds.controllerblueprints.core.deCompress
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
import org.slf4j.LoggerFactory
@MappedSuperclass
abstract class BlueprintCatalogServiceImpl(
- private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val blueprintValidator: BluePrintValidatorService) : BluePrintCatalogService {
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val blueprintValidator: BluePrintValidatorService
+) : BluePrintCatalogService {
private val log = LoggerFactory.getLogger(BlueprintCatalogServiceImpl::class.java)!!
return processingId
}
- override suspend fun getFromDatabase(name: String, version: String, extract: Boolean): Path = get(name, version,
- extract)
- ?: throw BluePrintException("Could not find blueprint $name:$version from database")
+ override suspend fun getFromDatabase(name: String, version: String, extract: Boolean): Path = get(
+ name, version,
+ extract
+ )
+ ?: throw BluePrintException("Could not find blueprint $name:$version from database")
override suspend fun deleteFromDatabase(name: String, version: String) = delete(name, version)
abstract suspend fun save(metadata: MutableMap<String, String>, archiveFile: File)
abstract suspend fun get(name: String, version: String, extract: Boolean): Path?
abstract suspend fun delete(name: String, version: String)
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelContent
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants
import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
+import org.onap.ccsdk.cds.controllerblueprints.core.deCompress
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs
import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.io.File
import java.nio.file.Path
-import java.util.*
+import java.util.UUID
// TODO("Duplicate : Merge BlueprintProcessorCatalogServiceImpl and ControllerBlueprintCatalogServiceImpl")
/**
* Similar/Duplicate implementation in [org.onap.ccsdk.cds.controllerblueprints.service.load.ControllerBlueprintCatalogServiceImpl]
*/
@Service("blueprintsProcessorCatalogService")
-class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: BluePrintValidatorService,
- private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val blueprintModelRepository: BlueprintModelRepository)
- : BlueprintCatalogServiceImpl(bluePrintLoadConfiguration, bluePrintRuntimeValidatorService) {
+class BlueprintProcessorCatalogServiceImpl(
+ bluePrintRuntimeValidatorService: BluePrintValidatorService,
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val blueprintModelRepository: BlueprintModelRepository
+) :
+ BlueprintCatalogServiceImpl(bluePrintLoadConfiguration, bluePrintRuntimeValidatorService) {
private val log = LoggerFactory.getLogger(BlueprintProcessorCatalogServiceImpl::class.toString())
override suspend fun delete(name: String, version: String) {
// Clean blueprint script cache
val cacheKey = BluePrintFileUtils
- .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, name, version))
+ .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, name, version))
BluePrintCompileCache.cleanClassLoader(cacheKey)
log.info("removed cba file name($name), version($version) from cache")
// Cleaning Deployed Blueprint
log.info("removed cba file name($name), version($version) from deploy location")
// Cleaning Data Base
blueprintModelRepository
- .deleteByArtifactNameAndArtifactVersion(name, version)
+ .deleteByArtifactNameAndArtifactVersion(name, version)
log.info("removed cba file name($name), version($version) from database")
}
-
override suspend fun get(name: String, version: String, extract: Boolean): Path? {
val deployFile = normalizedFile(bluePrintLoadConfiguration.blueprintDeployPath, name, version)
- val cbaFile = normalizedFile(bluePrintLoadConfiguration.blueprintArchivePath,
- UUID.randomUUID().toString(), "cba.zip")
+ val cbaFile = normalizedFile(
+ bluePrintLoadConfiguration.blueprintArchivePath,
+ UUID.randomUUID().toString(), "cba.zip"
+ )
if (extract && deployFile.exists()) {
log.info("cba file name($name), version($version) already present(${deployFile.absolutePath})")
}
} catch (e: Exception) {
deleteNBDir(deployFile.absolutePath)
- throw BluePrintProcessorException("failed to get get cba file name($name), version($version) from db" +
- " : ${e.message}")
+ throw BluePrintProcessorException(
+ "failed to get get cba file name($name), version($version) from db" +
+ " : ${e.message}"
+ )
} finally {
deleteNBDir(cbaFile.parentFile.absolutePath)
}
log.info("Overwriting blueprint model :$artifactName::$artifactVersion")
blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(artifactName, artifactVersion)
val deployFile =
- normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, artifactName, artifactVersion)
+ normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, artifactName, artifactVersion)
val cacheKey = BluePrintFileUtils.compileCacheKey(deployFile)
BluePrintCompileCache.cleanClassLoader(cacheKey)
blueprintModel.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID]
blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL
blueprintModel.published = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_VALID]
- ?: BluePrintConstants.FLAG_N
+ ?: BluePrintConstants.FLAG_N
blueprintModel.artifactName = artifactName
blueprintModel.artifactVersion = artifactVersion
blueprintModel.updatedBy = metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR]!!
try {
blueprintModelRepository.saveAndFlush(blueprintModel)
} catch (ex: DataIntegrityViolationException) {
- throw BluePrintException(ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " +
- "is already exist in database: ${ex.message}", ex)
+ throw BluePrintException(
+ ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " +
+ "is already exist in database: ${ex.message}", ex
+ )
}
}
-}
\ No newline at end of file
+}
@RunWith(SpringRunner::class)
@EnableAutoConfiguration
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor"])
-@ContextConfiguration(classes = [BlueprintProcessorCatalogServiceImpl::class, BluePrintCoreConfiguration::class,
- MockBlueprintProcessorCatalogServiceImpl::class])
+@ContextConfiguration(
+ classes = [BlueprintProcessorCatalogServiceImpl::class, BluePrintCoreConfiguration::class,
+ MockBlueprintProcessorCatalogServiceImpl::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BlueprintProcessorCatalogServiceImplTest {
@BeforeTest
fun setup() {
deleteDir("target", "blueprints")
- bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(blueprintId,
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ blueprintId,
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
}
@AfterTest
@Test
fun `test catalog service`() {
- //TODO: I thing this test function should be remve and replace by the other one.
+ // TODO: I thing this test function should be remve and replace by the other one.
runBlocking {
- //FIXME("Create ZIP from test blueprints")
+ // FIXME("Create ZIP from test blueprints")
val file = normalizedFile("./src/test/resources/test-cba.zip")
assertTrue(file.exists(), "couldn't get file ${file.absolutePath}")
blueprintsProcessorCatalogService.get("baseconfiguration", "1.0.0", true)
}
- assertTrue(File(blueprintCoreConfiguration.bluePrintLoadConfiguration().blueprintArchivePath +
- "/baseconfiguration").deleteRecursively(),"Couldn't get blueprint archive " +
- "${blueprintCoreConfiguration.bluePrintLoadConfiguration().blueprintArchivePath}/baseconfiguration " +
- "from data base.")
+ assertTrue(
+ File(
+ blueprintCoreConfiguration.bluePrintLoadConfiguration().blueprintArchivePath +
+ "/baseconfiguration"
+ ).deleteRecursively(), "Couldn't get blueprint archive " +
+ "${blueprintCoreConfiguration.bluePrintLoadConfiguration().blueprintArchivePath}/baseconfiguration " +
+ "from data base."
+ )
}
@Test
blueprintsProcessorCatalogService.delete("baseconfiguration", "1.0.0")
}
}
-}
\ No newline at end of file
+}
every { bluePrintValidatorService.validateBluePrints(any<BluePrintRuntimeService<*>>()) } returns true
return bluePrintValidatorService
}
-}
\ No newline at end of file
+}
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class,
- BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class])
+@ContextConfiguration(
+ classes = [BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class,
+ BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
@EnableAutoConfiguration
fun testPrimaryDatabaseConfiguration() {
assertNotNull(primaryDataSource, " failed to create primary data source")
}
-}
\ No newline at end of file
+}
/**
* Representation of DMAAP client service for AAF auth type.
*/
-class AafAuthDmaapClientService(private val clientProps:
- AafAuthDmaapClientProperties)
- : BluePrintDmaapClientService {
+class AafAuthDmaapClientService(
+ private val clientProps:
+ AafAuthDmaapClientProperties
+) :
+ BluePrintDmaapClientService {
/**
* The constructed DMAAP client.
*/
var clients: MutableList<MRBatchingPublisher> = mutableListOf()
-
/**
* Returns the DMAAP client after constructing it properly with the data
* that is required for AAF auth connection.
val client = MRClientFactory.createBatchingPublisher(
clientProps.host, t, clientProps.username,
clientProps.password, 1, 1, false,
- clientProps.type, "")
+ clientProps.type, ""
+ )
val batchPublisher = client as MRSimplerBatchPublisher
batchPublisher.props = clientProps.props
clients.add(client)
}
return clients
}
-
-}
\ No newline at end of file
+}
import java.io.IOException
import java.util.concurrent.TimeUnit
-
/**
* Abstraction of DMAAP client services that could form DMAAP client from the
* properties provided. This abstraction also provides a mechanism to send
* Static variable for logging.
*/
companion object {
+
var log = LoggerFactory.getLogger(
- BluePrintDmaapClientService::class.java)!!
+ BluePrintDmaapClientService::class.java
+ )!!
}
/**
* Returns the properly constructed DMAAP client with the type.
*/
- fun getDmaapClient(): MutableList<MRBatchingPublisher>
+ fun getDmaapClient(): MutableList<MRBatchingPublisher>
/**
* Sends messages to the sessions created by the information provided from
var ms = client.close(timeout, TimeUnit.SECONDS)
msgs.add(ms)
} catch (e: IOException) {
- log.warn("Unable to cleanly close the connection from the " +
- "client $client", e)
+ log.warn(
+ "Unable to cleanly close the connection from the " +
+ "client $client", e
+ )
}
}
return msgs
* Util constants required for DMAAP library to use.
*/
class DmaapLibConstants {
+
companion object {
const val SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY = "blueprint" +
"-dmaap-lib-property-service"
const val TYPE_HTTP_NO_AUTH = "HTTPNOAUTH"
const val TYPE_HTTP_AAF_AUTH = "HTTPAAF"
}
-}
\ No newline at end of file
+}
import org.springframework.core.env.Environment
import org.springframework.core.io.support.ResourcePropertySource
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.Properties
/**
* Representation of DMAAP lib property service to load the properties
* Static variable for logging.
*/
companion object {
+
var log = LoggerFactory.getLogger(
- BluePrintDmaapLibPropertyService::class.java)!!
+ BluePrintDmaapLibPropertyService::class.java
+ )!!
}
/**
*/
fun dmaapClientProperties(prefix: String): DmaapClientProperties {
val type = bluePrintPropertiesService.propertyBeanType(
- "$prefix.type", String::class.java)
+ "$prefix.type", String::class.java
+ )
val clientProps: DmaapClientProperties
when (type) {
TYPE_HTTP_NO_AUTH -> {
clientProps = bluePrintPropertiesService.propertyBeanType(
- prefix, HttpNoAuthDmaapClientProperties::class.java)
+ prefix, HttpNoAuthDmaapClientProperties::class.java
+ )
clientProps.props = parseEventProps()
}
TYPE_HTTP_AAF_AUTH -> {
clientProps = bluePrintPropertiesService.propertyBeanType(
- prefix, AafAuthDmaapClientProperties::class.java)
+ prefix, AafAuthDmaapClientProperties::class.java
+ )
clientProps.props = parseEventProps()
}
else -> {
- throw BluePrintProcessorException("DMAAP adaptor($type) is " +
- "not supported")
+ throw BluePrintProcessorException(
+ "DMAAP adaptor($type) is " +
+ "not supported"
+ )
}
}
return clientProps
when (type) {
TYPE_HTTP_NO_AUTH -> {
- clientProps = JacksonUtils.readValue(jsonNode,
- HttpNoAuthDmaapClientProperties::class.java)!!
+ clientProps = JacksonUtils.readValue(
+ jsonNode,
+ HttpNoAuthDmaapClientProperties::class.java
+ )!!
clientProps.props = parseEventProps()
}
TYPE_HTTP_AAF_AUTH -> {
- clientProps = JacksonUtils.readValue(jsonNode,
- AafAuthDmaapClientProperties::class.java)!!
+ clientProps = JacksonUtils.readValue(
+ jsonNode,
+ AafAuthDmaapClientProperties::class.java
+ )!!
clientProps.props = parseEventProps()
}
else -> {
- throw BluePrintProcessorException("DMAAP adaptor($type) is " +
- "not supported")
+ throw BluePrintProcessorException(
+ "DMAAP adaptor($type) is " +
+ "not supported"
+ )
}
}
return clientProps
}
else -> {
- throw BluePrintProcessorException("Unable to get the DMAAP " +
- "client")
+ throw BluePrintProcessorException(
+ "Unable to get the DMAAP " +
+ "client"
+ )
}
}
}
private fun parseEventProps(): Properties {
val prodProps = Properties()
val proProps = (env as ConfigurableEnvironment).propertySources.get(
- "class path resource [event.properties]")
+ "class path resource [event.properties]"
+ )
if (proProps != null) {
val entries = (proProps as ResourcePropertySource).source.entries
* Representation of data required for all DMAAP client.
*/
open class DmaapClientProperties {
+
lateinit var props: Properties
lateinit var type: String
lateinit var host: String
* Representation of data required for AAF auth DMAAP client.
*/
open class AafAuthDmaapClientProperties : DmaapClientProperties() {
+
lateinit var username: String
lateinit var password: String
}
/**
* Representation of DMAAP client service for HTTP no auth type.
*/
-class HttpNoAuthDmaapClientService(private val clientProps:
- HttpNoAuthDmaapClientProperties)
- : BluePrintDmaapClientService {
+class HttpNoAuthDmaapClientService(
+ private val clientProps:
+ HttpNoAuthDmaapClientProperties
+) :
+ BluePrintDmaapClientService {
/**
* The constructed DMAAP client.
*/
var clients: MutableList<MRBatchingPublisher> = mutableListOf()
-
/**
* Returns the DMAAP client after constructing it properly with the data
* that is required for HTTP no auth connection.
return clients
}
-
-}
\ No newline at end of file
+}
@RunWith(SpringRunner::class)
@EnableAutoConfiguration(exclude = [DataSourceAutoConfiguration::class])
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
-@ContextConfiguration(classes = [BluePrintDmaapLibConfiguration::class, TestController::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties = ["server.port=9111",
- "blueprintsprocessor.dmaapclient.aai.topic=cds_aai",
- "blueprintsprocessor.dmaapclient.aai.type=HTTPNOAUTH",
- "blueprintsprocessor.dmaapclient.aai.host=127.0.0.1:9111",
- "blueprintsprocessor.dmaapclient.multi.topic=cds_multi1,cds_multi2",
- "blueprintsprocessor.dmaapclient.multi.type=HTTPNOAUTH",
- "blueprintsprocessor.dmaapclient.multi.host=127.0.0.1:9111"])
+@ContextConfiguration(
+ classes = [BluePrintDmaapLibConfiguration::class, TestController::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties = ["server.port=9111",
+ "blueprintsprocessor.dmaapclient.aai.topic=cds_aai",
+ "blueprintsprocessor.dmaapclient.aai.type=HTTPNOAUTH",
+ "blueprintsprocessor.dmaapclient.aai.host=127.0.0.1:9111",
+ "blueprintsprocessor.dmaapclient.multi.topic=cds_multi1,cds_multi2",
+ "blueprintsprocessor.dmaapclient.multi.type=HTTPNOAUTH",
+ "blueprintsprocessor.dmaapclient.multi.host=127.0.0.1:9111"]
+)
class TestDmaapEventPublisher {
@Autowired
- lateinit var dmaapService : BluePrintDmaapLibPropertyService
+ lateinit var dmaapService: BluePrintDmaapLibPropertyService
/**
* Tests the event properties being set properly and sent as request.
val strList = mutableListOf<String>()
val dmaapClient = dmaapService.blueprintDmaapClientService("aai")
- strList.add("{\n" +
- " \"a\" : \"hello\"\n" +
- "}")
+ strList.add(
+ "{\n" +
+ " \"a\" : \"hello\"\n" +
+ "}"
+ )
dmaapClient.sendMessage(strList)
val msgs = dmaapClient.close(2)
assertEquals(msgs!!.size, 1)
@Test
fun testEventPropertiesWithSingleMsg() {
val dmaapClient = dmaapService.blueprintDmaapClientService("aai")
- val str : String = "{\n" +
+ val str: String = "{\n" +
" \"a\" : \"hello\"\n" +
"}"
dmaapClient.sendMessage(str)
val strList = mutableListOf<String>()
val dmaapClient = dmaapService.blueprintDmaapClientService("multi")
- strList.add("{\n" +
- " \"a\" : \"hello\"\n" +
- "}")
+ strList.add(
+ "{\n" +
+ " \"a\" : \"hello\"\n" +
+ "}"
+ )
dmaapClient.sendMessage(strList)
val msgs = dmaapClient.close(2)
assertEquals(msgs!!.size, 2)
assertEquals(topic2!!.size, 0)
}
-
/**
* Tests the event properties with multiple topics with JSON node as input.
*/
val strList = mutableListOf<String>()
val dmaapClient = dmaapService.blueprintDmaapClientService(node)
- strList.add("{\n" +
- " \"a\" : \"hello\"\n" +
- "}")
+ strList.add(
+ "{\n" +
+ " \"a\" : \"hello\"\n" +
+ "}"
+ )
dmaapClient.sendMessage(strList)
val msgs = dmaapClient.close(2)
assertEquals(msgs!!.size, 2)
assertEquals(topic2!!.size, 0)
}
-
/**
* Tests the event properties with multiple messages.
*/
val strList = mutableListOf<String>()
val dmaapClient = dmaapService.blueprintDmaapClientService("aai")
- strList.add("{\n" +
- " \"a\" : \"hello\"\n" +
- "}")
- strList.add("{\n" +
- " \"a\" : \"second\"\n" +
- "}")
+ strList.add(
+ "{\n" +
+ " \"a\" : \"hello\"\n" +
+ "}"
+ )
+ strList.add(
+ "{\n" +
+ " \"a\" : \"second\"\n" +
+ "}"
+ )
dmaapClient.sendMessage(strList)
val msgs = dmaapClient.close(2)
assertEquals(msgs!!.size, 1)
@Test
fun testDmaapClientProperties() {
val properties = dmaapService.dmaapClientProperties(
- "blueprintsprocessor.dmaapclient.aai")
+ "blueprintsprocessor.dmaapclient.aai"
+ )
assertNotNull(properties, "failed to create property bean")
- assertNotNull(properties.host, "failed to get url property" +
- " in property bean")
+ assertNotNull(
+ properties.host, "failed to get url property" +
+ " in property bean"
+ )
}
/**
fun testBlueprintDmaapClientService() {
val blueprintDmaapClientService =
dmaapService.blueprintDmaapClientService("aai")
- assertNotNull(blueprintDmaapClientService,
- "failed to create blueprintDmaapClientService")
+ assertNotNull(
+ blueprintDmaapClientService,
+ "failed to create blueprintDmaapClientService"
+ )
}
-
}
/**
* Accepts request for a topic and sends a message as response.
*/
@PostMapping(path = ["/{topic}"])
- fun postTopic(@PathVariable(value = "topic") topic : String):
+ fun postTopic(@PathVariable(value = "topic") topic: String):
ResponseEntity<Any> {
var a = "{\n" +
" \"message\" : \"The message is published into $topic " +
fun Metadata.putStringKeyValue(key: String, value: String) {
this.put(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER), value)
-}
\ No newline at end of file
+}
* Exposed Dependency Service by this GRPC Lib Module
*/
fun BluePrintDependencyService.grpcLibPropertyService(): BluePrintGrpcLibPropertyService =
- instance(GRPCLibConstants.SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY)
+ instance(GRPCLibConstants.SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY)
fun BluePrintDependencyService.grpcClientService(selector: String): BluePrintGrpcClientService {
return grpcLibPropertyService().blueprintGrpcClientService(selector)
const val TYPE_BASIC_AUTH = "basic-auth"
const val TYPE_TLS_AUTH = "tls-auth"
}
-}
\ No newline at end of file
+}
/** GRPC Server Properties */
open class GrpcServerProperties {
+
lateinit var type: String
var port: Int = -1
}
/** GRPC Client Properties */
open class GrpcClientProperties {
+
lateinit var type: String
lateinit var host: String
var port: Int = -1
open class BasicAuthGrpcClientProperties : GrpcClientProperties() {
lateinit var username: String
lateinit var password: String
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor
-import io.grpc.*
+import io.grpc.CallOptions
+import io.grpc.Channel
+import io.grpc.ClientCall
+import io.grpc.ClientInterceptor
+import io.grpc.ForwardingClientCall
+import io.grpc.ForwardingClientCallListener
+import io.grpc.Metadata
+import io.grpc.MethodDescriptor
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.GrpcLoggerService
import org.onap.ccsdk.cds.controllerblueprints.core.logger
-
class GrpcClientLoggingInterceptor : ClientInterceptor {
val log = logger(GrpcClientLoggingInterceptor::class)
val loggingService = GrpcLoggerService()
- override fun <ReqT, RespT> interceptCall(method: MethodDescriptor<ReqT, RespT>,
- callOptions: CallOptions, channel: Channel): ClientCall<ReqT, RespT> {
+ override fun <ReqT, RespT> interceptCall(
+ method: MethodDescriptor<ReqT, RespT>,
+ callOptions: CallOptions,
+ channel: Channel
+ ): ClientCall<ReqT, RespT> {
return object : ForwardingClientCall
.SimpleForwardingClientCall<ReqT, RespT>(channel.newCall(method, callOptions)) {
super.start(listener, headers)
}
}
-
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor
-import io.grpc.*
+import io.grpc.ForwardingServerCall
+import io.grpc.ForwardingServerCallListener
+import io.grpc.Metadata
+import io.grpc.ServerCall
+import io.grpc.ServerCallHandler
+import io.grpc.ServerInterceptor
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.GrpcLoggerService
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.logger
val log = logger(GrpcServerLoggingInterceptor::class)
val loggingService = GrpcLoggerService()
- override fun <ReqT : Any, RespT : Any> interceptCall(call: ServerCall<ReqT, RespT>,
- requestHeaders: Metadata, next: ServerCallHandler<ReqT, RespT>)
- : ServerCall.Listener<ReqT> {
+ override fun <ReqT : Any, RespT : Any> interceptCall(
+ call: ServerCall<ReqT, RespT>,
+ requestHeaders: Metadata,
+ next: ServerCallHandler<ReqT, RespT>
+ ):
+ ServerCall.Listener<ReqT> {
val forwardingServerCall = object : ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
override fun sendHeaders(responseHeaders: Metadata) {
}
}
- return object
- : ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
- next.startCall(forwardingServerCall, requestHeaders)) {
+ return object :
+ ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
+ next.startCall(forwardingServerCall, requestHeaders)
+ ) {
override fun onMessage(message: ReqT) {
/** Get the requestId, SubRequestId and Originator Id and set in MDS context
when (message) {
is ExecutionServiceInput -> {
val commonHeader = message.commonHeader
- ?: throw BluePrintProcessorException("missing common header in request")
+ ?: throw BluePrintProcessorException("missing common header in request")
loggingService.grpcRequesting(call, commonHeader, next)
}
is BluePrintUploadInput -> {
val commonHeader = message.commonHeader
- ?: throw BluePrintProcessorException("missing common header in request")
+ ?: throw BluePrintProcessorException("missing common header in request")
loggingService.grpcRequesting(call, commonHeader, next)
}
is BluePrintDownloadInput -> {
val commonHeader = message.commonHeader
- ?: throw BluePrintProcessorException("missing common header in request")
+ ?: throw BluePrintProcessorException("missing common header in request")
loggingService.grpcRequesting(call, commonHeader, next)
}
is BluePrintRemoveInput -> {
val commonHeader = message.commonHeader
- ?: throw BluePrintProcessorException("missing common header in request")
+ ?: throw BluePrintProcessorException("missing common header in request")
loggingService.grpcRequesting(call, commonHeader, next)
}
else -> {
MDC.clear()
super.onCancel()
}
-
}
}
-}
\ No newline at end of file
+}
import io.grpc.netty.NettyChannelBuilder
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties
-
-open class BasicAuthGrpcClientService(private val basicAuthGrpcClientProperties: BasicAuthGrpcClientProperties)
- : BluePrintGrpcClientService {
+open class BasicAuthGrpcClientService(private val basicAuthGrpcClientProperties: BasicAuthGrpcClientProperties) :
+ BluePrintGrpcClientService {
override suspend fun channel(): ManagedChannel {
val managedChannel = NettyChannelBuilder
- .forAddress(basicAuthGrpcClientProperties.host, basicAuthGrpcClientProperties.port)
- .nameResolverFactory(DnsNameResolverProvider())
- .loadBalancerFactory(PickFirstLoadBalancerProvider())
- // .intercept(BasicAuthClientInterceptor(basicAuthGrpcClientProperties)).usePlaintext()
- .build()
+ .forAddress(basicAuthGrpcClientProperties.host, basicAuthGrpcClientProperties.port)
+ .nameResolverFactory(DnsNameResolverProvider())
+ .loadBalancerFactory(PickFirstLoadBalancerProvider())
+ // .intercept(BasicAuthClientInterceptor(basicAuthGrpcClientProperties)).usePlaintext()
+ .build()
return managedChannel
}
-
-
}
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.grpc.*
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcServerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcServerProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
return blueprintGrpcServerService(grpcServerProperties)
}
-
/** GRPC Server Lib Property Service */
fun grpcServerProperties(jsonNode: JsonNode): GrpcServerProperties {
return when (val type = jsonNode.get("type").textValue()) {
fun grpcServerProperties(prefix: String): GrpcServerProperties {
val type = bluePrintPropertiesService.propertyBeanType(
- "$prefix.type", String::class.java)
+ "$prefix.type", String::class.java
+ )
return when (type) {
GRPCLibConstants.TYPE_TOKEN_AUTH -> {
tokenAuthGrpcServerProperties(prefix)
return bluePrintPropertiesService.propertyBeanType(prefix, TLSAuthGrpcServerProperties::class.java)
}
- private fun blueprintGrpcServerService(grpcServerProperties: GrpcServerProperties)
- : BluePrintGrpcServerService {
+ private fun blueprintGrpcServerService(grpcServerProperties: GrpcServerProperties):
+ BluePrintGrpcServerService {
when (grpcServerProperties) {
is TLSAuthGrpcServerProperties -> {
return TLSAuthGrpcServerService(grpcServerProperties)
}
}
-
/** GRPC Client Lib Property Service */
fun blueprintGrpcClientService(jsonNode: JsonNode): BluePrintGrpcClientService {
return blueprintGrpcClientService(restClientProperties)
}
-
fun grpcClientProperties(jsonNode: JsonNode): GrpcClientProperties {
val type = jsonNode.get("type").returnNullIfMissing()?.textValue()
- ?: BluePrintProcessorException("missing type property")
+ ?: BluePrintProcessorException("missing type property")
return when (type) {
GRPCLibConstants.TYPE_TOKEN_AUTH -> {
JacksonUtils.readValue(jsonNode, TokenAuthGrpcClientProperties::class.java)!!
fun grpcClientProperties(prefix: String): GrpcClientProperties {
val type = bluePrintPropertiesService.propertyBeanType(
- "$prefix.type", String::class.java)
+ "$prefix.type", String::class.java
+ )
return when (type) {
GRPCLibConstants.TYPE_TOKEN_AUTH -> {
tokenAuthGrpcClientProperties(prefix)
}
else -> {
throw BluePrintProcessorException("Grpc type($type) not supported")
-
}
}
}
private fun basicAuthGrpcClientProperties(prefix: String): BasicAuthGrpcClientProperties {
return bluePrintPropertiesService.propertyBeanType(prefix, BasicAuthGrpcClientProperties::class.java)
}
-}
\ No newline at end of file
+}
interface BluePrintGrpcClientService {
suspend fun channel(): ManagedChannel
-}
\ No newline at end of file
+}
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
-import java.util.*
+import java.util.UUID
class GrpcLoggerService {
private val log = logger(GrpcLoggerService::class)
/** Used when server receives request */
- fun <ReqT : Any, RespT : Any> grpcRequesting(call: ServerCall<ReqT, RespT>,
- headers: Metadata, next: ServerCallHandler<ReqT, RespT>) {
+ fun <ReqT : Any, RespT : Any> grpcRequesting(
+ call: ServerCall<ReqT, RespT>,
+ headers: Metadata,
+ next: ServerCallHandler<ReqT, RespT>
+ ) {
val requestID = headers.getStringKey(ONAP_REQUEST_ID).defaultToUUID()
val invocationID = headers.getStringKey(ONAP_INVOCATION_ID).defaultToUUID()
val partnerName = headers.getStringKey(ONAP_PARTNER_NAME) ?: "UNKNOWN"
grpcRequesting(requestID, invocationID, partnerName, call)
}
- fun <ReqT : Any, RespT : Any> grpcRequesting(call: ServerCall<ReqT, RespT>,
- headers: CommonHeader, next: ServerCallHandler<ReqT, RespT>) {
+ fun <ReqT : Any, RespT : Any> grpcRequesting(
+ call: ServerCall<ReqT, RespT>,
+ headers: CommonHeader,
+ next: ServerCallHandler<ReqT, RespT>
+ ) {
val requestID = headers.requestId.defaultToUUID()
val invocationID = headers.subRequestId.defaultToUUID()
val partnerName = headers.originatorId ?: "UNKNOWN"
grpcRequesting(requestID, invocationID, partnerName, call)
}
- fun <ReqT : Any, RespT : Any> grpcRequesting(requestID: String, invocationID: String, partnerName: String,
- call: ServerCall<ReqT, RespT>) {
+ fun <ReqT : Any, RespT : Any> grpcRequesting(
+ requestID: String,
+ invocationID: String,
+ partnerName: String,
+ call: ServerCall<ReqT, RespT>
+ ) {
val localhost = InetAddress.getLocalHost()
val clientSocketAddress = call.attributes.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR) as? InetSocketAddress
- ?: throw BluePrintProcessorException("failed to get client address")
+ ?: throw BluePrintProcessorException("failed to get client address")
val serviceName = call.methodDescriptor.fullMethodName
MDC.put("InvokeTimestamp", ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT))
log.trace("MDC Properties : ${MDC.getCopyOfContextMap()}")
}
-
/** Used before invoking any GRPC outbound request, Inbound Invocation ID is used as request Id
* for outbound Request, If invocation Id is missing then default Request Id will be generated.
*/
log.warn("couldn't set grpc response headers", e)
}
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcClientLoggingInterceptor
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
-class TLSAuthGrpcClientService(private val tlsAuthGrpcClientProperties: TLSAuthGrpcClientProperties)
- : BluePrintGrpcClientService {
+class TLSAuthGrpcClientService(private val tlsAuthGrpcClientProperties: TLSAuthGrpcClientProperties) :
+ BluePrintGrpcClientService {
override suspend fun channel(): ManagedChannel {
return NettyChannelBuilder
- .forAddress(tlsAuthGrpcClientProperties.host, tlsAuthGrpcClientProperties.port)
- .nameResolverFactory(DnsNameResolverProvider())
- .loadBalancerFactory(PickFirstLoadBalancerProvider())
- .intercept(GrpcClientLoggingInterceptor())
- .sslContext(sslContext())
- .build()
+ .forAddress(tlsAuthGrpcClientProperties.host, tlsAuthGrpcClientProperties.port)
+ .nameResolverFactory(DnsNameResolverProvider())
+ .loadBalancerFactory(PickFirstLoadBalancerProvider())
+ .intercept(GrpcClientLoggingInterceptor())
+ .sslContext(sslContext())
+ .build()
}
fun sslContext(): SslContext {
if (tlsAuthGrpcClientProperties.trustCertCollection != null) {
builder.trustManager(normalizedFile(tlsAuthGrpcClientProperties.trustCertCollection!!))
}
- if (tlsAuthGrpcClientProperties.clientCertChain != null
- && tlsAuthGrpcClientProperties.clientPrivateKey != null) {
- builder.keyManager(normalizedFile(tlsAuthGrpcClientProperties.clientCertChain!!),
- normalizedFile(tlsAuthGrpcClientProperties.clientPrivateKey!!))
+ if (tlsAuthGrpcClientProperties.clientCertChain != null &&
+ tlsAuthGrpcClientProperties.clientPrivateKey != null
+ ) {
+ builder.keyManager(
+ normalizedFile(tlsAuthGrpcClientProperties.clientCertChain!!),
+ normalizedFile(tlsAuthGrpcClientProperties.clientPrivateKey!!)
+ )
}
return builder.build()
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
-
-class TLSAuthGrpcServerService(private val tlsAuthGrpcServerProperties: TLSAuthGrpcServerProperties)
- : BluePrintGrpcServerService {
+class TLSAuthGrpcServerService(private val tlsAuthGrpcServerProperties: TLSAuthGrpcServerProperties) :
+ BluePrintGrpcServerService {
override fun serverBuilder(): NettyServerBuilder {
return NettyServerBuilder
- .forPort(tlsAuthGrpcServerProperties.port)
- .sslContext(sslContext())
+ .forPort(tlsAuthGrpcServerProperties.port)
+ .sslContext(sslContext())
}
fun sslContext(): SslContext {
val sslClientContextBuilder = SslContextBuilder
- .forServer(normalizedFile(tlsAuthGrpcServerProperties.certChain),
- normalizedFile(tlsAuthGrpcServerProperties.privateKey))
+ .forServer(
+ normalizedFile(tlsAuthGrpcServerProperties.certChain),
+ normalizedFile(tlsAuthGrpcServerProperties.privateKey)
+ )
tlsAuthGrpcServerProperties.trustCertCollection?.let { trustCertFile ->
sslClientContextBuilder.trustManager(normalizedFile(trustCertFile))
}
return GrpcSslContexts.configure(sslClientContextBuilder).build()
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service
-import io.grpc.*
+import io.grpc.CallOptions
+import io.grpc.Channel
+import io.grpc.ClientCall
+import io.grpc.ClientInterceptor
+import io.grpc.ForwardingClientCall
+import io.grpc.ManagedChannel
+import io.grpc.Metadata
+import io.grpc.MethodDescriptor
import io.grpc.internal.DnsNameResolverProvider
import io.grpc.internal.PickFirstLoadBalancerProvider
import io.grpc.netty.NettyChannelBuilder
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcClientLoggingInterceptor
-class TokenAuthGrpcClientService(private val tokenAuthGrpcClientProperties: TokenAuthGrpcClientProperties)
- : BluePrintGrpcClientService {
+class TokenAuthGrpcClientService(private val tokenAuthGrpcClientProperties: TokenAuthGrpcClientProperties) :
+ BluePrintGrpcClientService {
override suspend fun channel(): ManagedChannel {
val managedChannel = NettyChannelBuilder
- .forAddress(tokenAuthGrpcClientProperties.host, tokenAuthGrpcClientProperties.port)
- .nameResolverFactory(DnsNameResolverProvider())
- .loadBalancerFactory(PickFirstLoadBalancerProvider())
- .intercept(GrpcClientLoggingInterceptor())
- .intercept(TokenAuthClientInterceptor(tokenAuthGrpcClientProperties)).usePlaintext().build()
+ .forAddress(tokenAuthGrpcClientProperties.host, tokenAuthGrpcClientProperties.port)
+ .nameResolverFactory(DnsNameResolverProvider())
+ .loadBalancerFactory(PickFirstLoadBalancerProvider())
+ .intercept(GrpcClientLoggingInterceptor())
+ .intercept(TokenAuthClientInterceptor(tokenAuthGrpcClientProperties)).usePlaintext().build()
return managedChannel
}
}
class TokenAuthClientInterceptor(private val tokenAuthGrpcClientProperties: TokenAuthGrpcClientProperties) : ClientInterceptor {
- override fun <ReqT, RespT> interceptCall(method: MethodDescriptor<ReqT, RespT>,
- callOptions: CallOptions, channel: Channel): ClientCall<ReqT, RespT> {
+ override fun <ReqT, RespT> interceptCall(
+ method: MethodDescriptor<ReqT, RespT>,
+ callOptions: CallOptions,
+ channel: Channel
+ ): ClientCall<ReqT, RespT> {
val authHeader = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER)
import org.junit.runner.RunWith
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.grpc.*
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BluePrintGrpcLibConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties
import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import kotlin.test.assertTrue
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintGrpcLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.grpcclient.sample.type=basic-auth",
- "blueprintsprocessor.grpcclient.sample.host=127.0.0.1",
- "blueprintsprocessor.grpcclient.sample.port=50505",
- "blueprintsprocessor.grpcclient.sample.username=sampleuser",
- "blueprintsprocessor.grpcclient.sample.password=sampleuser",
-
- "blueprintsprocessor.grpcclient.token.type=token-auth",
- "blueprintsprocessor.grpcclient.token.host=127.0.0.1",
- "blueprintsprocessor.grpcclient.token.port=50505",
- "blueprintsprocessor.grpcclient.token.username=sampleuser",
- "blueprintsprocessor.grpcclient.token.password=sampleuser",
-
- "blueprintsprocessor.grpcserver.tls-sample.type=tls-auth",
- "blueprintsprocessor.grpcserver.tls-sample.port=50505",
- "blueprintsprocessor.grpcserver.tls-sample.certChain=server1.pem",
- "blueprintsprocessor.grpcserver.tls-sample.privateKey=server1.key",
- "blueprintsprocessor.grpcserver.tls-sample.trustCertCollection=ca.pem",
-
- "blueprintsprocessor.grpcclient.tls-sample.type=tls-auth",
- "blueprintsprocessor.grpcclient.tls-sample.host=127.0.0.1",
- "blueprintsprocessor.grpcclient.tls-sample.port=50505",
- "blueprintsprocessor.grpcclient.tls-sample.trustCertCollection=ca.pem",
- "blueprintsprocessor.grpcclient.tls-sample.clientCertChain=client.pem",
- "blueprintsprocessor.grpcclient.tls-sample.clientPrivateKey=client.key"
-])
+@ContextConfiguration(
+ classes = [BluePrintGrpcLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.grpcclient.sample.type=basic-auth",
+ "blueprintsprocessor.grpcclient.sample.host=127.0.0.1",
+ "blueprintsprocessor.grpcclient.sample.port=50505",
+ "blueprintsprocessor.grpcclient.sample.username=sampleuser",
+ "blueprintsprocessor.grpcclient.sample.password=sampleuser",
+
+ "blueprintsprocessor.grpcclient.token.type=token-auth",
+ "blueprintsprocessor.grpcclient.token.host=127.0.0.1",
+ "blueprintsprocessor.grpcclient.token.port=50505",
+ "blueprintsprocessor.grpcclient.token.username=sampleuser",
+ "blueprintsprocessor.grpcclient.token.password=sampleuser",
+
+ "blueprintsprocessor.grpcserver.tls-sample.type=tls-auth",
+ "blueprintsprocessor.grpcserver.tls-sample.port=50505",
+ "blueprintsprocessor.grpcserver.tls-sample.certChain=server1.pem",
+ "blueprintsprocessor.grpcserver.tls-sample.privateKey=server1.key",
+ "blueprintsprocessor.grpcserver.tls-sample.trustCertCollection=ca.pem",
+
+ "blueprintsprocessor.grpcclient.tls-sample.type=tls-auth",
+ "blueprintsprocessor.grpcclient.tls-sample.host=127.0.0.1",
+ "blueprintsprocessor.grpcclient.tls-sample.port=50505",
+ "blueprintsprocessor.grpcclient.tls-sample.trustCertCollection=ca.pem",
+ "blueprintsprocessor.grpcclient.tls-sample.clientCertChain=client.pem",
+ "blueprintsprocessor.grpcclient.tls-sample.clientPrivateKey=client.key"
+ ]
+)
class BluePrintGrpcLibPropertyServiceTest {
@Autowired
@Test
fun testGrpcClientProperties() {
val properties = bluePrintGrpcLibPropertyService.grpcClientProperties(
- "blueprintsprocessor.grpcclient.sample")
+ "blueprintsprocessor.grpcclient.sample"
+ )
as BasicAuthGrpcClientProperties
assertNotNull(properties, "failed to create property bean")
- assertNotNull(properties.host, "failed to get host property" +
- " in property bean")
- assertNotNull(properties.port, "failed to get host property" +
- " in property bean")
- assertNotNull(properties.username, "failed to get host pro" +
- "perty in property bean")
- assertNotNull(properties.password, "failed to get host pr" +
- "operty in property bean")
+ assertNotNull(
+ properties.host, "failed to get host property" +
+ " in property bean"
+ )
+ assertNotNull(
+ properties.port, "failed to get host property" +
+ " in property bean"
+ )
+ assertNotNull(
+ properties.username, "failed to get host pro" +
+ "perty in property bean"
+ )
+ assertNotNull(
+ properties.password, "failed to get host pr" +
+ "operty in property bean"
+ )
}
/**
val mapper = ObjectMapper()
val actualObj: JsonNode = mapper.readTree(json)
val properties = bluePrintGrpcLibPropertyService.grpcClientProperties(
- actualObj) as TokenAuthGrpcClientProperties
+ actualObj
+ ) as TokenAuthGrpcClientProperties
assertNotNull(properties, "failed to create property bean")
assertEquals(properties.host, "127.0.0.1")
assertNotNull(properties.port, "50505")
@Test
fun testGrpcClientServiceBasic() {
val svc = bluePrintGrpcLibPropertyService.blueprintGrpcClientService(
- "sample")
+ "sample"
+ )
assertTrue(svc is BasicAuthGrpcClientService)
}
@Test
fun testGrpcClientServiceToken() {
val svc = bluePrintGrpcLibPropertyService.blueprintGrpcClientService(
- "token")
+ "token"
+ )
assertTrue(svc is TokenAuthGrpcClientService)
}
val mapper = ObjectMapper()
val actualObj: JsonNode = mapper.readTree(json)
val svc = bluePrintGrpcLibPropertyService
- .blueprintGrpcClientService(actualObj)
+ .blueprintGrpcClientService(actualObj)
assertTrue(svc is BasicAuthGrpcClientService)
}
@Test
fun testGrpcClientTLSProperties() {
val properties = bluePrintGrpcLibPropertyService
- .grpcClientProperties("blueprintsprocessor.grpcclient.tls-sample") as TLSAuthGrpcClientProperties
+ .grpcClientProperties("blueprintsprocessor.grpcclient.tls-sample") as TLSAuthGrpcClientProperties
assertNotNull(properties, "failed to create property bean")
assertNotNull(properties.host, "failed to get host property in property bean")
assertNotNull(properties.port, "failed to get host property in property bean")
}
""".trimIndent()
val jsonProperties = bluePrintGrpcLibPropertyService
- .grpcClientProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcClientProperties
+ .grpcClientProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcClientProperties
assertNotNull(jsonProperties, "failed to create property bean from json")
}
@Test
fun testGrpcServerTLSProperties() {
val properties = bluePrintGrpcLibPropertyService
- .grpcServerProperties("blueprintsprocessor.grpcserver.tls-sample") as TLSAuthGrpcServerProperties
+ .grpcServerProperties("blueprintsprocessor.grpcserver.tls-sample") as TLSAuthGrpcServerProperties
assertNotNull(properties, "failed to create property bean")
assertNotNull(properties.port, "failed to get host property in property bean")
assertNotNull(properties.trustCertCollection, "failed to get trustCertCollection property in property bean")
}
""".trimIndent()
val jsonProperties = bluePrintGrpcLibPropertyService
- .grpcServerProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcServerProperties
+ .grpcServerProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcServerProperties
assertNotNull(jsonProperties, "failed to create property bean from json")
val grpcServerService = bluePrintGrpcLibPropertyService.blueprintGrpcServerService("tls-sample")
assertNotNull(grpcServerService, "failed to get grpc server service")
Assert.assertEquals(TLSAuthGrpcServerService::class.java, grpcServerService.javaClass)
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput
-import java.util.*
+import java.util.UUID
import kotlin.test.Test
import kotlin.test.assertNotNull
}
/** TLS Client Integration testing, GRPC TLS Junit testing is not supported. */
- //@Test
+ // @Test
fun testGrpcTLSServerIntegration() {
runBlocking {
val tlsAuthGrpcClientService = TLSAuthGrpcClientService(tlsAuthGrpcClientProperties)
val grpcChannel = tlsAuthGrpcClientService.channel()
/** Get Send and Receive Channel for bidirectional process method*/
- val (reqChannel, resChannel) = clientCallBidiStreaming(BluePrintProcessingServiceGrpc.getProcessMethod(),
- grpcChannel)
+ val (reqChannel, resChannel) = clientCallBidiStreaming(
+ BluePrintProcessingServiceGrpc.getProcessMethod(),
+ grpcChannel
+ )
launch {
resChannel.consumeEach {
log.info("Received Response")
private fun getRequest(requestId: String): ExecutionServiceInput {
val commonHeader = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(requestId)
- .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(requestId)
+ .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build()
val actionIdentifier = ActionIdentifiers.newBuilder()
- .setActionName("SampleScript")
- .setBlueprintName("sample-cba")
- .setBlueprintVersion("1.0.0")
- .setMode(ACTION_MODE_SYNC)
- .build()
+ .setActionName("SampleScript")
+ .setBlueprintName("sample-cba")
+ .setBlueprintVersion("1.0.0")
+ .setMode(ACTION_MODE_SYNC)
+ .build()
val jsonContent = """{ "key1" : "value1" }"""
val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder
JsonFormat.parser().merge(jsonContent, payloadBuilder)
return ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(actionIdentifier)
- .setPayload(payloadBuilder.build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setPayload(payloadBuilder.build())
+ .build()
}
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput
-
val log = logger(MockTLSBluePrintProcessingServer::class)
/** For Integration testing stat this server, Set the working path to run this method */
privateKey = "src/test/resources/tls-manual/py-executor-key.pem"
}
val server = TLSAuthGrpcServerService(tlsAuthGrpcServerProperties).serverBuilder()
- .intercept(GrpcServerLoggingInterceptor())
- .addService(MockTLSBluePrintProcessingServer())
- .build()
+ .intercept(GrpcServerLoggingInterceptor())
+ .addService(MockTLSBluePrintProcessingServer())
+ .build()
server.start()
log.info("GRPC Serve started(${server.isShutdown}) on port(${server.port})...")
server.awaitTermination()
} catch (e: Exception) {
log.error("Failed to start tls grpc integration server", e)
}
-
}
class MockTLSBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() {
return object : StreamObserver<ExecutionServiceInput> {
override fun onNext(executionServiceInput: ExecutionServiceInput) {
- log.info("Received requestId(${executionServiceInput.commonHeader.requestId}) " +
- "subRequestId(${executionServiceInput.commonHeader.subRequestId})")
+ log.info(
+ "Received requestId(${executionServiceInput.commonHeader.requestId}) " +
+ "subRequestId(${executionServiceInput.commonHeader.subRequestId})"
+ )
responseObserver.onNext(buildResponse(executionServiceInput))
responseObserver.onCompleted()
}
override fun onError(error: Throwable) {
log.debug("Fail to process message", error)
- responseObserver.onError(io.grpc.Status.INTERNAL
+ responseObserver.onError(
+ io.grpc.Status.INTERNAL
.withDescription(error.message)
- .asException())
+ .asException()
+ )
}
override fun onCompleted() {
private fun buildResponse(input: ExecutionServiceInput): ExecutionServiceOutput {
val status = Status.newBuilder().setCode(200)
- .setEventType(EventType.EVENT_COMPONENT_EXECUTED)
- .build()
+ .setEventType(EventType.EVENT_COMPONENT_EXECUTED)
+ .build()
return ExecutionServiceOutput.newBuilder()
- .setCommonHeader(input.commonHeader)
- .setActionIdentifiers(input.actionIdentifiers)
- .setStatus(status)
- .build()
-
+ .setCommonHeader(input.commonHeader)
+ .setActionIdentifiers(input.actionIdentifiers)
+ .setStatus(status)
+ .build()
}
-}
\ No newline at end of file
+}
import org.apache.kafka.common.header.internals.RecordHeader
import java.nio.charset.Charset
-
fun <T : Headers> T?.toMap(): MutableMap<String, String> {
val map: MutableMap<String, String> = hashMapOf()
this?.forEach { map[it.key()] = String(it.value(), Charset.defaultCharset()) }
fun Headers.addHeader(key: String, value: String) {
this.add(RecordHeader(key, value.toByteArray()))
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.message
-
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BluePrintMessageLibPropertyService
import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageConsumerService
* Exposed Dependency Service by this Message Lib Module
*/
fun BluePrintDependencyService.messageLibPropertyService(): BluePrintMessageLibPropertyService =
- instance(MessageLibConstants.SERVICE_BLUEPRINT_MESSAGE_LIB_PROPERTY)
+ instance(MessageLibConstants.SERVICE_BLUEPRINT_MESSAGE_LIB_PROPERTY)
/** Extension functions for message producer service **/
fun BluePrintDependencyService.messageProducerService(selector: String): BlueprintMessageProducerService {
return messageLibPropertyService().blueprintMessageProducerService(selector)
}
-
fun BluePrintDependencyService.messageProducerService(jsonNode: JsonNode): BlueprintMessageProducerService {
return messageLibPropertyService().blueprintMessageProducerService(jsonNode)
}
const val TYPE_KAFKA_BASIC_AUTH = "kafka-basic-auth"
const val TYPE_KAFKA_STREAMS_BASIC_AUTH = "kafka-streams-basic-auth"
}
-}
\ No newline at end of file
+}
/** Producer Properties **/
open class MessageProducerProperties
-
open class KafkaBasicAuthMessageProducerProperties : MessageProducerProperties() {
lateinit var bootstrapServers: String
var topic: String? = null
lateinit var processorContext: ProcessorContext
-
override fun process(key: K, value: V) = runBlocking(Dispatchers.IO) {
try {
processNB(key, value)
override fun init(context: ProcessorContext) {
log.info("initializing processor (${this.javaClass.simpleName})")
this.processorContext = context
-
}
override fun close() {
/** CDS Kafka Stream Punctuator abstract class to implement */
abstract class AbstractBluePrintMessagePunctuator : Punctuator {
- lateinit var processorContext: ProcessorContext
+ lateinit var processorContext: ProcessorContext
override fun punctuate(timestamp: Long) = runBlocking(Dispatchers.IO) {
punctuateNB(timestamp)
}
abstract suspend fun punctuateNB(timestamp: Long)
-}
\ No newline at end of file
+}
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.message.*
+import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaBasicAuthMessageConsumerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaBasicAuthMessageProducerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaStreamsBasicAuthConsumerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageConsumerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageLibConstants
+import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageProducerProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.stereotype.Service
}
}
- private fun blueprintMessageProducerService(MessageProducerProperties: MessageProducerProperties)
- : BlueprintMessageProducerService {
+ private fun blueprintMessageProducerService(MessageProducerProperties: MessageProducerProperties):
+ BlueprintMessageProducerService {
when (MessageProducerProperties) {
is KafkaBasicAuthMessageProducerProperties -> {
private fun kafkaBasicAuthMessageProducerProperties(prefix: String): KafkaBasicAuthMessageProducerProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, KafkaBasicAuthMessageProducerProperties::class.java)
+ prefix, KafkaBasicAuthMessageProducerProperties::class.java
+ )
}
/** Consumer Property Lib Service Implementation **/
}
}
- private fun blueprintMessageConsumerService(messageConsumerProperties: MessageConsumerProperties)
- : BlueprintMessageConsumerService {
+ private fun blueprintMessageConsumerService(messageConsumerProperties: MessageConsumerProperties):
+ BlueprintMessageConsumerService {
when (messageConsumerProperties) {
is KafkaBasicAuthMessageConsumerProperties -> {
private fun kafkaBasicAuthMessageConsumerProperties(prefix: String): KafkaBasicAuthMessageConsumerProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, KafkaBasicAuthMessageConsumerProperties::class.java)
+ prefix, KafkaBasicAuthMessageConsumerProperties::class.java
+ )
}
private fun kafkaStreamsBasicAuthMessageConsumerProperties(prefix: String): KafkaStreamsBasicAuthConsumerProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, KafkaStreamsBasicAuthConsumerProperties::class.java)
+ prefix, KafkaStreamsBasicAuthConsumerProperties::class.java
+ )
}
-
}
}
/** Consume the [topics] with [additionalConfig], so that we can execute dynamic function [consumerFunction] */
- suspend fun consume(topics: List<String>, additionalConfig: Map<String, Any>?,
- consumerFunction: ConsumerFunction) {
+ suspend fun consume(
+ topics: List<String>,
+ additionalConfig: Map<String, Any>?,
+ consumerFunction: ConsumerFunction
+ ) {
throw BluePrintProcessorException("Not Implemented")
}
/** close the channel, consumer and other resources */
suspend fun shutDown()
}
+
/** Consumer dynamic implementation interface */
interface KafkaConsumerRecordsFunction : ConsumerFunction {
- suspend fun invoke(messageConsumerProperties: MessageConsumerProperties, consumer: Consumer<*, *>,
- consumerRecords: ConsumerRecords<*, *>)
+
+ suspend fun invoke(
+ messageConsumerProperties: MessageConsumerProperties,
+ consumer: Consumer<*, *>,
+ consumerRecords: ConsumerRecords<*, *>
+ )
}
interface KafkaStreamConsumerFunction : ConsumerFunction {
- suspend fun createTopology(messageConsumerProperties: MessageConsumerProperties,
- additionalConfig: Map<String, Any>?): Topology
-}
\ No newline at end of file
+ suspend fun createTopology(
+ messageConsumerProperties: MessageConsumerProperties,
+ additionalConfig: Map<String, Any>?
+ ): Topology
+}
}
suspend fun sendMessageNB(topic: String, message: Any, headers: MutableMap<String, String>?): Boolean
-}
\ No newline at end of file
+}
import kotlin.concurrent.thread
open class KafkaBasicAuthMessageConsumerService(
- private val messageConsumerProperties: KafkaBasicAuthMessageConsumerProperties)
- : BlueprintMessageConsumerService {
+ private val messageConsumerProperties: KafkaBasicAuthMessageConsumerProperties
+) :
+ BlueprintMessageConsumerService {
val log = logger(KafkaBasicAuthMessageConsumerService::class)
val channel = Channel<String>()
return subscribe(consumerTopic, additionalConfig)
}
-
override suspend fun subscribe(topics: List<String>, additionalConfig: Map<String, Any>?): Channel<String> {
/** Create Kafka consumer */
kafkaConsumer = kafkaConsumer(additionalConfig)
return consume(topics = consumerTopic, additionalConfig = additionalConfig, consumerFunction = consumerFunction)
}
- override suspend fun consume(topics: List<String>, additionalConfig: Map<String, Any>?,
- consumerFunction: ConsumerFunction) {
+ override suspend fun consume(
+ topics: List<String>,
+ additionalConfig: Map<String, Any>?,
+ consumerFunction: ConsumerFunction
+ ) {
val kafkaConsumerFunction = consumerFunction as KafkaConsumerRecordsFunction
import org.apache.commons.lang.builder.ToStringBuilder
import org.apache.kafka.clients.producer.Callback
import org.apache.kafka.clients.producer.KafkaProducer
-import org.apache.kafka.clients.producer.ProducerConfig.*
+import org.apache.kafka.clients.producer.ProducerConfig.ACKS_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.BOOTSTRAP_SERVERS_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.CLIENT_ID_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.common.header.internals.RecordHeader
import org.apache.kafka.common.serialization.ByteArraySerializer
import java.nio.charset.Charset
class KafkaBasicAuthMessageProducerService(
- private val messageProducerProperties: KafkaBasicAuthMessageProducerProperties)
- : BlueprintMessageProducerService {
+ private val messageProducerProperties: KafkaBasicAuthMessageProducerProperties
+) :
+ BlueprintMessageProducerService {
private val log = LoggerFactory.getLogger(KafkaBasicAuthMessageProducerService::class.java)!!
return sendMessageNB(messageProducerProperties.topic!!, message, headers)
}
- override suspend fun sendMessageNB(topic: String, message: Any,
- headers: MutableMap<String, String>?): Boolean {
+ override suspend fun sendMessageNB(
+ topic: String,
+ message: Any,
+ headers: MutableMap<String, String>?
+ ): Boolean {
val byteArrayMessage = when (message) {
is String -> message.toByteArray(Charset.defaultCharset())
else -> message.asJsonString().toByteArray(Charset.defaultCharset())
return kafkaProducer!!
}
}
-
import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaStreamsBasicAuthConsumerProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.logger
-import java.util.*
+import java.util.Properties
-open class KafkaStreamsBasicAuthConsumerService(private val messageConsumerProperties: KafkaStreamsBasicAuthConsumerProperties)
- : BlueprintMessageConsumerService {
+open class KafkaStreamsBasicAuthConsumerService(private val messageConsumerProperties: KafkaStreamsBasicAuthConsumerProperties) :
+ BlueprintMessageConsumerService {
val log = logger(KafkaStreamsBasicAuthConsumerService::class)
lateinit var kafkaStreams: KafkaStreams
kafkaStreams.close()
}
}
-}
\ No newline at end of file
+}
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
-import java.util.*
+import java.util.UUID
class MessageLoggerService {
private val log = logger(MessageLoggerService::class)
fun messageConsuming(headers: CommonHeader, consumerRecord: ConsumerRecord<*, *>) {
- messageConsuming(headers.requestId, headers.subRequestId,
- headers.originatorId, consumerRecord)
+ messageConsuming(
+ headers.requestId, headers.subRequestId,
+ headers.originatorId, consumerRecord
+ )
}
fun messageConsuming(consumerRecord: ConsumerRecord<*, *>) {
messageConsuming(requestID, invocationID, partnerName, consumerRecord)
}
-
- fun messageConsuming(requestID: String, invocationID: String, partnerName: String,
- consumerRecord: ConsumerRecord<*, *>) {
+ fun messageConsuming(
+ requestID: String,
+ invocationID: String,
+ partnerName: String,
+ consumerRecord: ConsumerRecord<*, *>
+ ) {
val headers = consumerRecord.headers().toMap()
val localhost = InetAddress.getLocalHost()
- MDC.put("InvokeTimestamp", ZonedDateTime
+ MDC.put(
+ "InvokeTimestamp", ZonedDateTime
.ofInstant(Instant.ofEpochMilli(consumerRecord.timestamp()), ZoneOffset.UTC)
- .format(DateTimeFormatter.ISO_INSTANT))
+ .format(DateTimeFormatter.ISO_INSTANT)
+ )
MDC.put("RequestID", requestID)
MDC.put("InvocationID", invocationID)
MDC.put("PartnerName", partnerName)
fun messageConsumingExisting() {
MDC.clear()
}
-}
\ No newline at end of file
+}
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
-import org.apache.kafka.clients.consumer.*
+import org.apache.kafka.clients.consumer.Consumer
+import org.apache.kafka.clients.consumer.ConsumerRecord
+import org.apache.kafka.clients.consumer.ConsumerRecords
+import org.apache.kafka.clients.consumer.MockConsumer
+import org.apache.kafka.clients.consumer.OffsetResetStrategy
import org.apache.kafka.common.TopicPartition
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
-
@RunWith(SpringRunner::class)
@DirtiesContext
-@ContextConfiguration(classes = [BluePrintMessageLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.messageconsumer.sample.type=kafka-basic-auth",
- "blueprintsprocessor.messageconsumer.sample.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageconsumer.sample.groupId=sample-group",
- "blueprintsprocessor.messageconsumer.sample.topic=default-topic",
- "blueprintsprocessor.messageconsumer.sample.clientId=default-client-id",
- "blueprintsprocessor.messageconsumer.sample.pollMillSec=10",
- "blueprintsprocessor.messageconsumer.sample.pollRecords=1",
-
- "blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
- "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageproducer.sample.topic=default-topic",
- "blueprintsprocessor.messageproducer.sample.clientId=default-client-id"
-])
+@ContextConfiguration(
+ classes = [BluePrintMessageLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.messageconsumer.sample.type=kafka-basic-auth",
+ "blueprintsprocessor.messageconsumer.sample.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageconsumer.sample.groupId=sample-group",
+ "blueprintsprocessor.messageconsumer.sample.topic=default-topic",
+ "blueprintsprocessor.messageconsumer.sample.clientId=default-client-id",
+ "blueprintsprocessor.messageconsumer.sample.pollMillSec=10",
+ "blueprintsprocessor.messageconsumer.sample.pollRecords=1",
+
+ "blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
+ "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageproducer.sample.topic=default-topic",
+ "blueprintsprocessor.messageproducer.sample.clientId=default-client-id"
+ ]
+)
open class BlueprintMessageConsumerServiceTest {
+
val log = logger(BlueprintMessageConsumerServiceTest::class)
@Autowired
fun testKafkaBasicAuthConsumerService() {
runBlocking {
val blueprintMessageConsumerService = bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
+ .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
assertNotNull(blueprintMessageConsumerService, "failed to get blueprintMessageConsumerService")
val spyBlueprintMessageConsumerService = spyk(blueprintMessageConsumerService, recordPrivateCalls = true)
mockKafkaConsumer.updateBeginningOffsets(partitionsBeginningMap)
mockKafkaConsumer.updateEndOffsets(partitionsEndMap)
for (i in 1..10) {
- val record = ConsumerRecord<String, ByteArray>(topic, 1, i.toLong(), "key_$i",
- "I am message $i".toByteArray())
+ val record = ConsumerRecord<String, ByteArray>(
+ topic, 1, i.toLong(), "key_$i",
+ "I am message $i".toByteArray()
+ )
mockKafkaConsumer.addRecord(record)
}
fun testKafkaBasicAuthConsumerWithDynamicFunction() {
runBlocking {
val blueprintMessageConsumerService = bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
+ .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
assertNotNull(blueprintMessageConsumerService, "failed to get blueprintMessageConsumerService")
val spyBlueprintMessageConsumerService = spyk(blueprintMessageConsumerService, recordPrivateCalls = true)
mockKafkaConsumer.updateBeginningOffsets(partitionsBeginningMap)
mockKafkaConsumer.updateEndOffsets(partitionsEndMap)
for (i in 1..10) {
- val record = ConsumerRecord<String, ByteArray>(topic, 1, i.toLong(), "key_$i",
- "I am message $i".toByteArray())
+ val record = ConsumerRecord<String, ByteArray>(
+ topic, 1, i.toLong(), "key_$i",
+ "I am message $i".toByteArray()
+ )
mockKafkaConsumer.addRecord(record)
}
every { spyBlueprintMessageConsumerService.kafkaConsumer(any()) } returns mockKafkaConsumer
/** Test Consumer Function implementation */
val consumerFunction = object : KafkaConsumerRecordsFunction {
- override suspend fun invoke(messageConsumerProperties: MessageConsumerProperties,
- consumer: Consumer<*, *>, consumerRecords: ConsumerRecords<*, *>) {
+ override suspend fun invoke(
+ messageConsumerProperties: MessageConsumerProperties,
+ consumer: Consumer<*, *>,
+ consumerRecords: ConsumerRecords<*, *>
+ ) {
val count = consumerRecords.count()
log.trace("Received Message count($count)")
}
}
/** Integration Kafka Testing, Enable and use this test case only for local desktop testing with real kafka broker */
- //@Test
+ // @Test
fun testKafkaIntegration() {
runBlocking {
val blueprintMessageConsumerService = bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
+ .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
assertNotNull(blueprintMessageConsumerService, "failed to get blueprintMessageConsumerService")
val channel = blueprintMessageConsumerService.subscribe(null)
/** Send message with every 1 sec */
val blueprintMessageProducerService = bluePrintMessageLibPropertyService
- .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
+ .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
launch {
repeat(5) {
delay(100)
val headers: MutableMap<String, String> = hashMapOf()
headers["id"] = it.toString()
- blueprintMessageProducerService.sendMessageNB(message = "this is my message($it)",
- headers = headers)
+ blueprintMessageProducerService.sendMessageNB(
+ message = "this is my message($it)",
+ headers = headers
+ )
}
}
delay(5000)
blueprintMessageConsumerService.shutDown()
}
}
-}
\ No newline at end of file
+}
import kotlin.test.Test
import kotlin.test.assertTrue
-
@RunWith(SpringRunner::class)
@DirtiesContext
-@ContextConfiguration(classes = [BluePrintMessageLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
- "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageproducer.sample.topic=default-topic",
- "blueprintsprocessor.messageproducer.sample.clientId=default-client-id"
-])
+@ContextConfiguration(
+ classes = [BluePrintMessageLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
+ "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageproducer.sample.topic=default-topic",
+ "blueprintsprocessor.messageproducer.sample.clientId=default-client-id"
+ ]
+)
open class BlueprintMessageProducerServiceTest {
@Autowired
fun testKafkaBasicAuthProducertService() {
runBlocking {
val blueprintMessageProducerService = bluePrintMessageLibPropertyService
- .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
+ .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
val mockKafkaTemplate = mockk<KafkaProducer<String, ByteArray>>()
assertTrue(response, "failed to get command response")
}
}
-
}
-
-
-
import org.springframework.test.context.junit4.SpringRunner
import kotlin.test.assertNotNull
-
@RunWith(SpringRunner::class)
@DirtiesContext
-@ContextConfiguration(classes = [BluePrintMessageLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-[
- "blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
- "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageproducer.sample.topic=default-stream-topic",
- "blueprintsprocessor.messageproducer.sample.clientId=default-client-id",
+@ContextConfiguration(
+ classes = [BluePrintMessageLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ [
+ "blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
+ "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageproducer.sample.topic=default-stream-topic",
+ "blueprintsprocessor.messageproducer.sample.clientId=default-client-id",
- "blueprintsprocessor.messageconsumer.stream-consumer.type=kafka-streams-basic-auth",
- "blueprintsprocessor.messageconsumer.stream-consumer.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageconsumer.stream-consumer.applicationId=test-streams-application",
- "blueprintsprocessor.messageconsumer.stream-consumer.topic=default-stream-topic"
+ "blueprintsprocessor.messageconsumer.stream-consumer.type=kafka-streams-basic-auth",
+ "blueprintsprocessor.messageconsumer.stream-consumer.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageconsumer.stream-consumer.applicationId=test-streams-application",
+ "blueprintsprocessor.messageconsumer.stream-consumer.topic=default-stream-topic"
-])
+ ]
+)
class KafkaStreamsBasicAuthConsumerServiceTest {
+
@Autowired
lateinit var bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService
}
/** Integration Kafka Testing, Enable and use this test case only for local desktop testing with real kafka broker */
- //@Test
+ // @Test
fun testKafkaStreamingMessageConsumer() {
runBlocking {
val streamingConsumerService = bluePrintMessageLibPropertyService.blueprintMessageConsumerService("stream-consumer")
// Dynamic Consumer Function to create Topology
val consumerFunction = object : KafkaStreamConsumerFunction {
- override suspend fun createTopology(messageConsumerProperties: MessageConsumerProperties,
- additionalConfig: Map<String, Any>?): Topology {
+ override suspend fun createTopology(
+ messageConsumerProperties: MessageConsumerProperties,
+ additionalConfig: Map<String, Any>?
+ ): Topology {
val topology = Topology()
val kafkaStreamsBasicAuthConsumerProperties = messageConsumerProperties
as KafkaStreamsBasicAuthConsumerProperties
// Store Buolder
val countStoreSupplier = Stores.keyValueStoreBuilder(
- Stores.persistentKeyValueStore("PriorityMessageState"),
- Serdes.String(),
- PriorityMessageSerde())
- .withLoggingEnabled(changelogConfig)
+ Stores.persistentKeyValueStore("PriorityMessageState"),
+ Serdes.String(),
+ PriorityMessageSerde()
+ )
+ .withLoggingEnabled(changelogConfig)
topology.addProcessor("FirstProcessor", firstProcessorSupplier, "Source")
topology.addStateStore(countStoreSupplier, "FirstProcessor")
- topology.addSink("SINK", "default-stream-topic-out", Serdes.String().serializer(),
- PriorityMessageSerde().serializer(), "FirstProcessor")
+ topology.addSink(
+ "SINK", "default-stream-topic-out", Serdes.String().serializer(),
+ PriorityMessageSerde().serializer(), "FirstProcessor"
+ )
return topology
}
}
/** Send message with every 1 sec */
val blueprintMessageProducerService = bluePrintMessageLibPropertyService
- .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
+ .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
launch {
repeat(5) {
delay(1000)
val headers: MutableMap<String, String> = hashMapOf()
headers["id"] = it.toString()
- blueprintMessageProducerService.sendMessageNB(message = "this is my message($it)",
- headers = headers)
+ blueprintMessageProducerService.sendMessageNB(
+ message = "this is my message($it)",
+ headers = headers
+ )
}
}
streamingConsumerService.consume(null, consumerFunction)
streamingConsumerService.shutDown()
}
}
-}
\ No newline at end of file
+}
class MessageLoggerServiceTest {
-
@Test
fun testMessagingHeaders() {
val messageLoggerService = MessageLoggerService()
assertEquals("1234-12", map[BluePrintConstants.ONAP_REQUEST_ID])
messageLoggerService.messageConsumingExisting()
-
}
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import java.io.Serializable
import java.nio.charset.Charset
-import java.util.*
+import java.util.UUID
class PriorityMessage : Serializable {
lateinit var id: String
return object : Deserializer<PriorityMessage> {
override fun deserialize(topic: String, data: ByteArray): PriorityMessage {
return JacksonUtils.readValue(String(data), PriorityMessage::class.java)
- ?: throw BluePrintProcessorException("failed to convert")
+ ?: throw BluePrintProcessorException("failed to convert")
}
override fun configure(configs: MutableMap<String, *>?, isKey: Boolean) {
}
}
-
class FirstProcessor : Processor<ByteArray, ByteArray> {
private val log = logger(FirstProcessor::class)
override fun close() {
log.info("Close...")
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.asType
import kotlin.reflect.KClass
-
fun <T : Any> ExecutionServiceInput.payloadAsType(clazzType: KClass<T>): T {
val actionName = this.actionIdentifiers.actionName
val requestJsonNode = this.payload.get("$actionName-request")
return requestJsonNode.asType(clazzType.java)
-}
\ No newline at end of file
+}
@Bean
open fun bluePrintLoadConfiguration(): BluePrintLoadConfiguration {
return bluePrintPropertiesService
- .propertyBeanType(PREFIX_BLUEPRINT_PROCESSOR, BluePrintLoadConfiguration::class.java)
+ .propertyBeanType(PREFIX_BLUEPRINT_PROCESSOR, BluePrintLoadConfiguration::class.java)
}
}
@Configuration
open class BluePrintPropertyConfiguration {
+
@Autowired
lateinit var environment: Environment
@Service
open class BluePrintPropertiesService(private var bluePrintPropertyBinder: Binder) {
+
fun <T> propertyBeanType(prefix: String, type: Class<T>): T {
return bluePrintPropertyBinder.bind(prefix, Bindable.of(type)).get()
}
BluePrintDependencyService.inject(applicationContext)
log.info("Dependency Management module created...")
}
-
-}
\ No newline at end of file
+}
import io.swagger.annotations.ApiModelProperty
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
-import java.util.*
+import java.util.Date
/**
* BlueprintProcessorData
*/
open class ExecutionServiceInput {
+
@get:ApiModelProperty(required = true, value = "Headers providing request context.")
lateinit var commonHeader: CommonHeader
@get:ApiModelProperty(required = true, value = "Provide information about the action to execute.")
lateinit var actionIdentifiers: ActionIdentifiers
- @get:ApiModelProperty(required = true,
- value = "Contain the information to be passed as input to the action." +
- "The payload is constituted of two section: the workflow input which is the higher level block (xxx-request)" +
- " and the input for resource resolution located within the xxx-request block, contained within xxx-properties")
+ @get:ApiModelProperty(
+ required = true,
+ value = "Contain the information to be passed as input to the action." +
+ "The payload is constituted of two section: the workflow input which is the higher level block (xxx-request)" +
+ " and the input for resource resolution located within the xxx-request block, contained within xxx-properties"
+ )
lateinit var payload: ObjectNode
@get:ApiModelProperty(hidden = true)
@get:JsonIgnore
lateinit var actionIdentifiers: ActionIdentifiers
@get:ApiModelProperty(required = true, value = "Status of the request.")
lateinit var status: Status
- @get:ApiModelProperty(required = true,
- value = "Contain the information to be passed as input to the action." +
- "The payload is constituted of two section: the workflow input which is the higher level block (xxx-request)" +
- " and the input for resource resolution located within the xxx-request block, contained within xxx-properties")
+ @get:ApiModelProperty(
+ required = true,
+ value = "Contain the information to be passed as input to the action." +
+ "The payload is constituted of two section: the workflow input which is the higher level block (xxx-request)" +
+ " and the input for resource resolution located within the xxx-request block, contained within xxx-properties"
+ )
lateinit var payload: ObjectNode
@get:ApiModelProperty(hidden = true)
@get:JsonIgnore
lateinit var blueprintVersion: String
@get:ApiModelProperty(required = true, value = "Name of the workflow to execute.")
lateinit var actionName: String
- @get:ApiModelProperty(required = true,
- value = "Async processing is only supported for gRPC client.",
- allowableValues = "sync, async")
+ @get:ApiModelProperty(
+ required = true,
+ value = "Async processing is only supported for gRPC client.",
+ allowableValues = "sync, async"
+ )
lateinit var mode: String
}
var code: Int = 200
@get:ApiModelProperty(required = true, value = "Type of the event being emitted by CDS.")
var eventType: String = EventType.EVENT_COMPONENT_EXECUTED.name
- @get:ApiModelProperty(required = true,
- value = "Time when the execution ended.",
- example = "2012-04-23T18:25:43.511Z")
+ @get:ApiModelProperty(
+ required = true,
+ value = "Time when the execution ended.",
+ example = "2012-04-23T18:25:43.511Z"
+ )
@get:JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
var timestamp: Date = Date()
@get:ApiModelProperty(required = false, value = "Error message when system failed")
open class StepData {
lateinit var name: String
var properties: MutableMap<String, JsonNode> = mutableMapOf()
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.core.api.data
import com.fasterxml.jackson.databind.JsonNode
-import java.util.*
+import java.util.Date
enum class StatusType {
SUCCESS, FAILURE
}
-data class RemoteIdentifier(var blueprintName: String,
- var blueprintVersion: String)
-
-
-data class RemoteScriptExecutionInput(var requestId: String,
- var correlationId: String? = null,
- var remoteIdentifier: RemoteIdentifier? = null,
- var command: String,
- var timeOut: Long = 30,
- var properties: MutableMap<String, JsonNode> = hashMapOf()
+data class RemoteIdentifier(
+ var blueprintName: String,
+ var blueprintVersion: String
)
+data class RemoteScriptExecutionInput(
+ var requestId: String,
+ var correlationId: String? = null,
+ var remoteIdentifier: RemoteIdentifier? = null,
+ var command: String,
+ var timeOut: Long = 30,
+ var properties: MutableMap<String, JsonNode> = hashMapOf()
+)
-data class RemoteScriptExecutionOutput(var requestId: String,
- var response: List<String>,
- var status: StatusType = StatusType.SUCCESS,
- var timestamp: Date = Date(),
- var payload: JsonNode)
+data class RemoteScriptExecutionOutput(
+ var requestId: String,
+ var response: List<String>,
+ var status: StatusType = StatusType.SUCCESS,
+ var timestamp: Date = Date(),
+ var payload: JsonNode
+)
-data class PrepareRemoteEnvInput(var requestId: String,
- var correlationId: String? = null,
- var remoteIdentifier: RemoteIdentifier? = null,
- var packages: JsonNode,
- var timeOut: Long = 120,
- var properties: MutableMap<String, JsonNode> = hashMapOf())
+data class PrepareRemoteEnvInput(
+ var requestId: String,
+ var correlationId: String? = null,
+ var remoteIdentifier: RemoteIdentifier? = null,
+ var packages: JsonNode,
+ var timeOut: Long = 120,
+ var properties: MutableMap<String, JsonNode> = hashMapOf()
+)
* @author Brinda Santh
*/
open class ComponentNodeFactory : ApplicationContextAware {
+
private val log = LoggerFactory.getLogger(ComponentNodeFactory::class.java)
var componentNodes: MutableMap<String, ComponentNode> = hashMapOf()
componentNodes = context.getBeansOfType(ComponentNode::class.java)
log.info("Injected Component Nodes : {}", componentNodes)
}
-}
\ No newline at end of file
+}
import com.google.common.base.Strings
import com.google.protobuf.Struct
import com.google.protobuf.util.JsonFormat
-import org.onap.ccsdk.cds.controllerblueprints.common.api.*
+import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers
+import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader
+import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
+import org.onap.ccsdk.cds.controllerblueprints.common.api.Flag
+import org.onap.ccsdk.cds.controllerblueprints.common.api.Status
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput
import java.text.SimpleDateFormat
-import java.util.*
+import java.util.Date
private val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
JsonFormat.parser().merge(JacksonUtils.getJson(this.payload), struct)
executionServiceOuput.payload = struct.build()
return executionServiceOuput.build()
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
-
class PayloadUtils {
companion object {
fun prepareDynamicInputsFromComponentPayload(bluePrintRuntimeService: BluePrintRuntimeService<*>, payload: JsonNode) {
payload.fields().forEach { property ->
val path = StringBuilder(BluePrintConstants.PATH_INPUTS)
- .append(BluePrintConstants.PATH_DIVIDER).append(property.key).toString()
+ .append(BluePrintConstants.PATH_DIVIDER).append(property.key).toString()
bluePrintRuntimeService.put(path, property.value)
}
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.core
// TODO
-open class BluePrintPropertiesTest
\ No newline at end of file
+open class BluePrintPropertiesTest
fun commonHeaderToJavaTest() {
val flag = Flag.newBuilder().setIsForce(true).setTtl(2).build()
- val commonHeader = CommonHeader.newBuilder().setOriginatorId("Origin").setRequestId("requestID").setSubRequestId("subRequestID").setTimestamp(dateString).setFlag(flag).build()
+ val commonHeader =
+ CommonHeader.newBuilder().setOriginatorId("Origin").setRequestId("requestID").setSubRequestId("subRequestID").setTimestamp(dateString)
+ .setFlag(flag).build()
val commonHeader2 = commonHeader.toJava()
Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId)
@Test
fun actionIdentifierToJavaTest() {
- val actionIdentifiers = ActionIdentifiers.newBuilder().setActionName("Process Action").setBlueprintName("BlueprintName").setBlueprintVersion("3.0").setMode("Execution").build()
+ val actionIdentifiers =
+ ActionIdentifiers.newBuilder().setActionName("Process Action").setBlueprintName("BlueprintName").setBlueprintVersion("3.0")
+ .setMode("Execution").build()
val actionIdentifiers2 = actionIdentifiers.toJava()
Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName)
Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion)
Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode)
}
-}
\ No newline at end of file
+}
* 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"
// 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
}
}
open class SSLBasicAuthRestClientPropertiesBuilder : SSLRestClientPropertiesBuilder() {
- //TODO()
+ // TODO()
}
open class SSLTokenAuthRestClientPropertiesBuilder : SSLRestClientPropertiesBuilder() {
- //TODO()
-}
\ No newline at end of file
+ // TODO()
+}
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
+}
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"
}
private fun setBasicAuth(username: String, password: String): String {
val credentialsString = "$username:$password"
return Base64.getEncoder().encodeToString(
- credentialsString.toByteArray(Charset.defaultCharset()))
+ credentialsString.toByteArray(Charset.defaultCharset())
+ )
}
-
}
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
open fun blueprintWebClientService(jsonNode: JsonNode): BlueprintWebClientService {
val service = preInterceptor?.getInstance(jsonNode)
- ?: blueprintWebClientService(restClientProperties(jsonNode))
+ ?: blueprintWebClientService(restClientProperties(jsonNode))
return postInterceptor?.getInstance(jsonNode, service) ?: service
}
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)
policyManagerRestClientProperties(prefix)
}
else -> {
- throw BluePrintProcessorException("Rest adaptor($type) is" +
- " not supported")
+ throw BluePrintProcessorException(
+ "Rest adaptor($type) is" +
+ " not supported"
+ )
}
}
}
}
else -> {
throw BluePrintProcessorException(
- "Rest adaptor($type) is not supported")
+ "Rest adaptor($type) is not supported"
+ )
}
}
}
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
}
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
}
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 {
fun getInstance(selector: String, service: BlueprintWebClientService): BlueprintWebClientService
}
}
-
-
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
/** 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
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.
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()
}
@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 {
}
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)
}
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)
}
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)
}
}
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)
}
private fun basicHeaders(headers: Map<String, String>?):
- Array<BasicHeader> {
+ Array<BasicHeader> {
val basicHeaders = mutableListOf<BasicHeader>()
defaultHeaders().forEach { (name, value) ->
basicHeaders.add(BasicHeader(name, value))
.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 {
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
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
}
}
-
/** 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)
@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) {
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
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 {
}
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!!
TokenAuthRestClientService(token)
}
else -> {
- //Returns null for No auth
+ // Returns null for No auth
null
}
}
}
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 {
}
sslContext.loadTrustMaterial(File(sslTrust), sslTrustPwd.toCharArray(), acceptingTrustStrategy)
- var csf : SSLConnectionSocketFactory
+ var csf: SSLConnectionSocketFactory
if (sslTrustIgnoreHostname) {
csf = SSLConnectionSocketFactory(sslContext.build(), NoopHostnameVerifier())
} else {
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))
+ )
}
}
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!!
fun logResponse(): HttpResponseInterceptor =
HttpResponseInterceptor { response, _ -> log.info("Response status(${response.statusLine.statusCode} - ${response.statusLine.reasonPhrase})") }
}
-}
\ No newline at end of file
+}
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
@Test
fun testSSLTokenProperties() {
val properties = bluePrintRestLibPropertyService.restClientProperties(
- "blueprintsprocessor.restclient.ssltoken")
+ "blueprintsprocessor.restclient.ssltoken"
+ )
assertNotNull(properties, "failed to create property bean")
val p: SSLTokenAuthRestClientProperties =
@Test
fun testSSLNoAuthProperties() {
val properties = bluePrintRestLibPropertyService.restClientProperties(
- "blueprintsprocessor.restclient.ssl")
+ "blueprintsprocessor.restclient.ssl"
+ )
assertNotNull(properties, "failed to create property bean")
val p: SSLRestClientProperties =
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
fun testSSLNoAuthPropertiesAsJson() {
val actualObj: JsonNode = defaultMapper.readTree(sslNoAuthEndpointWithHeadersField())
val properties = bluePrintRestLibPropertyService.restClientProperties(
- actualObj)
+ actualObj
+ )
assertNotNull(properties, "failed to create property bean")
val p: SSLRestClientProperties =
fun testBlueprintWebClientService() {
val blueprintWebClientService = bluePrintRestLibPropertyService
.blueprintWebClientService("sample")
- assertNotNull(blueprintWebClientService,
- "failed to create blueprintWebClientService")
+ assertNotNull(
+ blueprintWebClientService,
+ "failed to create blueprintWebClientService"
+ )
}
@Test
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 =
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)
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 =
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)
@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)
}
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()
@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)
}
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()
@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)
}
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)
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 =
"""{
"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",
}""".trimIndent()
}
}
-
import kotlin.test.assertNotNull
class RestClientPropertiesDSLTest {
-
+
@Test
fun testBasicAuthRestClientProperties() {
val properties = BluePrintTypes.dslBasicAuthRestClientProperties {
}
assertNotNull(properties, "failed to get dslSSLRestClientProperties")
}
-}
\ No newline at end of file
+}
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
@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")
}
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()
}
@Test
fun testSampleAaiReq() {
val restClientService = bluePrintRestLibPropertyService
- .blueprintWebClientService("test")
+ .blueprintWebClientService("test")
val headers = mutableMapOf<String, String>()
headers["X-TransactionId"] = "9999"
headers["X-FromAppId"] = "AAI"
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()
@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 ""
}
@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 ""
}
@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 ""
}
@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 ""
}
@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()
}
}
* 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
+)
* Exposed Dependency Service by this SSH Lib Module
*/
fun BluePrintDependencyService.sshLibPropertyService(): BluePrintSshLibPropertyService =
- instance(SshLibConstants.SERVICE_BLUEPRINT_SSH_LIB_PROPERTY)
-
+ instance(SshLibConstants.SERVICE_BLUEPRINT_SSH_LIB_PROPERTY)
fun BluePrintDependencyService.sshClientService(selector: String): BlueprintSshClientService =
- sshLibPropertyService().blueprintSshClientService(selector)
-
+ sshLibPropertyService().blueprintSshClientService(selector)
fun BluePrintDependencyService.sshClientService(jsonNode: JsonNode): BlueprintSshClientService =
- sshLibPropertyService().blueprintSshClientService(jsonNode)
-
+ sshLibPropertyService().blueprintSshClientService(jsonNode)
class SshLibConstants {
companion object {
const val PROPERTY_SSH_CLIENT_PREFIX = "blueprintsprocessor.sshclient."
const val TYPE_BASIC_AUTH = "basic-auth"
}
-}
\ No newline at end of file
+}
open class BasicAuthSshClientProperties : SshClientProperties() {
lateinit var password: String
lateinit var username: String
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.slf4j.LoggerFactory
import java.io.ByteArrayOutputStream
-import java.util.*
+import java.util.Collections
+import java.util.EnumSet
-
-open class BasicAuthSshClientService(private val basicAuthSshClientProperties: BasicAuthSshClientProperties)
- : BlueprintSshClientService {
+open class BasicAuthSshClientService(private val basicAuthSshClientProperties: BasicAuthSshClientProperties) :
+ BlueprintSshClientService {
private val log = LoggerFactory.getLogger(BasicAuthSshClientService::class.java)!!
sshClient.serverKeyVerifier = AcceptAllServerKeyVerifier.INSTANCE
sshClient.start()
log.debug("SSH Client Service started successfully")
- clientSession = sshClient.connect(basicAuthSshClientProperties.username, basicAuthSshClientProperties.host,
- basicAuthSshClientProperties.port)
- .verify(basicAuthSshClientProperties.connectionTimeOut)
- .session
+ clientSession = sshClient.connect(
+ basicAuthSshClientProperties.username, basicAuthSshClientProperties.host,
+ basicAuthSshClientProperties.port
+ )
+ .verify(basicAuthSshClientProperties.connectionTimeOut)
+ .session
clientSession.addPasswordIdentity(basicAuthSshClientProperties.password)
clientSession.auth().verify(basicAuthSshClientProperties.connectionTimeOut)
channel = clientSession.createExecChannel(command)
checkNotNull(channel) { "failed to create Channel for the command : $command" }
- //TODO("Convert to streaming ")
+ // TODO("Convert to streaming ")
val outputStream = ByteArrayOutputStream()
channel!!.out = outputStream
channel!!.err = outputStream
fun sshClientProperties(jsonNode: JsonNode): SshClientProperties {
val type = jsonNode.get("type")?.textValue()
- ?: throw BluePrintProcessorException("missing type field in ssh client properties")
+ ?: throw BluePrintProcessorException("missing type field in ssh client properties")
return when (type) {
SshLibConstants.TYPE_BASIC_AUTH -> {
- JacksonUtils.readValue(jsonNode,
- BasicAuthSshClientProperties::class.java)!!
+ JacksonUtils.readValue(
+ jsonNode,
+ BasicAuthSshClientProperties::class.java
+ )!!
}
else -> {
throw BluePrintProcessorException("SSH adaptor($type) is not supported")
private fun basicAuthSshClientProperties(prefix: String): BasicAuthSshClientProperties {
return bluePrintProperties.propertyBeanType(
- prefix, BasicAuthSshClientProperties::class.java)
+ prefix, BasicAuthSshClientProperties::class.java
+ )
}
-
}
suspend fun executeCommandNB(command: String, timeOut: Long): String
suspend fun closeSessionNB()
-}
\ No newline at end of file
+}
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
-
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintSshLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.sshclient.sample.type=basic-auth",
- "blueprintsprocessor.sshclient.sample.host=127.0.0.1",
- "blueprintsprocessor.sshclient.sample.port=22",
- "blueprintsprocessor.sshclient.sample.password=1234",
- "blueprintsprocessor.sshclient.sample.username=dummy"
-])
+@ContextConfiguration(
+ classes = [BluePrintSshLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.sshclient.sample.type=basic-auth",
+ "blueprintsprocessor.sshclient.sample.host=127.0.0.1",
+ "blueprintsprocessor.sshclient.sample.port=22",
+ "blueprintsprocessor.sshclient.sample.password=1234",
+ "blueprintsprocessor.sshclient.sample.username=dummy"
+ ]
+)
class BluePrintSshLibPropertyServiceTest {
@Autowired
@Test
fun testRestClientProperties() {
val properties = bluePrintSshLibPropertyService
- .sshClientProperties("blueprintsprocessor.sshclient.sample") as BasicAuthSshClientProperties
+ .sshClientProperties("blueprintsprocessor.sshclient.sample") as BasicAuthSshClientProperties
assertNotNull(properties, "failed to create property bean")
assertEquals(properties.host, "127.0.0.1", "failed to match host property")
assertEquals(properties.port, 22, "failed to match port property")
assertEquals(properties.password, "1234", "failed to match host property")
assertEquals(properties.username, "dummy", "failed to match host property")
}
-}
\ No newline at end of file
+}
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
-
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintSshLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.sshclient.sample.type=basic-auth",
- "blueprintsprocessor.sshclient.sample.host=localhost",
- "blueprintsprocessor.sshclient.sample.port=52815",
- "blueprintsprocessor.sshclient.sample.username=root",
- "blueprintsprocessor.sshclient.sample.password=dummyps"
-])
+@ContextConfiguration(
+ classes = [BluePrintSshLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.sshclient.sample.type=basic-auth",
+ "blueprintsprocessor.sshclient.sample.host=localhost",
+ "blueprintsprocessor.sshclient.sample.port=52815",
+ "blueprintsprocessor.sshclient.sample.username=root",
+ "blueprintsprocessor.sshclient.sample.password=dummyps"
+ ]
+)
class BlueprintSshClientServiceTest {
@Autowired
sshd.keyPairProvider = createTestHostKeyProvider()
sshd.passwordAuthenticator = BogusPasswordAuthenticator(userName, password)
sshd.publickeyAuthenticator = AcceptAllPublickeyAuthenticator.INSTANCE
- //sshd.shellFactory = EchoShellFactory()
+ // sshd.shellFactory = EchoShellFactory()
sshd.commandFactory = ProcessShellCommandFactory.INSTANCE
return sshd
}
return true
}
}
-
-
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestMethod
+import org.springframework.web.bind.annotation.RequestParam
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
/**
* Exposes Resource Configuration Snapshot API to store and retrieve stored resource configurations.
*/
@RestController
@RequestMapping("/api/v1/configs")
-@Api(value = "/api/v1/configs",
- description = "Interaction with stored configurations.")
+@Api(
+ value = "/api/v1/configs",
+ description = "Interaction with stored configurations."
+)
open class ResourceConfigSnapshotController(private val resourceConfigSnapshotService: ResourceConfigSnapshotService) {
- @RequestMapping(path = ["/health-check"],
+ @RequestMapping(
+ path = ["/health-check"],
method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun ressCfgSnapshotControllerHealthCheck(): JsonNode = runBlocking {
"Success".asJsonPrimitive()
}
- @RequestMapping(path = [""],
+ @RequestMapping(
+ path = [""],
method = [RequestMethod.GET],
- produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE])
- @ApiOperation(value = "Retrieve a resource configuration snapshot.",
+ produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE]
+ )
+ @ApiOperation(
+ value = "Retrieve a resource configuration snapshot.",
notes = "Retrieve a config snapshot, identified by its Resource Id and Type. " +
- "An extra 'format' parameter can be passed to tell what content-type is expected.")
+ "An extra 'format' parameter can be passed to tell what content-type is expected."
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun get(
- @ApiParam(value = "Resource Type associated of the resource configuration snapshot.", required = false)
+ @ApiParam(value = "Resource Type associated of the resource configuration snapshot.", required = false)
@RequestParam(value = "resourceType", required = true) resourceType: String,
- @ApiParam(value = "Resource Id associated of the resource configuration snapshot.", required = false)
+ @ApiParam(value = "Resource Id associated of the resource configuration snapshot.", required = false)
@RequestParam(value = "resourceId", required = true) resourceId: String,
- @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = false)
+ @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = false)
@RequestParam(value = "status", required = false, defaultValue = "RUNNING") status: String,
- @ApiParam(value = "Expected format of the snapshot being retrieved.", defaultValue = MediaType.TEXT_PLAIN_VALUE,
- required = false)
- @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String)
+ @ApiParam(
+ value = "Expected format of the snapshot being retrieved.", defaultValue = MediaType.TEXT_PLAIN_VALUE,
+ required = false
+ )
+ @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String
+ ):
- : ResponseEntity<String> = runBlocking {
+ ResponseEntity<String> = runBlocking {
var configSnapshot = ""
if (resourceType.isNotEmpty() && resourceId.isNotEmpty()) {
try {
- configSnapshot = resourceConfigSnapshotService.findByResourceIdAndResourceTypeAndStatus(resourceId,
- resourceType, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase()))
- } catch (ex : NoSuchElementException) {
+ configSnapshot = resourceConfigSnapshotService.findByResourceIdAndResourceTypeAndStatus(
+ resourceId,
+ resourceType, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
+ )
+ } catch (ex: NoSuchElementException) {
throw ResourceConfigSnapshotException(
- "Could not find configuration snapshot entry for type $resourceType and Id $resourceId")
+ "Could not find configuration snapshot entry for type $resourceType and Id $resourceId"
+ )
}
} else {
throw IllegalArgumentException("Missing param. You must specify resource-id and resource-type.")
ResponseEntity.ok().contentType(expectedMediaType).body(configSnapshot)
}
- @PostMapping("/{resourceType}/{resourceId}/{status}",
- produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Store a resource configuration snapshot identified by resourceId, resourceType, status.",
+ @PostMapping(
+ "/{resourceType}/{resourceId}/{status}",
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
+ @ApiOperation(
+ value = "Store a resource configuration snapshot identified by resourceId, resourceType, status.",
notes = "Store a resource configuration snapshot, identified by its resourceId and resourceType, " +
"and optionally its status, either RUNNING or CANDIDATE.",
- response = ResourceConfigSnapshot::class, produces = MediaType.APPLICATION_JSON_VALUE)
+ response = ResourceConfigSnapshot::class, produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun postWithResourceIdAndResourceType(
@ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = true)
@PathVariable(value = "status", required = true) status: String,
@ApiParam(value = "Config snapshot to store.", required = true)
- @RequestBody snapshot: String): ResponseEntity<ResourceConfigSnapshot> = runBlocking {
+ @RequestBody snapshot: String
+ ): ResponseEntity<ResourceConfigSnapshot> = runBlocking {
val resultStored =
- resourceConfigSnapshotService.write(snapshot, resourceId, resourceType,
- ResourceConfigSnapshot.Status.valueOf(status.toUpperCase()))
+ resourceConfigSnapshotService.write(
+ snapshot, resourceId, resourceType,
+ ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
+ )
ResponseEntity.ok().body(resultStored)
}
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
import org.slf4j.LoggerFactory
+import org.springframework.dao.EmptyResultDataAccessException
+import org.springframework.dao.IncorrectResultSizeDataAccessException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.orm.jpa.JpaObjectRetrievalFailureException
-import org.springframework.dao.EmptyResultDataAccessException
-import org.springframework.dao.IncorrectResultSizeDataAccessException
-import org.springframework.web.server.ServerWebInputException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
+import org.springframework.web.server.ServerWebInputException
import java.io.Serializable
-import java.util.*
+import java.util.Date
/**
* Handle exceptions in ResourceConfigSnapshot API and provide relevant HTTP status codes and messages
log.error(e.message)
}
val errorMessage =
- ErrorMessage(errorCode.message(e.message!!),
+ ErrorMessage(
+ errorCode.message(e.message!!),
errorCode.value,
- debugMsg)
+ debugMsg
+ )
return ResponseEntity(errorMessage, HttpStatus.resolve(errorCode.httpCode)!!)
}
}
@JsonTypeName("errorMessage")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
class ErrorMessage(var message: String?, var code: Int?, var debugMessage: String?) : Serializable {
+
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
var timestamp = Date()
-}
\ No newline at end of file
+}
@RunWith(SpringRunner::class)
@WebFluxTest
-@ContextConfiguration(classes = [BluePrintCoreConfiguration::class,
- BluePrintCatalogService::class, SecurityProperties::class])
+@ContextConfiguration(
+ classes = [BluePrintCoreConfiguration::class,
+ BluePrintCatalogService::class, SecurityProperties::class]
+)
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
@TestPropertySource(locations = ["classpath:application-test.properties"])
class ResourceConfigSnapshotControllerTest {
runBlocking {
webTestClient
- .post()
- .uri("/api/v1/configs/$resourceType/$resourceId/running")
- .body(BodyInserters.fromObject(snapshotData))
- .exchange()
- .expectStatus().is2xxSuccessful
- .expectBody()
- .jsonPath("$.createdDate")
- .value<String> { println(it) }
+ .post()
+ .uri("/api/v1/configs/$resourceType/$resourceId/running")
+ .body(BodyInserters.fromObject(snapshotData))
+ .exchange()
+ .expectStatus().is2xxSuccessful
+ .expectBody()
+ .jsonPath("$.createdDate")
+ .value<String> { println(it) }
webTestClient
- .post()
- .uri("/api/v1/configs/$resourceType/$resourceId/running")
- .body(BodyInserters.fromObject(snapshotData))
- .exchange()
- .expectStatus().is2xxSuccessful
- .expectBody()
- .jsonPath("$.createdDate")
- .value<String> { println(it)}
+ .post()
+ .uri("/api/v1/configs/$resourceType/$resourceId/running")
+ .body(BodyInserters.fromObject(snapshotData))
+ .exchange()
+ .expectStatus().is2xxSuccessful
+ .expectBody()
+ .jsonPath("$.createdDate")
+ .value<String> { println(it) }
}
}
fun `get returns requested JSON content-type`() {
runBlocking {
post(resourceType, "22", "RUNNING")
- get("json", resourceType,"22", "RUNNING")
+ get("json", resourceType, "22", "RUNNING")
}
}
val arguments = "resourceId=MISSING&resourceType=PNF&status=TOTALLY_WRONG"
webTestClient.get().uri("/api/v1/configs?$arguments")
- .exchange()
- .expectStatus().isBadRequest
+ .exchange()
+ .expectStatus().isBadRequest
}
}
}
}
- private fun post( resourceType: String, resourceId: String, status: String) {
+ private fun post(resourceType: String, resourceId: String, status: String) {
webTestClient
.post()
.uri("/api/v1/configs/$resourceType/$resourceId/$status")
.expectBody()
}
- private fun get(expectedType : String, resourceType: String, resourceId: String, status: String) {
+ private fun get(expectedType: String, resourceType: String, resourceId: String, status: String) {
var requestArguments = "resourceId=$resourceId&resourceType=$resourceType&status=$status"
if (expectedType.isNotEmpty()) {
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
import org.onap.ccsdk.cds.controllerblueprints.core.emptyTONull
import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp
-import org.onap.ccsdk.cds.controllerblueprints.management.api.*
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintBootstrapInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintDownloadInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementOutput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintRemoveInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction
+import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk
+import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction
+import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction
import org.slf4j.LoggerFactory
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.stereotype.Service
-//TODO("Convert to coroutines handler")
+// TODO("Convert to coroutines handler")
@Service
-open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: BluePrintModelHandler)
- : BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() {
+open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: BluePrintModelHandler) :
+ BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() {
private val log = LoggerFactory.getLogger(BluePrintManagementGRPCHandler::class.java)
@PreAuthorize("hasRole('USER')")
- override fun uploadBlueprint(request: BluePrintUploadInput, responseObserver:
- StreamObserver<BluePrintManagementOutput>) {
+ override fun uploadBlueprint(
+ request: BluePrintUploadInput,
+ responseObserver: StreamObserver<BluePrintManagementOutput>
+ ) {
runBlocking {
- //TODO("catch if request id is missing")
+ // TODO("catch if request id is missing")
log.info("request(${request.commonHeader.requestId})")
try {
/** Get the file byte array */
val byteArray = request.fileChunk.chunk.toByteArray()
/** Get the Upload Action */
val uploadAction = request.actionIdentifiers?.actionName.emptyTONull()
- ?: UploadAction.DRAFT.toString()
+ ?: UploadAction.DRAFT.toString()
when (uploadAction) {
UploadAction.DRAFT.toString() -> {
responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString()))
}
UploadAction.VALIDATE.toString() -> {
- //TODO("Not Implemented")
- responseObserver.onNext(failStatus(request.commonHeader,
+ // TODO("Not Implemented")
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
"Upload action($uploadAction) not implemented",
- BluePrintProcessorException("Not Implemented")))
+ BluePrintProcessorException("Not Implemented")
+ )
+ )
}
UploadAction.ENRICH.toString() -> {
val enrichedByteArray = bluePrintModelHandler.enrichBlueprintFileSource(byteArray)
responseObserver.onNext(outputWithFileBytes(request.commonHeader, enrichedByteArray))
}
else -> {
- responseObserver.onNext(failStatus(request.commonHeader,
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
"Upload action($uploadAction) not implemented",
- BluePrintProcessorException("Not implemented")))
+ BluePrintProcessorException("Not implemented")
+ )
+ )
}
}
} catch (e: Exception) {
- responseObserver.onNext(failStatus(request.commonHeader,
- "request(${request.commonHeader.requestId}): Failed to upload CBA", e))
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
+ "request(${request.commonHeader.requestId}): Failed to upload CBA", e
+ )
+ )
} finally {
responseObserver.onCompleted()
}
}
@PreAuthorize("hasRole('USER')")
- override fun downloadBlueprint(request: BluePrintDownloadInput,
- responseObserver: StreamObserver<BluePrintManagementOutput>) {
+ override fun downloadBlueprint(
+ request: BluePrintDownloadInput,
+ responseObserver: StreamObserver<BluePrintManagementOutput>
+ ) {
runBlocking {
val blueprintName = request.actionIdentifiers.blueprintName
val blueprintVersion = request.actionIdentifiers.blueprintVersion
/** Get the Search Action */
val searchAction = request.actionIdentifiers?.actionName.emptyTONull()
- ?: DownloadAction.SEARCH.toString()
+ ?: DownloadAction.SEARCH.toString()
log.info("request(${request.commonHeader.requestId}): Received download $blueprint")
try {
responseObserver.onNext(outputWithFileBytes(request.commonHeader, downloadByteArray))
}
else -> {
- responseObserver.onNext(failStatus(request.commonHeader,
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
"Search action($searchAction) not implemented",
- BluePrintProcessorException("Not implemented")))
+ BluePrintProcessorException("Not implemented")
+ )
+ )
}
}
} catch (e: Exception) {
- responseObserver.onNext(failStatus(request.commonHeader,
- "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e))
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
+ "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e
+ )
+ )
} finally {
responseObserver.onCompleted()
}
}
@PreAuthorize("hasRole('USER')")
- override fun removeBlueprint(request: BluePrintRemoveInput, responseObserver:
- StreamObserver<BluePrintManagementOutput>) {
+ override fun removeBlueprint(
+ request: BluePrintRemoveInput,
+ responseObserver:
+ StreamObserver<BluePrintManagementOutput>
+ ) {
runBlocking {
val blueprintName = request.actionIdentifiers.blueprintName
/** Get the Remove Action */
val removeAction = request.actionIdentifiers?.actionName.emptyTONull()
- ?: RemoveAction.DEFAULT.toString()
+ ?: RemoveAction.DEFAULT.toString()
try {
when (removeAction) {
responseObserver.onNext(successStatus(request.commonHeader))
}
else -> {
- responseObserver.onNext(failStatus(request.commonHeader,
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
"Remove action($removeAction) not implemented",
- BluePrintProcessorException("Not implemented")))
+ BluePrintProcessorException("Not implemented")
+ )
+ )
}
}
} catch (e: Exception) {
- responseObserver.onNext(failStatus(request.commonHeader,
- "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e))
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
+ "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e
+ )
+ )
} finally {
responseObserver.onCompleted()
}
}
}
- override fun bootstrapBlueprint(request: BluePrintBootstrapInput,
- responseObserver: StreamObserver<BluePrintManagementOutput>) {
+ override fun bootstrapBlueprint(
+ request: BluePrintBootstrapInput,
+ responseObserver: StreamObserver<BluePrintManagementOutput>
+ ) {
runBlocking {
try {
log.info("request(${request.commonHeader.requestId}): Received bootstrap request")
/** Perform bootstrap of Model Types, Resource Definitions and CBA */
bluePrintModelHandler.bootstrapBlueprint(bootstrapRequest)
responseObserver.onNext(successStatus(request.commonHeader))
-
} catch (e: Exception) {
- responseObserver.onNext(failStatus(request.commonHeader,
- "request(${request.commonHeader.requestId}): Failed to bootstrap", e))
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
+ "request(${request.commonHeader.requestId}): Failed to bootstrap", e
+ )
+ )
} finally {
responseObserver.onCompleted()
}
}
private fun outputWithFileBytes(header: CommonHeader, byteArray: ByteArray): BluePrintManagementOutput =
- BluePrintManagementOutput.newBuilder()
- .setCommonHeader(header)
- .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray)))
- .setStatus(Status.newBuilder()
- .setTimestamp(currentTimestamp())
- .setMessage(BluePrintConstants.STATUS_SUCCESS)
- .setCode(200)
- .build())
+ BluePrintManagementOutput.newBuilder()
+ .setCommonHeader(header)
+ .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray)))
+ .setStatus(
+ Status.newBuilder()
+ .setTimestamp(currentTimestamp())
+ .setMessage(BluePrintConstants.STATUS_SUCCESS)
+ .setCode(200)
.build()
+ )
+ .build()
private fun successStatus(header: CommonHeader, propertyContent: String? = null): BluePrintManagementOutput {
// Populate Response Payload
JsonFormat.parser().merge(propertyContent, propertiesBuilder)
}
return BluePrintManagementOutput.newBuilder()
- .setCommonHeader(header)
- .setProperties(propertiesBuilder.build())
- .setStatus(Status.newBuilder()
- .setTimestamp(currentTimestamp())
- .setMessage(BluePrintConstants.STATUS_SUCCESS)
- .setCode(200)
- .build())
- .build()
+ .setCommonHeader(header)
+ .setProperties(propertiesBuilder.build())
+ .setStatus(
+ Status.newBuilder()
+ .setTimestamp(currentTimestamp())
+ .setMessage(BluePrintConstants.STATUS_SUCCESS)
+ .setCode(200)
+ .build()
+ )
+ .build()
}
private fun failStatus(header: CommonHeader, message: String, e: Exception): BluePrintManagementOutput {
log.error(message, e)
return BluePrintManagementOutput.newBuilder()
- .setCommonHeader(header)
- .setStatus(Status.newBuilder()
- .setTimestamp(currentTimestamp())
- .setMessage(BluePrintConstants.STATUS_FAILURE)
- .setErrorMessage(message)
- .setCode(500)
- .build())
- .build()
-// return io.grpc.Status.INTERNAL
-// .withDescription(message)
-// .withCause(e)
-// .asException()
+ .setCommonHeader(header)
+ .setStatus(
+ Status.newBuilder()
+ .setTimestamp(currentTimestamp())
+ .setMessage(BluePrintConstants.STATUS_FAILURE)
+ .setErrorMessage(message)
+ .setCode(500)
+ .build()
+ )
+ .build()
+ // return io.grpc.Status.INTERNAL
+ // .withDescription(message)
+ // .withCause(e)
+ // .asException()
}
}
import org.springframework.http.ResponseEntity
import org.springframework.http.codec.multipart.FilePart
import org.springframework.security.access.prepost.PreAuthorize
-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.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestParam
+import org.springframework.web.bind.annotation.RequestPart
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
/**
@RequestMapping("/api/v1/blueprint-model")
open class BlueprintModelController(private val bluePrintModelHandler: BluePrintModelHandler) {
- @PostMapping(path = arrayOf("/bootstrap"), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE),
- consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE))
+ @PostMapping(
+ path = arrayOf("/bootstrap"), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE),
+ consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE)
+ )
@ResponseBody
@Throws(BluePrintException::class)
@PreAuthorize("hasRole('USER')")
@GetMapping("/paged", produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
@PreAuthorize("hasRole('USER')")
- fun allBlueprintModel(@RequestParam(defaultValue = "20") limit: Int,
- @RequestParam(defaultValue = "0") offset: Int,
- @RequestParam(defaultValue = "DATE") sort: BlueprintSortByOption): Page<BlueprintModelSearch> {
+ fun allBlueprintModel(
+ @RequestParam(defaultValue = "20") limit: Int,
+ @RequestParam(defaultValue = "0") offset: Int,
+ @RequestParam(defaultValue = "DATE") sort: BlueprintSortByOption
+ ): Page<BlueprintModelSearch> {
val pageRequest = PageRequest.of(offset, limit, Sort.Direction.ASC, sort.columnName)
return this.bluePrintModelHandler.allBlueprintModel(pageRequest)
}
return this.bluePrintModelHandler.searchBluePrintModelsByKeyWord(keyWord)
}
-
@GetMapping("/paged/meta-data/{keyword}", produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
@PreAuthorize("hasRole('USER')")
- fun allBlueprintModelMetaDataPaged(@NotNull @PathVariable(value = "keyword") keyWord: String,
- @RequestParam(defaultValue = "20") limit: Int,
- @RequestParam(defaultValue = "0") offset: Int,
- @RequestParam(defaultValue = "DATE") sort: BlueprintSortByOption
+ fun allBlueprintModelMetaDataPaged(
+ @NotNull @PathVariable(value = "keyword") keyWord: String,
+ @RequestParam(defaultValue = "20") limit: Int,
+ @RequestParam(defaultValue = "0") offset: Int,
+ @RequestParam(defaultValue = "DATE") sort: BlueprintSortByOption
): Page<BlueprintModelSearch> {
val pageRequest = PageRequest.of(offset, limit, Sort.Direction.ASC, sort.columnName)
return this.bluePrintModelHandler.searchBluePrintModelsByKeyWordPaged(keyWord, pageRequest)
-
}
@DeleteMapping("/{id}")
@ResponseBody
@Throws(BluePrintException::class)
@PreAuthorize("hasRole('USER')")
- fun getBlueprintByNameAndVersion(@PathVariable(value = "name") name: String,
- @PathVariable(value = "version") version: String)
- : Mono<BlueprintModelSearch> = monoMdc {
+ fun getBlueprintByNameAndVersion(
+ @PathVariable(value = "name") name: String,
+ @PathVariable(value = "version") version: String
+ ):
+ Mono<BlueprintModelSearch> = monoMdc {
bluePrintModelHandler.getBlueprintModelSearchByNameAndVersion(name, version)
}
@ResponseBody
@Throws(BluePrintException::class)
@PreAuthorize("hasRole('USER')")
- fun downloadBlueprintByNameAndVersion(@PathVariable(value = "name") name: String,
- @PathVariable(value = "version") version: String)
- : Mono<ResponseEntity<Resource>> = monoMdc {
+ fun downloadBlueprintByNameAndVersion(
+ @PathVariable(value = "name") name: String,
+ @PathVariable(value = "version") version: String
+ ):
+ Mono<ResponseEntity<Resource>> = monoMdc {
bluePrintModelHandler.downloadBlueprintModelFileByNameAndVersion(name, version)
}
bluePrintModelHandler.downloadBlueprintModelFile(id)
}
- @PostMapping("/enrich", produces = [MediaType.APPLICATION_JSON_VALUE], consumes = [MediaType
- .MULTIPART_FORM_DATA_VALUE])
+ @PostMapping(
+ "/enrich", produces = [MediaType.APPLICATION_JSON_VALUE], consumes = [MediaType
+ .MULTIPART_FORM_DATA_VALUE]
+ )
@ResponseBody
@Throws(BluePrintException::class)
@PreAuthorize("hasRole('USER')")
}
@DeleteMapping("/name/{name}/version/{version}")
- @ApiOperation(value = "Delete a CBA",
- notes = "Delete the CBA package identified by its name and version.",
- produces = MediaType.APPLICATION_JSON_VALUE)
+ @ApiOperation(
+ value = "Delete a CBA",
+ notes = "Delete the CBA package identified by its name and version.",
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@PreAuthorize("hasRole('USER')")
- fun deleteBlueprint(@ApiParam(value = "Name of the CBA.", required = true)
- @PathVariable(value = "name") name: String,
- @ApiParam(value = "Version of the CBA.", required = true)
- @PathVariable(value = "version") version: String) = monoMdc {
+ fun deleteBlueprint(
+ @ApiParam(value = "Name of the CBA.", required = true)
+ @PathVariable(value = "name") name: String,
+ @ApiParam(value = "Version of the CBA.", required = true)
+ @PathVariable(value = "version") version: String
+ ) = monoMdc {
bluePrintModelHandler.deleteBlueprintModel(name, version)
}
}
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictionary
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import java.io.Serializable
-import java.util.*
-
+import java.util.Date
class BootstrapRequest {
var loadModelType: Boolean = false
* @version 1.0
*/
class AutoMapResponse {
+
var resourceAssignments: List<ResourceAssignment>? = null
var dataDictionaries: List<ResourceDictionary>? = null
}
-
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonTypeName("errorMessage")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
class ErrorMessage(var message: String?, var code: Int?, var debugMessage: String?) : Serializable {
+
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
var timestamp = Date()
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api
import kotlinx.coroutines.runBlocking
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ModelTypeHandler
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.springframework.http.MediaType
-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.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(value = arrayOf("/api/v1/model-type"))
fun deleteModelTypeByName(@PathVariable(value = "name") name: String) = runBlocking {
modelTypeHandler.deleteByModelName(name)
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceSourceMapping
import org.springframework.http.MediaType
-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.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(value = ["/api/v1/dictionary"])
@ResponseBody
fun searchResourceDictionaryByTags(@PathVariable(value = "tags") tags: String): List<ResourceDictionary> = runBlocking {
resourceDictionaryHandler.searchResourceDictionaryByTags(tags)
-
}
@GetMapping(path = ["/source-mapping"], produces = [MediaType.APPLICATION_JSON_VALUE])
fun getResourceSourceMapping(): ResourceSourceMapping = runBlocking {
resourceDictionaryHandler.getResourceSourceMapping()
}
-
}
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
-
import javax.persistence.AttributeConverter
import javax.persistence.Converter
override fun convertToEntityAttribute(dbData: String): JsonNode {
return JacksonUtils.jsonNode(dbData)
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
-
import javax.persistence.AttributeConverter
import javax.persistence.Converter
*/
@Converter
class JpaResourceDefinitionConverter : AttributeConverter<ResourceDefinition, String> {
+
override fun convertToDatabaseColumn(resourceDefinition: ResourceDefinition): String {
return JacksonUtils.getJson(resourceDefinition)
}
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Convert
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
/**
* Provide ModelType Entity
companion object {
private const val serialVersionUID = 1L
}
-}
\ No newline at end of file
+}
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Convert
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
/**
* Provide ResourceDictionary Entity
companion object {
private const val serialVersionUID = 1L
}
-
-
}
import org.springframework.stereotype.Service
@Service
-open class BluePrintArtifactDefinitionEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService)
- : BluePrintArtifactDefinitionEnhancer {
+open class BluePrintArtifactDefinitionEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService
+) :
+ BluePrintArtifactDefinitionEnhancer {
companion object {
const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource"
}
-
private val log = logger(BluePrintArtifactDefinitionEnhancerImpl::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
-
override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactDefinition: ArtifactDefinition) {
log.info("enhancing ArtifactDefinition($name)")
this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
val artifactTypeName = artifactDefinition.type
- ?: throw BluePrintException("artifact type is missing for ArtifactDefinition($name)")
+ ?: throw BluePrintException("artifact type is missing for ArtifactDefinition($name)")
// Populate Artifact Type
BluePrintEnhancerUtils.populateArtifactType(bluePrintContext, bluePrintRepoService, artifactTypeName)
if (!alreadyEnhanced) {
val resourceAssignments: MutableList<ResourceAssignment> = JacksonUtils.getListFromFile(artifactFilePath, ResourceAssignment::class.java)
as? MutableList<ResourceAssignment>
- ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($artifactFilePath)")
+ ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($artifactFilePath)")
// Call Resource Assignment Enhancer
resourceAssignmentEnhancerService.enhanceBluePrint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments)
bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive())
}
}
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
-class BluePrintAttributeDefinitionEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintAttributeDefinitionEnhancer {
+class BluePrintAttributeDefinitionEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintAttributeDefinitionEnhancer {
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
val propertyType = attributeDefinition.type
if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) {
-
} else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) {
val entrySchema = attributeDefinition.entrySchema
- ?: throw BluePrintException("Entry Schema is missing for collection property($name)")
+ ?: throw BluePrintException("Entry Schema is missing for collection property($name)")
if (!BluePrintTypes.validPrimitiveTypes().contains(entrySchema.type)) {
BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type)
BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType)
}
}
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.UUID
@Service
-open class BluePrintEnhancerServiceImpl(private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- private val resourceDefinitionEnhancerService: ResourceDefinitionEnhancerService) : BluePrintEnhancerService {
+open class BluePrintEnhancerServiceImpl(
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ private val resourceDefinitionEnhancerService: ResourceDefinitionEnhancerService
+) : BluePrintEnhancerService {
private val log = logger(BluePrintEnhancerServiceImpl::class)
log.info("Enhancing blueprint($basePath)")
val blueprintRuntimeService = BluePrintMetadataUtils
- .getBaseEnhancementBluePrintRuntime(UUID.randomUUID().toString(), basePath)
+ .getBaseEnhancementBluePrintRuntime(UUID.randomUUID().toString(), basePath)
try {
- bluePrintTypeEnhancerService.enhanceServiceTemplate(blueprintRuntimeService, "service_template",
- blueprintRuntimeService.bluePrintContext().serviceTemplate)
+ bluePrintTypeEnhancerService.enhanceServiceTemplate(
+ blueprintRuntimeService, "service_template",
+ blueprintRuntimeService.bluePrintContext().serviceTemplate
+ )
log.info("##### Enhancing blueprint Resource Definitions")
- val resourceDefinitions = resourceDefinitionEnhancerService.enhance(bluePrintTypeEnhancerService,
- blueprintRuntimeService)
+ val resourceDefinitions = resourceDefinitionEnhancerService.enhance(
+ bluePrintTypeEnhancerService,
+ blueprintRuntimeService
+ )
// Write the Enhanced Blueprint Definitions
BluePrintFileUtils.writeEnhancedBluePrint(blueprintRuntimeService.bluePrintContext())
if (blueprintRuntimeService.getBluePrintError().errors.isNotEmpty()) {
throw BluePrintException(blueprintRuntimeService.getBluePrintError().errors.toString())
}
-
} catch (e: Exception) {
throw e
}
return blueprintRuntimeService.bluePrintContext()
}
-
}
-
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintNodeTemplateEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintNodeTemplateEnhancer {
+open class BluePrintNodeTemplateEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintNodeTemplateEnhancer {
- private val log= logger(BluePrintNodeTemplateEnhancerImpl::class)
+ private val log = logger(BluePrintNodeTemplateEnhancerImpl::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
-
override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) {
log.info("***** Enhancing NodeTemplate($name)")
this.bluePrintRuntimeService = bluePrintRuntimeService
this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
-
val nodeTypeName = nodeTemplate.type
// Get NodeType from Repo and Update Service Template
val nodeType = BluePrintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, nodeTypeName)
// Enrich NodeType
bluePrintTypeEnhancerService.enhanceNodeType(bluePrintRuntimeService, nodeTypeName, nodeType)
- //Enrich Node Template Artifacts
+ // Enrich Node Template Artifacts
enhanceNodeTemplateArtifactDefinition(name, nodeTemplate)
}
bluePrintTypeEnhancerService.enhanceArtifactDefinition(bluePrintRuntimeService, artifactDefinitionName, artifactDefinition)
}
}
-
-}
\ No newline at end of file
+}
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintNodeTypeEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService) : BluePrintNodeTypeEnhancer {
+open class BluePrintNodeTypeEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) : BluePrintNodeTypeEnhancer {
- private val log= logger(BluePrintNodeTypeEnhancerImpl::class)
+ private val log = logger(BluePrintNodeTypeEnhancerImpl::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
-
override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeType: NodeType) {
this.bluePrintRuntimeService = bluePrintRuntimeService
this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
-
val derivedFrom = nodeType.derivedFrom
if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) {
// NodeType Property Definitions
enrichNodeTypeProperties(name, nodeType)
- //NodeType Requirement
+ // NodeType Requirement
enrichNodeTypeRequirements(name, nodeType)
- //NodeType Capability
+ // NodeType Capability
enrichNodeTypeCapabilityProperties(name, nodeType)
- //NodeType Interface
+ // NodeType Interface
enrichNodeTypeInterfaces(name, nodeType)
-
}
open fun enrichNodeTypeAttributes(nodeTypeName: String, nodeType: NodeType) {
// Populate Requirement Node
requirementDefinition.node?.let { requirementNodeTypeName ->
// Get Requirement NodeType from Repo and Update Service Template
- val requirementNodeType = BluePrintEnhancerUtils.populateNodeType(bluePrintContext,
- bluePrintRepoService, requirementNodeTypeName)
+ val requirementNodeType = BluePrintEnhancerUtils.populateNodeType(
+ bluePrintContext,
+ bluePrintRepoService, requirementNodeTypeName
+ )
// Enhance Node Type
enhance(bluePrintRuntimeService, requirementNodeTypeName, requirementNodeType)
// Enhance Relationship Type
val relationShipTypeName = requirementDefinition.relationship
- ?: throw BluePrintException("couldn't get relationship name for the NodeType($nodeTypeName) " +
- "Requirement($requirementName)")
+ ?: throw BluePrintException(
+ "couldn't get relationship name for the NodeType($nodeTypeName) " +
+ "Requirement($requirementName)"
+ )
enrichRelationShipType(relationShipTypeName)
}
}
// Populate Node type Interface Operation
log.debug("Enriching NodeType({}) Interface({})", nodeTypeName, interfaceName)
populateNodeTypeInterfaceOperation(nodeTypeName, interfaceName, interfaceObj)
-
}
}
}
}
- open fun enrichNodeTypeInterfaceOperationOutputs(nodeTypeName: String, operationName: String,
- operation: OperationDefinition) {
+ open fun enrichNodeTypeInterfaceOperationOutputs(
+ nodeTypeName: String,
+ operationName: String,
+ operation: OperationDefinition
+ ) {
operation.outputs?.let { inputs ->
bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs)
}
open fun enrichRelationShipType(relationshipName: String) {
BluePrintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, relationshipName)
}
-
-}
\ No newline at end of file
+}
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-class BluePrintPolicyTypeEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintPolicyTypeEnhancer {
+class BluePrintPolicyTypeEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintPolicyTypeEnhancer {
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
-
override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: PolicyType) {
- this.bluePrintRuntimeService = bluePrintRuntimeService
+ this.bluePrintRuntimeService = bluePrintRuntimeService
// TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
-}
\ No newline at end of file
+}
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintPropertyDefinitionEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintPropertyDefinitionEnhancer {
+open class BluePrintPropertyDefinitionEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintPropertyDefinitionEnhancer {
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
val propertyType = propertyDefinition.type
- if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)
- || BluePrintTypes.validComplexTypes().contains(propertyType)) {
+ if (BluePrintTypes.validPrimitiveTypes().contains(propertyType) ||
+ BluePrintTypes.validComplexTypes().contains(propertyType)
+ ) {
// Do Nothing,
} else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) {
val entrySchema = propertyDefinition.entrySchema
- ?: throw BluePrintException("Entry Schema is missing for collection property($name)")
+ ?: throw BluePrintException("Entry Schema is missing for collection property($name)")
if (!BluePrintTypes.validPrimitiveTypes().contains(entrySchema.type)) {
BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type)
BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType)
}
}
-
-}
\ No newline at end of file
+}
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintServiceTemplateEnhancer {
- private val log = logger(BluePrintServiceTemplateEnhancerImpl::class)
+open class BluePrintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService) :
+ BluePrintServiceTemplateEnhancer {
+ private val log = logger(BluePrintServiceTemplateEnhancerImpl::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
bluePrintContext.serviceTemplate.policyTypes = mutableMapOf()
bluePrintContext.serviceTemplate.relationshipTypes = mutableMapOf()
log.info("reinitialized all type definitions")
-
}
open fun enhanceTopologyTemplate() {
bluePrintTypeEnhancerService.enhanceTopologyTemplate(bluePrintRuntimeService, "topology_template", topologyTemplate)
}
}
-}
\ No newline at end of file
+}
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintTopologyTemplateEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService) : BluePrintTopologyTemplateEnhancer {
+open class BluePrintTopologyTemplateEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintTopologyTemplateEnhancer {
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
bluePrintTypeEnhancerService.enhanceWorkflow(bluePrintRuntimeService, workflowName, workflow)
}
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer
-import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.*
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPolicyTypeEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowEnhancer
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Service
override fun getAttributeDefinitionEnhancers(): List<BluePrintAttributeDefinitionEnhancer> {
return context.getBeansOfType(BluePrintAttributeDefinitionEnhancer::class.java).map { it.value }
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintWorkflowEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService)
- : BluePrintWorkflowEnhancer {
- private val log= logger(BluePrintWorkflowEnhancerImpl::class)
+open class BluePrintWorkflowEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService
+) :
+ BluePrintWorkflowEnhancer {
+
+ private val log = logger(BluePrintWorkflowEnhancerImpl::class)
companion object {
const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource"
// Enrich Only for Resource Assignment and Dynamic Input Properties if any
enhanceStepTargets(name, workflow)
-
-
}
open fun enhanceWorkflowInputs(name: String, workflow: Workflow) {
enhanceStepTargets(name, workflow, firstNodeTemplateName, true)
}
else -> {
- throw BluePrintProcessorException("couldn't execute workflow($name) step mapped " +
- "to node template($firstNodeTemplateName) derived from($derivedFrom)")
+ throw BluePrintProcessorException(
+ "couldn't execute workflow($name) step mapped " +
+ "to node template($firstNodeTemplateName) derived from($derivedFrom)"
+ )
}
}
-
}
private fun enhanceStepTargets(name: String, workflow: Workflow, nodeTemplateName: String, isDG: Boolean) {
log.info("identified workflow($name) targets($componentNodeTemplateName)")
val resourceAssignmentArtifacts = bluePrintContext.nodeTemplateByName(componentNodeTemplateName)
- .artifacts?.filter {
+ .artifacts?.filter {
it.value.type == ARTIFACT_TYPE_MAPPING_SOURCE
}?.map {
- log.info("resource assignment artifacts(${it.key}) for NodeType(${componentNodeTemplateName})")
+ log.info("resource assignment artifacts(${it.key}) for NodeType($componentNodeTemplateName)")
it.value.file
}
resourceAssignmentArtifacts
val filePath = "${bluePrintContext.rootPath}/$fileName"
- log.info("enriching artifacts file(${filePath}")
+ log.info("enriching artifacts file($filePath")
val resourceAssignmentProperties: MutableMap<String, PropertyDefinition> = hashMapOf()
val resourceAssignments: MutableList<ResourceAssignment> = JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java)
as? MutableList<ResourceAssignment>
- ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)")
+ ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)")
val alreadyEnhancedKey = "enhanced-$fileName"
val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey)
// Overwrite WorkFlow DataType
bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dynamicDataType)
-
} else {
log.info("dynamic dataType($dataTypeName) already present for workflow($workflowName).")
}
dynamicDataType.properties?.put(propertyName, propertyDefinition)
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.factory.ResourceSourceMappingFactory
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
interface ResourceAssignmentEnhancerService {
@Throws(BluePrintException::class)
- fun enhanceBluePrint(bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- bluePrintRuntimeService: BluePrintRuntimeService<*>,
- resourceAssignments: List<ResourceAssignment>)
+ fun enhanceBluePrint(
+ bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ resourceAssignments: List<ResourceAssignment>
+ )
}
/**
*/
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionRepoService: ResourceDefinitionRepoService)
- : ResourceAssignmentEnhancerService {
- private val log= logger(ResourceAssignmentEnhancerServiceImpl::class)
+open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionRepoService: ResourceDefinitionRepoService) :
+ ResourceAssignmentEnhancerService {
+
+ private val log = logger(ResourceAssignmentEnhancerServiceImpl::class)
/**
* Get the defined source instance from the ResourceAssignment,
* then get the NodeType of the Sources assigned
*/
- override fun enhanceBluePrint(bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- bluePrintRuntimeService: BluePrintRuntimeService<*>,
- resourceAssignments: List<ResourceAssignment>) {
+ override fun enhanceBluePrint(
+ bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ resourceAssignments: List<ResourceAssignment>
+ ) {
val uniqueSourceNodeTypeNames = hashSetOf<String>()
// TODO("Candidate for Optimisation")
if (checkResourceDefinitionNeeded(resourceAssignment)) {
- bluePrintTypeEnhancerService.enhancePropertyDefinition(bluePrintRuntimeService, resourceAssignment.name,
- resourceAssignment.property!!);
+ bluePrintTypeEnhancerService.enhancePropertyDefinition(
+ bluePrintRuntimeService, resourceAssignment.name,
+ resourceAssignment.property!!
+ )
// Get the Resource Definition from Repo
val resourceDefinition: ResourceDefinition = getResourceDefinition(dictionaryName)
val sourceNodeTemplate = resourceDefinition.sources[dictionarySource]
- ?: throw BluePrintException("failed to get assigned dictionarySource($dictionarySource) from resourceDefinition($dictionaryName)")
+ ?: throw BluePrintException("failed to get assigned dictionarySource($dictionarySource) from resourceDefinition($dictionaryName)")
// Enrich as NodeTemplate
bluePrintTypeEnhancerService.enhanceNodeTemplate(bluePrintRuntimeService, dictionarySource, sourceNodeTemplate)
val nodeType = resourceDefinitionRepoService.getNodeType(nodeTypeName)
bluePrintTypeEnhancerService.enhanceNodeType(bluePrintRuntimeService, nodeTypeName, nodeType)
}
-
}
private fun checkResourceDefinitionNeeded(resourceAssignment: ResourceAssignment): Boolean {
- return !((resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_INPUT)
- || resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_DEFAULT))
- && BluePrintTypes.validPrimitiveOrCollectionPrimitive(resourceAssignment.property!!))
+ return !((resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_INPUT) ||
+ resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_DEFAULT)) &&
+ BluePrintTypes.validPrimitiveOrCollectionPrimitive(resourceAssignment.property!!))
}
private fun getResourceDefinition(name: String): ResourceDefinition {
return resourceDefinitionRepoService.getResourceDefinition(name)
}
-}
\ No newline at end of file
+}
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService
import org.onap.ccsdk.cds.controllerblueprints.core.logger
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils
import org.springframework.stereotype.Service
interface ResourceDefinitionEnhancerService {
@Throws(BluePrintException::class)
- fun enhance(bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- bluePrintRuntimeService: BluePrintRuntimeService<*>): List<ResourceDefinition>
+ fun enhance(
+ bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>
+ ): List<ResourceDefinition>
}
@Service
class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoService: ResourceDefinitionRepoService) :
- ResourceDefinitionEnhancerService {
+ ResourceDefinitionEnhancerService {
private val log = logger(ResourceDefinitionEnhancerService::class)
// 2. Get all the Unique Resource assignments from all mapping files
// 3. Collect the Resource Definition for Resource Assignment names from database.
// 4. Create the Resource Definition under blueprint base path.
- override fun enhance(bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- bluePrintRuntimeService: BluePrintRuntimeService<*>): List<ResourceDefinition> {
+ override fun enhance(
+ bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>
+ ): List<ResourceDefinition> {
var resourceDefinitions: List<ResourceDefinition> = mutableListOf()
}?.mapNotNull { artifactDefinitionMap ->
artifactDefinitionMap.value.file
}
-
}?.flatten()?.distinct()
}
val distinctResourceAssignments = resourceAssignments.distinctBy { it.name }
generateResourceDictionary(blueprintBasePath, distinctResourceAssignments)
- //log.info("distinct Resource assignment ($distinctResourceAssignments)")
+ // log.info("distinct Resource assignment ($distinctResourceAssignments)")
}
-
// Read the Resource Definitions from the Database and write to type file.
- private fun generateResourceDictionary(blueprintBasePath: String, resourceAssignments: List<ResourceAssignment>)
- : List<ResourceDefinition> {
+ private fun generateResourceDictionary(blueprintBasePath: String, resourceAssignments: List<ResourceAssignment>):
+ List<ResourceDefinition> {
val resourceKeys = resourceAssignments.mapNotNull { it.dictionaryName }.distinct().sorted()
log.info("distinct resource keys ($resourceKeys)")
- //TODO("Optimise DB single Query to multiple Query")
+ // TODO("Optimise DB single Query to multiple Query")
return resourceKeys.map { resourceKey ->
getResourceDefinition(resourceKey)
}
}
- private fun enrichResourceDefinitionSources(bluePrintContext: BluePrintContext,
- resourceDefinitions: List<ResourceDefinition>) {
+ private fun enrichResourceDefinitionSources(
+ bluePrintContext: BluePrintContext,
+ resourceDefinitions: List<ResourceDefinition>
+ ) {
val sources = resourceDefinitions
- .map { it.sources }
- .map {
- it.values
- .map { nodeTemplate ->
- nodeTemplate.type
- }
- }
- .flatten().distinct()
+ .map { it.sources }
+ .map {
+ it.values
+ .map { nodeTemplate ->
+ nodeTemplate.type
+ }
+ }
+ .flatten().distinct()
log.info("Enriching Resource Definition sources Node Template: $sources")
sources.forEach {
BluePrintEnhancerUtils.populateNodeType(bluePrintContext, resourceDefinitionRepoService, it)
private fun getResourceDefinition(name: String): ResourceDefinition {
return resourceDefinitionRepoService.getResourceDefinition(name)
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.BootstrapRequest
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.BluePrintDatabaseLoadService
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintEnhancerService
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
import org.springframework.core.io.ByteArrayResource
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException
-import java.util.*
-
+import java.util.UUID
/**
* BlueprintModelHandler Purpose: Handler service to handle the request from BlurPrintModelRest
*/
@Service
-open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BluePrintDatabaseLoadService,
- private val blueprintsProcessorCatalogService: BluePrintCatalogService,
- private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val blueprintModelSearchRepository: BlueprintModelSearchRepository,
- private val blueprintModelRepository: BlueprintModelRepository,
- private val blueprintModelContentRepository: BlueprintModelContentRepository,
- private val bluePrintEnhancerService: BluePrintEnhancerService) {
+open class BluePrintModelHandler(
+ private val bluePrintDatabaseLoadService: BluePrintDatabaseLoadService,
+ private val blueprintsProcessorCatalogService: BluePrintCatalogService,
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val blueprintModelSearchRepository: BlueprintModelSearchRepository,
+ private val blueprintModelRepository: BlueprintModelRepository,
+ private val blueprintModelContentRepository: BlueprintModelContentRepository,
+ private val bluePrintEnhancerService: BluePrintEnhancerService
+) {
private val log = logger(BluePrintModelHandler::class)
-
open suspend fun bootstrapBlueprint(bootstrapRequest: BootstrapRequest) {
- log.info("Bootstrap request with type load(${bootstrapRequest.loadModelType}), " +
- "resource dictionary load(${bootstrapRequest.loadResourceDictionary}) and " +
- "cba load(${bootstrapRequest.loadCBA})")
+ log.info(
+ "Bootstrap request with type load(${bootstrapRequest.loadModelType}), " +
+ "resource dictionary load(${bootstrapRequest.loadResourceDictionary}) and " +
+ "cba load(${bootstrapRequest.loadCBA})"
+ )
if (bootstrapRequest.loadModelType) {
bluePrintDatabaseLoadService.initModelTypes()
}
try {
return upload(filePart, false)
} catch (e: IOException) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Save CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Save CBA: ${e.message}", e
+ )
}
}
-
/**
* This is a searchBlueprintModels method
*
@Throws(BluePrintException::class)
open fun getBlueprintModelSearchByNameAndVersion(name: String, version: String): BlueprintModelSearch {
return blueprintModelSearchRepository.findByArtifactNameAndArtifactVersion(name, version)
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version))
-
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version)
+ )
}
/**
* @throws BluePrintException BluePrintException
</Resource> */
@Throws(BluePrintException::class)
- open fun downloadBlueprintModelFileByNameAndVersion(name: String,
- version: String): ResponseEntity<Resource> {
+ open fun downloadBlueprintModelFileByNameAndVersion(
+ name: String,
+ version: String
+ ): ResponseEntity<Resource> {
try {
val archiveByteArray = download(name, version)
val fileName = "${name}_$version.zip"
return prepareResourceEntity(fileName, archiveByteArray)
} catch (e: BluePrintException) {
- throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format("Error while " + "downloading the CBA file: %s", e.message), e)
+ throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format("Error while " + "downloading the CBA file: %s", e.message), e
+ )
}
}
val fileName = "${blueprintModel.artifactName}_${blueprintModel.artifactVersion}.zip"
val file = blueprintModel.blueprintModelContent?.content
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format("Error while downloading the CBA file: couldn't get model content"))
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format("Error while downloading the CBA file: couldn't get model content")
+ )
return prepareResourceEntity(fileName, file)
}
</Resource> */
private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity<Resource> {
return ResponseEntity.ok()
- .contentType(MediaType.parseMediaType("text/plain"))
- .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
- .body(ByteArrayResource(file))
+ .contentType(MediaType.parseMediaType("text/plain"))
+ .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
+ .body(ByteArrayResource(file))
}
/**
@Throws(BluePrintException::class)
open fun getBlueprintModelByNameAndVersion(name: String, version: String): BlueprintModel {
val blueprintModel = blueprintModelRepository
- .findByArtifactNameAndArtifactVersion(name, version)
+ .findByArtifactNameAndArtifactVersion(name, version)
if (blueprintModel != null) {
return blueprintModel
} else {
@Throws(BluePrintException::class)
open fun getBlueprintModelSearch(id: String): BlueprintModelSearch {
return blueprintModelSearchRepository.findById(id)
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id))
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id)
+ )
}
/**
</BlueprintModelSearch> */
open fun searchBluePrintModelsByKeyWord(keyWord: String): List<BlueprintModelSearch> {
return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(
- keyWord, keyWord, keyWord, keyWord, keyWord)
+ keyWord, keyWord, keyWord, keyWord, keyWord
+ )
}
-
/**
* This is a searchBluePrintModelsByKeyWordPagebale method to retrieve specific BlueprintModel in Database
* where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type and pageable
* @return List<BlueprintModelSearch> list of the controller blueprint
</BlueprintModelSearch> */
open fun searchBluePrintModelsByKeyWordPaged(keyWord: String, pageRequest: PageRequest): Page<BlueprintModelSearch> {
- return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(keyWord, keyWord, keyWord, keyWord, keyWord, pageRequest)
+ return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(
+ keyWord,
+ keyWord,
+ keyWord,
+ keyWord,
+ keyWord,
+ pageRequest
+ )
}
/**
val enhancedByteArray = enrichBlueprintFileSource(filePart)
return BluePrintEnhancerUtils.prepareResourceEntity("enhanced-cba.zip", enhancedByteArray)
} catch (e: IOException) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Enriching CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Enriching CBA: ${e.message}", e
+ )
}
}
try {
return upload(filePart, true)
} catch (e: Exception) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Publishing CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Publishing CBA: ${e.message}", e
+ )
}
}
val blueprintId = blueprintsProcessorCatalogService.saveToDatabase(saveId, compressedFile, validate)
return blueprintModelSearchRepository.findById(blueprintId)
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, blueprintId))
-
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, blueprintId)
+ )
} catch (e: IOException) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Upload CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Upload CBA: ${e.message}", e
+ )
} finally {
// Clean blueprint script cache
val cacheKey = BluePrintFileUtils
- .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId))
+ .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId))
BluePrintCompileCache.cleanClassLoader(cacheKey)
deleteNBDir(blueprintArchive)
deleteNBDir(blueprintWorking)
try {
val blueprintModel = getBlueprintModelByNameAndVersion(name, version)
return blueprintModel.blueprintModelContent?.content
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format("Error while downloading the CBA file: couldn't get model content"))
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format("Error while downloading the CBA file: couldn't get model content")
+ )
} catch (e: BluePrintException) {
- throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format("Error while " + "downloading the CBA file: %s", e.message), e)
+ throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format("Error while " + "downloading the CBA file: %s", e.message), e
+ )
}
}
try {
when (fileSource) {
is FilePart -> BluePrintEnhancerUtils
- .copyFilePartToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir)
+ .copyFilePartToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir)
is ByteArray -> BluePrintEnhancerUtils
- .copyByteArrayToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir)
- } // Enhance the Blue Prints
+ .copyByteArrayToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir)
+ } // Enhance the Blue Prints
bluePrintEnhancerService.enhance(blueprintWorkingDir)
return BluePrintEnhancerUtils.compressEnhanceDirAndReturnByteArray(blueprintWorkingDir, blueprintArchive)
-
} catch (e: IOException) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Enriching CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Enriching CBA: ${e.message}", e
+ )
} finally {
BluePrintEnhancerUtils.cleanEnhancer(blueprintArchive, blueprintWorkingDir)
}
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.ModelTypeValidator
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
}
}
-
/**
* This is a searchModelTypes service
*
* @throws BluePrintException BluePrintException
*/
@Throws(BluePrintException::class)
- suspend open fun saveModel(modelType: ModelType): ModelType {
+ open suspend fun saveModel(modelType: ModelType): ModelType {
lateinit var dbModel: ModelType
ModelTypeValidator.validateModelType(modelType)
val dbModelType: ModelType? = modelTypeRepository.findByModelName(modelType.modelName)
return dbModel
}
-
/**
* This is a deleteByModelName service
*
* @param modelName modelName
*/
- suspend open fun deleteByModelName(modelName: String) {
+ open suspend fun deleteByModelName(modelName: String) {
check(modelName.isNotBlank()) { "Model Name Information is missing." }
modelTypeRepository.deleteByModelName(modelName)
-
}
/**
check(derivedFrom.isNotBlank()) { "Model derivedFrom Information is missing." }
return modelTypeRepository.findByDerivedFrom(derivedFrom)
}
-}
\ No newline at end of file
+}
@Service
class ResourceDictionaryHandler(private val resourceDictionaryRepository: ResourceDictionaryRepository) {
-
/**
* This is a getDataDictionaryByName service
*
val resourceDefinition = resourceDictionary.definition
Preconditions.checkNotNull(resourceDefinition, "failed to get resource definition from content")
// Validate the Resource Definitions
- //TODO( Save Validator)
- //validate(resourceDefinition)
+ // TODO( Save Validator)
+ // validate(resourceDefinition)
resourceDictionary.tags = resourceDefinition.tags!!
resourceDefinition.updatedBy = resourceDictionary.updatedBy
}
private fun validateResourceDictionary(resourceDictionary: ResourceDictionary): Boolean {
- checkNotEmpty(resourceDictionary.name){ "DataDictionary Definition name is missing."}
+ checkNotEmpty(resourceDictionary.name) { "DataDictionary Definition name is missing." }
checkNotNull(resourceDictionary.definition) { "DataDictionary Definition Information is missing." }
- checkNotEmpty(resourceDictionary.description){ "DataDictionary Definition Information is missing."}
- checkNotEmpty(resourceDictionary.tags){ "DataDictionary Definition tags is missing."}
- checkNotEmpty(resourceDictionary.updatedBy){ "DataDictionary Definition updatedBy is missing."}
+ checkNotEmpty(resourceDictionary.description) { "DataDictionary Definition Information is missing." }
+ checkNotEmpty(resourceDictionary.tags) { "DataDictionary Definition tags is missing." }
+ checkNotEmpty(resourceDictionary.updatedBy) { "DataDictionary Definition updatedBy is missing." }
return true
}
-}
\ No newline at end of file
+}
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.io.File
-import java.util.*
+import java.util.UUID
@Service
open class BluePrintCatalogLoadService(private val controllerBlueprintsCatalogService: BluePrintCatalogService) {
errorBuilder.appendln("Couldn't load BlueprintModel(${file.name}: ${e.message}")
}
}
-
-}
\ No newline at end of file
+}
import org.springframework.stereotype.Service
@Service
-open class BluePrintDatabaseLoadService(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val modelTypeLoadService: ModelTypeLoadService,
- private val resourceDictionaryLoadService: ResourceDictionaryLoadService,
- private val bluePrintCatalogLoadService: BluePrintCatalogLoadService) {
+open class BluePrintDatabaseLoadService(
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val modelTypeLoadService: ModelTypeLoadService,
+ private val resourceDictionaryLoadService: ResourceDictionaryLoadService,
+ private val bluePrintCatalogLoadService: BluePrintCatalogLoadService
+) {
private val log = LoggerFactory.getLogger(BluePrintDatabaseLoadService::class.java)
bluePrintCatalogLoadService.loadPathsBluePrintModelCatalog(paths)
}
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ModelTypeHandler
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.EntityType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
import org.onap.ccsdk.cds.controllerblueprints.core.readNBText
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
val dataKey = FilenameUtils.getBaseName(file.name)
val definitionContent = file.readNBText()
val definition = JacksonUtils.readValue(definitionContent, classType) as EntityType
- //checkNotNull(definition) { "failed to get data type from file : ${file.name}" }
+ // checkNotNull(definition) { "failed to get data type from file : ${file.name}" }
val modelType = ModelType()
val definitionType: String?
errorBuilder.appendln("Couldn't load ${classType.name}(${file.name}: ${e.message}")
}
}
-}
\ No newline at end of file
+}
if (!errorBuilder.isEmpty) {
log.error(errorBuilder.toString())
}
-
}
private suspend fun loadResourceDictionary(errorBuilder: StrBuilder, file: File) {
resourceDictionary.updatedBy = resourceDefinition.updatedBy
if (StringUtils.isBlank(resourceDefinition.tags)) {
- resourceDictionary.tags = (resourceDefinition.name + ", " + resourceDefinition.updatedBy
- + ", " + resourceDefinition.updatedBy)
-
+ resourceDictionary.tags = (resourceDefinition.name + ", " + resourceDefinition.updatedBy +
+ ", " + resourceDefinition.updatedBy)
} else {
resourceDictionary.tags = resourceDefinition.tags!!
}
errorBuilder.appendln("Couldn't load Resource dictionary (${file.name}: ${e.message}")
}
}
-
-}
\ No newline at end of file
+}
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
+
// TODO("Convert into coroutines")
/**
* ModelTypeReactRepository.
fun findByModelNameIn(modelNames: List<String>): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByModelNameIn(modelNames))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByDerivedFrom(derivedFrom: String): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByDerivedFrom(derivedFrom))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByDerivedFromIn(derivedFroms: List<String>): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByDerivedFromIn(derivedFroms))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByDefinitionType(definitionType: String): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByDefinitionType(definitionType))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByDefinitionTypeIn(definitionTypes: List<String>): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByDefinitionTypeIn(definitionTypes))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByTagsContainingIgnoreCase(tags: String): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByTagsContainingIgnoreCase(tags))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun deleteByModelName(modelName: String): Mono<Void> {
modelTypeRepository.deleteByModelName(modelName)
return Mono.empty()
}
-
-}
\ No newline at end of file
+}
@Repository
interface ModelTypeRepository : JpaRepository<ModelType, String> {
+
/**
* This is a findByModelName method
*
* @return Optional<ModelType>
*/
fun findByModelName(modelName: String): ModelType?
+
/**
* This is a findByModelNameIn method
*
* @return List<ModelType>
*/
fun findByModelNameIn(modelNames: List<String>): List<ModelType>
+
/**
* This is a findByDerivedFrom method
*
* @param derivedFrom Derived From
* @return List<ModelType>
- */
+ */
fun findByDerivedFrom(derivedFrom: String): List<ModelType>
+
/**
* This is a findByDerivedFromIn method
*
* @param derivedFroms Derived Froms
* @return List<ModelType>
- */
+ */
fun findByDerivedFromIn(derivedFroms: List<String>): List<ModelType>
/**
* @return List<ModelType>
*/
fun findByDefinitionType(definitionType: String): List<ModelType>
+
/**
* This is a findByDefinitionTypeIn method
*
* @param definitionTypes Definition Types
* @return List<ModelType>
- */
+ */
fun findByDefinitionTypeIn(definitionTypes: List<String>): List<ModelType>
/**
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
-
/**
* ResourceMappingRepository.java Purpose: Provide Configuration Generator ResourceMappingRepository
*
@Repository
interface ResourceDictionaryRepository : JpaRepository<ResourceDictionary, String> {
-
/**
* This is a findByName method
*
* @param name name
*/
fun deleteByName(name: String)
-
-
}
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ResourceDictionaryRepository
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
}
@Service
-open class BluePrintRepoFileService(private val modelTypeRepository: ModelTypeRepository,
- private val resourceDictionaryRepository: ResourceDictionaryRepository) : ResourceDefinitionRepoService {
+open class BluePrintRepoFileService(
+ private val modelTypeRepository: ModelTypeRepository,
+ private val resourceDictionaryRepository: ResourceDictionaryRepository
+) : ResourceDefinitionRepoService {
@Throws(BluePrintException::class)
override fun getNodeType(nodeTypeName: String): NodeType {
return getModelType(nodeTypeName, NodeType::class.java)
- ?: throw BluePrintException("couldn't get NodeType($nodeTypeName)")
+ ?: throw BluePrintException("couldn't get NodeType($nodeTypeName)")
}
@Throws(BluePrintException::class)
override fun getDataType(dataTypeName: String): DataType {
return getModelType(dataTypeName, DataType::class.java)
- ?: throw BluePrintException("couldn't get DataType($dataTypeName)")
+ ?: throw BluePrintException("couldn't get DataType($dataTypeName)")
}
@Throws(BluePrintException::class)
override fun getArtifactType(artifactTypeName: String): ArtifactType {
return getModelType(artifactTypeName, ArtifactType::class.java)
- ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName)")
+ ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName)")
}
@Throws(BluePrintException::class)
override fun getRelationshipType(relationshipTypeName: String): RelationshipType {
return getModelType(relationshipTypeName, RelationshipType::class.java)
- ?: throw BluePrintException("couldn't get RelationshipType($relationshipTypeName)")
+ ?: throw BluePrintException("couldn't get RelationshipType($relationshipTypeName)")
}
@Throws(BluePrintException::class)
override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition {
return getModelType(capabilityDefinitionName, CapabilityDefinition::class.java)
- ?: throw BluePrintException("couldn't get CapabilityDefinition($capabilityDefinitionName)")
+ ?: throw BluePrintException("couldn't get CapabilityDefinition($capabilityDefinitionName)")
}
@Throws(BluePrintException::class)
@Throws(BluePrintException::class)
private fun <T> getModelType(modelName: String, valueClass: Class<T>): T? {
- Preconditions.checkArgument(StringUtils.isNotBlank(modelName),
- "Failed to get model from repo, model name is missing")
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(modelName),
+ "Failed to get model from repo, model name is missing"
+ )
val modelDefinition = getModelDefinition(modelName)
- Preconditions.checkNotNull(modelDefinition,
- String.format("Failed to get model content for model name (%s)", modelName))
+ Preconditions.checkNotNull(
+ modelDefinition,
+ String.format("Failed to get model content for model name (%s)", modelName)
+ )
return JacksonUtils.readValue(modelDefinition, valueClass)
}
}
return modelDefinition
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils
import kotlinx.coroutines.reactive.awaitSingle
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
+import org.onap.ccsdk.cds.controllerblueprints.core.deCompress
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils
import org.springframework.core.io.ByteArrayResource
import java.io.File
import java.nio.file.Paths
-
class BluePrintEnhancerUtils {
companion object {
val log = logger(BluePrintEnhancerUtils)
- fun populateDataTypes(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService,
- dataTypeName: String): DataType {
+ fun populateDataTypes(
+ bluePrintContext: BluePrintContext,
+ bluePrintRepoService: BluePrintRepoService,
+ dataTypeName: String
+ ): DataType {
val dataType = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName)
- ?: bluePrintRepoService.getDataType(dataTypeName)
- ?: throw BluePrintException("couldn't get DataType($dataTypeName) from repo.")
+ ?: bluePrintRepoService.getDataType(dataTypeName)
+ ?: throw BluePrintException("couldn't get DataType($dataTypeName) from repo.")
bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dataType)
return dataType
}
- fun populateRelationshipType(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService,
- relationshipName: String): RelationshipType {
+ fun populateRelationshipType(
+ bluePrintContext: BluePrintContext,
+ bluePrintRepoService: BluePrintRepoService,
+ relationshipName: String
+ ): RelationshipType {
val relationshipType = bluePrintContext.serviceTemplate.relationshipTypes?.get(relationshipName)
- ?: bluePrintRepoService.getRelationshipType(relationshipName)
- ?: throw BluePrintException("couldn't get RelationshipType($relationshipName) from repo.")
+ ?: bluePrintRepoService.getRelationshipType(relationshipName)
+ ?: throw BluePrintException("couldn't get RelationshipType($relationshipName) from repo.")
bluePrintContext.serviceTemplate.relationshipTypes?.put(relationshipName, relationshipType)
return relationshipType
}
-
- fun populateNodeType(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService,
- nodeTypeName: String): NodeType {
+ fun populateNodeType(
+ bluePrintContext: BluePrintContext,
+ bluePrintRepoService: BluePrintRepoService,
+ nodeTypeName: String
+ ): NodeType {
val nodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(nodeTypeName)
- ?: bluePrintRepoService.getNodeType(nodeTypeName)
- ?: throw BluePrintException("couldn't get NodeType($nodeTypeName) from repo.")
+ ?: bluePrintRepoService.getNodeType(nodeTypeName)
+ ?: throw BluePrintException("couldn't get NodeType($nodeTypeName) from repo.")
bluePrintContext.serviceTemplate.nodeTypes?.put(nodeTypeName, nodeType)
return nodeType
}
- fun populateArtifactType(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService,
- artifactTypeName: String): ArtifactType {
+ fun populateArtifactType(
+ bluePrintContext: BluePrintContext,
+ bluePrintRepoService: BluePrintRepoService,
+ artifactTypeName: String
+ ): ArtifactType {
val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName)
- ?: bluePrintRepoService.getArtifactType(artifactTypeName)
- ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName) from repo.")
+ ?: bluePrintRepoService.getArtifactType(artifactTypeName)
+ ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName) from repo.")
bluePrintContext.serviceTemplate.artifactTypes?.put(artifactTypeName, artifactType)
return artifactType
}
return targetFile
}
-
suspend fun filePartAsFile(filePart: FilePart, targetFile: File): File {
// Delete the Directory
targetFile.parentFile.reCreateNBDirs()
return filePart.transferTo(targetFile)
- .thenReturn(targetFile)
- .awaitSingle()
+ .thenReturn(targetFile)
+ .awaitSingle()
}
private suspend fun byteArrayAsArchiveFile(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File {
- //Recreate the Base Directories
+ // Recreate the Base Directories
normalizedFile(archiveDir).reCreateNBDirs()
normalizedFile(enhanceDir).reCreateNBDirs()
val archiveFile = normalizedFile(archiveDir, "cba.zip")
}
private suspend fun filePartAsArchiveFile(filePart: FilePart, archiveDir: String, enhanceDir: String): File {
- //Recreate the Base Directories
+ // Recreate the Base Directories
normalizedFile(archiveDir).reCreateNBDirs()
normalizedFile(enhanceDir).reCreateNBDirs()
val archiveFile = normalizedFile(archiveDir, "cba.zip")
}
/** compress [enhanceDir] to [archiveDir] and return ByteArray */
- suspend fun compressEnhanceDirAndReturnByteArray(enhanceDir: String, archiveDir: String,
- outputFileName: String = "enhanced-cba.zip"): ByteArray {
+ suspend fun compressEnhanceDirAndReturnByteArray(
+ enhanceDir: String,
+ archiveDir: String,
+ outputFileName: String = "enhanced-cba.zip"
+ ): ByteArray {
val compressedFile = normalizedFile(archiveDir, outputFileName)
BluePrintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile)
return compressedFile.readBytes()
}
/** compress [enhanceDir] to [archiveDir] and return ResponseEntity */
- suspend fun compressEnhanceDirAndReturnFilePart(enhanceDir: String, archiveDir: String,
- outputFileName: String = "enhanced-cba.zip")
- : ResponseEntity<Resource> {
+ suspend fun compressEnhanceDirAndReturnFilePart(
+ enhanceDir: String,
+ archiveDir: String,
+ outputFileName: String = "enhanced-cba.zip"
+ ):
+ ResponseEntity<Resource> {
val compressedFile = normalizedFile(archiveDir, outputFileName)
BluePrintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile)
return prepareResourceEntity(compressedFile)
suspend fun prepareResourceEntity(file: File): ResponseEntity<Resource> {
return prepareResourceEntity(file.name, file.readBytes())
}
+
/** convert [byteArray] to ResourceEntity with [fileName]*/
fun prepareResourceEntity(fileName: String, byteArray: ByteArray): ResponseEntity<Resource> {
return ResponseEntity.ok()
- .contentType(MediaType.parseMediaType("text/plain"))
- .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
- .body(ByteArrayResource(byteArray))
+ .contentType(MediaType.parseMediaType("text/plain"))
+ .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
+ .body(ByteArrayResource(byteArray))
}
suspend fun cleanEnhancer(archiveLocation: String, enhancementLocation: String) {
enum class BlueprintSortByOption(val columnName: String) {
DATE("createdDate"),
NAME("artifactName")
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
class ModelTypeValidator {
when (definitionType) {
BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE -> {
JacksonUtils.readValue(definitionContent, DataType::class.java)
- ?: throw BluePrintException("Model type definition is not DataType valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not DataType valid content $definitionContent")
}
BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE -> {
JacksonUtils.readValue(definitionContent, NodeType::class.java)
- ?: throw BluePrintException("Model type definition is not NodeType valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not NodeType valid content $definitionContent")
}
BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE -> {
JacksonUtils.readValue(definitionContent, ArtifactType::class.java)
- ?: throw BluePrintException("Model type definition is not ArtifactType valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not ArtifactType valid content $definitionContent")
}
BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE -> {
JacksonUtils.readValue(definitionContent, CapabilityDefinition::class.java)
- ?: throw BluePrintException("Model type definition is not CapabilityDefinition valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not CapabilityDefinition valid content $definitionContent")
}
BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE -> {
JacksonUtils.readValue(definitionContent, RelationshipType::class.java)
- ?: throw BluePrintException("Model type definition is not RelationshipType valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not RelationshipType valid content $definitionContent")
}
}
return true
return true
}
}
-
}
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
-import org.onap.ccsdk.cds.controllerblueprints.management.api.*
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintBootstrapInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintDownloadInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintRemoveInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction
+import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk
+import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction
+import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.ComponentScan
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
-import kotlin.test.*
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+import kotlin.test.assertTrue
@RunWith(SpringRunner::class)
@EnableAutoConfiguration
@DirtiesContext
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
- "org.onap.ccsdk.cds.controllerblueprints"])
+@ComponentScan(
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
+ "org.onap.ccsdk.cds.controllerblueprints"]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BluePrintManagementGRPCHandlerTest {
val req = createBootstrapInputRequest(id)
val bootstrapOutput = blockingStub.bootstrapBlueprint(req)
assertEquals(200, bootstrapOutput.status.code)
- assertTrue(bootstrapOutput.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
- "failed to get success status")
+ assertTrue(
+ bootstrapOutput.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
+ "failed to get success status"
+ )
assertEquals(id, bootstrapOutput.commonHeader.requestId)
}
val output = blockingStub.uploadBlueprint(req)
assertEquals(200, output.status.code)
- assertTrue(output.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
- "failed to get success status")
+ assertTrue(
+ output.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
+ "failed to get success status"
+ )
assertEquals(id, output.commonHeader.requestId)
val downloadId = "123_download"
val downloadOutput = blockingStub.downloadBlueprint(downloadReq)
assertEquals(200, downloadOutput.status.code)
- assertTrue(downloadOutput.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
- "failed to get success status")
+ assertTrue(
+ downloadOutput.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
+ "failed to get success status"
+ )
assertNotNull(downloadOutput.fileChunk?.chunk, "failed to get cba file chunks")
assertEquals(downloadId, downloadOutput.commonHeader.requestId)
}
var output = blockingStub.uploadBlueprint(req)
assertEquals(200, output.status.code)
- assertTrue(output.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
- "failed to get success status")
+ assertTrue(
+ output.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
+ "failed to get success status"
+ )
assertEquals(id, output.commonHeader.requestId)
val removeReq = createRemoveInputRequest(id)
private fun createBootstrapInputRequest(id: String): BluePrintBootstrapInput {
val commonHeader = CommonHeader
- .newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(id)
- .setSubRequestId("1234-56").build()
+ .newBuilder()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(id)
+ .setSubRequestId("1234-56").build()
return BluePrintBootstrapInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setLoadModelType(false)
- .setLoadResourceDictionary(false)
- .setLoadCBA(false)
- .build()
+ .setCommonHeader(commonHeader)
+ .setLoadModelType(false)
+ .setLoadResourceDictionary(false)
+ .setLoadCBA(false)
+ .build()
}
private fun createUploadInputRequest(id: String, action: String): BluePrintUploadInput {
assertTrue(file.exists(), "couldnt get file ${file.absolutePath}")
val commonHeader = CommonHeader
- .newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(id)
- .setSubRequestId("1234-56").build()
+ .newBuilder()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(id)
+ .setSubRequestId("1234-56").build()
val actionIdentifier = ActionIdentifiers.newBuilder()
- .setActionName(action)
- .setBlueprintName("sample")
- .setBlueprintVersion("1.0.0")
- .build()
+ .setActionName(action)
+ .setBlueprintName("sample")
+ .setBlueprintVersion("1.0.0")
+ .build()
val fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(file.inputStream().readBytes()))
- .build()
+ .build()
return BluePrintUploadInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(actionIdentifier)
- .setFileChunk(fileChunk)
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setFileChunk(fileChunk)
+ .build()
}
private fun createDownloadInputRequest(id: String, action: String): BluePrintDownloadInput {
val commonHeader = CommonHeader
- .newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(id)
- .setSubRequestId("1234-56").build()
+ .newBuilder()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(id)
+ .setSubRequestId("1234-56").build()
return BluePrintDownloadInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(ActionIdentifiers.newBuilder()
- .setBlueprintName("baseconfiguration")
- .setBlueprintVersion("1.0.0")
- .setActionName(action).build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(
+ ActionIdentifiers.newBuilder()
+ .setBlueprintName("baseconfiguration")
+ .setBlueprintVersion("1.0.0")
+ .setActionName(action).build()
+ )
+ .build()
}
private fun createRemoveInputRequest(id: String): BluePrintRemoveInput {
val commonHeader = CommonHeader
- .newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(id)
- .setSubRequestId("1234-56").build()
+ .newBuilder()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(id)
+ .setSubRequestId("1234-56").build()
return BluePrintRemoveInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(ActionIdentifiers.newBuilder()
- .setBlueprintName("sample")
- .setBlueprintVersion("1.0.0")
- .setActionName(RemoveAction.DEFAULT.toString()).build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(
+ ActionIdentifiers.newBuilder()
+ .setBlueprintName("sample")
+ .setBlueprintVersion("1.0.0")
+ .setActionName(RemoveAction.DEFAULT.toString()).build()
+ )
+ .build()
}
}
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.compress
import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.reCreateDirs
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.core.io.ByteArrayResource
@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class BlueprintModelControllerTest {
private var testZipFile: File? = null
-
@Before
fun setUp() {
assertNotNull(webTestClient, " Failed to create WebTestClient")
}.build()
val saveBP = webTestClient
- .post()
- .uri("/api/v1/blueprint-model")
- .body(BodyInserters.fromMultipartData(body))
- .exchange()
- .expectStatus().isOk
- .returnResult<BlueprintModelSearch>()
- .responseBody
- .awaitSingle()
+ .post()
+ .uri("/api/v1/blueprint-model")
+ .body(BodyInserters.fromMultipartData(body))
+ .exchange()
+ .expectStatus().isOk
+ .returnResult<BlueprintModelSearch>()
+ .responseBody
+ .awaitSingle()
assertNotNull(saveBP, "failed to get response")
assertEquals("baseconfiguration", saveBP.artifactName, "mismatch artifact name")
@Test
@Throws(JSONException::class)
fun test02_getBluePrintByNameAndVersion() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}",
+ HttpStatus.OK, false
+ )
}
-
@Test
@Throws(JSONException::class)
fun test03_getBlueprintModel() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/${bp!!.id}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/${bp!!.id}",
+ HttpStatus.OK, false
+ )
}
@Test
@Test
@Throws(JSONException::class)
fun test05_downloadBluePrint() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/download/${bp!!.id}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/download/${bp!!.id}",
+ HttpStatus.OK, false
+ )
}
@Test
}.build()
val publishBP = webTestClient
- .post()
- .uri("/api/v1/blueprint-model/publish")
- .body(BodyInserters.fromMultipartData(body))
- .exchange()
- .expectStatus().isOk
- .returnResult<BlueprintModelSearch>()
- .responseBody
- .awaitSingle()
+ .post()
+ .uri("/api/v1/blueprint-model/publish")
+ .body(BodyInserters.fromMultipartData(body))
+ .exchange()
+ .expectStatus().isOk
+ .returnResult<BlueprintModelSearch>()
+ .responseBody
+ .awaitSingle()
assertNotNull(publishBP, "failed to get response")
assertEquals("baseconfiguration", publishBP.artifactName, "mismatch artifact name")
@Test
@Throws(JSONException::class)
fun test08_searchBlueprintModels() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/search/${bp!!.artifactName}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/search/${bp!!.artifactName}",
+ HttpStatus.OK, false
+ )
}
@Test
@Throws(JSONException::class)
fun test09_downloadBlueprintByNameAndVersion() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/download/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/download/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}",
+ HttpStatus.OK, false
+ )
}
@Test
fun test10_deleteBluePrint() {
-// webTestClient.delete().uri("/api/v1/blueprint-model/${bp!!.id}")
-// .header("Authorization", "Basic " + Base64Utils
-// .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8)))
-// .exchange()
-// .expectStatus().is2xxSuccessful
+ // webTestClient.delete().uri("/api/v1/blueprint-model/${bp!!.id}")
+ // .header("Authorization", "Basic " + Base64Utils
+ // .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8)))
+ // .exchange()
+ // .expectStatus().is2xxSuccessful
webTestClient.delete().uri("/api/v1/blueprint-model/name/${bp!!.artifactName}/version/${bp!!.artifactVersion}")
- .header("Authorization", "Basic " + Base64Utils
- .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8)))
- .exchange()
- .expectStatus().is2xxSuccessful
+ .header(
+ "Authorization", "Basic " + Base64Utils
+ .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))
+ )
+ .exchange()
+ .expectStatus().is2xxSuccessful
}
@Throws(JSONException::class)
- private fun webTestClient(requestMethod: HttpMethod, body: BodyInserters.MultipartInserter?, uri: String,
- expectedResponceStatus: HttpStatus, setParam: Boolean) {
+ private fun webTestClient(
+ requestMethod: HttpMethod,
+ body: BodyInserters.MultipartInserter?,
+ uri: String,
+ expectedResponceStatus: HttpStatus,
+ setParam: Boolean
+ ) {
log.info("Requesting($uri): Method(${requestMethod.name})")
webTestClient.method(requestMethod).uri(uri)
- .header("Authorization", "Basic " + Base64Utils
- .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8)))
- .body(body)
- .exchange()
- .expectStatus().isEqualTo(expectedResponceStatus)
- .expectBody()
- .returnResult().responseBody!!
-
+ .header(
+ "Authorization", "Basic " + Base64Utils
+ .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))
+ )
+ .body(body)
+ .exchange()
+ .expectStatus().isEqualTo(expectedResponceStatus)
+ .expectBody()
+ .returnResult().responseBody!!
}
-
-}
\ No newline at end of file
+}
import org.springframework.context.annotation.Configuration
@Configuration
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.controllerblueprints",
- "org.onap.ccsdk.cds.blueprintsprocessor"])
+@ComponentScan(
+ basePackages = ["org.onap.ccsdk.cds.controllerblueprints",
+ "org.onap.ccsdk.cds.blueprintsprocessor"]
+)
@EnableAutoConfiguration
open class DesignerApiTestConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.annotation.Commit
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ModelTypeControllerTest {
modelType.definition = JacksonUtils.jsonNode(content)
modelType.modelName = modelName
modelType.version = "1.0.0"
- modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + ","
- + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
+ modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," +
+ BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
modelType.updatedBy = "xxxxxx@xxx.com"
modelType = modelTypeController!!.saveModelType(modelType)
log.info("Saved Mode {}", modelType.toString())
Assert.assertNotNull("Failed to get Saved ModelType, Id", modelType.modelName)
val dbModelType = modelTypeController!!.getModelTypeByName(modelType.modelName)
- Assert.assertNotNull("Failed to query ResourceMapping for ID (" + dbModelType!!.modelName + ")",
- dbModelType)
+ Assert.assertNotNull(
+ "Failed to query ResourceMapping for ID (" + dbModelType!!.modelName + ")",
+ dbModelType
+ )
// Model Update
modelType.updatedBy = "bs2796@xxx.com"
modelType = modelTypeController!!.saveModelType(modelType)
Assert.assertNotNull("Failed to get Saved ModelType", modelType)
Assert.assertEquals("Failed to get Saved getUpdatedBy ", "bs2796@xxx.com", modelType.updatedBy)
-
}
@Test
val dbModelTypes = modelTypeController!!.searchModelTypes(tags)
Assert.assertNotNull("Failed to search ResourceMapping by tags", dbModelTypes)
Assert.assertTrue("Failed to search ResourceMapping by tags count", dbModelTypes.isNotEmpty())
-
}
@Test
@Throws(Exception::class)
fun test04DeleteModelType() {
log.info(
- "************************ test03DeleteModelType ***********************")
+ "************************ test03DeleteModelType ***********************"
+ )
val dbResourceMapping = modelTypeController!!.getModelTypeByName(modelName)
Assert.assertNotNull("Failed to get response for api call getModelByName ", dbResourceMapping)
Assert.assertNotNull("Failed to get Id for api call getModelByName ", dbResourceMapping!!.modelName)
@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ResourceDictionaryControllerTest {
fun testResourceDictionaryControllerPresence() {
assertNotNull(resourceDictionaryController, "failed to initialise ResourceDictionaryController")
}
-
-}
\ No newline at end of file
+}
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BluePrintEnhancerServiceImplTest {
@Autowired
lateinit var bluePrintValidatorService: BluePrintValidatorService
-
@Test
@Throws(Exception::class)
fun testEnhancementAndValidation() {
fun testRemoteScriptsEnhancementAndValidation() {
val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts"
testComponentInvokeEnhancementAndValidation(basePath, "remote_scripts-enhance")
-
}
fun testCapabilityCliEnhancementAndValidation() {
Assert.assertTrue("blueprint($basePath) validation failed ", valid)
// Enable this to get the enhanced zip file
-// val compressFile = normalizedFile("target/blueprints/enrichment", "$targetDirName.zip")
-// normalizedFile(targetPath).compress(compressFile)
+ // val compressFile = normalizedFile("target/blueprints/enrichment", "$targetDirName.zip")
+ // normalizedFile(targetPath).compress(compressFile)
deleteDir(targetPath)
}
}
-
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.annotation.Commit
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
-
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ModelTypeServiceTest {
+
@Autowired
private val modelTypeHandler: ModelTypeHandler? = null
modelType.definition = JacksonUtils.jsonNode(content)
modelType.modelName = modelName
modelType.version = "1.0.0"
- modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + ","
- + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
+ modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," +
+ BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
modelType.updatedBy = "xxxxxx@xxx.com"
modelType = modelTypeHandler!!.saveModel(modelType)
log.info("Saved Mode {}", modelType.toString())
Assert.assertNotNull("Failed to get Saved ModelType, Id", modelType.modelName)
val dbModelType = modelTypeHandler.getModelTypeByName(modelType.modelName)
- Assert.assertNotNull("Failed to query ResourceMapping for ID (" + dbModelType!!.modelName + ")",
- dbModelType)
+ Assert.assertNotNull(
+ "Failed to query ResourceMapping for ID (" + dbModelType!!.modelName + ")",
+ dbModelType
+ )
// Model Update
modelType.updatedBy = "bs2796@xxx.com"
Assert.assertNotNull("Failed to get Saved ModelType", modelType)
Assert.assertEquals("Failed to get Saved getUpdatedBy ", "bs2796@xxx.com", modelType.updatedBy)
}
-
}
@Test
Assert.assertNotNull("Failed to search ResourceMapping by tags", dbModelTypes)
Assert.assertTrue("Failed to search ResourceMapping by tags count", dbModelTypes.size > 0)
}
-
}
@Test
Assert.assertNotNull("Failed to find getModelTypeByDerivedFrom by tags", dbModelTypeByDerivedFroms)
Assert.assertTrue("Failed to find getModelTypeByDerivedFrom by count", dbModelTypeByDerivedFroms.size > 0)
}
-
}
@Test
fun test04DeleteModelType() {
runBlocking {
log.info(
- "************************ test03DeleteModelType ***********************")
+ "************************ test03DeleteModelType ***********************"
+ )
val dbResourceMapping = modelTypeHandler!!.getModelTypeByName(modelName)
Assert.assertNotNull("Failed to get response for api call getModelByName ", dbResourceMapping)
Assert.assertNotNull("Failed to get Id for api call getModelByName ", dbResourceMapping!!.modelName)
modelTypeHandler.deleteByModelName(dbResourceMapping.modelName)
}
}
-
-}
\ No newline at end of file
+}
class MockFilePart(private val fileName: String) : FilePart {
val log = LoggerFactory.getLogger(MockFilePart::class.java)!!
override fun content(): Flux<DataBuffer> {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override fun headers(): HttpHeaders {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override fun filename(): String {
}
override fun transferTo(path: Path): Mono<Void> {
- log.info("Copying file($fileName to ${path}")
+ log.info("Copying file($fileName to $path")
FileCopyUtils.copy(File(fileName), path.toFile())
return Mono.empty()
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.annotation.Commit
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
import java.nio.charset.Charset
-import java.util.*
+import java.util.Arrays
/**
* ModelTypeReactRepositoryTest.
*/
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ModelTypeReactRepositoryTest {
@Commit
fun test01Save() {
val content = normalizedFile("./src/test/resources/model_type/data_type/datatype-property.json")
- .readText(Charset.defaultCharset())
+ .readText(Charset.defaultCharset())
val modelType = ModelType()
modelType.definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE
modelType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT
modelType.definition = JacksonUtils.jsonNode(content)
modelType.modelName = modelName
modelType.version = "1.0.0"
- modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + ","
- + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
+ modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," +
+ BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
modelType.updatedBy = "xxxxxx@xxx.com"
val dbModelType = modelTypeReactRepository!!.save(modelType).block()
val dbFindByModelName = modelTypeReactRepository!!.findByModelName(modelName).block()
Assert.assertNotNull("Failed to findByModelName ", dbFindByModelName)
- val dbFindByDefinitionType = modelTypeReactRepository.findByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE).collectList().block()
+ val dbFindByDefinitionType =
+ modelTypeReactRepository.findByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE).collectList().block()
Assert.assertNotNull("Failed to findByDefinitionType ", dbFindByDefinitionType)
Assert.assertTrue("Failed to findByDefinitionType count", dbFindByDefinitionType!!.size > 0)
Assert.assertNotNull("Failed to findByModelNameIn ", dbFindByModelNameIn)
Assert.assertTrue("Failed to findByModelNameIn by count", dbFindByModelNameIn!!.size > 0)
- val dbFindByDefinitionTypeIn = modelTypeReactRepository.findByDefinitionTypeIn(Arrays.asList(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)).collectList().block()
+ val dbFindByDefinitionTypeIn =
+ modelTypeReactRepository.findByDefinitionTypeIn(Arrays.asList(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)).collectList().block()
Assert.assertNotNull("Failed to findByDefinitionTypeIn", dbFindByDefinitionTypeIn)
Assert.assertTrue("Failed to findByDefinitionTypeIn by count", dbFindByDefinitionTypeIn!!.size > 0)
- val dbFindByDerivedFromIn = modelTypeReactRepository.findByDerivedFromIn(Arrays.asList(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT)).collectList().block()
+ val dbFindByDerivedFromIn =
+ modelTypeReactRepository.findByDerivedFromIn(Arrays.asList(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT)).collectList().block()
Assert.assertNotNull("Failed to find findByDerivedFromIn", dbFindByDerivedFromIn)
Assert.assertTrue("Failed to find findByDerivedFromIn by count", dbFindByDerivedFromIn!!.size > 0)
}
fun test03Delete() {
modelTypeReactRepository!!.deleteByModelName(modelName).block()
}
-
}
import org.springframework.transaction.annotation.Transactional
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ResourceDictionaryReactRepositoryTest {
@Commit
fun test01Save() {
val resourceDefinition = JacksonUtils
- .readValueFromFile("./../../../../../components/model-catalog/resource-dictionary/starter-dictionary/sample-db-source.json",
- ResourceDefinition::class.java)
+ .readValueFromFile(
+ "./../../../../../components/model-catalog/resource-dictionary/starter-dictionary/sample-db-source.json",
+ ResourceDefinition::class.java
+ )
Assert.assertNotNull("Failed to get resourceDefinition from content", resourceDefinition)
resourceDefinition!!.name = sourceName
import org.junit.Before
import org.junit.Test
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.mock.MockFilePart
-import org.onap.ccsdk.cds.controllerblueprints.core.*
-import java.util.*
+import org.onap.ccsdk.cds.controllerblueprints.core.compress
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.reCreateDirs
+import java.util.UUID
import kotlin.test.assertTrue
class BluePrintEnhancerUtilsTest {
private val blueprintDir = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
private val blueprintArchivePath: String = "./target/blueprints/archive"
private val blueprintEnrichmentPath: String = "./target/blueprints/enrichment"
- private var zipBlueprintFileName = normalizedPathName(blueprintArchivePath, "test.zip")
+ private var zipBlueprintFileName = normalizedPathName(blueprintArchivePath, "test.zip")
@Before
fun setUp() {
}
}
}
-
<artifactId>health-api-common</artifactId>
<packaging>jar</packaging>
- <name>Blueprints Processor Health API common </name>
+ <name>Blueprints Processor Health API common</name>
<description>checking system check health endpoints</description>
<dependencies>
<artifactId>rest-lib</artifactId>
</dependency>
-
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
open fun getBasicAuthRestClientService(): BasicAuthRestClientService {
return BasicAuthRestClientService(getBasicAuthRestClientProperties())
}
-
}
open fun getCDSListenerServiceInformation(): List<ServiceEndpoint> {
val serviceName = ServiceName.BLUEPRINT
return getListOfServiceEndPoints(cdsListenerServiceMapping, serviceName)
-
}
private fun getListOfServiceEndPoints(serviceMapping: List<String>?, serviceName: ServiceName): MutableList<ServiceEndpoint> {
return serviceEndpoints
}
- private fun fillListOfService(serviceName: ServiceName , element: String, listOfCDSListenerServiceEndpoint: MutableList<ServiceEndpoint>) {
+ private fun fillListOfService(serviceName: ServiceName, element: String, listOfCDSListenerServiceEndpoint: MutableList<ServiceEndpoint>) {
val serviceEndpointInfo = element.split(",/")
val serviceEndpoint = getServiceEndpoint(serviceEndpointInfo)
if (serviceName.equals(ServiceName.CDSLISTENER))
listOfCDSListenerServiceEndpoint.add(serviceEndpoint)
}
-
private fun getServiceEndpoint(serviceEndpointInfo: List<String>): ServiceEndpoint {
- return ServiceEndpoint(removeSpecialCharacter(serviceEndpointInfo.get(0))
- , removeSpecialCharacter(serviceEndpointInfo.get(1))
+ return ServiceEndpoint(
+ removeSpecialCharacter(serviceEndpointInfo.get(0)), removeSpecialCharacter(serviceEndpointInfo.get(1))
)
}
- private fun removeSpecialCharacter(value:String):String{
- return value.replaceFirst(",[","")
- .replace("[","")
- .replace("]","")
+ private fun removeSpecialCharacter(value: String): String {
+ return value.replaceFirst(",[", "")
+ .replace("[", "")
+ .replace("]", "")
}
}
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration
-
import org.apache.commons.net.util.Base64
import org.springframework.stereotype.Component
-import org.springframework.stereotype.Service
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
-
@Component
class SecurityEncryptionConfiguration {
+
private val key = "aesEncryptionKey"
private val initVector = "encryptionIntVec"
data class ApplicationHealth(val status: Status?, val details: Map<String, Any>?) {
constructor() : this(null, HashMap())
}
-
-
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-
-data class HealthApiResponse(val status: HealthCheckStatus, val checks: List<ServicesCheckResponse>
+data class HealthApiResponse(
+ val status: HealthCheckStatus,
+ val checks: List<ServicesCheckResponse>
)
-
-
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-
data class Metrics(val names: ArrayList<Any>?) {
constructor() : this(ArrayList())
}
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-data class MetricsResponse(val maps: HashMap<String, String>) {
-
-}
+data class MetricsResponse(val maps: HashMap<String, String>)
*/
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-
data class ServiceEndpoint(val serviceName: String, var serviceLink: String)
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
enum class ServiceName(s: String) {
- BLUEPRINT("Blue Print service"),CDSLISTENER("CDS Listener service")
+ BLUEPRINT("Blue Print service"), CDSLISTENER("CDS Listener service")
}
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-
data class ServicesCheckResponse(val name: String, val status: HealthCheckStatus)
-
-
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
-data class WebClientEnpointResponse (val response:BlueprintWebClientService.WebClientResponse<String>?) {
-}
+data class WebClientEnpointResponse(val response: BlueprintWebClientService.WebClientResponse<String>?)
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service
-
import com.fasterxml.jackson.databind.ObjectMapper
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ApplicationHealth
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
* @version 1.0
*/
@Service
-open class EndPointExecution(private val basicAuthRestClientService: BasicAuthRestClientService
- , private val restClientProperties: BasicAuthRestClientProperties) {
+open class EndPointExecution(
+ private val basicAuthRestClientService: BasicAuthRestClientService,
+ private val restClientProperties: BasicAuthRestClientProperties
+) {
private var logger = LoggerFactory.getLogger(EndPointExecution::class.java)
val result = basicAuthRestClientService.exchangeResource(HttpMethod.GET.name, "", "")
if (result.status == 200)
return WebClientEnpointResponse(result)
-
} catch (e: Exception) {
logger.error("service name ${serviceEndpoint.serviceName} is down ${e.message}")
}
- return WebClientEnpointResponse(BlueprintWebClientService.WebClientResponse(500,""))
+ return WebClientEnpointResponse(BlueprintWebClientService.WebClientResponse(500, ""))
}
private fun addClientPropertiesConfiguration(serviceEndpoint: ServiceEndpoint) {
restClientProperties.url = serviceEndpoint.serviceLink
}
-
open fun getHealthFromWebClientEnpointResponse(webClientEnpointResponse: WebClientEnpointResponse): ApplicationHealth? {
return mappingMetricsToDTO(webClientEnpointResponse?.response?.body.toString())
-
}
private fun mappingMetricsToDTO(body: String): ApplicationHealth {
return ObjectMapper().readValue(body, ApplicationHealth::class.java)
}
}
-
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.*
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthApiResponse
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServicesCheckResponse
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.WebClientEnpointResponse
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.EndPointExecution
import org.slf4j.LoggerFactory
* @author Shaaban Ebrahim
* @version 1.0
*/
-abstract class AbstractHealthCheck (private val endPointExecution: EndPointExecution) {
+abstract class AbstractHealthCheck(private val endPointExecution: EndPointExecution) {
private var logger = LoggerFactory.getLogger(BluePrintProcessorHealthCheck::class.java)
}
healthApiResponse = HealthApiResponse(systemStatus, listOfResponse)
return healthApiResponse
-
}
-
private fun retrieveServiceStatus(serviceEndpoint: ServiceEndpoint): HealthCheckStatus {
var serviceStatus: HealthCheckStatus = HealthCheckStatus.UP
try {
} catch (e: Exception) {
logger.error("service name ${serviceEndpoint.serviceName} is down ${e.message}")
serviceStatus = HealthCheckStatus.DOWN
-
}
return serviceStatus
}
-
open fun retrieveEndpointExecutionStatus(): HealthApiResponse {
return retrieveSystemStatus(setupServiceEndpoint())
}
abstract fun setupServiceEndpoint(): List<ServiceEndpoint>
-
}
* @version 1.0
*/
@Service
-open class BluePrintProcessorHealthCheck(private val endPointExecution: EndPointExecution
- , private val healthCheckProperties: HealthCheckProperties)
- : AbstractHealthCheck(endPointExecution) {
+open class BluePrintProcessorHealthCheck(
+ private val endPointExecution: EndPointExecution,
+ private val healthCheckProperties: HealthCheckProperties
+) :
+ AbstractHealthCheck(endPointExecution) {
override fun setupServiceEndpoint(): List<ServiceEndpoint> {
return healthCheckProperties.getBluePrintServiceInformation()
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.HealthCheckProperties
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthApiResponse
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServicesCheckResponse
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.EndPointExecution
-import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
-import org.slf4j.LoggerFactory
-import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
/**
* @version 1.0
*/
@Service
-open class SDCListenerHealthCheck (private val endPointExecution: EndPointExecution
- ,private val healthCheckProperties: HealthCheckProperties)
- : AbstractHealthCheck(endPointExecution) {
+open class SDCListenerHealthCheck(
+ private val endPointExecution: EndPointExecution,
+ private val healthCheckProperties: HealthCheckProperties
+) :
+ AbstractHealthCheck(endPointExecution) {
override fun setupServiceEndpoint(): List<ServiceEndpoint> {
return healthCheckProperties.getCDSListenerServiceInformation()
}
-
-
}
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi
+import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
-import org.mockito.ArgumentMatchers.any
-import org.mockito.ArgumentMatchers.eq
-import org.mockito.Mockito.anyString
-import org.mockito.Mockito.mock
-
-import java.util.Arrays
-import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
-import org.mockito.ArgumentMatchers
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito
+import org.mockito.Mockito.anyString
import org.mockito.junit.MockitoJUnitRunner
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.HealthCheckProperties
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthApiResponse
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.EndPointExecution
import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BasicAuthRestClientService
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
-import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService.WebClientResponse
-import org.springframework.http.HttpMethod
+import java.util.Arrays
@RunWith(MockitoJUnitRunner::class)
class HealthCheckServiceTest {
private var bluePrintProcessorHealthCheck: BluePrintProcessorHealthCheck? = null
-
@Before
fun setup() {
endPointExecution = Mockito.spy(endPointExecution!!)
- Mockito.`when`(healthCheckProperties!!.getBluePrintServiceInformation()).thenReturn(Arrays.asList(
+ Mockito.`when`(healthCheckProperties!!.getBluePrintServiceInformation()).thenReturn(
+ Arrays.asList(
ServiceEndpoint("Execution service ", "http://cds-blueprints-processor-http:8080/api/v1/execution-service/health-check"),
- ServiceEndpoint("Resources service", "http://cds-blueprints-processor-http:8080/api/v1/resources/health-check"), ServiceEndpoint("Template service", "http://cds-blueprints-processor-http:8080/api/v1/template/health-check")
- ))
+ ServiceEndpoint("Resources service", "http://cds-blueprints-processor-http:8080/api/v1/resources/health-check"),
+ ServiceEndpoint("Template service", "http://cds-blueprints-processor-http:8080/api/v1/template/health-check")
+ )
+ )
bluePrintProcessorHealthCheck = BluePrintProcessorHealthCheck(endPointExecution!!, healthCheckProperties)
}
- @Test
+ @Test
fun testSystemIsCompletelyDown() {
- Mockito.`when`(basicAuthRestClientService!!.exchangeResource(
- anyString(),
- anyString(),
- anyString())).thenThrow(RuntimeException())
+ Mockito.`when`(
+ basicAuthRestClientService!!.exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ ).thenThrow(RuntimeException())
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
Assert.assertEquals(HealthCheckStatus.DOWN, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.DOWN, serviceEndpoint.status)
-
}
-
}
@Test
fun testSystemIsUPAndRunning() {
- Mockito.`when`(basicAuthRestClientService!!
- .exchangeResource(
- anyString(),
- anyString(),
- anyString())).thenReturn(BlueprintWebClientService.WebClientResponse(200, "Success"))
+ Mockito.`when`(
+ basicAuthRestClientService!!
+ .exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ ).thenReturn(BlueprintWebClientService.WebClientResponse(200, "Success"))
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
assertEquals(HealthCheckStatus.UP, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.UP, serviceEndpoint.status)
-
}
-
}
@Test
fun testServiceIsNotFound() {
- Mockito.`when`(basicAuthRestClientService!!.exchangeResource(
- anyString(),
- anyString(),
- anyString())).thenReturn(BlueprintWebClientService.WebClientResponse(404, "failure"))
+ Mockito.`when`(
+ basicAuthRestClientService!!.exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ ).thenReturn(BlueprintWebClientService.WebClientResponse(404, "failure"))
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
assertEquals(HealthCheckStatus.DOWN, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.DOWN, serviceEndpoint.status)
-
}
-
}
-
@Test
fun testServiceInternalServerError() {
- Mockito.`when`(basicAuthRestClientService!!.exchangeResource(
- anyString(),
- anyString(),
- anyString()))
- .thenReturn(BlueprintWebClientService.WebClientResponse(500, "failure"))
+ Mockito.`when`(
+ basicAuthRestClientService!!.exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ )
+ .thenReturn(BlueprintWebClientService.WebClientResponse(500, "failure"))
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
assertEquals(HealthCheckStatus.DOWN, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.DOWN, serviceEndpoint.status)
-
}
-
}
@Test
fun testServiceIsRedirected() {
- Mockito.`when`(basicAuthRestClientService!!.
- exchangeResource(
- anyString(),
- anyString(),
- anyString()))
- .thenReturn(BlueprintWebClientService.WebClientResponse(300, "failure"))
+ Mockito.`when`(
+ basicAuthRestClientService!!
+ .exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ )
+ .thenReturn(BlueprintWebClientService.WebClientResponse(300, "failure"))
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
assertEquals(HealthCheckStatus.DOWN, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.DOWN, serviceEndpoint.status)
-
}
}
}
import org.junit.Test
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.SecurityEncryptionConfiguration
-
class SecurityConfigurationTest {
@Test
*/
@RestController
@RequestMapping("/api/v1/combinedHealth")
-@Api(value = "/api/v1/combinedHealth",
- description = "gather all HealthCheckResponses for HealthChecks known to the runtime")
+@Api(
+ value = "/api/v1/combinedHealth",
+ description = "gather all HealthCheckResponses for HealthChecks known to the runtime"
+)
open class CombinedHealth(private val combinedHealthService: CombinedHealthService) {
- @RequestMapping(path = [""],
- method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ @RequestMapping(
+ path = [""],
+ method = [RequestMethod.GET],
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun getSystemHealthCheckResponse(): ResponseEntity<List<ApplicationHealth?>> {
return ResponseEntity.ok().body(combinedHealthService.getCombinedHealthCheck())
-
}
}
-
*/
@RestController
@RequestMapping("/api/v1/combinedMetrics")
-@Api(value = "/api/v1/combinedMetrics",
- description = "gather all Metrics info from BluePrint and CDSListener")
+@Api(
+ value = "/api/v1/combinedMetrics",
+ description = "gather all Metrics info from BluePrint and CDSListener"
+)
open class CombinedMetrics(private val combinedMetricsService: CombinedMetricsService) {
- @RequestMapping(path = [""],
- method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ @RequestMapping(
+ path = [""],
+ method = [RequestMethod.GET],
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = " Metrics Check", hidden = true)
fun getMetricsHealthCheckResponse(): ResponseEntity<MetricsInfo?> {
return ResponseEntity.ok().body(combinedMetricsService.metricsInfo)
-
}
-
}
import org.springframework.boot.actuate.health.Status
import org.springframework.stereotype.Service
-
/**
*Service for combined health (BluePrintProcessor and CDSListener)
*
* @version 1.0
*/
@Service
-open class CombinedHealthService(private val endPointExecution: EndPointExecution
- , private val healthCheckProperties: HealthCheckProperties) {
+open class CombinedHealthService(
+ private val endPointExecution: EndPointExecution,
+ private val healthCheckProperties: HealthCheckProperties
+) {
private fun setupServiceEndpoint(): List<ServiceEndpoint> {
return listOf(
- ServiceEndpoint("BluePrintProcessor Health Check ", healthCheckProperties.getBluePrintBaseURL() + "actuator/health")
- , ServiceEndpoint("CDSListener Health Check", healthCheckProperties.getCDSListenerBaseURL() + "actuator/health")
+ ServiceEndpoint("BluePrintProcessor Health Check ", healthCheckProperties.getBluePrintBaseURL() + "actuator/health"),
+ ServiceEndpoint("CDSListener Health Check", healthCheckProperties.getCDSListenerBaseURL() + "actuator/health")
)
}
for (serviceEndpoint in setupServiceEndpoint().parallelStream()) {
val result: WebClientEnpointResponse? = endPointExecution?.retrieveWebClientResponse(serviceEndpoint)
if (result?.response != null &&
- result.response!!.status?.equals(200)!!) {
+ result.response!!.status?.equals(200)!!
+ ) {
listOfResponse.add(endPointExecution?.getHealthFromWebClientEnpointResponse(result))
} else {
- listOfResponse.add(ApplicationHealth(Status.DOWN,
- hashMapOf(serviceEndpoint.serviceLink to serviceEndpoint.serviceLink)))
+ listOfResponse.add(
+ ApplicationHealth(
+ Status.DOWN,
+ hashMapOf(serviceEndpoint.serviceLink to serviceEndpoint.serviceLink)
+ )
+ )
}
}
return listOfResponse
}
-
}
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.HealthCheckProperties
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.*
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ActuatorCheckResponse
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.Metrics
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.MetricsInfo
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.MetricsResponse
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.utils.ObjectMappingUtils
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
import org.springframework.stereotype.Service
* @version 1.0
*/
@Service
-open class CombinedMetricsService(private val endPointExecution: EndPointExecution
- , private val healthCheckProperties: HealthCheckProperties
- , private val objectMappingUtils: ObjectMappingUtils<Metrics>) {
+open class CombinedMetricsService(
+ private val endPointExecution: EndPointExecution,
+ private val healthCheckProperties: HealthCheckProperties,
+ private val objectMappingUtils: ObjectMappingUtils<Metrics>
+) {
private fun setupServiceEndpoint(): List<ServiceEndpoint> {
return listOf(
- ServiceEndpoint("BluePrintProcessor metrics", healthCheckProperties.getBluePrintBaseURL() + "/actuator/metrics")
- , ServiceEndpoint("CDS Listener metrics", healthCheckProperties.getCDSListenerBaseURL() + "/actuator/metrics")
+ ServiceEndpoint("BluePrintProcessor metrics", healthCheckProperties.getBluePrintBaseURL() + "/actuator/metrics"),
+ ServiceEndpoint("CDS Listener metrics", healthCheckProperties.getCDSListenerBaseURL() + "/actuator/metrics")
)
}
val webClientResponse = endPointExecution?.retrieveWebClientResponse(serviceEndpoint)
var actuatorsHealthResponse: ActuatorCheckResponse? = null
actuatorsHealthResponse = if (webClientResponse?.response != null &&
- webClientResponse.response!!.status?.equals(200)!!) {
+ webClientResponse.response!!.status?.equals(200)!!
+ ) {
var body = gettingCustomizedBody(serviceEndpoint, webClientResponse.response!!)
ActuatorCheckResponse(serviceEndpoint.serviceName, body)
} else {
return MetricsInfo(containerHealthChecks)
}
- private fun gettingCustomizedBody(serviceEndpoint: ServiceEndpoint?, webClientResponse: BlueprintWebClientService.WebClientResponse<String>): Any {
+ private fun gettingCustomizedBody(
+ serviceEndpoint: ServiceEndpoint?,
+ webClientResponse: BlueprintWebClientService.WebClientResponse<String>
+ ): Any {
var body: Any
val metrics: Metrics = objectMappingUtils.getObjectFromBody(webClientResponse.body, Metrics::class.java)
val mapOfMetricsInfo = HashMap<String, String>()
return body
}
}
-
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi
-
import org.junit.Test
import org.junit.runner.RunWith
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration
*/
@RunWith(SpringRunner::class)
@WebFluxTest
-@ContextConfiguration(classes = [BluePrintRuntimeService::class, BluePrintCoreConfiguration::class,
- BluePrintCatalogService::class, SecurityProperties::class, ComponentScriptExecutor::class])
+@ContextConfiguration(
+ classes = [BluePrintRuntimeService::class, BluePrintCoreConfiguration::class,
+ BluePrintCatalogService::class, SecurityProperties::class, ComponentScriptExecutor::class]
+)
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
@TestPropertySource(locations = ["classpath:application-test.properties"])
class HealthCheckApplicationTests {
@Test
fun testHealthApiUp() {
webTestClient.get().uri("/api/v1/combinedHealth")
- .exchange()
- .expectStatus().is2xxSuccessful
-
+ .exchange()
+ .expectStatus().is2xxSuccessful
}
@Test
fun testMetricsApiUp() {
webTestClient.get().uri("/api/v1/combinedMetrics")
- .exchange()
- .expectStatus().is2xxSuccessful
+ .exchange()
+ .expectStatus().is2xxSuccessful
}
-
-
}
<artifactId>resource-resolution</artifactId>
</dependency>
-
<!-- Test Dependencies -->
<dependency>
<groupId>io.mockk</groupId>
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestMethod
+import org.springframework.web.bind.annotation.RequestParam
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/v1/resources")
-@Api(value = "/api/v1/resources",
- description = "Interaction with resolved resources.")
+@Api(
+ value = "/api/v1/resources",
+ description = "Interaction with resolved resources."
+)
open class ResourceController(private var resourceResolutionDBService: ResourceResolutionDBService) {
- @RequestMapping(path = ["/health-check"],
+ @RequestMapping(
+ path = ["/health-check"],
method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun resourceControllerHealthCheck(): JsonNode = runBlocking {
JacksonUtils.getJsonNode("Success")
}
- @RequestMapping(path = [""],
- method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Get all resolved resources using the resolution key. ",
+ @RequestMapping(
+ path = [""],
+ method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
+ @ApiOperation(
+ value = "Get all resolved resources using the resolution key. ",
notes = "Retrieve all stored resolved resources using the blueprint name, blueprint version, " +
"artifact name and the resolution-key.",
response = ResourceResolution::class,
responseContainer = "List",
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun getAllFromResolutionKeyOrFromResourceTypeAndId(
@ApiParam(value = "Resource Type associated with the resolution.", required = false)
@RequestParam(value = "resourceType", required = false, defaultValue = "") resourceType: String,
@ApiParam(value = "Resource Id associated with the resolution.", required = false)
- @RequestParam(value = "resourceId", required = false, defaultValue = "") resourceId: String)
- : ResponseEntity<List<ResourceResolution>> = runBlocking {
+ @RequestParam(value = "resourceId", required = false, defaultValue = "") resourceId: String
+ ):
+ ResponseEntity<List<ResourceResolution>> = runBlocking {
if ((resolutionKey.isNotEmpty() || artifactName.isNotEmpty()) && (resourceId.isNotEmpty() || resourceType.isNotEmpty())) {
throw ResolutionException("Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.")
.body(resourceResolutionDBService.readWithResolutionKey(bpName, bpVersion, artifactName, resolutionKey))
} else if (resourceType.isNotEmpty() && resourceId.isNotEmpty()) {
ResponseEntity.ok()
- .body(resourceResolutionDBService.readWithResourceIdAndResourceType(bpName,
- bpVersion,
- resourceId,
- resourceType))
+ .body(
+ resourceResolutionDBService.readWithResourceIdAndResourceType(
+ bpName,
+ bpVersion,
+ resourceId,
+ resourceType
+ )
+ )
} else {
throw ResolutionException("Missing param. Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.")
}
}
- @RequestMapping(path = ["/resource"],
+ @RequestMapping(
+ path = ["/resource"],
method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Fetch a resource value using resolution key.",
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
+ @ApiOperation(
+ value = "Fetch a resource value using resolution key.",
notes = "Retrieve a stored resource value using the blueprint metadata, artifact name, resolution-key along with the name of the resource value to retrieve.",
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
- fun getOneFromResolutionKey(@ApiParam(value = "Name of the CBA.", required = true)
- @RequestParam(value = "bpName", required = true) bpName: String,
- @ApiParam(value = "Version of the CBA.", required = true)
- @RequestParam(value = "bpVersion", required = true) bpVersion: String,
- @ApiParam(value = "Artifact name for which to retrieve a resolved resource.", required = true)
- @RequestParam(value = "artifactName", required = true) artifactName: String,
- @ApiParam(value = "Resolution Key associated with the resolution.", required = true)
- @RequestParam(value = "resolutionKey", required = true) resolutionKey: String,
- @ApiParam(value = "Name of the resource to retrieve.", required = true)
- @RequestParam(value = "name", required = true) name: String)
- : ResponseEntity<ResourceResolution> = runBlocking {
+ fun getOneFromResolutionKey(
+ @ApiParam(value = "Name of the CBA.", required = true)
+ @RequestParam(value = "bpName", required = true) bpName: String,
+ @ApiParam(value = "Version of the CBA.", required = true)
+ @RequestParam(value = "bpVersion", required = true) bpVersion: String,
+ @ApiParam(value = "Artifact name for which to retrieve a resolved resource.", required = true)
+ @RequestParam(value = "artifactName", required = true) artifactName: String,
+ @ApiParam(value = "Resolution Key associated with the resolution.", required = true)
+ @RequestParam(value = "resolutionKey", required = true) resolutionKey: String,
+ @ApiParam(value = "Name of the resource to retrieve.", required = true)
+ @RequestParam(value = "name", required = true) name: String
+ ):
+ ResponseEntity<ResourceResolution> = runBlocking {
ResponseEntity.ok()
.body(resourceResolutionDBService.readValue(bpName, bpVersion, artifactName, resolutionKey, name))
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
import org.slf4j.LoggerFactory
+import org.springframework.dao.EmptyResultDataAccessException
+import org.springframework.dao.IncorrectResultSizeDataAccessException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.orm.jpa.JpaObjectRetrievalFailureException
-import org.springframework.dao.EmptyResultDataAccessException
-import org.springframework.dao.IncorrectResultSizeDataAccessException
-import org.springframework.web.server.ServerWebInputException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
+import org.springframework.web.server.ServerWebInputException
import java.io.Serializable
-import java.util.*
+import java.util.Date
/**
* Handle exceptions in Resolution API and provide relevant HTTP status codes and messages
fun returnError(e: Exception, errorCode: ErrorCode): ResponseEntity<ErrorMessage> {
log.error(e.message, e)
val errorMessage =
- ErrorMessage(errorCode.message(e.message!!),
+ ErrorMessage(
+ errorCode.message(e.message!!),
errorCode.value,
- debugMsg)
+ debugMsg
+ )
return ResponseEntity(errorMessage, HttpStatus.resolve(errorCode.httpCode)!!)
}
@JsonTypeName("errorMessage")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
class ErrorMessage(var message: String?, var code: Int?, var debugMessage: String?) : Serializable {
+
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
var timestamp = Date()
-}
\ No newline at end of file
+}
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestMethod
+import org.springframework.web.bind.annotation.RequestParam
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
/**
* Exposes Template Resolution API to store and retrieve rendered template results.
*/
@RestController
@RequestMapping("/api/v1/template")
-@Api(value = "/api/v1/template",
- description = "Interaction with resolved template.")
+@Api(
+ value = "/api/v1/template",
+ description = "Interaction with resolved template."
+)
open class TemplateController(private val templateResolutionService: TemplateResolutionService) {
- @RequestMapping(path = ["/health-check"],
+ @RequestMapping(
+ path = ["/health-check"],
method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun templateControllerHealthCheck(): JsonNode = runBlocking {
JacksonUtils.getJsonNode("Success")
}
- @RequestMapping(path = [""],
+ @RequestMapping(
+ path = [""],
method = [RequestMethod.GET],
- produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE])
- @ApiOperation(value = "Retrieve a resolved template.",
+ produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE]
+ )
+ @ApiOperation(
+ value = "Retrieve a resolved template.",
notes = "Retrieve a config template for a given CBA's action, identified by its blueprint name, blueprint version, " +
"artifact name and resolution key. An extra 'format' parameter can be passed to tell what content-type" +
- " to expect in return")
+ " to expect in return"
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun get(
@RequestParam(value = "resourceType", required = false, defaultValue = "") resourceType: String,
@ApiParam(value = "Resource Id associated with the resolution.", required = false)
@RequestParam(value = "resourceId", required = false, defaultValue = "") resourceId: String,
- @ApiParam(value = "Expected format of the template being retrieved.",
+ @ApiParam(
+ value = "Expected format of the template being retrieved.",
defaultValue = MediaType.TEXT_PLAIN_VALUE,
- required = true)
- @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String)
- : ResponseEntity<String> = runBlocking {
+ required = true
+ )
+ @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String
+ ):
+ ResponseEntity<String> = runBlocking {
var result = ""
bpName,
bpVersion,
artifactName,
- resolutionKey)
+ resolutionKey
+ )
} else if (resourceType.isNotEmpty() && resourceId.isNotEmpty()) {
result =
templateResolutionService.findByResoureIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactName(
bpVersion,
artifactName,
resourceId,
- resourceType)
+ resourceType
+ )
} else {
throw ResolutionException("Missing param. Either retrieve resolved template using artifact name and resolution-key OR using resource-id and resource-type.")
}
-
var expectedContentType = format
if (expectedContentType.indexOf('/') < 0) {
expectedContentType = "application/$expectedContentType"
ResponseEntity.ok().contentType(expectedMediaType).body(result)
}
-
@PostMapping("/{bpName}/{bpVersion}/{artifactName}/{resolutionKey}", produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Store a resolved template w/ resolution-key",
+ @ApiOperation(
+ value = "Store a resolved template w/ resolution-key",
notes = "Store a template for a given CBA's action, identified by its blueprint name, blueprint version, " +
"artifact name and resolution key.",
response = TemplateResolution::class,
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun postWithResolutionKey(
@ApiParam(value = "Resolution Key associated with the resolution.", required = true)
@PathVariable(value = "resolutionKey") resolutionKey: String,
@ApiParam(value = "Template to store.", required = true)
- @RequestBody result: String): ResponseEntity<TemplateResolution> = runBlocking {
+ @RequestBody result: String
+ ): ResponseEntity<TemplateResolution> = runBlocking {
val resultStored =
templateResolutionService.write(bpName, bpVersion, artifactName, result, resolutionKey = resolutionKey)
ResponseEntity.ok().body(resultStored)
}
- @PostMapping("/{bpName}/{bpVersion}/{artifactName}/{resourceType}/{resourceId}",
- produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Store a resolved template w/ resourceId and resourceType",
+ @PostMapping(
+ "/{bpName}/{bpVersion}/{artifactName}/{resourceType}/{resourceId}",
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
+ @ApiOperation(
+ value = "Store a resolved template w/ resourceId and resourceType",
notes = "Store a template for a given CBA's action, identified by its blueprint name, blueprint version, " +
"artifact name, resourceId and resourceType.",
response = TemplateResolution::class,
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun postWithResourceIdAndResourceType(
@ApiParam(value = "Resource Id associated with the resolution.", required = false)
@PathVariable(value = "resourceId", required = true) resourceId: String,
@ApiParam(value = "Template to store.", required = true)
- @RequestBody result: String): ResponseEntity<TemplateResolution> = runBlocking {
+ @RequestBody result: String
+ ): ResponseEntity<TemplateResolution> = runBlocking {
val resultStored =
templateResolutionService.write(bpName, bpVersion, artifactName, result, resourceId = resourceId, resourceType = resourceType)
import org.junit.runner.RunWith
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolution
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolutionDBService
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.reactive.server.WebTestClient
-import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
-
@RunWith(SpringRunner::class)
@WebFluxTest
.consumeWith {
val json = String(it.responseBody!!)
val typeFactory = JacksonUtils.objectMapper.typeFactory
- val list: List<ResourceResolution> = JacksonUtils.objectMapper.readValue(json,
- typeFactory.constructCollectionType(List::class.java, ResourceResolution::class.java))
+ val list: List<ResourceResolution> = JacksonUtils.objectMapper.readValue(
+ json,
+ typeFactory.constructCollectionType(List::class.java, ResourceResolution::class.java)
+ )
Assert.assertEquals(2, list.size)
assertEqual(ra1, list[0])
assertEqual(ra1, list[0])
.consumeWith {
val json = String(it.responseBody!!)
val typeFactory = JacksonUtils.objectMapper.typeFactory
- val list: List<ResourceResolution> = JacksonUtils.objectMapper.readValue(json,
- typeFactory.constructCollectionType(List::class.java, ResourceResolution::class.java))
+ val list: List<ResourceResolution> = JacksonUtils.objectMapper.readValue(
+ json,
+ typeFactory.constructCollectionType(List::class.java, ResourceResolution::class.java)
+ )
Assert.assertEquals(2, list.size)
assertEqual(ra1, list[0])
assertEqual(ra1, list[0])
}
}
-
@Test
fun getAllFromMissingParamTest() {
runBlocking {
.expectBody()
.consumeWith {
val r = JacksonUtils.objectMapper.readValue(it.responseBody, ErrorMessage::class.java)
- Assert.assertEquals("Missing param. Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.",
- r.message)
+ Assert.assertEquals(
+ "Missing param. Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.",
+ r.message
+ )
}
}
}
.expectBody()
.consumeWith {
val r = JacksonUtils.objectMapper.readValue(it.responseBody, ErrorMessage::class.java)
- Assert.assertEquals("Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.",
- r.message)
+ Assert.assertEquals(
+ "Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.",
+ r.message
+ )
}
}
}
}
}
- private suspend fun store(resourceAssignment: ResourceAssignment, resKey: String = "", resId: String = "",
- resType: String = "") {
- resourceResolutionDBService.write(blueprintName,
+ private suspend fun store(
+ resourceAssignment: ResourceAssignment,
+ resKey: String = "",
+ resId: String = "",
+ resType: String = ""
+ ) {
+ resourceResolutionDBService.write(
+ blueprintName,
blueprintVersion,
resKey,
resId,
resType,
templatePrefix,
- resourceAssignment)
+ resourceAssignment
+ )
}
private fun createRA(prefix: String): ResourceAssignment {
}
private fun assertEqual(resourceAssignment: ResourceAssignment, resourceResolution: ResourceResolution) {
- Assert.assertEquals(JacksonUtils.getValue(resourceAssignment.property?.value!!).toString(),
- resourceResolution.value)
+ Assert.assertEquals(
+ JacksonUtils.getValue(resourceAssignment.property?.value!!).toString(),
+ resourceResolution.value
+ )
Assert.assertEquals(resourceAssignment.status, resourceResolution.status)
Assert.assertEquals(resourceAssignment.dictionarySource, resourceResolution.dictionarySource)
Assert.assertEquals(resourceAssignment.dictionaryName, resourceResolution.dictionaryName)
Assert.assertEquals(resourceAssignment.name, resourceResolution.name)
Assert.assertEquals(blueprintVersion, resourceResolution.blueprintVersion)
Assert.assertEquals(blueprintName, resourceResolution.blueprintName)
-
}
-}
\ No newline at end of file
+}
@RunWith(SpringRunner::class)
@WebFluxTest
-@ContextConfiguration(classes = [BluePrintCoreConfiguration::class,
- BluePrintCatalogService::class, SecurityProperties::class])
+@ContextConfiguration(
+ classes = [BluePrintCoreConfiguration::class,
+ BluePrintCatalogService::class, SecurityProperties::class]
+)
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
@TestPropertySource(locations = ["classpath:application-test.properties"])
class TemplateControllerTest {
webTestClient
.get()
- .uri("/api/v1/template?bpName=$blueprintName&bpVersion=$blueprintVersion" +
- "&artifactName=$templatePrefix&resolutionKey=notFound")
+ .uri(
+ "/api/v1/template?bpName=$blueprintName&bpVersion=$blueprintVersion" +
+ "&artifactName=$templatePrefix&resolutionKey=notFound"
+ )
.exchange()
.expectStatus().isNotFound
}
.expectBody().equals(payloadDummyTemplateData)
}
}
-}
\ No newline at end of file
+}
import javax.annotation.PreDestroy
@Service
-open class BluePrintProcessingGRPCHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration,
- private val executionServiceHandler: ExecutionServiceHandler)
- : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() {
+open class BluePrintProcessingGRPCHandler(
+ private val bluePrintCoreConfiguration: BluePrintCoreConfiguration,
+ private val executionServiceHandler: ExecutionServiceHandler
+) :
+ BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() {
+
private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandler::class.java)
private val ph = Phaser(1)
@PreAuthorize("hasRole('USER')")
override fun process(
- responseObserver: StreamObserver<ExecutionServiceOutput>): StreamObserver<ExecutionServiceInput> {
+ responseObserver: StreamObserver<ExecutionServiceOutput>
+ ): StreamObserver<ExecutionServiceInput> {
return object : StreamObserver<ExecutionServiceInput> {
override fun onNext(executionServiceInput: ExecutionServiceInput) {
}
} catch (e: Exception) {
onError(e)
- }
- finally {
+ } finally {
ph.arriveAndDeregister()
}
}
override fun onError(error: Throwable) {
log.debug("Fail to process message", error)
- responseObserver.onError(io.grpc.Status.INTERNAL
+ responseObserver.onError(
+ io.grpc.Status.INTERNAL
.withDescription(error.message)
- .asException())
+ .asException()
+ )
}
override fun onCompleted() {
ph.arriveAndAwaitAdvance()
log.info("Done waiting in $name")
}
-}
\ No newline at end of file
+}
import java.util.concurrent.Phaser
import javax.annotation.PreDestroy
-@ConditionalOnProperty(name = ["blueprintsprocessor.messageconsumer.self-service-api.kafkaEnable"],
- havingValue = "true")
+@ConditionalOnProperty(
+ name = ["blueprintsprocessor.messageconsumer.self-service-api.kafkaEnable"],
+ havingValue = "true"
+)
@Service
open class BluePrintProcessingKafkaConsumer(
- private val bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService,
- private val executionServiceHandler: ExecutionServiceHandler) {
+ private val bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService,
+ private val executionServiceHandler: ExecutionServiceHandler
+) {
val log = logger(BluePrintProcessingKafkaConsumer::class)
@EventListener(ApplicationReadyEvent::class)
fun setupMessageListener() = runBlocking {
try {
- log.info("Setting up message consumer($CONSUMER_SELECTOR) and " +
- "message producer($PRODUCER_SELECTOR)...")
+ log.info(
+ "Setting up message consumer($CONSUMER_SELECTOR) and " +
+ "message producer($PRODUCER_SELECTOR)..."
+ )
/** Get the Message Consumer Service **/
blueprintMessageConsumerService = try {
bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService(CONSUMER_SELECTOR)
+ .blueprintMessageConsumerService(CONSUMER_SELECTOR)
} catch (e: Exception) {
throw BluePrintProcessorException("failed to create consumer service ${e.message}")
}
/** Get the Message Producer Service **/
val blueprintMessageProducerService = try {
bluePrintMessageLibPropertyService
- .blueprintMessageProducerService(PRODUCER_SELECTOR)
+ .blueprintMessageProducerService(PRODUCER_SELECTOR)
} catch (e: Exception) {
throw BluePrintProcessorException("failed to create producer service ${e.message}")
}
log.trace("Consumed Message : $message")
val executionServiceInput = message.jsonAsType<ExecutionServiceInput>()
val executionServiceOutput = executionServiceHandler.doProcess(executionServiceInput)
- //TODO("In future, Message publisher configuration vary with respect to request")
+ // TODO("In future, Message publisher configuration vary with respect to request")
/** Send the response message */
blueprintMessageProducerService.sendMessage(executionServiceOutput)
} catch (e: Exception) {
log.error("failed in processing the consumed message : $message", e)
- }
- finally {
+ } finally {
ph.arriveAndDeregister()
}
}
}
}
} catch (e: Exception) {
- log.error("failed to start message consumer($CONSUMER_SELECTOR) and " +
- "message producer($PRODUCER_SELECTOR) ", e)
+ log.error(
+ "failed to start message consumer($CONSUMER_SELECTOR) and " +
+ "message producer($PRODUCER_SELECTOR) ", e
+ )
}
}
@PreDestroy
fun shutdownMessageListener() = runBlocking {
try {
- log.info("Shutting down message consumer($CONSUMER_SELECTOR) and " +
- "message producer($PRODUCER_SELECTOR)...")
+ log.info(
+ "Shutting down message consumer($CONSUMER_SELECTOR) and " +
+ "message producer($PRODUCER_SELECTOR)..."
+ )
blueprintMessageConsumerService.shutDown()
ph.arriveAndAwaitAdvance()
} catch (e: Exception) {
log.error("failed to shutdown message listener($CONSUMER_SELECTOR)", e)
}
}
-
-}
\ No newline at end of file
+}
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestMethod
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
import java.util.concurrent.Phaser
import javax.annotation.PreDestroy
@RestController
@RequestMapping("/api/v1/execution-service")
-@Api(value = "/api/v1/execution-service",
- description = "Interaction with CBA.")
+@Api(
+ value = "/api/v1/execution-service",
+ description = "Interaction with CBA."
+)
open class ExecutionServiceController {
+
val log = logger(ExecutionServiceController::class)
private val ph = Phaser(1)
@Autowired
lateinit var executionServiceHandler: ExecutionServiceHandler
- @RequestMapping(path = ["/health-check"],
- method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ @RequestMapping(
+ path = ["/health-check"],
+ method = [RequestMethod.GET],
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun executionServiceControllerHealthCheck() = monoMdc(Dispatchers.IO) {
}
@RequestMapping(path = ["/process"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Execute a CBA workflow (action)",
- notes = "Execute the appropriate CBA's action based on the ExecutionServiceInput object passed as input.",
- produces = MediaType.APPLICATION_JSON_VALUE,
- response = ExecutionServiceOutput::class)
+ @ApiOperation(
+ value = "Execute a CBA workflow (action)",
+ notes = "Execute the appropriate CBA's action based on the ExecutionServiceInput object passed as input.",
+ produces = MediaType.APPLICATION_JSON_VALUE,
+ response = ExecutionServiceOutput::class
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
- fun process(@ApiParam(value = "ExecutionServiceInput payload.", required = true)
- @RequestBody executionServiceInput: ExecutionServiceInput)
- : Mono<ResponseEntity<ExecutionServiceOutput>> = monoMdc(Dispatchers.IO) {
+ fun process(
+ @ApiParam(value = "ExecutionServiceInput payload.", required = true)
+ @RequestBody executionServiceInput: ExecutionServiceInput
+ ):
+ Mono<ResponseEntity<ExecutionServiceOutput>> = monoMdc(Dispatchers.IO) {
if (executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC) {
throw IllegalStateException("Can't process async request through the REST endpoint. Use gRPC for async processing.")
log.info("Done waiting in $name")
}
}
-
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
-import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_ASYNC
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.toProto
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractServiceFunction
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
import java.util.stream.Collectors
@Service
-class ExecutionServiceHandler(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val blueprintsProcessorCatalogService: BluePrintCatalogService,
- private val bluePrintWorkflowExecutionService
- : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput>) {
+class ExecutionServiceHandler(
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val blueprintsProcessorCatalogService: BluePrintCatalogService,
+ private val bluePrintWorkflowExecutionService:
+ BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput>
+) {
private val log = LoggerFactory.getLogger(ExecutionServiceHandler::class.toString())
- suspend fun process(executionServiceInput: ExecutionServiceInput,
- responseObserver: StreamObserver<org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput>) {
+ suspend fun process(
+ executionServiceInput: ExecutionServiceInput,
+ responseObserver: StreamObserver<org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput>
+ ) {
when {
executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC -> {
GlobalScope.launch(Dispatchers.Default) {
responseObserver.onNext(executionServiceOutput.toProto())
responseObserver.onCompleted()
}
- else -> responseObserver.onNext(response(executionServiceInput,
+ else -> responseObserver.onNext(
+ response(
+ executionServiceInput,
"Failed to process request, 'actionIdentifiers.mode' not specified. Valid value are: 'sync' or 'async'.",
- true).toProto());
+ true
+ ).toProto()
+ )
}
}
val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString())
- val output = bluePrintWorkflowExecutionService.executeBluePrintWorkflow(blueprintRuntimeService,
- executionServiceInput, hashMapOf())
+ val output = bluePrintWorkflowExecutionService.executeBluePrintWorkflow(
+ blueprintRuntimeService,
+ executionServiceInput, hashMapOf()
+ )
val errors = blueprintRuntimeService.getBluePrintError().errors
if (errors.isNotEmpty()) {
status.message = BluePrintConstants.STATUS_FAILURE
}
- private fun response(executionServiceInput: ExecutionServiceInput, errorMessage: String = "",
- failure: Boolean = false): ExecutionServiceOutput {
+ private fun response(
+ executionServiceInput: ExecutionServiceInput,
+ errorMessage: String = "",
+ failure: Boolean = false
+ ): ExecutionServiceOutput {
val executionServiceOutput = ExecutionServiceOutput()
executionServiceOutput.commonHeader = executionServiceInput.commonHeader
executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers
return executionServiceOutput
}
-
}
import java.io.File
import java.io.IOException
import java.nio.file.Path
-import java.util.*
+import java.util.UUID
const val INTERNAL_SERVER_ERROR_HTTP_STATUS_CODE = 500
try {
return HttpStatus.valueOf(statusCode)
} catch (exception: Exception) {
- //if statusCode cannot be converted to a proper HttpStatus, the resource still needs to assign a HTTP status
+ // if statusCode cannot be converted to a proper HttpStatus, the resource still needs to assign a HTTP status
// code to the response. In this case, a 500 Internal Server Error will be returned as default.
return HttpStatus.valueOf(INTERNAL_SERVER_ERROR_HTTP_STATUS_CODE)
}
-}
\ No newline at end of file
+}
import org.springframework.stereotype.Service
@Service("bluePrintRuntimeValidatorService")
-open class BluePrintRuntimeValidatorService(bluePrintTypeValidatorService: BluePrintTypeValidatorService,
- resourceDefinitionValidator: ResourceDefinitionValidator)
- : BluePrintDesignTimeValidatorService(bluePrintTypeValidatorService, resourceDefinitionValidator)
+open class BluePrintRuntimeValidatorService(
+ bluePrintTypeValidatorService: BluePrintTypeValidatorService,
+ resourceDefinitionValidator: ResourceDefinitionValidator
+) :
+ BluePrintDesignTimeValidatorService(bluePrintTypeValidatorService, resourceDefinitionValidator)
package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api
-
import com.google.protobuf.util.JsonFormat
import io.grpc.stub.StreamObserver
import io.grpc.testing.GrpcServerRule
@RunWith(SpringRunner::class)
@DirtiesContext
@EnableAutoConfiguration
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
- "org.onap.ccsdk.cds.controllerblueprints"])
+@ComponentScan(
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
+ "org.onap.ccsdk.cds.controllerblueprints"]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BluePrintProcessingGRPCHandlerTest {
+
private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandlerTest::class.java)
@get:Rule
override fun onNext(executionServiceOuput: ExecutionServiceOutput) {
log.debug("onNext {}", executionServiceOuput)
if ("1234".equals(executionServiceOuput.commonHeader.requestId)) {
- Assert.assertEquals("Failed to process request, \'actionIdentifiers.mode\' not specified. Valid value are: \'sync\' or \'async\'.", executionServiceOuput.status.errorMessage)
+ Assert.assertEquals(
+ "Failed to process request, \'actionIdentifiers.mode\' not specified. Valid value are: \'sync\' or \'async\'.",
+ executionServiceOuput.status.errorMessage
+ )
}
}
@Test
fun testSelfServiceGRPCHandler() {
val commonHeader = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId("1234")
- .setSubRequestId("1234-56").build()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId("1234")
+ .setSubRequestId("1234-56").build()
val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json")
val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder
JsonFormat.parser().merge(jsonContent, payloadBuilder)
val input = ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setPayload(payloadBuilder.build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setPayload(payloadBuilder.build())
+ .build()
requestObs.onNext(input)
val commonHeader2 = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId("2345")
- .setSubRequestId("1234-56").build()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId("2345")
+ .setSubRequestId("1234-56").build()
val actionIdentifier = ActionIdentifiers.newBuilder().setMode("sync").build()
val input2 = ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader2)
- .setActionIdentifiers(actionIdentifier)
- .setPayload(payloadBuilder.build())
- .build()
+ .setCommonHeader(commonHeader2)
+ .setActionIdentifiers(actionIdentifier)
+ .setPayload(payloadBuilder.build())
+ .build()
requestObs.onNext(input2)
requestObs.onCompleted()
}
-
-}
\ No newline at end of file
+}
private val log = logger(BluePrintProcessingIntegrationTest::class)
/** This is Integration test sample, Do not enable this test case in server build, this is for local desktop testing*/
- //@Test
+ // @Test
fun integrationTestGrpcManagement() {
runBlocking {
val tokenAuthGrpcClientProperties = TokenAuthGrpcClientProperties().apply {
})
val commonHeader = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId("1234-$it")
- .setSubRequestId("1234-56").build()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId("1234-$it")
+ .setSubRequestId("1234-56").build()
val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json")
val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder
JsonFormat.parser().merge(jsonContent, payloadBuilder)
val actionIdentifier = ActionIdentifiers.newBuilder()
- .setActionName("SampleScript")
- .setBlueprintName("sample-cba")
- .setBlueprintVersion("1.0.0")
- .build()
+ .setActionName("SampleScript")
+ .setBlueprintName("sample-cba")
+ .setBlueprintVersion("1.0.0")
+ .build()
val input = ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(actionIdentifier)
- .setPayload(payloadBuilder.build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setPayload(payloadBuilder.build())
+ .build()
requestObs.onNext(input)
requestObs.onCompleted()
channel.shutdownNow()
}
}
-}
\ No newline at end of file
+}
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintMessageLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
+@ContextConfiguration(
+ classes = [BluePrintMessageLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BluePrintProcessingKafkaConsumerTest {
@Test
fun testExecutionInputMessageConsumer() {
runBlocking {
- assertNotNull(bluePrintMessageLibPropertyService,
- "failed to initialise bluePrintMessageLibPropertyService")
+ assertNotNull(
+ bluePrintMessageLibPropertyService,
+ "failed to initialise bluePrintMessageLibPropertyService"
+ )
val executionServiceHandle = mockk<ExecutionServiceHandler>()
coEvery { executionServiceHandle.doProcess(any()) } returns mockk()
- val bluePrintProcessingKafkaConsumer = BluePrintProcessingKafkaConsumer(bluePrintMessageLibPropertyService,
- executionServiceHandle)
+ val bluePrintProcessingKafkaConsumer = BluePrintProcessingKafkaConsumer(
+ bluePrintMessageLibPropertyService,
+ executionServiceHandle
+ )
launch {
bluePrintProcessingKafkaConsumer.setupMessageListener()
bluePrintProcessingKafkaConsumer.shutdownMessageListener()
}
}
-
-}
\ No newline at end of file
+}
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.web.reactive.function.BodyInserters
import java.io.File
-import java.util.*
+import java.util.UUID
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.assertTrue
@RunWith(SpringRunner::class)
@WebFluxTest
-@ContextConfiguration(classes = [ExecutionServiceHandler::class, BluePrintCoreConfiguration::class,
- BluePrintCatalogService::class, SecurityProperties::class])
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
- "org.onap.ccsdk.cds.controllerblueprints"])
+@ContextConfiguration(
+ classes = [ExecutionServiceHandler::class, BluePrintCoreConfiguration::class,
+ BluePrintCatalogService::class, SecurityProperties::class]
+)
+@ComponentScan(
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
+ "org.onap.ccsdk.cds.controllerblueprints"]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class ExecutionServiceControllerTest {
blueprintsProcessorCatalogService.saveToDatabase(UUID.randomUUID().toString(), loadTestCbaFile())
val executionServiceInput = JacksonUtils
- .readValueFromClassPathFile("execution-input/default-input.json",
- ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile(
+ "execution-input/default-input.json",
+ ExecutionServiceInput::class.java
+ )!!
webTestClient
- .post()
- .uri("/api/v1/execution-service/process")
- .body(BodyInserters.fromObject(executionServiceInput))
- .exchange()
- .expectStatus().isOk
+ .post()
+ .uri("/api/v1/execution-service/process")
+ .body(BodyInserters.fromObject(executionServiceInput))
+ .exchange()
+ .expectStatus().isOk
}
}
blueprintsProcessorCatalogService.saveToDatabase(UUID.randomUUID().toString(), loadTestCbaFile())
val executionServiceInput = JacksonUtils
- .readValueFromClassPathFile("execution-input/faulty-input.json",
- ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile(
+ "execution-input/faulty-input.json",
+ ExecutionServiceInput::class.java
+ )!!
webTestClient
- .post()
- .uri("/api/v1/execution-service/process")
- .body(BodyInserters.fromObject(executionServiceInput))
- .exchange()
- .expectStatus().is5xxServerError
+ .post()
+ .uri("/api/v1/execution-service/process")
+ .body(BodyInserters.fromObject(executionServiceInput))
+ .exchange()
+ .expectStatus().is5xxServerError
}
}
assertTrue(testCbaFile.exists(), "couldn't get file ${testCbaFile.absolutePath}")
return testCbaFile
}
-}
\ No newline at end of file
+}
@Service("mock-service-action")
class MockServiceAction : AbstractServiceFunction() {
+
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
val responsePayload = """{"answer" : "correct"}""".jsonAsJsonType()
setResponsePayloadForAction(responsePayload)
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
-
}
-}
\ No newline at end of file
+}
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
log.info("Processing component : $operationInputs")
- bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName,
- "assignment-params", "params".asJsonPrimitive())
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ nodeTemplateName,
+ "assignment-params", "params".asJsonPrimitive()
+ )
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
}
open class MockResourceSource {
- @Bean(name = [
- "rr-processor-source-input",
- "rr-processor-source-default",
- "rr-processor-source-db",
- "rr-processor-source-rest"])
+ @Bean(
+ name = [
+ "rr-processor-source-input",
+ "rr-processor-source-default",
+ "rr-processor-source-db",
+ "rr-processor-source-rest"]
+ )
open fun sourceInstance(): ResourceAssignmentProcessor {
return mockk<ResourceAssignmentProcessor>()
}
-
}
val nonExistentHttpStatusCode = determineHttpStatusCode(999999)
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, nonExistentHttpStatusCode)
}
-
-}
\ No newline at end of file
+}
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintRuntimeValidatorService::class,
- BluePrintValidationConfiguration::class, MockResourceSource::class])
+@ContextConfiguration(
+ classes = [BluePrintRuntimeValidatorService::class,
+ BluePrintValidationConfiguration::class, MockResourceSource::class]
+)
class BluePrintRuntimeValidatorServiceTest {
@Autowired
assertNotNull(bluePrintRuntimeValidatorService, " failed to initilize bluePrintRuntimeValidatorService")
bluePrintRuntimeValidatorService.validateBluePrints(blueprintBasePath)
-
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.services.execution
-
import com.fasterxml.jackson.databind.JsonNode
import kotlinx.coroutines.withTimeout
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
+import org.onap.ccsdk.cds.controllerblueprints.core.getAsString
+import org.onap.ccsdk.cds.controllerblueprints.core.getOptionalAsInt
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.readNBLines
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
import org.slf4j.LoggerFactory
* @author Brinda Santh
*/
abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServiceInput, ExecutionServiceOutput> {
+
@Transient
private val log = LoggerFactory.getLogger(AbstractComponentFunction::class.java)
check(operationName.isNotEmpty()) { "couldn't get Operation name for step($stepName)" }
val operationResolvedProperties = bluePrintRuntimeService
- .resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName)
+ .resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName)
this.operationInputs.putAll(operationResolvedProperties)
try {
// Resolve the Output Expression
val stepOutputs = bluePrintRuntimeService
- .resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName)
+ .resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName)
val stepOutputData = StepData().apply {
name = stepName
fun getOperationInput(key: String): JsonNode {
return operationInputs[key]
- ?: throw BluePrintProcessorException("couldn't get the operation input($key) value.")
+ ?: throw BluePrintProcessorException("couldn't get the operation input($key) value.")
}
fun getOptionalOperationInput(key: String): JsonNode? {
val file = normalizedFile(bluePrintRuntimeService.bluePrintContext().rootPath, artifactDefinition.file)
return file.readNBLines()
}
-
-}
\ No newline at end of file
+}
@Deprecated("Dependencies will be resolved dynamically")
open fun <T> functionDependencyInstanceAsType(name: String): T {
return functionDependencyInstances[name] as? T
- ?: throw BluePrintProcessorException("couldn't get script property instance ($name)")
+ ?: throw BluePrintProcessorException("couldn't get script property instance ($name)")
}
fun checkDynamicProperties(key: String): Boolean {
override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
throw BluePrintException("Not Implemented, child class will implement this")
}
-}
\ No newline at end of file
+}
}
return executionServiceInput.payload.jsonPathParse(".$requestExpression")
}
-}
\ No newline at end of file
+}
import org.springframework.stereotype.Service
@Service
-class ComponentFunctionScriptingService(private val applicationContext: ApplicationContext,
- private val blueprintJythonService: BlueprintJythonService) {
+class ComponentFunctionScriptingService(
+ private val applicationContext: ApplicationContext,
+ private val blueprintJythonService: BlueprintJythonService
+) {
private val log = LoggerFactory.getLogger(ComponentFunctionScriptingService::class.java)
- suspend fun <T : AbstractScriptComponentFunction> scriptInstance(componentFunction: AbstractComponentFunction,
- scriptType: String,
- scriptClassReference: String,
- instanceDependencies: List<String>): T {
+ suspend fun <T : AbstractScriptComponentFunction> scriptInstance(
+ componentFunction: AbstractComponentFunction,
+ scriptType: String,
+ scriptClassReference: String,
+ instanceDependencies: List<String>
+ ): T {
- log.info("creating component function of script type($scriptType), reference name($scriptClassReference) and " +
- "instanceDependencies($instanceDependencies)")
+ log.info(
+ "creating component function of script type($scriptType), reference name($scriptClassReference) and " +
+ "instanceDependencies($instanceDependencies)"
+ )
- val scriptComponent: T = scriptInstance(componentFunction.bluePrintRuntimeService.bluePrintContext(),
- scriptType, scriptClassReference)
+ val scriptComponent: T = scriptInstance(
+ componentFunction.bluePrintRuntimeService.bluePrintContext(),
+ scriptType, scriptClassReference
+ )
checkNotNull(scriptComponent) { "failed to initialize script component" }
// Populate Instance Properties
instanceDependencies.forEach { instanceDependency ->
scriptComponent.functionDependencyInstances[instanceDependency] = applicationContext
- .getBean(instanceDependency)
+ .getBean(instanceDependency)
}
return scriptComponent
}
-
- suspend fun <T : BlueprintFunctionNode<*, *>> scriptInstance(bluePrintContext: BluePrintContext, scriptType: String,
- scriptClassReference: String): T {
+ suspend fun <T : BlueprintFunctionNode<*, *>> scriptInstance(
+ bluePrintContext: BluePrintContext,
+ scriptType: String,
+ scriptClassReference: String
+ ): T {
var scriptComponent: T? = null
when (scriptType) {
}
BluePrintConstants.SCRIPT_KOTLIN -> {
val bluePrintScriptsService: BluePrintScriptsService = BluePrintScriptsServiceImpl()
- scriptComponent = bluePrintScriptsService.scriptInstance<T>(bluePrintContext.rootPath,
- bluePrintContext.name(), bluePrintContext.version(), scriptClassReference, false)
+ scriptComponent = bluePrintScriptsService.scriptInstance<T>(
+ bluePrintContext.rootPath,
+ bluePrintContext.name(), bluePrintContext.version(), scriptClassReference, false
+ )
}
BluePrintConstants.SCRIPT_JYTHON -> {
scriptComponent = blueprintJythonService.jythonComponentInstance(bluePrintContext, scriptClassReference) as T
}
return scriptComponent
}
-
-}
\ No newline at end of file
+}
*/
@Component("component-script-executor")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ComponentScriptExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService)
- : AbstractComponentFunction() {
+open class ComponentScriptExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService) :
+ AbstractComponentFunction() {
companion object {
const val INPUT_SCRIPT_TYPE = "script-type"
val scriptDependencies: MutableList<String> = arrayListOf()
populateScriptDependencies(scriptDependencies)
- scriptComponentFunction = componentFunctionScriptingService.scriptInstance(this, scriptType,
- scriptClassReference, scriptDependencies)
+ scriptComponentFunction = componentFunctionScriptingService.scriptInstance(
+ this, scriptType,
+ scriptClassReference, scriptDependencies
+ )
// Handles both script processing and error handling
scriptComponentFunction.executeScript(executionServiceInput)
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
bluePrintRuntimeService.getBluePrintError()
- .addError("Failed in ComponentCliExecutor : ${runtimeException.message}")
-
+ .addError("Failed in ComponentCliExecutor : ${runtimeException.message}")
}
open fun populateScriptDependencies(scriptDependencies: MutableList<String>) {
/** Place holder for Child to add extra dependencies */
}
-}
\ No newline at end of file
+}
/** Component Extensions **/
fun BluePrintTypes.nodeTypeComponentScriptExecutor(): NodeType {
- return nodeType(id = "component-script-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
- description = "Generic Script Component Executor") {
+ return nodeType(
+ id = "component-script-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
+ description = "Generic Script Component Executor"
+ ) {
attribute(ComponentScriptExecutor.ATTRIBUTE_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON, false)
attribute(ComponentScriptExecutor.ATTRIBUTE_STATUS, BluePrintConstants.DATA_TYPE_STRING, true)
operation("ComponentScriptExecutor", "ComponentScriptExecutor Operation") {
inputs {
- property(ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BluePrintConstants.DATA_TYPE_STRING,
- true, "Script Type") {
+ property(
+ ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Script Type"
+ ) {
defaultValue(BluePrintConstants.SCRIPT_INTERNAL)
constrain {
- validValues(listOf(BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive(),
+ validValues(
+ listOf(
+ BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive(),
BluePrintConstants.SCRIPT_JYTHON.asJsonPrimitive(),
- BluePrintConstants.SCRIPT_KOTLIN.asJsonPrimitive()))
+ BluePrintConstants.SCRIPT_KOTLIN.asJsonPrimitive()
+ )
+ )
}
}
- property(ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BluePrintConstants.DATA_TYPE_STRING,
- true, "Kotlin Script class name or jython script name.")
- property(ComponentScriptExecutor.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
- false, "Dynamic Json Content or DSL Json reference.")
+ property(
+ ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Kotlin Script class name or jython script name."
+ )
+ property(
+ ComponentScriptExecutor.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
+ false, "Dynamic Json Content or DSL Json reference."
+ )
}
outputs {
- property(ComponentScriptExecutor.OUTPUT_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON,
- false, "Output Response")
- property(ComponentScriptExecutor.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING,
- true, "Status of the Component Execution ( success or failure )")
+ property(
+ ComponentScriptExecutor.OUTPUT_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON,
+ false, "Output Response"
+ )
+ property(
+ ComponentScriptExecutor.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Status of the Component Execution ( success or failure )"
+ )
}
}
}
}
/** Component Builder */
-fun BluePrintTypes.nodeTemplateComponentScriptExecutor(id: String,
- description: String,
- block: ComponentScriptExecutorNodeTemplateBuilder.() -> Unit)
- : NodeTemplate {
+fun BluePrintTypes.nodeTemplateComponentScriptExecutor(
+ id: String,
+ description: String,
+ block: ComponentScriptExecutorNodeTemplateBuilder.() -> Unit
+):
+ NodeTemplate {
return ComponentScriptExecutorNodeTemplateBuilder(id, description).apply(block).build()
}
class ComponentScriptExecutorNodeTemplateBuilder(id: String, description: String) :
- AbstractNodeTemplateOperationImplBuilder<PropertiesAssignmentBuilder,
- ComponentScriptExecutorNodeTemplateBuilder.InputsBuilder,
- ComponentScriptExecutorNodeTemplateBuilder.OutputsBuilder>(id, "component-script-executor",
- "ComponentScriptExecutor",
- description) {
+ AbstractNodeTemplateOperationImplBuilder<PropertiesAssignmentBuilder,
+ ComponentScriptExecutorNodeTemplateBuilder.InputsBuilder,
+ ComponentScriptExecutorNodeTemplateBuilder.OutputsBuilder>(
+ id, "component-script-executor",
+ "ComponentScriptExecutor",
+ description
+ ) {
class InputsBuilder : PropertiesAssignmentBuilder() {
property(ComponentScriptExecutor.OUTPUT_RESPONSE_DATA, responseData)
}
}
-}
\ No newline at end of file
+}
@ComponentScan
open class ExecutionServiceConfiguration
-
object ExecutionServiceConstant {
const val SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION = "grpc-remote-script-execution-service"
-}
\ No newline at end of file
+}
import com.google.protobuf.Timestamp
import com.google.protobuf.util.JsonFormat
import io.grpc.ManagedChannel
-import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionOutput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcClientService
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcLibPropertyService
-import org.onap.ccsdk.cds.controllerblueprints.command.api.*
+import org.onap.ccsdk.cds.controllerblueprints.command.api.CommandExecutorServiceGrpc
+import org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionInput
+import org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionOutput
+import org.onap.ccsdk.cds.controllerblueprints.command.api.Identifiers
+import org.onap.ccsdk.cds.controllerblueprints.command.api.Packages
+import org.onap.ccsdk.cds.controllerblueprints.command.api.PrepareEnvInput
import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.slf4j.LoggerFactory
}
@Service(ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION)
-@ConditionalOnProperty(prefix = "blueprintprocessor.remoteScriptCommand", name = arrayOf("enabled"),
- havingValue = "true", matchIfMissing = false)
+@ConditionalOnProperty(
+ prefix = "blueprintprocessor.remoteScriptCommand", name = arrayOf("enabled"),
+ havingValue = "true", matchIfMissing = false
+)
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService)
- : RemoteScriptExecutionService {
+class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService) :
+ RemoteScriptExecutionService {
private val log = LoggerFactory.getLogger(GrpcRemoteScriptExecutionService::class.java)!!
}
}
- override suspend fun prepareEnv(prepareEnvInput: PrepareRemoteEnvInput)
- : RemoteScriptExecutionOutput {
+ override suspend fun prepareEnv(prepareEnvInput: PrepareRemoteEnvInput):
+ RemoteScriptExecutionOutput {
val grpResponse = commandExecutorServiceGrpc.prepareEnv(prepareEnvInput.asGrpcData())
checkNotNull(grpResponse.status) {
return remoteScriptExecutionOutput
}
- override suspend fun executeCommand(remoteExecutionInput: RemoteScriptExecutionInput)
- : RemoteScriptExecutionOutput {
+ override suspend fun executeCommand(remoteExecutionInput: RemoteScriptExecutionInput):
+ RemoteScriptExecutionOutput {
val grpResponse = commandExecutorServiceGrpc.executeCommand(remoteExecutionInput.asGrpcData())
channel?.shutdownNow()
}
-
fun PrepareRemoteEnvInput.asGrpcData(): PrepareEnvInput {
val correlationId = this.correlationId ?: this.requestId
}
return PrepareEnvInput.newBuilder()
- .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
- .setRequestId(this.requestId)
- .setCorrelationId(correlationId)
- .setTimeOut(this.timeOut.toInt())
- .addAllPackages(packageList)
- .setProperties(this.properties.asGrpcData())
- .build()
+ .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
+ .setRequestId(this.requestId)
+ .setCorrelationId(correlationId)
+ .setTimeOut(this.timeOut.toInt())
+ .addAllPackages(packageList)
+ .setProperties(this.properties.asGrpcData())
+ .build()
}
fun RemoteScriptExecutionInput.asGrpcData(): ExecutionInput {
val correlationId = this.correlationId ?: this.requestId
return ExecutionInput.newBuilder()
- .setRequestId(this.requestId)
- .setCorrelationId(correlationId)
- .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
- .setCommand(this.command)
- .setTimeOut(this.timeOut.toInt())
- .setProperties(this.properties.asGrpcData())
- .setTimestamp(Timestamp.getDefaultInstance())
- .build()
+ .setRequestId(this.requestId)
+ .setCorrelationId(correlationId)
+ .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
+ .setCommand(this.command)
+ .setTimeOut(this.timeOut.toInt())
+ .setProperties(this.properties.asGrpcData())
+ .setTimestamp(Timestamp.getDefaultInstance())
+ .build()
}
fun RemoteIdentifier.asGrpcData(): Identifiers? {
return Identifiers.newBuilder()
- .setBlueprintName(this.blueprintName)
- .setBlueprintVersion(this.blueprintVersion)
- .build()
+ .setBlueprintName(this.blueprintName)
+ .setBlueprintVersion(this.blueprintVersion)
+ .build()
}
fun Map<String, JsonNode>.asGrpcData(): Struct {
fun ExecutionOutput.asJavaData(): RemoteScriptExecutionOutput {
return RemoteScriptExecutionOutput(
- requestId = this.requestId,
- response = this.responseList,
- status = StatusType.valueOf(this.status.name),
- payload = payload.jsonAsJsonType()
+ requestId = this.requestId,
+ response = this.responseList,
+ status = StatusType.valueOf(this.status.name),
+ payload = payload.jsonAsJsonType()
)
}
-
}
import com.github.marcoferrer.krotoplus.coroutines.client.ClientBidiCallChannel
import com.github.marcoferrer.krotoplus.coroutines.client.clientCallBidiStreaming
import io.grpc.ManagedChannel
-import kotlinx.coroutines.*
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.FlowPreview
+import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeout
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcClientProperties
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcClientService
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcLibPropertyService
}
@Service
-@ConditionalOnProperty(prefix = "blueprintsprocessor.streamingRemoteExecution", name = ["enabled"],
- havingValue = "true", matchIfMissing = false)
-class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService)
- : StreamingRemoteExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
+@ConditionalOnProperty(
+ prefix = "blueprintsprocessor.streamingRemoteExecution", name = ["enabled"],
+ havingValue = "true", matchIfMissing = false
+)
+class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService) :
+ StreamingRemoteExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
private val log = logger(StreamingRemoteExecutionServiceImpl::class)
private val commChannels: MutableMap<String,
ClientBidiCallChannel<ExecutionServiceInput, ExecutionServiceOutput>> = hashMapOf()
-
/**
* Open new channel to send and receive for grpc properties [selector] for [txId],
* Create the only one GRPC channel per host port and reuse for further communication.
}
val commChannel = commChannels[txId]
- ?: throw BluePrintException("failed to create response subscription for transactionId($txId) channel")
+ ?: throw BluePrintException("failed to create response subscription for transactionId($txId) channel")
log.info("created subscription for transactionId($txId)")
*/
override suspend fun send(txId: String, input: ExecutionServiceInput) {
val sendChannel = commChannels[txId]?.requestChannel
- ?: throw BluePrintException("failed to get transactionId($txId) send channel")
+ ?: throw BluePrintException("failed to get transactionId($txId) send channel")
coroutineScope {
launch {
sendChannel.send(input)
* so the correlation is sub request id to receive the response.
*/
@ExperimentalCoroutinesApi
- override suspend fun sendNonInteractive(selector: Any, txId: String, input: ExecutionServiceInput, timeOutMill: Long)
- : ExecutionServiceOutput {
+ override suspend fun sendNonInteractive(selector: Any, txId: String, input: ExecutionServiceInput, timeOutMill: Long):
+ ExecutionServiceOutput {
var output: ExecutionServiceOutput? = null
val flow = openSubscription(selector, txId)
/** Send the request */
val sendChannel = commChannels[txId]?.requestChannel
- ?: throw BluePrintException("failed to get transactionId($txId) send channel")
+ ?: throw BluePrintException("failed to get transactionId($txId) send channel")
sendChannel.send(input)
/** Receive the response with timeout */
if (!it.requestChannel.isClosedForSend)
it.requestChannel.close()
/** If receive channel has to close immediately, once the subscription has cancelled, then enable this */
- //it.responseChannel.cancel(CancellationException("subscription cancelled"))
+ // it.responseChannel.cancel(CancellationException("subscription cancelled"))
commChannels.remove(txId)
log.info("closed subscription for transactionId($txId)")
}
suspend fun createGrpcChannel(grpcProperties: GrpcClientProperties): ManagedChannel {
val grpcClientService: BluePrintGrpcClientService = bluePrintGrpcLibPropertyService
- .blueprintGrpcClientService(grpcProperties)
+ .blueprintGrpcClientService(grpcProperties)
return grpcClientService.channel()
}
import java.io.File
@Service
-class BlueprintJythonService(val pythonExecutorProperty: PythonExecutorProperty,
- private val applicationContext: ApplicationContext) {
+class BlueprintJythonService(
+ val pythonExecutorProperty: PythonExecutorProperty,
+ private val applicationContext: ApplicationContext
+) {
val log: Logger = LoggerFactory.getLogger(BlueprintJythonService::class.java)
- inline fun <reified T> jythonInstance(blueprintContext: BluePrintContext, pythonClassName: String, content: String,
- dependencyInstanceNames: MutableMap<String, Any>?): T {
+ inline fun <reified T> jythonInstance(
+ blueprintContext: BluePrintContext,
+ pythonClassName: String,
+ content: String,
+ dependencyInstanceNames: MutableMap<String, Any>?
+ ): T {
val blueprintBasePath: String = blueprintContext.rootPath
val pythonPath: MutableList<String> = arrayListOf()
BlueprintFunctionNode<*, *> {
val pythonFileName = bluePrintContext.rootPath
- .plus(File.separator)
- .plus(scriptClassReference)
+ .plus(File.separator)
+ .plus(scriptClassReference)
val pythonClassName = FilenameUtils.getBaseName(pythonFileName)
log.info("Getting Jython Script Class($pythonClassName)")
val jythonInstances: MutableMap<String, Any> = hashMapOf()
jythonInstances["log"] = LoggerFactory.getLogger(pythonClassName)
- return jythonInstance<BlueprintFunctionNode<*, *>>(bluePrintContext, pythonClassName,
- content, jythonInstances)
+ return jythonInstance<BlueprintFunctionNode<*, *>>(
+ bluePrintContext, pythonClassName,
+ content, jythonInstances
+ )
}
fun jythonComponentInstance(abstractComponentFunction: AbstractComponentFunction): AbstractComponentFunction {
val operationInputs: MutableMap<String, JsonNode> = abstractComponentFunction.operationInputs
val operationAssignment: OperationAssignment = bluePrintContext
- .nodeTemplateInterfaceOperation(abstractComponentFunction.nodeTemplateName,
- abstractComponentFunction.interfaceName, abstractComponentFunction.operationName)
+ .nodeTemplateInterfaceOperation(
+ abstractComponentFunction.nodeTemplateName,
+ abstractComponentFunction.interfaceName, abstractComponentFunction.operationName
+ )
val blueprintBasePath: String = bluePrintContext.rootPath
val artifactName: String = operationAssignment.implementation?.primary
- ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
+ ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
val pythonFileName = artifactDefinition.file
- ?: throw BluePrintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)")
+ ?: throw BluePrintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)")
val pythonClassName = FilenameUtils.getBaseName(pythonFileName)
log.info("Getting Jython Script Class($pythonClassName)")
val content: String? = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName)
- checkNotEmpty(content){ "artifact ($artifactName) content is empty"}
+ checkNotEmpty(content) { "artifact ($artifactName) content is empty" }
val pythonPath: MutableList<String> = operationAssignment.implementation?.dependencies ?: arrayListOf()
pythonPath.add(blueprintBasePath)
jythonInstances["log"] = LoggerFactory.getLogger(nodeTemplateName)
val instanceDependenciesNode: ArrayNode = operationInputs[PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES] as? ArrayNode
- ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})")
+ ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})")
instanceDependenciesNode.forEach { instanceName ->
jythonInstances[instanceName.textValue()] = applicationContext.getBean(instanceName.textValue())
}
- val scriptComponentFunction = jythonInstance<AbstractComponentFunction>(bluePrintContext, pythonClassName,
- content!!, jythonInstances)
+ val scriptComponentFunction = jythonInstance<AbstractComponentFunction>(
+ bluePrintContext, pythonClassName,
+ content!!, jythonInstances
+ )
return scriptComponentFunction
-
}
-
-}
\ No newline at end of file
+}
import org.python.core.PyObject
import org.python.util.PythonInterpreter
-open class BlueprintPythonHost(private val bluePrintPython: BluePrintPython){
+open class BlueprintPythonHost(private val bluePrintPython: BluePrintPython) {
private val blueprintPythonInterpreterProxy: BlueprintPythonInterpreterProxy
init {
try {
return blueprintPythonInterpreterProxy.getPythonInstance(properties)
} catch (e: Exception) {
- throw BluePrintProcessorException("Failed to execute Jython component ${e.toString()}", e)
+ throw BluePrintProcessorException("Failed to execute Jython component $e", e)
}
}
- //TODO Check potential errors in python scripts
+ // TODO Check potential errors in python scripts
}
try {
this.exec(bluePrintPython.content)
} catch (e: PySyntaxError) {
- throw BluePrintProcessorException("Error executing Jython code! Python error: '${e.toString()}'", e)
+ throw BluePrintProcessorException("Error executing Jython code! Python error: '$e'", e)
}
}
val initCommand = bluePrintPython.pythonClassName.plus(" = ").plus(
- bluePrintPython.pythonClassName).plus("()")
+ bluePrintPython.pythonClassName
+ ).plus("()")
this.exec(initCommand)
return this.get(bluePrintPython.pythonClassName)
@Configuration
open class PythonExecutorProperty {
+
@Value("\${blueprints.processor.functions.python.executor.executionPath}")
lateinit var executionPath: String
@Value("#{'\${blueprints.processor.functions.python.executor.modulePaths}'.split(',')}")
}
}
-open class BluePrintPython(executablePath: String, blueprintPythonPlatform: MutableList<String>,
- val argv: MutableList<String>){
+open class BluePrintPython(
+ executablePath: String,
+ blueprintPythonPlatform: MutableList<String>,
+ val argv: MutableList<String>
+) {
+
lateinit var moduleName: String
lateinit var pythonClassName: String
lateinit var content: String
props.setProperty("python.verbose", "error")
props.setProperty("python.executable", executablePath)
}
-}
\ No newline at end of file
+}
private val log = logger(MockBluePrintProcessingServer::class)
-
class MockBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() {
override fun process(responseObserver: StreamObserver<ExecutionServiceOutput>): StreamObserver<ExecutionServiceInput> {
return object : StreamObserver<ExecutionServiceInput> {
override fun onNext(executionServiceInput: ExecutionServiceInput) {
- log.info("Received requestId(${executionServiceInput.commonHeader.requestId}) " +
- "subRequestId(${executionServiceInput.commonHeader.subRequestId})")
+ log.info(
+ "Received requestId(${executionServiceInput.commonHeader.requestId}) " +
+ "subRequestId(${executionServiceInput.commonHeader.subRequestId})"
+ )
runBlocking {
launch(MDCContext()) {
responseObserver.onNext(buildNotification(executionServiceInput))
override fun onError(error: Throwable) {
log.debug("Fail to process message", error)
- responseObserver.onError(io.grpc.Status.INTERNAL
+ responseObserver.onError(
+ io.grpc.Status.INTERNAL
.withDescription(error.message)
- .asException())
+ .asException()
+ )
}
override fun onCompleted() {
}
}
-
private fun buildNotification(input: ExecutionServiceInput): ExecutionServiceOutput {
val status = Status.newBuilder()
- .setEventType(EventType.EVENT_COMPONENT_NOTIFICATION)
- .build()
+ .setEventType(EventType.EVENT_COMPONENT_NOTIFICATION)
+ .build()
return ExecutionServiceOutput.newBuilder()
- .setCommonHeader(input.commonHeader)
- .setActionIdentifiers(input.actionIdentifiers)
- .setStatus(status)
- .build()
+ .setCommonHeader(input.commonHeader)
+ .setActionIdentifiers(input.actionIdentifiers)
+ .setStatus(status)
+ .build()
}
private fun buildResponse(input: ExecutionServiceInput): ExecutionServiceOutput {
val status = Status.newBuilder().setCode(200)
- .setEventType(EventType.EVENT_COMPONENT_EXECUTED)
- .build()
+ .setEventType(EventType.EVENT_COMPONENT_EXECUTED)
+ .build()
return ExecutionServiceOutput.newBuilder()
- .setCommonHeader(input.commonHeader)
- .setActionIdentifiers(input.actionIdentifiers)
- .setStatus(status)
- .build()
-
+ .setCommonHeader(input.commonHeader)
+ .setActionIdentifiers(input.actionIdentifiers)
+ .setStatus(status)
+ .build()
}
}
fun main() {
try {
val server = ServerBuilder
- .forPort(50052)
- .intercept(GrpcServerLoggingInterceptor())
- .addService(MockBluePrintProcessingServer())
- .build()
+ .forPort(50052)
+ .intercept(GrpcServerLoggingInterceptor())
+ .addService(MockBluePrintProcessingServer())
+ .build()
server.start()
log.info("GRPC Serve started(${server.isShutdown}) on port(${server.port})...")
server.awaitTermination()
} catch (e: Exception) {
e.printStackTrace()
}
-
-}
\ No newline at end of file
+}
import io.mockk.coEvery
import io.mockk.mockk
import io.mockk.spyk
-import kotlinx.coroutines.*
+import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.FlowPreview
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
import org.onap.ccsdk.cds.controllerblueprints.core.logger
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput
-import java.util.*
+import java.util.UUID
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
-
class StreamingRemoteExecutionServiceTest {
val log = logger(StreamingRemoteExecutionServiceTest::class)
val request = getRequest(requestId)
val invocationId = request.commonHeader.subRequestId
val deferred = async {
- val response = spyStreamingRemoteExecutionService.sendNonInteractive(tokenAuthGrpcClientProperties,
- invocationId, request, 1000L)
+ val response = spyStreamingRemoteExecutionService.sendNonInteractive(
+ tokenAuthGrpcClientProperties,
+ invocationId, request, 1000L
+ )
assertNotNull(response, "failed to get non interactive response")
- assertEquals(response.commonHeader.requestId, requestId,
- "failed to match non interactive response id")
- assertEquals(response.status.eventType, EventType.EVENT_COMPONENT_EXECUTED,
- "failed to match non interactive response type")
+ assertEquals(
+ response.commonHeader.requestId, requestId,
+ "failed to match non interactive response id"
+ )
+ assertEquals(
+ response.status.eventType, EventType.EVENT_COMPONENT_EXECUTED,
+ "failed to match non interactive response type"
+ )
}
nonInteractiveDeferred.add(deferred)
-
}
nonInteractiveDeferred.awaitAll()
val request = getRequest(requestId)
val invocationId = request.commonHeader.requestId
val responseFlow = spyStreamingRemoteExecutionService
- .openSubscription(tokenAuthGrpcClientProperties, invocationId)
+ .openSubscription(tokenAuthGrpcClientProperties, invocationId)
val deferred = async {
responseFlow.collect {
responseFlowsDeferred.awaitAll()
streamingRemoteExecutionService.closeChannel(tokenAuthGrpcClientProperties)
}
-
}
private fun getRequest(requestId: String): ExecutionServiceInput {
val commonHeader = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(requestId)
- .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build()
-
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(requestId)
+ .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build()
val actionIdentifier = ActionIdentifiers.newBuilder()
- .setActionName("SampleScript")
- .setBlueprintName("sample-cba")
- .setBlueprintVersion("1.0.0")
- .setMode(ACTION_MODE_SYNC)
- .build()
+ .setActionName("SampleScript")
+ .setBlueprintName("sample-cba")
+ .setBlueprintVersion("1.0.0")
+ .setMode(ACTION_MODE_SYNC)
+ .build()
val jsonContent = """{ "key1" : "value1" }"""
val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder
JsonFormat.parser().merge(jsonContent, payloadBuilder)
return ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(actionIdentifier)
- .setPayload(payloadBuilder.build())
- .build()
-
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setPayload(payloadBuilder.build())
+ .build()
}
-}
\ No newline at end of file
+}
* ============LICENSE_END=========================================================
*/
-package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts;
+package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
* Unit test cases for abstract component function.
*/
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [ComponentFunctionScriptingService::class,
- BluePrintScriptsServiceImpl::class, PythonExecutorProperty::class,
- BlueprintJythonService::class])
+@ContextConfiguration(
+ classes = [ComponentFunctionScriptingService::class,
+ BluePrintScriptsServiceImpl::class, PythonExecutorProperty::class,
+ BlueprintJythonService::class]
+)
class AbstractComponentFunctionTest {
lateinit var blueprintContext: BluePrintContext
val sampleComponent = SampleComponent()
sampleComponent.workflowName = "sample-action"
sampleComponent.executionServiceInput = JacksonUtils.readValueFromClassPathFile(
- "payload/requests/sample-execution-request.json", ExecutionServiceInput::class.java)!!
+ "payload/requests/sample-execution-request.json", ExecutionServiceInput::class.java
+ )!!
val payload = sampleComponent.requestPayload()
assertNotNull(payload, "failed to get payload")
val data = sampleComponent.requestPayloadActionProperty("data")?.first()
val operationInputs = hashMapOf<String, JsonNode>()
operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] =
- "activate-restconf".asJsonPrimitive()
+ "activate-restconf".asJsonPrimitive()
operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] =
- "interfaceName".asJsonPrimitive()
+ "interfaceName".asJsonPrimitive()
operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] =
- "operationName".asJsonPrimitive()
+ "operationName".asJsonPrimitive()
operationInputs["dynamic-properties"] = rootNode
-
val stepInputData = StepData().apply {
name = "activate-restconf"
properties = operationInputs
every {
bluePrintRuntime.resolveNodeTemplateInterfaceOperationInputs(
- "activate-restconf", "interfaceName", "operationName")
+ "activate-restconf", "interfaceName", "operationName"
+ )
} returns operationInputs
val operationOutputs = hashMapOf<String, JsonNode>()
every {
bluePrintRuntime.resolveNodeTemplateInterfaceOperationOutputs(
- "activate-restconf", "interfaceName", "operationName")
+ "activate-restconf", "interfaceName", "operationName"
+ )
} returns operationOutputs
every { bluePrintRuntime.bluePrintContext() } returns blueprintContext
val componentScriptExecutor = BluePrintTypes.nodeTypeComponentScriptExecutor()
assertNotNull(componentScriptExecutor.interfaces, "failed to get interface operations")
}
-
}
-
@RunWith(SpringRunner::class)
@ContextConfiguration(classes = [BlueprintJythonService::class, PythonExecutorProperty::class])
-@TestPropertySource(properties =
-["blueprints.processor.functions.python.executor.modulePaths=./../../../../../components/scripts/python/ccsdk_blueprints",
- "blueprints.processor.functions.python.executor.executionPath=./../../../../../components/scripts/python/ccsdk_blueprints"])
+@TestPropertySource(
+ properties =
+ ["blueprints.processor.functions.python.executor.modulePaths=./../../../../../components/scripts/python/ccsdk_blueprints",
+ "blueprints.processor.functions.python.executor.executionPath=./../../../../../components/scripts/python/ccsdk_blueprints"]
+)
class BlueprintJythonServiceTest {
lateinit var blueprintContext: BluePrintContext
blueprintContext = mockk<BluePrintContext>()
every { blueprintContext.rootPath } returns normalizedPathName("target")
}
-
+
@Test
fun testGetAbstractPythonPlugin() {
- val content = JacksonUtils.getClassPathFileContent("scripts/SamplePythonComponentNode.py")
- val dependencies: MutableMap<String, Any> = hashMapOf()
+ val content = JacksonUtils.getClassPathFileContent("scripts/SamplePythonComponentNode.py")
+ val dependencies: MutableMap<String, Any> = hashMapOf()
- val abstractPythonPlugin = blueprintJythonService
- .jythonInstance<AbstractComponentFunction>(blueprintContext, "SamplePythonComponentNode",
- content, dependencies)
+ val abstractPythonPlugin = blueprintJythonService
+ .jythonInstance<AbstractComponentFunction>(
+ blueprintContext, "SamplePythonComponentNode",
+ content, dependencies
+ )
- assertNotNull(abstractPythonPlugin, "failed to get python component")
+ assertNotNull(abstractPythonPlugin, "failed to get python component")
}
@Test
fun testGetAbstractJythonComponent() {
- val scriptInstance = "test-classes/scripts/SamplePythonComponentNode.py"
-
- val abstractJythonComponent = blueprintJythonService.jythonComponentInstance(blueprintContext, scriptInstance)
+ val scriptInstance = "test-classes/scripts/SamplePythonComponentNode.py"
- assertNotNull(abstractJythonComponent, "failed to get Jython component")
+ val abstractJythonComponent = blueprintJythonService.jythonComponentInstance(blueprintContext, scriptInstance)
+ assertNotNull(abstractJythonComponent, "failed to get Jython component")
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts
import org.junit.Test
-
import org.junit.runner.RunWith
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
-import kotlin.test.assertNotNull
import kotlin.test.BeforeTest
+import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
@ContextConfiguration(classes = [BluePrintPython::class, PythonExecutorProperty::class, String::class])
-@TestPropertySource(properties =
-["blueprints.processor.functions.python.executor.modulePaths=./../../../../../components/scripts/python/ccsdk_blueprints",
- "blueprints.processor.functions.python.executor.executionPath=./../../../../../components/scripts/python/ccsdk_blueprints"])
+@TestPropertySource(
+ properties =
+ ["blueprints.processor.functions.python.executor.modulePaths=./../../../../../components/scripts/python/ccsdk_blueprints",
+ "blueprints.processor.functions.python.executor.executionPath=./../../../../../components/scripts/python/ccsdk_blueprints"]
+)
class BlueprintPythonHostTest {
lateinit var blueprintPythonHost: BlueprintPythonHost
assertNotNull(pythonObject, "failed to get python object")
}
-}
\ No newline at end of file
+}
* ============LICENSE_END=========================================================
*/
-
package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService
-
import org.slf4j.LoggerFactory
open class SampleComponent : AbstractComponentFunction() {
val log = LoggerFactory.getLogger(SampleComponent::class.java)!!
-
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
}
}
}
-open class SampleRestconfComponent (private var componentFunctionScriptingService: ComponentFunctionScriptingService)
- : AbstractComponentFunction() {
+open class SampleRestconfComponent(private var componentFunctionScriptingService: ComponentFunctionScriptingService) :
+ AbstractComponentFunction() {
val log = LoggerFactory.getLogger(SampleScriptComponent::class.java)!!
-
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
var scriptComponent: AbstractScriptComponentFunction
scriptComponent = componentFunctionScriptingService
- .scriptInstance<AbstractScriptComponentFunction>(this,
- "internal",
- "org.onap.ccsdk.cds.blueprintsprocessor.services" +
- ".execution.scripts.SampleTest",
- mutableListOf())
+ .scriptInstance<AbstractScriptComponentFunction>(
+ this,
+ "internal",
+ "org.onap.ccsdk.cds.blueprintsprocessor.services" +
+ ".execution.scripts.SampleTest",
+ mutableListOf()
+ )
scriptComponent.executeScript(executionServiceInput)
}
val log = LoggerFactory.getLogger(SampleScriptComponent::class.java)!!
-
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
-
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
}
-}
\ No newline at end of file
+}
val log = LoggerFactory.getLogger(SampleTest::class.java)!!
-
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
val isPresent = checkDynamicProperties("type")
assertTrue(isPresent)
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
}
-}
\ No newline at end of file
+}
@Service("bluePrintWorkflowExecutionService")
open class BluePrintWorkflowExecutionServiceImpl(
- private val componentWorkflowExecutionService: ComponentWorkflowExecutionService,
- private val dgWorkflowExecutionService: DGWorkflowExecutionService,
- private val imperativeWorkflowExecutionService: ImperativeWorkflowExecutionService
+ private val componentWorkflowExecutionService: ComponentWorkflowExecutionService,
+ private val dgWorkflowExecutionService: DGWorkflowExecutionService,
+ private val imperativeWorkflowExecutionService: ImperativeWorkflowExecutionService
) : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
private val log = LoggerFactory.getLogger(BluePrintWorkflowExecutionServiceImpl::class.java)!!
- override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- executionServiceInput: ExecutionServiceInput,
- properties: MutableMap<String, Any>): ExecutionServiceOutput {
+ override suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: ExecutionServiceInput,
+ properties: MutableMap<String, Any>
+ ): ExecutionServiceOutput {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
val workflowName = executionServiceInput.actionIdentifiers.actionName
// Assign Workflow inputs
- //check if request structure exists
+ // check if request structure exists
if (!executionServiceInput.payload.has("$workflowName-request")) {
throw BluePrintProcessorException("Input request missing the expected '$workflowName-request' block!")
}
/** If workflow has multiple steps, then it is imperative workflow */
val executionServiceOutput: ExecutionServiceOutput = if (steps.size > 1) {
imperativeWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
} else {
// Get the DG Node Template
val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName)
when {
derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> {
componentWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
}
derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, true) -> {
dgWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
}
else -> {
- throw BluePrintProcessorException("couldn't execute workflow($workflowName) step mapped " +
- "to node template($nodeTemplateName) derived from($derivedFrom)")
+ throw BluePrintProcessorException(
+ "couldn't execute workflow($workflowName) step mapped " +
+ "to node template($nodeTemplateName) derived from($derivedFrom)"
+ )
}
}
}
executionServiceOutput.payload.set("$workflowName-response", workflowOutputs.asObjectNode())
return executionServiceOutput
}
-
}
fun getResponse(): Any {
return this.response!!
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
-import org.onap.ccsdk.sli.core.sli.*
-import org.onap.ccsdk.sli.core.sli.provider.base.*
+import org.onap.ccsdk.sli.core.sli.ExitNodeException
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext
+import org.onap.ccsdk.sli.core.sli.SvcLogicException
+import org.onap.ccsdk.sli.core.sli.SvcLogicGraph
+import org.onap.ccsdk.sli.core.sli.SvcLogicNode
+import org.onap.ccsdk.sli.core.sli.SvcLogicStore
+import org.onap.ccsdk.sli.core.sli.provider.base.AbstractSvcLogicNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.BlockNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.BreakNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.ExecuteNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.ExitNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.ReturnNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.SvcLogicServiceBase
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.Properties
import javax.annotation.PostConstruct
interface BlueprintSvcLogicService : SvcLogicServiceBase {
}
}
-
@Service
class DefaultBlueprintSvcLogicService : BlueprintSvcLogicService {
}
}
- override suspend fun execute(graph: SvcLogicGraph, bluePrintRuntimeService: BluePrintRuntimeService<*>,
- input: Any): Any {
- //Initialise BlueprintSvcLogic Context with Blueprint Runtime Service and Input Request
+ override suspend fun execute(
+ graph: SvcLogicGraph,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ input: Any
+ ): Any {
+ // Initialise BlueprintSvcLogic Context with Blueprint Runtime Service and Input Request
val blueprintSvcLogicContext = BlueprintSvcLogicContext()
blueprintSvcLogicContext.setBluePrintRuntimeService(bluePrintRuntimeService)
blueprintSvcLogicContext.setRequest(input)
MDC.remove("currentGraph")
return svcLogicContext
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow
-
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService
import org.springframework.stereotype.Service
@Service("componentWorkflowExecutionService")
-open class ComponentWorkflowExecutionService(private val nodeTemplateExecutionService: NodeTemplateExecutionService)
- : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
+open class ComponentWorkflowExecutionService(private val nodeTemplateExecutionService: NodeTemplateExecutionService) :
+ BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
- override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- executionServiceInput: ExecutionServiceInput,
- properties: MutableMap<String, Any>): ExecutionServiceOutput {
+ override suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: ExecutionServiceInput,
+ properties: MutableMap<String, Any>
+ ): ExecutionServiceOutput {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
// Get the DG Node Template
val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName)
- return nodeTemplateExecutionService.executeNodeTemplate(bluePrintRuntimeService,
- nodeTemplateName, executionServiceInput)
+ return nodeTemplateExecutionService.executeNodeTemplate(
+ bluePrintRuntimeService,
+ nodeTemplateName, executionServiceInput
+ )
}
-
-}
\ No newline at end of file
+}
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
-
@Service("dgWorkflowExecutionService")
-open class DGWorkflowExecutionService(private val blueprintSvcLogicService: BlueprintSvcLogicService)
- : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
+open class DGWorkflowExecutionService(private val blueprintSvcLogicService: BlueprintSvcLogicService) :
+ BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
private val log = LoggerFactory.getLogger(DGWorkflowExecutionService::class.java)
- override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- executionServiceInput: ExecutionServiceInput,
- properties: MutableMap<String, Any>): ExecutionServiceOutput {
+ override suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: ExecutionServiceInput,
+ properties: MutableMap<String, Any>
+ ): ExecutionServiceOutput {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
log.info("Executing workflow($workflowName) directed graph NodeTemplate($nodeTemplateName)")
// Get the DG file info
- val artifactDefinition = bluePrintContext.nodeTemplateArtifactForArtifactType(nodeTemplateName,
- WorkflowServiceConstants.ARTIFACT_TYPE_DIRECTED_GRAPH)
+ val artifactDefinition = bluePrintContext.nodeTemplateArtifactForArtifactType(
+ nodeTemplateName,
+ WorkflowServiceConstants.ARTIFACT_TYPE_DIRECTED_GRAPH
+ )
// Populate the DG Path
val dgFilePath = normalizedPathName(bluePrintContext.rootPath, artifactDefinition.file)
val graph = SvcGraphUtils.getSvcGraphFromFile(dgFilePath)
// Execute the DG
- return blueprintSvcLogicService.execute(graph,
+ return blueprintSvcLogicService.execute(
+ graph,
bluePrintRuntimeService,
- executionServiceInput) as ExecutionServiceOutput
-
+ executionServiceInput
+ ) as ExecutionServiceOutput
}
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asGraph
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel
import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService
-import org.onap.ccsdk.cds.controllerblueprints.core.service.*
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.service.AbstractBluePrintWorkFlowService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintWorkFlowService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.NodeExecuteMessage
+import org.onap.ccsdk.cds.controllerblueprints.core.service.NodeSkipMessage
+import org.onap.ccsdk.cds.controllerblueprints.core.service.WorkflowExecuteMessage
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
@Service("imperativeWorkflowExecutionService")
class ImperativeWorkflowExecutionService(
- private val imperativeBluePrintWorkflowService: BluePrintWorkFlowService<ExecutionServiceInput, ExecutionServiceOutput>)
- : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
+ private val imperativeBluePrintWorkflowService: BluePrintWorkFlowService<ExecutionServiceInput, ExecutionServiceOutput>
+) :
+ BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
- override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- executionServiceInput: ExecutionServiceInput,
- properties: MutableMap<String, Any>): ExecutionServiceOutput {
+ override suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: ExecutionServiceInput,
+ properties: MutableMap<String, Any>
+ ): ExecutionServiceOutput {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
val graph = bluePrintContext.workflowByName(workflowName).asGraph()
- return imperativeBluePrintWorkflowService.executeWorkflow(graph, bluePrintRuntimeService,
- executionServiceInput)
+ return imperativeBluePrintWorkflowService.executeWorkflow(
+ graph, bluePrintRuntimeService,
+ executionServiceInput
+ )
}
}
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ImperativeBluePrintWorkflowService(private val nodeTemplateExecutionService: NodeTemplateExecutionService)
- : AbstractBluePrintWorkFlowService<ExecutionServiceInput, ExecutionServiceOutput>() {
+open class ImperativeBluePrintWorkflowService(private val nodeTemplateExecutionService: NodeTemplateExecutionService) :
+ AbstractBluePrintWorkFlowService<ExecutionServiceInput, ExecutionServiceOutput>() {
+
val log = logger(ImperativeBluePrintWorkflowService::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var executionServiceInput: ExecutionServiceInput
lateinit var workflowName: String
- override suspend fun executeWorkflow(graph: Graph, bluePrintRuntimeService: BluePrintRuntimeService<*>,
- input: ExecutionServiceInput): ExecutionServiceOutput {
+ override suspend fun executeWorkflow(
+ graph: Graph,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ input: ExecutionServiceInput
+ ): ExecutionServiceOutput {
this.graph = graph
this.bluePrintRuntimeService = bluePrintRuntimeService
this.executionServiceInput = input
}
}
- override suspend fun prepareNodeExecutionMessage(node: Graph.Node)
- : NodeExecuteMessage<ExecutionServiceInput, ExecutionServiceOutput> {
+ override suspend fun prepareNodeExecutionMessage(node: Graph.Node):
+ NodeExecuteMessage<ExecutionServiceInput, ExecutionServiceOutput> {
val nodeOutput = ExecutionServiceOutput().apply {
commonHeader = executionServiceInput.commonHeader
actionIdentifiers = executionServiceInput.actionIdentifiers
return NodeExecuteMessage(node, executionServiceInput, nodeOutput)
}
- override suspend fun prepareNodeSkipMessage(node: Graph.Node)
- : NodeSkipMessage<ExecutionServiceInput, ExecutionServiceOutput> {
+ override suspend fun prepareNodeSkipMessage(node: Graph.Node):
+ NodeSkipMessage<ExecutionServiceInput, ExecutionServiceOutput> {
val nodeOutput = ExecutionServiceOutput().apply {
commonHeader = executionServiceInput.commonHeader
actionIdentifiers = executionServiceInput.actionIdentifiers
return NodeSkipMessage(node, executionServiceInput, nodeOutput)
}
- override suspend fun executeNode(node: Graph.Node, nodeInput: ExecutionServiceInput,
- nodeOutput: ExecutionServiceOutput): EdgeLabel {
+ override suspend fun executeNode(
+ node: Graph.Node,
+ nodeInput: ExecutionServiceInput,
+ nodeOutput: ExecutionServiceOutput
+ ): EdgeLabel {
log.info("Executing workflow($workflowName[${this.workflowId}])'s step($${node.id})")
val step = bluePrintRuntimeService.bluePrintContext().workflowStepByName(this.workflowName, node.id)
checkNotEmpty(step.target) { "couldn't get step target for workflow(${this.workflowName})'s step(${node.id})" }
val nodeTemplateName = step.target!!
/** execute node template */
val executionServiceOutput = nodeTemplateExecutionService
- .executeNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeInput)
+ .executeNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeInput)
return when (executionServiceOutput.status.message) {
BluePrintConstants.STATUS_FAILURE -> EdgeLabel.FAILURE
}
}
- override suspend fun skipNode(node: Graph.Node, nodeInput: ExecutionServiceInput,
- nodeOutput: ExecutionServiceOutput): EdgeLabel {
+ override suspend fun skipNode(
+ node: Graph.Node,
+ nodeInput: ExecutionServiceInput,
+ nodeOutput: ExecutionServiceOutput
+ ): EdgeLabel {
return EdgeLabel.SUCCESS
}
- override suspend fun cancelNode(node: Graph.Node, nodeInput: ExecutionServiceInput,
- nodeOutput: ExecutionServiceOutput): EdgeLabel {
+ override suspend fun cancelNode(
+ node: Graph.Node,
+ nodeInput: ExecutionServiceInput,
+ nodeOutput: ExecutionServiceOutput
+ ): EdgeLabel {
TODO("not implemented")
}
- override suspend fun restartNode(node: Graph.Node, nodeInput: ExecutionServiceInput,
- nodeOutput: ExecutionServiceOutput): EdgeLabel {
+ override suspend fun restartNode(
+ node: Graph.Node,
+ nodeInput: ExecutionServiceInput,
+ nodeOutput: ExecutionServiceOutput
+ ): EdgeLabel {
TODO("not implemented")
}
-}
\ No newline at end of file
+}
private val log = LoggerFactory.getLogger(NodeTemplateExecutionService::class.java)!!
- suspend fun executeNodeTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
- executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
+ suspend fun executeNodeTemplate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ nodeTemplateName: String,
+ executionServiceInput: ExecutionServiceInput
+ ): ExecutionServiceOutput {
// Get the Blueprint Context
val blueprintContext = bluePrintRuntimeService.bluePrintContext()
val operationName = blueprintContext.nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName)
val nodeTemplateImplementation = blueprintContext
- .nodeTemplateOperationImplementation(nodeTemplateName, interfaceName, operationName)
+ .nodeTemplateOperationImplementation(nodeTemplateName, interfaceName, operationName)
val timeout: Int = nodeTemplateImplementation?.timeout ?: 180
- log.info("executing node template($nodeTemplateName) component($componentName) " +
- "interface($interfaceName) operation($operationName) with timeout($timeout) sec.")
+ log.info(
+ "executing node template($nodeTemplateName) component($componentName) " +
+ "interface($interfaceName) operation($operationName) with timeout($timeout) sec."
+ )
// Get the Component Instance
val plugin = BluePrintDependencyService.instance<AbstractComponentFunction>(componentName)
// Get the Request from the Context and Set to the Function Input and Invoke the function
return plugin.applyNB(clonedExecutionServiceInput)
}
-
-}
\ No newline at end of file
+}
@ComponentScan
open class WorkflowServiceConfiguration
-
class WorkflowServiceConstants {
companion object {
const val ARTIFACT_TYPE_DIRECTED_GRAPH = "artifact-directed-graph"
}
-}
\ No newline at end of file
+}
import org.springframework.stereotype.Service
@Service
-open class ComponentExecuteNodeExecutor(private val nodeTemplateExecutionService: NodeTemplateExecutionService)
- : ExecuteNodeExecutor() {
+open class ComponentExecuteNodeExecutor(private val nodeTemplateExecutionService: NodeTemplateExecutionService) :
+ ExecuteNodeExecutor() {
private val log = LoggerFactory.getLogger(ComponentExecuteNodeExecutor::class.java)
@Throws(SvcLogicException::class)
- override fun execute(svc: SvcLogicServiceBase, node: SvcLogicNode, svcLogicContext: SvcLogicContext)
- : SvcLogicNode = runBlocking {
+ override fun execute(svc: SvcLogicServiceBase, node: SvcLogicNode, svcLogicContext: SvcLogicContext):
+ SvcLogicNode = runBlocking {
var outValue: String
val executionInput = ctx.getRequest() as ExecutionServiceInput
- try { // Get the Request from the Context and Set to the Function Input and Invoke the function
- val executionOutput = nodeTemplateExecutionService.executeNodeTemplate(ctx.getBluePrintService(),
- nodeTemplateName, executionInput)
+ try { // Get the Request from the Context and Set to the Function Input and Invoke the function
+ val executionOutput = nodeTemplateExecutionService.executeNodeTemplate(
+ ctx.getBluePrintService(),
+ nodeTemplateName, executionInput
+ )
ctx.setResponse(executionOutput)
outValue = executionOutput.status.message
ctx.status = executionOutput.status.message
-
} catch (e: Exception) {
log.error("Could not execute plugin($nodeTemplateName) : ", e)
outValue = "failure"
getNextNode(node, outValue)
}
-
-}
\ No newline at end of file
+}
val svcLogicParser = SvcLogicParser()
return svcLogicParser.parse(fileName).first
}
-}
\ No newline at end of file
+}
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
-
@RunWith(SpringRunner::class)
@ContextConfiguration(classes = [WorkflowServiceConfiguration::class])
class BluePrintWorkflowExecutionServiceImplTest {
@Test
fun testBluePrintWorkflowExecutionService() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/resource-assignment-input.json",
- ExecutionServiceInput::class.java)!!
+ val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
+ "execution-input/resource-assignment-input.json",
+ ExecutionServiceInput::class.java
+ )!!
val executionServiceOutput = bluePrintWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
}
@Test
fun testImperativeBluePrintWorkflowExecutionService() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/imperative-test-input.json",
- ExecutionServiceInput::class.java)!!
+ val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
+ "execution-input/imperative-test-input.json",
+ ExecutionServiceInput::class.java
+ )!!
val executionServiceOutput = bluePrintWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
}
fun `Blueprint fails on missing workflowName-parameters with a useful message`() {
assertFailsWith(exceptionClass = BluePrintProcessorException::class) {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
- //service input will have a mislabeled input params, we are expecting to get an error when that happens with a useful error message
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/resource-assignment-input-missing-resource_assignment_request.json",
- ExecutionServiceInput::class.java)!!
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
+ // service input will have a mislabeled input params, we are expecting to get an error when that happens with a useful error message
+ val executionServiceInput =
+ JacksonUtils.readValueFromClassPathFile(
+ "execution-input/resource-assignment-input-missing-resource_assignment_request.json",
+ ExecutionServiceInput::class.java
+ )!!
val executionServiceOutput = bluePrintWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
}
}
}
-
}
@Test
fun testExecuteGraphWithSingleComponent() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput = JacksonReactorUtils
- .readValueFromClassPathFile("execution-input/resource-assignment-input.json", ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile("execution-input/resource-assignment-input.json", ExecutionServiceInput::class.java)!!
// Assign Workflow inputs Mock
val input = executionServiceInput.payload.get("resource-assignment-request")
bluePrintRuntimeService.assignWorkflowInputs("resource-assignment", input)
val executionServiceOutput = dgWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf())
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
-
-
}
@Test
fun testExecuteGraphWithMultipleComponents() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput = JacksonReactorUtils
- .readValueFromClassPathFile("execution-input/assign-activate-input.json", ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile("execution-input/assign-activate-input.json", ExecutionServiceInput::class.java)!!
// Assign Workflow inputs Mock
val input = executionServiceInput.payload.get("assign-activate-request")
bluePrintRuntimeService.assignWorkflowInputs("assign-activate", input)
-
val executionServiceOutput = dgWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf())
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
-
}
@Test
assertEquals(stepName1, proto1.stepName, " Failed to match the step1 name")
assertEquals(stepName2, proto2.stepName, " Failed to match the step2 name")
}
-
-}
\ No newline at end of file
+}
@Autowired
lateinit var dgWorkflowExecutionService: DGWorkflowExecutionService
-
@Before
fun init() {
BluePrintDependencyService.inject(applicationContext)
fun testExecuteDirectedGraph() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput = JacksonReactorUtils
- .readValueFromClassPathFile("execution-input/resource-assignment-input.json", ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile("execution-input/resource-assignment-input.json", ExecutionServiceInput::class.java)!!
// Assign Workflow inputs Mock
val input = executionServiceInput.payload.get("resource-assignment-request")
bluePrintRuntimeService.assignWorkflowInputs("resource-assignment", input)
- val executionServiceOutput = dgWorkflowExecutionService.executeBluePrintWorkflow(bluePrintRuntimeService,
- executionServiceInput, mutableMapOf())
+ val executionServiceOutput = dgWorkflowExecutionService.executeBluePrintWorkflow(
+ bluePrintRuntimeService,
+ executionServiceInput, mutableMapOf()
+ )
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
-
}
-
-
}
}
fun mockServiceTemplate(): ServiceTemplate {
- return serviceTemplate("imperative-test", "1.0.0",
- "brindasanth@onap.com", "tosca") {
+ return serviceTemplate(
+ "imperative-test", "1.0.0",
+ "brindasanth@onap.com", "tosca"
+ ) {
topologyTemplate {
- nodeTemplate(mockNodeTemplateComponentScriptExecutor("resolve-config",
- "cba.wt.imperative.test.ResolveConfig"))
- nodeTemplate(mockNodeTemplateComponentScriptExecutor("activate-config",
- "cba.wt.imperative.test.ActivateConfig"))
- nodeTemplate(mockNodeTemplateComponentScriptExecutor("activate-config-rollback",
- "cba.wt.imperative.test.ActivateConfigRollback"))
- nodeTemplate(mockNodeTemplateComponentScriptExecutor("activate-licence",
- "cba.wt.imperative.test.ActivateLicence"))
+ nodeTemplate(
+ mockNodeTemplateComponentScriptExecutor(
+ "resolve-config",
+ "cba.wt.imperative.test.ResolveConfig"
+ )
+ )
+ nodeTemplate(
+ mockNodeTemplateComponentScriptExecutor(
+ "activate-config",
+ "cba.wt.imperative.test.ActivateConfig"
+ )
+ )
+ nodeTemplate(
+ mockNodeTemplateComponentScriptExecutor(
+ "activate-config-rollback",
+ "cba.wt.imperative.test.ActivateConfigRollback"
+ )
+ )
+ nodeTemplate(
+ mockNodeTemplateComponentScriptExecutor(
+ "activate-licence",
+ "cba.wt.imperative.test.ActivateLicence"
+ )
+ )
workflow("imperative-test-wf", "Test Imperative flow") {
step("resolve-config", "resolve-config", "") {
val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("12345", bluePrintContext)
val executionServiceInput = JacksonUtils
- .readValueFromClassPathFile("execution-input/imperative-test-input.json",
- ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile(
+ "execution-input/imperative-test-input.json",
+ ExecutionServiceInput::class.java
+ )!!
val bluePrintWorkFlowService = ImperativeBluePrintWorkflowService(NodeTemplateExecutionService())
val imperativeWorkflowExecutionService = ImperativeWorkflowExecutionService(bluePrintWorkFlowService)
val output = imperativeWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
assertNotNull(output, "failed to get imperative workflow output")
assertNotNull(output.status, "failed to get imperative workflow output status")
assertEquals(output.status.message, BluePrintConstants.STATUS_SUCCESS)
assertEquals(output.status.eventType, EventType.EVENT_COMPONENT_EXECUTED.name)
}
}
-}
\ No newline at end of file
+}
@ContextConfiguration(classes = [WorkflowServiceConfiguration::class])
class NodeTemplateExecutionServiceTest {
+
@Before
fun init() {
mockkObject(BluePrintDependencyService)
@Test
fun testExecuteNodeTemplate() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/resource-assignment-input.json",
- ExecutionServiceInput::class.java)!!
+ val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
+ "execution-input/resource-assignment-input.json",
+ ExecutionServiceInput::class.java
+ )!!
// Assign Workflow inputs Mock
val input = executionServiceInput.payload.get("resource-assignment-request")
val nodeTemplate = "resource-assignment"
val nodeTemplateExecutionService = NodeTemplateExecutionService()
val executionServiceOutput = nodeTemplateExecutionService
- .executeNodeTemplate(bluePrintRuntimeService, nodeTemplate, executionServiceInput)
+ .executeNodeTemplate(bluePrintRuntimeService, nodeTemplate, executionServiceInput)
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
}
-}
\ No newline at end of file
+}
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
-fun mockNodeTemplateComponentScriptExecutor(id: String, script: String) = BluePrintTypes.nodeTemplateComponentScriptExecutor(id,
- "mock($id) component function") {
+fun mockNodeTemplateComponentScriptExecutor(id: String, script: String) = BluePrintTypes.nodeTemplateComponentScriptExecutor(
+ id,
+ "mock($id) component function"
+) {
definedOperation("") {
inputs {
type("kotlin")
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
log.info("Processing component : $operationInputs")
- bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName,
- "assignment-params", "params".asJsonPrimitive())
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ nodeTemplateName,
+ "assignment-params", "params".asJsonPrimitive()
+ )
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
log.info("Recovering component..")
}
-}
\ No newline at end of file
+}
const val MODEL_TYPE_ARTIFACT_SCRIPT_KOTLIN = "artifact-script-kotlin"
const val MODEL_TYPE_ARTIFACT_DIRECTED_GRAPH = "artifact-directed-graph"
const val MODEL_TYPE_ARTIFACT_COMPONENT_JAR = "artifact-component-jar"
-}
\ No newline at end of file
+}
fun addError(error: String) {
this.errors.add(error)
}
-}
\ No newline at end of file
+}
*/
package org.onap.ccsdk.cds.controllerblueprints.core
+
/**
*
*
this.code = code
}
- constructor(code: Int, cause: Throwable, message: String, vararg args: Any?)
- : super(String.format(message, *args), cause) {
+ constructor(code: Int, cause: Throwable, message: String, vararg args: Any?) :
+ super(String.format(message, *args), cause) {
this.code = code
}
}
-
package org.onap.ccsdk.cds.controllerblueprints.core
-import org.onap.ccsdk.cds.controllerblueprints.core.annotations.*
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.ArtifactExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.AttributeExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsConstrain
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsDataType
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsProperty
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.DSLExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.InputExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.OperationOutputExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyDefaultValue
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyExpression
import org.onap.ccsdk.cds.controllerblueprints.core.data.ConstraintClause
import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema
import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
-import org.onap.ccsdk.cds.controllerblueprints.core.dsl.*
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.dslExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getInput
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateArtifact
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateAttribute
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateOperationOutput
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.KType
property.entrySchema = this.returnType.entitySchema()
}
this.annotations.forEach { fieldAnnotation ->
- //println("Field : ${this.name} : Annotation : $fieldAnnotation")
+ // println("Field : ${this.name} : Annotation : $fieldAnnotation")
when (fieldAnnotation) {
is BluePrintsProperty ->
property.description = fieldAnnotation.description
property.value = getInput(fieldAnnotation.propertyName)
}
is PropertyExpression -> {
- property.value = getNodeTemplateProperty(fieldAnnotation.modelableEntityName,
- fieldAnnotation.propertyName, fieldAnnotation.subPropertyName)
+ property.value = getNodeTemplateProperty(
+ fieldAnnotation.modelableEntityName,
+ fieldAnnotation.propertyName, fieldAnnotation.subPropertyName
+ )
}
is AttributeExpression -> {
- property.value = getNodeTemplateAttribute(fieldAnnotation.modelableEntityName,
- fieldAnnotation.attributeName, fieldAnnotation.subAttributeName)
+ property.value = getNodeTemplateAttribute(
+ fieldAnnotation.modelableEntityName,
+ fieldAnnotation.attributeName, fieldAnnotation.subAttributeName
+ )
}
is ArtifactExpression -> {
- property.value = getNodeTemplateArtifact(fieldAnnotation.modelableEntityName,
- fieldAnnotation.artifactName)
+ property.value = getNodeTemplateArtifact(
+ fieldAnnotation.modelableEntityName,
+ fieldAnnotation.artifactName
+ )
}
is OperationOutputExpression -> {
- property.value = getNodeTemplateOperationOutput(fieldAnnotation.modelableEntityName,
- fieldAnnotation.interfaceName, fieldAnnotation.propertyName, fieldAnnotation.subPropertyName)
+ property.value = getNodeTemplateOperationOutput(
+ fieldAnnotation.modelableEntityName,
+ fieldAnnotation.interfaceName, fieldAnnotation.propertyName, fieldAnnotation.subPropertyName
+ )
}
is DSLExpression -> {
property.value = dslExpression(fieldAnnotation.propertyName)
internal fun <T : KType> T.asBluePrintsDataType(propertyName: String): String {
val simpleName = (this.classifier as? KClass<*>)?.java?.simpleName
- ?: throw BluePrintException("filed to get simple name.")
+ ?: throw BluePrintException("filed to get simple name.")
return when (simpleName) {
"String", "Date" -> BluePrintConstants.DATA_TYPE_STRING
"int" -> BluePrintConstants.DATA_TYPE_INTEGER
"Boolean" -> BluePrintConstants.DATA_TYPE_BOOLEAN
"Float" -> BluePrintConstants.DATA_TYPE_FLOAT
"Double" -> BluePrintConstants.DATA_TYPE_DOUBLE
- "List" -> BluePrintConstants.DATA_TYPE_LIST
+ "List" -> BluePrintConstants.DATA_TYPE_LIST
"Map" -> BluePrintConstants.DATA_TYPE_MAP
"Object", "JsonNode", "ObjectNode", "ArrayNode" -> BluePrintConstants.DATA_TYPE_JSON
else -> simpleName
}
-}
\ No newline at end of file
+}
* @author Brinda Santh
*/
class BluePrintProcessorException : RuntimeException {
+
var code: Int = 100
constructor(message: String, cause: Throwable) : super(message, cause)
this.code = code
}
- constructor(code: Int, cause: Throwable, message: String, vararg args: Any?)
- : super(String.format(message, *args), cause) {
+ constructor(code: Int, cause: Throwable, message: String, vararg args: Any?) :
+ super(String.format(message, *args), cause) {
this.code = code
}
}
@JvmStatic
val validNodeTypeDerivedFroms: MutableList<String> = arrayListOf(
- BluePrintConstants.MODEL_TYPE_NODES_ROOT,
- BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW,
- BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
- BluePrintConstants.MODEL_TYPE_NODE_VNF,
- BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
- BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA,
- BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_BUNDLE,
- BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_SCRIPT,
- BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_PYTHON,
- BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JYTHON,
- BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA_SCRIPT
+ BluePrintConstants.MODEL_TYPE_NODES_ROOT,
+ BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW,
+ BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
+ BluePrintConstants.MODEL_TYPE_NODE_VNF,
+ BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
+ BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA,
+ BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_BUNDLE,
+ BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_SCRIPT,
+ BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_PYTHON,
+ BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JYTHON,
+ BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA_SCRIPT
)
@JvmStatic
val validArtifactTypeDerivedFroms: MutableList<String> = arrayListOf(
- BluePrintConstants.MODEL_TYPE_ARTIFACTS_ROOT,
- BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION
+ BluePrintConstants.MODEL_TYPE_ARTIFACTS_ROOT,
+ BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION
)
@JvmStatic
val validDataTypeDerivedFroms: MutableList<String> = arrayListOf(
- BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT,
- BluePrintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC
+ BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT,
+ BluePrintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC
)
@JvmStatic
val validRelationShipDerivedFroms: MutableList<String> = arrayListOf(
- BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT,
- BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON,
- BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_HOSTED_ON,
- BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO,
- BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ATTACH_TO,
- BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROUTES_TO
+ BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT,
+ BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON,
+ BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_HOSTED_ON,
+ BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO,
+ BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ATTACH_TO,
+ BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROUTES_TO
)
@JvmStatic
val validCapabilityTypes: MutableList<String> = arrayListOf(
- BluePrintConstants.MODEL_TYPE_CAPABILITIES_ROOT,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NODE,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_COMPUTE,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETWORK,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_STORAGE,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_PUBLIC,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_ADMIN,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_DATABASE,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ATTACHMENT,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_OPERATION_SYSTEM,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_BINDABLE,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_CONTENT,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_MAPPING,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETCONF,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_SSH,
- BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_SFTP
+ BluePrintConstants.MODEL_TYPE_CAPABILITIES_ROOT,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NODE,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_COMPUTE,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETWORK,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_STORAGE,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_PUBLIC,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_ADMIN,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_DATABASE,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ATTACHMENT,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_OPERATION_SYSTEM,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_BINDABLE,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_CONTENT,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_MAPPING,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETCONF,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_SSH,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_SFTP
)
@JvmStatic
@JvmStatic
fun validPrimitiveOrCollectionPrimitive(propertyDefinition: PropertyDefinition): Boolean {
val entrySchema = propertyDefinition.entrySchema?.type ?: BluePrintConstants.DATA_TYPE_NULL
- return BluePrintTypes.validPropertyTypes().contains(propertyDefinition.type)
- && BluePrintTypes.validPrimitiveTypes().contains(entrySchema)
+ return BluePrintTypes.validPropertyTypes().contains(propertyDefinition.type) &&
+ BluePrintTypes.validPrimitiveTypes().contains(entrySchema)
}
@JvmStatic
fun validCommands(): List<String> {
- return listOf(BluePrintConstants.EXPRESSION_DSL_REFERENCE,
- BluePrintConstants.EXPRESSION_GET_INPUT,
- BluePrintConstants.EXPRESSION_GET_ATTRIBUTE,
- BluePrintConstants.EXPRESSION_GET_PROPERTY,
- BluePrintConstants.EXPRESSION_GET_ARTIFACT,
- BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT,
- BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE)
+ return listOf(
+ BluePrintConstants.EXPRESSION_DSL_REFERENCE,
+ BluePrintConstants.EXPRESSION_GET_INPUT,
+ BluePrintConstants.EXPRESSION_GET_ATTRIBUTE,
+ BluePrintConstants.EXPRESSION_GET_PROPERTY,
+ BluePrintConstants.EXPRESSION_GET_ARTIFACT,
+ BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT,
+ BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE
+ )
}
@JvmStatic
fun rootDataTypes(): List<String> {
return listOf(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT)
}
-
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core
import com.fasterxml.jackson.databind.JsonNode
-import com.fasterxml.jackson.databind.node.*
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.BooleanNode
+import com.fasterxml.jackson.databind.node.DoubleNode
+import com.fasterxml.jackson.databind.node.IntNode
+import com.fasterxml.jackson.databind.node.MissingNode
+import com.fasterxml.jackson.databind.node.NullNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+import com.fasterxml.jackson.databind.node.TextNode
import org.apache.commons.lang3.ObjectUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JsonParserUtils
import org.slf4j.LoggerFactory
import org.slf4j.helpers.MessageFormatter
-import java.util.*
+import java.util.UUID
import kotlin.reflect.KClass
/**
}
fun String.isJson(): Boolean {
- return ((this.trim().startsWith("{") && this.trim().endsWith("}"))
- || (this.trim().startsWith("[") && this.trim().endsWith("]")))
+ return ((this.trim().startsWith("{") && this.trim().endsWith("}")) ||
+ (this.trim().startsWith("[") && this.trim().endsWith("]")))
}
fun Any.asJsonString(intend: Boolean? = false): String {
fun <T> JsonNode.asType(clazzType: Class<T>): T {
return JacksonUtils.readValue(this, clazzType)
- ?: throw BluePrintException("couldn't convert JsonNode of type $clazzType")
+ ?: throw BluePrintException("couldn't convert JsonNode of type $clazzType")
}
fun JsonNode.asListOfString(): List<String> {
}
}
-
fun MutableMap<String, JsonNode>.putJsonElement(key: String, value: Any) {
val convertedValue = value.asJsonType()
this[key] = convertedValue
check(this.isComplexType()) { "$this is not complex or array node to apply expression" }
return JsonParserUtils.paths(this, expression)
}
-
-
fun Graph.findAllPaths(from: String, to: String, path: List<String> = emptyList()): List<List<String>> {
if (from == to) return listOf(path + to)
return nodes[from]!!.neighbors()
- .filter { !path.contains(it.id) }
- .flatMap { findAllPaths(it.id, to, path + from) }
+ .filter { !path.contains(it.id) }
+ .flatMap { findAllPaths(it.id, to, path + from) }
}
fun Graph.findCycles(node: String): List<List<String>> {
fun findCycles(path: List<String>): List<List<String>> {
if (path.size > 3 && path.first() == path.last()) return listOf(path)
return nodes[path.last()]!!.neighbors()
- .filterNot { path.tail().contains(it.id) }
- .flatMap { findCycles(path + it.id) }
+ .filterNot { path.tail().contains(it.id) }
+ .flatMap { findCycles(path + it.id) }
}
return findCycles(listOf(node))
}
fun Graph.node(node: String) = this.nodes[node]
fun Graph.edge(label: EdgeLabel) =
- this.edges.filter { it.label == label }
+ this.edges.filter { it.label == label }
fun Graph.incomingEdges(node: String) =
- this.edges.filter { it.target.id == node }
+ this.edges.filter { it.target.id == node }
fun Graph.incomingNodes(node: String) =
- this.incomingEdges(node).map { it.source }
+ this.incomingEdges(node).map { it.source }
fun Graph.outgoingEdges(node: String) =
- this.edges.filter { it.source.id == node }
+ this.edges.filter { it.source.id == node }
fun Graph.outgoingNodes(node: String) =
- this.outgoingEdges(node).map { it.target }
+ this.outgoingEdges(node).map { it.target }
fun Graph.outgoingEdges(node: String, label: EdgeLabel) =
- this.edges.filter { it.source.id == node && it.label == label }
+ this.edges.filter { it.source.id == node && it.label == label }
fun Graph.outgoingNodes(node: String, label: EdgeLabel) =
- this.outgoingEdges(node, label).map { it.target }
+ this.outgoingEdges(node, label).map { it.target }
fun Graph.outgoingNodesNotInEdgeLabels(node: String, labels: List<EdgeLabel>) =
- this.outgoingEdgesNotInLabels(node, labels).map { it.target }
+ this.outgoingEdgesNotInLabels(node, labels).map { it.target }
fun Graph.outgoingEdges(node: String, labels: List<EdgeLabel>) =
- this.edges.filter { it.source.id == node && labels.contains(it.label) }
+ this.edges.filter { it.source.id == node && labels.contains(it.label) }
fun Graph.outgoingEdgesNotInLabels(node: String, labels: List<EdgeLabel>) =
- this.edges.filter { it.source.id == node && !labels.contains(it.label) }
+ this.edges.filter { it.source.id == node && !labels.contains(it.label) }
fun Graph.outgoingNodes(node: String, labels: List<EdgeLabel>) =
- this.outgoingEdges(node, labels).map { it.target }
+ this.outgoingEdges(node, labels).map { it.target }
fun Graph.isEndNode(node: Graph.Node): Boolean {
return this.endNodes().contains(node)
}
fun <T> List<T>.tail(): List<T> = drop(1)
-
typealias MDCContextMap = Map<String, String>?
class MDCContext(private val contextMap: MDCContextMap = MDC.getCopyOfContextMap()) :
- ThreadContextElement<MDCContextMap>, AbstractCoroutineContextElement(Key) {
+ ThreadContextElement<MDCContextMap>, AbstractCoroutineContextElement(Key) {
+
/**
* Key of [MDCContext] in [CoroutineContext].
*/
MDC.setContextMap(contextMap)
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.annotations
-
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import kotlin.reflect.KClass
@Target(AnnotationTarget.CLASS)
annotation class BluePrintsDataType(
- val name: String,
- val version: String = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- val description: String,
- val derivedFrom: String = "tosca.datatypes.root"
+ val name: String,
+ val version: String = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ val description: String,
+ val derivedFrom: String = "tosca.datatypes.root"
)
@Target(AnnotationTarget.CLASS)
annotation class BluePrintsWorkflowOutput
@Target(AnnotationTarget.CLASS)
-annotation class BluePrintsNodeType(val propertiesType: KClass<*>, val attributesType: KClass<*>,
- val inputsType: KClass<*>, val outputsType: KClass<*>)
+annotation class BluePrintsNodeType(
+ val propertiesType: KClass<*>,
+ val attributesType: KClass<*>,
+ val inputsType: KClass<*>,
+ val outputsType: KClass<*>
+)
@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
annotation class BluePrintsProperty(
- val name: String = "",
- val description: String = ""
+ val name: String = "",
+ val description: String = ""
)
@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
annotation class InputExpression(
- val propertyName: String
+ val propertyName: String
)
@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
annotation class PropertyExpression(
- val modelableEntityName: String = "SELF",
- val reqOrCapEntityName: String = "",
- val propertyName: String,
- val subPropertyName: String = ""
+ val modelableEntityName: String = "SELF",
+ val reqOrCapEntityName: String = "",
+ val propertyName: String,
+ val subPropertyName: String = ""
)
@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
annotation class AttributeExpression(
- val modelableEntityName: String = "SELF",
- val reqOrCapEntityName: String = "",
- val attributeName: String,
- val subAttributeName: String = ""
+ val modelableEntityName: String = "SELF",
+ val reqOrCapEntityName: String = "",
+ val attributeName: String,
+ val subAttributeName: String = ""
)
@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
annotation class ArtifactExpression(
- val modelableEntityName: String = "SELF",
- val artifactName: String,
- val location: String = "LOCAL_FILE",
- val remove: Boolean = false
+ val modelableEntityName: String = "SELF",
+ val artifactName: String,
+ val location: String = "LOCAL_FILE",
+ val remove: Boolean = false
)
@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
annotation class OperationOutputExpression(
- val modelableEntityName: String = "SELF",
- val interfaceName: String,
- val operationName: String,
- val propertyName: String,
- val subPropertyName: String = ""
+ val modelableEntityName: String = "SELF",
+ val interfaceName: String,
+ val operationName: String,
+ val propertyName: String,
+ val subPropertyName: String = ""
)
@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
annotation class DSLExpression(
- val propertyName: String
-)
\ No newline at end of file
+ val propertyName: String
+)
package org.onap.ccsdk.cds.controllerblueprints.core.config
-
open class BluePrintLoadConfiguration {
lateinit var blueprintDeployPath: String
lateinit var blueprintArchivePath: String
lateinit var blueprintWorkingPath: String
-
+
var loadBluePrintPaths: String? = null
var loadModeTypePaths: String? = null
var loadResourceDictionaryPaths: String? = null
-}
\ No newline at end of file
+}
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ObjectNode
+
/**
*
*
* @author Brinda Santh
*/
data class ExpressionData(
- var isExpression: Boolean = false,
- var valueNode: JsonNode,
- var expressionNode: ObjectNode? = null,
- var dslExpression: DSLExpression? = null,
- var inputExpression: InputExpression? = null,
- var propertyExpression: PropertyExpression? = null,
- var attributeExpression: AttributeExpression? = null,
- var artifactExpression: ArtifactExpression? = null,
- var operationOutputExpression: OperationOutputExpression? = null,
- var command: String? = null
+ var isExpression: Boolean = false,
+ var valueNode: JsonNode,
+ var expressionNode: ObjectNode? = null,
+ var dslExpression: DSLExpression? = null,
+ var inputExpression: InputExpression? = null,
+ var propertyExpression: PropertyExpression? = null,
+ var attributeExpression: AttributeExpression? = null,
+ var artifactExpression: ArtifactExpression? = null,
+ var operationOutputExpression: OperationOutputExpression? = null,
+ var command: String? = null
)
data class InputExpression(
- var propertyName: String
+ var propertyName: String
)
data class PropertyExpression(
- var modelableEntityName: String = "SELF",
- var reqOrCapEntityName: String? = null,
- var propertyName: String,
- var subPropertyName: String? = null
+ var modelableEntityName: String = "SELF",
+ var reqOrCapEntityName: String? = null,
+ var propertyName: String,
+ var subPropertyName: String? = null
)
data class AttributeExpression(
- var modelableEntityName: String = "SELF",
- var reqOrCapEntityName: String? = null,
- var attributeName: String,
- var subAttributeName: String? = null
+ var modelableEntityName: String = "SELF",
+ var reqOrCapEntityName: String? = null,
+ var attributeName: String,
+ var subAttributeName: String? = null
)
data class ArtifactExpression(
- val modelableEntityName: String = "SELF",
- val artifactName: String,
- val location: String? = "LOCAL_FILE",
- val remove: Boolean? = false
+ val modelableEntityName: String = "SELF",
+ val artifactName: String,
+ val location: String? = "LOCAL_FILE",
+ val remove: Boolean? = false
)
data class OperationOutputExpression(
- val modelableEntityName: String = "SELF",
- val interfaceName: String,
- val operationName: String,
- val propertyName: String,
- var subPropertyName: String? = null
+ val modelableEntityName: String = "SELF",
+ val interfaceName: String,
+ val operationName: String,
+ val propertyName: String,
+ var subPropertyName: String? = null
)
data class DSLExpression(
- val propertyName: String
+ val propertyName: String
)
-
-
fun neighbors(): List<Node> = edges.map { edge -> edge.target(this) }
fun neighbors(label: EdgeLabel): List<Node> = edges.filter { it.label == label }
- .map { edge -> edge.target(this) }
+ .map { edge -> edge.target(this) }
fun labelEdges(label: EdgeLabel): List<Edge> = edges.filter { it.label == label }
}
data class Edge(
- val source: Node,
- val target: Node,
- val label: EdgeLabel,
- var status: EdgeStatus = EdgeStatus.NOT_STARTED) {
+ val source: Node,
+ val target: Node,
+ val label: EdgeLabel,
+ var status: EdgeStatus = EdgeStatus.NOT_STARTED
+ ) {
fun target(node: Node): Node = target
fun equivalentTo(other: Edge) =
- (source == other.source && target == other.target)
- || (source == other.target && target == other.source)
+ (source == other.source && target == other.target) ||
+ (source == other.target && target == other.source)
override fun toString() =
- "${source.id}>${target.id}/$label($status)"
+ "${source.id}>${target.id}/$label($status)"
}
data class TermForm(val nodes: Collection<String>, val edges: List<Term>) {
companion object {
fun labeledDirectedTerms(termForm: TermForm): Graph =
- createFromTerms(termForm) { graph, n1, n2, value -> graph.addEdge(n1, n2, value) }
+ createFromTerms(termForm) { graph, n1, n2, value -> graph.addEdge(n1, n2, value) }
fun labeledDirectedAdjacent(adjacencyList: AdjacencyList<String, EdgeLabel>): Graph =
- fromAdjacencyList(adjacencyList) { graph, n1, n2, value ->
- graph.addEdge(n1, n2, value)
- }
+ fromAdjacencyList(adjacencyList) { graph, n1, n2, value ->
+ graph.addEdge(n1, n2, value)
+ }
- private fun createFromTerms(termForm: TermForm,
- addFunction: (Graph, String, String, EdgeLabel) -> Unit): Graph {
+ private fun createFromTerms(
+ termForm: TermForm,
+ addFunction: (Graph, String, String, EdgeLabel) -> Unit
+ ): Graph {
val graph = Graph()
termForm.nodes.forEach { graph.addNode(it) }
termForm.edges.forEach { addFunction(graph, it.source, it.target, it.label) }
return graph
}
- private fun fromAdjacencyList(adjacencyList: AdjacencyList<String, EdgeLabel>,
- addFunction: (Graph, String, String, EdgeLabel) -> Unit): Graph {
+ private fun fromAdjacencyList(
+ adjacencyList: AdjacencyList<String, EdgeLabel>,
+ addFunction: (Graph, String, String, EdgeLabel) -> Unit
+ ): Graph {
val graph = Graph()
adjacencyList.entries.forEach { graph.addNode(it.node) }
adjacencyList.entries.forEach { (node, links) ->
return graph
}
}
-}
\ No newline at end of file
+}
* @author Brinda Santh
*/
open class EntityType {
+
@get:JsonIgnore
var id: String? = null
var description: String? = null
authorization credentials used to access network accessible resources.
*/
class Credential {
+
@get:JsonIgnore
var id: String? = null
var protocol: String? = null
A constraint clause defines an operation along with one or more compatible values that can be used to define a constraint on a property or parameter’s allowed values when it is defined in a TOSCA Service Template or one of its entities.
*/
class ConstraintClause {
+
var equal: JsonNode? = null
@get:JsonProperty("greater_than")
var greaterThan: JsonNode? = null
and implementation artifacts that are referenced within the TOSCA Service Template.
*/
class RepositoryDefinition {
+
@get:JsonIgnore
var id: String? = null
var description: String? = null
var credential: Credential? = null
}
-
/*
3.5.6 Artifact definition
An artifact definition defines a named, typed file that can be associated with Node Type
or Node Template and used by orchestration engine to facilitate deployment and implementation of interface operations.
*/
class ArtifactDefinition {
+
@get:JsonIgnore
var id: String? = null
lateinit var type: String
var properties: MutableMap<String, JsonNode>? = null
}
-
/*
3.5.7 Import definition
An import definition is used within a TOSCA Service Template to locate and uniquely name
and referenced within another Service Template.
*/
class ImportDefinition {
+
@get:JsonIgnore
var id: String? = null
lateinit var file: String
instantiated. The value of a property can be retrieved using the get_property function within TOSCA Service Templates.
*/
class PropertyDefinition {
+
@get:JsonIgnore
var id: String? = null
var description: String? = null
var value: JsonNode? = null
}
-
/*
3.5.10 Attribute definition
An operation definition defines a named function or procedure that can be bound to an implementation artifact (e.g., a script).
*/
class OperationDefinition {
+
@get:JsonIgnore
var id: String? = null
var description: String? = null
var dependencies: MutableList<String>? = null
@get:JsonProperty("operation_host")
var operationHost: String = BluePrintConstants.PROPERTY_SELF
- //Timeout value in seconds
+ // Timeout value in seconds
var timeout: Int = 180
}
An interface definition defines a named interface that can be associated with a Node or Relationship Type
*/
class InterfaceDefinition {
+
@get:JsonIgnore
var id: String? = null
var type: String? = null
An event filter definition defines criteria for selection of an attribute, for the purpose of monitoring it, within a TOSCA entity, or one its capabilities.
*/
class EventFilterDefinition {
+
@get:JsonIgnore
var id: String? = null
lateinit var node: String
A trigger definition defines the event, condition and action that is used to “trigger” a policy it is associated with.
*/
class TriggerDefinition {
+
@get:JsonIgnore
var id: String? = null
var description: String? = null
· Inline another workflow defined in the topology (to allow reusability)
*/
class Activity {
+
var delegate: String? = null
@get:JsonProperty("set_state")
var setState: String? = null
A workflow condition can be used as a filter or precondition to check if a workflow can be processed or not based on the state of the instances of a TOSCA topology deployment. When not met, the workflow will not be triggered.
*/
class PreConditionDefinition {
+
@get:JsonIgnore
var id: String? = null
lateinit var target: String
A workflow step allows to define one or multiple sequenced activities in a workflow and how they are connected to other steps in the workflow. They are the building blocks of a declarative workflow.
*/
class Step {
+
@get:JsonIgnore
var id: String? = null
var description: String? = null
The Requirement definition describes a named requirement (dependencies) of a TOSCA Node Type or Node template which needs to be fulfilled by a matching Capability definition declared by another TOSCA modelable entity. The requirement definition may itself include the specific name of the fulfilling entity (explicitly) or provide an abstract type, along with additional filtering characteristics, that a TOSCA orchestrator can use to fulfill the capability at runtime (implicitly).
*/
class RequirementDefinition {
+
@get:JsonIgnore
var id: String? = null
var description: String? = null
An Artifact Type is a reusable entity that defines the type of one or more files that are used to define implementation or deployment artifacts that are referenced by nodes or relationships on their operations.
*/
class ArtifactType : EntityType() {
+
@get:JsonProperty("mime_type")
var mimeType: String? = null
@get:JsonProperty("file_ext")
var fileExt: MutableList<String>? = null
-
}
/*
var requirements: ArrayList<RequirementDefinition>? = null
var capabilities: MutableMap<String, CapabilityDefinition>? = null
var interfaces: MutableMap<String, InterfaceDefinition>? = null
-
}
/*
(i.e., it does not prevent the application or service from being deployed or run if it did not exist).
*/
class PolicyType : EntityType() {
+
lateinit var targets: MutableList<String>
}
A capability assignment allows node template authors to assign values to properties and attributes for a named capability definition that is part of a Node Template’s type definition.
*/
class CapabilityAssignment {
+
@get:JsonIgnore
var id: String? = null
var attributes: MutableMap<String, JsonNode>? = null
A Relationship Template specifies the occurrence of a manageable relationship between node templates as part of an application’s topology model that is defined in a TOSCA Service Template. A Relationship template is an instance of a specified Relationship Type and can provide customized properties, constraints or operations which override the defaults provided by its Relationship Type and its implementations.
*/
class GroupDefinition {
+
@get:JsonIgnore
var id: String? = null
lateinit var type: String
A policy definition defines a policy that can be associated with a TOSCA topology or top-level entity definition (e.g., group definition, node template, etc.).
*/
class PolicyDefinition {
+
@get:JsonIgnore
var id: String? = null
lateinit var type: String
var targets: MutableList<String>? = null
}
-
/*
3.8 Topology Template definition
This section defines the topology template of a cloud application. The main ingredients of the topology template are node templates representing components of the application and relationship templates representing links between the components. These elements are defined in the nested node_templates section and the nested relationship_templates sections, respectively. Furthermore, a topology template allows for defining input parameters, output parameters as well as grouping of node templates.
*/
class TopologyTemplate {
+
@get:JsonIgnore
var id: String? = null
var description: String? = null
lateinit var type: String
var metadata: MutableMap<String, String>? = null
var directives: MutableList<String>? = null
- //@get:JsonSerialize(using = PropertyDefinitionValueSerializer::class)
+ // @get:JsonSerialize(using = PropertyDefinitionValueSerializer::class)
var properties: MutableMap<String, JsonNode>? = null
var attributes: MutableMap<String, JsonNode>? = null
var capabilities: MutableMap<String, CapabilityAssignment>? = null
var id: String? = null
var capability: String? = null
var node: String? = null
- //Relationship Type or Relationship Template
+ // Relationship Type or Relationship Template
var relationship: String? = null
}
-
class Workflow {
@get:JsonIgnore
var id: String? = null
var outputs: MutableMap<String, PropertyDefinition>? = null
}
-
class ConditionClause {
var and: ArrayList<MutableMap<String, Any>>? = null
var or: ArrayList<MutableMap<String, Any>>? = null
A TOSCA Service Template (YAML) document contains element definitions of building blocks for cloud application, or complete models of cloud applications. This section describes the top-level structural elements (TOSCA keynames) along with their grammars, which are allowed to appear in a TOSCA Service Template document.
*/
-@JsonPropertyOrder(value = ["toscaDefinitionsVersion", "description", "metadata", "imports", "dsl_definitions",
- "topologyTemplate"])
+@JsonPropertyOrder(
+ value = ["toscaDefinitionsVersion", "description", "metadata", "imports", "dsl_definitions",
+ "topologyTemplate"]
+)
class ServiceTemplate : Cloneable {
+
@get:JsonIgnore
var id: String? = null
@get:JsonProperty("tosca_definitions_version")
@get:JsonProperty("topology_template")
var topologyTemplate: TopologyTemplate? = null
- override public fun clone(): ServiceTemplate {
+ public override fun clone(): ServiceTemplate {
return super.clone() as ServiceTemplate
}
}
var templateVersion: String? = null
var templateTags: String? = null
}
-
* @author Steve Siani
* @version 1.0
*/
-enum class ErrorCode (val value: Int, val httpCode: Int) {
+enum class ErrorCode(val value: Int, val httpCode: Int) {
- /// TODO: Add more attribute for each needed application protocol
+ // / TODO: Add more attribute for each needed application protocol
// TODO: Example: INVALID_FILE_EXTENSION(2, 415, 25)
GENERIC_FAILURE(1, 500) {
+
override fun message(detailMsg: String): String {
return "Generic failure. Details : {$detailMsg}"
}
return if (map.containsKey(value)) map[value] else map[1]
}
}
-}
\ No newline at end of file
+}
abstract class AbstractNodeTemplateOperationImplBuilder<Prop : PropertiesAssignmentBuilder,
In : PropertiesAssignmentBuilder, Out : PropertiesAssignmentBuilder>(
- id: String, type: String, private val interfaceName: String, description: String
-) : AbstractNodeTemplatePropertyImplBuilder<Prop>(id, type, description) {
+ id: String,
+ type: String,
+ private val interfaceName: String,
+ description: String
+ ) : AbstractNodeTemplatePropertyImplBuilder<Prop>(id, type, description) {
open fun definedOperation(description: String, block: OperationAssignmentBuilder<In, Out>.() -> Unit) {
typedOperation<In, Out>(interfaceName, description, block)
}
abstract class AbstractNodeTemplatePropertyImplBuilder<Prop : PropertiesAssignmentBuilder>(
- id: String, type: String, description: String
+ id: String,
+ type: String,
+ description: String
) : NodeTemplateBuilder(id, type, description) {
open fun definedProperties(block: Prop.() -> Unit) {
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
// CDS DSLs
-fun blueprint(name: String, version: String, author: String, tags: String,
- block: DSLBluePrintBuilder.() -> Unit): DSLBluePrint {
+fun blueprint(
+ name: String,
+ version: String,
+ author: String,
+ tags: String,
+ block: DSLBluePrintBuilder.() -> Unit
+): DSLBluePrint {
return DSLBluePrintBuilder(name, version, author, tags).apply(block).build()
}
// TOSCA DSLs
-fun serviceTemplate(name: String, version: String, author: String, tags: String,
- block: ServiceTemplateBuilder.() -> Unit): ServiceTemplate {
- return ServiceTemplateBuilder(name, version, author, tags).apply(block).build()
+fun serviceTemplate(
+ name: String,
+ version: String,
+ author: String,
+ tags: String,
+ block: BluePrintServiceDSLBuilder.() -> Unit
+): ServiceTemplate {
+ return BluePrintServiceDSLBuilder(name, version, author, tags).apply(block).build()
}
fun workflow(id: String, description: String, block: WorkflowBuilder.() -> Unit): Workflow {
return WorkflowBuilder(id, description).apply(block).build()
}
-fun nodeTemplate(id: String, type: String, description: String,
- block: NodeTemplateBuilder.() -> Unit): NodeTemplate {
+fun nodeTemplate(
+ id: String,
+ type: String,
+ description: String,
+ block: NodeTemplateBuilder.() -> Unit
+): NodeTemplate {
return NodeTemplateBuilder(id, type, description).apply(block).build()
}
-fun nodeType(id: String, version: String, derivedFrom: String, description: String,
- block: NodeTypeBuilder.() -> Unit): NodeType {
+fun nodeType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: NodeTypeBuilder.() -> Unit
+): NodeType {
return NodeTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
-fun dataType(id: String, version: String, derivedFrom: String, description: String,
- block: DataTypeBuilder.() -> Unit): DataType {
+fun dataType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: DataTypeBuilder.() -> Unit
+): DataType {
return DataTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
-fun artifactType(id: String, version: String, derivedFrom: String, description: String,
- block: ArtifactTypeBuilder.() -> Unit): ArtifactType {
+fun artifactType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: ArtifactTypeBuilder.() -> Unit
+): ArtifactType {
return ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
-fun relationshipType(id: String, version: String, derivedFrom: String, description: String,
- block: RelationshipTypeBuilder.() -> Unit): RelationshipType {
+fun relationshipType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: RelationshipTypeBuilder.() -> Unit
+): RelationshipType {
return RelationshipTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
// Operation Function
-fun getNodeTemplateOperationOutput(nodeTemplateName: String, interfaceName: String, propertyId: String,
- jsonPath: String? = null): JsonNode {
+fun getNodeTemplateOperationOutput(
+ nodeTemplateName: String,
+ interfaceName: String,
+ propertyId: String,
+ jsonPath: String? = null
+): JsonNode {
return """{"get_operation_output": ["$nodeTemplateName", "$interfaceName", "process","$propertyId","$jsonPath" ]}""".trimMargin().jsonAsJsonType()
}
/** Blueprint Type Extensions */
fun BluePrintTypes.nodeTypeComponent(): NodeType {
- return nodeType(id = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT,
- description = "This is default Component Node") {
+ return nodeType(
+ id = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT,
+ description = "This is default Component Node"
+ ) {
}
}
fun BluePrintTypes.nodeTypeWorkflow(): NodeType {
- return nodeType(id = BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT,
- description = "This is default Workflow Node") {
+ return nodeType(
+ id = BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT,
+ description = "This is default Workflow Node"
+ ) {
}
}
fun BluePrintTypes.nodeTypeVnf(): NodeType {
- return nodeType(id = BluePrintConstants.MODEL_TYPE_NODE_VNF,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT,
- description = "This is default VNF Node") {
+ return nodeType(
+ id = BluePrintConstants.MODEL_TYPE_NODE_VNF,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT,
+ description = "This is default VNF Node"
+ ) {
}
}
fun BluePrintTypes.nodeTypeResourceSource(): NodeType {
- return nodeType(id = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT,
- description = "This is default Resource Source Node") {
+ return nodeType(
+ id = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT,
+ description = "This is default Resource Source Node"
+ ) {
}
}
/** Artifacts */
fun BluePrintTypes.artifactTypeTemplateVelocity(): ArtifactType {
- return artifactType(id = BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
- description = "Velocity Artifact") {
+ return artifactType(
+ id = BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
+ description = "Velocity Artifact"
+ ) {
fileExt("vtl")
}
}
fun BluePrintTypes.artifactTypeTempleJinja(): ArtifactType {
- return artifactType(id = BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
- description = "Jinja Artifact") {
+ return artifactType(
+ id = BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
+ description = "Jinja Artifact"
+ ) {
fileExt("jinja")
}
}
fun BluePrintTypes.artifactTypeMappingResource(): ArtifactType {
- return artifactType(id = BluePrintConstants.MODEL_TYPE_ARTIFACT_MAPPING_RESOURCE,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
- description = "Mapping Resource Artifact") {
+ return artifactType(
+ id = BluePrintConstants.MODEL_TYPE_ARTIFACT_MAPPING_RESOURCE,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
+ description = "Mapping Resource Artifact"
+ ) {
fileExt("json")
}
}
fun BluePrintTypes.artifactTypeScriptJython(): ArtifactType {
- return artifactType(id = BluePrintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_JYTHON,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
- description = "Jython Script Artifact") {
+ return artifactType(
+ id = BluePrintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_JYTHON,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
+ description = "Jython Script Artifact"
+ ) {
fileExt("py")
}
}
fun BluePrintTypes.artifactTypeScriptKotlin(): ArtifactType {
- return artifactType(id = BluePrintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_KOTLIN,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
- description = "Kotlin Script Artifact") {
+ return artifactType(
+ id = BluePrintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_KOTLIN,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
+ description = "Kotlin Script Artifact"
+ ) {
fileExt("kts")
}
}
fun BluePrintTypes.artifactTypeDirectedGraph(): ArtifactType {
- return artifactType(id = BluePrintConstants.MODEL_TYPE_ARTIFACT_DIRECTED_GRAPH,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
- description = "Directed Graph Artifact") {
+ return artifactType(
+ id = BluePrintConstants.MODEL_TYPE_ARTIFACT_DIRECTED_GRAPH,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
+ description = "Directed Graph Artifact"
+ ) {
fileExt("xml", "json")
}
}
fun BluePrintTypes.artifactTypeComponentJar(): ArtifactType {
- return artifactType(id = BluePrintConstants.MODEL_TYPE_ARTIFACT_COMPONENT_JAR,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
- description = "Component Artifact") {
+ return artifactType(
+ id = BluePrintConstants.MODEL_TYPE_ARTIFACT_COMPONENT_JAR,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION,
+ description = "Component Artifact"
+ ) {
fileExt("jar")
}
}
/** Relationship Types */
fun BluePrintTypes.relationshipTypeConnectsTo(): RelationshipType {
- return relationshipType(id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT,
- description = "Relationship connects to") {
+ return relationshipType(
+ id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT,
+ description = "Relationship connects to"
+ ) {
}
}
fun BluePrintTypes.relationshipTypeDependsOn(): RelationshipType {
- return relationshipType(id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON,
- version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT,
- description = "Relationship depends on") {
+ return relationshipType(
+ id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON,
+ version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT,
+ description = "Relationship depends on"
+ ) {
}
}
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Step
/**
* @author Brinda Santh
*/
-class DSLBluePrintBuilder(private val name: String,
- private val version: String,
- private val author: String,
- private val tags: String) {
+class DSLBluePrintBuilder(
+ private val name: String,
+ private val version: String,
+ private val author: String,
+ private val tags: String
+) {
private var dslBluePrint = DSLBluePrint()
private var metadata: MutableMap<String, String> = hashMapOf()
dataTypes[dataType.id!!] = dataType
}
- fun dataType(id: String, version: String, derivedFrom: String, description: String,
- block: DataTypeBuilder.() -> Unit) {
+ fun dataType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: DataTypeBuilder.() -> Unit
+ ) {
dataTypes[id] = DataTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
artifactTypes[artifactType.id!!] = artifactType
}
- fun artifactType(id: String, version: String, derivedFrom: String, description: String,
- block: ArtifactTypeBuilder.() -> Unit) {
+ fun artifactType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: ArtifactTypeBuilder.() -> Unit
+ ) {
artifactTypes[id] = ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
- fun component(id: String, type: String, version: String, description: String,
- block: DSLComponentBuilder.() -> Unit) {
+ fun component(
+ id: String,
+ type: String,
+ version: String,
+ description: String,
+ block: DSLComponentBuilder.() -> Unit
+ ) {
components[id] = DSLComponentBuilder(id, type, version, description).apply(block).build()
}
- fun registryComponent(id: String, type: String, version: String, interfaceName: String, description: String,
- block: DSLRegistryComponentBuilder.() -> Unit) {
+ fun registryComponent(
+ id: String,
+ type: String,
+ version: String,
+ interfaceName: String,
+ description: String,
+ block: DSLRegistryComponentBuilder.() -> Unit
+ ) {
registryComponents[id] = DSLRegistryComponentBuilder(id, type, version, interfaceName, description)
- .apply(block).build()
+ .apply(block).build()
}
fun workflow(id: String, description: String, block: DSLWorkflowBuilder.() -> Unit) {
}
}
-class DSLComponentBuilder(private val id: String, private val type: String,
- private val version: String, private val description: String) {
+class DSLComponentBuilder(
+ private val id: String,
+ private val type: String,
+ private val version: String,
+ private val description: String
+) {
+
private val dslComponent = DSLComponent()
var properties: MutableMap<String, PropertyDefinition>? = null
var attributes: MutableMap<String, AttributeDefinition>? = null
attributes!![id] = attribute
}
- fun attribute(id: String, type: String, required: Boolean, expression: Any, description: String? = "",
- block: DSLAttributeDefinitionBuilder.() -> Unit) {
+ fun attribute(
+ id: String,
+ type: String,
+ required: Boolean,
+ expression: Any,
+ description: String? = "",
+ block: DSLAttributeDefinitionBuilder.() -> Unit
+ ) {
if (attributes == null)
attributes = hashMapOf()
val attribute = DSLAttributeDefinitionBuilder(id, type, required, expression.asJsonType(), description)
- .apply(block).build()
+ .apply(block).build()
attributes!![id] = attribute
}
properties!![id] = property
}
- fun property(id: String, type: String, required: Boolean, expression: Any, description: String? = "",
- block: DSLPropertyDefinitionBuilder.() -> Unit) {
+ fun property(
+ id: String,
+ type: String,
+ required: Boolean,
+ expression: Any,
+ description: String? = "",
+ block: DSLPropertyDefinitionBuilder.() -> Unit
+ ) {
if (properties == null)
properties = hashMapOf()
val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description)
- .apply(block).build()
+ .apply(block).build()
properties!![id] = property
}
artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build()
}
-
fun input(id: String, type: String, required: Boolean, expression: Any, description: String? = "") {
if (inputs == null)
inputs = hashMapOf()
inputs!![id] = property.build()
}
- fun input(id: String, type: String, required: Boolean, expression: Any, description: String? = "",
- block: DSLPropertyDefinitionBuilder.() -> Unit) {
+ fun input(
+ id: String,
+ type: String,
+ required: Boolean,
+ expression: Any,
+ description: String? = "",
+ block: DSLPropertyDefinitionBuilder.() -> Unit
+ ) {
if (inputs == null)
inputs = hashMapOf()
val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description)
- .apply(block).build()
+ .apply(block).build()
inputs!![id] = property
}
outputs!![id] = property.build()
}
- fun output(id: String, type: String, required: Boolean, expression: Any, description: String? = "",
- block: DSLPropertyDefinitionBuilder.() -> Unit) {
+ fun output(
+ id: String,
+ type: String,
+ required: Boolean,
+ expression: Any,
+ description: String? = "",
+ block: DSLPropertyDefinitionBuilder.() -> Unit
+ ) {
if (outputs == null)
outputs = hashMapOf()
val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description)
- .apply(block).build()
+ .apply(block).build()
outputs!![id] = property
}
}
}
-class DSLRegistryComponentBuilder(private val id: String, private val type: String,
- private val version: String,
- private val interfaceName: String,
- private val description: String) {
+class DSLRegistryComponentBuilder(
+ private val id: String,
+ private val type: String,
+ private val version: String,
+ private val interfaceName: String,
+ private val description: String
+) {
+
private val dslComponent = DSLRegistryComponent()
var properties: MutableMap<String, JsonNode>? = null
inputs!![id] = property.build()
}
- fun input(id: String, type: String, required: Boolean, description: String, defaultValue: Any?,
- block: PropertyDefinitionBuilder.() -> Unit) {
+ fun input(
+ id: String,
+ type: String,
+ required: Boolean,
+ description: String,
+ defaultValue: Any?,
+ block: PropertyDefinitionBuilder.() -> Unit
+ ) {
if (inputs == null)
inputs = hashMapOf()
val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build()
outputs!![id] = property.build()
}
- fun output(id: String, type: String, required: Boolean, expression: Any, description: String? = "",
- block: DSLPropertyDefinitionBuilder.() -> Unit) {
+ fun output(
+ id: String,
+ type: String,
+ required: Boolean,
+ expression: Any,
+ description: String? = "",
+ block: DSLPropertyDefinitionBuilder.() -> Unit
+ ) {
if (outputs == null)
outputs = hashMapOf()
val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description)
- .apply(block).build()
+ .apply(block).build()
outputs!![id] = property
}
}
}
-class DSLAttributeDefinitionBuilder(private val id: String,
- private val type: String? = BluePrintConstants.DATA_TYPE_STRING,
- private val required: Boolean? = false,
- private val expression: JsonNode,
- private val description: String? = "") {
+class DSLAttributeDefinitionBuilder(
+ private val id: String,
+ private val type: String? = BluePrintConstants.DATA_TYPE_STRING,
+ private val required: Boolean? = false,
+ private val expression: JsonNode,
+ private val description: String? = ""
+) {
private var attributeDefinition = AttributeDefinition()
}
}
-class DSLPropertyDefinitionBuilder(private val id: String,
- private val type: String? = BluePrintConstants.DATA_TYPE_STRING,
- private val required: Boolean? = false,
- private val expression: JsonNode,
- private val description: String? = "") {
+class DSLPropertyDefinitionBuilder(
+ private val id: String,
+ private val type: String? = BluePrintConstants.DATA_TYPE_STRING,
+ private val required: Boolean? = false,
+ private val expression: JsonNode,
+ private val description: String? = ""
+) {
private var propertyDefinition: PropertyDefinition = PropertyDefinition()
propertyDefinition.description = description
return propertyDefinition
}
-}
\ No newline at end of file
+}
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.databind.JsonNode
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Step
/**
* This is simplified version of DSL, which is used for generating the Service template
*/
class DSLBluePrint {
+
var metadata: MutableMap<String, String> = hashMapOf()
var properties: MutableMap<String, JsonNode>? = null
var dataTypes: MutableMap<String, DataType> = hashMapOf()
var outputs: MutableMap<String, PropertyDefinition>? = null
}
-
class DSLRegistryComponent {
lateinit var id: String
lateinit var type: String
var artifacts: MutableMap<String, ArtifactDefinition>? = null
var inputs: MutableMap<String, JsonNode>? = null
var outputs: MutableMap<String, JsonNode>? = null
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.dsl
import com.fasterxml.jackson.databind.JsonNode
-import org.onap.ccsdk.cds.controllerblueprints.core.*
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.asBluePrintsDataTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
+import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
import kotlin.reflect.KClass
-class ServiceTemplateBuilder(private val name: String,
- private val version: String,
- private val author: String,
- private val tags: String) {
+class BluePrintServiceDSLBuilder(
+ private val name: String,
+ private val version: String,
+ private val author: String,
+ private val tags: String
+) {
+
private var serviceTemplate = ServiceTemplate()
private var topologyTemplate: TopologyTemplate? = null
private var metadata: MutableMap<String, String> = hashMapOf()
nodeTypes!![nodeType.id!!] = nodeType
}
- fun dataType(id: String, version: String, derivedFrom: String, description: String,
- block: DataTypeBuilder.() -> Unit) {
+ fun dataType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: DataTypeBuilder.() -> Unit
+ ) {
if (dataTypes == null)
dataTypes = hashMapOf()
dataTypes!![id] = DataTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
- fun artifactType(id: String, version: String, derivedFrom: String, description: String,
- block: ArtifactTypeBuilder.() -> Unit) {
+ fun artifactType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: ArtifactTypeBuilder.() -> Unit
+ ) {
if (artifactTypes == null)
artifactTypes = hashMapOf()
artifactTypes!![id] = ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
- fun relationshipType(id: String, version: String, derivedFrom: String, description: String,
- block: RelationshipTypeBuilder.() -> Unit) {
+ fun relationshipType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: RelationshipTypeBuilder.() -> Unit
+ ) {
if (relationshipTypes == null)
relationshipTypes = hashMapOf()
relationshipTypes!![id] = RelationshipTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
- fun policyType(id: String, version: String, derivedFrom: String, description: String,
- block: PolicyTypeBuilder.() -> Unit) {
+ fun policyType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: PolicyTypeBuilder.() -> Unit
+ ) {
if (policyTypes == null)
policyTypes = hashMapOf()
policyTypes!![id] = PolicyTypeBuilder(id, version, derivedFrom, description).apply(block).build()
}
- fun nodeType(id: String, version: String, derivedFrom: String, description: String,
- block: NodeTypeBuilder.() -> Unit) {
+ fun nodeType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: NodeTypeBuilder.() -> Unit
+ ) {
if (nodeTypes == null)
nodeTypes = hashMapOf()
nodeTypes!![id] = NodeTypeBuilder(id, version, derivedFrom, description).apply(block).build()
import com.fasterxml.jackson.databind.node.NullNode
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.bpClone
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
/**
* Generate Service Template for the simplified DSL.
return nodeTemplates
}
-
private fun populateWorkflow(): MutableMap<String, Workflow>? {
var workflows: MutableMap<String, Workflow>? = null
if (dslBluePrint.workflows.isNotEmpty()) {
}
return assignments
}
-}
\ No newline at end of file
+}
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
import kotlin.reflect.KClass
import kotlin.reflect.full.createInstance
import kotlin.reflect.jvm.reflect
nodeTemplates!![nodeTemplate.id!!] = nodeTemplate
}
- fun nodeTemplateOperation(nodeTemplateName: String, type: String, interfaceName: String, description: String,
- operationBlock: OperationAssignmentBuilder<PropertiesAssignmentBuilder,
- PropertiesAssignmentBuilder>.() -> Unit) {
+ fun nodeTemplateOperation(
+ nodeTemplateName: String,
+ type: String,
+ interfaceName: String,
+ description: String,
+ operationBlock: OperationAssignmentBuilder<PropertiesAssignmentBuilder,
+ PropertiesAssignmentBuilder>.() -> Unit
+ ) {
if (nodeTemplates == null)
nodeTemplates = hashMapOf()
workflows!![workflow.id!!] = workflow
}
- //TODO("populate inputs, outputs")
- fun workflowNodeTemplate(actionName: String,
- nodeTemplateType: String, description: String, block: NodeTemplateBuilder.() -> Unit) {
+ // TODO("populate inputs, outputs")
+ fun workflowNodeTemplate(
+ actionName: String,
+ nodeTemplateType: String,
+ description: String,
+ block: NodeTemplateBuilder.() -> Unit
+ ) {
if (nodeTemplates == null)
nodeTemplates = hashMapOf()
}
}
-open class NodeTemplateBuilder(private val id: String,
- private val type: String,
- private val description: String? = "") {
+open class NodeTemplateBuilder(
+ private val id: String,
+ private val type: String,
+ private val description: String? = ""
+) {
+
private var nodeTemplate: NodeTemplate = NodeTemplate()
private var properties: MutableMap<String, JsonNode>? = null
private var interfaces: MutableMap<String, InterfaceAssignment>? = null
}
open fun <In : PropertiesAssignmentBuilder, Out : PropertiesAssignmentBuilder> typedOperation(
- interfaceName: String, description: String = "",
- block: OperationAssignmentBuilder<In, Out>.() -> Unit) {
+ interfaceName: String,
+ description: String = "",
+ block: OperationAssignmentBuilder<In, Out>.() -> Unit
+ ) {
if (interfaces == null)
interfaces = hashMapOf()
val defaultOperationName = BluePrintConstants.DEFAULT_STEP_OPERATION
interfaceAssignment.operations = hashMapOf()
interfaceAssignment.operations!![defaultOperationName] =
- OperationAssignmentBuilder<In, Out>(defaultOperationName, description).apply(block).build()
+ OperationAssignmentBuilder<In, Out>(defaultOperationName, description).apply(block).build()
interfaces!![interfaceName] = interfaceAssignment
}
- fun operation(interfaceName: String, description: String,
- block: OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>.() -> Unit) {
+ fun operation(
+ interfaceName: String,
+ description: String,
+ block: OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>.() -> Unit
+ ) {
typedOperation<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>(interfaceName, description, block)
}
}
}
-open class RequirementAssignmentBuilder(private val id: String, private val capability: String,
- private val node: String,
- private val relationship: String) {
+open class RequirementAssignmentBuilder(
+ private val id: String,
+ private val capability: String,
+ private val node: String,
+ private val relationship: String
+) {
+
private var requirementAssignment: RequirementAssignment = RequirementAssignment()
fun build(): RequirementAssignment {
private var interfaceAssignment: InterfaceAssignment = InterfaceAssignment()
private var operations: MutableMap<String, OperationAssignment>? = null
- fun operation(id: String, description: String? = "",
- block: OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>.() -> Unit) {
+ fun operation(
+ id: String,
+ description: String? = "",
+ block: OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>.() -> Unit
+ ) {
if (operations == null)
operations = hashMapOf()
operations!![id] = OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>(
- id, description).apply(block).build()
+ id, description
+ ).apply(block).build()
}
fun build(): InterfaceAssignment {
}
class OperationAssignmentBuilder<In : PropertiesAssignmentBuilder, Out : PropertiesAssignmentBuilder>(
- private val id: String,
- private val description: String? = "") {
+ private val id: String,
+ private val description: String? = ""
+) {
private var operationAssignment: OperationAssignment = OperationAssignment()
}
}
- fun implementation(timeout: Int, operationHost: String? = BluePrintConstants.PROPERTY_SELF,
- block: ImplementationBuilder.() -> Unit) {
+ fun implementation(
+ timeout: Int,
+ operationHost: String? = BluePrintConstants.PROPERTY_SELF,
+ block: ImplementationBuilder.() -> Unit
+ ) {
operationAssignment.implementation = ImplementationBuilder(timeout, operationHost!!).apply(block).build()
}
fun build(): MutableMap<String, JsonNode> {
return attributes
}
-}
\ No newline at end of file
+}
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ArrayNode
-import org.onap.ccsdk.cds.controllerblueprints.core.*
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
+import org.onap.ccsdk.cds.controllerblueprints.core.asListOfString
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ConstraintClause
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.EntityType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
+
+open class EntityTypeBuilder(
+ private val id: String,
+ private val version: String,
+ private val derivedFrom: String,
+ private val description: String? = ""
+) {
-
-open class EntityTypeBuilder(private val id: String,
- private val version: String,
- private val derivedFrom: String,
- private val description: String? = "") {
var metadata: MutableMap<String, String>? = null
var properties: MutableMap<String, PropertyDefinition>? = null
var attributes: MutableMap<String, AttributeDefinition>? = null
attributes!![id] = attribute
}
- fun attribute(id: String, type: String, required: Boolean, description: String? = "",
- block: AttributeDefinitionBuilder.() -> Unit) {
+ fun attribute(
+ id: String,
+ type: String,
+ required: Boolean,
+ description: String? = "",
+ block: AttributeDefinitionBuilder.() -> Unit
+ ) {
if (attributes == null)
attributes = hashMapOf()
val attribute = AttributeDefinitionBuilder(id, type, required, description).apply(block).build()
properties!![id] = property
}
- fun property(id: String, type: String, required: Boolean, description: String? = "",
- block: PropertyDefinitionBuilder.() -> Unit) {
+ fun property(
+ id: String,
+ type: String,
+ required: Boolean,
+ description: String? = "",
+ block: PropertyDefinitionBuilder.() -> Unit
+ ) {
if (properties == null)
properties = hashMapOf()
val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build()
}
}
-class NodeTypeBuilder(id: String, version: String, derivedFrom: String,
- description: String?) : EntityTypeBuilder(id, version, derivedFrom, description) {
+class NodeTypeBuilder(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String?
+) : EntityTypeBuilder(id, version, derivedFrom, description) {
+
private var nodeType = NodeType()
private var capabilities: MutableMap<String, CapabilityDefinition>? = null
private var requirements: MutableMap<String, RequirementDefinition>? = null
requirements!![id] = RequirementDefinitionBuilder(id, capability, node, relationship, description).build()
}
- fun requirement(id: String, capability: String, node: String, relationship: String, description: String,
- block: RequirementDefinitionBuilder.() -> Unit) {
+ fun requirement(
+ id: String,
+ capability: String,
+ node: String,
+ relationship: String,
+ description: String,
+ block: RequirementDefinitionBuilder.() -> Unit
+ ) {
if (requirements == null)
requirements = hashMapOf()
requirements!![id] = RequirementDefinitionBuilder(id, capability, node, relationship, description)
- .apply(block).build()
+ .apply(block).build()
}
fun artifact(id: String, type: String, file: String) {
val defaultOperationName = "process"
interfaceDefinition.operations = hashMapOf()
interfaceDefinition.operations!![defaultOperationName] =
- OperationDefinitionBuilder(defaultOperationName, description).apply(block).build()
+ OperationDefinitionBuilder(defaultOperationName, description).apply(block).build()
interfaces!![interfaceName] = interfaceDefinition
}
}
}
-class ArtifactTypeBuilder(id: String, version: String, derivedFrom: String,
- description: String?) : EntityTypeBuilder(id, version, derivedFrom, description) {
+class ArtifactTypeBuilder(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String?
+) : EntityTypeBuilder(id, version, derivedFrom, description) {
+
private var artifactType = ArtifactType()
private var fileExt: MutableList<String>? = null
}
}
-class PolicyTypeBuilder(id: String, version: String, derivedFrom: String,
- description: String?) : EntityTypeBuilder(id, version, derivedFrom, description) {
+class PolicyTypeBuilder(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String?
+) : EntityTypeBuilder(id, version, derivedFrom, description) {
+
private var policyType = PolicyType()
fun targets(targetsStr: String) {
}
}
-class RelationshipTypeBuilder(private val id: String, private val version: String,
- derivedFrom: String, private val description: String?)
- : EntityTypeBuilder(id, version, derivedFrom, description) {
+class RelationshipTypeBuilder(
+ private val id: String,
+ private val version: String,
+ derivedFrom: String,
+ private val description: String?
+) :
+ EntityTypeBuilder(id, version, derivedFrom, description) {
private var relationshipType = RelationshipType()
}
}
-class DataTypeBuilder(id: String, version: String, derivedFrom: String,
- description: String?) : EntityTypeBuilder(id, version, derivedFrom, description) {
+class DataTypeBuilder(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String?
+) : EntityTypeBuilder(id, version, derivedFrom, description) {
+
private var dataType = DataType()
fun constrain(block: ConstraintClauseBuilder.() -> Unit) {
}
}
-class RequirementDefinitionBuilder(private val id: String, private val capability: String, private val node: String,
- private val relationship: String, private val description: String? = "") {
+class RequirementDefinitionBuilder(
+ private val id: String,
+ private val capability: String,
+ private val node: String,
+ private val relationship: String,
+ private val description: String? = ""
+) {
+
private var requirementDefinition = RequirementDefinition()
fun build(): RequirementDefinition {
}
}
-class OperationDefinitionBuilder(private val id: String,
- private val description: String? = "") {
+class OperationDefinitionBuilder(
+ private val id: String,
+ private val description: String? = ""
+) {
+
private var operationDefinition: OperationDefinition = OperationDefinition()
fun inputs(block: PropertiesDefinitionBuilder.() -> Unit) {
}
}
-class AttributeDefinitionBuilder(private val id: String,
- private val type: String? = BluePrintConstants.DATA_TYPE_STRING,
- private val required: Boolean? = false,
- private val description: String? = "") {
+class AttributeDefinitionBuilder(
+ private val id: String,
+ private val type: String? = BluePrintConstants.DATA_TYPE_STRING,
+ private val required: Boolean? = false,
+ private val description: String? = ""
+) {
private var attributeDefinition: AttributeDefinition = AttributeDefinition()
properties[id] = property
}
- fun property(id: String, type: String?, required: Boolean?, description: String? = "",
- block: PropertyDefinitionBuilder.() -> Unit) {
+ fun property(
+ id: String,
+ type: String?,
+ required: Boolean?,
+ description: String? = "",
+ block: PropertyDefinitionBuilder.() -> Unit
+ ) {
val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build()
properties[id] = property
}
}
}
-class PropertyDefinitionBuilder(private val id: String,
- private val type: String? = BluePrintConstants.DATA_TYPE_STRING,
- private val required: Boolean? = false,
- private val description: String? = "") {
+class PropertyDefinitionBuilder(
+ private val id: String,
+ private val type: String? = BluePrintConstants.DATA_TYPE_STRING,
+ private val required: Boolean? = false,
+ private val description: String? = ""
+) {
private var propertyDefinition: PropertyDefinition = PropertyDefinition()
}
}
-
class EntrySchemaBuilder(private val type: String) {
private var entrySchema: EntrySchema = EntrySchema()
entrySchema.type = type
return entrySchema
}
-}
\ No newline at end of file
+}
workflow.outputs = outputs
return workflow
}
-
}
-class StepBuilder(private val id: String, private val target: String,
- private val description: String) {
+class StepBuilder(
+ private val id: String,
+ private val target: String,
+ private val description: String
+) {
private var step = Step()
private var activities: ArrayList<Activity> = arrayListOf()
@Throws(BluePrintException::class)
suspend fun deleteFromDatabase(name: String, version: String)
-}
\ No newline at end of file
+}
override fun otherDefinitions(): MutableMap<String, Any> {
return otherDefinitionMap
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.interfaces
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
interface BluePrintAttributeDefinitionEnhancer : BluePrintEnhancer<AttributeDefinition>
-
interface BluePrintEnhancerService {
@Throws(BluePrintException::class)
}
@Suppress("UNCHECKED_CAST")
- private fun <T> doEnhancement(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, definition: Any, enhancers: List<BluePrintEnhancer<T>>) {
+ private fun <T> doEnhancement(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ definition: Any,
+ enhancers: List<BluePrintEnhancer<T>>
+ ) {
if (enhancers.isNotEmpty()) {
enhancers.forEach {
it.enhance(bluePrintRuntimeService, name, definition as T)
}
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.interfaces
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
import java.io.Serializable
/**
@Throws(BluePrintException::class)
fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition
-
-}
\ No newline at end of file
+}
suspend fun <T> scriptInstance(bluePrintSourceCode: BluePrintSourceCode, scriptClassName: String): T
- suspend fun <T> scriptInstance(blueprintBasePath: String, artifactName: String, artifactVersion: String,
- scriptClassName: String, reCompile: Boolean): T
+ suspend fun <T> scriptInstance(
+ blueprintBasePath: String,
+ artifactName: String,
+ artifactVersion: String,
+ scriptClassName: String,
+ reCompile: Boolean
+ ): T
suspend fun <T> scriptInstance(blueprintBasePath: String, scriptClassName: String, reCompile: Boolean): T
suspend fun <T> scriptInstance(cacheKey: String, scriptClassName: String): T
suspend fun <T> scriptInstance(scriptClassName: String): T
-}
\ No newline at end of file
+}
interface BluePrintWorkflowExecutionService<Input, Output> {
- suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- executionServiceInput: Input,
- properties: MutableMap<String, Any> = hashMapOf()): Output
-}
\ No newline at end of file
+ suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: Input,
+ properties: MutableMap<String, Any> = hashMapOf()
+ ): Output
+}
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import java.util.function.Function
-
interface BlueprintFunctionNode<T, R> : Function<T, R> {
fun getName(): String
@Throws(BluePrintProcessorException::class)
suspend fun applyNB(t: T): R
-}
\ No newline at end of file
+}
* @return Content result
*
**/
- suspend fun generateContent(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- nodeTemplateName: String,
- artifactName: String,
- jsonData: String = "",
- ignoreJsonNull: Boolean = false,
- additionalContext: MutableMap<String, Any> = mutableMapOf()): String
+ suspend fun generateContent(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ nodeTemplateName: String,
+ artifactName: String,
+ jsonData: String = "",
+ ignoreJsonNull: Boolean = false,
+ additionalContext: MutableMap<String, Any> = mutableMapOf()
+ ): String
}
/**
* Customise JsonNodeFactory and TextNode, Since it introduces quotes for string data.
*/
open class BluePrintJsonNodeFactory : JsonNodeFactory() {
+
override fun textNode(text: String): TextNode {
return BluePrintTextNode(text)
}
CharTypes.appendQuoted(sb, this._value)
return sb.toString()
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.interfaces
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
-
interface BluePrintValidator<T> {
fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: T)
-
}
-
interface BluePrintServiceTemplateValidator : BluePrintValidator<ServiceTemplate>
interface BluePrintTopologyTemplateValidator : BluePrintValidator<TopologyTemplate>
fun validateBluePrints(bluePrintRuntimeService: BluePrintRuntimeService<*>): Boolean
}
-
interface BluePrintTypeValidatorService {
fun <T : BluePrintValidator<*>> bluePrintValidator(referenceName: String, classType: Class<T>): T?
doValidation(bluePrintRuntimeService, name, artifactType, validators)
}
- fun validateArtifactDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String,
- artifactDefinition: ArtifactDefinition) {
+ fun validateArtifactDefinition(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ artifactDefinition: ArtifactDefinition
+ ) {
val validators = getArtifactDefinitionsValidators()
doValidation(bluePrintRuntimeService, name, artifactDefinition, validators)
}
}
@Suppress("UNCHECKED_CAST")
- private fun <T> doValidation(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, definition: Any, validators: List<BluePrintValidator<T>>) {
+ private fun <T> doValidation(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ definition: Any,
+ validators: List<BluePrintValidator<T>>
+ ) {
validators.forEach {
it.validate(bluePrintRuntimeService, name, definition as T)
}
}
}
-
-
-
import org.onap.ccsdk.cds.controllerblueprints.core.logger
import java.io.File
import java.net.URLClassLoader
-import java.util.*
+import java.util.ArrayList
import kotlin.script.experimental.api.SourceCode
import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty
import kotlin.system.measureTimeMillis
-
open class BluePrintCompileService {
val log = logger(BluePrintCompileService::class)
}
/** Compile the [bluePrintSourceCode] and get the [kClassName] instance for the constructor [args] */
- suspend fun <T> eval(bluePrintSourceCode: BluePrintSourceCode, kClassName: String,
- args: ArrayList<Any?>?): T {
+ suspend fun <T> eval(
+ bluePrintSourceCode: BluePrintSourceCode,
+ kClassName: String,
+ args: ArrayList<Any?>?
+ ): T {
/** Compile the source code */
compile(bluePrintSourceCode)
/** Get the class loader with compiled jar */
/** Compile [bluePrintSourceCode] and put into cache */
suspend fun compile(bluePrintSourceCode: BluePrintSourceCode) {
- //TODO("Include Multiple folders")
+ // TODO("Include Multiple folders")
val sourcePath = bluePrintSourceCode.blueprintKotlinSources.first()
val compiledJarFile = bluePrintSourceCode.targetJarFile
/** Check cache is present for the blueprint scripts */
val hasCompiledCache = BluePrintCompileCache.hasClassLoader(bluePrintSourceCode.cacheKey)
- log.debug("Jar Exists : ${compiledJarFile.exists()}, Regenerate : ${bluePrintSourceCode.regenerate}," +
- " Compiled hash(${bluePrintSourceCode.cacheKey}) : $hasCompiledCache")
+ log.debug(
+ "Jar Exists : ${compiledJarFile.exists()}, Regenerate : ${bluePrintSourceCode.regenerate}," +
+ " Compiled hash(${bluePrintSourceCode.cacheKey}) : $hasCompiledCache"
+ )
if (!compiledJarFile.exists() || bluePrintSourceCode.regenerate || !hasCompiledCache) {
log.info("compiling for cache key(${bluePrintSourceCode.cacheKey})")
val exitCode: ExitCode = k2jvmCompiler.exec(messageCollector, Services.EMPTY, arguments)
when (exitCode) {
ExitCode.OK -> {
- checkFileExists(compiledJarFile)
- { "couldn't generate compiled jar(${compiledJarFile.absolutePath})" }
+ checkFileExists(compiledJarFile) { "couldn't generate compiled jar(${compiledJarFile.absolutePath})" }
}
else -> {
throw BluePrintException("$exitCode :${messageCollector.errors().joinToString("\n")}")
/** create class [kClassName] instance from [classLoader] */
fun <T> instance(classLoader: URLClassLoader, kClassName: String, args: ArrayList<Any?>? = arrayListOf()): T {
val kClazz = classLoader.loadClass(kClassName)
- ?: throw BluePrintException("failed to load class($kClassName) from current class loader.")
+ ?: throw BluePrintException("failed to load class($kClassName) from current class loader.")
val instance = if (args.isNullOrEmpty()) {
kClazz.newInstance()
} else {
kClazz.constructors
- .single().newInstance(*args.toArray())
+ .single().newInstance(*args.toArray())
} ?: throw BluePrintException("failed to create class($kClassName) instance for constructor argument($args).")
return instance as T
}
/** Compile source code information */
open class BluePrintSourceCode : SourceCode {
+
lateinit var blueprintKotlinSources: MutableList<String>
lateinit var moduleName: String
lateinit var targetJarFile: File
/** Class to collect compilation Data */
data class CompiledMessageData(
- val severity: CompilerMessageSeverity,
- val message: String,
- val location: CompilerMessageLocation?
+ val severity: CompilerMessageSeverity,
+ val message: String,
+ val location: CompilerMessageLocation?
)
/** Class to collect compilation results */
}
override fun hasErrors() =
- synchronized(compiledMessages) {
- compiledMessages.any { it.severity.isError }
- }
+ synchronized(compiledMessages) {
+ compiledMessages.any { it.severity.isError }
+ }
override fun clear() {
synchronized(compiledMessages) {
}
fun errors(): List<CompiledMessageData> = compiledMessages.filter { it.severity == CompilerMessageSeverity.ERROR }
-}
\ No newline at end of file
+}
import java.net.URL
import java.net.URLClassLoader
-
object BluePrintCompileCache {
val log = logger(BluePrintCompileCache::class)
private val classLoaderCache: LoadingCache<String, URLClassLoader> = CacheBuilder.newBuilder()
- .maximumSize(50)
- .build(BluePrintClassLoader)
+ .maximumSize(50)
+ .build(BluePrintClassLoader)
fun classLoader(key: String): URLClassLoader {
return classLoaderCache.get(key)
}
fun cleanClassLoader(key: String) {
- if(hasClassLoader(key)){
+ if (hasClassLoader(key)) {
// Make sure to close all classloader loaded resources before we let go of it.
// This fixes a Delete failure message on filesystem that keeps locks on opened jars;
// like Windows and NFS.
classLoaderCache.get(key).close()
classLoaderCache.invalidate(key)
log.info("Cleaned compiled cache($key)")
- }else{
+ } else {
log.warn("No compiled cache($key) present to clean.")
}
}
}
val urls = arrayListOf<URL>()
keyPath.walkTopDown()
- .filter { it.name.endsWith("cba-kts.jar") }
- .forEach {
- log.debug("Adding (${it.absolutePath}) to cache($key)")
- urls.add(it.toURI().toURL())
- }
+ .filter { it.name.endsWith("cba-kts.jar") }
+ .forEach {
+ log.debug("Adding (${it.absolutePath}) to cache($key)")
+ urls.add(it.toURI().toURL())
+ }
return URLClassLoader(urls.toTypedArray(), this.javaClass.classLoader)
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
-import java.util.*
-
+import java.util.ArrayList
open class BluePrintScriptsServiceImpl : BluePrintScriptsService {
return bluePrintCompileService.eval(bluePrintSourceCode, scriptClassName, null)
}
- override suspend fun <T> scriptInstance(blueprintBasePath: String, artifactName: String, artifactVersion: String,
- scriptClassName: String, reCompile: Boolean): T {
+ override suspend fun <T> scriptInstance(
+ blueprintBasePath: String,
+ artifactName: String,
+ artifactVersion: String,
+ scriptClassName: String,
+ reCompile: Boolean
+ ): T {
val sources: MutableList<String> = arrayListOf()
sources.add(normalizedPathName(blueprintBasePath, BluePrintConstants.TOSCA_SCRIPTS_KOTLIN_DIR))
return scriptInstance(scriptSource, scriptClassName)
}
- override suspend fun <T> scriptInstance(blueprintBasePath: String, scriptClassName: String,
- reCompile: Boolean): T {
+ override suspend fun <T> scriptInstance(
+ blueprintBasePath: String,
+ scriptClassName: String,
+ reCompile: Boolean
+ ): T {
val toscaMetaData = BluePrintMetadataUtils.toscaMetaData(blueprintBasePath)
checkNotNull(toscaMetaData.templateName) { "couldn't find 'Template-Name' key in TOSCA.meta" }
checkNotNull(toscaMetaData.templateVersion) { "couldn't find 'Template-Version' key in TOSCA.meta" }
- return scriptInstance(blueprintBasePath, toscaMetaData.templateName!!, toscaMetaData.templateVersion!!,
- scriptClassName, reCompile)
+ return scriptInstance(
+ blueprintBasePath, toscaMetaData.templateName!!, toscaMetaData.templateVersion!!,
+ scriptClassName, reCompile
+ )
}
override suspend fun <T> scriptInstance(cacheKey: String, scriptClassName: String): T {
val args = ArrayList<Any?>()
return BluePrintCompileCache.classLoader(cacheKey).loadClass(scriptClassName).constructors
- .single().newInstance(*args.toArray()) as T
+ .single().newInstance(*args.toArray()) as T
}
override suspend fun <T> scriptInstance(scriptClassName: String): T {
val args = ArrayList<Any?>()
return Thread.currentThread().contextClassLoader.loadClass(scriptClassName).constructors
- .single().newInstance(*args.toArray()) as T
+ .single().newInstance(*args.toArray()) as T
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.service
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition
+
/**
*
*
* @author Brinda Santh
*/
class BluePrintChainedService {
- var bpc : BluePrintContext
- constructor(bpc : BluePrintContext){
+ var bpc: BluePrintContext
+
+ constructor(bpc: BluePrintContext) {
this.bpc = bpc
}
recNodeTypesChained(nodeTypeName).forEach { nodeType ->
- val subAttributes = bpc.nodeTypeByName(nodeType.id!!).attributes
+ val subAttributes = bpc.nodeTypeByName(nodeType.id!!).attributes
if (subAttributes != null) {
attributes.putAll(subAttributes)
}
- val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties
+ val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties
if (subProperties != null) {
properties.putAll(subProperties)
}
- val subRequirements = bpc.nodeTypeByName(nodeType.id!!).requirements
+ val subRequirements = bpc.nodeTypeByName(nodeType.id!!).requirements
if (subRequirements != null) {
requirements.putAll(subRequirements)
}
- val subCapabilities = bpc.nodeTypeByName(nodeType.id!!).capabilities
+ val subCapabilities = bpc.nodeTypeByName(nodeType.id!!).capabilities
if (subCapabilities != null) {
capabilities.putAll(subCapabilities)
}
- val subInterfaces = bpc.nodeTypeByName(nodeType.id!!).interfaces
+ val subInterfaces = bpc.nodeTypeByName(nodeType.id!!).interfaces
if (subInterfaces != null) {
interfaces.putAll(subInterfaces)
}
- val subArtifacts = bpc.nodeTypeByName(nodeType.id!!).artifacts
+ val subArtifacts = bpc.nodeTypeByName(nodeType.id!!).artifacts
if (subArtifacts != null) {
artifacts.putAll(subArtifacts)
}
}
fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap<String, PropertyDefinition>? {
- val nodeType = bpc.nodeTypeByName(nodeTypeName)
+ val nodeType = bpc.nodeTypeByName(nodeTypeName)
val properties = hashMapOf<String, PropertyDefinition>()
recNodeTypesChained(nodeTypeName).forEach { nodeType ->
- val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties
+ val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties
if (subProperties != null) {
properties.putAll(subProperties)
}
}
private fun recNodeTypesChained(nodeTypeName: String, nodeTypes: MutableList<NodeType>? = arrayListOf()): MutableList<NodeType> {
- val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName)
+ val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName)
nodeType.id = nodeTypeName
val derivedFrom: String = nodeType.derivedFrom
if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) {
}
private fun recDataTypesChained(dataTypeName: String, dataTypes: MutableList<DataType>? = arrayListOf()): MutableList<DataType> {
- val dataType: DataType = bpc.dataTypeByName(dataTypeName)!!
+ val dataType: DataType = bpc.dataTypeByName(dataTypeName)!!
dataType.id = dataTypeName
val derivedFrom: String = dataType.derivedFrom
if (!BluePrintTypes.rootDataTypes().contains(derivedFrom)) {
dataTypes!!.add(dataType)
return dataTypes
}
-
-}
\ No newline at end of file
+}
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Step
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.slf4j.LoggerFactory
}
fun name(): String = metadata?.get(BluePrintConstants.METADATA_TEMPLATE_NAME)
- ?: throw BluePrintException("could't get template name from meta data")
+ ?: throw BluePrintException("could't get template name from meta data")
fun version(): String = metadata?.get(BluePrintConstants.METADATA_TEMPLATE_VERSION)
- ?: throw BluePrintException("could't get template version from meta data")
+ ?: throw BluePrintException("could't get template version from meta data")
fun author(): String = metadata?.get(BluePrintConstants.METADATA_TEMPLATE_AUTHOR)
- ?: throw BluePrintException("could't get template author from meta data")
+ ?: throw BluePrintException("could't get template author from meta data")
// Workflow
fun workflows(): MutableMap<String, Workflow>? = serviceTemplate.topologyTemplate?.workflows
fun workflowByName(workFlowName: String): Workflow = workflows()?.get(workFlowName)
- ?: throw BluePrintException("could't get workflow($workFlowName)")
+ ?: throw BluePrintException("could't get workflow($workFlowName)")
fun workflowInputs(workFlowName: String) = workflowByName(workFlowName).inputs
fun workflowStepByName(workFlowName: String, stepName: String): Step {
return workflowByName(workFlowName).steps?.get(stepName)
- ?: throw BluePrintException("could't get step($stepName) for workflow($workFlowName)")
+ ?: throw BluePrintException("could't get step($stepName) for workflow($workFlowName)")
}
fun workflowStepNodeTemplate(workFlowName: String, stepName: String): String {
return workflowStepByName(workFlowName, stepName).target
- ?: throw BluePrintException("could't get node template name for workflow($workFlowName)'s step($stepName)")
+ ?: throw BluePrintException("could't get node template name for workflow($workFlowName)'s step($stepName)")
}
fun workflowFirstStepNodeTemplate(workFlowName: String): String {
val firstStepName = workflowByName(workFlowName).steps?.keys?.first()
- ?: throw BluePrintException("could't get first step for workflow($workFlowName)")
+ ?: throw BluePrintException("could't get first step for workflow($workFlowName)")
return workflowStepNodeTemplate(workFlowName, firstStepName)
}
fun workflowStepFirstCallOperation(workFlowName: String, stepName: String): String {
return workflowStepByName(workFlowName, stepName).activities?.filter { it.callOperation != null }?.single()?.callOperation
- ?: throw BluePrintException("couldn't get first callOperation for WorkFlow($workFlowName) ")
+ ?: throw BluePrintException("couldn't get first callOperation for WorkFlow($workFlowName) ")
}
// DSL
fun dslPropertiesByName(name: String): JsonNode = dslDefinitions()?.get(name)
- ?: throw BluePrintException("couldn't get policy type for the dsl($name)")
+ ?: throw BluePrintException("couldn't get policy type for the dsl($name)")
// Data Type
fun dataTypeByName(name: String): DataType? = dataTypes()?.get(name)
fun policyTypes(): MutableMap<String, PolicyType>? = serviceTemplate.policyTypes
fun policyTypeByName(policyName: String) = policyTypes()?.get(policyName)
- ?: throw BluePrintException("could't get policy type for the name($policyName)")
+ ?: throw BluePrintException("could't get policy type for the name($policyName)")
fun policyTypesDerivedFrom(name: String): MutableMap<String, PolicyType>? {
return policyTypes()?.filterValues { policyType -> policyType.derivedFrom == name }?.toMutableMap()
fun nodeTypes(): MutableMap<String, NodeType>? = serviceTemplate.nodeTypes
fun nodeTypeByName(name: String): NodeType =
- nodeTypes()?.get(name)
- ?: throw BluePrintException("could't get node type for the name($name)")
+ nodeTypes()?.get(name)
+ ?: throw BluePrintException("could't get node type for the name($name)")
fun nodeTypeDerivedFrom(name: String): MutableMap<String, NodeType>? {
return nodeTypes()?.filterValues { nodeType -> nodeType.derivedFrom == name }?.toMutableMap()
fun nodeTypeInterface(nodeTypeName: String, interfaceName: String): InterfaceDefinition {
return nodeTypeByName(nodeTypeName).interfaces?.get(interfaceName)
- ?: throw BluePrintException("could't get node type($nodeTypeName)'s interface definition($interfaceName)")
+ ?: throw BluePrintException("could't get node type($nodeTypeName)'s interface definition($interfaceName)")
}
fun nodeTypeInterfaceOperation(nodeTypeName: String, interfaceName: String, operationName: String): OperationDefinition {
return nodeTypeInterface(nodeTypeName, interfaceName).operations?.get(operationName)
- ?: throw BluePrintException("could't get node type($nodeTypeName)'s interface definition($interfaceName) operation definition($operationName)")
+ ?: throw BluePrintException("could't get node type($nodeTypeName)'s interface definition($interfaceName) operation definition($operationName)")
}
fun interfaceNameForNodeType(nodeTypeName: String): String {
return nodeTypeByName(nodeTypeName).interfaces?.keys?.first()
- ?: throw BluePrintException("could't get NodeType($nodeTypeName)'s first InterfaceDefinition name")
+ ?: throw BluePrintException("could't get NodeType($nodeTypeName)'s first InterfaceDefinition name")
}
- fun nodeTypeInterfaceOperationInputs(nodeTypeName: String, interfaceName: String, operationName: String): MutableMap<String, PropertyDefinition>? {
+ fun nodeTypeInterfaceOperationInputs(
+ nodeTypeName: String,
+ interfaceName: String,
+ operationName: String
+ ): MutableMap<String, PropertyDefinition>? {
return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).inputs
}
- fun nodeTypeInterfaceOperationOutputs(nodeTypeName: String, interfaceName: String, operationName: String): MutableMap<String, PropertyDefinition>? {
+ fun nodeTypeInterfaceOperationOutputs(
+ nodeTypeName: String,
+ interfaceName: String,
+ operationName: String
+ ): MutableMap<String, PropertyDefinition>? {
return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).outputs
}
fun nodeTemplates(): MutableMap<String, NodeTemplate>? = serviceTemplate.topologyTemplate?.nodeTemplates
fun nodeTemplateByName(name: String): NodeTemplate =
- nodeTemplates()?.get(name) ?: throw BluePrintException("could't get node template for the name($name)")
+ nodeTemplates()?.get(name) ?: throw BluePrintException("could't get node template for the name($name)")
fun nodeTemplateForNodeType(name: String): MutableMap<String, NodeTemplate>? {
return nodeTemplates()?.filterValues { nodeTemplate -> nodeTemplate.type == name }?.toMutableMap()
fun nodeTemplateArtifact(nodeTemplateName: String, artifactName: String): ArtifactDefinition {
return nodeTemplateArtifacts(nodeTemplateName)?.get(artifactName)
- ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s ArtifactDefinition($artifactName)")
+ ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s ArtifactDefinition($artifactName)")
}
fun nodeTemplateArtifactForArtifactType(nodeTemplateName: String, artifactType: String): ArtifactDefinition {
return nodeTemplateArtifacts(nodeTemplateName)?.filter { it.value.type == artifactType }?.map { it.value }?.get(0)
- ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s Artifact Type($artifactType)")
+ ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s Artifact Type($artifactType)")
}
fun nodeTemplateFirstInterface(nodeTemplateName: String): InterfaceAssignment {
return nodeTemplateByName(nodeTemplateName).interfaces?.values?.first()
- ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment")
+ ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment")
}
fun nodeTemplateFirstInterfaceName(nodeTemplateName: String): String {
return nodeTemplateByName(nodeTemplateName).interfaces?.keys?.first()
- ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment name")
+ ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment name")
}
fun nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName: String): String {
return nodeTemplateFirstInterface(nodeTemplateName).operations?.keys?.first()
- ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment's first OperationAssignment name")
+ ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment's first OperationAssignment name")
}
- fun nodeTemplateOperationImplementation(nodeTemplateName: String, interfaceName: String, operationName: String)
- : Implementation? {
+ fun nodeTemplateOperationImplementation(nodeTemplateName: String, interfaceName: String, operationName: String):
+ Implementation? {
return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).implementation
}
fun nodeTemplateInterface(nodeTemplateName: String, interfaceName: String): InterfaceAssignment {
return nodeTemplateByName(nodeTemplateName).interfaces?.get(interfaceName)
- ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName)")
+ ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName)")
}
fun nodeTemplateInterfaceOperation(nodeTemplateName: String, interfaceName: String, operationName: String): OperationAssignment {
return nodeTemplateInterface(nodeTemplateName, interfaceName).operations?.get(operationName)
- ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName) OperationAssignment($operationName)")
+ ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName) OperationAssignment($operationName)")
}
fun nodeTemplateCapability(nodeTemplateName: String, capabilityName: String): CapabilityAssignment {
return nodeTemplateByName(nodeTemplateName).capabilities?.get(capabilityName)
- ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s CapabilityAssignment($capabilityName)")
+ ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s CapabilityAssignment($capabilityName)")
}
fun nodeTemplateRequirement(nodeTemplateName: String, requirementName: String): RequirementAssignment {
return nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName)
- ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first RequirementAssignment($requirementName)")
+ ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first RequirementAssignment($requirementName)")
}
fun nodeTemplateRequirementNode(nodeTemplateName: String, requirementName: String): NodeTemplate {
val filteredNodeTemplateName: String = nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName)?.node
- ?: throw BluePrintException("could't NodeTemplate for NodeTemplate's($nodeTemplateName) requirement's ($requirementName) ")
+ ?: throw BluePrintException("could't NodeTemplate for NodeTemplate's($nodeTemplateName) requirement's ($requirementName) ")
return nodeTemplateByName(filteredNodeTemplateName)
}
fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap<String, PropertyDefinition>? {
return BluePrintChainedService(this).nodeTypeChainedProperties(nodeTypeName)
}
-
}
inline fun <reified T> instance(name: String): T {
return applicationContext.getBean(name) as? T
- ?: throw BluePrintProcessorException("failed to get instance($name)")
+ ?: throw BluePrintProcessorException("failed to get instance($name)")
}
inline fun <reified T> instance(type: Class<T>): T {
return applicationContext.getBean(type)
- ?: throw BluePrintProcessorException("failed to get instance($type)")
+ ?: throw BluePrintProcessorException("failed to get instance($type)")
}
inline fun <reified T> instance(type: KClass<*>): T {
return applicationContext.getBean(type.java) as? T
- ?: throw BluePrintProcessorException("failed to get instance($type)")
+ ?: throw BluePrintProcessorException("failed to get instance($type)")
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.service
-import org.slf4j.LoggerFactory
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DSLExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InputExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationOutputExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyExpression
+import org.slf4j.LoggerFactory
/**
*
* @author Brinda Santh
*/
object BluePrintExpressionService {
- val log= LoggerFactory.getLogger(this::class.toString())
+
+ val log = LoggerFactory.getLogger(this::class.toString())
@JvmStatic
fun checkContainsExpression(propertyAssignmentNode: JsonNode): Boolean {
val json = propertyAssignmentNode.toString()
// FIXME("Check if any Optimisation needed")
- return (json.contains(BluePrintConstants.EXPRESSION_GET_INPUT)
- || json.contains(BluePrintConstants.EXPRESSION_GET_ATTRIBUTE)
- || json.contains(BluePrintConstants.EXPRESSION_GET_PROPERTY))
-
+ return (json.contains(BluePrintConstants.EXPRESSION_GET_INPUT) ||
+ json.contains(BluePrintConstants.EXPRESSION_GET_ATTRIBUTE) ||
+ json.contains(BluePrintConstants.EXPRESSION_GET_PROPERTY))
}
@JvmStatic
}
}
}
- } else if (propertyAssignmentNode is TextNode
- && propertyAssignmentNode.textValue().startsWith(BluePrintConstants.EXPRESSION_DSL_REFERENCE)) {
+ } else if (propertyAssignmentNode is TextNode &&
+ propertyAssignmentNode.textValue().startsWith(BluePrintConstants.EXPRESSION_DSL_REFERENCE)
+ ) {
expressionData.isExpression = true
expressionData.command = BluePrintConstants.EXPRESSION_DSL_REFERENCE
expressionData.dslExpression = populateDSLExpression(propertyAssignmentNode)
@JvmStatic
fun populateDSLExpression(jsonNode: TextNode): DSLExpression {
- return DSLExpression(propertyName = jsonNode.textValue()
- .removePrefix(BluePrintConstants.EXPRESSION_DSL_REFERENCE))
+ return DSLExpression(
+ propertyName = jsonNode.textValue()
+ .removePrefix(BluePrintConstants.EXPRESSION_DSL_REFERENCE)
+ )
}
@JvmStatic
fun populatePropertyExpression(jsonNode: JsonNode): PropertyExpression {
val arrayNode: ArrayNode = jsonNode.first() as ArrayNode
check(arrayNode.size() >= 2) {
- throw BluePrintException(String.format("missing property expression, " +
- "it should be [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>, " +
- "<nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ] , but present {}", jsonNode))
+ throw BluePrintException(
+ String.format(
+ "missing property expression, " +
+ "it should be [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>, " +
+ "<nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ] , but present {}", jsonNode
+ )
+ )
}
var reqOrCapEntityName: String? = null
var propertyName = ""
}
}
- return PropertyExpression(modelableEntityName = arrayNode[0].asText(),
- reqOrCapEntityName = reqOrCapEntityName,
- propertyName = propertyName,
- subPropertyName = subProperty
+ return PropertyExpression(
+ modelableEntityName = arrayNode[0].asText(),
+ reqOrCapEntityName = reqOrCapEntityName,
+ propertyName = propertyName,
+ subPropertyName = subProperty
)
}
fun populateAttributeExpression(jsonNode: JsonNode): AttributeExpression {
val arrayNode: ArrayNode = jsonNode.first() as ArrayNode
check(arrayNode.size() >= 2) {
- throw BluePrintException(String.format("missing attribute expression, " +
- "it should be [ <modelable_entity_name>, <optional_req_or_cap_name>, <attribute_name>," +
- " <nested_attribute_name_or_index_1>, ..., <nested_attribute_name_or_index_n> ] , but present {}", jsonNode))
+ throw BluePrintException(
+ String.format(
+ "missing attribute expression, " +
+ "it should be [ <modelable_entity_name>, <optional_req_or_cap_name>, <attribute_name>," +
+ " <nested_attribute_name_or_index_1>, ..., <nested_attribute_name_or_index_n> ] , but present {}", jsonNode
+ )
+ )
}
var reqOrCapEntityName: String? = null
subAttributeName = propertyPaths.joinToString("/")
}
}
- return AttributeExpression(modelableEntityName = arrayNode[0].asText(),
- reqOrCapEntityName = reqOrCapEntityName,
- attributeName = attributeName,
- subAttributeName = subAttributeName
+ return AttributeExpression(
+ modelableEntityName = arrayNode[0].asText(),
+ reqOrCapEntityName = reqOrCapEntityName,
+ attributeName = attributeName,
+ subAttributeName = subAttributeName
)
}
val arrayNode: ArrayNode = jsonNode.first() as ArrayNode
check(arrayNode.size() >= 4) {
- throw BluePrintException(String.format("missing operation output expression, " +
- "it should be (<modelable_entity_name>, <interface_name>, <operation_name>, <output_variable_name>) , but present {}", jsonNode))
+ throw BluePrintException(
+ String.format(
+ "missing operation output expression, " +
+ "it should be (<modelable_entity_name>, <interface_name>, <operation_name>, <output_variable_name>) , but present {}",
+ jsonNode
+ )
+ )
}
var subPropertyName: String? = null
if (arrayNode.size() == 5)
subPropertyName = arrayNode[4].asText()
- return OperationOutputExpression(modelableEntityName = arrayNode[0].asText(),
- interfaceName = arrayNode[1].asText(),
- operationName = arrayNode[2].asText(),
- propertyName = arrayNode[3].asText(),
- subPropertyName = subPropertyName
+ return OperationOutputExpression(
+ modelableEntityName = arrayNode[0].asText(),
+ interfaceName = arrayNode[1].asText(),
+ operationName = arrayNode[2].asText(),
+ propertyName = arrayNode[3].asText(),
+ subPropertyName = subPropertyName
)
}
val arrayNode: ArrayNode = jsonNode.first() as ArrayNode
check(arrayNode.size() >= 2) {
- throw BluePrintException(String.format("missing artifact expression, " +
- "it should be [ <modelable_entity_name>, <artifact_name>, <location>, <remove> ] , but present {}", jsonNode))
+ throw BluePrintException(
+ String.format(
+ "missing artifact expression, " +
+ "it should be [ <modelable_entity_name>, <artifact_name>, <location>, <remove> ] , but present {}", jsonNode
+ )
+ )
}
- return ArtifactExpression(modelableEntityName = arrayNode[0].asText(),
- artifactName = arrayNode[1].asText(),
- location = arrayNode[2]?.asText() ?: "LOCAL_FILE",
- remove = arrayNode[3]?.asBoolean() ?: false
+ return ArtifactExpression(
+ modelableEntityName = arrayNode[0].asText(),
+ artifactName = arrayNode[1].asText(),
+ location = arrayNode[2]?.asText() ?: "LOCAL_FILE",
+ remove = arrayNode[3]?.asBoolean() ?: false
)
}
-}
\ No newline at end of file
+}
private var importServiceTemplateMap: MutableMap<String, ServiceTemplate> = hashMapOf()
-
suspend fun getImportResolvedServiceTemplate(): ServiceTemplate {
// Populate Imported Service Templates
traverseSchema(PARENT_SERVICE_TEMPLATE, parentServiceTemplate)
val decodedSystemId: String = URLDecoder.decode(file, Charset.defaultCharset().toString())
log.trace("file ({}), decodedSystemId ({}) ", file, decodedSystemId)
try {
- if (decodedSystemId.startsWith("http", true)
- || decodedSystemId.startsWith("https", true)) {
+ if (decodedSystemId.startsWith("http", true) ||
+ decodedSystemId.startsWith("https", true)
+ ) {
val givenUrl: String = URL(decodedSystemId).toString()
val systemUrl: String = File(".").toURI().toURL().toString()
log.trace("givenUrl ({}), systemUrl ({}) ", givenUrl, systemUrl)
if (givenUrl.startsWith(systemUrl)) {
-
}
} else {
if (!decodedSystemId.startsWith("/")) {
}
return serviceTemplate
}
-
-
}
/**
* To enable inheritance within CBA, we need Jinja runtime to know where to load the templates.
*/
- class BlueprintRelatedTemplateLocator(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val artifactName: String,
- private val artifactVersion: String) : ResourceLocator {
+ class BlueprintRelatedTemplateLocator(
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val artifactName: String,
+ private val artifactVersion: String
+ ) : ResourceLocator {
@Throws(IOException::class)
override fun getString(fullName: String, encoding: Charset, interpreter: JinjavaInterpreter): String {
try {
val deployFile =
- normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath,
+ normalizedPathName(
+ bluePrintLoadConfiguration.blueprintDeployPath,
artifactName,
artifactVersion,
- fullName)
+ fullName
+ )
return String(readAllBytes(Paths.get(deployFile)))
} catch (var5: IllegalArgumentException) {
throw ResourceNotFoundException("Couldn't find resource: $fullName")
}
-
}
}
- fun generateContent(template: String, json: String, ignoreJsonNull: Boolean,
- additionalContext: MutableMap<String, Any>,
- bluePrintLoadConfiguration: BluePrintLoadConfiguration, artifactName: String,
- artifactVersion: String): String {
-
- return generateContent(template,
+ fun generateContent(
+ template: String,
+ json: String,
+ ignoreJsonNull: Boolean,
+ additionalContext: MutableMap<String, Any>,
+ bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ artifactName: String,
+ artifactVersion: String
+ ): String {
+
+ return generateContent(
+ template,
json,
ignoreJsonNull,
additionalContext,
- BlueprintRelatedTemplateLocator(bluePrintLoadConfiguration, artifactName, artifactVersion))
+ BlueprintRelatedTemplateLocator(bluePrintLoadConfiguration, artifactName, artifactVersion)
+ )
}
- fun generateContent(template: String, json: String, ignoreJsonNull: Boolean,
- additionalContext: MutableMap<String, Any>, resourceLocator: ResourceLocator? = null): String {
+ fun generateContent(
+ template: String,
+ json: String,
+ ignoreJsonNull: Boolean,
+ additionalContext: MutableMap<String, Any>,
+ resourceLocator: ResourceLocator? = null
+ ): String {
val jinJava = Jinjava(JinjavaConfig())
if (resourceLocator != null) {
jinJava.resourceLocator = resourceLocator
return jinJava.render(template, additionalContext)
}
}
-
package org.onap.ccsdk.cds.controllerblueprints.core.service
-import org.slf4j.LoggerFactory
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import org.slf4j.LoggerFactory
open class BluePrintRepoFileService(modelTypePath: String) : BluePrintRepoService {
- private val log= LoggerFactory.getLogger(BluePrintRepoFileService::class.toString())
+ private val log = LoggerFactory.getLogger(BluePrintRepoFileService::class.toString())
private val dataTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
private val nodeTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE)
private val artifactTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE)
- private val capabilityTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE)
- private val relationshipTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE)
+ private val capabilityTypePath =
+ modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE)
+ private val relationshipTypePath =
+ modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE)
private val extension = ".json"
override fun getDataType(dataTypeName: String): DataType {
val fileName = dataTypePath.plus(BluePrintConstants.PATH_DIVIDER)
- .plus(dataTypeName).plus(extension)
+ .plus(dataTypeName).plus(extension)
return getModelType(fileName, DataType::class.java)
}
override fun getArtifactType(artifactTypeName: String): ArtifactType {
val fileName = artifactTypePath.plus(BluePrintConstants.PATH_DIVIDER)
- .plus(artifactTypeName).plus(extension)
+ .plus(artifactTypeName).plus(extension)
return getModelType(fileName, ArtifactType::class.java)
}
override fun getRelationshipType(relationshipTypeName: String): RelationshipType {
val fileName = relationshipTypePath.plus(BluePrintConstants.PATH_DIVIDER)
- .plus(relationshipTypeName).plus(extension)
+ .plus(relationshipTypeName).plus(extension)
return getModelType(fileName, RelationshipType::class.java)
}
override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition {
val fileName = capabilityTypePath.plus(BluePrintConstants.PATH_DIVIDER)
- .plus(capabilityDefinitionName).plus(extension)
+ .plus(capabilityDefinitionName).plus(extension)
return getModelType(fileName, CapabilityDefinition::class.java)
}
private fun <T> getModelType(fileName: String, valueType: Class<T>): T {
return JacksonUtils.readValueFromFile(fileName, valueType)
- ?: throw BluePrintException("couldn't get file($fileName) for type(${valueType.name}")
+ ?: throw BluePrintException("couldn't get file($fileName) for type(${valueType.name}")
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.service
-
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.NullNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
+import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
import org.slf4j.LoggerFactory
import java.io.File
propertyAssignments: MutableMap<String, JsonNode>
): MutableMap<String, JsonNode>
- fun resolvePropertyDefinitions(name: String, propertyDefinitions: MutableMap<String, PropertyDefinition>)
- : MutableMap<String, JsonNode>
+ fun resolvePropertyDefinitions(name: String, propertyDefinitions: MutableMap<String, PropertyDefinition>):
+ MutableMap<String, JsonNode>
- fun resolvePropertyAssignments(name: String, propertyAssignments: MutableMap<String, JsonNode>)
- : MutableMap<String, JsonNode>
+ fun resolvePropertyAssignments(name: String, propertyAssignments: MutableMap<String, JsonNode>):
+ MutableMap<String, JsonNode>
fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap<String, JsonNode>
JsonNode>
fun resolveNodeTemplateInterfaceOperationInputs(
- nodeTemplateName: String, interfaceName: String,
+ nodeTemplateName: String,
+ interfaceName: String,
operationName: String
): MutableMap<String, JsonNode>
fun resolveNodeTemplateInterfaceOperationOutputs(
- nodeTemplateName: String, interfaceName: String,
+ nodeTemplateName: String,
+ interfaceName: String,
operationName: String
): MutableMap<String, JsonNode>
fun setInputValue(propertyName: String, value: JsonNode)
fun setWorkflowInputValue(
- workflowName: String, propertyName: String, propertyDefinition: PropertyDefinition,
+ workflowName: String,
+ propertyName: String,
+ propertyDefinition: PropertyDefinition,
value: JsonNode
)
fun setNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String, value: JsonNode)
fun setNodeTemplateOperationPropertyValue(
- nodeTemplateName: String, interfaceName: String,
- operationName: String, propertyName: String, value: JsonNode
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String,
+ propertyName: String,
+ value: JsonNode
)
fun setNodeTemplateOperationInputValue(
- nodeTemplateName: String, interfaceName: String,
- operationName: String, propertyName: String, value: JsonNode
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String,
+ propertyName: String,
+ value: JsonNode
)
fun setNodeTemplateOperationOutputValue(
- nodeTemplateName: String, interfaceName: String,
- operationName: String, propertyName: String, value: JsonNode
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String,
+ propertyName: String,
+ value: JsonNode
)
fun getInputValue(propertyName: String): JsonNode
fun getNodeTemplateOperationOutputValue(
- nodeTemplateName: String, interfaceName: String,
- operationName: String, propertyName: String
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String,
+ propertyName: String
): JsonNode
fun getNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String): JsonNode?
val absoluteEnvFilePath = bluePrintContext.rootPath.plus(File.separator)
.plus(BluePrintConstants.TOSCA_ENVIRONMENTS_DIR)
loadEnvironments(BluePrintConstants.PROPERTY_BPP, absoluteEnvFilePath)
-
}
override fun id(): String {
nodeTemplateName: String,
propertyDefinitions: MutableMap<String, PropertyDefinition>,
propertyAssignments: MutableMap<String, JsonNode>
- )
- : MutableMap<String, JsonNode> {
+ ):
+ MutableMap<String, JsonNode> {
val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf()
// Resolve the Expressing
val propertyAssignmentExpression = PropertyAssignmentService(this)
resolvedValue = propertyAssignmentExpression.resolveAssignmentExpression(
- nodeTemplateName, nodeTypePropertyName, propertyAssignment)
+ nodeTemplateName, nodeTypePropertyName, propertyAssignment
+ )
}
// Set default value if null
return propertyAssignmentValue
}
- override fun resolvePropertyDefinitions(name: String, propertyDefinitions: MutableMap<String, PropertyDefinition>)
- : MutableMap<String, JsonNode> {
+ override fun resolvePropertyDefinitions(name: String, propertyDefinitions: MutableMap<String, PropertyDefinition>):
+ MutableMap<String, JsonNode> {
val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf()
propertyDefinitions.forEach { propertyName, propertyDefinition ->
return propertyAssignmentValue
}
- override fun resolvePropertyAssignments(name: String, propertyAssignments: MutableMap<String, JsonNode>)
- : MutableMap<String, JsonNode> {
+ override fun resolvePropertyAssignments(name: String, propertyAssignments: MutableMap<String, JsonNode>):
+ MutableMap<String, JsonNode> {
val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf()
propertyAssignments.forEach { (propertyName, propertyExpression) ->
interfaceName: String,
operationName: String
): MutableMap<String, JsonNode> {
- log.info("resolveNodeTemplateInterfaceOperationInputs for node template ($nodeTemplateName), " +
- "interface name($interfaceName), operationName($operationName)")
+ log.info(
+ "resolveNodeTemplateInterfaceOperationInputs for node template ($nodeTemplateName), " +
+ "interface name($interfaceName), operationName($operationName)"
+ )
val propertyAssignments: MutableMap<String, JsonNode> =
bluePrintContext.nodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName)
* Resolve the Property Input Assignment Values.
*/
return resolveNodeTemplatePropertyAssignments(nodeTemplateName, nodeTypeInterfaceOperationInputs, propertyAssignments)
-
}
-
override fun resolveNodeTemplateInterfaceOperationOutputs(
nodeTemplateName: String,
interfaceName: String,
* Resolve the Property Output Assignment Values.
*/
val propertyAssignmentValue =
- resolveNodeTemplatePropertyAssignments(nodeTemplateName,nodeTypeInterfaceOperationOutputs, propertyAssignments)
+ resolveNodeTemplatePropertyAssignments(nodeTemplateName, nodeTypeInterfaceOperationOutputs, propertyAssignments)
// Store operation output values into context
propertyAssignmentValue.forEach { (key, value) ->
return nodeTemplate.artifacts?.get(artifactName)
?: throw BluePrintProcessorException(
- "failed to get artifact definition($artifactName) from the node template")
+ "failed to get artifact definition($artifactName) from the node template"
+ )
}
/**
*/
override fun resolveDSLExpression(dslPropertyName: String): JsonNode {
val propertyAssignments = bluePrintContext.dslPropertiesByName(dslPropertyName)
- return if (BluePrintExpressionService.checkContainsExpression(propertyAssignments)
- && propertyAssignments is ObjectNode) {
+ return if (BluePrintExpressionService.checkContainsExpression(propertyAssignments) &&
+ propertyAssignments is ObjectNode
+ ) {
val rootKeyMap = propertyAssignments.rootFieldsToMap()
val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf()
}
override fun setInputValue(propertyName: String, value: JsonNode) {
- val path = """${BluePrintConstants.PATH_INPUTS}${BluePrintConstants.PATH_DIVIDER}${propertyName}"""
+ val path = """${BluePrintConstants.PATH_INPUTS}${BluePrintConstants.PATH_DIVIDER}$propertyName"""
log.trace("setting input path ({}), values ({})", path, value)
put(path, value)
}
override fun setWorkflowInputValue(
- workflowName: String, propertyName: String,
- propertyDefinition: PropertyDefinition, value: JsonNode
+ workflowName: String,
+ propertyName: String,
+ propertyDefinition: PropertyDefinition,
+ value: JsonNode
) {
val path: String = StringBuilder(BluePrintConstants.PATH_NODE_WORKFLOWS)
.append(BluePrintConstants.PATH_DIVIDER).append(workflowName)
}
override fun setNodeTemplateOperationPropertyValue(
- nodeTemplateName: String, interfaceName: String,
- operationName: String, propertyName: String,
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String,
+ propertyName: String,
value: JsonNode
) {
val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES)
}
override fun setNodeTemplateOperationInputValue(
- nodeTemplateName: String, interfaceName: String,
- operationName: String, propertyName: String,
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String,
+ propertyName: String,
value: JsonNode
) {
val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES)
}
override fun setNodeTemplateOperationOutputValue(
- nodeTemplateName: String, interfaceName: String,
- operationName: String, propertyName: String,
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String,
+ propertyName: String,
value: JsonNode
) {
val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES)
put(path, value)
}
-
override fun getInputValue(propertyName: String): JsonNode {
val path = StringBuilder(BluePrintConstants.PATH_INPUTS)
.append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
}
override fun getNodeTemplateOperationOutputValue(
- nodeTemplateName: String, interfaceName: String,
- operationName: String, propertyName: String
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String,
+ propertyName: String
): JsonNode {
val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES)
.append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName)
}
override fun assignWorkflowInputs(workflowName: String, jsonNode: JsonNode) {
- log.info("For workflow ($workflowName) driving input data from (${jsonNode})")
+ log.info("For workflow ($workflowName) driving input data from ($jsonNode)")
val dynamicInputPropertiesName = "$workflowName-properties"
- bluePrintContext.workflowByName(workflowName).inputs?.
- forEach { propertyName, property ->
- if (propertyName != dynamicInputPropertiesName) {
- val valueNode: JsonNode =
- jsonNode.at(BluePrintConstants.PATH_DIVIDER + propertyName).returnNullIfMissing()
- ?: property.defaultValue
- ?: NullNode.getInstance()
- log.trace("Setting input data - attribute:($propertyName) value:($valueNode)")
- setInputValue(propertyName, valueNode)
+ bluePrintContext.workflowByName(workflowName).inputs
+ ?.forEach { propertyName, property ->
+ if (propertyName != dynamicInputPropertiesName) {
+ val valueNode: JsonNode =
+ jsonNode.at(BluePrintConstants.PATH_DIVIDER + propertyName).returnNullIfMissing()
+ ?: property.defaultValue
+ ?: NullNode.getInstance()
+ log.trace("Setting input data - attribute:($propertyName) value:($valueNode)")
+ setInputValue(propertyName, valueNode)
+ }
}
- }
// Load Dynamic data Types
jsonNode.get(dynamicInputPropertiesName)?.let {
- bluePrintContext.dataTypeByName("dt-$dynamicInputPropertiesName")?.properties?.
- forEach { propertyName, property ->
- val valueNode: JsonNode =
- it.at(BluePrintConstants.PATH_DIVIDER + propertyName).returnNullIfMissing()
- ?: property.defaultValue
- ?: NullNode.getInstance()
- log.trace("Setting input data - attribute:($propertyName) value:($valueNode)")
- setInputValue(propertyName, valueNode)
- }
+ bluePrintContext.dataTypeByName("dt-$dynamicInputPropertiesName")?.properties
+ ?.forEach { propertyName, property ->
+ val valueNode: JsonNode =
+ it.at(BluePrintConstants.PATH_DIVIDER + propertyName).returnNullIfMissing()
+ ?: property.defaultValue
+ ?: NullNode.getInstance()
+ log.trace("Setting input data - attribute:($propertyName) value:($valueNode)")
+ setInputValue(propertyName, valueNode)
+ }
}
}
}
return jsonNode
}
-
-
-}
\ No newline at end of file
+}
class BluePrintTemplateService(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration) :
BlueprintTemplateService {
- override suspend fun generateContent(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- nodeTemplateName: String, artifactName: String, jsonData: String,
- ignoreJsonNull: Boolean, additionalContext: MutableMap<String, Any>): String {
+ override suspend fun generateContent(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ nodeTemplateName: String,
+ artifactName: String,
+ jsonData: String,
+ ignoreJsonNull: Boolean,
+ additionalContext: MutableMap<String, Any>
+ ): String {
val artifactDefinition =
bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
return when (templateType) {
BluePrintConstants.ARTIFACT_JINJA_TYPE_NAME -> {
- BluePrintJinjaTemplateService.generateContent(template,
+ BluePrintJinjaTemplateService.generateContent(
+ template,
jsonData,
ignoreJsonNull,
additionalContext,
bluePrintLoadConfiguration,
bluePrintRuntimeService.bluePrintContext().name(),
- bluePrintRuntimeService.bluePrintContext().version())
+ bluePrintRuntimeService.bluePrintContext().version()
+ )
}
BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME -> {
BluePrintVelocityTemplateService.generateContent(template, jsonData, ignoreJsonNull, additionalContext)
}
else -> {
- throw BluePrintProcessorException("Unknown Artifact type, expecting ${BluePrintConstants.ARTIFACT_JINJA_TYPE_NAME}" +
- "or ${BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME}")
+ throw BluePrintProcessorException(
+ "Unknown Artifact type, expecting ${BluePrintConstants.ARTIFACT_JINJA_TYPE_NAME}" +
+ "or ${BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME}"
+ )
}
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.service
-import org.slf4j.LoggerFactory
import com.fasterxml.jackson.databind.JsonNode
import com.google.common.base.Preconditions
import org.apache.commons.lang3.StringUtils
-import org.onap.ccsdk.cds.controllerblueprints.core.*
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
+import org.onap.ccsdk.cds.controllerblueprints.core.format
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import org.slf4j.LoggerFactory
import java.io.Serializable
/**
@Deprecated("Decomposed implementation moved to blueprint-validation module")
open class BluePrintValidatorDefaultService : BluePrintValidatorService {
- val log= LoggerFactory.getLogger(BluePrintValidatorDefaultService::class.toString())
+ val log = LoggerFactory.getLogger(BluePrintValidatorDefaultService::class.toString())
lateinit var bluePrintContext: BluePrintContext
lateinit var serviceTemplate: ServiceTemplate
} catch (e: Exception) {
log.error("validation failed in the path : {}", paths.joinToString(separator), e)
log.error("validation trace message :{} ", message)
- throw BluePrintException(e,
- format("failed to validate blueprint on path ({}) with message {}"
- , paths.joinToString(separator), e.message))
+ throw BluePrintException(
+ e,
+ format("failed to validate blueprint on path ({}) with message {}", paths.joinToString(separator), e.message)
+ )
}
}
paths.add(nodeTypeName)
message.appendln("--> Node Type :" + paths.joinToString(separator))
val derivedFrom: String = nodeType.derivedFrom
- //Check Derived From
+ // Check Derived From
checkValidNodeTypesDerivedFrom(nodeTypeName, derivedFrom)
if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) {
serviceTemplate.nodeTypes?.get(derivedFrom)
- ?: throw BluePrintException(format("Failed to get derivedFrom NodeType({})'s for NodeType({}) ",
- derivedFrom, nodeTypeName))
+ ?: throw BluePrintException(
+ format(
+ "Failed to get derivedFrom NodeType({})'s for NodeType({}) ",
+ derivedFrom, nodeTypeName
+ )
+ )
}
nodeType.properties?.let { validatePropertyDefinitions(nodeType.properties!!) }
val type: String = nodeTemplate.type
val nodeType: NodeType = serviceTemplate.nodeTypes?.get(type)
- ?: throw BluePrintException(format("Failed to get NodeType({}) definition for NodeTemplate({})", type, nodeTemplateName))
+ ?: throw BluePrintException(format("Failed to get NodeType({}) definition for NodeTemplate({})", type, nodeTemplateName))
nodeTemplate.artifacts?.let { validateArtifactDefinitions(nodeTemplate.artifacts!!) }
nodeTemplate.properties?.let { validatePropertyAssignments(nodeType.properties!!, nodeTemplate.properties!!) }
paths.add(artifactDefinitionName)
message.appendln("Validating artifact " + paths.joinToString(separator))
val type: String = artifactDefinition.type
- ?: throw BluePrintException(format("type is missing for ArtifactDefinition({})", artifactDefinitionName))
+ ?: throw BluePrintException(format("type is missing for ArtifactDefinition({})", artifactDefinitionName))
// Check Artifact Type
checkValidArtifactType(artifactDefinitionName, type)
val file: String = artifactDefinition.file
- ?: throw BluePrintException(format("file is missing for ArtifactDefinition({})", artifactDefinitionName))
+ ?: throw BluePrintException(format("file is missing for ArtifactDefinition({})", artifactDefinitionName))
paths.removeAt(paths.lastIndex)
}
}
BluePrintTypes.validCollectionTypes().contains(dataType) -> {
val entrySchemaType: String = propertyDefinition.entrySchema?.type
- ?: throw BluePrintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, propertyName))
+ ?: throw BluePrintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, propertyName))
checkPrimitiveOrComplex(entrySchemaType, propertyName)
}
else -> checkPropertyDataType(dataType, propertyName)
}
@Throws(BluePrintException::class)
- open fun validatePropertyAssignments(nodeTypeProperties: MutableMap<String, PropertyDefinition>,
- properties: MutableMap<String, JsonNode>) {
+ open fun validatePropertyAssignments(
+ nodeTypeProperties: MutableMap<String, PropertyDefinition>,
+ properties: MutableMap<String, JsonNode>
+ ) {
properties.forEach { propertyName, propertyAssignment ->
val propertyDefinition: PropertyDefinition = nodeTypeProperties[propertyName]
- ?: throw BluePrintException(format("failed to get definition for the property ({})", propertyName))
+ ?: throw BluePrintException(format("failed to get definition for the property ({})", propertyName))
validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment)
-
}
}
@Throws(BluePrintException::class)
- open fun validatePropertyAssignment(propertyName: String, propertyDefinition: PropertyDefinition,
- propertyAssignment: JsonNode) {
+ open fun validatePropertyAssignment(
+ propertyName: String,
+ propertyDefinition: PropertyDefinition,
+ propertyAssignment: JsonNode
+ ) {
// Check and Validate if Expression Node
val expressionData = BluePrintExpressionService.getExpressionData(propertyAssignment)
if (!expressionData.isExpression) {
paths.add(capabilityName)
val capabilityDefinition = nodeType.capabilities?.get(capabilityName)
- ?: throw BluePrintException(format("Failed to get NodeTemplate({}) capability definition ({}) " +
- "from NodeType({}) ", nodeTemplateName, capabilityName, nodeTemplate.type))
+ ?: throw BluePrintException(
+ format(
+ "Failed to get NodeTemplate({}) capability definition ({}) " +
+ "from NodeType({}) ", nodeTemplateName, capabilityName, nodeTemplate.type
+ )
+ )
validateCapabilityAssignment(nodeTemplateName, capabilityName, capabilityDefinition, capabilityAssignment)
}
@Throws(BluePrintException::class)
- open fun validateCapabilityAssignment(nodeTemplateName: String, capabilityName: String,
- capabilityDefinition: CapabilityDefinition, capabilityAssignment: CapabilityAssignment) {
+ open fun validateCapabilityAssignment(
+ nodeTemplateName: String,
+ capabilityName: String,
+ capabilityDefinition: CapabilityDefinition,
+ capabilityAssignment: CapabilityAssignment
+ ) {
capabilityAssignment.properties?.let { validatePropertyAssignments(capabilityDefinition.properties!!, capabilityAssignment.properties!!) }
-
}
@Throws(BluePrintException::class)
requirements?.forEach { requirementName, requirementAssignment ->
paths.add(requirementName)
val requirementDefinition = nodeType.requirements?.get(requirementName)
- ?: throw BluePrintException(format("Failed to get NodeTemplate({}) requirement definition ({}) from" +
- " NodeType({}) ", nodeTemplateName, requirementName, nodeTemplate.type))
+ ?: throw BluePrintException(
+ format(
+ "Failed to get NodeTemplate({}) requirement definition ({}) from" +
+ " NodeType({}) ", nodeTemplateName, requirementName, nodeTemplate.type
+ )
+ )
// Validate Requirement Assignment
validateRequirementAssignment(nodeTemplateName, requirementName, requirementDefinition, requirementAssignment)
paths.removeAt(paths.lastIndex)
}
paths.removeAt(paths.lastIndex)
-
}
@Throws(BluePrintException::class)
- open fun validateRequirementAssignment(nodeTemplateName: String, requirementAssignmentName: String,
- requirementDefinition: RequirementDefinition, requirementAssignment: RequirementAssignment) {
+ open fun validateRequirementAssignment(
+ nodeTemplateName: String,
+ requirementAssignmentName: String,
+ requirementDefinition: RequirementDefinition,
+ requirementAssignment: RequirementAssignment
+ ) {
log.info("Validating NodeTemplate({}) requirement assignment ({}) ", nodeTemplateName, requirementAssignmentName)
val requirementNodeTemplateName = requirementAssignment.node!!
val capabilityName = requirementAssignment.capability
val relationship = requirementAssignment.relationship!!
check(BluePrintTypes.validRelationShipDerivedFroms.contains(relationship)) {
- throw BluePrintException(format("Failed to get relationship type ({}) for NodeTemplate({})'s requirement({}) ",
- relationship, nodeTemplateName, requirementAssignmentName))
+ throw BluePrintException(
+ format(
+ "Failed to get relationship type ({}) for NodeTemplate({})'s requirement({}) ",
+ relationship, nodeTemplateName, requirementAssignmentName
+ )
+ )
}
val relationShipNodeTemplate = serviceTemplate.topologyTemplate?.nodeTemplates?.get(requirementNodeTemplateName)
- ?: throw BluePrintException(format("Failed to get requirement NodeTemplate({})'s for NodeTemplate({}) requirement({}) ",
- requirementNodeTemplateName, nodeTemplateName, requirementAssignmentName))
+ ?: throw BluePrintException(
+ format(
+ "Failed to get requirement NodeTemplate({})'s for NodeTemplate({}) requirement({}) ",
+ requirementNodeTemplateName, nodeTemplateName, requirementAssignmentName
+ )
+ )
relationShipNodeTemplate.capabilities?.get(capabilityName)
- ?: throw BluePrintException(format("Failed to get requirement NodeTemplate({})'s capability({}) for NodeTemplate ({})'s requirement({}) ",
- requirementNodeTemplateName, capabilityName, nodeTemplateName, requirementAssignmentName))
-
-
+ ?: throw BluePrintException(
+ format(
+ "Failed to get requirement NodeTemplate({})'s capability({}) for NodeTemplate ({})'s requirement({}) ",
+ requirementNodeTemplateName, capabilityName, nodeTemplateName, requirementAssignmentName
+ )
+ )
}
@Throws(BluePrintException::class)
interfaces?.forEach { interfaceAssignmentName, interfaceAssignment ->
paths.add(interfaceAssignmentName)
val interfaceDefinition = nodeType.interfaces?.get(interfaceAssignmentName)
- ?: throw BluePrintException(format("Failed to get NodeTemplate({}) interface definition ({}) from" +
- " NodeType({}) ", nodeTemplateName, interfaceAssignmentName, nodeTemplate.type))
-
- validateInterfaceAssignment(nodeTemplateName, interfaceAssignmentName, interfaceDefinition,
- interfaceAssignment)
+ ?: throw BluePrintException(
+ format(
+ "Failed to get NodeTemplate({}) interface definition ({}) from" +
+ " NodeType({}) ", nodeTemplateName, interfaceAssignmentName, nodeTemplate.type
+ )
+ )
+
+ validateInterfaceAssignment(
+ nodeTemplateName, interfaceAssignmentName, interfaceDefinition,
+ interfaceAssignment
+ )
paths.removeAt(paths.lastIndex)
}
paths.removeAt(paths.lastIndex)
-
-
}
@Throws(BluePrintException::class)
- open fun validateInterfaceAssignment(nodeTemplateName: String, interfaceAssignmentName: String,
- interfaceDefinition: InterfaceDefinition,
- interfaceAssignment: InterfaceAssignment) {
+ open fun validateInterfaceAssignment(
+ nodeTemplateName: String,
+ interfaceAssignmentName: String,
+ interfaceDefinition: InterfaceDefinition,
+ interfaceAssignment: InterfaceAssignment
+ ) {
val operations = interfaceAssignment.operations
operations?.let {
- validateInterfaceOperationsAssignment(nodeTemplateName, interfaceAssignmentName, interfaceDefinition,
- interfaceAssignment)
+ validateInterfaceOperationsAssignment(
+ nodeTemplateName, interfaceAssignmentName, interfaceDefinition,
+ interfaceAssignment
+ )
}
-
}
@Throws(BluePrintException::class)
- open fun validateInterfaceOperationsAssignment(nodeTemplateName: String, interfaceAssignmentName: String,
- interfaceDefinition: InterfaceDefinition,
- interfaceAssignment: InterfaceAssignment) {
+ open fun validateInterfaceOperationsAssignment(
+ nodeTemplateName: String,
+ interfaceAssignmentName: String,
+ interfaceDefinition: InterfaceDefinition,
+ interfaceAssignment: InterfaceAssignment
+ ) {
val operations = interfaceAssignment.operations
operations?.let {
it.forEach { operationAssignmentName, operationAssignments ->
val operationDefinition = interfaceDefinition.operations?.get(operationAssignmentName)
- ?: throw BluePrintException(format("Failed to get NodeTemplate({}) operation definition ({}) ",
- nodeTemplateName, operationAssignmentName))
-
- log.info("Validation NodeTemplate({}) Interface({}) Operation ({})", nodeTemplateName,
- interfaceAssignmentName, operationAssignmentName)
+ ?: throw BluePrintException(
+ format(
+ "Failed to get NodeTemplate({}) operation definition ({}) ",
+ nodeTemplateName, operationAssignmentName
+ )
+ )
+
+ log.info(
+ "Validation NodeTemplate({}) Interface({}) Operation ({})", nodeTemplateName,
+ interfaceAssignmentName, operationAssignmentName
+ )
val inputs = operationAssignments.inputs
val outputs = operationAssignments.outputs
inputs?.forEach { propertyName, propertyAssignment ->
val propertyDefinition = operationDefinition.inputs?.get(propertyName)
- ?: throw BluePrintException(format("Failed to get NodeTemplate({}) operation definition ({}) " +
- "property definition({})", nodeTemplateName, operationAssignmentName, propertyName))
+ ?: throw BluePrintException(
+ format(
+ "Failed to get NodeTemplate({}) operation definition ({}) " +
+ "property definition({})", nodeTemplateName, operationAssignmentName, propertyName
+ )
+ )
// Check the property values with property definition
validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment)
}
outputs?.forEach { propertyName, propertyAssignment ->
val propertyDefinition = operationDefinition.outputs?.get(propertyName)
- ?: throw BluePrintException(format("Failed to get NodeTemplate({}) operation definition ({}) " +
- "output property definition({})", nodeTemplateName, operationAssignmentName,
- propertyName))
+ ?: throw BluePrintException(
+ format(
+ "Failed to get NodeTemplate({}) operation definition ({}) " +
+ "output property definition({})", nodeTemplateName, operationAssignmentName,
+ propertyName
+ )
+ )
// Check the property values with property definition
validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment)
}
-
}
}
-
}
@Throws(BluePrintException::class)
}
@Throws(BluePrintException::class)
- open fun validateCapabilityDefinition(nodeTypeName: String, nodeType: NodeType, capabilityName: String,
- capabilityDefinition: CapabilityDefinition) {
+ open fun validateCapabilityDefinition(
+ nodeTypeName: String,
+ nodeType: NodeType,
+ capabilityName: String,
+ capabilityDefinition: CapabilityDefinition
+ ) {
val capabilityType = capabilityDefinition.type
check(BluePrintTypes.validCapabilityTypes.contains(capabilityType)) {
- throw BluePrintException(format("Failed to get CapabilityType({}) for NodeType({})",
- capabilityType, nodeTypeName))
+ throw BluePrintException(
+ format(
+ "Failed to get CapabilityType({}) for NodeType({})",
+ capabilityType, nodeTypeName
+ )
+ )
}
}
}
@Throws(BluePrintException::class)
- open fun validateRequirementDefinition(nodeTypeName: String, nodeType: NodeType, requirementDefinitionName: String,
- requirementDefinition: RequirementDefinition) {
+ open fun validateRequirementDefinition(
+ nodeTypeName: String,
+ nodeType: NodeType,
+ requirementDefinitionName: String,
+ requirementDefinition: RequirementDefinition
+ ) {
log.info("Validating NodeType({}) RequirementDefinition ({}) ", nodeTypeName, requirementDefinitionName)
val requirementNodeTypeName = requirementDefinition.node!!
val relationship = requirementDefinition.relationship!!
check(BluePrintTypes.validRelationShipDerivedFroms.contains(relationship)) {
- throw BluePrintException(format("Failed to get relationship({}) for NodeType({})'s requirement({}) ",
- relationship, nodeTypeName, requirementDefinitionName))
+ throw BluePrintException(
+ format(
+ "Failed to get relationship({}) for NodeType({})'s requirement({}) ",
+ relationship, nodeTypeName, requirementDefinitionName
+ )
+ )
}
val relationShipNodeType = serviceTemplate.nodeTypes?.get(requirementNodeTypeName)
- ?: throw BluePrintException(format("Failed to get requirement NodeType({})'s for requirement({}) ",
- requirementNodeTypeName, requirementDefinitionName))
+ ?: throw BluePrintException(
+ format(
+ "Failed to get requirement NodeType({})'s for requirement({}) ",
+ requirementNodeTypeName, requirementDefinitionName
+ )
+ )
relationShipNodeType.capabilities?.get(capabilityName)
- ?: throw BluePrintException(format("Failed to get requirement NodeType({})'s capability({}) for NodeType ({})'s requirement({}) ",
- requirementNodeTypeName, capabilityName, nodeTypeName, requirementDefinitionName))
-
+ ?: throw BluePrintException(
+ format(
+ "Failed to get requirement NodeType({})'s capability({}) for NodeType ({})'s requirement({}) ",
+ requirementNodeTypeName, capabilityName, nodeTypeName, requirementDefinitionName
+ )
+ )
}
-
@Throws(BluePrintException::class)
open fun validateInterfaceDefinitions(interfaces: MutableMap<String, InterfaceDefinition>) {
paths.add("interfaces")
open fun checkValidArtifactType(artifactDefinitionName: String, artifactTypeName: String) {
val artifactType = serviceTemplate.artifactTypes?.get(artifactTypeName)
- ?: throw BluePrintException("failed to artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)")
+ ?: throw BluePrintException("failed to artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)")
checkValidArtifactTypeDerivedFrom(artifactTypeName, artifactType.derivedFrom)
}
if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) {
isValid = JacksonUtils.checkJsonNodeValueOfPrimitiveType(propertyType, propertyAssignment)
-
} else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) {
val entrySchemaType = propertyDefinition.entrySchema?.type
- ?: throw BluePrintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName))
+ ?: throw BluePrintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName))
if (!BluePrintTypes.validPropertyTypes().contains(entrySchemaType)) {
checkPropertyDataType(entrySchemaType, propertyName)
}
check(isValid) {
- throw BluePrintException(format("property({}) defined of type({}) is not comptable with the value ({})",
- propertyName, propertyType, propertyAssignment))
+ throw BluePrintException(
+ format(
+ "property({}) defined of type({}) is not comptable with the value ({})",
+ propertyName, propertyType, propertyAssignment
+ )
+ )
}
}
private fun checkPropertyDataType(dataTypeName: String, propertyName: String) {
val dataType = serviceTemplate.dataTypes?.get(dataTypeName)
- ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName))
+ ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName))
checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom)
-
}
private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean {
private fun checkDataType(key: String): Boolean {
return serviceTemplate.dataTypes?.containsKey(key) ?: false
}
-
-}
\ No newline at end of file
+}
/**
* Generate Content from Velocity Template and JSON Content with injected API
*/
- fun generateContent(template: String, json: String, ignoreJsonNull: Boolean = false,
- additionalContext: MutableMap<String, Any> = mutableMapOf()): String {
+ fun generateContent(
+ template: String,
+ json: String,
+ ignoreJsonNull: Boolean = false,
+ additionalContext: MutableMap<String, Any> = mutableMapOf()
+ ): String {
// Customized Object Mapper to remove String double quotes
val mapper = ObjectMapper()
val jsonNode: JsonNode? = if (json.isNotEmpty()) {
mapper.readValue(json, JsonNode::class.java)
- ?: throw BluePrintProcessorException("couldn't get json node from json")
+ ?: throw BluePrintProcessorException("couldn't get json node from json")
} else {
null
}
/**
* Generate Content from Velocity Template and JSON Node with injected API
*/
- fun generateContent(template: String, jsonNode: JsonNode?, ignoreJsonNull: Boolean = false,
- additionalContext: MutableMap<String, Any> = mutableMapOf()): String {
+ fun generateContent(
+ template: String,
+ jsonNode: JsonNode?,
+ ignoreJsonNull: Boolean = false,
+ additionalContext: MutableMap<String, Any> = mutableMapOf()
+ ): String {
/*
* create a new instance of the velocity engine
package org.onap.ccsdk.cds.controllerblueprints.core.service
-import kotlinx.coroutines.*
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.CoroutineName
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.channels.consumeEach
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import kotlinx.coroutines.launch
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel
import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeStatus
import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeStatus
+import org.onap.ccsdk.cds.controllerblueprints.core.incomingEdges
+import org.onap.ccsdk.cds.controllerblueprints.core.isEndNode
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.outgoingEdges
+import org.onap.ccsdk.cds.controllerblueprints.core.outgoingEdgesNotInLabels
+import org.onap.ccsdk.cds.controllerblueprints.core.startNodes
import kotlin.coroutines.CoroutineContext
interface BluePrintWorkFlowService<In, Out> {
suspend fun cancelNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel
suspend fun restartNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel
-
}
/** Workflow Message Types */
}
}
-
private suspend fun nodeActor() = actor<NodeMessage<In, Out>>(coroutineContext, Channel.UNLIMITED) {
/** Send message to process from one state to other state */
suspend fun executeNodeWorker(message: NodeExecuteMessage<In, Out>) {
val node = message.node
node.status = NodeStatus.EXECUTING
- val nodeState = if (node.id == BluePrintConstants.GRAPH_START_NODE_NAME
- || node.id == BluePrintConstants.GRAPH_END_NODE_NAME) {
+ val nodeState = if (node.id == BluePrintConstants.GRAPH_START_NODE_NAME ||
+ node.id == BluePrintConstants.GRAPH_END_NODE_NAME
+ ) {
EdgeLabel.SUCCESS
} else {
log.debug("##### Processing workflow($workflowId) node($node) #####")
}
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.service
-
-import org.slf4j.LoggerFactory
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.NullNode
-import org.onap.ccsdk.cds.controllerblueprints.core.*
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationOutputExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.format
+import org.onap.ccsdk.cds.controllerblueprints.core.isComplexType
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.ResourceResolverUtils
+import org.slf4j.LoggerFactory
/**
*
* @author Brinda Santh
*/
class PropertyAssignmentService(var bluePrintRuntimeService: BluePrintRuntimeService<MutableMap<String, JsonNode>>) {
- private val log= LoggerFactory.getLogger(this::class.toString())
+
+ private val log = LoggerFactory.getLogger(this::class.toString())
private var bluePrintContext: BluePrintContext = bluePrintRuntimeService.bluePrintContext()
-/*
+ /*
-If Property Assignment is Expression.
- Get the Expression
- Recursively resolve the expression
- */
+ If Property Assignment is Expression.
+ Get the Expression
+ Recursively resolve the expression
+ */
- fun resolveAssignmentExpression(nodeTemplateName: String, assignmentName: String,
- assignment: JsonNode): JsonNode {
+ fun resolveAssignmentExpression(
+ nodeTemplateName: String,
+ assignmentName: String,
+ assignment: JsonNode
+ ): JsonNode {
val valueNode: JsonNode
log.trace("Assignment ({})", assignment)
val expressionData = BluePrintExpressionService.getExpressionData(assignment)
valueNode = bluePrintRuntimeService.resolveDSLExpression(expressionData.dslExpression!!.propertyName)
}
BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE -> {
-
}
else -> {
throw BluePrintException(format("for property ({}), command ({}) is not supported ", propName, command))
}
BluePrintConstants.PROPERTY_BPP -> {
valueNode = bluePrintRuntimeService.getNodeTemplateAttributeValue(BluePrintConstants.PROPERTY_BPP, attributeName)
- ?: throw BluePrintException("failed to get env attribute name ($attributeName) ")
+ ?: throw BluePrintException("failed to get env attribute name ($attributeName) ")
}
else -> {
if (!attributeExpression.modelableEntityName.equals(BluePrintConstants.PROPERTY_SELF, true)) {
}
var attributeDefinition: AttributeDefinition = bluePrintContext
- .nodeTemplateNodeType(attributeNodeTemplateName).attributes?.get(attributeName)
- ?: throw BluePrintException("failed to get attribute definitions for node template ($attributeNodeTemplateName)'s attribute name ($attributeName) ")
+ .nodeTemplateNodeType(attributeNodeTemplateName).attributes?.get(attributeName)
+ ?: throw BluePrintException("failed to get attribute definitions for node template ($attributeNodeTemplateName)'s attribute name ($attributeName) ")
valueNode = bluePrintRuntimeService.getNodeTemplateAttributeValue(attributeNodeTemplateName, attributeName)
- ?: throw BluePrintException("failed to get node template ($attributeNodeTemplateName)'s attribute name ($attributeName) ")
+ ?: throw BluePrintException("failed to get node template ($attributeNodeTemplateName)'s attribute name ($attributeName) ")
}
-
}
if (subAttributeName != null) {
if (valueNode.isComplexType())
}
val nodeTemplatePropertyExpression = bluePrintContext.nodeTemplateByName(propertyNodeTemplateName).properties?.get(propertyName)
- ?: throw BluePrintException(format("failed to get property definitions for node template ({})'s property name ({}) ", nodeTemplateName, propertyName))
+ ?: throw BluePrintException(
+ format(
+ "failed to get property definitions for node template ({})'s property name ({}) ",
+ nodeTemplateName,
+ propertyName
+ )
+ )
var propertyDefinition: PropertyDefinition = bluePrintContext.nodeTemplateNodeType(propertyNodeTemplateName).properties?.get(propertyName)!!
- log.info("node template name ({}), property Name ({}) resolved value ({})", propertyNodeTemplateName, propertyName, nodeTemplatePropertyExpression)
+ log.info(
+ "node template name ({}), property Name ({}) resolved value ({})",
+ propertyNodeTemplateName,
+ propertyName,
+ nodeTemplatePropertyExpression
+ )
// Check it it is a nested expression
valueNode = resolveAssignmentExpression(propertyNodeTemplateName, propertyName, nodeTemplatePropertyExpression)
outputNodeTemplateName = operationOutputExpression.modelableEntityName
}
- var valueNode = bluePrintRuntimeService.getNodeTemplateOperationOutputValue(outputNodeTemplateName,
- operationOutputExpression.interfaceName, operationOutputExpression.operationName,
- operationOutputExpression.propertyName)
+ var valueNode = bluePrintRuntimeService.getNodeTemplateOperationOutputValue(
+ outputNodeTemplateName,
+ operationOutputExpression.interfaceName, operationOutputExpression.operationName,
+ operationOutputExpression.propertyName
+ )
val subPropertyName: String? = operationOutputExpression.subPropertyName
if (subPropertyName != null) {
artifactNodeTemplateName = artifactExpression.modelableEntityName
}
val artifactDefinition: ArtifactDefinition = bluePrintContext.nodeTemplateByName(artifactNodeTemplateName)
- .artifacts?.get(artifactExpression.artifactName)
- ?: throw BluePrintException(format("failed to get artifact definitions for node template ({})'s " +
- "artifact name ({}) ", nodeTemplateName, artifactExpression.artifactName))
+ .artifacts?.get(artifactExpression.artifactName)
+ ?: throw BluePrintException(
+ format(
+ "failed to get artifact definitions for node template ({})'s " +
+ "artifact name ({}) ", nodeTemplateName, artifactExpression.artifactName
+ )
+ )
return JacksonUtils.jsonNodeFromObject(artifactContent(artifactDefinition))
}
return ""
}
}
-
import com.google.common.base.Predicates
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.slf4j.LoggerFactory
-import java.io.*
-import java.nio.charset.*
-import java.nio.file.*
-import java.nio.file.attribute.*
-import java.util.function.*
-import java.util.zip.*
+import java.io.BufferedInputStream
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.io.FileOutputStream
+import java.io.IOException
+import java.io.OutputStream
+import java.nio.charset.Charset
+import java.nio.file.FileVisitResult
+import java.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.SimpleFileVisitor
+import java.nio.file.attribute.BasicFileAttributes
+import java.util.function.Predicate
+import java.util.zip.Deflater
+import java.util.zip.ZipEntry
+import java.util.zip.ZipFile
+import java.util.zip.ZipOutputStream
class BluePrintArchiveUtils {
*/
fun compress(source: File, destination: File): Boolean {
try {
- if(!destination.parentFile.exists()) {
+ if (!destination.parentFile.exists()) {
destination.parentFile.mkdirs()
}
destination.createNewFile()
*/
fun compressToBytes(baseDir: Path, compressionLevel: Int = Deflater.NO_COMPRESSION): ByteArray {
return compressFolder(baseDir, ByteArrayOutputStream(), compressionLevel = compressionLevel)
- .toByteArray()
+ .toByteArray()
}
/**
* @param fixedModificationTime to force every entry to have this modification time.
* Useful for reproducible operations, like tests, for example.
*/
- private fun <T> compressFolder(baseDir: Path, output: T,
- pathFilter: Predicate<Path> = Predicates.alwaysTrue(),
- compressionLevel: Int = Deflater.DEFAULT_COMPRESSION,
- fixedModificationTime: Long? = null): T
+ private fun <T> compressFolder(
+ baseDir: Path,
+ output: T,
+ pathFilter: Predicate<Path> = Predicates.alwaysTrue(),
+ compressionLevel: Int = Deflater.DEFAULT_COMPRESSION,
+ fixedModificationTime: Long? = null
+ ): T
where T : OutputStream {
ZipOutputStream(output)
- .apply { setLevel(compressionLevel) }
- .use { zos ->
- Files.walkFileTree(baseDir, object : SimpleFileVisitor<Path>() {
- @Throws(IOException::class)
- override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
- if (pathFilter.test(file)) {
- val zipEntry = ZipEntry(baseDir.relativize(file).toString())
- fixedModificationTime?.let {
- zipEntry.time = it
- }
- zipEntry.time = 0;
- zos.putNextEntry(zipEntry)
- Files.copy(file, zos)
- zos.closeEntry()
- }
- return FileVisitResult.CONTINUE
- }
-
- @Throws(IOException::class)
- override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
- val zipEntry = ZipEntry(baseDir.relativize(dir).toString() + "/")
+ .apply { setLevel(compressionLevel) }
+ .use { zos ->
+ Files.walkFileTree(baseDir, object : SimpleFileVisitor<Path>() {
+ @Throws(IOException::class)
+ override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
+ if (pathFilter.test(file)) {
+ val zipEntry = ZipEntry(baseDir.relativize(file).toString())
fixedModificationTime?.let {
zipEntry.time = it
}
+ zipEntry.time = 0
zos.putNextEntry(zipEntry)
+ Files.copy(file, zos)
zos.closeEntry()
- return FileVisitResult.CONTINUE
}
- })
- }
+ return FileVisitResult.CONTINUE
+ }
+
+ @Throws(IOException::class)
+ override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
+ val zipEntry = ZipEntry(baseDir.relativize(dir).toString() + "/")
+ fixedModificationTime?.let {
+ zipEntry.time = it
+ }
+ zos.putNextEntry(zipEntry)
+ zos.closeEntry()
+ return FileVisitResult.CONTINUE
+ }
+ })
+ }
return output
}
return destinationDir
}
}
-
-}
\ No newline at end of file
+}
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileFilter
-import java.nio.file.*
-
+import java.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.Paths
+import java.nio.file.StandardOpenOption
class BluePrintFileUtils {
companion object {
val metaDataDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_METADATA_DIR))
Files.createDirectories(metaDataDir.toPath())
- val metaFile = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants
- .TOSCA_METADATA_ENTRY_DEFINITION_FILE))
+ val metaFile = File(
+ blueprintDir.absolutePath.plus(File.separator).plus(
+ BluePrintConstants
+ .TOSCA_METADATA_ENTRY_DEFINITION_FILE
+ )
+ )
Files.write(metaFile.toPath(), getMetaDataContent().toByteArray(), StandardOpenOption.CREATE_NEW)
val definitionsDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR))
val templatesDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_TEMPLATES_DIR))
Files.createDirectories(templatesDir.toPath())
-
}
fun copyBluePrint(sourcePath: String, targetPath: String) {
populateDefaultImports(blueprintContext)
// Rewrite the Entry Definition Files
writeEntryDefinitionFile(blueprintContext)
-
}
fun writeBluePrintTypes(blueprintContext: BluePrintContext) {
val definitionDir = File(definitionPath)
check(definitionDir.exists()) {
- throw BluePrintException(ErrorCode.BLUEPRINT_PATH_MISSING.value, "couldn't get definition file under " +
- "path(${definitionDir.absolutePath})")
+ throw BluePrintException(
+ ErrorCode.BLUEPRINT_PATH_MISSING.value, "couldn't get definition file under " +
+ "path(${definitionDir.absolutePath})"
+ )
}
blueprintContext.serviceTemplate.dataTypes?.let {
private fun populateDefaultImports(blueprintContext: BluePrintContext) {
// Get the Default Types
- val types = arrayListOf(BluePrintConstants.PATH_DATA_TYPES, BluePrintConstants.PATH_RELATIONSHIP_TYPES,
- BluePrintConstants.PATH_ARTIFACT_TYPES, BluePrintConstants.PATH_NODE_TYPES,
- BluePrintConstants.PATH_POLICY_TYPES)
+ val types = arrayListOf(
+ BluePrintConstants.PATH_DATA_TYPES, BluePrintConstants.PATH_RELATIONSHIP_TYPES,
+ BluePrintConstants.PATH_ARTIFACT_TYPES, BluePrintConstants.PATH_NODE_TYPES,
+ BluePrintConstants.PATH_POLICY_TYPES
+ )
// Clean Type Imports
cleanImportTypes(blueprintContext.serviceTemplate)
Files.write(definitionFile.toPath(), content.toByteArray(), StandardOpenOption.CREATE_NEW)
check(definitionFile.exists()) {
- throw BluePrintException(ErrorCode.BLUEPRINT_WRITING_FAIL.value, "couldn't write definition file under " +
- "path(${definitionFile.absolutePath})")
+ throw BluePrintException(
+ ErrorCode.BLUEPRINT_WRITING_FAIL.value, "couldn't write definition file under " +
+ "path(${definitionFile.absolutePath})"
+ )
}
}
Files.write(typeFile.toPath(), content.toByteArray(), StandardOpenOption.CREATE_NEW)
check(typeFile.exists()) {
- throw BluePrintException(ErrorCode.BLUEPRINT_WRITING_FAIL.value, "couldn't write $type.json file under " +
- "path(${typeFile.absolutePath})")
+ throw BluePrintException(
+ ErrorCode.BLUEPRINT_WRITING_FAIL.value, "couldn't write $type.json file under " +
+ "path(${typeFile.absolutePath})"
+ )
}
}
"\nCSAR-Version: <VERSION>" +
"\nCreated-By: <AUTHOR NAME>" +
"\nEntry-Definitions: Definitions/<BLUEPRINT_NAME>.json" +
- "\nTemplate-Name: <BLUEPRINT_NAME>"+
- "\nTemplate-Tags: <BLUEPRINT_VERSION>"+
+ "\nTemplate-Name: <BLUEPRINT_NAME>" +
+ "\nTemplate-Tags: <BLUEPRINT_VERSION>" +
"\nTemplate-Tags: <TAGS>"
}
-
fun getBluePrintFile(fileName: String, targetPath: Path): File {
val filePath = targetPath.resolve(fileName).toString()
val file = File(filePath)
check(file.exists()) {
- throw BluePrintException(ErrorCode.BLUEPRINT_PATH_MISSING.value, "couldn't get definition file under " +
- "path(${file.absolutePath})")
+ throw BluePrintException(
+ ErrorCode.BLUEPRINT_PATH_MISSING.value, "couldn't get definition file under " +
+ "path(${file.absolutePath})"
+ )
}
return file
}
fun getCbaStorageDirectory(path: String): Path {
check(StringUtils.isNotBlank(path)) {
- throw BluePrintException(ErrorCode.BLUEPRINT_PATH_MISSING.value, "couldn't get " +
- "Blueprint folder under path($path)")
+ throw BluePrintException(
+ ErrorCode.BLUEPRINT_PATH_MISSING.value, "couldn't get " +
+ "Blueprint folder under path($path)"
+ )
}
val fileStorageLocation = Paths.get(path).toAbsolutePath().normalize()
}
fun compileJarFilePathName(basePath: String, artifactName: String, artifactVersion: String): String {
- return normalizedPathName(basePath, BluePrintConstants.TOSCA_SCRIPTS_KOTLIN_DIR,
- compileJarFileName(artifactName, artifactVersion))
+ return normalizedPathName(
+ basePath, BluePrintConstants.TOSCA_SCRIPTS_KOTLIN_DIR,
+ compileJarFileName(artifactName, artifactVersion)
+ )
}
fun compileJarFile(basePath: String, artifactName: String, artifactVersion: String): File {
- return normalizedFile(compileJarFilePathName(basePath,
- artifactName, artifactVersion))
+ return normalizedFile(
+ compileJarFilePathName(
+ basePath,
+ artifactName, artifactVersion
+ )
+ )
}
fun stripFileExtension(fileName: String): String {
// In case dot is in first position, we are dealing with a hidden file rather than an extension
return if (dotIndexe > 0) fileName.substring(0, dotIndexe) else fileName
}
-
}
-}
\ No newline at end of file
+}
object BluePrintIOUtils {
- suspend fun <T> retry(times: Int = 1, initialDelay: Long = 0, delay: Long = 1000,
- block: suspend (Int) -> T, exceptionBlock: (e: Exception) -> Unit): T {
+ suspend fun <T> retry(
+ times: Int = 1,
+ initialDelay: Long = 0,
+ delay: Long = 1000,
+ block: suspend (Int) -> T,
+ exceptionBlock: (e: Exception) -> Unit
+ ): T {
var currentDelay = initialDelay
val currentTimes = times - 1
repeat(currentTimes) { count ->
}
return block(currentTimes)
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.utils
-
import com.fasterxml.jackson.databind.JsonNode
import kotlinx.coroutines.runBlocking
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
import org.onap.ccsdk.cds.controllerblueprints.core.data.ToscaMetaData
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDefinitions
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.readNBLines
import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintScriptsServiceImpl
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintImportService
import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService
import org.slf4j.LoggerFactory
import java.io.File
-import java.util.*
+import java.util.Properties
class BluePrintMetadataUtils {
companion object {
private val log = LoggerFactory.getLogger(this::class.toString())
-
suspend fun toscaMetaData(basePath: String): ToscaMetaData {
val toscaMetaPath = basePath.plus(BluePrintConstants.PATH_DIVIDER)
- .plus(BluePrintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE)
+ .plus(BluePrintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE)
return toscaMetaDataFromMetaFile(toscaMetaPath)
}
suspend fun entryDefinitionFile(basePath: String): String {
val toscaMetaPath = basePath.plus(BluePrintConstants.PATH_DIVIDER)
- .plus(BluePrintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE)
+ .plus(BluePrintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE)
return toscaMetaDataFromMetaFile(toscaMetaPath).entityDefinitions
}
fun bluePrintEnvProperties(basePath: String): Properties {
val blueprintsEnvFilePath = basePath.plus(File.separator)
- .plus(BluePrintConstants.TOSCA_ENVIRONMENTS_DIR)
+ .plus(BluePrintConstants.TOSCA_ENVIRONMENTS_DIR)
return environmentFileProperties(blueprintsEnvFilePath)
}
val envDir = normalizedFile(pathName)
// Verify if the environment directory exists
if (envDir.exists() && envDir.isDirectory) {
- //Find all available environment files
+ // Find all available environment files
envDir.listFiles()!!
- .filter { it.name.endsWith(".properties") }
- .forEach {
- val istream = it.inputStream()
- properties.load(istream)
- istream.close()
- }
+ .filter { it.name.endsWith(".properties") }
+ .forEach {
+ val istream = it.inputStream()
+ properties.load(istream)
+ istream.close()
+ }
}
return properties
}
}
}
}
-
}
return toscaMetaData
}
- fun getBluePrintRuntime(id: String, blueprintBasePath: String)
- : BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+ fun getBluePrintRuntime(id: String, blueprintBasePath: String):
+ BluePrintRuntimeService<MutableMap<String, JsonNode>> {
val bluePrintContext: BluePrintContext = getBluePrintContext(blueprintBasePath)
return getBluePrintRuntime(id, bluePrintContext)
}
- fun getBluePrintRuntime(id: String, bluePrintContext: BluePrintContext)
- : BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+ fun getBluePrintRuntime(id: String, bluePrintContext: BluePrintContext):
+ BluePrintRuntimeService<MutableMap<String, JsonNode>> {
checkNotEmpty(bluePrintContext.rootPath) { "blueprint context root path is missing." }
checkNotEmpty(bluePrintContext.entryDefinition) { "blueprint context entry definition is missing." }
val blueprintBasePath = bluePrintContext.rootPath
return bluePrintRuntimeService
}
- suspend fun getBaseEnhancementBluePrintRuntime(id: String, blueprintBasePath: String)
- : BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+ suspend fun getBaseEnhancementBluePrintRuntime(id: String, blueprintBasePath: String):
+ BluePrintRuntimeService<MutableMap<String, JsonNode>> {
val bluePrintContext: BluePrintContext = getBaseEnhancementBluePrintContext(blueprintBasePath)
val bluePrintScriptsService = BluePrintScriptsServiceImpl()
val bluePrintDefinitions = bluePrintScriptsService
- .scriptInstance<BluePrintDefinitions>(normalizedBasePath, toscaMetaData.templateName!!,
- toscaMetaData.templateVersion!!, definitionClassName, false)
+ .scriptInstance<BluePrintDefinitions>(
+ normalizedBasePath, toscaMetaData.templateName!!,
+ toscaMetaData.templateVersion!!, definitionClassName, false
+ )
// Get the Service Template
val serviceTemplate = bluePrintDefinitions.serviceTemplate()
return blueprintContext
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.utils
-import org.slf4j.LoggerFactory
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.NullNode
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
+import org.slf4j.LoggerFactory
/**
*
* @author Brinda Santh
*/
object BluePrintRuntimeUtils {
- private val log= LoggerFactory.getLogger(this::class.toString())
+
+ private val log = LoggerFactory.getLogger(this::class.toString())
fun assignInputsFromFile(bluePrintContext: BluePrintContext, fileName: String, context: MutableMap<String, JsonNode>) {
val jsonNode: JsonNode = JacksonUtils.jsonNodeFromFile(fileName)
return assignInputs(bluePrintContext, jsonNode, context)
}
- fun assignInputsFromClassPathFile(bluePrintContext: BluePrintContext, fileName: String, context: MutableMap<String,
- JsonNode>) {
+ fun assignInputsFromClassPathFile(
+ bluePrintContext: BluePrintContext,
+ fileName: String,
+ context: MutableMap<String,
+ JsonNode>
+ ) {
val jsonNode = JacksonUtils.jsonNodeFromClassPathFile(fileName)
return assignInputs(bluePrintContext, jsonNode, context)
}
context[path] = valueNode
}
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.utils
-import org.slf4j.LoggerFactory
import com.fasterxml.jackson.databind.JsonNode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.commons.io.IOUtils
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.slf4j.LoggerFactory
import java.io.File
import java.nio.charset.Charset
class JacksonReactorUtils {
companion object {
- private val log= LoggerFactory.getLogger(this::class.toString())
+ private val log = LoggerFactory.getLogger(this::class.toString())
suspend fun getContent(fileName: String): String {
- //log.info("Reading File($fileName)")
+ // log.info("Reading File($fileName)")
return getContent(normalizedFile(fileName))
}
- suspend fun getContent(file: File): String = withContext(Dispatchers.IO) {
+ suspend fun getContent(file: File): String = withContext(Dispatchers.IO) {
// log.info("Reading File(${file.absolutePath})")
file.readText(Charsets.UTF_8)
}
suspend fun getClassPathFileContent(fileName: String): String = withContext(Dispatchers.IO) {
- //log.trace("Reading Classpath File($fileName)")
- IOUtils.toString(JacksonUtils::class.java.classLoader
- .getResourceAsStream(fileName), Charset.defaultCharset())
+ // log.trace("Reading Classpath File($fileName)")
+ IOUtils.toString(
+ JacksonUtils::class.java.classLoader
+ .getResourceAsStream(fileName), Charset.defaultCharset()
+ )
}
suspend fun <T> readValueFromFile(fileName: String, valueType: Class<T>): T? {
val content: String = getClassPathFileContent(fileName)
return JacksonUtils.getMapFromJson(content, valueType)
}
-
}
-}
\ No newline at end of file
+}
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.SerializationFeature
-import com.fasterxml.jackson.databind.node.*
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.BooleanNode
+import com.fasterxml.jackson.databind.node.DoubleNode
+import com.fasterxml.jackson.databind.node.FloatNode
+import com.fasterxml.jackson.databind.node.IntNode
+import com.fasterxml.jackson.databind.node.MissingNode
+import com.fasterxml.jackson.databind.node.NullNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+import com.fasterxml.jackson.databind.node.TextNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.apache.commons.io.IOUtils
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.readNBText
import java.io.File
import java.io.InputStream
import java.nio.charset.Charset
* @author Brinda Santh
*/
class JacksonUtils {
+
companion object {
val objectMapper = jacksonObjectMapper()
inline fun <reified T : Any> readValue(content: String): T =
- objectMapper.readValue(content, T::class.java)
+ objectMapper.readValue(content, T::class.java)
inline fun <reified T : Any> readValue(stream: InputStream): T =
- objectMapper.readValue(stream, T::class.java)
+ objectMapper.readValue(stream, T::class.java)
fun <T> readValue(content: String, valueType: Class<T>): T? {
return objectMapper.readValue(content, valueType)
fun getClassPathFileContent(fileName: String): String {
return runBlocking {
withContext(Dispatchers.Default) {
- IOUtils.toString(JacksonUtils::class.java.classLoader
- .getResourceAsStream(fileName), Charset.defaultCharset())
+ IOUtils.toString(
+ JacksonUtils::class.java.classLoader
+ .getResourceAsStream(fileName), Charset.defaultCharset()
+ )
}
}
}
fun <T> getInstanceFromMap(properties: MutableMap<String, JsonNode>, classType: Class<T>): T {
return readValue(getJson(properties), classType)
- ?: throw BluePrintProcessorException("failed to transform content ($properties) to type ($classType)")
+ ?: throw BluePrintProcessorException("failed to transform content ($properties) to type ($classType)")
}
fun checkJsonNodeValueOfType(type: String, jsonNode: JsonNode): Boolean {
}
fun populatePrimitiveDefaultValues(key: String, primitiveType: String, objectNode: ObjectNode) {
- val defaultValue = getDefaultValueOfPrimitiveAsJsonNode(primitiveType) ?:
- throw BluePrintException("populatePrimitiveDefaultValues expected only primitive values! Received type ($primitiveType)")
+ val defaultValue = getDefaultValueOfPrimitiveAsJsonNode(primitiveType)
+ ?: throw BluePrintException("populatePrimitiveDefaultValues expected only primitive values! Received type ($primitiveType)")
objectNode.set(key, defaultValue)
}
fun populatePrimitiveDefaultValuesForArrayNode(primitiveType: String, arrayNode: ArrayNode) {
- val defaultValue = getDefaultValueOfPrimitiveAsJsonNode(primitiveType) ?:
- throw BluePrintException("populatePrimitiveDefaultValuesForArrayNode expected only primitive values! Received type ($primitiveType)")
+ val defaultValue = getDefaultValueOfPrimitiveAsJsonNode(primitiveType)
+ ?: throw BluePrintException("populatePrimitiveDefaultValuesForArrayNode expected only primitive values! Received type ($primitiveType)")
arrayNode.add(defaultValue)
}
package org.onap.ccsdk.cds.controllerblueprints.core.utils
-
import com.fasterxml.jackson.databind.JsonNode
import com.jayway.jsonpath.Configuration
import com.jayway.jsonpath.JsonPath
class JsonParserUtils {
companion object {
- //TODO("Optimise this")
+ // TODO("Optimise this")
val JACKSON_JSON_NODE_CONFIGURATION = Configuration.builder()
- .mappingProvider(JacksonMappingProvider()).jsonProvider(JacksonJsonNodeJsonProvider()).build()
+ .mappingProvider(JacksonMappingProvider()).jsonProvider(JacksonJsonNodeJsonProvider()).build()
val PATH_CONFIGURATION = Configuration.builder().options(Option.AS_PATH_LIST).build()
return parseNSet(jsonNode.asJsonString(), expression, valueNode)
}
}
-}
\ No newline at end of file
+}
* @author Brinda Santh
*/
object ResourceResolverUtils {
- private val log= LoggerFactory.getLogger(this::class.toString())
+
+ private val log = LoggerFactory.getLogger(this::class.toString())
fun getFileContent(filename: String, basePath: String?): String {
log.trace("file ({}), basePath ({}) ", filename, basePath)
try {
var resolvedFileName: String = filename
- if (filename.startsWith("http", true)
- || filename.startsWith("https", true)) {
+ if (filename.startsWith("http", true) ||
+ filename.startsWith("https", true)
+ ) {
val givenUrl: String = URL(filename).toString()
val systemUrl: String = File(".").toURI().toURL().toString()
log.trace("givenUrl ({}), systemUrl ({}) ", givenUrl, systemUrl)
if (givenUrl.startsWith(systemUrl)) {
-
}
} else {
if (!filename.startsWith("/")) {
}
}
}
- //FIXME("Convert into reactive")
+ // FIXME("Convert into reactive")
return JacksonUtils.getContent(resolvedFileName)
} catch (e: Exception) {
throw BluePrintException(e, "failed to file (%s), basePath (%s) ", filename, basePath)
}
}
-}
\ No newline at end of file
+}
toMerge.topologyTemplate?.inputs?.let {
parentServiceTemplate.topologyTemplate?.inputs = parentServiceTemplate.topologyTemplate?.inputs
- ?: hashMapOf()
+ ?: hashMapOf()
parentServiceTemplate.topologyTemplate?.inputs?.putAll(parentServiceTemplate.topologyTemplate?.inputs as MutableMap)
}
toMerge.topologyTemplate?.nodeTemplates?.let {
parentServiceTemplate.topologyTemplate?.nodeTemplates = parentServiceTemplate.topologyTemplate?.nodeTemplates
- ?: hashMapOf()
+ ?: hashMapOf()
parentServiceTemplate.topologyTemplate?.nodeTemplates?.putAll(parentServiceTemplate.topologyTemplate?.nodeTemplates as MutableMap)
}
toMerge.topologyTemplate?.relationshipTemplates?.let {
parentServiceTemplate.topologyTemplate?.relationshipTemplates = parentServiceTemplate.topologyTemplate?.relationshipTemplates
- ?: hashMapOf()
+ ?: hashMapOf()
parentServiceTemplate.topologyTemplate?.relationshipTemplates?.putAll(parentServiceTemplate.topologyTemplate?.relationshipTemplates as MutableMap)
}
toMerge.topologyTemplate?.policies?.let {
parentServiceTemplate.topologyTemplate?.policies = parentServiceTemplate.topologyTemplate?.policies
- ?: hashMapOf()
+ ?: hashMapOf()
parentServiceTemplate.topologyTemplate?.policies?.putAll(parentServiceTemplate.topologyTemplate?.policies as MutableMap)
}
toMerge.topologyTemplate?.workflows?.let {
parentServiceTemplate.topologyTemplate?.workflows = parentServiceTemplate.topologyTemplate?.workflows
- ?: hashMapOf()
+ ?: hashMapOf()
parentServiceTemplate.topologyTemplate?.workflows?.putAll(parentServiceTemplate.topologyTemplate?.workflows as MutableMap)
}
return parentServiceTemplate
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.utils
-import java.util.*
+import java.util.ArrayList
+import java.util.HashMap
+import java.util.LinkedList
+import java.util.Stack
/**
*
return result
}
-
fun inDegree(): MutableMap<V, Int> {
val result = HashMap<V, Int>()
for (v in neighbors.keys)
- result[v] = 0 // All in-degrees are 0
+ result[v] = 0 // All in-degrees are 0
for (from in neighbors.keys) {
for (to in neighbors[from]!!) {
- result[to] = result[to]!! + 1 // Increment in-degree
+ result[to] = result[to]!! + 1 // Increment in-degree
}
}
return result
fun topSort(): List<V>? {
val degree = inDegree()
// Determine all vertices with zero in-degree
- val zeroVerts = Stack<V>() // Stack as good as any here
+ val zeroVerts = Stack<V>() // Stack as good as any here
for (v in degree.keys) {
if (degree[v] == 0) zeroVerts.push(v)
}
// Determine the topological order
val result = ArrayList<V>()
while (!zeroVerts.isEmpty()) {
- val v = zeroVerts.pop() // Choose a vertex with zero in-degree
- result.add(v) // Vertex v is next in topol order
+ val v = zeroVerts.pop() // Choose a vertex with zero in-degree
+ result.add(v) // Vertex v is next in topol order
// "Remove" vertex v by updating its neighbors
for (neighbor in neighbors[v]!!) {
degree[neighbor] = degree[neighbor]!! - 1
return if (result.size != neighbors.size) null else result
}
-
fun bfsDistance(start: V): Map<*, *> {
val distance: MutableMap<V, Int> = hashMapOf()
// Initially, all distance are infinity, except start node
distance[start] = 0
// Process nodes in queue order
val queue = LinkedList<V>()
- queue.offer(start) // Place start node in queue
+ queue.offer(start) // Place start node in queue
while (!queue.isEmpty()) {
val v = queue.remove()
val vDist = distance[v]!!
// Update neighbors
for (neighbor in neighbors[v]!!) {
- if (distance[neighbor] != null) continue // Ignore if already done
+ if (distance[neighbor] != null) continue // Ignore if already done
distance[neighbor] = vDist + 1
queue.offer(neighbor)
}
}
return distance
}
-}
\ No newline at end of file
+}
}
return graph
}
-}
\ No newline at end of file
+}
assertEquals("error", bluePrintError.errors[0])
}
-}
\ No newline at end of file
+}
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
-import com.fasterxml.jackson.databind.node.*
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.BooleanNode
+import com.fasterxml.jackson.databind.node.IntNode
+import com.fasterxml.jackson.databind.node.JsonNodeType
+import com.fasterxml.jackson.databind.node.MissingNode
+import com.fasterxml.jackson.databind.node.NullNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+import com.fasterxml.jackson.databind.node.TextNode
import org.junit.Test
-import kotlin.test.*
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
/**
*
* @author Brinda Santh
*/
class CustomFunctionsTest {
+
@Test
fun testFormat() {
- val returnValue : String = format("This is {} for times {}", "test", 2)
+ val returnValue: String = format("This is {} for times {}", "test", 2)
assertEquals("This is test for times 2", returnValue, "Failed to format String")
- val returnValue1 : String = format("This is test for times 2")
+ val returnValue1: String = format("This is test for times 2")
assertEquals("This is test for times 2", returnValue1, "Failed to format empty args")
}
@Test(expected = BluePrintException::class)
fun testCheckEquals() {
- assertTrue(checkEquals("hello", "hello", { -> "error"}))
+ assertTrue(checkEquals("hello", "hello", { -> "error" }))
- checkEquals("hello", "test", { -> "error"})
+ checkEquals("hello", "test", { -> "error" })
}
@Test(expected = IllegalStateException::class)
fun testCheckNotEmpty() {
- assertEquals("hello", checkNotEmpty("hello", { -> "error"}))
+ assertEquals("hello", checkNotEmpty("hello", { -> "error" }))
- checkNotEmpty("", { -> "error"})
+ checkNotEmpty("", { -> "error" })
}
@Test(expected = IllegalStateException::class)
fun testCheckNotBlank() {
- assertEquals("hello", checkNotBlank("hello", { -> "error"}))
+ assertEquals("hello", checkNotBlank("hello", { -> "error" }))
- checkNotBlank(" ", { -> "error"})
+ checkNotBlank(" ", { -> "error" })
}
@Test
assertEquals("hello", nullToEmpty("hello"))
}
-}
\ No newline at end of file
+}
blueprintFile.compress(targetZip)
assertTrue(blueprintFile.exists(), "failed to create compressed file(${targetZip.absolutePath} ")
}
-
-}
\ No newline at end of file
+}
assertEquals(null, MDC.get(BluePrintConstants.ONAP_REQUEST_ID))
}
launch(MDCContext()) {
- assertEquals("12345", MDC.get(BluePrintConstants.ONAP_REQUEST_ID),
- "couldn't get request id")
+ assertEquals(
+ "12345", MDC.get(BluePrintConstants.ONAP_REQUEST_ID),
+ "couldn't get request id"
+ )
MDC.put("client_id", "client-1")
assertEquals("client-1", MDC.get("client_id"), "couldn't get client id")
}
}
}
-}
\ No newline at end of file
+}
@Test
fun testBluePrintWorkflowData() {
val wfInput = TestBluePrintsWorkflowInput::class.asPropertyDefinitionMap()
- //println(wfInput.asJsonString(true))
+ // println(wfInput.asJsonString(true))
assertNotNull(wfInput, "failed to generate wfInput property map")
val wfOutput = TestBluePrintsWorkflowOutput::class.asPropertyDefinitionMap()
- //println(wfOutput.asJsonString(true))
+ // println(wfOutput.asJsonString(true))
assertNotNull(wfInput, "failed to generate wfOutput property map")
}
@Test
fun testBluePrintDataType() {
val dataTypes = TestBluePrintsDataType::class.asBluePrintsDataTypes()
- //println(dataTypes.asJsonString(true))
+ // println(dataTypes.asJsonString(true))
assertNotNull(dataTypes, "failed to generate dataTypes definition")
}
}
-@BluePrintsDataType(name = "dt-test-datatype", description = "I am test",
- version = "1.0.0", derivedFrom = "tosca.datatypes.root")
+@BluePrintsDataType(
+ name = "dt-test-datatype", description = "I am test",
+ version = "1.0.0", derivedFrom = "tosca.datatypes.root"
+)
data class TestBluePrintsDataType(
- @BluePrintsProperty(description = "this stringData")
- var stringData: String,
- @BluePrintsProperty(description = "this stringDataWithValue")
- @PropertyDefaultValue(value = "USA")
- val stringDataWithValue: String,
- @BluePrintsProperty(description = "this intDataWithValue")
- @PropertyDefaultValue(value = "30")
- val intDataWithValue: Int,
- @BluePrintsProperty(description = "this booleanDataWithValue")
- @PropertyDefaultValue(value = "true")
- val booleanDataWithValue: Boolean,
- @BluePrintsProperty(description = "this anyData")
- val anyData: Any,
- @BluePrintsProperty(description = "this jsonDataWithValue")
- @PropertyDefaultValue(value = """{"data" : "1234"}""")
- val jsonDataWithValue: JsonNode?,
- @BluePrintsProperty(description = "listData")
- val listData: MutableList<String>,
- @BluePrintsProperty(description = "this mapData")
- val mapData: MutableMap<String, String> = hashMapOf(),
- @BluePrintsProperty(description = "this complexData")
- val complexData: TestBluePrintsChildDataType?,
- @BluePrintsProperty(description = "this complexDataList")
- val complexDataList: MutableList<TestBluePrintsChildDataType>
+ @BluePrintsProperty(description = "this stringData")
+ var stringData: String,
+ @BluePrintsProperty(description = "this stringDataWithValue")
+ @PropertyDefaultValue(value = "USA")
+ val stringDataWithValue: String,
+ @BluePrintsProperty(description = "this intDataWithValue")
+ @PropertyDefaultValue(value = "30")
+ val intDataWithValue: Int,
+ @BluePrintsProperty(description = "this booleanDataWithValue")
+ @PropertyDefaultValue(value = "true")
+ val booleanDataWithValue: Boolean,
+ @BluePrintsProperty(description = "this anyData")
+ val anyData: Any,
+ @BluePrintsProperty(description = "this jsonDataWithValue")
+ @PropertyDefaultValue(value = """{"data" : "1234"}""")
+ val jsonDataWithValue: JsonNode?,
+ @BluePrintsProperty(description = "listData")
+ val listData: MutableList<String>,
+ @BluePrintsProperty(description = "this mapData")
+ val mapData: MutableMap<String, String> = hashMapOf(),
+ @BluePrintsProperty(description = "this complexData")
+ val complexData: TestBluePrintsChildDataType?,
+ @BluePrintsProperty(description = "this complexDataList")
+ val complexDataList: MutableList<TestBluePrintsChildDataType>
)
data class TestBluePrintsChildDataType(val name: String)
-
@BluePrintsWorkflowInput
data class TestBluePrintsWorkflowInput(
- @BluePrintsProperty(description = "this sample name")
- @PropertyDefaultValue(value = "Brinda")
- var name: String,
- @BluePrintsProperty(description = "this sample name")
- val place: String
+ @BluePrintsProperty(description = "this sample name")
+ @PropertyDefaultValue(value = "Brinda")
+ var name: String,
+ @BluePrintsProperty(description = "this sample name")
+ val place: String
)
@BluePrintsWorkflowOutput
data class TestBluePrintsWorkflowOutput(
- @BluePrintsProperty(description = "this is dslExpression")
- @DSLExpression("field1")
- var dslExpression: String,
-
- @BluePrintsProperty(description = "this is withNodeAttributeExpression")
- @AttributeExpression(modelableEntityName = "sample-node", attributeName = "response-data")
- var withNodeAttributeExpression: String,
-
- @BluePrintsProperty(description = "this is withNodeAttributeExpressionSubAttribute")
- @AttributeExpression(modelableEntityName = "sample-node", attributeName = "response-data",
- subAttributeName = ".\$field1")
- var withNodeAttributeExpressionSubAttribute: String,
-
- @BluePrintsProperty(description = "this is withAttributeExpressionSubAttribute")
- @AttributeExpression(attributeName = "response-data", subAttributeName = ".\$field1")
- var withAttributeExpressionSubAttribute: String,
-
- @BluePrintsProperty(description = "this is withAttributeExpression")
- @AttributeExpression(attributeName = "response-data")
- var withAttributeExpression: String,
-
- @BluePrintsProperty(description = "this is withAArtifactExpression")
- @ArtifactExpression(modelableEntityName = "test-node", artifactName = "content-template")
- var withAArtifactExpression: String,
-
- @BluePrintsProperty(description = "this status")
- val status: String = "success"
-)
\ No newline at end of file
+ @BluePrintsProperty(description = "this is dslExpression")
+ @DSLExpression("field1")
+ var dslExpression: String,
+
+ @BluePrintsProperty(description = "this is withNodeAttributeExpression")
+ @AttributeExpression(modelableEntityName = "sample-node", attributeName = "response-data")
+ var withNodeAttributeExpression: String,
+
+ @BluePrintsProperty(description = "this is withNodeAttributeExpressionSubAttribute")
+ @AttributeExpression(
+ modelableEntityName = "sample-node", attributeName = "response-data",
+ subAttributeName = ".\$field1"
+ )
+ var withNodeAttributeExpressionSubAttribute: String,
+
+ @BluePrintsProperty(description = "this is withAttributeExpressionSubAttribute")
+ @AttributeExpression(attributeName = "response-data", subAttributeName = ".\$field1")
+ var withAttributeExpressionSubAttribute: String,
+
+ @BluePrintsProperty(description = "this is withAttributeExpression")
+ @AttributeExpression(attributeName = "response-data")
+ var withAttributeExpression: String,
+
+ @BluePrintsProperty(description = "this is withAArtifactExpression")
+ @ArtifactExpression(modelableEntityName = "test-node", artifactName = "content-template")
+ var withAArtifactExpression: String,
+
+ @BluePrintsProperty(description = "this status")
+ val status: String = "success"
+)
@Test
fun testOperationDSLWorkflow() {
- val blueprint = blueprint("sample-bp", "1.0.0",
- "brindasanth@onap.com", "sample, blueprints") {
+ val blueprint = blueprint(
+ "sample-bp", "1.0.0",
+ "brindasanth@onap.com", "sample, blueprints"
+ ) {
artifactType(BluePrintTypes.artifactTypeTemplateVelocity())
// For New Component Definition
- component("resource-resolution", "component-script-executor", "1.0.0",
- "Resource Resolution component.") {
+ component(
+ "resource-resolution", "component-script-executor", "1.0.0",
+ "Resource Resolution component."
+ ) {
implementation(180)
// Attributes ( Properties which will be set during execution)
attribute("template1-data", "string", true, "")
}
// Already definitions Registered Components
- registryComponent("activate-restconf", "component-resource-resolution", "1.0.0",
- "RestconfExecutor", "Resource Resolution component.") {
+ registryComponent(
+ "activate-restconf", "component-resource-resolution", "1.0.0",
+ "RestconfExecutor", "Resource Resolution component."
+ ) {
implementation(180)
// Properties
property("string-value1", "data")
output("self-attribute-expression", getAttribute("template1-data"))
// Artifacts
artifact("template2", "artifact-template-velocity", "Templates/template1.vtl")
-
}
workflow("resource-resolution-process", "Resource Resolution wf") {
}
assertNotNull(blueprint.components, "failed to get components")
assertNotNull(blueprint.workflows, "failed to get workflows")
- //println(blueprint.asJsonString(true))
+ // println(blueprint.asJsonString(true))
val serviceTemplateGenerator = BluePrintServiceTemplateGenerator(blueprint)
val serviceTemplate = serviceTemplateGenerator.serviceTemplate()
assertNotNull(serviceTemplate.topologyTemplate, "failed to get service topology template")
- //println(serviceTemplate.asJsonString(true))
+ // println(serviceTemplate.asJsonString(true))
}
@Test
fun testServiceTemplate() {
- val serviceTemplate = serviceTemplate("sample-bp", "1.0.0",
- "brindasanth@onap.com", "sample, blueprints") {
+ val serviceTemplate = serviceTemplate(
+ "sample-bp", "1.0.0",
+ "brindasanth@onap.com", "sample, blueprints"
+ ) {
metadata("release", "1806")
import("Definition/data_types.json")
dsl("rest-endpoint", """{ "selector" : "odl-selector"}""")
dsl("db-endpoint", """{ "selector" : "db-selector"}""")
topologyTemplate {
- nodeTemplateOperation(nodeTemplateName = "activate", type = "sample-node-type", interfaceName = "RestconfExecutor",
- description = "sample activation") {
+ nodeTemplateOperation(
+ nodeTemplateName = "activate", type = "sample-node-type", interfaceName = "RestconfExecutor",
+ description = "sample activation"
+ ) {
implementation(360, "SELF") {
primary("Scripts/sample.py")
dependencies("one", "two")
assertNotNull(serviceTemplate.topologyTemplate, "failed to get topology template")
assertNotNull(serviceTemplate.topologyTemplate?.nodeTemplates, "failed to get nodeTypes")
assertNotNull(serviceTemplate.topologyTemplate?.nodeTemplates!!["activate"], "failed to get nodeTypes(activate)")
- //println(serviceTemplate.asJsonString(true))
+ // println(serviceTemplate.asJsonString(true))
}
@Test
maxLength(20)
minLength(10)
}
-
}
property("disk-space", "string", true, "") {
defaultValue(10)
@Test
fun testServiceTemplateWorkflow() {
- val serviceTemplate = serviceTemplate("sample-bp", "1.0.0",
- "brindasanth@onap.com", "sample, blueprints") {
+ val serviceTemplate = serviceTemplate(
+ "sample-bp", "1.0.0",
+ "brindasanth@onap.com", "sample, blueprints"
+ ) {
topologyTemplate {
workflowNodeTemplate("activate", "component-resource-resolution", "") {
operation("ResourceResolutionExecutor", "") {
}
assertNotNull(serviceTemplate.topologyTemplate, "failed to get topology template")
assertNotNull(serviceTemplate.topologyTemplate?.workflows?.get("activate"), "failed to get workflow(activate)")
- //println(serviceTemplate.asJsonString(true))
+ // println(serviceTemplate.asJsonString(true))
}
@Test
fun testNodeTemplateOperationTypes() {
- val testNodeTemplateInstance = BluePrintTypes.nodeTemplateComponentTestExecutor(id = "test-node-template",
- description = "") {
+ val testNodeTemplateInstance = BluePrintTypes.nodeTemplateComponentTestExecutor(
+ id = "test-node-template",
+ description = ""
+ ) {
definedProperties {
prop1("i am property1")
prop2("i am property2")
}
}
assertNotNull(testNodeTemplateInstance, "failed to get test node template")
- //println(testNodeTemplateInstance.asJsonString(true))
+ // println(testNodeTemplateInstance.asJsonString(true))
}
}
-fun BluePrintTypes.nodeTemplateComponentTestExecutor(id: String,
- description: String,
- block: TestNodeTemplateOperationImplBuilder.() -> Unit)
- : NodeTemplate {
+fun BluePrintTypes.nodeTemplateComponentTestExecutor(
+ id: String,
+ description: String,
+ block: TestNodeTemplateOperationImplBuilder.() -> Unit
+):
+ NodeTemplate {
return TestNodeTemplateOperationImplBuilder(id, description).apply(block).build()
}
class TestNodeTemplateOperationImplBuilder(id: String, description: String) :
- AbstractNodeTemplateOperationImplBuilder<TestProperty, TestInput, TestOutput>(id, "component-test-executor",
- "ComponentTestExecutor",
- description)
+ AbstractNodeTemplateOperationImplBuilder<TestProperty, TestInput, TestOutput>(
+ id, "component-test-executor",
+ "ComponentTestExecutor",
+ description
+ )
class TestProperty : PropertiesAssignmentBuilder() {
fun prop1(prop1: String) {
package org.onap.ccsdk.cds.controllerblueprints.core.scripts
-
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
private fun viewClassPathInfo() {
println(" *********** classpathFromClass *********** ")
- classpathFromClass(BluePrintScriptsServiceImplTest::class.java.classLoader,
- BluePrintScriptsServiceImplTest::class)!!
- .forEach(::println)
+ classpathFromClass(
+ BluePrintScriptsServiceImplTest::class.java.classLoader,
+ BluePrintScriptsServiceImplTest::class
+ )!!
+ .forEach(::println)
println(" *********** classpathFromClassloader *********** ")
classpathFromClassloader(BluePrintScriptsServiceImplTest::class.java.classLoader)!!
- .forEach(::println)
+ .forEach(::println)
println(" *********** classpathFromClasspathProperty *********** ")
classpathFromClasspathProperty()!!
- .forEach(::println)
+ .forEach(::println)
}
@Test
val basePath = normalizedPathName("src/test/resources/compile")
/** Load the Definitions */
val bluePrintDefinitions = bluePrintScriptsService
- .scriptInstance<BluePrintDefinitions>(basePath,
- "cba.scripts.ActivateBlueprintDefinitions", true)
+ .scriptInstance<BluePrintDefinitions>(
+ basePath,
+ "cba.scripts.ActivateBlueprintDefinitions", true
+ )
assertNotNull(bluePrintDefinitions, "failed to get blueprint definitions")
val serviceTemplate = bluePrintDefinitions.serviceTemplate()
assertNotNull(customDataType, "failed to get custom definitions")
val instance = bluePrintScriptsService
- .scriptInstance<BlueprintFunctionNode<String, String>>(basePath,
- "cba.scripts.SampleBlueprintFunctionNode", false)
+ .scriptInstance<BlueprintFunctionNode<String, String>>(
+ basePath,
+ "cba.scripts.SampleBlueprintFunctionNode", false
+ )
assertNotNull(instance, "failed to get compiled instance")
val cachedInstance = bluePrintScriptsService
- .scriptInstance<BlueprintFunctionNode<String, String>>(basePath,
- "cba.scripts.SampleBlueprintFunctionNode", false)
+ .scriptInstance<BlueprintFunctionNode<String, String>>(
+ basePath,
+ "cba.scripts.SampleBlueprintFunctionNode", false
+ )
assertNotNull(cachedInstance, "failed to get cached compile instance")
}
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.service
-
import com.fasterxml.jackson.databind.ObjectMapper
-import org.slf4j.LoggerFactory
import org.junit.Test
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Activity
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Step
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import org.slf4j.LoggerFactory
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
*/
class BluePrintContextTest {
- private val log= LoggerFactory.getLogger(this::class.toString())
+ private val log = LoggerFactory.getLogger(this::class.toString())
val blueprintBasePath: String = ("./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
* @author Brinda Santh
*/
class BluePrintExpressionServiceTest {
+
@Test
fun testInputExpression() {
val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_input\" : \"input-name\" }")
assertNotNull(expressionData1.propertyExpression, " Failed to populate nested property expression data")
assertEquals("SELF", expressionData1.propertyExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
assertEquals("property-name", expressionData1.propertyExpression?.propertyName, " Failed to get expected propertyName")
- assertEquals("resource/name", expressionData1.propertyExpression?.subPropertyName, " Failed to populate nested subPropertyName expression data")
+ assertEquals(
+ "resource/name",
+ expressionData1.propertyExpression?.subPropertyName,
+ " Failed to populate nested subPropertyName expression data"
+ )
}
@Test
assertNotNull(expressionData1.attributeExpression, " Failed to populate attribute expression data")
assertEquals("SELF", expressionData1.attributeExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
assertEquals("attribute-name", expressionData1.attributeExpression?.attributeName, " Failed to get expected attributeName")
- assertEquals("resource/name", expressionData1.attributeExpression?.subAttributeName, " Failed to populate nested subAttributeName expression data")
+ assertEquals(
+ "resource/name",
+ expressionData1.attributeExpression?.subAttributeName,
+ " Failed to populate nested subAttributeName expression data"
+ )
}
-
@Test
fun testOutputOperationExpression() {
- val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_operation_output\": [\"SELF\", \"interface-name\", \"operation-name\", \"output-property-name\"] }")
+ val node: JsonNode =
+ jacksonObjectMapper().readTree("{ \"get_operation_output\": [\"SELF\", \"interface-name\", \"operation-name\", \"output-property-name\"] }")
val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node)
assertNotNull(expressionData, " Failed to populate expression data")
assertEquals(expressionData.isExpression, true, "Failed to identify as expression")
assertEquals("output-property-name", expressionData.operationOutputExpression?.propertyName, " Failed to get expected propertyName")
}
-
@Test
fun testArtifactExpression() {
val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_artifact\" : [\"SELF\", \"artifact-template\"] }")
assertEquals("SELF", expressionData.artifactExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
assertEquals("artifact-template", expressionData.artifactExpression?.artifactName, " Failed to get expected artifactName")
-
val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_artifact\" : [\"SELF\", \"artifact-template\", \"location\", true] }")
val expressionData1: ExpressionData = BluePrintExpressionService.getExpressionData(node1)
assertNotNull(expressionData1, " Failed to populate expression data")
assertNotNull(expressionData, " Failed to populate expression data")
assertEquals(expressionData.isExpression, true, "Failed to identify as expression")
assertNotNull(expressionData.dslExpression, " Failed to populate dsl expression data")
- assertEquals("dynamic-rest-source", expressionData.dslExpression!!.propertyName,
- " Failed to populate dsl property name")
+ assertEquals(
+ "dynamic-rest-source", expressionData.dslExpression!!.propertyName,
+ " Failed to populate dsl property name"
+ )
}
-}
\ No newline at end of file
+}
val dataType = bluePrintRepoFileService.getDataType("dt-not-found")
assertNotNull(dataType, "Failed to get DataType from repo")
}
-}
\ No newline at end of file
+}
import org.junit.Test
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
-import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintRuntimeUtils
* @author Brinda Santh
*/
class BluePrintRuntimeServiceTest {
+
private val log = LoggerFactory.getLogger(this::class.toString())
@Test
bluePrintRuntimeService.assignInputs(inputNode)
val propContext: MutableMap<String, JsonNode> = bluePrintRuntimeService
- .resolveNodeTemplateProperties("activate-process")
+ .resolveNodeTemplateProperties("activate-process")
assertNotNull(propContext, "Failed to populate interface property values")
}
val executionContext = bluePrintRuntimeService.getExecutionContext()
- BluePrintRuntimeUtils.assignInputsFromClassPathFile(bluePrintRuntimeService.bluePrintContext(),
- "data/default-context.json", executionContext)
+ BluePrintRuntimeUtils.assignInputsFromClassPathFile(
+ bluePrintRuntimeService.bluePrintContext(),
+ "data/default-context.json", executionContext
+ )
val assignmentParams = "{\n" +
" \"ipAddress\": \"127.0.0.1\",\n" +
" \"hostName\": \"vnf-host\"\n" +
" }"
- bluePrintRuntimeService.setNodeTemplateAttributeValue("resource-assignment", "assignment-params",
- JacksonUtils.jsonNode(assignmentParams))
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ "resource-assignment", "assignment-params",
+ JacksonUtils.jsonNode(assignmentParams)
+ )
- val capProperties = bluePrintRuntimeService.resolveNodeTemplateCapabilityProperties("sample-netconf-device",
- "netconf")
+ val capProperties = bluePrintRuntimeService.resolveNodeTemplateCapabilityProperties(
+ "sample-netconf-device",
+ "netconf"
+ )
assertNotNull(capProperties, "Failed to populate capability property values")
assertEquals(capProperties["target-ip-address"], "127.0.0.1".asJsonPrimitive(), "Failed to populate parameter target-ip-address")
assertEquals(capProperties["port-number"], JacksonUtils.jsonNodeFromObject(830), "Failed to populate parameter port-number")
val executionContext = bluePrintRuntimeService.getExecutionContext()
- BluePrintRuntimeUtils.assignInputsFromClassPathFile(bluePrintRuntimeService.bluePrintContext(),
- "data/default-context.json", executionContext)
+ BluePrintRuntimeUtils.assignInputsFromClassPathFile(
+ bluePrintRuntimeService.bluePrintContext(),
+ "data/default-context.json", executionContext
+ )
val inContext: MutableMap<String, JsonNode> = bluePrintRuntimeService
- .resolveNodeTemplateInterfaceOperationInputs("resource-assignment",
- "ResourceResolutionComponent", "process")
+ .resolveNodeTemplateInterfaceOperationInputs(
+ "resource-assignment",
+ "ResourceResolutionComponent", "process"
+ )
assertNotNull(inContext, "Failed to populate interface input property values")
assertEquals(inContext["action-name"], JacksonUtils.jsonNodeFromObject("sample-action"), "Failed to populate parameter action-name")
bluePrintRuntimeService.setNodeTemplateAttributeValue("resource-assignment", "assignment-params", NullNode.getInstance())
- bluePrintRuntimeService.resolveNodeTemplateInterfaceOperationOutputs("resource-assignment",
- "ResourceResolutionComponent", "process")
+ bluePrintRuntimeService.resolveNodeTemplateInterfaceOperationOutputs(
+ "resource-assignment",
+ "ResourceResolutionComponent", "process"
+ )
- val outputStatus = bluePrintRuntimeService.getNodeTemplateOperationOutputValue("resource-assignment",
- "ResourceResolutionComponent", "process", "status")
+ val outputStatus = bluePrintRuntimeService.getNodeTemplateOperationOutputValue(
+ "resource-assignment",
+ "ResourceResolutionComponent", "process", "status"
+ )
assertEquals("success".asJsonPrimitive(), outputStatus, "Failed to get operation property status")
- val outputParams = bluePrintRuntimeService.getNodeTemplateOperationOutputValue("resource-assignment",
- "ResourceResolutionComponent", "process", "resource-assignment-params")
+ val outputParams = bluePrintRuntimeService.getNodeTemplateOperationOutputValue(
+ "resource-assignment",
+ "ResourceResolutionComponent", "process", "resource-assignment-params"
+ )
assertEquals(NullNode.getInstance(), outputParams, "Failed to get operation property resource-assignment-params")
-
}
@Test
log.info("************************ testNodeTemplateContextProperty **********************")
val bluePrintRuntimeService = getBluePrintRuntimeService()
- bluePrintRuntimeService.setNodeTemplateAttributeValue("resource-assignment-ra-component", "context1",
- JacksonUtils.jsonNodeFromObject("context1-value"))
- bluePrintRuntimeService.setNodeTemplateAttributeValue("resource-assignment-ra-component", "context2",
- JacksonUtils.jsonNodeFromObject("context2-value"))
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ "resource-assignment-ra-component", "context1",
+ JacksonUtils.jsonNodeFromObject("context1-value")
+ )
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ "resource-assignment-ra-component", "context2",
+ JacksonUtils.jsonNodeFromObject("context2-value")
+ )
val keys = listOf("context1", "context2")
val jsonValueNode = bluePrintRuntimeService.getJsonForNodeTemplateAttributeProperties("resource-assignment-ra-component", keys)
assertNotNull(jsonValueNode, "Failed to get Json for Node Template Context Properties")
log.info("JSON Prepared Value Context {}", jsonValueNode)
-
}
@Test
val assignmentParams = "{\"ipAddress\": \"127.0.0.1\", \"hostName\": \"vnf-host\"}"
- bluePrintRuntimeService.setNodeTemplateAttributeValue("resource-assignment", "assignment-params",
- JacksonUtils.jsonNode(assignmentParams))
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ "resource-assignment", "assignment-params",
+ JacksonUtils.jsonNode(assignmentParams)
+ )
val resolvedJsonNode = bluePrintRuntimeService.resolveWorkflowOutputs("resource-assignment")
assertNotNull(resolvedJsonNode, "Failed to populate workflow output property values")
val checkProcessId = blueprintRuntime.get(BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID)
val checkBasePath = blueprintRuntime.get(BluePrintConstants.PROPERTY_BLUEPRINT_BASE_PATH)
- assertEquals("1234".asJsonPrimitive(),
- checkProcessId, "Failed to get process id after runtime creation")
- assertEquals(blueprintBasePath.asJsonPrimitive(),
- checkBasePath, "Failed to get base path after runtime creation")
+ assertEquals(
+ "1234".asJsonPrimitive(),
+ checkProcessId, "Failed to get process id after runtime creation"
+ )
+ assertEquals(
+ blueprintBasePath.asJsonPrimitive(),
+ checkBasePath, "Failed to get base path after runtime creation"
+ )
return blueprintRuntime
}
-
-}
\ No newline at end of file
+}
val content = BluePrintVelocityTemplateService.generateContent(template, json)
assertNotNull(content, "failed to generate content for velocity template")
}
-
}
@Test
val json = JacksonUtils.getClassPathFileContent("templates/base-config-data-jinja.json")
val element: MutableMap<String, Any> = mutableMapOf()
- element["additional_array"] = arrayListOf(hashMapOf("name" to "Element1", "location" to "Region0"),
- hashMapOf("name" to "Element2", "location" to "Region1"))
+ element["additional_array"] = arrayListOf(
+ hashMapOf("name" to "Element1", "location" to "Region0"),
+ hashMapOf("name" to "Element2", "location" to "Region1")
+ )
val content = BluePrintJinjaTemplateService.generateContent(template, json, false, element)
assertNotNull(content, "failed to generate content for velocity template")
}
-
}
-
@Test
fun `no value variable should evaluate to default value - standalone template mesh test`() {
runBlocking {
val json = JacksonUtils.getClassPathFileContent("templates/default-variable-value-data.json")
val content = BluePrintVelocityTemplateService.generateContent(template, json)
- //first line represents a variable whose value was successfully retrieved, second line contains a variable
+ // first line represents a variable whose value was successfully retrieved, second line contains a variable
// whose value could not be evaluated
val expected = "sample-hostname\n\${node0_backup_router_address}"
assertEquals(expected, content, "No value variable should use default value")
}
}
-
}
-
import io.mockk.every
import io.mockk.mockk
-import kotlinx.coroutines.*
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
import org.junit.Test
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
fun testSimpleFlow() {
runBlocking {
val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>E/SUCCESS, E>END/SUCCESS]"
- .toGraph()
+ .toGraph()
val simpleWorkflow = TestBluePrintWorkFlowService()
simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D", "E"), null)
val input = "123456"
val wfs = listOf("12345", "12346").map {
async {
val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]"
- .toGraph()
+ .toGraph()
val simpleWorkflow = TestBluePrintWorkFlowService()
simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D"), null)
val response = simpleWorkflow.executeWorkflow(graph, mockBluePrintRuntimeService(it), it)
fun testMissingEdgeForBFailureState() {
runBlocking {
val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]"
- .toGraph()
+ .toGraph()
val simpleWorkflow = TestBluePrintWorkFlowService()
simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "C", "D", "E"), arrayListOf("B"))
val input = "123456"
fun testBExceptionFlow() {
runBlocking {
val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]"
- .toGraph()
+ .toGraph()
val simpleWorkflow = TestBluePrintWorkFlowService()
simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "C", "D", "E"), null)
val input = "123456"
fun testTimeoutExceptionFlow() {
runBlocking {
val graph = "[START>A/SUCCESS, A>TO/SUCCESS, TO>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]"
- .toGraph()
+ .toGraph()
val simpleWorkflow = TestBluePrintWorkFlowService()
simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "TO", "C", "D", "E"), null)
val input = "123456"
fun testConditionalFlow() {
runBlocking {
val graph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/FAILURE, B>D/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]"
- .toGraph()
+ .toGraph()
val simpleWorkflow = TestBluePrintWorkFlowService()
simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D", "E"), null)
val input = "123456"
runBlocking {
// Failure Flow
val failurePatGraph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/FAILURE, B>D/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]"
- .toGraph()
+ .toGraph()
val failurePathWorkflow = TestBluePrintWorkFlowService()
- failurePathWorkflow.simulatedState = prepareSimulation(arrayListOf("B", "C", "D", "E"),
- arrayListOf("A"))
+ failurePathWorkflow.simulatedState = prepareSimulation(
+ arrayListOf("B", "C", "D", "E"),
+ arrayListOf("A")
+ )
val failurePathWorkflowInput = "123456"
val failurePathResponse = failurePathWorkflow.executeWorkflow(failurePatGraph, mockBluePrintRuntimeService(), failurePathWorkflowInput)
assertNotNull(failurePathResponse, "failed to get response")
fun testMultipleSkipFlow() {
runBlocking {
val graph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/FAILURE, C>D/SUCCESS, D>E/SUCCESS, B>E/SUCCESS, E>END/SUCCESS]"
- .toGraph()
+ .toGraph()
val simpleWorkflow = TestBluePrintWorkFlowService()
simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D", "E"), null)
val input = "123456"
fun testParallelFlow() {
runBlocking {
val graph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/SUCCESS, B>D/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]"
- .toGraph()
+ .toGraph()
val simpleWorkflow = TestBluePrintWorkFlowService()
simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D"), null)
val input = "123456"
}
}
-class TestBluePrintWorkFlowService
- : AbstractBluePrintWorkFlowService<String, String>() {
+class TestBluePrintWorkFlowService :
+ AbstractBluePrintWorkFlowService<String, String>() {
+
val log = logger(TestBluePrintWorkFlowService::class)
lateinit var simulatedState: MutableMap<String, EdgeLabel>
return startMessage.output.await()
}
- override suspend fun prepareNodeExecutionMessage(node: Graph.Node)
- : NodeExecuteMessage<String, String> {
+ override suspend fun prepareNodeExecutionMessage(node: Graph.Node):
+ NodeExecuteMessage<String, String> {
return NodeExecuteMessage(node, "$node Input", "")
}
- override suspend fun executeNode(node: Graph.Node, nodeInput: String,
- nodeOutput: String): EdgeLabel {
-// val random = (1..10).random() * 100
-// log.info("workflow($workflowId) node(${node.id}) will reply in $random ms")
-// kotlinx.coroutines.delay(random.toLong())
-// //Simulation for timeout
+ override suspend fun executeNode(
+ node: Graph.Node,
+ nodeInput: String,
+ nodeOutput: String
+ ): EdgeLabel {
+ // val random = (1..10).random() * 100
+ // log.info("workflow($workflowId) node(${node.id}) will reply in $random ms")
+ // kotlinx.coroutines.delay(random.toLong())
+ // //Simulation for timeout
if (node.id == "TO") {
withTimeout(1) {
kotlinx.coroutines.delay(2)
return NodeSkipMessage(node, "$node Skip Input", nodeOutput)
}
- override suspend fun skipNode(node: Graph.Node, nodeInput: String,
- nodeOutput: String): EdgeLabel {
+ override suspend fun skipNode(
+ node: Graph.Node,
+ nodeInput: String,
+ nodeOutput: String
+ ): EdgeLabel {
return simulatedState[node.id] ?: throw BluePrintException("failed to get status for the node($node)")
}
- override suspend fun cancelNode(node: Graph.Node, nodeInput: String,
- nodeOutput: String): EdgeLabel {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ override suspend fun cancelNode(
+ node: Graph.Node,
+ nodeInput: String,
+ nodeOutput: String
+ ): EdgeLabel {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
- override suspend fun restartNode(node: Graph.Node, nodeInput: String,
- nodeOutput: String): EdgeLabel {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ override suspend fun restartNode(
+ node: Graph.Node,
+ nodeInput: String,
+ nodeOutput: String
+ ): EdgeLabel {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override suspend fun prepareWorkflowOutput(): String {
}
return "Final Response"
}
-}
\ No newline at end of file
+}
import java.nio.file.Paths
import kotlin.test.assertTrue
-
class BluePrintFileUtilsTest {
@Test
fun testNewBlueprint() = runBlocking {
val targetPath: String = Paths.get("target").toUri().toURL().path.plus("/bp-new-test")
BluePrintFileUtils.createEmptyBluePrint(targetPath)
-
}
@Test
bluePrintContext.rootPath = targetDir.absolutePath
BluePrintFileUtils.writeBluePrintTypes(bluePrintContext)
-
-
}
-}
\ No newline at end of file
+}
import org.junit.Test
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintRetryException
-
class BluePrintIOUtilsTest {
@Test
BluePrintIOUtils.retry<String>(4, 0, 500, executionBlock, exceptionBlock)
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.utils
-
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.onap.ccsdk.cds.controllerblueprints.core.data.ToscaMetaData
assertNotNull(toscaMetaData.entityDefinitions, "Missing Tosca Entity Definition")
assertNotNull(toscaMetaData.templateTags, "Missing Template Tags")
}
-
}
@Test
assertEquals(properties.getProperty("blueprintsprocessor.database.alt2.password"), "password2", "failed 4")
assertNull(properties.getProperty("blueprintsprocessor.database.alt3.password"), "failed 5")
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.utils
-import org.slf4j.LoggerFactory
import kotlinx.coroutines.runBlocking
import org.junit.Test
+import org.slf4j.LoggerFactory
class JacksonReactorUtilsTest {
- private val log= LoggerFactory.getLogger(this::class.toString())
+ private val log = LoggerFactory.getLogger(this::class.toString())
@Test
fun testJsonNodeFromClassPathFile() {
JacksonReactorUtils.jsonNodeFromFile(filePath)
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.core.utils
-import org.slf4j.LoggerFactory
import org.junit.Test
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.slf4j.LoggerFactory
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
*/
class JacksonUtilsTest {
- private val log= LoggerFactory.getLogger(this::class.toString())
+ private val log = LoggerFactory.getLogger(this::class.toString())
@Test
fun testJsonNodeFromClassPathFile() {
assertNotNull(nodeType, "Failed to get String array from content")
}
-
@Test
fun testJsonValue() {
val filePath = "data/alltype-data.json"
assertTrue(JacksonUtils.checkJsonNodeValueOfType(BluePrintConstants.DATA_TYPE_MAP, mapValue), "Failed to get as Map value")
assertTrue(!JacksonUtils.checkJsonNodeValueOfType(BluePrintConstants.DATA_TYPE_LIST, stringValue), "Negative type failed")
-
-
}
-}
\ No newline at end of file
+}
val parsedPath = jsonNode.jsonPaths("$..prop1")
assertNotNull(parsedPath, "failed to get parsed path")
}
-}
\ No newline at end of file
+}
log.debug("Out-degrees: " + graph.outDegree())
log.debug("A topological sort of the vertices: " + graph.topSort())
}
-}
\ No newline at end of file
+}
val graph = WorkflowGraphUtils.workFlowToGraph(workflow)
assertNotNull(graph, "failed to create graph")
}
-}
\ No newline at end of file
+}
override fun serviceTemplate(): ServiceTemplate {
- return serviceTemplate("sample-blue-print", "1.0.0",
- "brindasanth@onap.com", "sample, blueprints") {
+ return serviceTemplate(
+ "sample-blue-print", "1.0.0",
+ "brindasanth@onap.com", "sample, blueprints"
+ ) {
topologyTemplate {
workflowNodeTemplate("activate", "component-resource-resolution", "") {
operation("ResourceResolutionExecutor", "") {
override fun loadOtherDefinitions() {
/** Sample Definitions */
- val customDataType = dataType("custom-datatype", "1.0.0",
- BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT, "") {
+ val customDataType = dataType(
+ "custom-datatype", "1.0.0",
+ BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT, ""
+ ) {
property("name", BluePrintConstants.DATA_TYPE_STRING, true, "")
property("value", BluePrintConstants.DATA_TYPE_STRING, true, "")
}
/** Loading to definitions */
addOtherDefinition("datatype-custom-datatype", customDataType)
}
-}
\ No newline at end of file
+}
}
override fun prepareRequest(executionRequest: String): String {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override fun process(executionRequest: String) {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override fun recover(runtimeException: RuntimeException, executionRequest: String) {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override fun prepareResponse(): String {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override fun apply(t: String): String {
}
override suspend fun prepareRequestNB(executionRequest: String): String {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override suspend fun processNB(executionRequest: String) {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: String) {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override suspend fun prepareResponseNB(): String {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override suspend fun applyNB(t: String): String {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.validation
-import org.slf4j.LoggerFactory
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
@Service("default-artifact-definition-validator")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
open class BluePrintArtifactDefinitionValidatorImpl(
- private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintArtifactDefinitionValidator {
+ private val bluePrintTypeValidatorService: BluePrintTypeValidatorService
+) : BluePrintArtifactDefinitionValidator {
- private val log= LoggerFactory.getLogger(BluePrintArtifactDefinitionValidatorImpl::class.toString())
+ private val log = LoggerFactory.getLogger(BluePrintArtifactDefinitionValidatorImpl::class.toString())
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
var paths: MutableList<String> = arrayListOf()
- override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String,
- artifactDefinition: ArtifactDefinition) {
+ override fun validate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ artifactDefinition: ArtifactDefinition
+ ) {
this.bluePrintRuntimeService = bluePrintRuntimeService
this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
open fun checkValidArtifactType(artifactDefinitionName: String, artifactTypeName: String) {
val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName)
- ?: throw BluePrintException("failed to get artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)")
+ ?: throw BluePrintException("failed to get artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)")
checkValidArtifactTypeDerivedFrom(artifactTypeName, artifactType.derivedFrom)
}
private fun validateExtension(referencePrefix: String, name: String, artifactDefinition: ArtifactDefinition) {
val customValidators = bluePrintTypeValidatorService
- .bluePrintValidators(referencePrefix, BluePrintArtifactDefinitionValidator::class.java)
+ .bluePrintValidators(referencePrefix, BluePrintArtifactDefinitionValidator::class.java)
customValidators?.let {
it.forEach { validator ->
validator.validate(bluePrintRuntimeService, name, artifactDefinition)
}
-
}
}
-}
\ No newline at end of file
+}
import org.springframework.stereotype.Service
@Service("default-artifact-type-validator")
-open class BluePrintArtifactTypeValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintArtifactTypeValidator {
+open class BluePrintArtifactTypeValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintArtifactTypeValidator {
override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactType: ArtifactType) {
bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, artifactType.properties!!)
}
}
-}
\ No newline at end of file
+}
@Service("default-attribute-definition-validator")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintAttributeDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintAttributeDefinitionValidator {
+open class BluePrintAttributeDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintAttributeDefinitionValidator {
-
- private val log= LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
+ private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
-
- override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String,
- attributeDefinition: AttributeDefinition) {
+ override fun validate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ attributeDefinition: AttributeDefinition
+ ) {
log.trace("Validating AttributeDefinition($name)")
this.bluePrintRuntimeService = bluePrintRuntimeService
}
BluePrintTypes.validCollectionTypes().contains(dataType) -> {
val entrySchemaType: String = attributeDefinition.entrySchema?.type
- ?: throw BluePrintException("Entry schema for DataType ($dataType) for the property ($name) not found")
+ ?: throw BluePrintException("Entry schema for DataType ($dataType) for the property ($name) not found")
checkPrimitiveOrComplex(entrySchemaType, name)
}
else -> checkPropertyDataType(dataType, name)
private fun checkPropertyDataType(dataTypeName: String, propertyName: String) {
val dataType = bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.get(dataTypeName)
- ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName))
+ ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName))
checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom)
}
throw BluePrintException("Failed to get DataType($dataTypeName)'s derivedFrom($derivedFrom) definition ")
}
}
-}
\ No newline at end of file
+}
bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, dataType.properties!!)
}
}
-}
\ No newline at end of file
+}
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.io.File
-import java.util.*
-
+import java.util.UUID
@Service("bluePrintDesignTimeValidatorService")
-open class BluePrintDesignTimeValidatorService(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService,
- private val resourceDefinitionValidator: ResourceDefinitionValidator)
- : BluePrintValidatorService {
+open class BluePrintDesignTimeValidatorService(
+ private val bluePrintTypeValidatorService: BluePrintTypeValidatorService,
+ private val resourceDefinitionValidator: ResourceDefinitionValidator
+) :
+ BluePrintValidatorService {
- private val log= LoggerFactory.getLogger(BluePrintDesignTimeValidatorService::class.toString())
+ private val log = LoggerFactory.getLogger(BluePrintDesignTimeValidatorService::class.toString())
override fun validateBluePrints(basePath: String): Boolean {
override fun validateBluePrints(bluePrintRuntimeService: BluePrintRuntimeService<*>): Boolean {
- bluePrintTypeValidatorService.validateServiceTemplate(bluePrintRuntimeService, "service_template",
- bluePrintRuntimeService.bluePrintContext().serviceTemplate)
+ bluePrintTypeValidatorService.validateServiceTemplate(
+ bluePrintRuntimeService, "service_template",
+ bluePrintRuntimeService.bluePrintContext().serviceTemplate
+ )
// Validate Resource Definitions
validateResourceDefinitions(bluePrintRuntimeService)
val blueprintBasePath = bluePrintRuntimeService.bluePrintContext().rootPath
val resourceDefinitionsPath = blueprintBasePath.plus(File.separator)
- .plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR).plus(File.separator)
- .plus("${ResourceDictionaryConstants.PATH_RESOURCE_DEFINITION_TYPE}.json")
+ .plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR).plus(File.separator)
+ .plus("${ResourceDictionaryConstants.PATH_RESOURCE_DEFINITION_TYPE}.json")
val resourceDefinitionFile = File(resourceDefinitionsPath)
package org.onap.ccsdk.cds.controllerblueprints.validation
-import org.slf4j.LoggerFactory
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateValidator
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.onap.ccsdk.cds.controllerblueprints.validation.utils.PropertyAssignmentValidationUtils
+import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
-
@Service("default-node-template-validator")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintNodeTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintNodeTemplateValidator {
+open class BluePrintNodeTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintNodeTemplateValidator {
- private val log= LoggerFactory.getLogger(BluePrintNodeTemplateValidatorImpl::class.toString())
+ private val log = LoggerFactory.getLogger(BluePrintNodeTemplateValidatorImpl::class.toString())
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
val type: String = nodeTemplate.type
val nodeType: NodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(type)
- ?: throw BluePrintException("Failed to get NodeType($type) definition for NodeTemplate($name)")
+ ?: throw BluePrintException("Failed to get NodeType($type) definition for NodeTemplate($name)")
nodeTemplate.properties?.let {
propertyAssignmentValidationUtils
- .validatePropertyAssignments(nodeType.properties!!, nodeTemplate.properties!!)
+ .validatePropertyAssignments(nodeType.properties!!, nodeTemplate.properties!!)
}
nodeTemplate.capabilities?.let { validateCapabilityAssignments(nodeType, name, nodeTemplate) }
nodeTemplate.requirements?.let { validateRequirementAssignments(nodeType, name, nodeTemplate) }
open fun validateArtifactDefinitions(artifacts: MutableMap<String, ArtifactDefinition>) {
paths.add("artifacts")
artifacts.forEach { artifactDefinitionName, artifactDefinition ->
- bluePrintTypeValidatorService.validateArtifactDefinition(bluePrintRuntimeService,
- artifactDefinitionName, artifactDefinition)
+ bluePrintTypeValidatorService.validateArtifactDefinition(
+ bluePrintRuntimeService,
+ artifactDefinitionName, artifactDefinition
+ )
}
paths.removeAt(paths.lastIndex)
}
paths.add(capabilityName)
val capabilityDefinition = nodeType.capabilities?.get(capabilityName)
- ?: throw BluePrintException("Failed to get NodeTemplate($nodeTemplateName) capability definition ($capabilityName) " +
- "from NodeType(${nodeTemplate.type})")
+ ?: throw BluePrintException(
+ "Failed to get NodeTemplate($nodeTemplateName) capability definition ($capabilityName) " +
+ "from NodeType(${nodeTemplate.type})"
+ )
validateCapabilityAssignment(nodeTemplateName, capabilityName, capabilityDefinition, capabilityAssignment)
}
@Throws(BluePrintException::class)
- open fun validateCapabilityAssignment(nodeTemplateName: String, capabilityName: String,
- capabilityDefinition: CapabilityDefinition, capabilityAssignment: CapabilityAssignment) {
+ open fun validateCapabilityAssignment(
+ nodeTemplateName: String,
+ capabilityName: String,
+ capabilityDefinition: CapabilityDefinition,
+ capabilityAssignment: CapabilityAssignment
+ ) {
capabilityAssignment.properties?.let {
propertyAssignmentValidationUtils
- .validatePropertyAssignments(capabilityDefinition.properties!!, capabilityAssignment.properties!!)
+ .validatePropertyAssignments(capabilityDefinition.properties!!, capabilityAssignment.properties!!)
}
-
}
@Throws(BluePrintException::class)
requirements?.forEach { requirementName, requirementAssignment ->
paths.add(requirementName)
val requirementDefinition = nodeType.requirements?.get(requirementName)
- ?: throw BluePrintException("Failed to get NodeTemplate($nodeTemplateName) requirement definition ($requirementName) from" +
- " NodeType(${nodeTemplate.type})")
+ ?: throw BluePrintException(
+ "Failed to get NodeTemplate($nodeTemplateName) requirement definition ($requirementName) from" +
+ " NodeType(${nodeTemplate.type})"
+ )
// Validate Requirement Assignment
validateRequirementAssignment(nodeTemplateName, requirementName, requirementDefinition, requirementAssignment)
paths.removeAt(paths.lastIndex)
}
paths.removeAt(paths.lastIndex)
-
}
@Throws(BluePrintException::class)
- open fun validateRequirementAssignment(nodeTemplateName: String, requirementAssignmentName: String,
- requirementDefinition: RequirementDefinition, requirementAssignment: RequirementAssignment) {
- log.debug("Validating NodeTemplate({}) requirement assignment ({}) ", nodeTemplateName,
- requirementAssignmentName)
+ open fun validateRequirementAssignment(
+ nodeTemplateName: String,
+ requirementAssignmentName: String,
+ requirementDefinition: RequirementDefinition,
+ requirementAssignment: RequirementAssignment
+ ) {
+ log.debug(
+ "Validating NodeTemplate({}) requirement assignment ({}) ", nodeTemplateName,
+ requirementAssignmentName
+ )
val requirementNodeTemplateName = requirementAssignment.node!!
val capabilityName = requirementAssignment.capability
val relationship = requirementAssignment.relationship!!
}
val relationShipNodeTemplate = bluePrintContext.serviceTemplate.topologyTemplate?.nodeTemplates?.get(requirementNodeTemplateName)
- ?: throw BluePrintException("Failed to get requirement NodeTemplate($requirementNodeTemplateName)'s " +
- "for NodeTemplate($nodeTemplateName) requirement($requirementAssignmentName)")
+ ?: throw BluePrintException(
+ "Failed to get requirement NodeTemplate($requirementNodeTemplateName)'s " +
+ "for NodeTemplate($nodeTemplateName) requirement($requirementAssignmentName)"
+ )
relationShipNodeTemplate.capabilities?.get(capabilityName)
- ?: throw BluePrintException("Failed to get requirement NodeTemplate($requirementNodeTemplateName)'s " +
- "capability($capabilityName) for NodeTemplate ($nodeTemplateName)'s requirement($requirementAssignmentName)")
-
-
+ ?: throw BluePrintException(
+ "Failed to get requirement NodeTemplate($requirementNodeTemplateName)'s " +
+ "capability($capabilityName) for NodeTemplate ($nodeTemplateName)'s requirement($requirementAssignmentName)"
+ )
}
@Throws(BluePrintException::class)
interfaces?.forEach { interfaceAssignmentName, interfaceAssignment ->
paths.add(interfaceAssignmentName)
val interfaceDefinition = nodeType.interfaces?.get(interfaceAssignmentName)
- ?: throw BluePrintException("Failed to get NodeTemplate($nodeTemplateName) interface definition ($interfaceAssignmentName) from" +
- " NodeType(${nodeTemplate.type})")
-
- validateInterfaceAssignment(nodeTemplateName, interfaceAssignmentName, interfaceDefinition,
- interfaceAssignment)
+ ?: throw BluePrintException(
+ "Failed to get NodeTemplate($nodeTemplateName) interface definition ($interfaceAssignmentName) from" +
+ " NodeType(${nodeTemplate.type})"
+ )
+
+ validateInterfaceAssignment(
+ nodeTemplateName, interfaceAssignmentName, interfaceDefinition,
+ interfaceAssignment
+ )
paths.removeAt(paths.lastIndex)
}
paths.removeAt(paths.lastIndex)
-
-
}
@Throws(BluePrintException::class)
- open fun validateInterfaceAssignment(nodeTemplateName: String, interfaceAssignmentName: String,
- interfaceDefinition: InterfaceDefinition,
- interfaceAssignment: InterfaceAssignment) {
+ open fun validateInterfaceAssignment(
+ nodeTemplateName: String,
+ interfaceAssignmentName: String,
+ interfaceDefinition: InterfaceDefinition,
+ interfaceAssignment: InterfaceAssignment
+ ) {
val operations = interfaceAssignment.operations
operations?.let {
- validateInterfaceOperationsAssignment(nodeTemplateName, interfaceAssignmentName, interfaceDefinition,
- interfaceAssignment)
+ validateInterfaceOperationsAssignment(
+ nodeTemplateName, interfaceAssignmentName, interfaceDefinition,
+ interfaceAssignment
+ )
}
-
}
@Throws(BluePrintException::class)
- open fun validateInterfaceOperationsAssignment(nodeTemplateName: String, interfaceAssignmentName: String,
- interfaceDefinition: InterfaceDefinition,
- interfaceAssignment: InterfaceAssignment) {
+ open fun validateInterfaceOperationsAssignment(
+ nodeTemplateName: String,
+ interfaceAssignmentName: String,
+ interfaceDefinition: InterfaceDefinition,
+ interfaceAssignment: InterfaceAssignment
+ ) {
val operations = interfaceAssignment.operations
operations?.let {
it.forEach { operationAssignmentName, operationAssignments ->
val operationDefinition = interfaceDefinition.operations?.get(operationAssignmentName)
- ?: throw BluePrintException("Failed to get NodeTemplate($nodeTemplateName) operation definition ($operationAssignmentName)")
+ ?: throw BluePrintException("Failed to get NodeTemplate($nodeTemplateName) operation definition ($operationAssignmentName)")
- log.debug("Validation NodeTemplate($nodeTemplateName) Interface($interfaceAssignmentName) Operation " +
- "($operationAssignmentName)")
+ log.debug(
+ "Validation NodeTemplate($nodeTemplateName) Interface($interfaceAssignmentName) Operation " +
+ "($operationAssignmentName)"
+ )
val inputs = operationAssignments.inputs
val outputs = operationAssignments.outputs
inputs?.forEach { propertyName, propertyAssignment ->
val propertyDefinition = operationDefinition.inputs?.get(propertyName)
- ?: throw BluePrintException("Failed to get NodeTemplate($nodeTemplateName) operation " +
- "definition ($operationAssignmentName) property definition($propertyName)")
+ ?: throw BluePrintException(
+ "Failed to get NodeTemplate($nodeTemplateName) operation " +
+ "definition ($operationAssignmentName) property definition($propertyName)"
+ )
// Check the property values with property definition
propertyAssignmentValidationUtils
- .validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment)
+ .validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment)
}
outputs?.forEach { propertyName, propertyAssignment ->
val propertyDefinition = operationDefinition.outputs?.get(propertyName)
- ?: throw BluePrintException("Failed to get NodeTemplate($nodeTemplateName) operation definition ($operationAssignmentName) " +
- "output property definition($propertyName)")
+ ?: throw BluePrintException(
+ "Failed to get NodeTemplate($nodeTemplateName) operation definition ($operationAssignmentName) " +
+ "output property definition($propertyName)"
+ )
// Check the property values with property definition
propertyAssignmentValidationUtils
- .validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment)
+ .validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment)
}
-
}
}
-
}
-
private fun validateExtension(referencePrefix: String, name: String, nodeTemplate: NodeTemplate) {
val customValidator = bluePrintTypeValidatorService
- .bluePrintValidator(referencePrefix, BluePrintNodeTemplateValidator::class.java)
+ .bluePrintValidator(referencePrefix, BluePrintNodeTemplateValidator::class.java)
customValidator?.let {
it.validate(bluePrintRuntimeService, name, nodeTemplate)
}
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.validation
-import org.slf4j.LoggerFactory
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeValidator
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
-
@Service("default-node-type-validator")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
open class BluePrintNodeTypeValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintNodeTypeValidator {
paths.add(nodeTypeName)
val derivedFrom: String = nodeType.derivedFrom
- //Check Derived From
+ // Check Derived From
checkValidNodeTypesDerivedFrom(nodeTypeName, derivedFrom)
if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) {
bluePrintContext.serviceTemplate.nodeTypes?.get(derivedFrom)
- ?: throw BluePrintException("Failed to get derivedFrom NodeType($derivedFrom)'s for NodeType($nodeTypeName)")
+ ?: throw BluePrintException("Failed to get derivedFrom NodeType($derivedFrom)'s for NodeType($nodeTypeName)")
}
nodeType.attributes?.let {
paths.removeAt(paths.lastIndex)
}
- open fun validateCapabilityDefinition(nodeTypeName: String, nodeType: NodeType, capabilityName: String,
- capabilityDefinition: CapabilityDefinition) {
+ open fun validateCapabilityDefinition(
+ nodeTypeName: String,
+ nodeType: NodeType,
+ capabilityName: String,
+ capabilityDefinition: CapabilityDefinition
+ ) {
val capabilityType = capabilityDefinition.type
check(BluePrintTypes.validCapabilityTypes.contains(capabilityType)) {
throw BluePrintException("failed to get CapabilityType($capabilityType) for NodeType($nodeTypeName)")
paths.removeAt(paths.lastIndex)
}
- open fun validateRequirementDefinition(nodeTypeName: String, nodeType: NodeType, requirementDefinitionName: String,
- requirementDefinition: RequirementDefinition) {
+ open fun validateRequirementDefinition(
+ nodeTypeName: String,
+ nodeType: NodeType,
+ requirementDefinitionName: String,
+ requirementDefinition: RequirementDefinition
+ ) {
log.info("validating NodeType({}) RequirementDefinition ({}) ", nodeTypeName, requirementDefinitionName)
val requirementNodeTypeName = requirementDefinition.node!!
}
val relationShipNodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(requirementNodeTypeName)
- ?: throw BluePrintException("failed to get requirement NodeType($requirementNodeTypeName)'s for requirement($requirementDefinitionName) ")
+ ?: throw BluePrintException("failed to get requirement NodeType($requirementNodeTypeName)'s for requirement($requirementDefinitionName) ")
relationShipNodeType.capabilities?.get(capabilityName)
- ?: throw BluePrintException("failed to get requirement NodeType($requirementNodeTypeName)'s " +
- "capability($nodeTypeName) for NodeType ($capabilityName)'s requirement($requirementDefinitionName) ")
-
+ ?: throw BluePrintException(
+ "failed to get requirement NodeType($requirementNodeTypeName)'s " +
+ "capability($nodeTypeName) for NodeType ($capabilityName)'s requirement($requirementDefinitionName) "
+ )
}
open fun validateInterfaceDefinitions(interfaces: MutableMap<String, InterfaceDefinition>) {
open fun validateImplementation(implementation: Implementation) {
checkNotEmpty(implementation.primary) { "couldn't get implementation" }
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.validation
-import org.slf4j.LoggerFactory
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionValidator
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
@Service("default-property-definition-validator")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintPropertyDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintPropertyDefinitionValidator {
+open class BluePrintPropertyDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintPropertyDefinitionValidator {
- private val log= LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
+ private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
-
override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) {
this.bluePrintRuntimeService = bluePrintRuntimeService
-
log.trace("Validating PropertyDefinition($name)")
val dataType: String = propertyDefinition.type
}
BluePrintTypes.validCollectionTypes().contains(dataType) -> {
val entrySchemaType: String = propertyDefinition.entrySchema?.type
- ?: throw BluePrintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, name))
+ ?: throw BluePrintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, name))
checkPrimitiveOrComplex(entrySchemaType, name)
}
else -> checkPropertyDataType(dataType, name)
}
}
-
private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean {
if (BluePrintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) {
return true
private fun checkPropertyDataType(dataTypeName: String, propertyName: String) {
val dataType = bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.get(dataTypeName)
- ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName))
+ ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName))
checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom)
}
throw BluePrintException(format("Failed to get DataType({})'s derivedFrom({}) definition ", dataTypeName, derivedFrom))
}
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.validation
-import org.slf4j.LoggerFactory
import com.google.common.base.Preconditions
import org.apache.commons.lang3.StringUtils
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateValidator
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
@Service("default-service-template-validator")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintServiceTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintServiceTemplateValidator {
+open class BluePrintServiceTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintServiceTemplateValidator {
- private val log= LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
+ private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var error: BluePrintError
paths.removeAt(paths.lastIndex)
}
-
fun validateDataTypes(dataTypes: MutableMap<String, DataType>) {
paths.add(BluePrintConstants.PATH_DATA_TYPES)
bluePrintTypeValidatorService.validateTopologyTemplate(bluePrintRuntimeService, "topologyTemplate", topologyTemplate)
paths.removeAt(paths.lastIndex)
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.validation
-import org.slf4j.LoggerFactory
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateValidator
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
@Service("default-topology-template-validator")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintTopologyTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintTopologyTemplateValidator {
+open class BluePrintTopologyTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintTopologyTemplateValidator {
- private val log= LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
+ private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, inputs)
}
-
@Throws(BluePrintException::class)
fun validateNodeTemplates(nodeTemplates: MutableMap<String, NodeTemplate>) {
bluePrintTypeValidatorService.validateWorkflow(bluePrintRuntimeService, workflowName, workflow)
}
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.validation
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
-import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.*
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDataTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowValidator
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Service
override fun <T : BluePrintValidator<*>> bluePrintValidators(referenceNamePrefix: String, classType: Class<T>): List<T>? {
return context.getBeansOfType(classType)
- .filter { it.key.startsWith(referenceNamePrefix) }
- .mapNotNull { it.value }
+ .filter { it.key.startsWith(referenceNamePrefix) }
+ .mapNotNull { it.value }
}
override fun <T : BluePrintValidator<*>> bluePrintValidators(classType: Class<T>): List<T>? {
override fun getServiceTemplateValidators(): List<BluePrintServiceTemplateValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintServiceTemplateValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default ServiceTemplate validators")
+ ?: throw BluePrintProcessorException("failed to get default ServiceTemplate validators")
}
override fun getDataTypeValidators(): List<BluePrintDataTypeValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintDataTypeValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default DataType validators")
+ ?: throw BluePrintProcessorException("failed to get default DataType validators")
}
override fun getArtifactTypeValidators(): List<BluePrintArtifactTypeValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintArtifactTypeValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default ArtifactType validators")
+ ?: throw BluePrintProcessorException("failed to get default ArtifactType validators")
}
override fun getArtifactDefinitionsValidators(): List<BluePrintArtifactDefinitionValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintArtifactDefinitionValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default ArtifactDefinition validators")
+ ?: throw BluePrintProcessorException("failed to get default ArtifactDefinition validators")
}
override fun getNodeTypeValidators(): List<BluePrintNodeTypeValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintNodeTypeValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default NodeType validators")
+ ?: throw BluePrintProcessorException("failed to get default NodeType validators")
}
override fun getTopologyTemplateValidators(): List<BluePrintTopologyTemplateValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintTopologyTemplateValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default TopologyTemplate validators")
+ ?: throw BluePrintProcessorException("failed to get default TopologyTemplate validators")
}
override fun getNodeTemplateValidators(): List<BluePrintNodeTemplateValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintNodeTemplateValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default NodeTemplate validators")
+ ?: throw BluePrintProcessorException("failed to get default NodeTemplate validators")
}
override fun getWorkflowValidators(): List<BluePrintWorkflowValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintWorkflowValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default Workflow validators")
+ ?: throw BluePrintProcessorException("failed to get default Workflow validators")
}
override fun getPropertyDefinitionValidators(): List<BluePrintPropertyDefinitionValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintPropertyDefinitionValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default PropertyDefinition validators")
+ ?: throw BluePrintProcessorException("failed to get default PropertyDefinition validators")
}
override fun getAttributeDefinitionValidators(): List<BluePrintAttributeDefinitionValidator> {
return bluePrintValidators(PREFIX_DEFAULT, BluePrintAttributeDefinitionValidator::class.java)
- ?: throw BluePrintProcessorException("failed to get default AttributeDefinition validators")
+ ?: throw BluePrintProcessorException("failed to get default AttributeDefinition validators")
}
}
-
@Configuration
@ComponentScan
-open class BluePrintValidationConfiguration
\ No newline at end of file
+open class BluePrintValidationConfiguration
package org.onap.ccsdk.cds.controllerblueprints.validation
-import org.slf4j.LoggerFactory
-import org.onap.ccsdk.cds.controllerblueprints.validation.utils.PropertyAssignmentValidationUtils
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowValidator
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.onap.ccsdk.cds.controllerblueprints.validation.utils.PropertyAssignmentValidationUtils
+import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
open class BluePrintWorkflowValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintWorkflowValidator {
- private val log= LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
+ private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
var paths: MutableList<String> = arrayListOf()
this.bluePrintRuntimeService = bluePrintRuntimeService
-
paths.add(workflowName)
paths.joinToString(BluePrintConstants.PATH_DIVIDER)
val nodeTypeDerivedFrom = bluePrintRuntimeService.bluePrintContext().nodeTemplateNodeType(it).derivedFrom
- check(nodeTypeDerivedFrom == BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW
- || nodeTypeDerivedFrom == BluePrintConstants.MODEL_TYPE_NODE_COMPONENT) {
+ check(
+ nodeTypeDerivedFrom == BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW ||
+ nodeTypeDerivedFrom == BluePrintConstants.MODEL_TYPE_NODE_COMPONENT
+ ) {
"NodeType(${nodeTemplate.type}) derived from is '$nodeTypeDerivedFrom', Expected " +
"'${BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW}' or '${BluePrintConstants.MODEL_TYPE_NODE_COMPONENT}'"
}
} catch (e: Exception) {
bluePrintRuntimeService.getBluePrintError()
- .addError("Failed to validate Workflow($workflowName)'s step($stepName)'s " +
- "definition", paths.joinToString(BluePrintConstants.PATH_DIVIDER), e.message!!)
+ .addError(
+ "Failed to validate Workflow($workflowName)'s step($stepName)'s " +
+ "definition", paths.joinToString(BluePrintConstants.PATH_DIVIDER), e.message!!
+ )
}
}
-
}
paths.removeAt(paths.lastIndex)
// Step Validation Ends
bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, workflow.outputs!!)
PropertyAssignmentValidationUtils(bluePrintRuntimeService.bluePrintContext())
- .validatePropertyDefinitionNAssignments(workflow.outputs!!)
+ .validatePropertyDefinitionNAssignments(workflow.outputs!!)
}
// Validate Value or Expression
workflow.outputs?.forEach { propertyName, propertyDefinition ->
-
}
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.validation.extension
-import org.slf4j.LoggerFactory
import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionValidator
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.service.ResourceAssignmentValidationServiceImpl
+import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.io.File
@Service("artifact-mapping-resource-artifact-definition-validator")
-open class ArtifactMappingResourceValidator(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService)
- : BluePrintArtifactDefinitionValidator {
+open class ArtifactMappingResourceValidator(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintArtifactDefinitionValidator {
- private val log= LoggerFactory.getLogger(ArtifactMappingResourceValidator::class.toString())
+ private val log = LoggerFactory.getLogger(ArtifactMappingResourceValidator::class.toString())
- override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String,
- artifactDefinition: ArtifactDefinition) {
+ override fun validate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ artifactDefinition: ArtifactDefinition
+ ) {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
val file: String = artifactDefinition.file
val resourceAssignmentValidationService = ResourceAssignmentValidationServiceImpl()
resourceAssignmentValidationService.validate(resourceAssignment)
}
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.validation.extension
-import org.slf4j.LoggerFactory
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidator
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
+import org.slf4j.LoggerFactory
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
open class ResourceDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : ResourceDefinitionValidator {
- private val log= LoggerFactory.getLogger(ResourceDefinitionValidatorImpl::class.java)
+ private val log = LoggerFactory.getLogger(ResourceDefinitionValidatorImpl::class.java)
- override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String,
- resourceDefinition: ResourceDefinition) {
+ override fun validate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ resourceDefinition: ResourceDefinition
+ ) {
log.trace("validating resource definition($name)")
resourceDefinition.sources.forEach { name, nodeTemplate ->
bluePrintTypeValidatorService.validateNodeTemplate(bluePrintRuntimeService, name, nodeTemplate)
}
}
-}
\ No newline at end of file
+}
}
}
- open fun validatePropertyAssignments(nodeTypeProperties: MutableMap<String, PropertyDefinition>,
- properties: MutableMap<String, JsonNode>) {
+ open fun validatePropertyAssignments(
+ nodeTypeProperties: MutableMap<String, PropertyDefinition>,
+ properties: MutableMap<String, JsonNode>
+ ) {
properties.forEach { propertyName, propertyAssignment ->
val propertyDefinition: PropertyDefinition = nodeTypeProperties[propertyName]
- ?: throw BluePrintException("validatePropertyAssignments failed to get definition for the property ($propertyName)")
+ ?: throw BluePrintException("validatePropertyAssignments failed to get definition for the property ($propertyName)")
validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment)
-
}
}
- open fun validatePropertyAssignment(propertyName: String, propertyDefinition: PropertyDefinition,
- propertyAssignment: JsonNode) {
+ open fun validatePropertyAssignment(
+ propertyName: String,
+ propertyDefinition: PropertyDefinition,
+ propertyAssignment: JsonNode
+ ) {
// Check and Validate if Expression Node
val expressionData = BluePrintExpressionService.getExpressionData(propertyAssignment)
if (!expressionData.isExpression) {
if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) {
isValid = JacksonUtils.checkJsonNodeValueOfPrimitiveType(propertyType, propertyAssignment)
-
} else if (BluePrintTypes.validComplexTypes().contains(propertyType)) {
isValid = true
} else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) {
val entrySchemaType = propertyDefinition.entrySchema?.type
- ?: throw BluePrintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName))
+ ?: throw BluePrintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName))
if (!BluePrintTypes.validPropertyTypes().contains(entrySchemaType)) {
checkPropertyDataType(entrySchemaType, propertyName)
open fun checkPropertyDataType(dataTypeName: String, propertyName: String) {
val dataType = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName)
- ?: throw BluePrintException("DataType ($dataTypeName) for the property ($propertyName) not found")
+ ?: throw BluePrintException("DataType ($dataTypeName) for the property ($propertyName) not found")
checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom)
-
}
open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) {
workflowValidator.validate(bluePrintRuntime, workflowName, workflow)
assertEquals(1, bluePrintRuntime.getBluePrintError().errors.size)
- assertEquals("Failed to validate Workflow(resource-assignment)'s step(test)'s definition : resource-assignment/steps/test : could't get node template for the name(TestCaseFailNoNodeTemplate)", bluePrintRuntime.getBluePrintError().errors[0])
+ assertEquals(
+ "Failed to validate Workflow(resource-assignment)'s step(test)'s definition : resource-assignment/steps/test : could't get node template for the name(TestCaseFailNoNodeTemplate)",
+ bluePrintRuntime.getBluePrintError().errors[0]
+ )
}
@Test
workflowValidator.validate(bluePrintRuntime, workflowName, workflow)
assertEquals(1, bluePrintRuntime.getBluePrintError().errors.size)
- assertEquals("Failed to validate Workflow(resource-assignment)'s step(test)'s definition : " +
- "resource-assignment/steps/test : NodeType(TestNodeType) derived from is 'tosca.nodes.TEST', " +
- "Expected 'tosca.nodes.Workflow' or 'tosca.nodes.Component'", bluePrintRuntime.getBluePrintError().errors[0])
+ assertEquals(
+ "Failed to validate Workflow(resource-assignment)'s step(test)'s definition : " +
+ "resource-assignment/steps/test : NodeType(TestNodeType) derived from is 'tosca.nodes.TEST', " +
+ "Expected 'tosca.nodes.Workflow' or 'tosca.nodes.Component'", bluePrintRuntime.getBluePrintError().errors[0]
+ )
}
@Test
val workflowName = "resource-assignment"
workflowValidator.validate(bluePrintRuntime, workflowName, bluePrintRuntime.bluePrintContext().workflowByName(workflowName))
}
-
}
-
package org.onap.ccsdk.cds.controllerblueprints.validation
-import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.*
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDataTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowValidator
class MockBluePrintTypeValidatorService : BluePrintTypeValidatorService {
}
override fun <T : BluePrintValidator<*>> bluePrintValidators(referenceNamePrefix: String, classType: Class<T>): List<T>? {
- return null
+ return null
}
override fun <T : BluePrintValidator<*>> bluePrintValidators(classType: Class<T>): List<T>? {
- return null
+ return null
}
override fun getServiceTemplateValidators(): List<BluePrintServiceTemplateValidator> {
override fun getAttributeDefinitionValidators(): List<BluePrintAttributeDefinitionValidator> {
return listOf(BluePrintAttributeDefinitionValidatorImpl(this))
}
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
import java.io.Serializable
-import java.util.*
+import java.util.Date
open class ResourceDefinition {
*/
interface ResourceSource : Serializable
-
open class ResourceSourceMapping {
lateinit var resourceSourceMappings: MutableMap<String, String>
}
* @author Brinda Santh
*/
object ResourceDictionaryConstants {
+
const val SOURCE_INPUT = "input"
const val SOURCE_DEFAULT = "default"
const val PROCESSOR_DB = "processor-db"
fun getRegisterSourceMapping(sourceInstance: String): String {
return resourceSourceMappings[sourceInstance]
- ?: throw BluePrintException(format("failed to get source({}) mapping", sourceInstance))
+ ?: throw BluePrintException(format("failed to get source({}) mapping", sourceInstance))
}
fun getRegisterSourceMapping(): ResourceSourceMapping {
return resourceSourceMapping
}
}
-
package org.onap.ccsdk.cds.controllerblueprints.resource.dict.service
-import org.slf4j.LoggerFactory
import org.apache.commons.collections.CollectionUtils
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.text.StrBuilder
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.utils.TopologicalSortingUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
+import org.slf4j.LoggerFactory
import java.io.Serializable
/**
* @author Brinda Santh
*/
open class ResourceAssignmentValidationServiceImpl : ResourceAssignmentValidationService {
- private val log= LoggerFactory.getLogger(ResourceAssignmentValidationServiceImpl::class.java)
+
+ private val log = LoggerFactory.getLogger(ResourceAssignmentValidationServiceImpl::class.java)
open var resourceAssignmentMap: Map<String, ResourceAssignment> = hashMapOf()
open val validationMessage = StrBuilder()
return true
}
-
open fun validateTemplateNDictionaryKeys(resourceAssignments: List<ResourceAssignment>) {
resourceAssignmentMap = resourceAssignments.map { it.name to it }.toMap()
// Check the Resource Assignment has Duplicate Key Names
val duplicateKeyNames = resourceAssignments.groupBy { it.name }
- .filter { it.value.size > 1 }
- .map { it.key }
+ .filter { it.value.size > 1 }
+ .map { it.key }
if (duplicateKeyNames.isNotEmpty()) {
validationMessage.appendln(String.format("Duplicate Assignment Template Keys (%s) is Present", duplicateKeyNames))
if (v.name == "*") {
s.append("\n * -> [")
for (resourceAssignment in vs) {
- s.append("(" + resourceAssignment.dictionaryName + ":" + resourceAssignment.name
- + "),")
+ s.append(
+ "(" + resourceAssignment.dictionaryName + ":" + resourceAssignment.name +
+ "),"
+ )
}
s.append("]")
} else {
s.append("\n (" + v.dictionaryName + ":" + v.name + ") -> [")
for (resourceAssignment in vs) {
- s.append("(" + resourceAssignment.dictionaryName + ":" + resourceAssignment.name
- + "),")
+ s.append(
+ "(" + resourceAssignment.dictionaryName + ":" + resourceAssignment.name +
+ "),"
+ )
}
s.append("]")
}
}
return s.toString()
}
-
-
-}
\ No newline at end of file
+}
import org.onap.ccsdk.cds.controllerblueprints.core.utils.TopologicalSortingUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.slf4j.LoggerFactory
-import java.util.*
+import java.util.ArrayList
/**
* BulkResourceSequencingUtils.
* @author Brinda Santh
*/
object BulkResourceSequencingUtils {
+
private val log = LoggerFactory.getLogger(BulkResourceSequencingUtils::class.java)
@JvmStatic
dependencyPresence = CollectionUtils.containsAny(batchAssignmentName, resourceAssignment.dependencies)
}
- log.trace("({}) -> Checking ({}), with ({}), result ({})", resourceAssignment.name,
- batchAssignmentName, resourceAssignment.dependencies, dependencyPresence)
+ log.trace(
+ "({}) -> Checking ({}), with ({}), result ({})", resourceAssignment.name,
+ batchAssignmentName, resourceAssignment.dependencies, dependencyPresence
+ )
- if (previousResourceAssignment != null && resourceAssignment.dictionarySource != null
- && resourceAssignment.dictionarySource!!.equals(previousResourceAssignment.dictionarySource, true)
- && !dependencyPresence) {
+ if (previousResourceAssignment != null && resourceAssignment.dictionarySource != null &&
+ resourceAssignment.dictionarySource!!.equals(previousResourceAssignment.dictionarySource, true) &&
+ !dependencyPresence
+ ) {
batchResourceAssignment!!.add(resourceAssignment)
batchAssignmentName!!.add(resourceAssignment.name)
} else {
return sequenceBatchResourceAssignment
}
-
-}
\ No newline at end of file
+}
package org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils
-import org.slf4j.LoggerFactory
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.NullNode
import org.apache.commons.collections.MapUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants
+import org.slf4j.LoggerFactory
import java.io.File
-
object ResourceDictionaryUtils {
- private val log= LoggerFactory.getLogger(ResourceDictionaryUtils::class.java)
+ private val log = LoggerFactory.getLogger(ResourceDictionaryUtils::class.java)
@JvmStatic
- fun populateSourceMapping(resourceAssignment: ResourceAssignment,
- resourceDefinition: ResourceDefinition) {
+ fun populateSourceMapping(
+ resourceAssignment: ResourceAssignment,
+ resourceDefinition: ResourceDefinition
+ ) {
if (StringUtils.isBlank(resourceAssignment.dictionarySource)) {
fun getResourceAssignmentFromFile(filePath: String): List<ResourceAssignment> {
return JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java)
- ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)")
+ ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)")
}
fun writeResourceDefinitionTypes(basePath: String, resourceDefinitions: List<ResourceDefinition>) {
val resourceDefinitionMap = resourceDefinitions.map { it.name to it }.toMap()
writeResourceDefinitionTypes(basePath, resourceDefinitionMap)
-
}
fun writeResourceDefinitionTypes(basePath: String, resourceDefinitionMap: Map<String, ResourceDefinition>) {
val typePath = basePath.plus(File.separator).plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR)
- .plus(File.separator).plus("${ResourceDictionaryConstants.PATH_RESOURCE_DEFINITION_TYPE}.json")
+ .plus(File.separator).plus("${ResourceDictionaryConstants.PATH_RESOURCE_DEFINITION_TYPE}.json")
val resourceDefinitionContent = JacksonUtils.getJson(resourceDefinitionMap.toSortedMap(), true)
BluePrintFileUtils.writeDefinitionFile(typePath, resourceDefinitionContent)
}
-}
\ No newline at end of file
+}
private String basePath = "./../../../../components/model-catalog/resource-dictionary/starter-dictionary";
@Test
- public void testDictionaryDefinitionInputSource(){
+ public void testDictionaryDefinitionInputSource() {
String fileName = basePath + "/input-source.json";
ResourceDefinition resourceDefinition = JacksonUtils.Companion.readValueFromFile(fileName, ResourceDefinition.class);
}
@Test
- public void testDictionaryDefinitionDefaultSource(){
+ public void testDictionaryDefinitionDefaultSource() {
String fileName = basePath + "/default-source.json";
ResourceDefinition resourceDefinition = JacksonUtils.Companion.readValueFromFile(fileName, ResourceDefinition.class);
}
@Test
- public void testDictionaryDefinitionDBSource(){
+ public void testDictionaryDefinitionDBSource() {
String fileName = basePath + "/db-source.json";
ResourceDefinition resourceDefinition = JacksonUtils.Companion.readValueFromFile(fileName, ResourceDefinition.class);
}
@Test
- public void testDictionaryDefinitionMDSALSource(){
+ public void testDictionaryDefinitionMDSALSource() {
String fileName = basePath + "/mdsal-source.json";
ResourceDefinition resourceDefinition = JacksonUtils.Companion.readValueFromFile(fileName, ResourceDefinition.class);
Assert.assertNotNull("Failed to populate dictionaryDefinition for mdsal type", resourceDefinition);
}
+
}
package org.onap.ccsdk.cds.controllerblueprints.resource.dict.service
import org.junit.Assert
+import org.junit.Before
import org.junit.Test
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
-import org.junit.Before
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryTestUtils
import org.slf4j.LoggerFactory
* @author Brinda Santh
*/
class ResourceAssignmentValidationServiceTest {
+
private val log = LoggerFactory.getLogger(ResourceAssignmentValidationServiceTest::class.java)
@Before
fun setUp() {
val resourceAssignmentValidator = ResourceAssignmentValidationServiceImpl()
resourceAssignmentValidator.validate(assignments!!)
}
-}
\ No newline at end of file
+}
import org.junit.Test;
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils;
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment;
+
import java.util.List;
+
/**
* BulkResourceSequencingUtils.
*
public class BulkResourceSequencingUtilsTest {
@Test
- public void testProcess(){
+ public void testProcess() {
List<ResourceAssignment> assignments = JacksonUtils.Companion.getListFromClassPathFile("validation/success.json", ResourceAssignment.class);
Assert.assertNotNull("failed to get ResourceAssignment from validation/success.json ", assignments);
BulkResourceSequencingUtils.process(assignments);
}
+
}
\ No newline at end of file
resourceAssignment.setDictionarySource(null);
sources.put(ResourceDictionaryConstants.SOURCE_DEFAULT, new NodeTemplate());
ResourceDictionaryUtils.populateSourceMapping(resourceAssignment, resourceDefinition);
- Assert.assertEquals("Expected First source Default, but.", ResourceDictionaryConstants.SOURCE_DEFAULT, resourceAssignment.getDictionarySource());
+ Assert.assertEquals("Expected First source Default, but.",
+ ResourceDictionaryConstants.SOURCE_DEFAULT,
+ resourceAssignment.getDictionarySource());
// To Check Assigned Source
resourceAssignment.setDictionarySource(ResourceDictionaryConstants.PROCESSOR_DB);
ResourceDictionaryUtils.assignInputs(data, context);
String path = BluePrintConstants.PATH_INPUTS.concat(BluePrintConstants.PATH_DIVIDER).concat("mapValue");
log.info("populated context {}", context);
- Assert.assertTrue(String.format("failed to get variable : %s",path),context.containsKey(path));
+ Assert.assertTrue(String.format("failed to get variable : %s", path), context.containsKey(path));
}
-
}
* 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.
<scope>test</scope>
</dependency>
-
-
<dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
<artifactId>health-api-common</artifactId>
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener;
import org.springframework.boot.SpringApplication;
public static void main(String[] args) {
SpringApplication.run(SdcListenerApplication.class, args);
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener;
-import java.util.List;
import org.onap.sdc.api.consumer.IConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
+import java.util.List;
+
/**
* In order to initiate a SDC distribution client we need to supply some pre-configuration values that
* distribution client needs.
public Boolean isUseHttpsWithDmaap() {
return isUseHttpsWithDmaap;
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener;
-import static org.onap.sdc.utils.DistributionActionResultEnum.SUCCESS;
-import java.io.File;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.Objects;
import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto;
import org.onap.ccsdk.cds.sdclistener.service.ListenerService;
import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
+import java.io.File;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Objects;
+
+import static org.onap.sdc.utils.DistributionActionResultEnum.SUCCESS;
+
@ConfigurationProperties("listenerservice")
@Component
@ComponentScan("org.onap.ccsdk.cds.cdssdclistener.dto")
private void processNotification(INotificationData notificationData) {
final IDistributionClient distributionClient = sdcListenerDto.getDistributionClient();
notificationData.getServiceArtifacts()
- .forEach(artifactInfo -> downloadCsarArtifacts(artifactInfo, distributionClient));
+ .forEach(artifactInfo -> downloadCsarArtifacts(artifactInfo, distributionClient));
}
/**
* Download the TOSCA CSAR artifact and process it.
*
- * @param info - Artifact information
+ * @param info - Artifact information
* @param distributionClient - SDC distribution client
*/
private void downloadCsarArtifacts(IArtifactInfo info, IDistributionClient distributionClient) {
if (!Objects.equals(result.getDistributionActionResult(), SUCCESS)) {
final String errorMessage = String.format("Failed to download the artifact from : %s due to %s ", url,
- result.getDistributionActionResult());
+ result.getDistributionActionResult());
listenerStatus
- .sendResponseBackToSdc(distributionId, DistributionStatusEnum.DOWNLOAD_ERROR, errorMessage,
- url, NotificationType.DOWNLOAD);
+ .sendResponseBackToSdc(distributionId, DistributionStatusEnum.DOWNLOAD_ERROR, errorMessage,
+ url, NotificationType.DOWNLOAD);
LOGGER.error(errorMessage);
} else {
listenerStatus.sendResponseBackToSdc(distributionId, DistributionStatusEnum.DOWNLOAD_OK, null, url,
- NotificationType.DOWNLOAD);
+ NotificationType.DOWNLOAD);
LOGGER.info("Trying to write CSAR artifact to file with URL {} and UUID {}", url, id);
processCsarArtifact(result);
}
listenerService.saveBluePrintToCdsDatabase(cbaArchivePath, sdcListenerDto.getManagedChannelForGrpc());
}
+
}
package org.onap.ccsdk.cds.sdclistener.actuator.indicator;
-
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthApiResponse;
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus;
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health.SDCListenerHealthCheck;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.stereotype.Component;
+
/**
* Health Indicator for SDCListener.
+ *
* @author Shaaban Ebrahim
* @version 1.0
*/
@Component
public class SDCListenerCustomIndicator extends AbstractHealthIndicator {
- @Autowired
- private SDCListenerHealthCheck sDCListenerHealthCheck;
+ @Autowired
+ private SDCListenerHealthCheck sDCListenerHealthCheck;
- @Override
- protected void doHealthCheck(Builder builder) {
- HealthApiResponse healthAPIResponse = sDCListenerHealthCheck.retrieveEndpointExecutionStatus();
- if (healthAPIResponse.getStatus() == HealthCheckStatus.UP) {
- builder.up();
- } else {
- builder.down();
+ @Override
+ protected void doHealthCheck(Builder builder) {
+ HealthApiResponse healthAPIResponse = sDCListenerHealthCheck.retrieveEndpointExecutionStatus();
+ if (healthAPIResponse.getStatus() == HealthCheckStatus.UP) {
+ builder.up();
+ } else {
+ builder.down();
+ }
+ builder.withDetail("Services", healthAPIResponse.getChecks());
}
- builder.withDetail("Services", healthAPIResponse.getChecks());
- }
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.client;
-import io.grpc.*;
+import io.grpc.CallOptions;
+import io.grpc.Channel;
+import io.grpc.ClientCall;
+import io.grpc.ClientInterceptor;
+import io.grpc.ForwardingClientCall;
+import io.grpc.Metadata;
import io.grpc.Metadata.Key;
+import io.grpc.MethodDescriptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
CallOptions callOptions, Channel channel) {
Key<String> authHeader = Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER);
return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(
- channel.newCall(methodDescriptor, callOptions)) {
+ channel.newCall(methodDescriptor, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
headers.put(authHeader, basicAuth);
}
};
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.client;
-import java.util.Optional;
import org.onap.ccsdk.cds.sdclistener.SdcListenerConfiguration;
-import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto;
import org.onap.ccsdk.cds.sdclistener.SdcListenerNotificationCallback;
+import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto;
import org.onap.ccsdk.cds.sdclistener.exceptions.SdcListenerException;
import org.onap.sdc.api.IDistributionClient;
import org.onap.sdc.api.results.IDistributionClientResult;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
+import java.util.Optional;
+
@Component
@ComponentScan("org.onap.ccsdk.cds.cdssdclistener.dto")
public class SdcListenerClient {
LOG.info("Initialize the SDC distribution client");
distributionClient = Optional.of(DistributionClientFactory.createDistributionClient())
- .orElseThrow(() -> new SdcListenerException("Could not able to create SDC Distribution client"));
+ .orElseThrow(() -> new SdcListenerException("Could not able to create SDC Distribution client"));
listenerDto.setManagedChannelForGrpc();
private void startSdcClientBasedOnTheResult(IDistributionClientResult result) throws SdcListenerException {
if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
throw new SdcListenerException(
- "SDC distribution client init failed with reason:" + result.getDistributionMessageResult());
+ "SDC distribution client init failed with reason:" + result.getDistributionMessageResult());
}
LOG.info("Initialization of the SDC distribution client is complete");
if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
throw new SdcListenerException(
- "Startup of the SDC distribution client failed with reason: " + result.getDistributionMessageResult());
+ "Startup of the SDC distribution client failed with reason: " + result.getDistributionMessageResult());
}
}
IDistributionClientResult status = this.distributionClient.stop();
if (status.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
throw new SdcListenerException(
- "Failed to close the SDC distribution client due to : " + status.getDistributionMessageResult());
+ "Failed to close the SDC distribution client due to : " + status.getDistributionMessageResult());
}
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.controller;
import org.springframework.http.MediaType;
Mono<String> ping() {
return Mono.just("{\"status\":\"UP\"}");
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.dto;
import io.grpc.ManagedChannel;
public void setManagedChannelForGrpc() {
managedChannel = ManagedChannelBuilder.forAddress(grpcAddress, grpcPort)
- .usePlaintext()
- .intercept(sdcListenerAuthClientInterceptor)
- .build();
+ .usePlaintext()
+ .intercept(sdcListenerAuthClientInterceptor)
+ .build();
}
public ManagedChannel getManagedChannelForGrpc() {
public void setArtifactUrl(String artifactUrl) {
this.artifactUrl = artifactUrl;
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.exceptions;
public class SdcListenerException extends Exception {
/**
* @param message The message to dump
- * @param cause The Throwable cause object
+ * @param cause The Throwable cause object
*/
public SdcListenerException(final String message, final Throwable cause) {
super(message, cause);
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.handler;
import io.grpc.ManagedChannel;
/**
* Sending CBA archive to CDS backend to store into its Database.
*
- * @param request BluePrintManagementInput object holds CBA archive, its version and blueprints.
+ * @param request BluePrintManagementInput object holds CBA archive, its version and blueprints.
* @param managedChannel - ManagedChannel object helps to access the server or application end point.
+ *
* @return A response object
*/
public Status sendRequest(BluePrintUploadInput request, ManagedChannel managedChannel) {
}
LOGGER.info("Stopping GRPC connection to CDS backend");
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.service;
import io.grpc.ManagedChannel;
-import java.nio.file.Path;
import org.onap.sdc.api.results.IDistributionClientDownloadResult;
+import java.nio.file.Path;
+
public interface ListenerService {
/**
* Get the controller blueprint archive from CSAR package.
*
* @param csarArchivePath The path where CSAR archive is stored.
- * @param cbaArchivePath The destination path where CBA will be stored.
+ * @param cbaArchivePath The destination path where CBA will be stored.
*/
void extractBluePrint(String csarArchivePath, String cbaArchivePath);
/**
* Store the Zip file into CDS database.
*
- * @param path path where zip file exists.
+ * @param path path where zip file exists.
* @param managedChannel To access the blueprint processor application end point
*/
- void saveBluePrintToCdsDatabase(Path path, ManagedChannel managedChannel);
+ void saveBluePrintToCdsDatabase(Path path, ManagedChannel managedChannel);
/**
* Extract and store the csar package to local disk.
*
- * @param result - IDistributionClientDownloadResult contains payload.
+ * @param result - IDistributionClientDownloadResult contains payload.
* @param csarArchivePath The destination path where CSAR will be stored.
*/
void extractCsarAndStore(IDistributionClientDownloadResult result, Path csarArchivePath);
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.service;
import com.google.protobuf.ByteString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
-import java.io.*;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
if (validPathCount == 0) {
LOGGER
- .info("CBA archive doesn't exist in the CSAR Package or it doesn't exist as per the given path {}",
- CBA_ZIP_PATH);
+ .info("CBA archive doesn't exist in the CSAR Package or it doesn't exist as per the given path {}",
+ CBA_ZIP_PATH);
listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null,
- artifactUrl, SDC_LISTENER_COMPONENT);
+ artifactUrl, SDC_LISTENER_COMPONENT);
}
} catch (Exception e) {
final String errorMessage = format("Failed to extract blueprint %s", e.getMessage());
listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage,
- artifactUrl, SDC_LISTENER_COMPONENT);
+ artifactUrl, SDC_LISTENER_COMPONENT);
LOGGER.error(errorMessage);
}
}
File targetZipFile = new File(targetLocation.toString());
try {
- if (! targetZipFile.createNewFile()) {
+ if (!targetZipFile.createNewFile()) {
LOGGER.warn("Overwriting zip file {}", targetLocation);
}
} catch (IOException e) {
}
try (InputStream inputStream = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(
- targetZipFile)) {
+ targetZipFile)) {
IOUtils.copy(inputStream, out);
LOGGER.info("Successfully store the CBA archive {} at this location", targetZipFile);
} catch (Exception e) {
if (responseStatus.getCode() != SUCCESS_CODE) {
final String errorMessage = format("Failed to store the CBA archive into CDS DB due to %s",
- responseStatus.getErrorMessage());
+ responseStatus.getErrorMessage());
listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage, artifactUrl,
- SDC_LISTENER_COMPONENT);
+ SDC_LISTENER_COMPONENT);
LOGGER.error(errorMessage);
} else {
LOGGER.info(responseStatus.getMessage());
listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null, artifactUrl,
- SDC_LISTENER_COMPONENT);
+ SDC_LISTENER_COMPONENT);
}
} catch (Exception e) {
final String errorMessage = format("Failure due to %s", e.getMessage());
listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage, artifactUrl,
- SDC_LISTENER_COMPONENT);
+ SDC_LISTENER_COMPONENT);
LOGGER.error(errorMessage);
}
});
private String getArtifactUrl() {
return sdcListenerDto.getArtifactUrl();
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.status;
import org.onap.sdc.api.consumer.IComponentDoneStatusMessage;
import org.onap.sdc.api.consumer.IDistributionStatusMessage;
import org.onap.sdc.utils.DistributionStatusEnum;
-public class ComponentStatusMessage implements IComponentDoneStatusMessage, IDistributionStatusMessage {
+public class ComponentStatusMessage implements IComponentDoneStatusMessage, IDistributionStatusMessage {
private String componentName;
public void setArtifactUrl(String artifactUrl) {
this.artifactUrl = artifactUrl;
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.status;
-import static org.onap.sdc.utils.DistributionActionResultEnum.SUCCESS;
-import java.util.Objects;
import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto;
import org.onap.ccsdk.cds.sdclistener.util.BuilderUtil;
import org.onap.sdc.api.IDistributionClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
+import java.util.Objects;
+
+import static org.onap.sdc.utils.DistributionActionResultEnum.SUCCESS;
+
@Component
@ConfigurationProperties("listenerservice")
@ComponentScan("org.onap.ccsdk.cds.cdssdclistener.dto")
@Autowired
private SdcListenerDto sdcListenerDto;
+
public enum NotificationType {
- DOWNLOAD, SDC_LISTENER_COMPONENT;
+ DOWNLOAD,
+ SDC_LISTENER_COMPONENT;
}
/**
* Send the component status back to SDC.
+ *
* @param distributionID SDC Distribution ID
- * @param status Distribution status
- * @param errorReason Reason of failure if present
- * @param url Artifact URL
- * @param type - NotificationType(Download or Component)
+ * @param status Distribution status
+ * @param errorReason Reason of failure if present
+ * @param url Artifact URL
+ * @param type - NotificationType(Download or Component)
*/
public void sendResponseBackToSdc(String distributionID, DistributionStatusEnum status, String errorReason,
- String url, NotificationType type) {
+ String url, NotificationType type) {
final IDistributionClient distributionClient = sdcListenerDto.getDistributionClient();
switch (type) {
case SDC_LISTENER_COMPONENT:
IComponentDoneStatusMessage componentStatusMessage = buildStatusMessage(distributionID, status, url,
- COMPONENT_NAME);
+ COMPONENT_NAME);
if (errorReason == null) {
checkResponseStatusFromSdc(distributionClient.sendComponentDoneStatus(componentStatusMessage));
} else {
checkResponseStatusFromSdc(
- distributionClient.sendComponentDoneStatus(componentStatusMessage, errorReason));
+ distributionClient.sendComponentDoneStatus(componentStatusMessage, errorReason));
}
break;
case DOWNLOAD:
IDistributionStatusMessage downloadStatusMessage = buildStatusMessage(distributionID, status, url,
- null);
+ null);
if (errorReason == null) {
checkResponseStatusFromSdc(distributionClient.sendDownloadStatus(downloadStatusMessage));
} else {
checkResponseStatusFromSdc(
- distributionClient.sendDownloadStatus(downloadStatusMessage, errorReason));
+ distributionClient.sendDownloadStatus(downloadStatusMessage, errorReason));
}
default:
break;
}
private ComponentStatusMessage buildStatusMessage(String distributionId, DistributionStatusEnum status, String url,
- String componentName) {
+ String componentName) {
return new BuilderUtil<>(new ComponentStatusMessage()).build(builder -> {
builder.setDistributionID(distributionId);
builder.setStatus(status);
private void checkResponseStatusFromSdc(IDistributionClientResult result) {
if (!Objects.equals(result.getDistributionActionResult(), SUCCESS)) {
LOGGER.error("SDC failed to receive the response from cds-sdc listener due to {}",
- result.getDistributionMessageResult());
+ result.getDistributionMessageResult());
} else {
LOGGER.info("SDC successfully received the response");
}
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.util;
import java.util.function.Consumer;
public T create() {
return object;
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.util;
import org.apache.commons.io.FileUtils;
* Extract files from the given path
*
* @param path where files reside.
+ *
* @return list of files.
*/
public static List<File> getFilesFromDisk(Path path) {
try (Stream<Path> fileTree = walk(path)) {
// Get the list of files from the path
- return fileTree.filter(Files::isRegularFile)
- .map(Path::toFile)
- .collect(Collectors.toList());
+ return fileTree.filter(Files :: isRegularFile)
+ .map(Path :: toFile)
+ .collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to find the file due to", e);
}
return new ArrayList<>();
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener;
-import mockit.*;
+import mockit.Expectations;
+import mockit.Injectable;
+import mockit.Mock;
+import mockit.MockUp;
+import mockit.Tested;
+import mockit.VerificationsInOrder;
import mockit.integration.junit4.JMockit;
import org.junit.Test;
import org.junit.runner.RunWith;
@Test
public void testInitCdsClientSuccesfully(@Injectable IDistributionClient distributionClient,
- @Injectable SdcListenerConfiguration configuration,
- @Injectable SdcListenerNotificationCallback notification,
- @Injectable SdcListenerDto sdcListenerDto) throws SdcListenerException {
+ @Injectable SdcListenerConfiguration configuration,
+ @Injectable SdcListenerNotificationCallback notification,
+ @Injectable SdcListenerDto sdcListenerDto) throws SdcListenerException {
- //Arrange
+ //Arrange
new MockUp<DistributionClientFactory>() {
@Mock
public IDistributionClient createDistributionClient() {
public IDistributionClientResult getResult() {
return new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS,
- DistributionActionResultEnum.SUCCESS.name());
+ DistributionActionResultEnum.SUCCESS.name());
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener;
-import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
+import static org.junit.Assert.assertEquals;
+
@RunWith(SpringRunner.class)
@EnableConfigurationProperties(SdcListenerConfiguration.class)
@SpringBootTest(classes = {SdcListenerConfigurationTest.class})
assertEquals(listenerConfiguration.getConsumerID(), "cds-id-local");
assertEquals(listenerConfiguration.activateServerTLSAuth(), false);
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.handler;
import com.google.protobuf.ByteString;
byte[] bytes = FileUtils.readFileToByteArray(file);
FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build();
-
return BluePrintUploadInput.newBuilder()
.setCommonHeader(CommonHeader.newBuilder()
.setRequestId(UUID.randomUUID().toString())
.setStatus(Status.newBuilder().setMessage(SUCCESS_MSG).setCode(200).build())
.build();
}
+
}
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.sdclistener.service;
import org.apache.commons.io.FileUtils;
@RunWith(SpringRunner.class)
@EnableConfigurationProperties({SdcListenerAuthClientInterceptor.class,
- BluePrintProcesssorHandler.class, SdcListenerDto.class, ListenerServiceImpl.class, SdcListenerStatus.class,
- SdcListenerConfiguration.class})
+ BluePrintProcesssorHandler.class, SdcListenerDto.class, ListenerServiceImpl.class, SdcListenerStatus.class,
+ SdcListenerConfiguration.class})
@SpringBootTest(classes = {ListenerServiceImplTest.class})
public class ListenerServiceImplTest {
private static final String DISTRIBUTION_ID = "1";
private static final String URL = "/sdc/v1/artifact";
-
private String csarArchivePath;
private Path tempDirectoryPath;
Mockito.when(listenerDto.getDistributionId()).thenReturn(DISTRIBUTION_ID);
Mockito.when(listenerDto.getArtifactUrl()).thenReturn(URL);
Mockito.doCallRealMethod().when(status)
- .sendResponseBackToSdc(DISTRIBUTION_ID, COMPONENT_DONE_OK, null, URL, SDC_LISTENER_COMPONENT);
+ .sendResponseBackToSdc(DISTRIBUTION_ID, COMPONENT_DONE_OK, null, URL, SDC_LISTENER_COMPONENT);
// Act
listenerService.extractBluePrint(WRONG_CSAR_SAMPLE, tempDirectoryPath.toString());
// Verify
Mockito.verify(status)
- .sendResponseBackToSdc(DISTRIBUTION_ID, COMPONENT_DONE_OK, null, URL, SDC_LISTENER_COMPONENT);
+ .sendResponseBackToSdc(DISTRIBUTION_ID, COMPONENT_DONE_OK, null, URL, SDC_LISTENER_COMPONENT);
}
@Test
- public void storeCsarArtifactToFileSuccessfully() throws IOException {
+ public void storeCsarArtifactToFileSuccessfully() throws IOException {
// Arrange
DistributionClientDownloadResultStubImpl resultStub = new DistributionClientDownloadResultStubImpl();
private String checkFileExists(Path path) throws IOException {
return Files.walk(path)
- .filter(Files::isRegularFile)
- .map(Path::toFile)
- .findAny()
- .get()
- .getName();
+ .filter(Files :: isRegularFile)
+ .map(Path :: toFile)
+ .findAny()
+ .get()
+ .getName();
}
public byte[] convertFileToByteArray(File file) {
}
public class DistributionClientDownloadResultStubImpl extends DistributionClientResultStubImpl implements
- IDistributionClientDownloadResult {
+ IDistributionClientDownloadResult {
public DistributionClientDownloadResultStubImpl() {
}
public String getArtifactFilename() {
return "MackArtifactName.csar";
}
+
}
+
}
</execution>
</executions>
</plugin>
+
+ <!-- Plugin to Format/Validate Kotlin Files -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <version>1.7</version>
+ <executions>
+ <execution>
+ <id>validate-kotlin</id>
+ <phase>validate</phase>
+ <configuration>
+ <target name="ktlint">
+ <java taskname="ktlint" dir="${project.basedir}" fork="true" failonerror="true"
+ classname="com.pinterest.ktlint.Main" classpathref="maven.plugin.classpath">
+ <arg value="src/**/*.kt"/>
+ </java>
+ </target>
+ <skip>${format.skipValidate}</skip>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+ <execution>
+ <!-- Built-in formatter So that you wouldn't have to fix all style violations by hand.-->
+ <id>format-kotlin</id>
+ <phase>process-sources</phase>
+ <configuration>
+ <target name="ktlint">
+ <java taskname="ktlint" dir="${project.basedir}" fork="true" failonerror="true"
+ classname="com.pinterest.ktlint.Main" classpathref="maven.plugin.classpath">
+ <arg value="-F"/>
+ <arg value="src/**/*.kt"/>
+ </java>
+ </target>
+ <skip>${format.skipExecute}</skip>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+ </executions>
+ <dependencies>
+ <dependency>
+ <groupId>com.pinterest</groupId>
+ <artifactId>ktlint</artifactId>
+ <version>0.35.0</version>
+ </dependency>
+ </dependencies>
+ </plugin>
</plugins>
</build>
<format.skipExecute>false</format.skipExecute>
</properties>
</profile>
+
</profiles>
</project>