2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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.openecomp.policy.controller;
25 import java.io.FileInputStream;
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.PrintWriter;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.LinkedHashMap;
38 import java.util.LinkedList;
39 import java.util.List;
41 import java.util.UUID;
42 import java.util.Map.Entry;
43 import java.util.Properties;
44 import java.util.TreeMap;
46 import javax.json.Json;
47 import javax.json.JsonReader;
48 import javax.servlet.http.HttpServletRequest;
49 import javax.servlet.http.HttpServletResponse;
51 import org.apache.commons.lang.StringUtils;
52 import org.json.JSONArray;
53 import org.json.JSONObject;
54 import org.openecomp.policy.adapter.PolicyAdapter;
55 import org.openecomp.policy.admin.PolicyNotificationMail;
56 import org.openecomp.policy.admin.RESTfulPAPEngine;
57 import org.openecomp.policy.dao.PolicyVersionDao;
58 import org.openecomp.policy.dao.RemoteCatalogValuesDao;
59 import org.openecomp.policy.dao.RuleAlgorithmsDao;
60 import org.openecomp.policy.dao.WatchPolicyNotificationDao;
61 import org.openecomp.policy.elk.client.PolicyElasticSearchController;
62 import org.openecomp.policy.rest.XACMLRestProperties;
63 import org.openecomp.policy.rest.dao.GroupPolicyScopeListDao;
64 import org.openecomp.policy.rest.dao.MicroServiceModelsDao;
65 import org.openecomp.policy.rest.jpa.GroupPolicyScopeList;
66 import org.openecomp.policy.rest.jpa.MicroServiceModels;
67 import org.openecomp.policy.rest.jpa.PolicyVersion;
68 import org.openecomp.policy.rest.jpa.RemoteCatalogValues;
69 import org.openecomp.policy.rest.jpa.RuleAlgorithms;
70 import org.openecomp.policy.utils.ConfigurableRESTUtils;
71 import org.openecomp.policy.utils.ConfigurableRESTUtils.RESQUEST_METHOD;
72 import org.openecomp.policy.utils.ConfigurableRESTUtils.REST_RESPONSE_FORMAT;
73 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
74 import org.openecomp.portalsdk.core.web.support.JsonMessage;
75 import org.openecomp.portalsdk.core.web.support.UserUtils;
76 import org.springframework.beans.factory.annotation.Autowired;
77 import org.springframework.http.MediaType;
78 import org.springframework.stereotype.Controller;
79 import org.springframework.web.bind.annotation.RequestMapping;
80 import org.springframework.web.servlet.ModelAndView;
82 import com.att.research.xacml.api.XACML3;
83 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
84 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
85 import com.att.research.xacml.util.XACMLProperties;
86 import com.fasterxml.jackson.core.JsonProcessingException;
87 import com.fasterxml.jackson.databind.DeserializationFeature;
88 import com.fasterxml.jackson.databind.JsonNode;
89 import com.fasterxml.jackson.databind.ObjectMapper;
90 import com.fasterxml.jackson.databind.ObjectWriter;
91 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
92 import com.fasterxml.jackson.databind.node.ObjectNode;
93 import com.google.common.base.Joiner;
94 import com.google.common.base.Splitter;
95 import com.google.gson.Gson;
96 import com.google.gson.JsonArray;
97 import com.google.gson.JsonElement;
98 import com.google.gson.JsonObject;
99 import com.google.gson.JsonParser;
101 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
102 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
103 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
104 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
105 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
106 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
107 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
108 import org.openecomp.policy.common.logging.flexlogger.Logger;
112 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
113 private static final Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
115 private static RuleAlgorithmsDao ruleAlgorithmsDao;
116 private static RemoteCatalogValuesDao remoteCatalogValuesDao;
117 private static MicroServiceModelsDao microServiceModelsDao;
118 private static PolicyVersionDao policyVersionDao;
119 private static GroupPolicyScopeListDao groupPolicyScopeListDao;
120 private static WatchPolicyNotificationDao policyNotificationDao;
123 private CreateDcaeMicroServiceController(RuleAlgorithmsDao ruleAlgorithmsDao, RemoteCatalogValuesDao remoteCatalogValuesDao,
124 MicroServiceModelsDao microServiceModelsDao, PolicyVersionDao policyVersionDao, GroupPolicyScopeListDao groupPolicyScopeListDao,
125 WatchPolicyNotificationDao policyNotificationDao){
126 CreateDcaeMicroServiceController.groupPolicyScopeListDao = groupPolicyScopeListDao;
127 CreateDcaeMicroServiceController.policyVersionDao = policyVersionDao;
128 CreateDcaeMicroServiceController.microServiceModelsDao = microServiceModelsDao;
129 CreateDcaeMicroServiceController.remoteCatalogValuesDao = remoteCatalogValuesDao;
130 CreateDcaeMicroServiceController.ruleAlgorithmsDao = ruleAlgorithmsDao;
131 CreateDcaeMicroServiceController.policyNotificationDao = policyNotificationDao;
134 public CreateDcaeMicroServiceController(){}
136 protected PolicyAdapter policyAdapter = null;
137 private String ruleID = "";
138 private int priorityCount;
139 private Map<String, String> attributesListRefMap = new HashMap<String, String>();
140 private Map<String, LinkedList<String>> arrayTextList = new HashMap<String, LinkedList<String>>();
143 public String newPolicyID() {
144 return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"),
145 PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID());
149 @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
150 public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{
151 ObjectMapper mapper = new ObjectMapper();
152 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
153 JsonNode root = mapper.readTree(request.getReader());
155 String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
156 String servicename = value.toString().split("-v")[0];
157 String version = null;
158 if (value.toString().contains("-v")){
159 version = value.toString().split("-v")[1];
161 MicroServiceModels returnModel = getAttributeObject(servicename, version);
163 response.setCharacterEncoding("UTF-8");
164 response.setContentType("application / json");
165 request.setCharacterEncoding("UTF-8");
166 List<Object> list = new ArrayList<>();
167 PrintWriter out = response.getWriter();
168 String responseString = mapper.writeValueAsString(returnModel);
169 JSONObject j = new JSONObject("{dcaeModelData: " + responseString +"}");
171 out.write(list.toString());
175 private MicroServiceModels getAttributeObject(String name, String version) {
176 MicroServiceModels workingModel = new MicroServiceModels();
177 List<MicroServiceModels> microServiceModelsData = microServiceModelsDao.getMicroServiceModelsData();
178 for (int i = 0; i < microServiceModelsData.size(); i++) {
179 workingModel = microServiceModelsData.get(i);
180 if (version!=null && workingModel.getVersion()!=null){
181 if (workingModel.getModelName().equals(name) && workingModel.getVersion().equals(version)){
185 if (workingModel.getModelName().equals(name) && workingModel.getVersion() == null){
193 @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
194 public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
196 Map<String, Object> model = new HashMap<String, Object>();
197 ObjectMapper mapper = new ObjectMapper();
198 List<String> priorityList = new ArrayList<String>();
200 for (int i = 1; i < priorityCount; i++) {
201 priorityList.add(String.valueOf(i));
203 model.put("priorityDatas", mapper.writeValueAsString(priorityList));
204 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
205 JSONObject j = new JSONObject(msg);
206 response.getWriter().write(j.toString());
214 @RequestMapping(value={"/policyController/save_DCAEMSPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
215 public ModelAndView saveDCAEMSPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
217 String userId = UserUtils.getUserIdFromCookie(request);
218 RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine();
219 ObjectMapper mapper = new ObjectMapper();
220 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
221 JsonNode root = mapper.readTree(request.getReader());
222 String jsonContent = null;
224 jsonContent = decodeContent(root.get("policyJSON")).toString();
226 logger.error("Error while decoding microservice content");
228 PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class);
229 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
230 if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
231 policyData.isEditPolicy = true;
234 if(root.get("policyData").get("model").get("path").size() != 0){
236 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
237 dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
239 if(policyData.isEditPolicy){
240 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
242 policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", ""));
245 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
248 if (policyData.getTtlDate()==null){
249 policyData.setTtlDate("NA");
251 String dateTTL = policyData.getTtlDate();
252 String newDate = convertDate(dateTTL);
253 policyData.setTtlDate(newDate);
257 int highestVersion = 0;
258 int descriptionVersion = 0;
259 //get the highest version of policy from policy version table.
260 //getting the sub scope domain where the policy is created or updated
261 String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_MS_" + policyData.getPolicyName();
262 List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName);
263 if (versionList.size() > 0) {
264 for(int i = 0; i < versionList.size(); i++) {
265 PolicyVersion entityItem = versionList.get(i);
266 if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
267 highestVersion = entityItem.getHigherVersion();
271 if(highestVersion != 0){
272 version = highestVersion;
273 descriptionVersion = highestVersion +1;
276 descriptionVersion = 1;
279 //set policy adapter values for Building JSON object containing policy data
280 String createdBy = "";
281 String modifiedBy = userId;
282 if(descriptionVersion == 1){
285 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
286 File policyPath = new File(policyName);
288 createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
289 } catch (IOException e) {
294 policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
295 policyData.setEcompName(policyData.getEcompName());
297 String jsonBody = null;
299 jsonBody = constructJson(policyData, jsonContent);
300 } catch (Exception e) {
301 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
303 policyData.setJsonBody(jsonBody);
304 Map<String, String> successMap = new HashMap<String, String>();
305 //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
306 List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms();
307 for (int i = 0; i < ruleAlgorithmsList.size(); i++) {
308 RuleAlgorithms a = ruleAlgorithmsList.get(i);
309 if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) {
310 policyData.setRuleCombiningAlgId(a.getXacmlId());
314 if (policyData.isEditPolicy()){
315 //increment the version and set in policyAdapter
316 policyData.setVersion(String.valueOf(version));
317 policyData.setHighestVersion(version);
318 policyData.setPolicyID(this.newPolicyID());
319 policyData.setRuleID(ruleID);
320 successMap = engine.updatePolicyRequest(policyData);
322 //send it for policy creation
323 policyData.setVersion(String.valueOf(version));
324 policyData.setHighestVersion(version);
325 successMap = engine.createPolicyRequest(policyData);
329 if (successMap.containsKey("success")) {
330 // Add it into our tree
331 Path finalPolicyPath = null;
332 finalPolicyPath = Paths.get(successMap.get("success"));
333 PolicyElasticSearchController controller = new PolicyElasticSearchController();
334 controller.updateElk(finalPolicyPath.toString());
335 File file = finalPolicyPath.toFile();
337 String policyName = file.toString();
338 String removePath = policyName.substring(policyName.indexOf("repository")+11);
339 String removeXml = removePath.replace(".xml", "");
340 String removeExtension = removeXml.substring(0, removeXml.indexOf("."));
341 List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension);
342 if (policyVersionList.size() > 0) {
343 for(int i = 0; i < policyVersionList.size(); i++) {
344 PolicyVersion entityItem = policyVersionList.get(i);
345 if(entityItem.getPolicyName().equals(removeExtension)){
346 version = entityItem.getHigherVersion() +1;
347 entityItem.setActiveVersion(version);
348 entityItem.setHigherVersion(version);
349 entityItem.setModifiedBy(userId);
350 policyVersionDao.update(entityItem);
351 if(policyData.isEditPolicy){
352 PolicyNotificationMail email = new PolicyNotificationMail();
353 String mode = "EditPolicy";
354 String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
355 email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao);
360 PolicyVersion entityItem = new PolicyVersion();
361 entityItem.setActiveVersion(version);
362 entityItem.setHigherVersion(version);
363 entityItem.setPolicyName(removeExtension);
364 entityItem.setCreatedBy(userId);
365 entityItem.setModifiedBy(userId);
366 policyVersionDao.Save(entityItem);
371 System.out.println(root);
372 response.setCharacterEncoding("UTF-8");
373 response.setContentType("application / json");
374 request.setCharacterEncoding("UTF-8");
376 PrintWriter out = response.getWriter();
377 String responseString = mapper.writeValueAsString(successMap);
378 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
379 out.write(j.toString());
383 response.setCharacterEncoding("UTF-8");
384 request.setCharacterEncoding("UTF-8");
385 PrintWriter out = response.getWriter();
386 out.write(e.getMessage());
391 private JSONObject decodeContent(JsonNode jsonNode){
392 Iterator<JsonNode> jsonElements = jsonNode.elements();
393 Iterator<String> jsonKeys = jsonNode.fieldNames();
394 Map<String,String> element = new TreeMap<String,String>();
395 while(jsonElements.hasNext() && jsonKeys.hasNext()){
396 element.put(jsonKeys.next(), jsonElements.next().toString());
398 JSONObject jsonResult = new JSONObject();
399 JSONArray jsonArray = null;
400 String oldValue = null;
401 String nodeKey = null;
402 String arryKey = null;
403 Boolean isArray = false;
404 JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
405 ObjectNode node = nodeFactory.objectNode();
406 String prevKey = null;
407 String presKey = null;
408 for(String key: element.keySet()){
409 if(key.contains(".")){
410 presKey = key.substring(0,key.indexOf("."));
411 }else if(key.contains("@")){
412 presKey = key.substring(0,key.indexOf("@"));
416 // first check if we are different from old.
417 System.out.println(key+"\n");
418 if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
419 if(!oldValue.equals(key.substring(0,key.indexOf("@")))){
420 jsonResult.put(oldValue, jsonArray);
421 jsonArray = new JSONArray();
423 }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
424 jsonResult.put(oldValue, jsonArray);
426 jsonArray = new JSONArray();
428 /*if(node.size()!=0 && key.contains("@")){
437 if(key.contains(".")){
439 nodeKey = key.substring(0,key.indexOf("."));
441 if(nodeKey.equals(key.substring(0,key.indexOf(".")))){
442 node.put(key.substring(key.indexOf(".")+1), element.get(key));
445 if(nodeKey.contains("@")){
447 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
449 if(nodeKey.endsWith("@0")){
451 jsonArray = new JSONArray();
453 if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
454 jsonArray.put(decodeContent(node));
456 if(key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))){
457 jsonResult.put(arryKey, jsonArray);
458 jsonArray = new JSONArray();
459 }else if(!key.contains("@")){
460 jsonResult.put(arryKey, jsonArray);
461 jsonArray = new JSONArray();
463 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
466 jsonResult.put(nodeKey, decodeContent(node));
468 node = nodeFactory.objectNode();
470 nodeKey = key.substring(0,key.indexOf("."));
471 if(nodeKey.contains("@")){
472 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
474 node.put(key.substring(key.indexOf(".")+1), element.get(key));
476 }else if(node.size()!=0){
477 if(nodeKey.contains("@")){
479 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
481 if(nodeKey.endsWith("@0")){
483 jsonArray = new JSONArray();
485 if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
486 jsonArray.put(decodeContent(node));
488 jsonResult.put(arryKey, jsonArray);
489 jsonArray = new JSONArray();
490 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
493 jsonResult.put(nodeKey, decodeContent(node));
495 node = nodeFactory.objectNode();
496 if(key.contains("@")){
498 if(key.endsWith("@0")|| jsonArray==null){
499 jsonArray = new JSONArray();
501 }else if(!key.contains("@")){
506 oldValue = key.substring(0,key.indexOf("@"));
508 if(oldValue!=prevKey){
509 oldValue = key.substring(0,key.indexOf("@"));
511 if(oldValue.equals(key.substring(0,key.indexOf("@")))){
512 jsonArray.put(element.get(key));
514 jsonResult.put(oldValue, jsonArray);
515 jsonArray = new JSONArray();
517 oldValue = key.substring(0,key.indexOf("@"));
519 jsonResult.put(key, element.get(key));
522 if(key.contains("@")){
524 if(key.endsWith("@0")|| jsonArray==null){
525 jsonArray = new JSONArray();
527 }else if(!key.contains("@")){
532 oldValue = key.substring(0,key.indexOf("@"));
534 if(oldValue!=prevKey){
535 oldValue = key.substring(0,key.indexOf("@"));
537 if(oldValue.equals(key.substring(0,key.indexOf("@")))){
538 jsonArray.put(element.get(key));
540 jsonResult.put(oldValue, jsonArray);
541 jsonArray = new JSONArray();
543 oldValue = key.substring(0,key.indexOf("@"));
545 jsonResult.put(key, element.get(key));
550 if(nodeKey.contains("@")){
552 jsonArray = new JSONArray();
555 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
557 jsonArray.put(decodeContent(node));
558 jsonResult.put(arryKey, jsonArray);
561 jsonResult.put(nodeKey, decodeContent(node));
564 if(isArray && jsonArray.length() > 0){
565 jsonResult.put(oldValue, jsonArray);
570 public void PrePopulateDCAEMSPolicyData(PolicyAdapter policyAdapter) {
571 if (policyAdapter.getPolicyData() instanceof PolicyType) {
572 Object policyData = policyAdapter.getPolicyData();
573 PolicyType policy = (PolicyType) policyData;
574 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
575 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3 , policyAdapter.getPolicyName().lastIndexOf("."));
576 policyAdapter.setPolicyName(policyNameValue);
577 String description = "";
579 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
581 description = policy.getDescription();
583 policyAdapter.setPolicyDescription(description);
584 String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + ".";
585 policyAdapter.setConfigBodyPath(jsonBodyName);
586 // Get the target data under policy.
587 TargetType target = policy.getTarget();
588 if (target != null) {
589 // Under target we have AnyOFType
590 List<AnyOfType> anyOfList = target.getAnyOf();
591 if (anyOfList != null) {
592 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
593 while (iterAnyOf.hasNext()) {
594 AnyOfType anyOf = iterAnyOf.next();
595 // Under AnyOFType we have AllOFType
596 List<AllOfType> allOfList = anyOf.getAllOf();
597 if (allOfList != null) {
598 Iterator<AllOfType> iterAllOf = allOfList.iterator();
599 while (iterAllOf.hasNext()) {
600 AllOfType allOf = iterAllOf.next();
601 // Under AllOFType we have Match
602 List<MatchType> matchList = allOf.getMatch();
603 if (matchList != null) {
605 Iterator<MatchType> iterMatch = matchList.iterator();
606 while (matchList.size()>1 && iterMatch.hasNext()) {
607 MatchType match = iterMatch.next();
609 // Under the match we have attributevalue and
610 // attributeDesignator. So,finally down to the actual attribute.
612 AttributeValueType attributeValue = match.getAttributeValue();
613 String value = (String) attributeValue.getContent().get(0);
615 // First match in the target is EcompName, so set that value.
617 policyAdapter.setEcompName(value);
620 policyAdapter.setConfigName(value);
624 readFile(policyAdapter);
628 policyAdapter.setUuid(value);
631 policyAdapter.setLocation(value);
634 policyAdapter.setRiskType(value);
638 policyAdapter.setRiskLevel(value);
642 policyAdapter.setGuard(value);
644 if (index == 8 && !value.contains("NA")){
645 String newDate = convertDate(value, true);
646 policyAdapter.setTtlDate(newDate);
660 private String convertDate(String dateTTL, boolean portalType) {
661 String formateDate = null;
666 parts = dateTTL.split("-");
667 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
669 date = dateTTL.split("T");
670 parts = date[0].split("-");
671 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
676 @SuppressWarnings("unchecked")
677 private String readFile(PolicyAdapter policyAdapter) {
678 String fileLocation = null;
679 String policyScopeName = null;
680 String fileName = policyAdapter.getConfigBodyPath();
681 if (fileName != null ) {
682 fileLocation = PolicyController.getConfigHome();
684 if (fileLocation == null) {
687 File dir = new File(fileLocation);
688 File[] listOfFiles = dir.listFiles();
689 for (File file : listOfFiles) {
690 if (file.isFile() && file.getName().contains(fileName)) {
691 FileInputStream inputStream = null;
692 String location = file.toString();
694 inputStream = new FileInputStream(location);
695 } catch (FileNotFoundException e) {
698 if (location.endsWith("json")) {
699 JsonReader jsonReader = null;
700 jsonReader = Json.createReader(inputStream);
701 ObjectMapper mapper = new ObjectMapper();
703 DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(jsonReader.read().toString(), DCAEMicroServiceObject.class);
704 policyScopeName = getPolicyScope(msBody.getPolicyScope());
705 policyAdapter.setPolicyScope(policyScopeName);
707 policyAdapter.setPriority(msBody.getPriority());
709 if (msBody.getVersion()!= null){
710 policyAdapter.setServiceType(msBody.getService() + "-v" + msBody.getVersion());
712 policyAdapter.setServiceType(msBody.getService());
714 if(msBody.getContent() != null){
715 LinkedHashMap<String, Object> data = new LinkedHashMap<String, Object>();
716 LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
717 readRecursivlyJSONContent(map, data);
718 policyAdapter.setRuleData(data);
721 } catch (Exception e) {
732 @SuppressWarnings({ "rawtypes", "unchecked" })
733 private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
734 for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
735 Object key = iterator.next();
736 Object value = map.get(key);
737 if(value instanceof LinkedHashMap<?, ?>){
738 readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, data);
739 }else if(value instanceof ArrayList){
740 ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
741 for(int i = 0; i < jsonArrayVal.size(); i++){
742 Object arrayvalue = jsonArrayVal.get(i);
743 if(arrayvalue instanceof LinkedHashMap<?, ?>){
744 LinkedHashMap<String, Object> newData = new LinkedHashMap<String, Object>();
745 readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
746 for(String objKey: newData.keySet()){
747 data.put(key+"@"+i+"." +objKey, newData.get(objKey));
749 }else if(arrayvalue instanceof ArrayList){
750 ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
751 for(int j = 0; j < jsonArrayVal1.size(); j++){
752 Object arrayvalue1 = jsonArrayVal1.get(i);
753 data.put(key+"@"+j, arrayvalue1.toString());
756 data.put(key+"@"+i, arrayvalue.toString());
760 data.put(key.toString(), value.toString());
765 private String getPolicyScope(String value) {
766 GroupPolicyScopeList pScope = new GroupPolicyScopeList();
767 List<GroupPolicyScopeList> groupList= groupPolicyScopeListDao.getGroupPolicyScopeListData();
768 if(groupList.size() > 0){
769 for(int i = 0 ; i < groupList.size() ; i ++){
770 pScope = groupList.get(i);
771 if (pScope.getGroupList().equals(value)){
776 return pScope.getGroupName();
779 private GroupPolicyScopeList getPolicyObject(String policyScope) {
780 GroupPolicyScopeList pScope = new GroupPolicyScopeList();
781 List<GroupPolicyScopeList> groupList = groupPolicyScopeListDao.getGroupPolicyScopeListData();
782 if(groupList.size() > 0){
783 for(int i = 0 ; i < groupList.size() ; i ++){
784 pScope = groupList.get(i);
785 if (pScope.getGroupName().equals(policyScope)){
793 private String constructJson(PolicyAdapter policyAdapter, String jsonContent) {
794 ObjectWriter om = new ObjectMapper().writer();
796 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
798 microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
799 if(policyAdapter.getServiceType() !=null){
800 microServiceObject.setService(policyAdapter.getServiceType().toString().split("-v")[0]);
801 if (policyAdapter.getServiceType().toString().contains("-v")){
802 microServiceObject.setVersion(policyAdapter.getServiceType().toString().split("-v")[1]);
805 if(policyAdapter.getUuid()!=null){
806 microServiceObject.setUuid(policyAdapter.getUuid());
809 if(policyAdapter.getLocation()!=null){
810 microServiceObject.setLocation(policyAdapter.getLocation());
812 if(policyAdapter.getPolicyName()!=null){
813 microServiceObject.setPolicyName(policyAdapter.getPolicyName());
816 if(policyAdapter.getConfigName()!=null){
817 microServiceObject.setConfigName(policyAdapter.getConfigName());
819 if(policyAdapter.getPolicyDescription()!=null){
820 microServiceObject.setDescription(policyAdapter.getPolicyDescription());
822 if (policyAdapter.getPriority()!=null){
823 microServiceObject.setPriority(policyAdapter.getPriority());
825 microServiceObject.setPriority("9999");
827 microServiceObject.setContent(jsonContent);
828 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
829 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
831 json = om.writeValueAsString(microServiceObject);
832 } catch (JsonProcessingException e) {
833 logger.error("Error writing out the object");
835 System.out.println(json);
836 String cleanJson = cleanUPJson(json);
840 private String cleanUPJson(String json) {
841 String cleanJason = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
842 cleanJason = StringUtils.replaceEach(json, new String[]{"\\\\\\"}, new String[]{"\\"});
843 cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
845 cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
846 cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
847 cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
848 cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
849 cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
850 cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\\\""}, new String[]{""});
854 //Convert the map values and set into JSON body
855 public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
856 Map<String, String> attribute = new HashMap<String, String>();
860 for (Entry<String, String> entry : attributesMap.entrySet()) {
861 key = entry.getKey();
862 value = entry.getValue();
863 attribute.put(key, value);
865 for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
866 key = entryRef.getKey();
867 value = entryRef.getValue().toString();
868 attribute.put(key, value);
870 for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
871 key = entryList.getKey();
872 value = entryList.getValue().toString();
873 attribute.put(key, value);
875 for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
876 key = arrayList.getKey();
878 for (Object textList : arrayList.getValue()){
880 temp = "[" + textList;
882 temp = temp + "," + textList;
885 attribute.put(key, temp+ "]");
891 private String convertDate(String dateTTL) {
892 String formateDate = null;
893 String[] date = dateTTL.split("T");
894 String[] parts = date[0].split("-");
896 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
901 class DCAEMicroServiceObject {
903 public String service;
904 public String location;
906 public String policyName;
907 public String description;
908 public String configName;
909 public String templateVersion;
910 public String version;
911 public String priority;
912 public String policyScope;
914 public String getPolicyScope() {
917 public void setPolicyScope(String policyScope) {
918 this.policyScope = policyScope;
921 public String getPriority() {
924 public void setPriority(String priority) {
925 this.priority = priority;
927 public String getVersion() {
930 public void setVersion(String version) {
931 this.version = version;
933 private Object content;
936 public String getPolicyName() {
939 public void setPolicyName(String policyName) {
940 this.policyName = policyName;
942 public String getDescription() {
945 public void setDescription(String description) {
946 this.description = description;
948 public String getConfigName() {
951 public void setConfigName(String configName) {
952 this.configName = configName;
954 public Object getContent() {
957 public void setContent(Object content) {
958 this.content = content;
961 public String getService() {
964 public void setService(String service) {
965 this.service = service;
967 public String getLocation() {
970 public void setLocation(String location) {
971 this.location = location;
974 public String getUuid() {
977 public void setUuid(String uuid) {
980 public String getTemplateVersion() {
981 return templateVersion;
983 public void setTemplateVersion(String templateVersion) {
984 this.templateVersion = templateVersion;