Include impacted changes for APPC-346,APPC-348
[appc.git] / appc-dispatcher / appc-request-handler / appc-request-handler-core / src / main / java / org / onap / appc / validationpolicy / RequestValidationPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.validationpolicy;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.fasterxml.jackson.databind.DeserializationFeature;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import org.apache.commons.lang.StringUtils;
32 import org.onap.appc.domainmodel.lcm.VNFOperation;
33 import org.onap.appc.validationpolicy.executors.ActionInProgressRuleExecutor;
34 import org.onap.appc.validationpolicy.executors.RuleExecutor;
35 import org.onap.appc.validationpolicy.objects.Policy;
36 import org.onap.appc.validationpolicy.objects.PolicyNames;
37 import org.onap.appc.validationpolicy.objects.Rule;
38 import org.onap.appc.validationpolicy.objects.ValidationJSON;
39 import org.onap.appc.validationpolicy.rules.RuleFactory;
40 import org.onap.ccsdk.sli.core.dblib.DbLibService;
41
42 import javax.sql.rowset.CachedRowSet;
43 import java.sql.SQLException;
44 import java.util.ArrayList;
45 import java.util.Collections;
46 import java.util.HashMap;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Set;
50 import java.util.stream.Collectors;
51
52 /**
53  * Reads the request validation policy on start-up and provides
54  *  accessors for rule executors
55  */
56 public class RequestValidationPolicy {
57
58     private DbLibService dbLibService;
59
60     private RuleExecutor actionInProgressRuleExecutor;
61
62     private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidationPolicy.class);
63
64     public void setDbLibService(DbLibService dbLibService) {
65         this.dbLibService = dbLibService;
66     }
67
68     public void initialize(){
69         try {
70             String jsonContent = getPolicyJson();
71             if (jsonContent == null) return;
72
73             ObjectMapper objectMapper = new ObjectMapper();
74             objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
75             ValidationJSON validationJSON = objectMapper.readValue(jsonContent, ValidationJSON.class);
76             List<Policy> policyList = validationJSON.getPolicies();
77             policyList.stream()
78                     .filter(policy -> PolicyNames.ActionInProgress.name().equals(policy.getPolicyName()))
79                     .forEach(policy -> {
80                 Rule[] ruleDTOs = policy.getRules();
81                 Map<String, org.onap.appc.validationpolicy.rules.Rule> rules = new HashMap<>();
82                 for(Rule ruleDTO : ruleDTOs) {
83                     String action = ruleDTO.getActionReceived();
84                     String validationRule = ruleDTO.getValidationRule();
85                     Set<VNFOperation> inclusionSet = null;
86                     Set<VNFOperation> exclusionSet = null;
87                     if (ruleDTO.getInclusionList() != null && !ruleDTO.getInclusionList().isEmpty()) {
88                         inclusionSet = ruleDTO.getInclusionList().stream()
89                                 .map(VNFOperation::findByString).filter(operation -> operation!=null)
90                                 .collect(Collectors.toSet());
91                     }
92                     if (ruleDTO.getExclusionList() != null && !ruleDTO.getExclusionList().isEmpty()) {
93                         exclusionSet = ruleDTO.getExclusionList().stream()
94                                 .map(VNFOperation::findByString).filter(operation -> operation!=null)
95                                 .collect(Collectors.toSet());
96                     }
97                     org.onap.appc.validationpolicy.rules.Rule rule = RuleFactory
98                             .createRule(validationRule, inclusionSet, exclusionSet);
99                     rules.put(action, rule);
100                 }
101                 actionInProgressRuleExecutor = new ActionInProgressRuleExecutor(Collections.unmodifiableMap(rules));
102             });
103         } catch (Exception e) {
104             logger.error("Error reading request validation policies",e);
105         }
106     }
107
108     protected String getPolicyJson() {
109         String schema = "sdnctl";
110         String query = "SELECT MAX(INTERNAL_VERSION),ARTIFACT_CONTENT " +
111                        "FROM ASDC_ARTIFACTS " +
112                        "WHERE ARTIFACT_NAME = ? " +
113                        "GROUP BY ARTIFACT_NAME";
114         ArrayList<String> arguments = new ArrayList<>();
115         arguments.add("request_validation_policy");
116         String jsonContent =null;
117         try{
118             CachedRowSet rowSet = dbLibService.getData(query,arguments,schema);
119             if(rowSet.next()){
120                 jsonContent = rowSet.getString("ARTIFACT_CONTENT");
121             }
122             if(logger.isDebugEnabled()){
123                 logger.debug("request validation policy = " + jsonContent);
124             }
125             if(StringUtils.isBlank(jsonContent)){
126                 logger.warn("request validation policy not found in app-c database");
127             }
128         }
129         catch(SQLException e){
130             logger.error("Error accessing database",e);
131             throw new RuntimeException(e);
132         }
133         return jsonContent;
134     }
135
136     public RuleExecutor getInProgressRuleExecutor(){
137         if(actionInProgressRuleExecutor ==null){
138             throw new RuntimeException("Rule executor not available, initialization of RequestValidationPolicy failed");
139         }
140         return actionInProgressRuleExecutor;
141     }
142 }