Add internal modifiers to comply with new HvVesCustomRule
[dcaegen2/collectors/hv-ves.git] / sources / hv-collector-core / src / main / kotlin / org / onap / dcae / collectors / veshv / impl / HeaderValidator.kt
1 /*
2  * ============LICENSE_START=======================================================
3  * dcaegen2-collectors-veshv
4  * ================================================================================
5  * Copyright (C) 2018 NOKIA
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.dcae.collectors.veshv.impl
22
23 import arrow.core.Either
24 import arrow.data.Nel
25 import arrow.data.NonEmptyList
26 import com.google.protobuf.Descriptors
27 import org.onap.dcae.collectors.veshv.domain.headerRequiredFieldDescriptors
28 import org.onap.dcae.collectors.veshv.domain.vesEventListenerVersionRegex
29 import org.onap.ves.VesEventOuterClass.CommonEventHeader
30
31 internal typealias Validator = (CommonEventHeader) -> List<ValidationError>
32
33 internal object HeaderValidator {
34     private val validators = (listOf(validateEventListenerVersion()) +
35             headerRequiredFieldDescriptors.map { fieldDescriptor ->
36                 validateRequiredField(fieldDescriptor)
37             })
38
39
40     fun validate(header: CommonEventHeader): Either<Nel<ValidationError>, CommonEventHeader> {
41         val result: List<ValidationError> = validators.flatMap { it(header) }
42
43         return Either.cond(result.isEmpty(), { header }, { NonEmptyList.fromListUnsafe(result) })
44     }
45
46     private fun validateEventListenerVersion(): Validator = { header: CommonEventHeader ->
47         if (!vesEventListenerVersionRegex.matches(header.vesEventListenerVersion))
48             listOf(ValidationError.VersionMismatch(header.vesEventListenerVersion))
49         else
50             emptyList()
51     }
52
53     private fun validateRequiredField(requiredField: Descriptors.FieldDescriptor): Validator =
54         { header: CommonEventHeader ->
55             if (!header.hasField(requiredField))
56                 listOf(ValidationError.MissingField(requiredField.name))
57             else
58                 emptyList()
59         }
60 }