Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / controller / CreateDcaeMicroServiceController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.controller;
22
23
24 import java.io.File;
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;
40 import java.util.Map;
41 import java.util.UUID;
42 import java.util.Map.Entry;
43 import java.util.Properties;
44 import java.util.TreeMap;
45
46 import javax.json.Json;
47 import javax.json.JsonReader;
48 import javax.servlet.http.HttpServletRequest;
49 import javax.servlet.http.HttpServletResponse;
50
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;
81
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;
100
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;
109
110 @Controller
111 @RequestMapping("/")
112 public class CreateDcaeMicroServiceController extends RestrictedBaseController {
113         private static final Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
114
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;
121         
122         @Autowired
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;
132         }
133         
134         public CreateDcaeMicroServiceController(){}
135         
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>>();
141
142
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());
146         }
147
148
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());
154
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];
160                 }
161                 MicroServiceModels returnModel = getAttributeObject(servicename, version);
162                 
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 +"}");
170                 list.add(j);
171                 out.write(list.toString());
172                 return null;
173         }
174
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)){
182                                         break;
183                                 }
184                         }else{
185                                 if (workingModel.getModelName().equals(name) && workingModel.getVersion() == null){
186                                         break;
187                                 }
188                         }
189                 }
190                 return workingModel;
191         }
192
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){
195                 try{
196                         Map<String, Object> model = new HashMap<String, Object>();
197                         ObjectMapper mapper = new ObjectMapper();
198                         List<String> priorityList = new ArrayList<String>();
199                         priorityCount = 10;
200                         for (int i = 1; i < priorityCount; i++) {
201                                 priorityList.add(String.valueOf(i));
202                         }
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());
207                 }
208                 catch (Exception e){
209                         e.printStackTrace();
210                 }
211         }
212
213
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{
216                 try {
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;
223                         try{
224                                 jsonContent = decodeContent(root.get("policyJSON")).toString();
225                         }catch(Exception e){
226                                 logger.error("Error while decoding microservice content");
227                         }
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;
232                         }
233                         
234                         if(root.get("policyData").get("model").get("path").size() != 0){
235                                 String dirName = "";
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;
238                                 }
239                                 if(policyData.isEditPolicy){
240                                         policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
241                                 }else{
242                                         policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", ""));
243                                 }
244                         }else{
245                                 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
246                         }
247                         
248                         if (policyData.getTtlDate()==null){
249                                 policyData.setTtlDate("NA");
250                         }else{
251                                 String dateTTL = policyData.getTtlDate();
252                                 String newDate = convertDate(dateTTL);
253                                 policyData.setTtlDate(newDate);
254                         }
255                         
256                         int version = 0;
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();
268                                         }
269                                 }
270                         }               
271                         if(highestVersion != 0){
272                                 version = highestVersion;
273                                 descriptionVersion = highestVersion +1;         
274                         }else{
275                                 version = 1;
276                                 descriptionVersion = 1;
277                         }
278                         
279                         //set policy adapter values for Building JSON object containing policy data
280                         String createdBy = "";
281                         String modifiedBy = userId;
282                         if(descriptionVersion == 1){
283                                 createdBy = userId;
284                         }else{
285                                 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
286                                 File policyPath = new File(policyName);
287                                 try {
288                                         createdBy =     XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
289                                 } catch (IOException e) {
290                                         createdBy = "guest";
291                                 }
292                         }
293                         
294                         policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
295                         policyData.setEcompName(policyData.getEcompName());
296                         //get the jsonBody 
297                         String jsonBody = null;
298                         try {
299                                 jsonBody = constructJson(policyData, jsonContent);
300                         } catch (Exception e) {
301                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
302                         }
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());
311                                         break;
312                                 }
313                         }
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);
321                         } else {
322                                 //send it for policy creation
323                                 policyData.setVersion(String.valueOf(version));
324                                 policyData.setHighestVersion(version);
325                                 successMap = engine.createPolicyRequest(policyData);
326
327                         }
328
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();
336                                 if(file != null){
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);
356                                                                 }
357                                                         }
358                                                 }
359                                         }else{
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);
367                                         }
368                                 }
369                         }
370                         
371                         System.out.println(root);
372                         response.setCharacterEncoding("UTF-8");
373                         response.setContentType("application / json");
374                         request.setCharacterEncoding("UTF-8");
375
376                         PrintWriter out = response.getWriter();
377                         String responseString = mapper.writeValueAsString(successMap);
378                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
379                         out.write(j.toString());
380                         return null;
381                 }
382                 catch (Exception e){
383                         response.setCharacterEncoding("UTF-8");
384                         request.setCharacterEncoding("UTF-8");
385                         PrintWriter out = response.getWriter();
386                         out.write(e.getMessage());
387                 }
388                 return null;
389         }
390
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());
397                 }
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("@"));
413                         }else{
414                                 presKey = key;
415                         }
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();
422                                 }
423                         }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){ 
424                                 jsonResult.put(oldValue, jsonArray);
425                                 isArray = false;
426                                 jsonArray = new JSONArray();
427                         }
428                         /*if(node.size()!=0 && key.contains("@")){
429                                 
430                         }else{
431                                 if(node.size()!=0){
432                                         
433                                 }
434                         }*/
435                         prevKey = presKey;
436                         // 
437                         if(key.contains(".")){
438                                 if(nodeKey==null){
439                                         nodeKey = key.substring(0,key.indexOf("."));
440                                 }
441                                 if(nodeKey.equals(key.substring(0,key.indexOf(".")))){
442                                         node.put(key.substring(key.indexOf(".")+1), element.get(key));
443                                 }else{
444                                         if(node.size()!=0){
445                                                 if(nodeKey.contains("@")){
446                                                         if(arryKey==null){
447                                                                 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
448                                                         }
449                                                         if(nodeKey.endsWith("@0")){
450                                                                 isArray = true;
451                                                                 jsonArray = new JSONArray();
452                                                         }
453                                                         if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
454                                                                 jsonArray.put(decodeContent(node));
455                                                         } 
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();
462                                                         }
463                                                         arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
464                                                 }else{
465                                                         isArray = false;
466                                                         jsonResult.put(nodeKey, decodeContent(node));
467                                                 }
468                                                 node = nodeFactory.objectNode();
469                                         }
470                                         nodeKey = key.substring(0,key.indexOf("."));
471                                         if(nodeKey.contains("@")){
472                                                 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
473                                         }
474                                         node.put(key.substring(key.indexOf(".")+1), element.get(key));
475                                 }
476                         }else if(node.size()!=0){
477                                 if(nodeKey.contains("@")){
478                                         if(arryKey==null){
479                                                 arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
480                                         }
481                                         if(nodeKey.endsWith("@0")){
482                                                 isArray = true;
483                                                 jsonArray = new JSONArray();
484                                         }
485                                         if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){
486                                                 jsonArray.put(decodeContent(node));
487                                         }
488                                         jsonResult.put(arryKey, jsonArray);
489                                         jsonArray = new JSONArray();
490                                         arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
491                                 }else{
492                                         isArray = false;
493                                         jsonResult.put(nodeKey, decodeContent(node));
494                                 }
495                                 node = nodeFactory.objectNode();
496                                 if(key.contains("@")){
497                                         isArray = true;
498                                         if(key.endsWith("@0")|| jsonArray==null){
499                                                 jsonArray = new JSONArray();
500                                         }
501                                 }else if(!key.contains("@")){
502                                         isArray = false;
503                                 }
504                                 if(isArray){
505                                         if(oldValue==null){
506                                                 oldValue = key.substring(0,key.indexOf("@"));
507                                         }
508                                         if(oldValue!=prevKey){
509                                                 oldValue = key.substring(0,key.indexOf("@"));
510                                         }
511                                         if(oldValue.equals(key.substring(0,key.indexOf("@")))){
512                                                 jsonArray.put(element.get(key));
513                                         }else{
514                                                 jsonResult.put(oldValue, jsonArray);
515                                                 jsonArray = new JSONArray();
516                                         }
517                                         oldValue = key.substring(0,key.indexOf("@"));
518                                 }else{
519                                         jsonResult.put(key, element.get(key));
520                                 }
521                         }else{
522                                 if(key.contains("@")){
523                                         isArray = true;
524                                         if(key.endsWith("@0")|| jsonArray==null){
525                                                 jsonArray = new JSONArray();
526                                         }
527                                 }else if(!key.contains("@")){
528                                         isArray = false;
529                                 }
530                                 if(isArray){
531                                         if(oldValue==null){
532                                                 oldValue = key.substring(0,key.indexOf("@"));
533                                         }
534                                         if(oldValue!=prevKey){
535                                                 oldValue = key.substring(0,key.indexOf("@"));
536                                         }
537                                         if(oldValue.equals(key.substring(0,key.indexOf("@")))){
538                                                 jsonArray.put(element.get(key));
539                                         }else{
540                                                 jsonResult.put(oldValue, jsonArray);
541                                                 jsonArray = new JSONArray();
542                                         }
543                                         oldValue = key.substring(0,key.indexOf("@"));
544                                 }else{
545                                         jsonResult.put(key, element.get(key));
546                                 }
547                         }
548                 }
549                 if(node.size()>0){
550                         if(nodeKey.contains("@")){
551                                 if(jsonArray==null){
552                                         jsonArray = new JSONArray();
553                                 }
554                                 if(arryKey==null){
555                                         arryKey = nodeKey.substring(0,nodeKey.indexOf("@"));
556                                 }
557                                 jsonArray.put(decodeContent(node));
558                                 jsonResult.put(arryKey, jsonArray);
559                                 isArray = false;;
560                         }else{
561                                 jsonResult.put(nodeKey, decodeContent(node));
562                         }
563                 }
564                 if(isArray && jsonArray.length() > 0){
565                         jsonResult.put(oldValue, jsonArray);
566                 }
567                 return jsonResult;
568         }
569
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 = "";
578                         try{
579                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
580                         }catch(Exception e){
581                                 description = policy.getDescription();
582                         }
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) {
604                                                                         int index = 0;
605                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
606                                                                         while (matchList.size()>1 && iterMatch.hasNext()) {
607                                                                                 MatchType match = iterMatch.next();
608                                                                                 //
609                                                                                 // Under the match we have attributevalue and
610                                                                                 // attributeDesignator. So,finally down to the actual attribute.
611                                                                                 //
612                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
613                                                                                 String value = (String) attributeValue.getContent().get(0);
614
615                                                                                 // First match in the target is EcompName, so set that value.
616                                                                                 if (index == 0) {
617                                                                                         policyAdapter.setEcompName(value);
618                                                                                 }
619                                                                                 if (index == 1){
620                                                                                         policyAdapter.setConfigName(value);
621                                                                                 }
622                                                                                 if (index == 2){
623                                                                                         if(value != null){
624                                                                                                 readFile(policyAdapter);
625                                                                                         }
626                                                                                 }
627                                                                                 if (index == 3){
628                                                                                         policyAdapter.setUuid(value);
629                                                                                 }
630                                                                                 if (index == 4){
631                                                                                         policyAdapter.setLocation(value);
632                                                                                 }
633                                                                                 if (index ==  5){
634                                                                                         policyAdapter.setRiskType(value);
635                                                                                 }
636
637                                                                                 if (index ==  6){
638                                                                                         policyAdapter.setRiskLevel(value);
639                                                                                 }
640                                                                                 
641                                                                                 if (index ==  7){
642                                                                                         policyAdapter.setGuard(value);
643                                                                                 }
644                                                                                 if (index == 8 && !value.contains("NA")){
645                                                                                         String newDate = convertDate(value, true);
646                                                                                         policyAdapter.setTtlDate(newDate);
647                                                                                 }
648                                                                                 index++;
649                                                                         }
650                                                                 }
651                                                         }
652                                                 }
653                                         }
654                                 }
655                         }
656                 }
657
658         }
659
660         private String convertDate(String dateTTL, boolean portalType) {
661                 String formateDate = null;
662                 String[] date;
663                 String[] parts;
664                 
665                 if (portalType){
666                         parts = dateTTL.split("-");
667                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
668                 } else {
669                         date  = dateTTL.split("T");
670                         parts = date[0].split("-");
671                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
672                 }
673                 return formateDate;
674         }
675         
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();
683                 }               
684                 if (fileLocation == null) {
685                         return fileLocation;
686                 }
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();
693                                 try {
694                                         inputStream = new FileInputStream(location);
695                                 } catch (FileNotFoundException e) {
696                                         e.printStackTrace();
697                                 }
698                                 if (location.endsWith("json")) {
699                                         JsonReader jsonReader = null;
700                                         jsonReader = Json.createReader(inputStream);
701                                         ObjectMapper mapper = new ObjectMapper();
702                                         try {
703                                                 DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(jsonReader.read().toString(), DCAEMicroServiceObject.class);
704                                                 policyScopeName = getPolicyScope(msBody.getPolicyScope());
705                                                 policyAdapter.setPolicyScope(policyScopeName);
706
707                                                 policyAdapter.setPriority(msBody.getPriority());
708                                                 
709                                                 if (msBody.getVersion()!= null){
710                                                         policyAdapter.setServiceType(msBody.getService() + "-v" + msBody.getVersion());
711                                                 }else{
712                                                         policyAdapter.setServiceType(msBody.getService());
713                                                 }
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);
719                                                 }
720                                                 
721                                         } catch (Exception e) {
722                                                 e.printStackTrace();
723                                         }
724                                         jsonReader.close();
725                                 }
726                         }
727                 }
728                 return fileName;
729                 
730         }
731         
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));
748                                                 }
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());
754                                         }       
755                                         }else{
756                                                 data.put(key+"@"+i, arrayvalue.toString());
757                                         }       
758                         }
759                         }else{
760                                 data.put(key.toString(), value.toString());
761                         }       
762                 }
763         }
764         
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)){
772                                         break;
773                                 }               
774                         }
775                 }
776                 return pScope.getGroupName();
777         }
778         
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)){
786                                         break;
787                                 }               
788                         }
789                 }
790                 return pScope;
791         }
792         
793         private String constructJson(PolicyAdapter policyAdapter, String jsonContent) {
794                 ObjectWriter om = new ObjectMapper().writer();
795                 String json="";
796                 DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
797
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]);
803                         }
804                 }
805                 if(policyAdapter.getUuid()!=null){
806                         microServiceObject.setUuid(policyAdapter.getUuid());
807                 }
808
809                 if(policyAdapter.getLocation()!=null){
810                         microServiceObject.setLocation(policyAdapter.getLocation());
811                 }
812                 if(policyAdapter.getPolicyName()!=null){
813                         microServiceObject.setPolicyName(policyAdapter.getPolicyName());
814                 }
815
816                 if(policyAdapter.getConfigName()!=null){
817                         microServiceObject.setConfigName(policyAdapter.getConfigName());
818                 }
819                 if(policyAdapter.getPolicyDescription()!=null){
820                         microServiceObject.setDescription(policyAdapter.getPolicyDescription());
821                 }
822                 if (policyAdapter.getPriority()!=null){
823                         microServiceObject.setPriority(policyAdapter.getPriority());
824                 }else {
825                         microServiceObject.setPriority("9999");
826                 }
827                 microServiceObject.setContent(jsonContent);
828                 GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
829                 microServiceObject.setPolicyScope(policyScopeValue.getGroupList());             
830                 try {
831                         json = om.writeValueAsString(microServiceObject);
832                 } catch (JsonProcessingException e) {
833                         logger.error("Error writing out the object");
834                 }
835                 System.out.println(json);
836                 String cleanJson = cleanUPJson(json);
837                 return cleanJson;
838         }
839         
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[]{"\\", "[", "]"});
844                 
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[]{""});
851                 return cleanJason;
852         }
853
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>();
857                         String temp = null;
858                         String key;
859                         String value;
860                         for (Entry<String, String> entry : attributesMap.entrySet()) {
861                                 key = entry.getKey();
862                                 value = entry.getValue();
863                                 attribute.put(key, value);
864                         }
865                         for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
866                                 key = entryRef.getKey();
867                                 value = entryRef.getValue().toString();
868                                 attribute.put(key, value);
869                         }
870                         for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
871                                 key = entryList.getKey();
872                                 value = entryList.getValue().toString();
873                                 attribute.put(key, value);
874                         }
875                         for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
876                                 key = arrayList.getKey();
877                                 temp = null;
878                                 for (Object textList : arrayList.getValue()){
879                                         if (temp == null){
880                                                 temp = "[" + textList;
881                                         }else{
882                                                 temp = temp + "," + textList;
883                                         }
884                                 }
885                                 attribute.put(key, temp+ "]");                  
886                         }
887
888                         return  attribute;
889                 }
890                 
891                 private String convertDate(String dateTTL) {
892                         String formateDate = null;
893                         String[] date  = dateTTL.split("T");
894                         String[] parts = date[0].split("-");
895                         
896                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
897                         return formateDate;
898                 }
899 }
900
901 class DCAEMicroServiceObject {
902
903         public String service;
904         public String location;
905         public String uuid;
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;
913         
914         public String getPolicyScope() {
915                 return policyScope;
916         }
917         public void setPolicyScope(String policyScope) {
918                 this.policyScope = policyScope;
919         }
920         
921         public String getPriority() {
922                 return priority;
923         }
924         public void setPriority(String priority) {
925                 this.priority = priority;
926         }
927         public String getVersion() {
928                 return version;
929         }
930         public void setVersion(String version) {
931                 this.version = version;
932         }
933         private Object content;
934         
935         
936         public String getPolicyName() {
937                 return policyName;
938         }
939         public void setPolicyName(String policyName) {
940                 this.policyName = policyName;
941         }
942         public String getDescription() {
943                 return description;
944         }
945         public void setDescription(String description) {
946                 this.description = description;
947         }
948         public String getConfigName() {
949                 return configName;
950         }
951         public void setConfigName(String configName) {
952                 this.configName = configName;
953         }
954         public Object getContent() {
955                 return content;
956         }
957         public void setContent(Object content) {
958                 this.content = content;
959         }
960         
961         public String getService() {
962                 return service;
963         }
964         public void setService(String service) {
965                 this.service = service;
966         }
967         public String getLocation() {
968                 return location;
969         }
970         public void setLocation(String location) {
971                 this.location = location;
972         }
973
974         public String getUuid() {
975                 return uuid;
976         }
977         public void setUuid(String uuid) {
978                 this.uuid = uuid;
979         }
980         public String getTemplateVersion() {
981                 return templateVersion;
982         }
983         public void setTemplateVersion(String templateVersion) {
984                 this.templateVersion = templateVersion;
985         }
986         
987 }