Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / controller / CreateClosedLoopFaultController.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.PrintWriter;
29 import java.io.UnsupportedEncodingException;
30 import java.net.URLEncoder;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.text.DateFormat;
34 import java.text.ParseException;
35 import java.text.SimpleDateFormat;
36 import java.util.ArrayList;
37 import java.util.Date;
38 import java.util.HashMap;
39 import java.util.Iterator;
40 import java.util.LinkedHashMap;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.UUID;
44
45 import javax.json.Json;
46 import javax.json.JsonReader;
47 import javax.servlet.http.HttpServletRequest;
48 import javax.servlet.http.HttpServletResponse;
49
50 import org.json.JSONObject;
51 import org.openecomp.policy.adapter.ClosedLoopFaultBody;
52 import org.openecomp.policy.adapter.ClosedLoopFaultTriggerUISignatures;
53 import org.openecomp.policy.adapter.ClosedLoopSignatures;
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.RuleAlgorithmsDao;
59 import org.openecomp.policy.dao.WatchPolicyNotificationDao;
60 import org.openecomp.policy.elk.client.PolicyElasticSearchController;
61 import org.openecomp.policy.rest.dao.VarbindDictionaryDao;
62 import org.openecomp.policy.rest.jpa.EcompName;
63 import org.openecomp.policy.rest.jpa.PolicyVersion;
64 import org.openecomp.policy.rest.jpa.RuleAlgorithms;
65 import org.openecomp.policy.rest.jpa.VarbindDictionary;
66 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
67 import org.openecomp.portalsdk.core.web.support.UserUtils;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.stereotype.Controller;
70 import org.springframework.web.bind.annotation.RequestMapping;
71 import org.springframework.web.servlet.ModelAndView;
72
73 import com.att.research.xacml.api.XACML3;
74 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
75 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
76 import com.fasterxml.jackson.databind.DeserializationFeature;
77 import com.fasterxml.jackson.databind.JsonNode;
78 import com.fasterxml.jackson.databind.ObjectMapper;
79 import com.fasterxml.jackson.databind.ObjectWriter;
80 import com.google.common.base.Joiner;
81
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
84 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
85 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
86 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
87 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
88
89 @Controller
90 @RequestMapping("/")
91 public class CreateClosedLoopFaultController extends RestrictedBaseController{
92  
93         private static RuleAlgorithmsDao ruleAlgorithmsDao;
94         private static PolicyVersionDao policyVersionDao;
95         private static VarbindDictionaryDao varbindDictionaryDao;
96         private static WatchPolicyNotificationDao policyNotificationDao;
97         
98         @Autowired
99         private CreateClosedLoopFaultController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, VarbindDictionaryDao varbindDictionaryDao,
100                         WatchPolicyNotificationDao policyNotificationDao){
101                 CreateClosedLoopFaultController.policyVersionDao = policyVersionDao;
102                 CreateClosedLoopFaultController.ruleAlgorithmsDao = ruleAlgorithmsDao;
103                 CreateClosedLoopFaultController.varbindDictionaryDao = varbindDictionaryDao;
104                 CreateClosedLoopFaultController.policyNotificationDao = policyNotificationDao;
105         }
106         
107         public CreateClosedLoopFaultController(){}
108         protected PolicyAdapter policyAdapter = null;
109         private String ruleID = "";
110         public String newPolicyID() {
111                 return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"),
112                                 PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID());
113         }
114         
115         @RequestMapping(value={"/policyController/save_Faultpolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
116         public ModelAndView saveFaultPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
117                 try {
118                         String userId = UserUtils.getUserIdFromCookie(request);
119                         RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine();
120                         ObjectMapper mapper = new ObjectMapper();
121                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
122                         JsonNode root = mapper.readTree(request.getReader());
123                         PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class);       
124                         TrapDatas trapDatas = mapper.readValue(root.get("trapData").toString(), TrapDatas.class);
125                         TrapDatas faultDatas = mapper.readValue(root.get("faultData").toString(), TrapDatas.class);
126                         ClosedLoopGridJSONData policyJsonData = mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class);
127                         ClosedLoopFaultBody jsonBody = mapper.readValue(root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
128                         policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
129                         if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
130                                 policyData.isEditPolicy = true;
131                         }
132                         
133                         if (policyData.getTtlDate()==null){
134                                 policyData.setTtlDate("NA");
135                         }else{
136                                 String dateTTL = policyData.getTtlDate();
137                                 String newDate = convertDate(dateTTL);
138                                 policyData.setTtlDate(newDate);
139                         }
140                         
141                         if(root.get("policyData").get("model").get("path").size() != 0){
142                                 String dirName = "";
143                                 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
144                                         dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
145                                 }
146                                 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
147                         }else{
148                                 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
149                         }
150                         ArrayList<Object> trapSignatureDatas = new ArrayList<Object>();
151                         if(trapDatas.getTrap1() != null){
152                                 trapSignatureDatas.add(trapDatas);
153                         }
154                         ArrayList<Object> faultSignatureDatas = new ArrayList<Object>();
155                         if(faultDatas.getTrap1() != null){
156                                 faultSignatureDatas.add(faultDatas);
157                         }
158                         
159                         String resultBody = "";
160                         if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){
161                                 resultBody = resultBody + "(";
162                                 for(int i = policyJsonData.getConnecttriggerSignatures().size()-1; i>=0 ; i--){
163                                         String connectBody = connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(), trapSignatureDatas.get(0));
164                                         resultBody = resultBody  + connectBody;
165                                 }
166                                 resultBody = resultBody + ")";
167                         }else{
168                                 if(!trapSignatureDatas.isEmpty()){
169                                         resultBody = callTrap("nill", trapSignatureDatas.get(0));
170                                 }
171                         }
172                         ClosedLoopSignatures triggerSignatures = new ClosedLoopSignatures();
173                         triggerSignatures.setSignatures(resultBody);
174                         if(policyData.getClearTimeOut() != null){
175                                 triggerSignatures.setTimeWindow(Integer.parseInt(policyData.getClearTimeOut()));        
176                                 triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge()));
177                                 ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures();
178                                 if(!trapSignatureDatas.isEmpty()){
179                                         uiTriggerSignatures.setSignatures(getUITriggerSignature("Trap", trapSignatureDatas.get(0)));
180                                         if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){
181                                                 uiTriggerSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures()));
182                                         }                               
183                                 }                       
184                                 jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures);
185                                 jsonBody.setTriggerTimeWindowUsedForUI(Integer.parseInt(policyData.getClearTimeOut()));
186                                 jsonBody.setTrapMaxAgeUsedForUI(Integer.parseInt(policyData.getTrapMaxAge()));
187                         }
188                         
189                         jsonBody.setTriggerSignatures(triggerSignatures);
190                         String faultBody = "";
191                         if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){
192                                 faultBody = faultBody + "(";
193                                 for(int i = policyJsonData.getConnectVerificationSignatures().size()-1; i>=0 ; i--){
194                                         String connectBody = connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(), faultSignatureDatas.get(0));
195                                         faultBody = faultBody  + connectBody;
196                                 }
197                                 faultBody = faultBody + ")";
198                         }else{
199                                 if(!faultSignatureDatas.isEmpty()){
200                                         faultBody = callTrap("nill", faultSignatureDatas.get(0));
201                                 }
202                         }
203                         ClosedLoopSignatures faultSignatures = new ClosedLoopSignatures();
204                         faultSignatures.setSignatures(faultBody);
205                         if(policyData.getVerificationclearTimeOut() != null){
206                                 faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut()));
207                                 ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures();
208                                 if(!faultSignatureDatas.isEmpty()){
209                                         uifaultSignatures.setSignatures(getUITriggerSignature("Fault", faultSignatureDatas.get(0)));
210                                         if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){
211                                                 uifaultSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures()));
212                                         }               
213                                 }
214                                 
215                                 jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures);
216                                 jsonBody.setVerfificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut()));
217                         }               
218                         jsonBody.setVerificationSignatures(faultSignatures);
219                         ObjectWriter om = new ObjectMapper().writer();
220                         String json = om.writeValueAsString(jsonBody);
221                         policyData.setJsonBody(json);
222                         
223                         int version = 0;
224                         int highestVersion = 0;
225                         int descriptionVersion = 0;
226                         //get the highest version of policy from policy version table.
227                         //getting the sub scope domain where the policy is created or updated
228                         String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_Fault_" + policyData.getPolicyName();
229                         List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName);
230                         if (policyVersionList.size() > 0) {             
231                                 for(int i = 0;  i < policyVersionList.size(); i++) {
232                                         PolicyVersion entityItem = policyVersionList.get(i);
233                                         if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
234                                                 highestVersion = entityItem.getHigherVersion();
235                                         }
236                                 }
237                         }               
238                         if(highestVersion != 0){
239                                 version = highestVersion;
240                                 descriptionVersion = highestVersion +1;         
241                         }else{
242                                 version = 1;
243                                 descriptionVersion = 1;
244                         }
245                         
246                         //set policy adapter values for Building JSON object containing policy data
247                         String createdBy = "";
248                         String modifiedBy = userId;
249                         if(descriptionVersion == 1){
250                                 createdBy = userId;
251                         }else{
252                                 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
253                                 File policyPath = new File(policyName);
254                                 try {
255                                         createdBy =     XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
256                                 } catch (IOException e) {
257                                         createdBy = "guest";
258                                 }
259                         }
260                         
261                         policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
262                         Map<String, String> successMap = new HashMap<String, String>();
263                         //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
264                         List<RuleAlgorithms> ruleAlgorithsList = ruleAlgorithmsDao.getRuleAlgorithms();
265                         for (int i = 0; i < ruleAlgorithsList.size(); i++) {
266                                 RuleAlgorithms a = ruleAlgorithsList.get(i);
267                                 if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) {
268                                         policyData.setRuleCombiningAlgId(a.getXacmlId());
269                                         break;
270                                 }
271                         }
272                         if (policyData.isEditPolicy()){
273                                 //increment the version and set in policyAdapter
274                                 policyData.setVersion(String.valueOf(version));
275                                 policyData.setHighestVersion(version);
276                                 policyData.setPolicyID(this.newPolicyID());
277                                 policyData.setRuleID(ruleID);
278                                 successMap = engine.updatePolicyRequest(policyData);
279                         } else {
280                                 //send it for policy creation
281                                 policyData.setVersion(String.valueOf(version));
282                                 policyData.setHighestVersion(version);
283                                 successMap = engine.createPolicyRequest(policyData);
284
285                         }
286
287                         if (successMap.containsKey("success")) {
288                                 // Add it into our tree
289                                 Path finalPolicyPath = null;
290                                 finalPolicyPath = Paths.get(successMap.get("success"));
291                                 PolicyElasticSearchController controller = new PolicyElasticSearchController();
292                                 controller.updateElk(finalPolicyPath.toString());
293                                 File file = finalPolicyPath.toFile();
294                                 if(file != null){
295                                         String policyName = file.toString();
296                                         String removePath = policyName.substring(policyName.indexOf("repository")+11);
297                                         String removeXml = removePath.replace(".xml", "");
298                                         String removeExtension = removeXml.substring(0, removeXml.indexOf("."));
299                                         List<PolicyVersion> versionlist = policyVersionDao.getPolicyVersionEntityByName(removeExtension);
300                                         if (versionlist.size() > 0) {           
301                                                 for(int i = 0;  i < versionlist.size(); i++) {
302                                                 PolicyVersion entityItem = versionlist.get(i);
303                                                         if(entityItem.getPolicyName().equals(removeExtension)){
304                                                                 version = entityItem.getHigherVersion() +1;
305                                                                 entityItem.setActiveVersion(version);
306                                                                 entityItem.setHigherVersion(version);
307                                                                 entityItem.setModifiedBy(userId);
308                                                                 policyVersionDao.update(entityItem);
309                                                                 if(policyData.isEditPolicy){
310                                                                         PolicyNotificationMail email = new PolicyNotificationMail();
311                                                                         String mode = "EditPolicy";
312                                                                         String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
313                                                                         email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao);
314                                                                 }
315                                                         }
316                                                 }
317                                         }else{
318                                                 PolicyVersion entityItem = new PolicyVersion();
319                                                 entityItem.setActiveVersion(version);
320                                                 entityItem.setHigherVersion(version);
321                                                 entityItem.setPolicyName(removeExtension);
322                                                 entityItem.setCreatedBy(userId);
323                                                 entityItem.setModifiedBy(userId);
324                                                 policyVersionDao.Save(entityItem);
325                                         }
326                                 }
327                         }
328                         
329                         response.setCharacterEncoding("UTF-8");
330                         response.setContentType("application / json");
331                         request.setCharacterEncoding("UTF-8");
332
333                         PrintWriter out = response.getWriter();
334                         String responseString = mapper.writeValueAsString(successMap);
335                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
336                         out.write(j.toString());
337                         return null;
338                 }
339                 catch (Exception e){
340                         response.setCharacterEncoding("UTF-8");
341                         request.setCharacterEncoding("UTF-8");
342                         PrintWriter out = response.getWriter();
343                         out.write(e.getMessage());
344                 }
345                 return null;
346         }
347         
348         //connect traps data set to JSON Body as String
349         @SuppressWarnings("rawtypes")
350         private String getUIConnectTraps(ArrayList<Object> connectTrapSignatures) {
351                 String resultBody = "";
352                 String connectMainBody = "";
353                 for(int j = 0; j < connectTrapSignatures.size(); j++){
354                         Map<String, String> connectTraps = (Map<String, String>)connectTrapSignatures.get(j);
355                         String connectBody = "";
356                         Object object = connectTraps;
357                         if(object instanceof LinkedHashMap<?, ?>){
358                                 String notBox = "";
359                                 if(((LinkedHashMap) object).keySet().contains("notBox")){
360                                         notBox = ((LinkedHashMap) object).get("notBox").toString();
361                                 }
362                                 String connectTrap1 = ((LinkedHashMap) object).get("connectTrap1").toString();
363                                 String trapCount1 = ((LinkedHashMap) object).get("trapCount1").toString();
364                                 String operatorBox = ((LinkedHashMap) object).get("operatorBox").toString();
365                                 String connectTrap2 = ((LinkedHashMap) object).get("connectTrap2").toString();
366                                 String trapCount2 = ((LinkedHashMap) object).get("trapCount2").toString();
367                                 connectBody = notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + connectTrap2 + "@!" + trapCount2 + "#!?!"; 
368                         }
369                         resultBody = resultBody + connectBody;
370                 }
371                 connectMainBody = connectMainBody + resultBody;
372                 return connectMainBody;
373         }
374
375                 
376
377                 // get Trigger signature from JSON body
378                 private String getUITriggerSignature(String trap, Object object2) {
379                         String triggerBody = "";
380                         TrapDatas trapDatas = (TrapDatas) object2;
381                         ArrayList<Object> attributeList = new ArrayList<>();
382                         // Read the Trap 
383                         if(trap.startsWith("Trap")){
384                                 if(trapDatas.getTrap1()!= null){
385                                         attributeList.add(trapDatas.getTrap1());
386                                 }
387                                 if(trapDatas.getTrap2()!= null){
388                                         attributeList.add(trapDatas.getTrap2());
389                                 }
390                                 if(trapDatas.getTrap3()!= null){
391                                         attributeList.add(trapDatas.getTrap3());
392                                 }
393                                 if(trapDatas.getTrap4()!= null){
394                                         attributeList.add(trapDatas.getTrap4());
395                                 }
396                                 if(trapDatas.getTrap5()!= null){
397                                         attributeList.add(trapDatas.getTrap5());
398                                 }
399                                 if(trapDatas.getTrap6()!= null){
400                                         attributeList.add(trapDatas.getTrap6());
401                                 }
402                         }else{
403                                 if(trap.equals("Fault")){
404                                         if(trapDatas.getTrap1()!= null){
405                                                 attributeList.add(trapDatas.getTrap1());
406                                         }
407                                         if(trapDatas.getTrap2()!= null){
408                                                 attributeList.add(trapDatas.getTrap2());
409                                         }
410                                         if(trapDatas.getTrap3()!= null){
411                                                 attributeList.add(trapDatas.getTrap3());
412                                         }
413                                         if(trapDatas.getTrap4()!= null){
414                                                 attributeList.add(trapDatas.getTrap4());
415                                         }
416                                         if(trapDatas.getTrap5()!= null){
417                                                 attributeList.add(trapDatas.getTrap5());
418                                         }
419                                         if(trapDatas.getTrap6()!= null){
420                                                 attributeList.add(trapDatas.getTrap6());
421                                         }                               
422                                 }       
423                         }
424
425                         for(int j = 0; j < attributeList.size(); j++){
426                                 String signatureBody = "";
427                                 ArrayList<Object> connectTraps = (ArrayList<Object>) attributeList.get(j);
428                                 for(int i =0 ; i < connectTraps.size(); i++){
429                                         String connectBody = "";
430                                         Object object = connectTraps.get(i);
431                                         if(object instanceof LinkedHashMap<?, ?>){
432                                                 String notBox = "";
433                                                 if(((LinkedHashMap) object).keySet().contains("notBox")){
434                                                         notBox = ((LinkedHashMap) object).get("notBox").toString();
435                                                 }
436                                                 String trigger1 = ((LinkedHashMap) object).get("trigger1").toString();
437                                                 String operatorBox = ((LinkedHashMap) object).get("operatorBox").toString();
438                                                 String trigger2 = ((LinkedHashMap) object).get("trigger2").toString();
439                                                 connectBody = notBox + "@!" + trigger1 + "@!" + operatorBox + "@!" + trigger2 + "#!"; 
440                                         }
441                                         signatureBody = signatureBody + connectBody;
442                                 }
443                                 triggerBody = triggerBody + signatureBody + "?!";
444                         }
445                         
446                         return triggerBody;             
447                 }
448
449                 private String convertDate(String dateTTL) {
450                         String formateDate = null;
451                         String[] date  = dateTTL.split("T");
452                         String[] parts = date[0].split("-");
453                         
454                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
455                         return formateDate;
456                 }
457                 
458         private String callTrap(String trap, Object object) {
459                 String signatureBody = "";
460                 TrapDatas trapDatas = (TrapDatas) object;
461                 ArrayList<Object> attributeList = new ArrayList<>();
462                 // Read the Trap 
463                 if(!trap.equals("nill")){
464                         try{
465                                 if(trap.startsWith("Trap")){
466                                         if(trap.equals("Trap1")){
467                                                  attributeList = trapDatas.getTrap1();
468                                         }else if(trap.equals("Trap2")){
469                                                 attributeList = trapDatas.getTrap2();
470                                         }else if(trap.equals("Trap3")){
471                                                 attributeList = trapDatas.getTrap3();
472                                         }else if(trap.equals("Trap4")){
473                                                 attributeList = trapDatas.getTrap4();
474                                         }else if(trap.equals("Trap5")){
475                                                 attributeList = trapDatas.getTrap5();
476                                         }else if(trap.equals("Trap6")){
477                                                 attributeList = trapDatas.getTrap6();
478                                         }
479                                 }else{
480                                         if(trap.equals("Fault")){
481                                                 if(trap.equals("Fault1")){
482                                                         attributeList = trapDatas.getTrap1();
483                                                 }else if(trap.equals("Fault2")){
484                                                         attributeList = trapDatas.getTrap2();
485                                                 }else if(trap.equals("Fault3")){
486                                                         attributeList = trapDatas.getTrap3();
487                                                 }else if(trap.equals("Fault4")){
488                                                         attributeList = trapDatas.getTrap4();
489                                                 }else if(trap.equals("Fault5")){
490                                                         attributeList = trapDatas.getTrap5();
491                                                 }else if(trap.equals("Fault6")){
492                                                         attributeList = trapDatas.getTrap6();
493                                                 }       
494                                         }
495                                 }
496                         } catch(Exception e){
497                                 return "(" + trap + ")";
498                         }
499                 }else{
500                         if(trapDatas.getTrap1()!=null){
501                                 attributeList = trapDatas.getTrap1();
502                         }else{
503                                 return "";
504                         }
505                 }
506                 signatureBody = signatureBody + "(" + readAttributes(attributeList, attributeList.size()-1) + ")";
507                 return signatureBody;
508         }
509
510         private String readAttributes(ArrayList<Object> object, int index) {
511                 String attributes = "";
512                 Map<String, String> trapSignatures = (Map<String, String>) object.get(index);
513                 // Read the Elements. 
514                 Object notBox = "";
515                 if(trapSignatures.keySet().contains("notBox")){
516                         notBox = trapSignatures.get("notBox");
517                 }
518                 if(notBox!=null){
519                         attributes = attributes + notBox.toString();
520                 }
521                 Object trapName1 = trapSignatures.get("trigger1");
522                 if(trapName1!=null){
523                         String attrib = trapName1.toString();
524                         if(attrib.startsWith("A")){
525                                 try{
526                                         int iy = Integer.parseInt(attrib.substring(1))-1;
527                                         attributes = attributes + "(" + readAttributes(object, iy) + ")";
528                                 }catch(NumberFormatException e){
529                                         try {
530                                                 attrib  = getVarbindOID(attrib);
531                                                 attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")";
532                                         } catch (UnsupportedEncodingException e1) {
533                                                 //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1);
534                                         }
535                                 }
536                         }else{
537                                 try {
538                                         attrib  = getVarbindOID(attrib);
539                                         attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")";
540                                 } catch (UnsupportedEncodingException e) {
541                                         //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e);
542                                 }
543                         }
544                 }else{
545                         return "";
546                 }
547                 Object comboBox = trapSignatures.get("operatorBox");
548                 if(comboBox!=null){
549                         attributes = attributes + comboBox.toString();
550                 }else{
551                         return attributes;
552                 }
553                 Object trapName2 = trapSignatures.get("trigger2"); 
554                 if(trapName2!=null){
555                         String attrib = trapName2.toString();
556                         if(attrib.startsWith("A")){
557                                 try{
558                                         int iy = Integer.parseInt(attrib.substring(1))-1;
559                                         attributes = attributes + "(" + readAttributes(object, iy) + ")";
560                                 }catch(NumberFormatException e){
561                                         try {
562                                                 attrib  = getVarbindOID(attrib);
563                                                 attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")";
564                                         } catch (UnsupportedEncodingException e1) {
565                                                 //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1);
566                                         }
567                                 }
568                         }else{
569                                 try {
570                                         attrib  = getVarbindOID(attrib);
571                                         attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")";
572                                 } catch (UnsupportedEncodingException e) {
573                                         //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e);
574                                 }
575                         }
576                 }
577                 return attributes;
578         }
579
580         private String getVarbindOID(String attrib) {
581                 VarbindDictionary varbindId = varbindDictionaryDao.getVarbindEntityByName(attrib).get(0);
582                 return varbindId.getVarbindOID();
583         }
584
585         private String connectTriggerSignature(int index, ArrayList<Object> triggerSignatures, Object object) {
586                 String resultBody = "";
587                 Map<String, String> connectTraps = (Map<String, String>) triggerSignatures.get(index);
588                 try{
589                         String notBox = "";
590                         if(connectTraps.keySet().contains("notBox")){
591                                 notBox = connectTraps.get("notBox");
592                         }
593                         resultBody = resultBody + "(" + notBox;
594                 }catch(NullPointerException e){
595                         resultBody = resultBody + "(";
596                 }
597                 String connectTrap1 = connectTraps.get("connectTrap1");
598                 if(connectTrap1.startsWith("Trap") || connectTrap1.startsWith("Fault")){
599                         String trapBody = callTrap(connectTrap1, object);
600                         if(trapBody!=null){
601                                 resultBody = resultBody + trapBody;
602                         }
603                 }else if(connectTrap1.startsWith("C")){
604                         for(int i=0; i<= triggerSignatures.size(); i++){
605                                 Map<String,String> triggerSignature = (Map<String, String>) triggerSignatures.get(i);
606                                 if(triggerSignature.get("id").equals(connectTrap1)){
607                                         resultBody = resultBody + "(";
608                                         String connectBody = connectTriggerSignature(i, triggerSignatures, object);
609                                         resultBody = resultBody + connectBody + ")";
610                                 }else{
611                                         i++;
612                                 }
613                         }
614                 }
615                 try{
616                         String trapCount1 = connectTraps.get("trapCount1");
617                         resultBody = resultBody + ", Time = " + trapCount1 + ")";
618                 }catch(NullPointerException e){
619                 }
620                 try{
621                         String operatorBox = connectTraps.get("operatorBox");
622                         resultBody = resultBody + operatorBox +"(";
623                 }catch (NullPointerException e){
624                 }
625                 try{
626                         String connectTrap2 = connectTraps.get("connectTrap2");
627                         if(connectTrap2.startsWith("Trap") || connectTrap2.startsWith("Fault")){
628                                 String trapBody = callTrap(connectTrap2, object);
629                                 if(trapBody!=null){
630                                         resultBody = resultBody + trapBody;
631                                 }
632                         }else if(connectTrap2.startsWith("C")){
633                                 for(int i=0; i<= triggerSignatures.size(); i++){
634                                         Map<String,String> triggerSignature = (Map<String, String>) triggerSignatures.get(i);
635                                         if(triggerSignature.get("id").equals(connectTrap2)){
636                                                 resultBody = resultBody + "(";
637                                                 String connectBody = connectTriggerSignature(i, triggerSignatures, object);
638                                                 resultBody = resultBody + connectBody + ")";
639                                         }else{
640                                                 i++;
641                                         }
642                                 }
643                         }
644                 }catch(NullPointerException e){
645                 }
646                 try{
647                         String trapCount2 = connectTraps.get("trapCount2");
648                         resultBody = resultBody + ", Time = " + trapCount2 + ")";
649                 }catch(NullPointerException e){
650                 }
651                 return resultBody;
652         }
653
654         public  void PrePopulateClosedLoopFaultPolicyData(PolicyAdapter policyAdapter) {
655                 if (policyAdapter.getPolicyData() instanceof PolicyType) {
656                         Object policyData = policyAdapter.getPolicyData();
657                         PolicyType policy = (PolicyType) policyData;
658                         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
659                         String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("Fault_") +6 , policyAdapter.getPolicyName().lastIndexOf("."));
660                         policyAdapter.setPolicyName(policyNameValue);
661                         String description = "";
662                         try{
663                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
664                         }catch(Exception e){
665                                 description = policy.getDescription();
666                         }
667                         policyAdapter.setPolicyDescription(description);
668                         // Get the target data under policy.
669                         TargetType target = policy.getTarget();
670                         if (target != null) {
671                                 // Under target we have AnyOFType
672                                 List<AnyOfType> anyOfList = target.getAnyOf();
673                                 if (anyOfList != null) {
674                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
675                                         while (iterAnyOf.hasNext()) {
676                                                 AnyOfType anyOf = iterAnyOf.next();
677                                                 // Under AnyOFType we have AllOFType
678                                                 List<AllOfType> allOfList = anyOf.getAllOf();
679                                                 if (allOfList != null) {
680                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
681                                                         int index = 0;
682                                                         while (iterAllOf.hasNext()) {
683                                                                 AllOfType allOf = iterAllOf.next();
684                                                                 // Under AllOFType we have Match
685                                                                 List<MatchType> matchList = allOf.getMatch();
686                                                                 if (matchList != null) {
687                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
688                                                                         while (iterMatch.hasNext()) {
689                                                                                 MatchType match = iterMatch.next();
690                                                                                 //
691                                                                                 // Under the match we have attributevalue and
692                                                                                 // attributeDesignator. So,finally down to the actual attribute.
693                                                                                 //
694                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
695                                                                                 String value = (String) attributeValue.getContent().get(0);
696
697                                                                                 // First match in the target is EcompName, so set that value.
698                                                                                 if (index == 1) {
699                                                                                         policyAdapter.setEcompName(value);
700                                                                                         EcompName ecompName = new EcompName();
701                                                                                         ecompName.setEcompName(value);
702                                                                                         policyAdapter.setEcompNameField(ecompName);
703                                                                                 }
704                                                                                 if (index ==  2){
705                                                                                         policyAdapter.setRiskType(value);
706                                                                                 }
707
708                                                                                 if (index ==  3){
709                                                                                         policyAdapter.setRiskLevel(value);
710                                                                                 }
711                                                                                 
712                                                                                 if (index ==  4){
713                                                                                         policyAdapter.setGuard(value);
714                                                                                 }
715                                                                                 if (index == 5 && !value.contains("NA")){
716                                                                                         String newDate = convertDate(value, true);
717                                                                                         policyAdapter.setTtlDate(newDate);
718                                                                                 }
719                                                                                 index++;
720                                                                         }
721                                                                 }
722                                                         }
723                                                 }
724                                         }
725                                 }
726                         }
727                         String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + ".";
728                         policyAdapter.setConfigBodyPath(jsonBodyName);
729                         readClosedLoopJSONFile(policyAdapter);
730                 }       
731                 
732         }
733
734         private String convertDate(String dateTTL, boolean portalType) {
735                 String formateDate = null;
736                 String[] date;
737                 String[] parts;
738                 
739                 if (portalType){
740                         parts = dateTTL.split("-");
741                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
742                 } else {
743                         date  = dateTTL.split("T");
744                         parts = date[0].split("-");
745                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
746                 }
747                 return formateDate;
748         }
749         
750         private String readClosedLoopJSONFile(PolicyAdapter policyAdapter) {
751                 String fileLocation = null;
752                 String fileName = policyAdapter.getConfigBodyPath();
753                 if (fileName != null ) {
754                         fileLocation = PolicyController.getConfigHome();
755                 }               
756                 if (fileLocation == null) {
757                         return fileLocation;
758                 }
759                 File dir = new File(fileLocation);
760                 File[] listOfFiles = dir.listFiles();
761                 for (File file : listOfFiles) {
762                         if (file.isFile() && file.getName().contains(fileName)) {
763                                 FileInputStream inputStream = null;
764                                 String location = file.toString();
765                                 try {
766                                         inputStream = new FileInputStream(location);
767                                 } catch (FileNotFoundException e) {
768                                         e.printStackTrace();
769                                 }
770                                 if (location.endsWith("json")) {
771                                         JsonReader jsonReader = null;
772                                         jsonReader = Json.createReader(inputStream);
773                                         ObjectMapper mapper = new ObjectMapper();
774                                         try {
775                                                 ClosedLoopFaultBody closedLoopBody = mapper.readValue(jsonReader.read().toString(), ClosedLoopFaultBody.class);
776                                                 if(closedLoopBody.getClosedLoopPolicyStatus().equalsIgnoreCase("ACTIVE")){
777                                                         closedLoopBody.setClosedLoopPolicyStatus("Active");
778                                                 }else{
779                                                         closedLoopBody.setClosedLoopPolicyStatus("InActive");
780                                                 }
781                                                 policyAdapter.setJsonBodyData(closedLoopBody);
782                                                 if(closedLoopBody.getTrapMaxAgeUsedForUI() != null){
783                                                         policyAdapter.setTrapMaxAge(closedLoopBody.getTrapMaxAgeUsedForUI().toString());
784                                                 }
785                                                 if(closedLoopBody.getTriggerTimeWindowUsedForUI() != null){
786                                                         policyAdapter.setClearTimeOut(closedLoopBody.getTriggerTimeWindowUsedForUI().toString());
787                                                 }
788                                                 if(closedLoopBody.getVerfificationTimeWindowUsedForUI() != null){
789                                                         policyAdapter.setVerificationclearTimeOut(closedLoopBody.getVerfificationTimeWindowUsedForUI().toString());
790                                                 }
791                                                 
792                                         } catch (Exception e) {
793                                                 e.printStackTrace();
794                                         }
795                                         jsonReader.close();
796                                 }
797                         }
798                 }
799                 return null;    
800         }
801
802 }
803
804 class ClosedLoopGridJSONData{
805
806         private String clearTimeOut;
807         private String trapMaxAge;
808         private String verificationclearTimeOut;
809         private ArrayList<Object> connecttriggerSignatures;
810         private ArrayList<Object> connectVerificationSignatures;
811
812         public String getClearTimeOut() {
813                 return clearTimeOut;
814         }
815         public void setClearTimeOut(String clearTimeOut) {
816                 this.clearTimeOut = clearTimeOut;
817         }
818         public String getTrapMaxAge() {
819                 return trapMaxAge;
820         }
821         public void setTrapMaxAge(String trapMaxAge) {
822                 this.trapMaxAge = trapMaxAge;
823         }
824         public String getVerificationclearTimeOut() {
825                 return verificationclearTimeOut;
826         }
827         public void setVerificationclearTimeOut(String verificationclearTimeOut) {
828                 this.verificationclearTimeOut = verificationclearTimeOut;
829         }
830         
831
832         public ArrayList<Object> getConnecttriggerSignatures() {
833                 return connecttriggerSignatures;
834         }
835         public void setConnecttriggerSignatures(ArrayList<Object> connecttriggerSignatures) {
836                 this.connecttriggerSignatures = connecttriggerSignatures;
837         }
838         public ArrayList<Object> getConnectVerificationSignatures() {
839                 return connectVerificationSignatures;
840         }
841         public void setConnectVerificationSignatures(ArrayList<Object> connectVerificationSignatures) {
842                 this.connectVerificationSignatures = connectVerificationSignatures;
843         }
844 }
845
846 class TrapDatas{
847         private ArrayList<Object> trap1;
848         private ArrayList<Object> trap2;
849         private ArrayList<Object> trap3;
850         private ArrayList<Object> trap4;
851         private ArrayList<Object> trap5;
852         private ArrayList<Object> trap6;
853         public ArrayList<Object> getTrap1() {
854                 return trap1;
855         }
856         public void setTrap1(ArrayList<Object> trap1) {
857                 this.trap1 = trap1;
858         }
859         public ArrayList<Object> getTrap2() {
860                 return trap2;
861         }
862         public void setTrap2(ArrayList<Object> trap2) {
863                 this.trap2 = trap2;
864         }
865         public ArrayList<Object> getTrap3() {
866                 return trap3;
867         }
868         public void setTrap3(ArrayList<Object> trap3) {
869                 this.trap3 = trap3;
870         }
871         public ArrayList<Object> getTrap4() {
872                 return trap4;
873         }
874         public void setTrap4(ArrayList<Object> trap4) {
875                 this.trap4 = trap4;
876         }
877         public ArrayList<Object> getTrap5() {
878                 return trap5;
879         }
880         public void setTrap5(ArrayList<Object> trap5) {
881                 this.trap5 = trap5;
882         }
883         public ArrayList<Object> getTrap6() {
884                 return trap6;
885         }
886         public void setTrap6(ArrayList<Object> trap6) {
887                 this.trap6 = trap6;
888         }
889 }