Fix for Penetration test _ Session and cookie management
[vid.git] / vid-app-common / src / main / java / org / onap / vid / dal / AsyncInstantiationRepository.kt
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
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.vid.dal
22
23 import org.onap.portalsdk.core.domain.support.DomainVo
24 import org.onap.portalsdk.core.service.DataAccessService
25 import org.onap.vid.dao.JobRequest
26 import org.onap.vid.exceptions.GenericUncheckedException
27 import org.onap.vid.exceptions.NotFoundException
28 import org.onap.vid.job.Job
29 import org.onap.vid.model.JobAuditStatus
30 import org.onap.vid.model.ResourceInfo
31 import org.onap.vid.model.ServiceInfo
32 import org.onap.vid.model.serviceInstantiation.ServiceInstantiation
33 import org.onap.vid.utils.DaoUtils
34 import org.springframework.beans.factory.annotation.Autowired
35 import org.springframework.stereotype.Repository
36 import java.sql.Timestamp
37 import java.time.LocalDateTime
38 import java.util.*
39 import kotlin.collections.HashMap
40
41 @Repository
42 class AsyncInstantiationRepository @Autowired constructor(val dataAccessService:DataAccessService) {
43
44     fun addJobRequest(jobUuid: UUID, request:ServiceInstantiation) {
45         save(JobRequest(jobUuid, request))
46     }
47
48     fun getJobRequest(jobUuid: UUID):ServiceInstantiation? {
49         return getSingleItem(JobRequest::class.java, "JOB_ID", jobUuid).request
50     }
51
52     fun saveResourceInfo(resource:ResourceInfo) {
53         save(resource)
54     }
55
56     fun getResourceInfoByRootJobId(rootJobId: UUID): Map<String, ResourceInfo> {
57         val resourceInfoList:List<ResourceInfo> = getResultList(ResourceInfo::class.java, "ROOT_JOB_ID", rootJobId)
58
59         if (resourceInfoList.isEmpty()) {
60             throw GenericUncheckedException("Failed to retrieve resource info with rootJobId " + rootJobId + " from ResourceInfo table. no resource found")
61         }
62         return resourceInfoList.fold(HashMap(), { accumulator, item ->
63             accumulator.put(item.trackById, item); accumulator})
64     }
65
66     fun getResourceInfoByTrackId(trackById: String):ResourceInfo {
67         return getSingleItem(ResourceInfo::class.java, "TRACK_BY_ID", trackById)
68     }
69
70     fun saveServiceInfo(serviceInfo: ServiceInfo) {
71         save(serviceInfo)
72     }
73
74     fun getServiceInfoByJobId(jobUuid: UUID): ServiceInfo {
75         return getSingleItem(ServiceInfo::class.java, "jobId", jobUuid)
76     }
77
78     fun getServiceInfoByTemplateIdAndJobStatus(templateId: UUID, jobStatus: Job.JobStatus): List<ServiceInfo> {
79         return getResultList(ServiceInfo::class.java, mapOf("templateId" to templateId, "jobStatus" to jobStatus), "AND")
80     }
81
82     fun getAllServicesInfo(): List<ServiceInfo> {
83         return dataAccessService.getList(ServiceInfo::class.java, filterByCreationDateAndNotDeleted(), orderByCreatedDateAndStatus(), null) as List<ServiceInfo>
84     }
85
86     private fun filterByCreationDateAndNotDeleted(): String {
87         val minus3Months = LocalDateTime.now().minusMonths(3)
88         val filterDate = Timestamp.valueOf(minus3Months)
89         return filterServicesByNotHiddenAndNotDeleted() +
90                 "   and created >= '" + filterDate + "' "
91     }
92
93     private fun filterByInstantiateActionStatus(): String{
94         return filterServicesByNotHiddenAndNotDeleted() +
95                 " and ACTION  = 'INSTANTIATE'"
96     }
97
98     private fun filterInstantiatedServiceByServiceModelId(serviceModelUuid: UUID): String {
99         return filterByInstantiateActionStatus() +
100                 " and SERVICE_MODEL_ID = '$serviceModelUuid'"
101     }
102
103     private fun filterServicesByNotHiddenAndNotDeleted(): String {
104         return " WHERE" +
105                 "   hidden = false" +
106                 "   and deleted_at is null" // don't fetch deleted
107     }
108
109
110     private fun orderByCreatedDateAndStatus(): String {
111         return " createdBulkDate DESC ,\n" +
112                 "  (CASE jobStatus\n" +
113                 "   WHEN 'COMPLETED' THEN 0\n" +
114                 "   WHEN 'FAILED' THEN 0\n" +
115                 "   WHEN 'COMPLETED_WITH_ERRORS' THEN 0\n" +
116                 "   WHEN 'IN_PROGRESS' THEN 1\n" +
117                 "   WHEN 'PAUSE' THEN 2\n" +
118                 "   WHEN 'PENDING' THEN 3\n" +
119                 "   WHEN 'STOPPED' THEN 3 END),\n" +
120                 "  statusModifiedDate "
121     }
122
123     fun getAuditStatuses(jobUUID: UUID, source: JobAuditStatus.SourceStatus): List<JobAuditStatus> {
124         // order by ORDINAL.
125         // CREATED_DATE is kept for backward compatibility: when all Ordinals are zero
126         return getResultList(JobAuditStatus::class.java, mapOf("SOURCE" to source, "JOB_ID" to jobUUID), "AND", " ORDINAL, CREATED_DATE ")
127     }
128
129     fun addJobAudiStatus(jobAuditStatus:JobAuditStatus) {
130         save(jobAuditStatus)
131     }
132
133     private fun <T: DomainVo> save(item:T) {
134         dataAccessService.saveDomainObject(item, DaoUtils.getPropsMap())
135     }
136
137     private fun <T> getSingleItem(className:Class<T>, filterKey:String, filterValue:Any): T {
138         val resultList:List<T> = getResultList(className, filterKey, filterValue)
139         if (resultList.size < 1) {
140             throw NotFoundException("Failed to retrieve $className with $filterKey $filterValue from table. no resource found")
141         }else if (resultList.size > 1) {
142             throw GenericUncheckedException("Failed to retrieve $className with $filterKey $filterValue from table. found more than 1 resources")
143         }
144         return resultList[0]
145     }
146
147     private fun <T> getResultList(className:Class<T>, filterKey:String, filterValue:Any): List<T> {
148         return getResultList(className, mapOf(filterKey to filterValue), "AND", null)
149     }
150
151     private fun <T> getResultList(className:Class<T>, filters: Map<String, Any>, conditionType: String): List<T> {
152         return getResultList(className, filters, conditionType, null)
153     }
154
155     private fun <T> getResultList(className:Class<T>, filters: Map<String, Any>, conditionType: String, orderBy: String?): List<T> {
156         var condition:String = filters
157                 .map{f -> f.key + " = '" + f.value + "'"}
158                 .joinToString(" $conditionType ")
159         return dataAccessService.getList(className, " WHERE $condition", orderBy, null) as List<T>
160     }
161
162     fun listInstantiatedServicesByServiceModelId(serviceModelId: UUID): List<ServiceInfo> =
163             dataAccessService.getList(ServiceInfo::class.java, filterInstantiatedServiceByServiceModelId(serviceModelId), orderByCreatedDateAndStatus(), null) as List<ServiceInfo>;
164
165     fun getAllTemplatesServiceModelIds(): Set<String> {
166         val allTemplatesServiceModelID: List<String> =
167             dataAccessService.executeQuery(
168                 "select distinct serviceModelId from ServiceInfo ${filterByInstantiateActionStatus()}",
169                 null) as List<String>
170         return allTemplatesServiceModelID.toHashSet()
171     }
172 }