Merge from ECOMP's repository
[vid.git] / vid-app-common / src / main / java / org / onap / vid / job / command / WatchChildrenJobsBL.kt
1 package org.onap.vid.job.command
2
3 import org.apache.commons.lang3.StringUtils
4 import org.onap.portalsdk.core.service.DataAccessService
5 import org.onap.vid.job.Job
6 import org.onap.vid.job.Job.JobStatus.*
7 import org.onap.vid.job.impl.JobDaoImpl
8 import org.onap.vid.utils.DaoUtils
9 import org.springframework.beans.factory.annotation.Autowired
10 import org.springframework.stereotype.Service
11 import java.util.*
12 import java.util.stream.Collectors
13 import java.util.stream.Stream
14
15
16 @Service
17 class WatchChildrenJobsBL @Autowired
18 constructor(private val dataAccessService: DataAccessService) {
19
20     fun retrieveChildrenJobsStatus(childrenJobsIds: List<String>): Job.JobStatus {
21         val jobs = getAllChildrenJobs(childrenJobsIds)
22
23         val jobsStatuses = childrenJobsIds.stream()
24                 .map<JobDaoImpl> { jobId -> jobs[UUID.fromString(jobId)] }
25                 .map {when {
26                     (it == null || it.status == null) -> Job.JobStatus.FAILED
27                     else -> it.status
28                 }}
29
30         return cumulateJobStatus(jobsStatuses)
31
32     }
33
34     fun cumulateJobStatus(childrenComulatedStatus: Job.JobStatus, fatherJobStatus: Job.JobStatus): Job.JobStatus {
35         return cumulateJobStatus(Stream.of(childrenComulatedStatus, fatherJobStatus))
36     }
37
38     private fun cumulateJobStatus(jobsStatuses: Stream<Job.JobStatus>): Job.JobStatus {
39
40         return jobsStatuses.reduce{ a, b ->
41             when {
42                 !a.isFinal || !b.isFinal -> IN_PROGRESS
43                 a == COMPLETED_WITH_ERRORS || b == COMPLETED_WITH_ERRORS-> COMPLETED_WITH_ERRORS
44                 a == COMPLETED && b.isFailure -> COMPLETED_WITH_ERRORS
45                 b == COMPLETED && a.isFailure -> COMPLETED_WITH_ERRORS
46                 a == COMPLETED || b == COMPLETED -> COMPLETED
47                 a.isFailure || b.isFailure -> FAILED
48                 else ->  COMPLETED_WITH_NO_ACTION
49             }
50         } .orElse(COMPLETED_WITH_NO_ACTION)
51   }
52
53     private fun getAllChildrenJobs(childrenJobsIds: List<String>): Map<UUID, JobDaoImpl> {
54         val jobs:MutableList<JobDaoImpl> = dataAccessService.getList(JobDaoImpl::class.java, filterByJobIds(childrenJobsIds), null, DaoUtils.getPropsMap()) as MutableList<JobDaoImpl>
55         return jobs.stream().collect(Collectors.toMap( { it.uuid }, { it }))
56     }
57
58     private fun filterByJobIds(childrenJobsIds: List<String>): String {
59         return " WHERE JOB_ID IN('" + StringUtils.join(childrenJobsIds, "', '") + "')"
60     }
61 }