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