2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.rest.util;
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.google.common.base.Splitter;
27 import com.google.common.base.Strings;
29 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
30 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
32 import java.io.ByteArrayInputStream;
33 import java.io.IOException;
34 import java.io.StringReader;
35 import java.nio.charset.StandardCharsets;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Iterator;
40 import java.util.LinkedHashMap;
41 import java.util.List;
43 import java.util.Map.Entry;
45 import javax.json.Json;
46 import javax.json.JsonException;
47 import javax.json.JsonObject;
48 import javax.json.JsonReader;
49 import javax.json.JsonValue;
51 import org.apache.commons.lang3.StringEscapeUtils;
52 import org.apache.commons.lang3.StringUtils;
53 import org.json.JSONArray;
54 import org.json.JSONObject;
55 import org.onap.policy.common.logging.flexlogger.FlexLogger;
56 import org.onap.policy.common.logging.flexlogger.Logger;
57 import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
58 import org.onap.policy.rest.adapter.ClosedLoopPMBody;
59 import org.onap.policy.rest.adapter.PolicyRestAdapter;
60 import org.onap.policy.rest.dao.CommonClassDao;
61 import org.onap.policy.rest.jpa.MicroServiceModels;
62 import org.onap.policy.rest.jpa.OptimizationModels;
63 import org.onap.policy.rest.jpa.SafePolicyWarning;
64 import org.onap.policy.utils.PolicyUtils;
65 import org.onap.policy.xacml.api.XACMLErrorConstants;
66 import org.onap.policy.xacml.util.XACMLPolicyScanner;
67 import org.springframework.beans.factory.annotation.Autowired;
68 import org.springframework.stereotype.Service;
72 public class PolicyValidation {
74 private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidation.class);
76 public static final String CONFIG_POLICY = "Config";
77 public static final String ACTION_POLICY = "Action";
78 public static final String DECISION_POLICY = "Decision";
79 public static final String DECISION_POLICY_MS = "Decision_MS";
80 public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
81 public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
82 public static final String ENFORCER_CONFIG_POLICY = "Enforcer Config";
83 public static final String MICROSERVICES = "Micro Service";
84 public static final String FIREWALL = "Firewall Config";
85 public static final String OPTIMIZATION="Optimization";
86 public static final String BRMSPARAM = "BRMS_Param";
87 public static final String BRMSRAW = "BRMS_Raw";
88 public static final String HTML_ITALICS_LNBREAK = "</i><br>";
89 public static final String SUCCESS = "success";
90 public static final String EMPTY_COMPONENT_ATTR =
91 "Component Attributes: One or more Fields in Component Attributes is Empty.";
92 public static final String ISREQUIRED = " is required";
93 public static final String SPACESINVALIDCHARS = " : value has spaces or invalid characters</i><br>";
94 private static final String REQUIRED_ATTRIBUTE = "required-true";
95 private static final String DECISION_MS_MODEL = "MicroService_Model";
96 private static final String RAW = "Raw";
98 private static Map<String, String> mapAttribute = new HashMap<>();
99 private static Map<String, String> jsonRequestMap = new HashMap<>();
100 private static List<String> modelRequiredFieldsList = new ArrayList<>();
101 private Set<String> allReqTrueKeys = new HashSet<>();
103 private static CommonClassDao commonClassDao;
106 public PolicyValidation(CommonClassDao commonClassDao) {
107 PolicyValidation.commonClassDao = commonClassDao;
111 * This is an empty constructor
113 public PolicyValidation() {
121 * @param policyData the policy data
122 * @return the string builder
123 * @throws IOException Signals that an I/O exception has occurred.
125 public StringBuilder validatePolicy(PolicyRestAdapter policyData) throws IOException {
127 boolean valid = true;
128 StringBuilder responseString = new StringBuilder();
129 ObjectMapper mapper = new ObjectMapper();
131 if (policyData.getPolicyName() != null) {
132 String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
133 if (!policyNameValidate.contains(SUCCESS)) {
134 responseString.append("<b>PolicyName</b>:<i>" + policyNameValidate + HTML_ITALICS_LNBREAK);
138 responseString.append("<b>PolicyName</b>: PolicyName Should not be empty" + HTML_ITALICS_LNBREAK);
141 if (policyData.getPolicyDescription() != null) {
142 String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
143 if (!descriptionValidate.contains(SUCCESS)) {
144 responseString.append("<b>Description</b>:<i>" + descriptionValidate + HTML_ITALICS_LNBREAK);
149 if (!"API".equals(policyData.getApiflag()) && policyData.getAttributes() != null
150 && !policyData.getAttributes().isEmpty()) {
151 for (Object attribute : policyData.getAttributes()) {
152 if (attribute instanceof LinkedHashMap<?, ?>) {
155 if (((LinkedHashMap<?, ?>) attribute).get("key") != null) {
156 key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
157 if (!PolicyUtils.policySpecialCharWithDashValidator(key).contains(SUCCESS)) {
158 responseString.append("<b>Attributes or Component Attributes</b>:<i>" + value
159 + SPACESINVALIDCHARS);
163 if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
164 if ("Base".equals(policyData.getConfigPolicyType())) {
166 .append("<b>Attributes</b>:<i> has one missing Attribute key</i><br>");
168 if (BRMSPARAM.equals(policyData.getConfigPolicyType())
169 || BRMSRAW.equals(policyData.getConfigPolicyType())) {
171 .append("<b>Rule Attributes</b>:<i> has one missing Attribute key</i><br>");
174 responseString.append(
175 "<b>Component Attributes</b>:<i> has one missing Component Attribute key</i><br>");
179 if (((LinkedHashMap<?, ?>) attribute).get("value") != null) {
180 value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
181 if (!PolicyUtils.policySpecialCharWithDashValidator(value).contains(SUCCESS)) {
182 if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
183 if ("Base".equals(policyData.getConfigPolicyType())) {
184 responseString.append("<b>Attributes</b>:<i>" + value
185 + SPACESINVALIDCHARS);
187 if (BRMSPARAM.equals(policyData.getConfigPolicyType())
188 || BRMSRAW.equals(policyData.getConfigPolicyType())) {
189 responseString.append("<b>Rule Attributes</b>:<i>" + value
190 + SPACESINVALIDCHARS);
193 responseString.append("<b>Component Attributes</b>:<i>" + value
194 + SPACESINVALIDCHARS);
199 if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
200 if ("Base".equals(policyData.getConfigPolicyType())) {
202 .append("<b>Attributes</b>:<i> has one missing Attribute value</i><br>");
204 if (BRMSPARAM.equals(policyData.getConfigPolicyType())
205 || BRMSRAW.equals(policyData.getConfigPolicyType())) {
206 responseString.append(
207 "<b>Rule Attributes</b>:<i> has one missing Attribute value</i><br>");
210 responseString.append(
211 "<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>");
219 // Decision Policy Attributes Validation
220 if (!"API".equals(policyData.getApiflag()) && policyData.getSettings() != null
221 && !policyData.getSettings().isEmpty()) {
222 for (Object attribute : policyData.getAttributes()) {
223 if (attribute instanceof LinkedHashMap<?, ?>) {
225 if (((LinkedHashMap<?, ?>) attribute).get("key") == null) {
227 .append("<b>Settings Attributes</b>:<i> has one missing Attribute key</i><br>");
230 if (((LinkedHashMap<?, ?>) attribute).get("value") != null) {
231 value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
232 if (!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)) {
233 responseString.append("<b>Settings Attributes</b>:<i>" + value
234 + SPACESINVALIDCHARS);
239 .append("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>");
246 if (!"API".equals(policyData.getApiflag()) && policyData.getRuleAlgorithmschoices() != null
247 && !policyData.getRuleAlgorithmschoices().isEmpty()) {
248 for (Object attribute : policyData.getRuleAlgorithmschoices()) {
249 if (attribute instanceof LinkedHashMap<?, ?>) {
250 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
251 if (((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1") == null) {
252 responseString.append(
253 "<b>Rule Algorithms</b>:<i>" + label + " : Field 1 value is not selected</i><br>");
256 if (((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo") == null) {
257 responseString.append(
258 "<b>Rule Algorithms</b>:<i>" + label + " : Field 2 value is not selected</i><br>");
261 if (((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2") != null) {
263 ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
264 if (!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)) {
265 responseString.append("<b>Rule Algorithms</b>:<i>" + label
266 + " : Field 3 value has special characters</i><br>");
271 .append("<b>Rule Algorithms</b>:<i>" + label + " : Field 3 value is empty</i><br>");
278 if (CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())) {
279 if ("Base".equals(policyData.getConfigPolicyType())
280 || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType())
281 || CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType())
282 || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType())
283 || MICROSERVICES.equals(policyData.getConfigPolicyType())
284 || OPTIMIZATION.equals(policyData.getConfigPolicyType())) {
286 if (!Strings.isNullOrEmpty(policyData.getOnapName())) {
287 String onapNameValidate = PolicyUtils.policySpecialCharWithDashValidator(policyData.getOnapName());
288 if (!onapNameValidate.contains(SUCCESS)) {
289 responseString.append("<b>OnapName</b>:<i>" + onapNameValidate + HTML_ITALICS_LNBREAK);
293 responseString.append("<b>Onap Name</b>: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
298 if (!Strings.isNullOrEmpty(policyData.getRiskType())) {
299 String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType());
300 if (!riskTypeValidate.contains(SUCCESS)) {
301 responseString.append("<b>RiskType</b>:<i>" + riskTypeValidate + HTML_ITALICS_LNBREAK);
305 responseString.append("<b>RiskType</b>: Risk Type Should not be Empty" + HTML_ITALICS_LNBREAK);
309 if (!Strings.isNullOrEmpty(policyData.getRiskLevel())) {
310 String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel());
311 if (!validateRiskLevel.contains(SUCCESS)) {
312 responseString.append("<b>RiskLevel</b>:<i>" + validateRiskLevel + HTML_ITALICS_LNBREAK);
316 responseString.append("<b>RiskLevel</b>: Risk Level Should not be Empty" + HTML_ITALICS_LNBREAK);
320 if (!Strings.isNullOrEmpty(policyData.getGuard())) {
321 String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard());
322 if (!validateGuard.contains(SUCCESS)) {
323 responseString.append("<b>Guard</b>:<i>" + validateGuard + HTML_ITALICS_LNBREAK);
327 responseString.append("<b>Guard</b>: Guard Value Should not be Empty" + HTML_ITALICS_LNBREAK);
331 // Validate Config Base Policy Data
332 if ("Base".equalsIgnoreCase(policyData.getConfigPolicyType())) {
333 if (!Strings.isNullOrEmpty(policyData.getConfigName())) {
334 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
335 if (!configNameValidate.contains(SUCCESS)) {
336 responseString.append("ConfigName:" + configNameValidate + HTML_ITALICS_LNBREAK);
340 responseString.append("Config Name: Config Name Should not be Empty" + HTML_ITALICS_LNBREAK);
343 if (!Strings.isNullOrEmpty(policyData.getConfigType())) {
344 String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType());
345 if (!configTypeValidate.contains(SUCCESS)) {
346 responseString.append("ConfigType:" + configTypeValidate + HTML_ITALICS_LNBREAK);
350 responseString.append("Config Type: Config Type Should not be Empty" + HTML_ITALICS_LNBREAK);
353 if (!Strings.isNullOrEmpty(policyData.getConfigBodyData())) {
354 String configBodyData = policyData.getConfigBodyData();
355 String configType = policyData.getConfigType();
356 if (configType != null) {
357 if ("JSON".equals(configType)) {
358 if (!PolicyUtils.isJSONValid(configBodyData)) {
360 .append("Config Body: JSON Content is not valid" + HTML_ITALICS_LNBREAK);
363 } else if ("XML".equals(configType)) {
364 if (!PolicyUtils.isXMLValid(configBodyData)) {
365 responseString.append(
366 "Config Body: XML Content data is not valid" + HTML_ITALICS_LNBREAK);
369 } else if ("PROPERTIES".equals(configType)) {
370 if (!PolicyUtils.isPropValid(configBodyData) || "".equals(configBodyData)) {
372 .append("Config Body: Property data is not valid" + HTML_ITALICS_LNBREAK);
375 } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) {
377 .append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
382 responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
386 // Validate Config Firewall Policy Data
387 if (FIREWALL.equalsIgnoreCase(policyData.getConfigPolicyType())) {
388 if (policyData.getConfigName() != null && !policyData.getConfigName().isEmpty()) {
389 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
390 if (!configNameValidate.contains(SUCCESS)) {
391 responseString.append("<b>ConfigName</b>:<i>" + configNameValidate + HTML_ITALICS_LNBREAK);
395 responseString.append("<b>Config Name</b>:<i> Config Name is required" + HTML_ITALICS_LNBREAK);
398 if (policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()) {
400 .append("<b>Security Zone</b>:<i> Security Zone is required" + HTML_ITALICS_LNBREAK);
404 // Validate BRMS_Param Policy Data
405 if (BRMSPARAM.equalsIgnoreCase(policyData.getConfigPolicyType())
406 && Strings.isNullOrEmpty(policyData.getRuleName())) {
407 responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required" + HTML_ITALICS_LNBREAK);
410 // Validate BRMS_Raw Policy Data
411 if (BRMSRAW.equalsIgnoreCase(policyData.getConfigPolicyType())) {
412 if (policyData.getConfigBodyData() != null && !policyData.getConfigBodyData().isEmpty()) {
413 String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
415 // If there are any error other than Annotations then this is not Valid
416 if (message.contains("[ERR")) {
417 responseString.append(
418 "<b>Raw Rule Validate</b>:<i>Raw Rule has error" + message + HTML_ITALICS_LNBREAK);
422 responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required" + HTML_ITALICS_LNBREAK);
426 // Validate ClosedLoop_PM Policy Data
427 if (CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())) {
429 if (Strings.isNullOrEmpty(
430 policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())) {
431 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required"
432 + HTML_ITALICS_LNBREAK);
436 } catch (Exception e) {
437 LOGGER.error("ERROR in ClosedLoop_PM PolicyName", e);
438 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required"
439 + HTML_ITALICS_LNBREAK);
443 if (policyData.getJsonBody() != null) {
445 ClosedLoopPMBody pmBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopPMBody.class);
446 if (pmBody.getEmailAddress() != null) {
447 String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
448 if (result != SUCCESS) {
449 responseString.append(result + HTML_ITALICS_LNBREAK);
453 if ((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS()
454 || pmBody.isvUSP()) != true) {
456 .append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services"
457 + HTML_ITALICS_LNBREAK);
460 if (pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()) {
461 String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
462 if (!result.contains(SUCCESS)) {
463 responseString.append("<b>GeoLink</b>:<i>" + result + HTML_ITALICS_LNBREAK);
467 if (pmBody.getAttributes() != null && !pmBody.getAttributes().isEmpty()) {
468 for (Entry<String, String> entry : pmBody.getAttributes().entrySet()) {
469 String key = entry.getKey();
470 String value = entry.getValue();
471 if (!key.contains("Message")) {
472 String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
473 if (!attributeValidate.contains(SUCCESS)) {
474 responseString.append("<b>Attributes</b>:<i>" + key
475 + " : value has spaces or invalid characters" + HTML_ITALICS_LNBREAK);
483 .append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services"
484 + HTML_ITALICS_LNBREAK);
488 if (CLOSEDLOOP_POLICY.equalsIgnoreCase(policyData.getConfigPolicyType())) {
489 if (policyData.getJsonBody() != null) {
491 // For API we need to get the conditions key from the Json request and check it before
492 // deserializing to POJO due to the enum
493 if ("API".equals(policyData.getApiflag())) {
494 JSONObject json = new JSONObject(policyData.getJsonBody());
495 if (!json.isNull("conditions")) {
496 String apiCondition = (String) json.get("conditions");
497 if (Strings.isNullOrEmpty(apiCondition)) {
498 responseString.append("<b>Conditions</b>: <i>Select At least one Condition"
499 + HTML_ITALICS_LNBREAK);
500 return responseString;
504 .append("<b>Conditions</b>: <i>There were no conditions provided in configBody json"
505 + HTML_ITALICS_LNBREAK);
506 return responseString;
509 if (policyData.getTrapDatas().getTrap1() != null) {
510 if (policyData.getClearTimeOut() == null) {
511 responseString.append(
512 "<b>Trigger Clear TimeOut</b>: <i>Trigger Clear TimeOut is required when atleast One Trigger Signature is enabled</i><br>");
515 if (policyData.getTrapMaxAge() == null) {
516 responseString.append(
517 "<b>Trap Max Age</b>: <i>Trap Max Age is required when atleast One Trigger Signature is enabled</i><br>");
521 if (policyData.getFaultDatas().getTrap1() != null
522 && policyData.getVerificationclearTimeOut() == null) {
523 responseString.append(
524 "<b>Fault Clear TimeOut</b>: <i>Fault Clear TimeOut is required when atleast One Fault Signature is enabled</i><br>");
529 ClosedLoopFaultBody faultBody =
530 mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class);
531 if (faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()) {
532 String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
533 if (!SUCCESS.equals(result)) {
534 responseString.append(result + HTML_ITALICS_LNBREAK);
538 if (!(faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS()
539 || faultBody.isvUSP())) {
541 .append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services"
542 + HTML_ITALICS_LNBREAK);
545 if (faultBody.getActions() == null || faultBody.getActions().isEmpty()) {
547 .append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
550 if (faultBody.getClosedLoopPolicyStatus() == null
551 || faultBody.getClosedLoopPolicyStatus().isEmpty()) {
552 responseString.append(
553 "<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
556 if (faultBody.getConditions() == null) {
557 responseString.append(
558 "<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
561 if (faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()) {
562 String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
563 if (!result.contains(SUCCESS)) {
564 responseString.append("<b>GeoLink</b>:<i>" + result + HTML_ITALICS_LNBREAK);
568 if (faultBody.getAgingWindow() == 0) {
570 .append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
573 if (faultBody.getTimeInterval() == 0) {
574 responseString.append(
575 "<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
578 if (faultBody.getRetrys() == 0) {
579 responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required"
580 + HTML_ITALICS_LNBREAK);
583 if (faultBody.getTimeOutvPRO() == 0) {
584 responseString.append(
585 "<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
588 if (faultBody.getTimeOutRuby() == 0) {
590 .append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
593 if (faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()) {
594 responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
599 .append("<b>D2/Virtualized Services</b>: <i>Select atleast one D2/Virtualized Services"
600 + HTML_ITALICS_LNBREAK);
602 .append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
604 .append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
606 .append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
608 .append("<b>Conditions</b>: <i>Select Atleast one Condition" + HTML_ITALICS_LNBREAK);
609 responseString.append("<b>PEP Name</b>: <i>PEP Name is required" + HTML_ITALICS_LNBREAK);
610 responseString.append("<b>PEP Action</b>: <i>PEP Action is required" + HTML_ITALICS_LNBREAK);
612 .append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
613 responseString.append(
614 "<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
616 .append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
617 responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
618 responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
623 if (MICROSERVICES.equals(policyData.getConfigPolicyType())) {
624 boolean tmpValid = validateMsModel(policyData, responseString);
630 // Validate Optimization Policy Data
631 if (OPTIMIZATION.equals(policyData.getConfigPolicyType())){
633 if(!Strings.isNullOrEmpty(policyData.getServiceType())){
635 modelRequiredFieldsList.clear();
636 pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
640 if (policyData.getServiceType().contains("-v")){
641 service = policyData.getServiceType().split("-v")[0];
642 version = policyData.getServiceType().split("-v")[1];
644 service = policyData.getServiceType();
645 version = policyData.getVersion();
648 if (!Strings.isNullOrEmpty(version)) {
649 OptimizationModels returnModel = getOptimizationModelData(service, version);
651 if (returnModel != null) {
653 String annotation = returnModel.getAnnotation();
654 String refAttributes = returnModel.getRefattributes();
655 String subAttributes = returnModel.getSubattributes();
656 String modelAttributes = returnModel.getAttributes();
658 if (!Strings.isNullOrEmpty(annotation)) {
659 Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=")
661 for (Entry<String, String> rMap : rangeMap.entrySet()) {
662 if (rMap.getValue().contains("range::")) {
663 String value = mapAttribute.get(rMap.getKey().trim());
664 String[] tempString = rMap.getValue().split("::")[1].split("-");
665 int startNum = Integer.parseInt(tempString[0]);
666 int endNum = Integer.parseInt(tempString[1]);
667 String returnString = "InvalidreturnModel Range:" + rMap.getKey()
668 + " must be between " + startNum + " - " + endNum + ",";
671 if (PolicyUtils.isInteger(value.replace("\"", ""))) {
672 int result = Integer.parseInt(value.replace("\"", ""));
673 if (result < startNum || result > endNum) {
674 responseString.append(returnString);
678 responseString.append(returnString);
682 responseString.append("<b>" + rMap.getKey() + "</b>:<i>" + rMap.getKey()
683 + " is required for the Optimization model " + service
684 + HTML_ITALICS_LNBREAK);
692 // If request comes from the API we need to validate required fields in the
693 // Micro Service Model
694 // GUI request are already validated from the SDK-APP
695 if ("API".equals(policyData.getApiflag())) {
696 // get list of required fields from the sub_Attributes of the Model
697 if (!Strings.isNullOrEmpty(subAttributes)) {
698 JsonObject subAttributesJson = stringToJsonObject(subAttributes);
699 findRequiredFields(subAttributesJson);
702 // get list of required fields from the attributes of the Model
703 if (!Strings.isNullOrEmpty(modelAttributes)) {
704 Map<String, String> modelAttributesMap = null;
705 if (",".equals(modelAttributes.substring(modelAttributes.length() - 1))) {
706 String attributeString = modelAttributes.substring(0,
707 modelAttributes.length() - 1);
708 modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=")
709 .split(attributeString);
711 modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=")
712 .split(modelAttributes);
714 String json = new ObjectMapper().writeValueAsString(modelAttributesMap);
715 findRequiredFields(stringToJsonObject(json));
718 // get list of required fields from the ref_Attributes of the Model
719 if (!Strings.isNullOrEmpty(refAttributes)) {
720 Map<String, String> refAttributesMap = null;
721 if (",".equals(refAttributes.substring(refAttributes.length() - 1))) {
722 String attributesString = refAttributes.substring(0,
723 refAttributes.length() - 1);
724 refAttributesMap = Splitter.on(",").withKeyValueSeparator("=")
725 .split(attributesString);
727 refAttributesMap = Splitter.on(",").withKeyValueSeparator("=")
728 .split(modelAttributes);
730 String json = new ObjectMapper().writeValueAsString(refAttributesMap);
731 findRequiredFields(stringToJsonObject(json));
734 if (modelRequiredFieldsList != null || !modelRequiredFieldsList.isEmpty()) {
735 // create jsonRequestMap with all json keys and values from request
736 JsonNode rootNode = (JsonNode) policyData.getPolicyJSON();
737 jsonRequestMap.clear();
738 pullModelJsonKeyPairs(rootNode);
740 // validate if the requiredFields are in the request
741 for (String requiredField : modelRequiredFieldsList) {
742 if (jsonRequestMap.containsKey(requiredField)) {
743 String value = jsonRequestMap.get(requiredField);
744 if (Strings.isNullOrEmpty(jsonRequestMap.get(requiredField))
745 || "\"\"".equals(value)
746 || "".equals(jsonRequestMap.get(requiredField))) {
747 responseString.append("<b>Optimization Service Model</b>:<i> "
748 + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
752 responseString.append("<b>Optimization Service Model</b>:<i> "
753 + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
761 .append("<b>Optimization Service Model</b>:<i> Invalid Model. The model name, "
762 + service + " of version, " + version
763 + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
767 responseString.append(
768 "<b>Optimization Service Version</b>:<i> Optimization Service Version is required"
769 + HTML_ITALICS_LNBREAK);
773 responseString.append("<b>Optimization Service</b>:<i> Optimization Service Model is required"
774 + HTML_ITALICS_LNBREAK);
778 if (Strings.isNullOrEmpty(policyData.getPriority())) {
779 responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
785 if ((DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType()))
786 || (DECISION_POLICY_MS.equalsIgnoreCase(policyData.getPolicyType()))) {
787 if (!RAW.equalsIgnoreCase(policyData.getRuleProvider())) {
788 if (!Strings.isNullOrEmpty(policyData.getOnapName())) {
789 String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
790 if (!onapNameValidate.contains(SUCCESS)) {
791 responseString.append("OnapName:" + onapNameValidate + HTML_ITALICS_LNBREAK);
795 responseString.append("Onap Name: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
799 if (RAW.equalsIgnoreCase(policyData.getRuleProvider())) {
800 Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils.unescapeXml(policyData.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
801 if (!(policy instanceof PolicySetType || policy instanceof PolicyType)) {
802 responseString.append("Raw XACML: The XACML Content is not valid" + HTML_ITALICS_LNBREAK);
807 if (DECISION_MS_MODEL.equals(policyData.getRuleProvider())) {
808 LOGGER.info("Validating Decision MS Policy - ");
809 boolean tmpValid = validateMsModel(policyData, responseString);
815 if ("Rainy_Day".equals(policyData.getRuleProvider())) {
816 if (policyData.getRainyday() == null) {
817 responseString.append("<b> Rainy Day Parameters are Required </b><br>");
820 if (Strings.isNullOrEmpty(policyData.getRainyday().getServiceType())) {
821 responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
824 if (Strings.isNullOrEmpty(policyData.getRainyday().getVnfType())) {
825 responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
828 if (Strings.isNullOrEmpty(policyData.getRainyday().getBbid())) {
829 responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
832 if (Strings.isNullOrEmpty(policyData.getRainyday().getWorkstep())) {
833 responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
836 if (!policyData.getRainyday().getTreatmentTableChoices().isEmpty()
837 && policyData.getRainyday().getTreatmentTableChoices() != null) {
839 for (Object treatmentMap : policyData.getRainyday().getTreatmentTableChoices()) {
840 String errorCode = null;
841 String treatment = null;
842 if (treatmentMap instanceof LinkedHashMap<?, ?>) {
844 if (((LinkedHashMap<?, ?>) treatmentMap).containsKey("errorcode")) {
845 errorCode = ((LinkedHashMap<?, ?>) treatmentMap).get("errorcode").toString();
847 if (((LinkedHashMap<?, ?>) treatmentMap).containsKey("treatment")) {
848 treatment = ((LinkedHashMap<?, ?>) treatmentMap).get("treatment").toString();
852 if (Strings.isNullOrEmpty(errorCode) && Strings.isNullOrEmpty(treatment)) {
853 responseString.append(
854 "Rainy Day <b>Error Code</b> and <b>Desired Treatment</b> cannot be empty<br>");
858 if (Strings.isNullOrEmpty(errorCode)) {
859 responseString.append(
860 "Rainy Day <b>Error Code</b> is Required for each Desired Treatment<br>");
864 if (Strings.isNullOrEmpty(treatment)) {
865 responseString.append(
866 "Rainy Day <b>Desired Treatment</b> is Required for each Error Code<br>");
873 responseString.append("Rainy Day <b>Desired Automated Treatments</b> are Required<br>");
879 if ("GUARD_YAML".equals(policyData.getRuleProvider())
880 || "GUARD_BL_YAML".equals(policyData.getRuleProvider())
881 || "GUARD_MIN_MAX".equals(policyData.getRuleProvider())) {
882 if (policyData.getYamlparams() == null) {
883 responseString.append("<b> Guard Params are Required </b>" + HTML_ITALICS_LNBREAK);
886 if (Strings.isNullOrEmpty(policyData.getYamlparams().getActor())) {
887 responseString.append("Guard Params <b>Actor</b> is Required " + HTML_ITALICS_LNBREAK);
890 if (Strings.isNullOrEmpty(policyData.getYamlparams().getRecipe())) {
891 responseString.append("Guard Params <b>Recipe</b> is Required " + HTML_ITALICS_LNBREAK);
894 if (Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())) {
895 responseString.append(
896 "Guard Params <b>Guard Active Start</b> is Required " + HTML_ITALICS_LNBREAK);
899 if (Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())) {
901 .append("Guard Params <b>Guard Active End</b> is Required " + HTML_ITALICS_LNBREAK);
904 if ("GUARD_YAML".equals(policyData.getRuleProvider())) {
905 if (Strings.isNullOrEmpty(policyData.getYamlparams().getLimit())) {
906 responseString.append(" Guard Params <b>Limit</b> is Required " + HTML_ITALICS_LNBREAK);
908 } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())) {
910 .append(" Guard Params <b>Limit</b> Should be Integer " + HTML_ITALICS_LNBREAK);
913 if (Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())) {
915 .append("Guard Params <b>Time Window</b> is Required" + HTML_ITALICS_LNBREAK);
917 } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())) {
918 responseString.append(
919 " Guard Params <b>Time Window</b> Should be Integer " + HTML_ITALICS_LNBREAK);
922 if (Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())) {
924 .append("Guard Params <b>Time Units</b> is Required" + HTML_ITALICS_LNBREAK);
927 } else if ("GUARD_MIN_MAX".equals(policyData.getRuleProvider())) {
928 if (Strings.isNullOrEmpty(policyData.getYamlparams().getMin())) {
929 responseString.append(" Guard Params <b>Min</b> is Required " + HTML_ITALICS_LNBREAK);
931 } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getMin())) {
933 .append(" Guard Params <b>Min</b> Should be Integer " + HTML_ITALICS_LNBREAK);
936 if (Strings.isNullOrEmpty(policyData.getYamlparams().getMax())) {
937 responseString.append(" Guard Params <b>Max</b> is Required " + HTML_ITALICS_LNBREAK);
939 } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getMax())) {
941 .append(" Guard Params <b>Max</b> Should be Integer " + HTML_ITALICS_LNBREAK);
944 } else if ("GUARD_BL_YAML".equals(policyData.getRuleProvider())
945 && "Use Manual Entry".equals(policyData.getBlackListEntryType())) {
947 if (policyData.getYamlparams().getBlackList() == null
948 || policyData.getYamlparams().getBlackList().isEmpty()) {
950 .append(" Guard Params <b>BlackList</b> is Required " + HTML_ITALICS_LNBREAK);
953 for (String blackList : policyData.getYamlparams().getBlackList()) {
954 if (blackList == null
955 || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))) {
956 responseString.append(" Guard Params <b>BlackList</b> Should be valid String"
957 + HTML_ITALICS_LNBREAK);
968 if (ACTION_POLICY.equalsIgnoreCase(policyData.getPolicyType())) {
969 if (!Strings.isNullOrEmpty(policyData.getActionPerformer())) {
970 String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
971 if (!actionPerformer.contains(SUCCESS)) {
972 responseString.append("<b>ActionPerformer</b>:<i>" + actionPerformer + HTML_ITALICS_LNBREAK);
976 responseString.append(
977 "<b>ActionPerformer</b>:<i> ActionPerformer Should not be empty" + HTML_ITALICS_LNBREAK);
981 if (!Strings.isNullOrEmpty(policyData.getActionAttributeValue())) {
982 String actionAttribute =
983 PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
984 if (!actionAttribute.contains(SUCCESS)) {
985 responseString.append("<b>ActionAttribute</b>:<i>" + actionAttribute + HTML_ITALICS_LNBREAK);
989 responseString.append(
990 "<b>ActionAttribute</b>:<i> ActionAttribute Should not be empty" + HTML_ITALICS_LNBREAK);
995 if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
998 if (commonClassDao != null) {
999 List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType",
1000 policyData.getRiskType());
1001 if (!spData.isEmpty()) {
1002 SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0);
1003 value = "<b>Message</b>:<i>" + safePolicyWarningData.getMessage() + "</i>";
1006 responseString.append(SUCCESS + "@#" + value);
1010 responseString.append(SUCCESS);
1014 return responseString;
1015 } catch (Exception e) {
1016 LOGGER.error("Exception Occured during Policy Validation" + e);
1021 protected String emailValidation(String email, String response) {
1022 String res = response;
1023 if (email != null) {
1024 String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
1025 if (!validateEmail.contains(SUCCESS)) {
1026 res += "<b>Email</b>:<i>" + validateEmail + HTML_ITALICS_LNBREAK;
1034 private MicroServiceModels getAttributeObject(String name, String version) {
1035 MicroServiceModels workingModel = null;
1037 List<Object> microServiceModelsData =
1038 commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name + ":" + version);
1039 if (microServiceModelsData != null) {
1040 workingModel = (MicroServiceModels) microServiceModelsData.get(0);
1042 } catch (Exception e) {
1043 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + name
1044 + " was not found in the dictionary: ";
1045 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
1049 return workingModel;
1052 private OptimizationModels getOptimizationModelData(String name, String version) {
1053 OptimizationModels workingModel = null;
1055 List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, "modelName:version", name+":"+version);
1056 if(optimizationModelsData != null){
1057 workingModel = (OptimizationModels) optimizationModelsData.get(0);
1059 }catch(Exception e){
1060 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, "
1061 + name + " was not found in the dictionary: ";
1062 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
1066 return workingModel;
1069 private void pullJsonKeyPairs(JsonNode rootNode) {
1070 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
1072 while (fieldsIterator.hasNext()) {
1073 Map.Entry<String, JsonNode> field = fieldsIterator.next();
1074 final String key = field.getKey();
1075 final JsonNode value = field.getValue();
1076 if (value.isContainerNode() && !value.isArray()) {
1077 pullJsonKeyPairs(value); // RECURSIVE CALL
1079 if (value.isArray()) {
1080 String newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""},
1081 new String[] {"", "", ""});
1082 mapAttribute.put(key, newValue);
1084 mapAttribute.put(key, value.toString().trim());
1090 private void pullModelJsonKeyPairs(JsonNode rootNode) {
1091 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
1093 while (fieldsIterator.hasNext()) {
1094 Map.Entry<String, JsonNode> field = fieldsIterator.next();
1095 final String key = field.getKey();
1096 final JsonNode value = field.getValue();
1098 if (value.isContainerNode() && !value.isArray()) {
1099 jsonRequestMap.put(key.trim(), value.toString().trim());
1100 pullModelJsonKeyPairs(value); // RECURSIVE CALL
1101 } else if (value.isArray()) {
1103 String valueStr = value.toString();
1104 String stringValue = valueStr.substring(valueStr.indexOf('[') + 1, valueStr.lastIndexOf(']'));
1105 ObjectMapper mapper = new ObjectMapper();
1106 JsonNode newValue = mapper.readTree(stringValue);
1107 jsonRequestMap.put(key.trim(), value.toString().trim());
1108 pullModelJsonKeyPairs(newValue);
1109 } catch (IOException e) {
1110 LOGGER.info("PolicyValidation: Exception occurred while mapping string to JsonNode " + e);
1113 jsonRequestMap.put(key.trim(), value.toString().trim());
1119 private JsonObject stringToJsonObject(String value) {
1120 try (JsonReader jsonReader = Json.createReader(new StringReader(value))) {
1121 return jsonReader.readObject();
1122 } catch (JsonException | IllegalStateException e) {
1124 XACMLErrorConstants.ERROR_DATA_ISSUE
1125 + "Improper JSON format... may or may not cause issues in validating the policy: " + value,
1131 private void findRequiredFields(JsonObject json) {
1135 for (Entry<String, JsonValue> keyMap : json.entrySet()) {
1136 Object obj = keyMap.getValue();
1137 String key = keyMap.getKey();
1138 if (obj instanceof JsonObject) {
1139 if (allReqTrueKeys.contains(key)) {
1140 JsonObject jsonObj = (JsonObject) obj;
1141 // only check fields in obj if obj itself is required.
1142 for (Entry<String, JsonValue> jsonMap : jsonObj.entrySet()) {
1143 if (jsonMap.getValue().toString().contains(REQUIRED_ATTRIBUTE)) {
1144 modelRequiredFieldsList.add(jsonMap.getKey().trim());
1148 } else if (keyMap.getValue().toString().contains(REQUIRED_ATTRIBUTE)) {
1149 modelRequiredFieldsList.add(key.trim());
1156 // call this method to start the recursive
1157 private Set<String> getAllKeys(JSONObject json) {
1158 return getAllKeys(json, new HashSet<>());
1161 private Set<String> getAllKeys(JSONArray arr) {
1162 return getAllKeys(arr, new HashSet<>());
1165 private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1166 for (int i = 0; i < arr.length(); i++) {
1167 Object obj = arr.get(i);
1168 if (obj instanceof JSONObject) {
1169 keys.addAll(getAllKeys(arr.getJSONObject(i)));
1171 if (obj instanceof JSONArray) {
1172 keys.addAll(getAllKeys(arr.getJSONArray(i)));
1179 // this method returns a set of keys with "required-true" defined in their value.
1180 private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1181 for (String key : json.keySet()) {
1182 Object obj = json.get(key);
1183 if (obj instanceof String && ((String) obj).contains(REQUIRED_ATTRIBUTE)) {
1184 LOGGER.debug("key : " + key);
1185 LOGGER.debug("obj : " + obj);
1186 allReqTrueKeys.add(key);
1187 // get the type from value and add that one also
1188 String type = StringUtils.substringBefore((String) obj, ":");
1189 if (!StringUtils.isBlank(type) && !StringUtils.containsAny(type.toLowerCase(), MSModelUtils.STRING,
1190 MSModelUtils.INTEGER, MSModelUtils.LIST, MSModelUtils.MAP, "java", "boolean")) {
1191 allReqTrueKeys.add(type);
1194 if (obj instanceof JSONObject) {
1195 keys.addAll(getAllKeys(json.getJSONObject(key)));
1197 if (obj instanceof JSONArray) {
1198 keys.addAll(getAllKeys(json.getJSONArray(key)));
1205 private boolean validateMsModel(PolicyRestAdapter policyData, StringBuilder responseString)
1206 throws JsonProcessingException {
1207 boolean valid = true;
1208 if (!Strings.isNullOrEmpty(policyData.getServiceType())) {
1210 modelRequiredFieldsList.clear();
1211 pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
1215 if (policyData.getServiceType().contains("-v")) {
1216 service = policyData.getServiceType().split("-v")[0];
1217 version = policyData.getServiceType().split("-v")[1];
1219 service = policyData.getServiceType();
1220 version = policyData.getVersion();
1223 if (!Strings.isNullOrEmpty(version)) {
1224 MicroServiceModels returnModel = getAttributeObject(service, version);
1226 if (returnModel != null) {
1228 String annotation = returnModel.getAnnotation();
1229 String refAttributes = returnModel.getRef_attributes();
1230 String subAttributes = returnModel.getSub_attributes();
1231 String modelAttributes = returnModel.getAttributes();
1233 if (!Strings.isNullOrEmpty(annotation)) {
1234 Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation);
1235 for (Entry<String, String> raMap : rangeMap.entrySet()) {
1236 if (raMap.getValue().contains("range::")) {
1237 String value = mapAttribute.get(raMap.getKey().trim());
1238 String[] tempString = raMap.getValue().split("::")[1].split("-");
1239 int startNum = Integer.parseInt(tempString[0]);
1240 int endNum = Integer.parseInt(tempString[1]);
1241 String returnString = "InvalidreturnModel Range:" + raMap.getKey() + " must be between "
1242 + startNum + " - " + endNum + ",";
1244 if (value != null) {
1245 if (PolicyUtils.isInteger(value.replace("\"", ""))) {
1246 int result = Integer.parseInt(value.replace("\"", ""));
1247 if (result < startNum || result > endNum) {
1248 responseString.append(returnString);
1252 responseString.append(returnString);
1256 responseString.append("<b>" + raMap.getKey() + "</b>:<i>" + raMap.getKey()
1257 + " is required for the MicroService model " + service
1258 + HTML_ITALICS_LNBREAK);
1264 } else if (!DECISION_MS_MODEL.equals(policyData.getRuleProvider())) {
1265 // Validate for configName, location, uuid, and policyScope if no annotations exist for this
1267 if (Strings.isNullOrEmpty(policyData.getLocation())) {
1268 responseString.append("<b>Micro Service Model</b>:<i> location is required for this model"
1269 + HTML_ITALICS_LNBREAK);
1273 if (Strings.isNullOrEmpty(policyData.getConfigName())) {
1274 responseString.append("<b>Micro Service Model</b>:<i> configName is required for this model"
1275 + HTML_ITALICS_LNBREAK);
1279 if (Strings.isNullOrEmpty(policyData.getUuid())) {
1280 responseString.append("<b>Micro Service Model</b>:<i> uuid is required for this model"
1281 + HTML_ITALICS_LNBREAK);
1285 if (Strings.isNullOrEmpty(policyData.getPolicyScope())) {
1287 .append("<b>Micro Service Model</b>:<i> policyScope is required for this model"
1288 + HTML_ITALICS_LNBREAK);
1293 // If request comes from the API we need to validate required fields in the Micro Service Model
1294 // GUI request are already validated from the SDK-APP
1295 if ("API".equals(policyData.getApiflag())) {
1296 // first , get the complete set of required fields
1297 populateReqFieldSet(new String[] {refAttributes, modelAttributes}, subAttributes);
1299 // ignore req fields in which parent is not reqd
1300 populateRequiredFields(new String[] {refAttributes, modelAttributes}, subAttributes,
1303 if (modelRequiredFieldsList != null && !modelRequiredFieldsList.isEmpty()) {
1304 // create jsonRequestMap with all json keys and values from request
1305 JsonNode rootNode = (JsonNode) policyData.getPolicyJSON();
1306 jsonRequestMap.clear();
1307 pullModelJsonKeyPairs(rootNode);
1309 // validate if the requiredFields are in the request
1310 for (String requiredField : modelRequiredFieldsList) {
1311 if (jsonRequestMap.containsKey(requiredField)) {
1312 String value = jsonRequestMap.get(requiredField);
1313 if (StringUtils.isBlank(value) || "\"\"".equals(value)) {
1314 responseString.append("<b>Micro Service Model</b>:<i> " + requiredField
1315 + ISREQUIRED + HTML_ITALICS_LNBREAK);
1319 responseString.append("<b>Micro Service Model</b>:<i> " + requiredField
1320 + ISREQUIRED + HTML_ITALICS_LNBREAK);
1327 responseString.append("<b>Micro Service Model</b>:<i> Invalid Model. The model name, " + service
1328 + " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
1332 responseString.append(
1333 "<b>Micro Service Version</b>:<i> Micro Service Version is required" + HTML_ITALICS_LNBREAK);
1337 responseString.append("<b>Micro Service</b>:<i> Micro Service Model is required" + HTML_ITALICS_LNBREAK);
1341 if (Strings.isNullOrEmpty(policyData.getPriority())
1342 && !DECISION_MS_MODEL.equals(policyData.getRuleProvider())) {
1343 responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
1350 private void populateRequiredFields(String[] attrArr, String subAttributes, String modelAttributes)
1351 throws JsonProcessingException {
1352 // get list of required fields from the ref_Attributes of the Model
1353 for (String attributes : attrArr) {
1354 if (!StringUtils.isBlank(attributes)) {
1355 Map<String, String> attributesMap = null;
1356 if (",".equals(attributes.substring(attributes.length() - 1))) {
1357 String attributesString = attributes.substring(0, attributes.length() - 1);
1358 attributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributesString);
1359 } else if (!StringUtils.isBlank(modelAttributes)) {
1360 attributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
1364 String json = new ObjectMapper().writeValueAsString(attributesMap);
1365 findRequiredFields(stringToJsonObject(json));
1371 // get list of required fields from the sub_Attributes of the Model
1372 if (!StringUtils.isBlank(subAttributes)) {
1373 JsonObject subAttributesJson = stringToJsonObject(subAttributes);
1374 findRequiredFields(subAttributesJson);
1379 private void populateReqFieldSet(String[] attrArr, String subAttributes) {
1380 allReqTrueKeys.clear();
1381 JSONObject jsonSub = new JSONObject(subAttributes);
1382 // Get all keys with "required-true" defined in their value from subAttribute
1383 getAllKeys(jsonSub);
1386 // parse refAttrbutes
1387 for (String attr : attrArr) {
1389 String[] referAarray = attr.split(",");
1390 String[] element = null;
1391 for (int i = 0; i < referAarray.length; i++) {
1392 element = referAarray[i].split("=");
1393 if (element.length > 1 && element[1].contains(REQUIRED_ATTRIBUTE)) {
1394 allReqTrueKeys.add(element[0]);