Initial OpenECOMP policy/engine commit
[policy/engine.git] / PolicyEngineAPI / src / main / java / org / openecomp / policy / std / StdPolicyEngine.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * PolicyEngineAPI
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
22 package org.openecomp.policy.std;
23
24 import java.io.ByteArrayInputStream;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30 import java.io.StringReader;
31 import java.net.HttpURLConnection;
32 import java.net.MalformedURLException;
33 import java.net.URI;
34 import java.net.URL;
35 import java.net.URLConnection;
36 import java.nio.charset.StandardCharsets;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.text.SimpleDateFormat;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Base64;
44 import java.util.Collection;
45 import java.util.Collections;
46 import java.util.Date;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Properties;
52 import java.util.UUID;
53
54 import javax.json.Json;
55 import javax.json.JsonArrayBuilder;
56 import javax.json.JsonObject;
57 import javax.json.JsonObjectBuilder;
58 import javax.json.JsonReader;
59 import javax.xml.parsers.DocumentBuilder;
60 import javax.xml.parsers.DocumentBuilderFactory;
61 import javax.xml.parsers.ParserConfigurationException;
62
63 import org.apache.commons.io.IOUtils;
64 import org.apache.http.entity.ContentType;
65 //import org.apache.log4j.Logger;
66 import org.json.JSONObject;
67 import org.openecomp.policy.api.AttributeType;
68 import org.openecomp.policy.api.ConfigRequestParameters;
69 import org.openecomp.policy.api.DecisionRequestParameters;
70 import org.openecomp.policy.api.DecisionResponse;
71 import org.openecomp.policy.api.DeletePolicyParameters;
72 import org.openecomp.policy.api.DictionaryParameters;
73 import org.openecomp.policy.api.EventRequestParameters;
74 import org.openecomp.policy.api.ImportParameters;
75 import org.openecomp.policy.api.NotificationHandler;
76 import org.openecomp.policy.api.NotificationScheme;
77 import org.openecomp.policy.api.PDPNotification;
78 import org.openecomp.policy.api.PolicyChangeResponse;
79 import org.openecomp.policy.api.PolicyClass;
80 import org.openecomp.policy.api.PolicyConfig;
81 import org.openecomp.policy.api.PolicyConfigException;
82 import org.openecomp.policy.api.PolicyConfigStatus;
83 import org.openecomp.policy.api.PolicyConfigType;
84 import org.openecomp.policy.api.PolicyDecision;
85 import org.openecomp.policy.api.PolicyDecisionException;
86 import org.openecomp.policy.api.PolicyEngineException;
87 import org.openecomp.policy.api.PolicyEventException;
88 import org.openecomp.policy.api.PolicyParameters;
89 import org.openecomp.policy.api.PolicyResponse;
90 import org.openecomp.policy.api.PolicyResponseStatus;
91 import org.openecomp.policy.api.PolicyType;
92 import org.openecomp.policy.api.PushPolicyParameters;
93 import org.openecomp.policy.api.RuleProvider;
94 //import org.openecomp.policy.utils.AAFPolicyClient;
95 //import org.openecomp.policy.utils.AAFPolicyException;
96 import org.w3c.dom.Document;
97 import org.xml.sax.SAXException;
98
99 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
100 import org.openecomp.policy.common.logging.flexlogger.Logger;
101
102 import com.att.research.xacml.api.Advice;
103 import com.att.research.xacml.api.AttributeAssignment;
104 import com.att.research.xacml.api.Decision;
105 import com.att.research.xacml.api.Obligation;
106 import com.att.research.xacml.api.Request;
107 import com.att.research.xacml.api.Response;
108 import com.att.research.xacml.api.Result;
109 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
110 import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
111 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
112
113 import com.att.research.xacml.api.pap.PAPException;
114 import com.att.research.xacml.api.pap.PDPPolicy;
115 import com.att.research.xacml.std.json.JSONRequest;
116 import com.att.research.xacml.std.json.JSONResponse;
117 import com.fasterxml.jackson.databind.ObjectMapper;
118 import com.google.common.base.CharMatcher;
119
120
121
122 /**
123  * PolicyEngine Implementation class
124  * 
125  * @version 1.0
126  */
127 public class StdPolicyEngine {
128         // Change the default Priority value here. 
129         private static final int defaultPriority = 9999;
130         
131         private String propertyFilePath = null;
132         private static List<String> pdps = null;
133         private static List<String> paps = null;
134         private static String environment= null; 
135         private static String userName = null;
136         private static String pass = null; 
137         private static List<String> encoding = null;
138         private static List<String> encodingPAP = null;
139         private List<String> pdp_default = null;
140         private List<String> pap_default = null;
141         private List<String> type_default = null;
142         private List<String> notificationType = new ArrayList<String>();
143         private List<String> uebURLList = new ArrayList<String>();
144         private NotificationScheme scheme = null;
145         private NotificationHandler handler = null;
146         private Matches match = null;
147         private Boolean decide = false;
148         private AutoClientUEB UEBClientThread = null;
149         private Thread registerUEBThread = null;
150         private boolean UEBThread = false;
151         private String policyId = null; 
152         private String description = null;      
153         private String pushVersion = null;
154         private boolean isValid = false;
155         private int responseCode = 0;
156         private boolean unique = false;
157         private boolean junit = false;
158         //private AAFPolicyClient aafClient = null;
159         // Backward code. 
160         private String pyPDPClientFile = null;
161         
162         final private static String uniqueID = UUID.randomUUID ().toString ();
163         
164         private static Logger logger = FlexLogger.getLogger(StdPolicyConfig.class.getName());
165         
166         /*
167          * Taking the Property file even if it null.
168          */
169         public StdPolicyEngine(String propertyFilePath)
170                         throws PolicyEngineException {
171                 setProperty(propertyFilePath);
172         }
173
174         /*
175          * Taking the Notification Constructor.
176          */
177         public StdPolicyEngine(String propertyFilePath, NotificationScheme scheme,
178                         NotificationHandler handler) throws PolicyEngineException {
179                 setProperty(propertyFilePath);
180                 this.scheme = scheme;
181                 this.handler = handler;
182                 if (!notificationType.get(0).equals("ueb")){
183                         AutoClientEnd.setAuto(scheme, handler);
184                 }
185                 notification(scheme, handler);
186         }
187
188         /*
189          * Taking the Notification Constructor.
190          */
191         public StdPolicyEngine(String propertyFilePath, NotificationScheme scheme)
192                         throws PolicyEngineException {
193                 setProperty(propertyFilePath);
194                 this.scheme = scheme;
195                 setScheme(scheme);
196         }
197
198         // This Call will be used by PyPDP Requests
199         public StdPolicyEngine(List<String> configURL, List<String> configPapURL, List<String> encodingPAP, List<String> encoding, NotificationScheme scheme, NotificationHandler handler, String environment, String clientProperties, Boolean isTest) {
200                 StdPolicyEngine.pdps = configURL;
201                 StdPolicyEngine.paps = configPapURL;
202                 StdPolicyEngine.encoding = encoding;
203                 StdPolicyEngine.encodingPAP = encodingPAP;
204                 StdPolicyEngine.environment = environment;
205                 Properties props = new Properties();
206                 props.setProperty("ENVIRONMENT", environment);
207                 //Not Supported for 1610 Open Source
208                 /*try {
209                         aafClient = AAFPolicyClient.getInstance(props);
210                 } catch (AAFPolicyException e) {
211                         logger.error(XACMLErrorConstants.ERROR_UNKNOWN + e.getMessage());
212                 }*/
213                 pyPDPClientFile = clientProperties;
214                 // Default Notification Type for PyPDPServers. 
215                 notificationType.add("websocket");
216                 if(!isTest){
217                         notification(scheme, handler);
218                 }
219         }
220
221         /*
222          * sendEvent API Implementation
223          */
224         public Collection<PolicyResponse> event(Map<String, String> eventAttributes, UUID requestID)
225                         throws PolicyEventException {
226                 Collection<PolicyResponse> policyResponse = null;
227                 policyResponse = event(eventAttributes, requestID, userName, pass);
228                 return policyResponse;
229         }
230         
231         /*
232          * sendEvent API Implementation for eventRequestParameters 
233          */
234         public Collection<PolicyResponse> event(EventRequestParameters eventRequestParameters) throws PolicyEventException{
235                 Collection<PolicyResponse> response = event(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID());
236                 return response;
237         }
238
239         /*
240          * getConfig API Implementation
241          */
242         public Collection<PolicyConfig> config(String eCOMPComponentName,
243                         String configName, Map<String, String> configAttributes, UUID requestID)
244                         throws PolicyConfigException {
245                 Collection<PolicyConfig> policyConfig = null;
246                 policyConfig = config(eCOMPComponentName, configName, configAttributes, requestID, userName, pass);
247                 return policyConfig;
248         }
249
250         /*
251          * getConfig API Implementation
252          */
253         public Collection<PolicyConfig> config(String eCOMPComponentName,
254                         String configName, UUID requestID) throws PolicyConfigException {
255                 Collection<PolicyConfig> policyConfig = null;
256                 policyConfig = config(eCOMPComponentName, configName,null, requestID, userName, pass);
257                 return policyConfig;
258         }
259
260         /*
261          * getConfig API Implementation
262          */
263         public Collection<PolicyConfig> config(String eCOMPComponentName, UUID requestID)
264                         throws PolicyConfigException {
265                 Collection<PolicyConfig> policyConfig = null;
266                 policyConfig = config(eCOMPComponentName, requestID, userName, pass);
267                 return policyConfig;
268         }
269
270         /*
271          * getConfig using the PolicyFileName Implementation
272          */
273         public Collection<PolicyConfig> policyName(String policyName, UUID requestID)
274                         throws PolicyConfigException {
275                 Collection<PolicyConfig> policyConfig = null;
276                 policyConfig = configPolicyName(policyName, requestID, userName, pass);
277                 return policyConfig;
278         }
279         
280         /*
281          * getConfig using configRequestParameters Implementation 
282          */
283         public Collection<PolicyConfig> config(ConfigRequestParameters configRequestParameters) throws PolicyConfigException{
284                 Collection<PolicyConfig> response = null;
285                 response = configRequest(configRequestParameters, userName, pass);
286                 return response;
287         }
288         
289         /*
290          * listPolicies using configRequestParameters Implementation
291          */
292         public Collection<String> listConfig(ConfigRequestParameters listPolicyRequestParameters) throws PolicyConfigException{
293                 Collection<String> policyList = new ArrayList<String>();
294                 policyList = listConfigRequest(listPolicyRequestParameters, userName, pass);
295                 return policyList;
296         }
297
298         /*
299          * getDecision using the decision Attributes.
300          */
301         public DecisionResponse decide(String eCOMPComponentName,
302                         Map<String, String> decisionAttributes, UUID requestID)
303                         throws PolicyDecisionException {
304                 DecisionResponse policyDecision = policyDecide(eCOMPComponentName,
305                                 decisionAttributes, requestID, userName, pass);
306                 return policyDecision;
307         }
308         
309         /*
310          * getDecision Using decisionRequestParameters.  
311          */
312         public DecisionResponse decide(DecisionRequestParameters decisionRequestParameters) throws PolicyDecisionException{
313                 DecisionResponse decision = decide(decisionRequestParameters.getECOMPComponentName(), decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID());
314                 return decision;
315         }
316         
317         /*
318          * PushPolicy using pushPolicyParameters. 
319          */
320         public PolicyChangeResponse pushPolicy(PushPolicyParameters pushPolicyParameters) throws Exception{
321                 return pushPolicy(pushPolicyParameters, userName, pass);
322         }
323         
324         public PolicyChangeResponse pushPolicy(PushPolicyParameters pushPolicyParameters, String userID, String passcode) throws Exception{
325                 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
326                 String resource= "pushPolicy";
327                 if(!checkPermissions(userID, passcode, resource)){
328                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
329                         response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
330                         response.setResponseCode(401);
331                         return response;
332                 }
333                 String plainName = null;
334                 String scope = null;
335                 try{
336                         if(pushPolicyParameters.getPolicyName()!=null){
337                                 plainName = pushPolicyParameters.getPolicyName().substring(pushPolicyParameters.getPolicyName().lastIndexOf(".")+1, pushPolicyParameters.getPolicyName().length());
338                                 scope = pushPolicyParameters.getPolicyName().substring(0, pushPolicyParameters.getPolicyName().lastIndexOf("."));
339                                 logger.info("Name is "+ plainName +"   scope is "+ scope);
340                         }
341                 }catch(Exception e){
342                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
343                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
344                 }
345
346                 // check incoming requestID, if null then generate one here so the same id can be used for the multiple transactions for the same Push Policy request  (i.e. POST, PUT)
347                 UUID requestID = pushPolicyParameters.getRequestID();
348                 if (requestID == null) {
349                         requestID = UUID.randomUUID();
350                         logger.info("Request ID was not provided from input, so sending generated ID: " + requestID.toString());
351                 } else {        
352                         logger.info("Request ID was provided from input: " + requestID.toString());
353                 }
354                 // now use the local requestID field derived above to pass to the rest of the Push Policy process (below)
355                 // response.setResponseMessage(pushPolicy(scope, plainName, pushPolicyParameters.getPolicyType(), pushPolicyParameters.getPdpGroup(), pushPolicyParameters.getRequestID()));
356                 response.setResponseMessage(pushPolicy(scope, plainName, pushPolicyParameters.getPolicyType(), pushPolicyParameters.getPdpGroup(), requestID));
357                 response.setResponseCode(responseCode);
358                 return response;
359         }
360         
361         /*
362          * Delete a Policy using deletePolicyParameters
363          */
364         public PolicyChangeResponse deletePolicy(DeletePolicyParameters parameters) throws Exception {
365                 return deletePolicy(parameters, userName, pass);
366         }
367         
368         public PolicyChangeResponse deletePolicy(DeletePolicyParameters parameters, String userID,String passcode) throws Exception {
369                 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
370                 String resource= "deletePolicy";
371                 if(!checkPermissions(userID, passcode, resource)){
372                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
373                         response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
374                         response.setResponseCode(401);
375                         return response;
376                 }
377                 if (parameters.getPolicyComponent()!=null) {
378                         if (parameters.getPolicyComponent().equalsIgnoreCase("PAP")) {
379                                 response.setResponseMessage(deletePolicyFromPAP(parameters));
380                         } else if (parameters.getPolicyComponent().equalsIgnoreCase("PDP")) {
381                                 response.setResponseMessage(deletePolicyFromPDP(parameters));
382                         } else {
383                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist.");
384                                 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist. Please enter either PAP or PDP to delete the policy from a specified Policy Component.");
385                         }
386                 } else {
387                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given.");
388                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given.");
389                 }
390
391                 response.setResponseCode(responseCode);
392                 return response;
393         }
394         
395         /*
396          * createDictionaryItem using dictionaryParameters.
397          */
398         public PolicyChangeResponse createDictionaryItem(DictionaryParameters parameters) throws Exception{
399                 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
400                 
401                 if(parameters.getDictionaryType()!=null || parameters.getDictionaryType().equals("")){
402                         if(parameters.getDictionary()!=null || parameters.getDictionary().equals("")){
403                                 if(parameters.getDictionaryFields()!=null){
404                                         logger.info("Parameters are good... start create dictionary item API...");
405                                         
406                                         Map<String,String> dictionaryFields = parameters.getDictionaryFields().get(AttributeType.DICTIONARY);
407                                         
408                                         StdPAPPolicy newDictionaryItem = new StdPAPPolicy(parameters.getDictionaryType().toString(), parameters.getDictionary(), dictionaryFields);
409
410                                         String result = (String) callPAP(newDictionaryItem, new String[] {"operation=createDictionary", "apiflag=dictionaryApi"}, parameters.getRequestID(), "dictionaryItem");
411                                         
412                                         response.setResponseCode(responseCode);
413                                         response.setResponseMessage(result);
414
415                                 }else{
416                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Fields given.");
417                                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Fields given.");
418                                 }
419                         }else{
420                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given.");
421                                 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given.");
422                         }
423                 }else{
424                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given.");
425                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given.");
426                 }
427                 try{
428                         
429                 }catch(Exception e){
430
431                 }
432                 
433                 return response;
434         }
435         
436         /*
437          * createPolicy Using policyParameters. 
438          */
439         public PolicyChangeResponse createPolicy(PolicyParameters policyParameters) throws Exception{
440                 return createPolicy(policyParameters, userName, pass);
441         }
442         
443         public PolicyChangeResponse createPolicy(PolicyParameters policyParameters, String userID, String passcode) throws Exception{
444                 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
445                 String resource= "createPolicy";
446                 if(!checkPermissions(userID, passcode, resource)){
447                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
448                         response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
449                         response.setResponseCode(401);
450                         return response;
451                 }
452                 String plainName = null;
453                 String scope = null;
454                 String date = "NA";
455                 if (policyParameters.getTtlDate()!=null){
456                         date = ConvertDate(policyParameters.getTtlDate());
457                 }
458                 try{
459                         if(policyParameters.getPolicyName()!=null){
460                                 plainName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf(".")+1, policyParameters.getPolicyName().length());
461                                 scope = policyParameters.getPolicyName().substring(0, policyParameters.getPolicyName().lastIndexOf("."));
462                                 logger.info("Name is "+ plainName +"   scope is "+ scope);
463                         }
464                 }catch(Exception e){
465                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
466                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
467                 }
468                 if(policyParameters.getPolicyConfigType()!=null){
469                         // This is Config Class Policy. 
470                         // Firewall
471                         if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.Firewall)){
472                                 if(policyParameters.getConfigBody()!=null){
473                                         JsonObject json = null;
474                                         try{
475                                                 json = stringToJsonObject(policyParameters.getConfigBody());
476                                         }catch(Exception e){
477                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
478                                                 logger.error(message);
479                                                 throw new Exception(message);
480                                         }
481                                         response.setResponseMessage(createConfigFirewallPolicy(plainName, json, scope, policyParameters.getRequestID(), userID, passcode,
482                                                         policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
483                                 }else{
484                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
485                                         logger.error(message);
486                                         response.setResponseMessage(message);
487                                 }
488                         }
489                         //Base
490                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.Base)){
491                                 if(policyParameters.getConfigBody()!=null) {
492                                         if(policyParameters.getConfigBodyType()!=null){
493                                                 response.setResponseMessage(createConfigPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getConfigName(),
494                                                                 policyParameters.getAttributes().get(AttributeType.MATCHING), policyParameters.getConfigBodyType().toString(), policyParameters.getConfigBody(), scope, policyParameters.getRequestID(), userID, passcode,
495                                                                 policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
496                                         } else {
497                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body Type given.";
498                                                 logger.error(message);
499                                                 response.setResponseMessage(message);
500                                         }
501                                 } else {
502                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
503                                         logger.error(message);
504                                         response.setResponseMessage(message);
505                                 }
506                         }
507                         //BRMS Raw
508                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.BRMS_RAW)){
509                                 if(policyParameters.getConfigBody()!=null){
510                                         
511                                         /*public String createUpdateBRMSRawPolicy(String policyName, String policyDescription, Map<String,String> dyanamicFieldConfigAttributes,
512                                          * String brmsRawBody, String policyScope, Boolean isEdit, UUID requestID)*/
513                                         response.setResponseMessage(createUpdateBRMSRawPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
514                                                         policyParameters.getConfigBody(),scope, false, 
515                                                         policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), 
516                                                         date));
517                                 }else{
518                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
519                                         logger.error(message);
520                                         throw new Exception(message);
521                                 }
522                         }
523                         //BRMS Param
524                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.BRMS_PARAM)){
525                                 if(policyParameters.getConfigBody()!=null){
526                         
527                                         response.setResponseMessage(createUpdateBRMSParamPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
528                                                         policyParameters.getConfigBody(),scope, false, 
529                                                         policyParameters.getRequestID(),policyParameters.getAttributes(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), 
530                                                         String.valueOf(policyParameters.getGuard()), date));
531                                 }else{
532                                         response.setResponseMessage(createUpdateBRMSParamPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
533                                                         null,scope, false, 
534                                                         policyParameters.getRequestID(),policyParameters.getAttributes(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), 
535                                                         String.valueOf(policyParameters.getGuard()), date));
536                                 }
537                         }
538                         // Micro Services Policy
539                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.MicroService)){
540                                 if(policyParameters.getConfigBody()!=null){
541                                         JsonObject json = null;
542                                         try{
543                                                 json = stringToJsonObject(policyParameters.getConfigBody());
544                                         }catch(Exception e){
545                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
546                                                 logger.error(message);
547                                                 throw new Exception(message);
548                                         }
549                                         //call Micro Services Create API here
550                                         response.setResponseMessage(createUpdateMicroServicesPolicy(plainName, json, policyParameters.getEcompName(),
551                                                                                                         scope, false, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), 
552                                                                                                         String.valueOf(policyParameters.getGuard()), date));
553                                         
554                                 }else{
555                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Micro Service or Attributes Config Body Present";
556                                         logger.error(message);
557                                         throw new Exception(message);
558                                 }
559                         }
560                         // ClosedLoop_Fault Policy
561                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.ClosedLoop_Fault)){
562                                 if(policyParameters.getConfigBody()!=null){
563                                         JsonObject json = null;
564                                         try{
565                                                 if(validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
566                                                         json = stringToJsonObject(policyParameters.getConfigBody());
567                                                 } else {
568                                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "The ClosedLoop JSON Contains Non ASCII Characters.";
569                                                         logger.error(message);
570                                                         response.setResponseCode(400);
571                                                         response.setResponseMessage(message);
572                                                         return response;
573                                                 }
574                                                 
575                                         }catch(Exception e){
576                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
577                                                 logger.error(message);
578                                                 response.setResponseCode(400);
579                                                 response.setResponseMessage(message);
580                                                 return response;
581                                                 
582                                         }
583                                         //call ClosedLoop_Fault Create API here
584                                         response.setResponseMessage(createUpdateClosedLoopPolicy(plainName, json, policyParameters.getPolicyDescription(),
585                                                                                                         scope, false, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), 
586                                                                                                         String.valueOf(policyParameters.getGuard()), date));
587                                         
588                                 }else{
589                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
590                                         logger.error(message);
591                                         response.setResponseMessage(message);
592                                         response.setResponseCode(400);
593                                         return response;
594                                 }
595                         }
596                         // ClosedLoop_PM Policy
597                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.ClosedLoop_PM)){
598                                 if(policyParameters.getConfigBody()!=null){
599                                         JsonObject json = null;
600                                         try{
601                                                 if(validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
602                                                         json = stringToJsonObject(policyParameters.getConfigBody());
603                                                 } else {
604                                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "The ClosedLoop PM JSON Contains Non ASCII Characters.";
605                                                         logger.error(message);
606                                                         response.setResponseMessage(message);
607                                                         response.setResponseCode(400);
608                                                         return response;
609                                                         
610                                                 }
611                                                 
612                                         }catch(Exception e){
613                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
614                                                 logger.error(message);
615                                                 response.setResponseMessage(message);
616                                                 response.setResponseCode(400);
617                                                 return response;
618                                                 
619                                         }
620                                         //call ClosedLoop_Fault Create API here
621                                         response.setResponseMessage(createUpdateClosedLoopPmPolicy(plainName, json, policyParameters.getPolicyDescription(),
622                                                                                                         scope, false, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), 
623                                                                                                         String.valueOf(policyParameters.getGuard()), date));
624                                         
625                                 }else{
626                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
627                                         logger.error(message);
628                                         response.setResponseMessage(message);
629                                         response.setResponseCode(400);
630                                         return response;
631                                         
632                                 }
633                         }
634                         
635                 } else if (policyParameters.getPolicyClass()!=null){ 
636                         if(policyParameters.getPolicyClass().equals(PolicyClass.Action)){
637                                 // call Action Create API here. 
638                                 response.setResponseMessage(createUpdateActionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getAttributes().get(AttributeType.MATCHING), 
639                                                 policyParameters.getDynamicRuleAlgorithmLabels(), policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
640                                                 policyParameters.getActionPerformer(), policyParameters.getActionAttribute(), scope, false, policyParameters.getRequestID()));
641                         }else if(policyParameters.getPolicyClass().equals(PolicyClass.Decision)){
642                                 // Call Decision Create API here. 
643                                 if (policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)) {
644                                         response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
645                                                         policyParameters.getAttributes().get(AttributeType.MATCHING), policyParameters.getAttributes().get(AttributeType.SETTINGS), policyParameters.getDynamicRuleAlgorithmLabels(), 
646                                                         policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
647                                                         scope, false, policyParameters.getRequestID()));
648                                 }else if(policyParameters.getAttributes()!=null && !policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
649                                         response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
650                                                         null, policyParameters.getAttributes().get(AttributeType.SETTINGS), policyParameters.getDynamicRuleAlgorithmLabels(), 
651                                                         policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
652                                                         scope, false, policyParameters.getRequestID()));
653                                 }else if(policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && !policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
654                                         response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
655                                                         policyParameters.getAttributes().get(AttributeType.MATCHING), null, policyParameters.getDynamicRuleAlgorithmLabels(), 
656                                                         policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
657                                                         scope, false, policyParameters.getRequestID()));
658                                 }else{
659                                         response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
660                                                         null, null, policyParameters.getDynamicRuleAlgorithmLabels(), 
661                                                         policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
662                                                         scope, false, policyParameters.getRequestID()));
663                                 }
664                         }
665                 } else {
666                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Class found.");
667                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Class found.");
668                 }
669                 response.setResponseCode(responseCode);
670                 return response;
671         }
672         
673         /*
674          * updatePolicy using policyParameters. 
675          */
676         public PolicyChangeResponse updatePolicy(PolicyParameters policyParameters) throws Exception{
677                 return updatePolicy(policyParameters, userName, pass);
678         }
679         
680         public PolicyChangeResponse updatePolicy(PolicyParameters policyParameters,String userID, String passcode) throws Exception{
681                 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
682                 String resource= "updatePolicy";
683                 if(!checkPermissions(userID, passcode, resource)){
684                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
685                         response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
686                         response.setResponseCode(401);
687                         return response;
688                 }
689                 String plainName = null;
690                 String scope = null;
691                 String date = "NA";
692                 if (policyParameters.getTtlDate()!=null){
693                         date = ConvertDate(policyParameters.getTtlDate());
694                 }
695                 try{
696                         if(policyParameters.getPolicyName()!=null){
697                                 plainName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf(".")+1, policyParameters.getPolicyName().length());
698                                 scope = policyParameters.getPolicyName().substring(0, policyParameters.getPolicyName().lastIndexOf("."));
699                                 logger.info("Name is "+ plainName +"   scope is "+ scope);
700                         }
701                 }catch(Exception e){
702                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
703                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
704                 }
705                 if(policyParameters.getPolicyConfigType()!=null){
706                         // This is Config Class Policy.
707                         //Firewall
708                         if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.Firewall)){
709                                 if(policyParameters.getConfigBody()!=null){
710                                         JsonObject json = null;
711                                         try{
712                                                 json = stringToJsonObject(policyParameters.getConfigBody());
713                                         }catch(Exception e){
714                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
715                                                 logger.error(message);
716                                                 throw new Exception(message);
717                                         }
718                                         response.setResponseMessage(updateConfigFirewallPolicy(plainName, json, scope, policyParameters.getRequestID(), userID, passcode,policyParameters.getRiskLevel(), 
719                                                         policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
720                                 }else{
721                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
722                                         logger.error(message);
723                                         response.setResponseMessage(message);
724                                 }
725                         }
726                         //Base Policy
727                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.Base)){
728                                 if(policyParameters.getConfigBody()!=null) {
729                                         if(policyParameters.getConfigBodyType()!=null){
730                                                 response.setResponseMessage(updateConfigPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getConfigName(),
731                                                                 policyParameters.getAttributes().get(AttributeType.MATCHING), policyParameters.getConfigBodyType().toString(), policyParameters.getConfigBody(), scope, 
732                                                                 policyParameters.getRequestID(), userID, passcode, policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
733                                         } else {
734                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body Type given.";
735                                                 logger.error(message);
736                                                 response.setResponseMessage(message);
737                                         }
738                                 } else {
739                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
740                                         logger.error(message);
741                                         response.setResponseMessage(message);
742                                 }
743                         }
744                         //BRMS Raw
745                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.BRMS_RAW)){
746                                 if(policyParameters.getConfigBody()!=null){
747                                         /*public String createUpdateBRMSRawPolicy(String policyName, String policyDescription, Map<String,String> dyanamicFieldConfigAttributes,
748                                          * String brmsRawBody, String policyScope, Boolean isEdit, UUID requestID)*/
749                                         response.setResponseMessage(createUpdateBRMSRawPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
750                                                         policyParameters.getConfigBody(),scope, true, 
751                                                         policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
752                                 }else{
753                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
754                                         logger.error(message);
755                                         throw new Exception(message);
756                                 }
757                         }
758                         //BRMS Param
759                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.BRMS_PARAM)){
760                                 if(policyParameters.getConfigBody()!=null){
761                                         
762                                 /*      public String createUpdateBRMSParamPolicy(String policyName, String policyDescription, Map<AttributeType, Map<String, String>>  dyanamicFieldConfigAttributes,
763                                                         String brmsRawBody, String policyScope, Boolean isEdit, 
764                                                         UUID requestID,Map<String,String> drlRuleAndUIParams)*/
765                                         response.setResponseMessage(createUpdateBRMSParamPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
766                                                         policyParameters.getConfigBody(),scope, true, 
767                                                         policyParameters.getRequestID(),policyParameters.getAttributes(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
768                                 }else{
769                                         response.setResponseMessage(createUpdateBRMSParamPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
770                                                         null,scope, true, 
771                                                         policyParameters.getRequestID(),policyParameters.getAttributes(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
772                                 }
773                         }
774                         // Micro Services Policy
775                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.MicroService)){
776                                 if(policyParameters.getConfigBody()!=null){
777                                         JsonObject json = null;
778                                         try{
779                                                 json = stringToJsonObject(policyParameters.getConfigBody());
780                                         }catch(Exception e){
781                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
782                                                 logger.error(message);
783                                                 throw new Exception(message);
784                                         }
785                                         //call Micro Services Create API here
786                                         response.setResponseMessage(createUpdateMicroServicesPolicy(plainName, json, policyParameters.getEcompName(),
787                                                         scope, true, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
788                                         
789                                 }else{
790                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Micro Service or Attributes Config Body Present";
791                                         logger.error(message);
792                                         throw new Exception(message);
793                                 }
794                         }
795                         // ClosedLoop_Fault Policy
796                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.ClosedLoop_Fault)){
797                                 if(policyParameters.getConfigBody()!=null){
798                                         JsonObject json = null;
799                                         try{
800                                                 if(validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
801                                                         json = stringToJsonObject(policyParameters.getConfigBody());
802                                                 } else {
803                                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "The ClosedLoop JSON Contains Non ASCII Characters.";
804                                                         logger.error(message);
805                                                         response.setResponseMessage(message);
806                                                         return response;
807                                                 }
808                                                 
809                                         }catch(Exception e){
810                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
811                                                 logger.error(message);
812                                                 response.setResponseMessage(message);
813                                                 return response;
814                                         }
815                                         //call ClosedLoop_Fault Create API here
816                                         response.setResponseMessage(createUpdateClosedLoopPolicy(plainName, json, policyParameters.getPolicyDescription(),
817                                                                                                         scope, true, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
818                                         
819                                 }else{
820                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
821                                         logger.error(message);
822                                         response.setResponseMessage(message);
823                                 }
824                         }
825                         // ClosedLoop_PM Policy
826                         else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.ClosedLoop_PM)){
827                                 if(policyParameters.getConfigBody()!=null){
828                                         JsonObject json = null;
829                                         try{
830                                                 if(validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
831                                                         json = stringToJsonObject(policyParameters.getConfigBody());
832                                                 } else {
833                                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "The ClosedLoop PM JSON Contains Non ASCII Characters.";
834                                                         logger.error(message);
835                                                         response.setResponseMessage(message);
836                                                         return response;
837                                                 }
838                                                 
839                                         }catch(Exception e){
840                                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
841                                                 logger.error(message);
842                                                 response.setResponseMessage(message);
843                                                 return response;
844                                         }
845                                         //call ClosedLoop_Fault Create API here
846                                         response.setResponseMessage(createUpdateClosedLoopPmPolicy(plainName, json, policyParameters.getPolicyDescription(),
847                                                                                                         scope, true, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), 
848                                                                                                         String.valueOf(policyParameters.getGuard()), date));
849                                         
850                                 }else{
851                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
852                                         logger.error(message);
853                                         response.setResponseMessage(message);
854                                 }
855                         }
856                         
857                 }else{
858                         
859                         if(policyParameters.getPolicyClass().equals(PolicyClass.Action)){
860                                 // call Action Update API here. 
861                                 response.setResponseMessage(createUpdateActionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getAttributes().get(AttributeType.MATCHING), 
862                                                 policyParameters.getDynamicRuleAlgorithmLabels(), policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
863                                                 policyParameters.getActionPerformer(), policyParameters.getActionAttribute(), scope, true, policyParameters.getRequestID()));
864                         
865                         }else if(policyParameters.getPolicyClass().equals(PolicyClass.Decision)){
866                                 // Call Decision Create API here. 
867                                 if (policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)) {
868                                         response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
869                                                         policyParameters.getAttributes().get(AttributeType.MATCHING), policyParameters.getAttributes().get(AttributeType.SETTINGS), policyParameters.getDynamicRuleAlgorithmLabels(), 
870                                                         policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
871                                                         scope, true, policyParameters.getRequestID()));
872                                 }else if(policyParameters.getAttributes()!=null && !policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
873                                         response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
874                                                         null, policyParameters.getAttributes().get(AttributeType.SETTINGS), policyParameters.getDynamicRuleAlgorithmLabels(), 
875                                                         policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
876                                                         scope, true, policyParameters.getRequestID()));
877                                 }else if(policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && !policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
878                                         response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
879                                                         policyParameters.getAttributes().get(AttributeType.MATCHING), null, policyParameters.getDynamicRuleAlgorithmLabels(), 
880                                                         policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
881                                                         scope, true, policyParameters.getRequestID()));
882                                 }else{
883                                         response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
884                                                         null, null, policyParameters.getDynamicRuleAlgorithmLabels(), 
885                                                         policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(), 
886                                                         scope, true, policyParameters.getRequestID()));
887                                 }
888                         }
889                 }
890                 response.setResponseCode(responseCode);
891                 return response;
892         }
893         
894         public DecisionResponse policyDecide(String eCOMPComponentName,
895                         Map<String, String> decisionAttributes, UUID requestID, String userID, String passcode)
896                         throws PolicyDecisionException {
897                 String resource= "getDecision";
898                 if(!checkPermissions(userID, passcode, resource)){
899                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
900                         throw new PolicyDecisionException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
901                 }
902                 DecisionResponse policyDecision;
903                 if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) {
904                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName);
905                         throw new PolicyDecisionException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given.");
906                 }
907                 if (decisionAttributes != null && !decisionAttributes.isEmpty()) {
908                         JsonArrayBuilder resourceArray = Json.createArrayBuilder();
909                         for (String key : decisionAttributes.keySet()) {
910                                 if (key.isEmpty()) {
911                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key");
912                                         throw new PolicyDecisionException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an empty Key");
913                                 }
914                                 JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
915                                 if (decisionAttributes.get(key).matches("[0-9]+")) {
916                                         int val = Integer.parseInt(decisionAttributes.get(key));
917                                         resourceBuilder.add("Value", val);
918                                 } else {
919                                         resourceBuilder.add("Value", decisionAttributes.get(key));
920                                 }
921                                 resourceBuilder.add("AttributeId", key);
922                                 resourceArray.add(resourceBuilder);
923                         }
924                         JsonObject model = Json
925                                         .createObjectBuilder()
926                                         .add("Request",
927                                                         Json.createObjectBuilder()
928                                                                         .add("AccessSubject",
929                                                                                         Json.createObjectBuilder()
930                                                                                                         .add("Attribute",
931                                                                                                                         Json.createObjectBuilder()
932                                                                                                                                         .add("Value",
933                                                                                                                                                         eCOMPComponentName)
934                                                                                                                                         .add("AttributeId",
935                                                                                                                                                         "ECOMPName")))
936                                                                         .add("Resource",
937                                                                                         Json.createObjectBuilder().add(
938                                                                                                         "Attribute", resourceArray))
939                                                                         .add("Action",
940                                                                                         Json.createObjectBuilder()
941                                                                                                         .add("Attribute",
942                                                                                                                         Json.createObjectBuilder()
943                                                                                                                                         .add("Value",
944                                                                                                                                                         "DECIDE")
945                                                                                                                                         .add("AttributeId",
946                                                                                                                                                         "urn:oasis:names:tc:xacml:1.0:action:action-id"))))
947                                         .build();
948                         try {
949                                 decide = true;
950                                 policyDecision = decisionResult(generateRequest(model
951                                                 .toString(), requestID));
952                         } catch (Exception e) {
953                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
954                                 decide = false;
955                                 throw new PolicyDecisionException(e);
956                         }
957                 } else {
958                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Attributes Given. ");
959                         throw new PolicyDecisionException(XACMLErrorConstants.ERROR_DATA_ISSUE +"No DecisionAttributes Given.");
960                 }
961                 decide = false;
962                 return policyDecision;
963         }
964
965         public Collection<PolicyConfig> configPolicyName(String policyName, UUID requestID, String userID, String passcode)
966                         throws PolicyConfigException {
967                 String resource= "getConfigByPolicyName";
968                 if(!checkPermissions(userID, passcode, resource)){
969                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
970                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
971                 }
972                 Collection<PolicyConfig> policyConfig = null;
973                 if (policyName == null || policyName.isEmpty()) {
974                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Policy FileName specified!! : " + policyName);
975                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE+"No Policy FileName specified!!");
976                 }
977                 if(policyName!= null && !policyName.trim().equals("") && !policyName.endsWith("xml")){
978                         policyName = policyName + ".[\\d].*";
979                 }
980                 JsonObject model = Json
981                                 .createObjectBuilder()
982                                 .add("Request",
983                                                 Json.createObjectBuilder()
984                                                                 .add("AccessSubject",
985                                                                                 Json.createObjectBuilder().add(
986                                                                                                 "Attribute",
987                                                                                                 Json.createObjectBuilder()
988                                                                                                                 .add("Value",
989                                                                                                                                 policyName)
990                                                                                                                 .add("AttributeId",
991                                                                                                                                 "PolicyName")))
992                                                                 .add("Action",
993                                                                                 Json.createObjectBuilder()
994                                                                                                 .add("Attribute",
995                                                                                                                 Json.createObjectBuilder()
996                                                                                                                                 .add("Value",
997                                                                                                                                                 "ACCESS")
998                                                                                                                                 .add("AttributeId",
999                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1000                                                                 .add("Resource",
1001                                                                                 Json.createObjectBuilder()
1002                                                                                                 .add("Attribute",
1003                                                                                                                 Json.createObjectBuilder()
1004                                                                                                                                 .add("Value",
1005                                                                                                                                                 "Config")
1006                                                                                                                                 .add("AttributeId",
1007                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))
1008                                 .build();
1009                 try {
1010                         policyConfig = configResult(generateRequest(model.toString(), requestID));
1011                 } catch (Exception e) {
1012                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1013                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1014                 }
1015                 return policyConfig;
1016         }
1017
1018         public Collection<PolicyConfig> config(String eCOMPComponentName, UUID requestID, String userID, String passcode)
1019                         throws PolicyConfigException {
1020                 String resource= "getConfig";
1021                 if(!checkPermissions(userID, passcode, resource)){
1022                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1023                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1024                 }
1025                 Collection<PolicyConfig> policyConfig = null;
1026                 if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) {
1027                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName);
1028                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given.");
1029                 }
1030                 JsonObject model = Json
1031                                 .createObjectBuilder()
1032                                 .add("Request",
1033                                                 Json.createObjectBuilder()
1034                                                                 .add("AccessSubject",
1035                                                                                 Json.createObjectBuilder()
1036                                                                                                 .add("Attribute",
1037                                                                                                                 Json.createObjectBuilder()
1038                                                                                                                                 .add("Value",
1039                                                                                                                                                 eCOMPComponentName)
1040                                                                                                                                 .add("AttributeId",
1041                                                                                                                                                 "ECOMPName")))
1042                                                                 .add("Action",
1043                                                                                 Json.createObjectBuilder()
1044                                                                                                 .add("Attribute",
1045                                                                                                                 Json.createObjectBuilder()
1046                                                                                                                                 .add("Value",
1047                                                                                                                                                 "ACCESS")
1048                                                                                                                                 .add("AttributeId",
1049                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1050                                                                 .add("Resource",
1051                                                                                 Json.createObjectBuilder()
1052                                                                                                 .add("Attribute",
1053                                                                                                                 Json.createObjectBuilder()
1054                                                                                                                                 .add("Value",
1055                                                                                                                                                 "Config")
1056                                                                                                                                 .add("AttributeId",
1057                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))
1058                                 .build();
1059                 try {
1060                         policyConfig = configResult(generateRequest(model.toString(), requestID));
1061                 } catch (Exception e) {
1062                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1063                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1064                 }
1065                 return policyConfig;
1066         }
1067
1068         public Collection<PolicyConfig> config(String eCOMPComponentName,
1069                         String configName, UUID requestID, String userID, String passcode) throws PolicyConfigException {
1070                 String resource= "getConfig";
1071                 if(!checkPermissions(userID, passcode, resource)){
1072                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1073                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1074                 }
1075                 Collection<PolicyConfig> policyConfig = null;
1076                 if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) {
1077                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName);
1078                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given.");
1079                 }
1080                 if (configName == null || configName.isEmpty()) {
1081                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No configName given : " + configName);
1082                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"No configName given.");
1083                 }
1084                 JsonObject model = Json
1085                                 .createObjectBuilder()
1086                                 .add("Request",
1087                                                 Json.createObjectBuilder()
1088                                                                 .add("AccessSubject",
1089                                                                                 Json.createObjectBuilder()
1090                                                                                                 .add("Attribute",
1091                                                                                                                 Json.createArrayBuilder()
1092                                                                                                                                 .add(Json
1093                                                                                                                                                 .createObjectBuilder()
1094                                                                                                                                                 .add("Value",
1095                                                                                                                                                                 eCOMPComponentName)
1096                                                                                                                                                 .add("AttributeId",
1097                                                                                                                                                                 "ECOMPName"))
1098                                                                                                                                 .add(Json
1099                                                                                                                                                 .createObjectBuilder()
1100                                                                                                                                                 .add("Value",
1101                                                                                                                                                                 configName)
1102                                                                                                                                                 .add("AttributeId",
1103                                                                                                                                                                 "ConfigName"))))
1104                                                                 .add("Action",
1105                                                                                 Json.createObjectBuilder()
1106                                                                                                 .add("Attribute",
1107                                                                                                                 Json.createObjectBuilder()
1108                                                                                                                                 .add("Value",
1109                                                                                                                                                 "ACCESS")
1110                                                                                                                                 .add("AttributeId",
1111                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1112                                                                 .add("Resource",
1113                                                                                 Json.createObjectBuilder()
1114                                                                                                 .add("Attribute",
1115                                                                                                                 Json.createObjectBuilder()
1116                                                                                                                                 .add("Value",
1117                                                                                                                                                 "Config")
1118                                                                                                                                 .add("AttributeId",
1119                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))
1120                                 .build();
1121                 try {
1122                         policyConfig = configResult(generateRequest(model.toString(), requestID));
1123                 } catch (Exception e) {
1124                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1125                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1126                 }
1127
1128                 return policyConfig;
1129         }
1130
1131         public Collection<PolicyConfig> config(String eCOMPComponentName,
1132                         String configName, Map<String, String> configAttributes, UUID requestID, String userID, String passcode)
1133                         throws PolicyConfigException {
1134                 String resource= "getConfig";
1135                 if(!checkPermissions(userID, passcode, resource)){
1136                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1137                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1138                 }
1139                 Collection<PolicyConfig> policyConfig = null;
1140                 if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) {
1141                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName);
1142                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given.");
1143                 }
1144                 if (configName == null || configName.isEmpty()) {
1145                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No configName given : " + configName);
1146                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"No configName given.");
1147                 }
1148                 if (configAttributes != null && !configAttributes.isEmpty()) {
1149                         if(!configAttributes.containsKey("RiskType")){
1150                                 configAttributes.put("RiskType", ".*");
1151                         }
1152                         if(!configAttributes.containsKey("RiskLevel")){
1153                                 configAttributes.put("RiskLevel", ".*");
1154                         }
1155                         if(!configAttributes.containsKey("guard")){
1156                                 configAttributes.put("guard", ".*");
1157                         }
1158                         if(!configAttributes.containsKey("TTLDate")){
1159                                 configAttributes.put("TTLDate", ".*");
1160                         }
1161                 }else{
1162                         // ConfigAttributes is Null. So add basic values. 
1163                         configAttributes = new HashMap<String,String>();
1164                         configAttributes.put("RiskType", ".*");
1165                         configAttributes.put("RiskLevel", ".*");
1166                         configAttributes.put("guard", ".*");
1167                         configAttributes.put("TTLDate", ".*");
1168                 }
1169                 JsonArrayBuilder resourceArray = Json.createArrayBuilder();
1170                 for (String key : configAttributes.keySet()) {
1171                         if (key.isEmpty()) {
1172                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an empty Key");
1173                                 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"Cannot have an empty Key");
1174                         }
1175                         JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
1176                         /*if (configAttributes.get(key).matches("[0-9]+")) {
1177                                 int val = Integer.parseInt(configAttributes.get(key));
1178                                 resourceBuilder.add("Value", val);
1179                         } else {*/
1180                         resourceBuilder.add("Value", configAttributes.get(key));
1181                         resourceBuilder.add("AttributeId", key);
1182                         resourceArray.add(resourceBuilder);
1183                 }
1184                 JsonObject model = Json
1185                         .createObjectBuilder()
1186                         .add("Request",
1187                                         Json.createObjectBuilder()                                              
1188                                                         .add("AccessSubject",
1189                                                                         Json.createObjectBuilder()
1190                                                                                                 .add("Attribute",
1191                                                                                                         Json.createArrayBuilder()
1192                                                                                                                         .add(Json
1193                                                                                                                                         .createObjectBuilder()
1194                                                                                                                                         .add("Value",
1195                                                                                                                                                         eCOMPComponentName)
1196                                                                                                                                         .add("AttributeId",
1197                                                                                                                                                         "ECOMPName"))
1198                                                                                                                         .add(Json
1199                                                                                                                                         .createObjectBuilder()
1200                                                                                                                                         .add("Value",
1201                                                                                                                                                         configName)
1202                                                                                                                                         .add("AttributeId",
1203                                                                                                                                                         "ConfigName"))))
1204                                                         .add("Action",
1205                                                                         Json.createObjectBuilder()
1206                                                                                                 .add("Attribute",
1207                                                                                                         Json.createObjectBuilder()
1208                                                                                                                         .add("Value",
1209                                                                                                                                                 "ACCESS")
1210                                                                                                                         .add("AttributeId",
1211                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1212                                                         .add("Resource",
1213                                                                         Json.createObjectBuilder()
1214                                                                                                 .add("Attribute",
1215                                                                                                                 resourceArray
1216                                                                                                                                 .add(Json.createObjectBuilder()
1217                                                                                                                                                 .add("Value",
1218                                                                                                                                                                 "Config")
1219                                                                                                                                                 .add("AttributeId",
1220                                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:resource:resource-id")))))
1221                                 .build();
1222                 try {
1223                         policyConfig = configResult(generateRequest(model.toString(), requestID));
1224                 } catch (Exception e) {
1225                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1226                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1227                 }
1228                 return policyConfig;
1229         }
1230         
1231         public Collection<PolicyConfig> configRequest(ConfigRequestParameters configRequestParameters, String userID, String passcode) throws PolicyConfigException{
1232                 String resource= "getConfig";
1233                 if(!checkPermissions(userID, passcode, resource)){
1234                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1235                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1236                 }
1237                 Collection<PolicyConfig> policyConfig = null;
1238                 unique = false;
1239                 if(configRequestParameters==null){
1240                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No config Request Parameters given ");
1241                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No config Request Parameters given.");
1242                 }
1243                 if(configRequestParameters.getEcompName() == null && configRequestParameters.getPolicyName() == null){
1244                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot proceed without eCOMPComponentName or PolicyName");
1245                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName or PolicyName given.");
1246                 }
1247                 String policyName = configRequestParameters.getPolicyName();
1248                 if(policyName!= null && !policyName.trim().equals("") && !policyName.endsWith("xml")){
1249                         policyName = policyName + ".[\\d].*";
1250                 }
1251                 JsonArrayBuilder subjectArray = Json.createArrayBuilder();
1252                 JsonArrayBuilder resourceArray = Json.createArrayBuilder();
1253                 if(configRequestParameters.getPolicyName()!=null){
1254                         JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
1255                         subjectBuilder.add("Value", policyName);
1256                         subjectBuilder.add("AttributeId", "PolicyName");
1257                         subjectArray.add(subjectBuilder);
1258                 }else{
1259                         logger.info("PolicyName values are not given. ");
1260                 }
1261                 if(configRequestParameters.getEcompName()!=null){
1262                         JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
1263                         subjectBuilder.add("Value", configRequestParameters.getEcompName());
1264                         subjectBuilder.add("AttributeId", "ECOMPName");
1265                         subjectArray.add(subjectBuilder);
1266                         if(configRequestParameters.getConfigName()!=null){
1267                                 subjectBuilder = Json.createObjectBuilder();
1268                                 subjectBuilder.add("Value", configRequestParameters.getConfigName());
1269                                 subjectBuilder.add("AttributeId", "ConfigName");
1270                                 subjectArray.add(subjectBuilder);
1271                                 Map<String,String> configAttributes = configRequestParameters.getConfigAttributes();
1272                                 if (configAttributes != null && !configAttributes.isEmpty()) {
1273                                         if(!configAttributes.containsKey("RiskType")){
1274                                                 configAttributes.put("RiskType", ".*");
1275                                         }
1276                                         if(!configAttributes.containsKey("RiskLevel")){
1277                                                 configAttributes.put("RiskLevel", ".*");
1278                                         }
1279                                         if(!configAttributes.containsKey("guard")){
1280                                                 configAttributes.put("guard", ".*");
1281                                         }
1282                                         if(!configAttributes.containsKey("TTLDate")){
1283                                                 configAttributes.put("TTLDate", ".*");
1284                                         }
1285                                 }else{
1286                                         // ConfigAttributes is Null. So add basic values. 
1287                                         configAttributes = new HashMap<String,String>();
1288                                         configAttributes.put("RiskType", ".*");
1289                                         configAttributes.put("RiskLevel", ".*");
1290                                         configAttributes.put("guard", ".*");
1291                                         configAttributes.put("TTLDate", ".*");
1292                                 }
1293                                 for (String key : configAttributes.keySet()) {
1294                                         if (key.isEmpty()) {
1295                                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an empty Key");
1296                                                 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"Cannot have an empty Key");
1297                                         }
1298                                         JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
1299                                         /*if (configAttributes.get(key).matches("[0-9]+")) {
1300                                                 int val = Integer.parseInt(configAttributes.get(key));
1301                                                 resourceBuilder.add("Value", val);
1302                                         } else {*/
1303                                         resourceBuilder.add("Value", configAttributes.get(key));
1304                                         resourceBuilder.add("AttributeId", key);
1305                                         resourceArray.add(resourceBuilder);
1306                                 }
1307                         }else{
1308                                 logger.info("Config Name is not given. ");
1309                         }
1310                 }else{
1311                         logger.info("Ecomp Name is not given. ");
1312                 }
1313                 JsonObject model = Json
1314                                 .createObjectBuilder()
1315                                 .add("Request",
1316                                                 Json.createObjectBuilder()
1317                                                                 .add("AccessSubject",
1318                                                                                 Json.createObjectBuilder()
1319                                                                                                 .add("Attribute",subjectArray))
1320                                                                 .add("Action",
1321                                                                                 Json.createObjectBuilder()
1322                                                                                                 .add("Attribute",
1323                                                                                                                 Json.createObjectBuilder()
1324                                                                                                                                 .add("Value",
1325                                                                                                                                                 "ACCESS")
1326                                                                                                                                 .add("AttributeId",
1327                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1328                                                                 .add("Resource",
1329                                                                                 Json.createObjectBuilder()
1330                                                                                                 .add("Attribute",
1331                                                                                                                 resourceArray
1332                                                                                                                                 .add(Json
1333                                                                                                                                                 .createObjectBuilder()
1334                                                                                                                                                 .add("Value",
1335                                                                                                                                                                 "Config")
1336                                                                                                                                                 .add("AttributeId",
1337                                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:resource:resource-id")))))
1338                                 .build();
1339                 logger.debug("Generated JSON Request is: " + model.toString());
1340                 if(configRequestParameters.getUnique()){
1341                         logger.info("Requested for Unique Result only. ");
1342                         unique = true;
1343                 }
1344                 try {
1345                         policyConfig = configResult(generateRequest(model.toString(), configRequestParameters.getRequestID()));
1346                 } catch (Exception e) {
1347                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1348                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1349                 }
1350                 return policyConfig;
1351         }
1352         
1353         public Collection<String> listConfigRequest(ConfigRequestParameters listRequestParameters, String userID, String passcode) throws PolicyConfigException{
1354                 String resource= "listConfig";
1355                 if(!checkPermissions(userID, passcode, resource)){
1356                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1357                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1358                 }
1359                 Collection<PolicyConfig> policyConfig = null;
1360                 Collection<String> policyList = new ArrayList<String>();
1361                 
1362                 unique = false;
1363                 if(listRequestParameters==null){
1364                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Request Parameters given ");
1365                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Request Parameters given.");
1366                 }
1367                 
1368                 if (junit){
1369                         policyList.add("Policy Name: listConfigTest");
1370                         return policyList;
1371                 }
1372
1373                 String policyName = listRequestParameters.getPolicyName();
1374                 if(policyName!= null && !policyName.trim().equals("") && !policyName.endsWith("xml")){
1375                         policyName = policyName + ".[\\d].*";
1376                 }
1377                 JsonArrayBuilder subjectArray = Json.createArrayBuilder();
1378                 JsonArrayBuilder resourceArray = Json.createArrayBuilder();
1379                 if(listRequestParameters.getPolicyName()!=null){
1380                         JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
1381                         subjectBuilder.add("Value", policyName);
1382                         subjectBuilder.add("AttributeId", "PolicyName");
1383                         subjectArray.add(subjectBuilder);
1384                 }else{
1385                         logger.info("PolicyName values are not given. ");
1386                 }
1387                 if(listRequestParameters.getEcompName()!=null){
1388                         JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
1389                         subjectBuilder.add("Value", listRequestParameters.getEcompName());
1390                         subjectBuilder.add("AttributeId", "ECOMPName");
1391                         subjectArray.add(subjectBuilder);
1392                         if(listRequestParameters.getConfigName()!=null){
1393                                 subjectBuilder = Json.createObjectBuilder();
1394                                 subjectBuilder.add("Value", listRequestParameters.getConfigName());
1395                                 subjectBuilder.add("AttributeId", "ConfigName");
1396                                 subjectArray.add(subjectBuilder);
1397                                 Map<String,String> configAttributes = listRequestParameters.getConfigAttributes();
1398                                 if (configAttributes != null && !configAttributes.isEmpty()) {
1399                                         if(!configAttributes.containsKey("RiskType")){
1400                                                 configAttributes.put("RiskType", ".*");
1401                                         }
1402                                         if(!configAttributes.containsKey("RiskLevel")){
1403                                                 configAttributes.put("RiskLevel", ".*");
1404                                         }
1405                                         if(!configAttributes.containsKey("guard")){
1406                                                 configAttributes.put("guard", ".*");
1407                                         }
1408                                         if(!configAttributes.containsKey("TTLDate")){
1409                                                 configAttributes.put("TTLDate", ".*");
1410                                         }
1411                                 }else{
1412                                         // ConfigAttributes is Null. So add basic values. 
1413                                         configAttributes = new HashMap<String,String>();
1414                                         configAttributes.put("RiskType", ".*");
1415                                         configAttributes.put("RiskLevel", ".*");
1416                                         configAttributes.put("guard", ".*");
1417                                         configAttributes.put("TTLDate", ".*");
1418                                 }
1419                                 for (String key : configAttributes.keySet()) {
1420                                         if (key.isEmpty()) {
1421                                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an empty Key");
1422                                                 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"Cannot have an empty Key");
1423                                         }
1424                                         JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
1425                                         /*if (configAttributes.get(key).matches("[0-9]+")) {
1426                                                 int val = Integer.parseInt(configAttributes.get(key));
1427                                                 resourceBuilder.add("Value", val);
1428                                         } else {*/
1429                                         resourceBuilder.add("Value", configAttributes.get(key));
1430                                         resourceBuilder.add("AttributeId", key);
1431                                         resourceArray.add(resourceBuilder);
1432                                 }
1433                         }else{
1434                                 logger.info("Config Name is not given. ");
1435                         }
1436                 }else{
1437                         logger.info("Ecomp Name is not given. ");
1438                 }
1439                 JsonObject model = Json
1440                                 .createObjectBuilder()
1441                                 .add("Request",
1442                                                 Json.createObjectBuilder()
1443                                                                 .add("AccessSubject",
1444                                                                                 Json.createObjectBuilder()
1445                                                                                                 .add("Attribute",subjectArray))
1446                                                                 .add("Action",
1447                                                                                 Json.createObjectBuilder()
1448                                                                                                 .add("Attribute",
1449                                                                                                                 Json.createObjectBuilder()
1450                                                                                                                                 .add("Value",
1451                                                                                                                                                 "ACCESS")
1452                                                                                                                                 .add("AttributeId",
1453                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1454                                                                 .add("Resource",
1455                                                                                 Json.createObjectBuilder()
1456                                                                                                 .add("Attribute",
1457                                                                                                                 resourceArray
1458                                                                                                                                 .add(Json
1459                                                                                                                                                 .createObjectBuilder()
1460                                                                                                                                                 .add("Value",
1461                                                                                                                                                                 "Config")
1462                                                                                                                                                 .add("AttributeId",
1463                                                                                                                                                                 "urn:oasis:names:tc:xacml:1.0:resource:resource-id")))))
1464                                 .build();
1465                 logger.debug("Generated JSON Request is: " + model.toString());
1466                 if(listRequestParameters.getUnique()){
1467                         logger.info("Requested for Unique Result only. ");
1468                         unique = true;
1469                 }
1470                 try {
1471                         policyConfig = configResult(generateRequest(model.toString(), listRequestParameters.getRequestID()));
1472                 } catch (Exception e) {
1473                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1474                         throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1475                 }
1476                 for(PolicyConfig policy : policyConfig){
1477                         if(policy.getPolicyConfigMessage()!=null && policy.getPolicyConfigMessage().contains("PE300")){
1478                                 policyList.add(policy.getPolicyConfigMessage());
1479                         } else {
1480                                 policyList.add("Policy Name: " + policy.getPolicyName());
1481                         }
1482                 }
1483                 return policyList;
1484         }
1485         
1486
1487
1488         public Collection<PolicyResponse> event(Map<String, String> eventAttributes, UUID requestID, String userID, String passcode)
1489                         throws PolicyEventException {
1490                 String resource= "sendEvent";
1491                 if(!checkPermissions(userID, passcode, resource)){
1492                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1493                         throw new PolicyEventException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1494                 }
1495                 Collection<PolicyResponse> policyResponse = null;
1496                 if (eventAttributes != null && !eventAttributes.isEmpty()) {
1497                         JsonArrayBuilder resourceArray = Json.createArrayBuilder();
1498                         for (String key : eventAttributes.keySet()) {
1499                                 if (key.isEmpty()) {
1500                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key");
1501                                         throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +"Cannot have an empty Key");
1502                                 }
1503                                 JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
1504                                 if (eventAttributes.get(key).matches("[0-9]+")) {
1505                                         int val = Integer.parseInt(eventAttributes.get(key));
1506                                         resourceBuilder.add("Value", val);
1507                                 } else {
1508                                         resourceBuilder.add("Value", eventAttributes.get(key));
1509                                 }
1510                                 resourceBuilder.add("AttributeId", key);
1511                                 resourceArray.add(resourceBuilder);
1512                         }
1513                         JsonObject model = Json
1514                                         .createObjectBuilder()
1515                                         .add("Request",
1516                                                         Json.createObjectBuilder().add(
1517                                                                         "Resource",
1518                                                                         Json.createObjectBuilder().add("Attribute",
1519                                                                                         resourceArray))).build();
1520                         // Removed Part can be Useful in Future.
1521                         /*
1522                          * .add("AccessSubject",Json.createObjectBuilder() .add("Attribute",
1523                          * subjectArray)) .add("Action", Json.createObjectBuilder()
1524                          * .add("Attribute", actionArray))
1525                          */
1526                         // System.out.println(model.toString());
1527                         try {
1528                                 // StdPolicyResponse stdPolicyResponse =
1529                                 // generateRequest(model.toString());
1530                                 // stdPolicyResponse.setRequestAttributes(eventAttributes);
1531                                 policyResponse = eventResult(generateRequest(model.toString(), requestID),
1532                                                 eventAttributes);
1533                         } catch (Exception e) {
1534                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1535                                 throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1536                         }
1537                 } else {
1538                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Attributes Given. ");
1539                         throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +"No EventAttributes Given.");
1540                 }
1541                 return policyResponse;
1542         }
1543
1544         private Collection<StdStatus> generateRequest(String Json, UUID requestID) throws Exception {
1545                 Collection<StdStatus> results = null;
1546                 
1547                 Response response = null;
1548                 // Create Request. We need XACML API here.
1549                 try {
1550                         Request request = JSONRequest.load(Json);
1551                         String jRequest = JSONRequest.toString(request);
1552                                 
1553                         // Call the PDP
1554                         logger.debug("--- Generating Request: ---\n" + jRequest );
1555                         response = callPDP(new ByteArrayInputStream(jRequest.getBytes()), requestID);
1556
1557                 } catch (Exception e) {
1558                         logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e);
1559                         StdStatus stdStatus = new StdStatus();
1560                         results = new HashSet<StdStatus>();
1561                         stdStatus.setStatus("Unable to Call PDP. Error with the URL",
1562                                         PolicyResponseStatus.NO_ACTION_REQUIRED,
1563                                         PolicyConfigStatus.CONFIG_NOT_FOUND);
1564                         results.add(stdStatus);
1565                         throw new Exception(e);
1566                 }
1567
1568                 if(this.UEBThread){
1569                         this.UEBThread = registerUEBThread.isAlive();
1570                 }
1571                 if (response != null) {
1572                         results = checkResponse(response);
1573                         // TODO Starting Auto Client Here.
1574                         if (notificationType.get(0).equals("ueb") && !this.UEBThread){
1575                                 this.UEBClientThread = new AutoClientUEB(pdps.get(0), uebURLList); 
1576                                 this.registerUEBThread = new Thread(this.UEBClientThread);
1577                                 this.registerUEBThread.start();
1578                                 this.UEBThread = true;
1579                                 
1580                         }else {
1581                                 if(AutoClientEnd.getURL()==null){
1582                                         AutoClientEnd.start(pdps.get(0));
1583                                 }else if(AutoClientEnd.getURL()!=pdps.get(0)){
1584                                         AutoClientEnd.stop();
1585                                         AutoClientEnd.start(pdps.get(0));
1586                                 }
1587                         }
1588                 } else {
1589                         logger.debug("No Response Received from PDP");
1590                         StdStatus stdStatus = new StdStatus();
1591                         results = new HashSet<StdStatus>();
1592                         stdStatus.setStatus("No Response Received",
1593                                         PolicyResponseStatus.NO_ACTION_REQUIRED,
1594                                         PolicyConfigStatus.CONFIG_NOT_FOUND);
1595                         results.add(stdStatus);
1596                 }
1597
1598                 return results;
1599         }
1600         
1601         private Response callPDP(ByteArrayInputStream input, UUID requestID) throws Exception {
1602                 Response response = null;
1603                 HttpURLConnection connection = null;
1604                 responseCode = 0;
1605                 // Checking for the available PDPs is done during the first Request and
1606                 // the List is going to have the connected PDP as first element.
1607                 // This makes it Real-Time to change the list depending on their
1608                 // availability.
1609                 if (pdps == null || pdps.isEmpty()) {
1610                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDPs List is Empty.");
1611                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PDPs List is empty.");
1612                 } else {
1613                         int pdpsCount = 0;
1614                         boolean connected = false;
1615                         while (pdpsCount < pdps.size()) {
1616                                 input.reset();
1617                                 try {
1618                                         String urlValue = pdps.get(0);
1619                                         URL url = new URL(urlValue);
1620                                         logger.debug("--- Sending Request to PDP : "+ url.toString() + " ---");
1621                                         connection = (HttpURLConnection) url.openConnection();
1622                                         // Setting Content-Type
1623                                         connection.setRequestProperty("Content-Type","application/json");
1624                                         // Adding Authorization
1625                                         connection.setRequestProperty("Authorization", "Basic " + encoding.get(0));
1626                                         // Adding Environment. 
1627                                         connection.setRequestProperty("Environment", environment);
1628                                         // Adding RequestID
1629                                         if (requestID == null) {
1630                                                 requestID = UUID.randomUUID();
1631                                                 logger.info("No request ID provided, sending generated ID: " + requestID.toString());
1632                                         } else {
1633                                                 logger.info("Using provided request ID: " + requestID.toString());
1634                                         }
1635                                         connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
1636                                         // Setting up connection method and headers.
1637                                         connection.setRequestMethod("POST");
1638                                         connection.setUseCaches(false);
1639                                         connection.setInstanceFollowRedirects(false);
1640                                         connection.setDoOutput(true);
1641                                         connection.setDoInput(true);
1642                                         OutputStream os = connection.getOutputStream();
1643                                         IOUtils.copy(input, os);
1644                                         
1645                                         
1646                                         connection.connect();
1647                                         responseCode = connection.getResponseCode();
1648                                         // If Connected to a PDP Then break from the loop and
1649                                         // continue with the Request.
1650                                         if (connection.getResponseCode() == 200 || junit) {
1651                                                 connected = true;
1652                                                 break;
1653                                         } else {
1654                                                 logger.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PDP Response Code : "      + connection.getResponseCode());
1655                                                 Collections.rotate(pdps, -1);
1656                                                 Collections.rotate(encoding, -1);
1657                                         }
1658                                 } catch (Exception e) {
1659                                         // This means that the PDP is not working and needs to
1660                                         // Re-Order our List and Connect to the next one.
1661                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP connection Error : " + e);
1662                                         Collections.rotate(pdps, -1);
1663                                         Collections.rotate(encoding, -1);
1664                                 }
1665                                 pdpsCount++;
1666                         }
1667                         if (connected) {
1668                                 // Read the Response
1669                                 // System.out.println("connected to PDP : " + pdps.get(0));
1670                                 logger.debug("connected to PDP : " + pdps.get(0));
1671                                 logger.debug("--- Response:  ---");
1672                                 Map<String,List<String>> headers = connection.getHeaderFields();
1673                                 for(String key : headers.keySet()){
1674                                         logger.debug("Header : " + key + "   Value: " + headers.get(key));
1675                                 }
1676                                 try {
1677                                         if (connection.getResponseCode() == 200 || junit) {
1678                                                 // Read the Response
1679                                                 ContentType contentType = null;
1680                                                 try {
1681                                                         contentType = ContentType.parse(connection
1682                                                                         .getContentType());
1683                                                         if (contentType.getMimeType().equalsIgnoreCase(
1684                                                                         ContentType.APPLICATION_JSON.getMimeType())) {
1685                                                                 if(junit){
1686                                                                         response = JSONResponse.load(getJsonResponseString());
1687                                                                 } else {
1688                                                                         response = JSONResponse.load(connection.getInputStream());
1689                                                                 }
1690                                                                 logger.debug(response + "\n---");
1691                                                         } else {
1692                                                                 logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unknown Content-Type: "
1693                                                                                 + contentType);
1694                                                                 throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unknown Content-Type: "
1695                                                                                 + contentType);
1696                                                         }
1697                                                 } catch (Exception e) {
1698                                                         String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Parsing Content-Type: "
1699                                                                         + connection.getContentType() + ", error="
1700                                                                         + e;
1701                                                         logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e);
1702                                                         throw new Exception(message, e);
1703                                                 }
1704                                         } else {
1705                                                 throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS+ "ERROR response code of the URL " + pdps.get(0) + " is "
1706                                                                 + connection.getResponseCode());
1707                                         }
1708                                 } catch (IOException e) {
1709                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1710                                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error in Connecting to the  PDP ", e);
1711                                 }
1712                                 return response;
1713                         } else {
1714                                 if(junit){
1715                                         response = JSONResponse.load(getJsonResponseString());
1716                                         return response;
1717                                 }
1718                                 throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS+ "Unable to get valid Response from  PDP(s) " + pdps);
1719                         }
1720                 }
1721         }
1722         
1723         private Collection<StdStatus> checkResponse(Response response)
1724                         throws Exception {
1725
1726                 String pdpConfigURL = null;
1727
1728                 Collection<StdStatus> combinedResult = new HashSet<StdStatus>();
1729                 int priority = defaultPriority;
1730                 Map<Integer, StdStatus> uniqueResult = new HashMap<Integer, StdStatus>();
1731                 for (Result result : response.getResults()) {
1732                         if (!result.getDecision().equals(Decision.PERMIT)) {
1733                                 logger.debug("Decision not a Permit. "  + result.getDecision().toString());
1734                                 StdStatus stdStatus = new StdStatus();
1735                                 if (decide) {
1736                                         stdStatus.setDecision(PolicyDecision.DENY);
1737                                         for(Advice advice: result.getAssociatedAdvice()){
1738                                                 for(AttributeAssignment attribute: advice.getAttributeAssignments()){
1739                                                         stdStatus.setDetails(attribute.getAttributeValue().getValue().toString());
1740                                                         break;
1741                                                 }
1742                                         }
1743                                         combinedResult.add(stdStatus);
1744                                         return combinedResult;
1745                                 }
1746                                 stdStatus.setStatus(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.",PolicyResponseStatus.NO_ACTION_REQUIRED,PolicyConfigStatus.CONFIG_NOT_FOUND);
1747                                 combinedResult.add(stdStatus);
1748                                 return combinedResult;
1749                         } else {
1750                                 if (decide) {
1751                                         // check for Decision for decision based calls.
1752                                         StdStatus stdStatus = new StdStatus();
1753                                         stdStatus.setDecision(PolicyDecision.PERMIT);
1754                                         stdStatus.setDetails("Decision Permit. OK!");
1755                                         combinedResult.add(stdStatus);
1756                                         return combinedResult;
1757                                 }
1758                                 if (!result.getAssociatedAdvice().isEmpty()) {
1759                                         // @ TODO Add advice actions
1760                                         // Configurations should be in advice. + Also PDP took
1761                                         // actions could be here.
1762                                         for (Advice advice : result.getAssociatedAdvice()) {
1763                                                 int config = 0, uri = 0;
1764                                                 String configURL = null;
1765                                                 String policyName = null;
1766                                                 String policyVersion = null;
1767                                                 Map<String, String> matchingConditions = new HashMap<String, String>();
1768                                                 match = new Matches();
1769                                                 Map<String, String> configAttributes = new HashMap<String, String>();
1770                                                 Map<String, String> responseAttributes = new HashMap<String,String>();
1771                                                 Map<String, String> actionTaken = new HashMap<String, String>();
1772                                                 StdStatus stdStatus = new StdStatus();
1773                                                 Map<String, String> adviseAttributes = new HashMap<String, String>();
1774                                                 for (AttributeAssignment attribute : advice.getAttributeAssignments()) {
1775                                                         adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString());
1776                                                         if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("CONFIGURATION")) {
1777                                                                 config++;
1778                                                         } else if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) {
1779                                                                 uri++;
1780                                                                 if (uri == 1) {
1781                                                                         configURL = attribute.getAttributeValue().getValue().toString();
1782                                                                         String currentUsedPDP = pdps.get(0);
1783                                                                         int pos = (pdps.get(0)).lastIndexOf("/");
1784                                                                         String configURLPath = currentUsedPDP.substring(0, pos);
1785                                                                         int pos1 = configURLPath.lastIndexOf("/");
1786                                                                         String pdpConfigURLPath = configURLPath.substring(0, pos1 + 1);
1787                                                                         pdpConfigURL = configURL.replace("$URL", pdpConfigURLPath);
1788                                                                 } else {
1789                                                                         if (!(attribute.getIssuer().equalsIgnoreCase("PDP"))) {
1790                                                                                 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error having multiple URI in the Policy");
1791                                                                         }
1792                                                                 }
1793                                                         } else if (attribute.getAttributeId().stringValue()
1794                                                                         .equalsIgnoreCase("PolicyName")) {
1795                                                                 policyName = attribute.getAttributeValue()
1796                                                                                 .getValue().toString();
1797                                                         } else if (attribute.getAttributeId().stringValue()
1798                                                                         .equalsIgnoreCase("VersionNumber")) {
1799                                                                 policyVersion = attribute.getAttributeValue()
1800                                                                                 .getValue().toString();
1801                                                         } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("Priority")){
1802                                                                 try{
1803                                                                         priority = Integer.parseInt(attribute.getAttributeValue().getValue().toString());
1804                                                                 } catch(Exception e){
1805                                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Unable to Parse Integer for Priority. Setting to default value");
1806                                                                         priority = defaultPriority;
1807                                                                 }
1808                                                         } else if (attribute.getAttributeId().stringValue()
1809                                                                         .startsWith("matching")) {
1810                                                                 matchingConditions.put(attribute
1811                                                                                 .getAttributeId().stringValue()
1812                                                                                 .replaceFirst("(matching).", ""),
1813                                                                                 attribute.getAttributeValue()
1814                                                                                                 .getValue().toString());
1815                                                                 if (attribute.getAttributeId().stringValue()
1816                                                                                 .replaceFirst("(matching).", "")
1817                                                                                 .equals("ECOMPName")) {
1818                                                                         match.setEcompName(attribute
1819                                                                                         .getAttributeValue().getValue()
1820                                                                                         .toString());
1821                                                                 } else if (attribute.getAttributeId()
1822                                                                                 .stringValue()
1823                                                                                 .replaceFirst("(matching).", "")
1824                                                                                 .equals("ConfigName")) {
1825                                                                         match.setConfigName(attribute
1826                                                                                         .getAttributeValue().getValue()
1827                                                                                         .toString());
1828                                                                 } else {
1829                                                                         configAttributes.put(attribute
1830                                                                                         .getAttributeId().stringValue()
1831                                                                                         .replaceFirst("(matching).", ""),
1832                                                                                         attribute.getAttributeValue()
1833                                                                                                         .getValue().toString());
1834                                                                 }
1835                                                         } else if (attribute.getAttributeId().stringValue().startsWith("key:")) {
1836                                                                 responseAttributes.put(attribute
1837                                                                                 .getAttributeId().stringValue()
1838                                                                                 .replaceFirst("(key).", ""),
1839                                                                                 attribute.getAttributeValue()
1840                                                                                                 .getValue().toString());
1841                                                         }
1842                                                 }
1843                                                 if (!configAttributes.isEmpty()) {
1844                                                         match.setConfigAttributes(configAttributes);
1845                                                 }
1846                                                 if ((config == 1) && (uri == 1)) {
1847                                                         // If there is a configuration.
1848                                                         try {
1849                                                                 logger.debug("Configuration Call to : "
1850                                                                                 + configURL);
1851                                                                 stdStatus = ConfigCall(pdpConfigURL);
1852                                                         } catch (Exception e) {
1853                                                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ e);
1854                                                                 stdStatus
1855                                                                                 .setStatus(
1856                                                                                                 "Error in Calling the Configuration URL "
1857                                                                                                                 + e,
1858                                                                                                 PolicyResponseStatus.NO_ACTION_REQUIRED,
1859                                                                                                 PolicyConfigStatus.CONFIG_NOT_FOUND);
1860                                                         }
1861                                                         stdStatus.setPolicyName(policyName);
1862                                                         stdStatus.setPolicyVersion(policyVersion);
1863                                                         stdStatus.setMatchingConditions(matchingConditions);
1864                                                         stdStatus.setResposneAttributes(responseAttributes);
1865                                                         if(!unique){
1866                                                                 combinedResult.add(stdStatus);
1867                                                         }else{
1868                                                                 if(!uniqueResult.isEmpty()){
1869                                                                         if(uniqueResult.containsKey(priority)){
1870                                                                                 // Not any more unique, check the matching conditions size
1871                                                                                 int oldSize = uniqueResult.get(priority).getMatchingConditions().size();
1872                                                                                 int newSize = matchingConditions.size();
1873                                                                                 if(oldSize < newSize){
1874                                                                                         uniqueResult.put(priority, stdStatus);
1875                                                                                 }else if(oldSize == newSize){
1876                                                                                         stdStatus = new StdStatus();
1877                                                                                         stdStatus.setStatus("Two/more Policies have Same Priority and matching conditions, Please correct your policies.", PolicyResponseStatus.NO_ACTION_REQUIRED,
1878                                                                                                         PolicyConfigStatus.CONFIG_NOT_FOUND);
1879                                                                                         combinedResult.add(stdStatus);
1880                                                                                         unique = false;
1881                                                                                         return combinedResult;
1882                                                                                 }
1883                                                                         }else{
1884                                                                                 uniqueResult.put(priority, stdStatus);
1885                                                                         }
1886                                                                 }else{
1887                                                                         uniqueResult.put(priority, stdStatus);
1888                                                                 }
1889                                                         }
1890                                                 } else {
1891                                                         // Else it is Action Taken.
1892                                                         logger.info("Action Taken by PDP. ");
1893                                                         actionTaken.putAll(adviseAttributes);
1894                                                         stdStatus.setActionTaken(actionTaken);
1895                                                         stdStatus.setPolicyResponseStatus(
1896                                                                         "Action Taken by the PDP",
1897                                                                         PolicyResponseStatus.ACTION_TAKEN);
1898                                                         combinedResult.add(stdStatus);
1899                                                 }
1900                                         }
1901                                 }
1902                                 if (!result.getObligations().isEmpty()) {
1903                                         // @ TODO add Obligation actions
1904                                         // Action advised should be in obligations.
1905                                         for (Obligation obligation : result.getObligations()) {
1906                                                 Map<String, String> actionAdvised = new HashMap<String, String>();
1907                                                 StdStatus stdStatus = new StdStatus();
1908                                                 for (AttributeAssignment attribute : obligation
1909                                                                 .getAttributeAssignments()) {
1910                                                         actionAdvised.put(attribute.getAttributeId()
1911                                                                         .stringValue(), attribute
1912                                                                         .getAttributeValue().getValue().toString());
1913                                                 }
1914                                                 stdStatus.setActionAdvised(actionAdvised);
1915                                                 stdStatus.setPolicyResponseStatus(
1916                                                                 "Action has been Advised ",
1917                                                                 PolicyResponseStatus.ACTION_ADVISED);
1918                                                 combinedResult.add(stdStatus);
1919                                         }
1920                                 }
1921                         }
1922                 }
1923                 if(unique){
1924                         // Select Unique policy. 
1925                         int minNum = defaultPriority;
1926                         for(int num: uniqueResult.keySet()){
1927                                 if(num < minNum){
1928                                         minNum = num;
1929                                 }
1930                         }
1931                         combinedResult.add(uniqueResult.get(minNum));
1932                         // Turn off Unique
1933                         unique = false;
1934                 }
1935                 
1936                 return combinedResult;
1937         }
1938
1939         private StdStatus ConfigCall(String stringURL) throws Exception {
1940                 StdStatus stdStatus = new StdStatus();
1941                 try {
1942                         URL configURL = new URL(stringURL);
1943                         URLConnection connection = null;
1944                         try {
1945                                 connection = configURL.openConnection();
1946                                 if (stringURL.endsWith("json")) {
1947                                         stdStatus.setPolicyType(PolicyType.JSON);
1948                                         JsonReader jsonReader = Json.createReader(connection
1949                                                         .getInputStream());
1950                                         stdStatus.setJsonObject(jsonReader.readObject());
1951                                         jsonReader.close();
1952                                         logger.info("config Retrieved ");
1953                                         stdStatus.setStatus("Config Retrieved from: " + configURL,
1954                                                         PolicyResponseStatus.NO_ACTION_REQUIRED,
1955                                                         PolicyConfigStatus.CONFIG_RETRIEVED);
1956                                         try {
1957                                                 MatchStore.storeMatch(match);
1958                                         } catch (Exception e) {
1959                                                 logger.info("StoreMatch failed for Ecomp:"
1960                                                                 + match.getEcompName() + " Config: "
1961                                                                 + match.getConfigName());
1962                                         }
1963                                         return stdStatus;
1964                                 } else if (stringURL.endsWith("xml")) {
1965                                         stdStatus.setPolicyType(PolicyType.XML);
1966                                         DocumentBuilderFactory dbf = DocumentBuilderFactory
1967                                                         .newInstance();
1968                                         DocumentBuilder db = null;
1969                                         try {
1970                                                 db = dbf.newDocumentBuilder();
1971                                                 Document config = db.parse(connection.getInputStream());
1972                                                 stdStatus.setDocument(config);
1973                                         } catch (ParserConfigurationException e) {
1974                                                 logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e);
1975                                                 throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to create Document Object",
1976                                                                 e);
1977                                         } catch (SAXException e) {
1978                                                 logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e);
1979                                                 throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e);
1980                                         }
1981                                         logger.info("config Retrieved ");
1982                                         stdStatus.setStatus("Config Retrieved from: " + configURL,
1983                                                         PolicyResponseStatus.NO_ACTION_REQUIRED,
1984                                                         PolicyConfigStatus.CONFIG_RETRIEVED);
1985                                         try {
1986                                                 MatchStore.storeMatch(match);
1987                                         } catch (Exception e) {
1988                                                 logger.info("StoreMatch failed for Ecomp:"
1989                                                                 + match.getEcompName() + " Config: "
1990                                                                 + match.getConfigName());
1991                                         }
1992                                         return stdStatus;
1993                                 } else if (stringURL.endsWith("properties")) {
1994                                         stdStatus.setPolicyType(PolicyType.PROPERTIES);
1995                                         Properties configProp = new Properties();
1996                                         configProp.load(connection.getInputStream());
1997                                         stdStatus.setProperties(configProp);
1998                                         logger.info("config Retrieved ");
1999                                         stdStatus.setStatus("Config Retrieved from: " + configURL,
2000                                                         PolicyResponseStatus.NO_ACTION_REQUIRED,
2001                                                         PolicyConfigStatus.CONFIG_RETRIEVED);
2002                                         try {
2003                                                 MatchStore.storeMatch(match);
2004                                         } catch (Exception e) {
2005                                                 logger.info("StoreMatch failed for Ecomp:"
2006                                                                 + match.getEcompName() + " Config: "
2007                                                                 + match.getConfigName());
2008                                         }
2009                                         return stdStatus;
2010                                 } else if (stringURL.endsWith("txt")) {
2011                                         stdStatus.setPolicyType(PolicyType.OTHER);
2012                                         InputStream in = connection.getInputStream();
2013                                         String other = IOUtils.toString(in);
2014                                         IOUtils.closeQuietly(in);
2015                                         stdStatus.setOther(other);
2016                                         logger.info("config Retrieved ");
2017                                         stdStatus.setStatus("Config Retrieved from: " + configURL,
2018                                                         PolicyResponseStatus.NO_ACTION_REQUIRED,
2019                                                         PolicyConfigStatus.CONFIG_RETRIEVED);
2020                                         try {
2021                                                 MatchStore.storeMatch(match);
2022                                         } catch (Exception e) {
2023                                                 logger.info("StoreMatch failed for Ecomp:"
2024                                                                 + match.getEcompName() + " Config: "
2025                                                                 + match.getConfigName());
2026                                         }
2027                                         return stdStatus;
2028                                 } else {
2029                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found");
2030                                         stdStatus
2031                                                         .setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
2032                                         stdStatus
2033                                                         .setConfigStatus("Illegal form of Configuration Type Found.");
2034                                         return stdStatus;
2035                                 }
2036                         } catch (IOException e) {
2037                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
2038                                 throw new Exception(XACMLErrorConstants.ERROR_PROCESS_FLOW +
2039                                                 "Cannot open a connection to the configURL", e);
2040                         }
2041                 } catch (MalformedURLException e) {
2042                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
2043                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e);
2044                 }
2045         }
2046
2047         private void setProperty(String propertyFilePath)
2048                         throws PolicyEngineException {
2049                 this.propertyFilePath = propertyFilePath;
2050                 if (this.propertyFilePath == null) {
2051                         // This is only for testing purpose. Or We will add a default PDP
2052                         // address here.
2053                         // url_default = "http://localhost:8080/pdp/";
2054                         // The General Error Message is Below.
2055                         throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided");
2056                 } else {
2057                         // Adding logic for remote Properties file.
2058                         Properties prop = new Properties();
2059                         if (propertyFilePath.startsWith("http")) {
2060                                 URL configURL;
2061                                 try {
2062                                         configURL = new URL(propertyFilePath);
2063                                         URLConnection connection = null;
2064                                         connection = configURL.openConnection();
2065                                         prop.load(connection.getInputStream());
2066                                 } catch (IOException e) {
2067                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
2068                                         throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL "+ e.getMessage());
2069                                 }
2070                         } else {
2071                                 Path file = Paths.get(propertyFilePath);
2072                                 if (Files.notExists(file)) {
2073                                         throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "File doesn't exist in the specified Path "      + file.toString());
2074                                 } 
2075                                 if (file.toString().endsWith(".properties")) {
2076                                         InputStream in;
2077                                         prop = new Properties();
2078                                         try {
2079                                                 in = new FileInputStream(file.toFile());
2080                                                 prop.load(in);
2081                                         } catch (IOException e) {
2082                                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
2083                                                 throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", e);
2084                                         }
2085                                 } else {
2086                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath);
2087                                         throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR  + "Not a .properties file");
2088                                 }
2089                         }
2090                         // UEB Settings
2091                         String check_type = prop.getProperty("NOTIFICATION_TYPE");
2092                         String serverList = prop.getProperty("NOTIFICATION_UEB_SERVERS");
2093                         if(check_type==null) {
2094                                 notificationType.add("websocket");
2095                                 logger.info("Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets"); 
2096                         }else{
2097                                 if(check_type.contains(",")) {
2098                                         type_default = new ArrayList<String>(Arrays.asList(prop.getProperty("NOTIFICATION_TYPE").split(",")));
2099                                         notificationType = type_default; 
2100                                 } else {
2101                                                 notificationType = new ArrayList<String>();
2102                                                 notificationType.add(check_type);
2103                                 }
2104                         }
2105                         if(serverList==null) {
2106                                 notificationType.clear();
2107                                 notificationType.add("websocket");
2108                                 logger.info("Properties file doesn't have the NOTIFICATION_UEB_SERVERS parameter system will use defualt websockets");  
2109                         }else{
2110                                 if(serverList.contains(",")) {
2111                                         uebURLList = new ArrayList<String>(Arrays.asList(prop.getProperty("NOTIFICATION_UEB_SERVERS").split(","))); 
2112                                 } else {
2113                                         uebURLList = new ArrayList<String>();
2114                                         uebURLList.add(serverList);
2115                                 }
2116                         }
2117                         // Client ID Authorization Settings. 
2118                         String clientID = prop.getProperty("CLIENT_ID");
2119                         String clientKey = prop.getProperty("CLIENT_KEY");
2120                         userName = clientID;
2121                         pass = clientKey;
2122                         pyPDPClientFile = prop.getProperty("CLIENT_FILE");
2123                         environment = prop.getProperty("ENVIRONMENT", "DEVL");
2124                         /*try {
2125                                 aafClient = AAFPolicyClient.getInstance(prop);
2126                         } catch (AAFPolicyException e) {
2127                                 logger.error(XACMLErrorConstants.ERROR_UNKNOWN + e.getMessage());
2128                                 throw new PolicyEngineException(XACMLErrorConstants.ERROR_UNKNOWN + e);
2129                         }*/
2130                         // Initializing the values.
2131                         pdps = new ArrayList<String>();
2132                         paps = new ArrayList<String>(); 
2133                         encoding = new ArrayList<String>();
2134                         encodingPAP = new ArrayList<String>();
2135                         // Check the Keys for PDP_URLs
2136                         Collection<Object> unsorted = prop.keySet();
2137                         @SuppressWarnings({ "rawtypes", "unchecked" })
2138                         List<String> sorted = new ArrayList(unsorted);
2139                         Collections.sort(sorted);
2140                         for (String propKey : sorted) {
2141                                 if (propKey.startsWith("PDP_URL")) {
2142                                         String check_val = prop.getProperty(propKey);
2143                                         if (check_val == null) {
2144                                                 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Properties file doesn't have the PDP_URL parameter");
2145                                         }
2146                                         if (check_val.contains(";")) {
2147                                                 pdp_default = new ArrayList<String>(Arrays.asList(check_val.split("\\s*;\\s*")));
2148                                                 int pdpCount = 0;
2149                                                 while (pdpCount < pdp_default.size()) {
2150                                                         String pdpVal = pdp_default.get(pdpCount);
2151                                                         readPDPParam(pdpVal);
2152                                                         pdpCount++;
2153                                                 }
2154                                         } else {
2155                                                 readPDPParam(check_val);
2156                                         }
2157                                 } else if (propKey.startsWith("PAP_URL")) {
2158                                         String check_val = prop.getProperty(propKey);
2159                                         if (check_val == null) {
2160                                                 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Properties file doesn't have the PAP_URL parameter");
2161                                         }
2162                                         if (check_val.contains(";")) {
2163                                                 pap_default = new ArrayList<String>(Arrays.asList(check_val.split("\\s*;\\s*")));
2164                                                 int papCount = 0;
2165                                                 while (papCount < pap_default.size()) {
2166                                                         String papVal = pap_default.get(papCount);
2167                                                         readPAPParam(papVal);
2168                                                         papCount++;
2169                                                 }
2170                                         } else {
2171                                                 readPAPParam(check_val);
2172                                         }
2173                                 }
2174                         }
2175                         if (pdps == null || pdps.isEmpty()) {
2176                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
2177                                 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
2178                         }
2179                         
2180                         if (paps == null || paps.isEmpty()) {
2181                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PAP_URLs");
2182                                 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed with out PAP_URLs");
2183                         }
2184                         
2185                         // Get JUNIT property from properties file when running tests
2186                         String junit = prop.getProperty("JUNIT");
2187                         if(junit == null || junit.isEmpty()){
2188                                 logger.info("No JUNIT property provided, this will not be executed as a test.");
2189                         }else{
2190                                 if(junit.equals("test")){
2191                                         this.junit = true;
2192                                 } else {
2193                                         this.junit = false;
2194                                 }
2195                         }
2196                 }
2197         }
2198         
2199         /*
2200          * Read the PDP_URL parameter
2201          */
2202         private void readPDPParam(String pdpVal) throws PolicyEngineException{
2203                 if(pdpVal.contains(",")){
2204                         List<String> pdpValues = new ArrayList<String>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
2205                         if(pdpValues.size()==3){
2206                                 // 0 - PDPURL
2207                                 pdps.add(pdpValues.get(0));
2208                                 // 1:2 will be UserID:Password
2209                                 String userID = pdpValues.get(1);
2210                                 String pass = pdpValues.get(2);
2211                                 Base64.Encoder encoder = Base64.getEncoder();
2212                                 encoding.add(encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
2213                         }else{
2214                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues);
2215                                 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues);
2216                         }
2217                 }else{
2218                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal);
2219                         throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values.");
2220                 }
2221         }
2222         
2223         /*
2224          * Read the PAP_URL parameter
2225          */
2226         private void readPAPParam(String papVal) throws PolicyEngineException{
2227                 if(papVal.contains(",")){
2228                         List<String> papValues = new ArrayList<String>(Arrays.asList(papVal.split("\\s*,\\s*")));
2229                         if(papValues.size()==3){
2230                                 // 0 - PAPURL
2231                                 paps.add(papValues.get(0));
2232                                 // 1:2 will be UserID:Password
2233                                 String userID = papValues.get(1);
2234                                 String pass = papValues.get(2);
2235                                 Base64.Encoder encoder = Base64.getEncoder();
2236                                 encodingPAP.add(encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
2237                         }else{
2238                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + papValues);
2239                                 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + papValues);
2240                         }
2241                 }else{
2242                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + papVal);
2243                         throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request.");
2244                 }
2245         }
2246         /*
2247          * Allowing changes to the scheme and Handler.
2248          */
2249         public void notification(NotificationScheme scheme, NotificationHandler handler) {
2250                 this.scheme = scheme;
2251                 this.handler = handler;
2252                 logger.debug("Scheme is : " + scheme.toString());
2253                 logger.debug("Handler is : " + handler.getClass().getName());
2254                 if (!notificationType.get(0).equals("ueb")){
2255                         AutoClientEnd.setAuto(scheme, handler);
2256                 }else {
2257                         if (this.UEBThread){
2258                                 UEBClientThread.setAuto(scheme, handler);
2259                                 this.UEBThread = registerUEBThread.isAlive();
2260                         }
2261                 }
2262         
2263                 //TODO This could also be a Start point for Auto Notifications..
2264                 if(pdps!=null){
2265                         if (notificationType.get(0).equals("ueb")  && !this.UEBThread){
2266                                 this.UEBClientThread = new AutoClientUEB(pdps.get(0), uebURLList); 
2267                                 this.UEBClientThread.setAuto(scheme, handler);
2268                                 this.registerUEBThread = new Thread(this.UEBClientThread);
2269                                 this.registerUEBThread.start();
2270                                 this.UEBThread = true;
2271                         }
2272                         if (!notificationType.get(0).equals("ueb")){
2273                                 if(pdps.get(0)!=null){
2274                                         if(AutoClientEnd.getURL()==null){
2275                                                 AutoClientEnd.start(pdps.get(0));
2276                                         }else {
2277                                                 AutoClientEnd.stop();
2278                                                 AutoClientEnd.start(pdps.get(0));
2279                                         }
2280                                 }
2281                         }
2282                 }
2283         }
2284
2285         /*
2286          * Gets the Notification if one exists. Used only for Manual Polling
2287          * purposes.
2288          */
2289         public PDPNotification getNotification(){
2290                 //TODO manual Polling
2291                 //Check if there is proper scheme.. 
2292                 PDPNotification notification = null;
2293                 if(this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS) || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
2294                         if (notificationType.get(0).equals("ueb")){
2295                                 ManualClientEndUEB.start(pdps.get(0), uebURLList, uniqueID);
2296                                 notification = ManualClientEndUEB.result(scheme);
2297                         }else{
2298                                 ManualClientEnd.start(pdps.get(0));
2299                                 logger.debug("manual notification requested.. : " + scheme.toString());
2300                                 notification = ManualClientEnd.result(scheme);
2301                         }
2302                         
2303                         if (notification == null){
2304                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet..");
2305                                 return null;
2306                         } else {
2307                                 return notification;
2308                         }
2309                         
2310                 }else {
2311                         return null;
2312                 }
2313         }
2314
2315         /*
2316          * Setting the Scheme.
2317          */
2318         public void setScheme(NotificationScheme scheme) {
2319                 this.scheme = scheme;
2320                 if (notificationType.get(0).equals("ueb")){
2321                         AutoClientUEB.setScheme(this.scheme);
2322                         if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)){
2323                                 ManualClientEndUEB.createTopic(pdps.get(0), uniqueID, uebURLList);
2324                         }
2325                 }else{
2326                         AutoClientEnd.setScheme(this.scheme);
2327                 }       
2328         }
2329
2330         /*
2331          * Returns the Scheme
2332          */
2333         public NotificationScheme getScheme() {
2334                 return this.scheme;
2335         }
2336
2337         /*
2338          * Returns the NotificationHandler
2339          */
2340         public NotificationHandler getNotificationHandler() {
2341                 return this.handler;
2342         }
2343
2344         private Collection<PolicyConfig> configResult(
2345                         Collection<StdStatus> generateRequest) {
2346                 Collection<PolicyConfig> result = new HashSet<PolicyConfig>();
2347                 if (generateRequest == null) {
2348                         return null;
2349                 }
2350                 if (!generateRequest.isEmpty()) {
2351                         for (StdStatus stdStatus : generateRequest) {
2352                                 PolicyConfig policyConfig = new StdPolicyConfig();
2353                                 policyConfig = stdStatus;
2354                                 result.add(policyConfig);
2355                         }
2356                 }
2357                 return result;
2358         }
2359
2360         private Collection<PolicyResponse> eventResult(
2361                         Collection<StdStatus> generateRequest,
2362                         Map<String, String> eventAttributes) {
2363                 Collection<PolicyResponse> result = new HashSet<PolicyResponse>();
2364                 if (generateRequest == null) {
2365                         return null;
2366                 }
2367                 if (!generateRequest.isEmpty()) {
2368                         for (StdStatus stdStatus : generateRequest) {
2369                                 StdPolicyResponse policyResponse = new StdPolicyResponse();
2370                                 policyResponse = stdStatus;
2371                                 policyResponse.setRequestAttributes(eventAttributes);
2372                                 result.add(policyResponse);
2373                         }
2374                 }
2375                 return result;
2376         }
2377
2378         private DecisionResponse decisionResult(Collection<StdStatus> generateRequest) {
2379                 StdDecisionResponse policyDecision = new StdDecisionResponse();
2380                 if (generateRequest == null) {
2381                         return policyDecision;
2382                 }
2383                 if (!generateRequest.isEmpty()) {
2384                         for (StdStatus stdStatus : generateRequest) {
2385                                 policyDecision.setDecision(stdStatus.getDecision());
2386                                 policyDecision.setDetails(stdStatus.getDetails());
2387                         }
2388                 }
2389                 return policyDecision;
2390         }
2391
2392         /*
2393          * Stop the Notification Service if its running.
2394          */
2395         public void stopNotification() {
2396                 if (this.scheme != null && this.handler != null) {
2397                         if (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)
2398                                         || this.scheme
2399                                                         .equals(NotificationScheme.AUTO_NOTIFICATIONS)) {
2400                                 logger.info("Clear Notification called.. ");
2401                                 if (notificationType.get(0).equals("ueb")){
2402                                         this.UEBClientThread.terminate();
2403                                         this.UEBThread = false;
2404                                 }else{
2405                                         AutoClientEnd.stop();
2406                                 }
2407                         }
2408                 }
2409         }
2410         
2411         /*
2412          * Create Config Policy API Implementation
2413          */
2414         public String createConfigPolicy(String policyName, String policyDescription, String ecompName, String configName,
2415                         Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID,
2416                         String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2417                 return createConfigPolicy(policyName,policyDescription, ecompName, configName,
2418                                 configAttributes, configType, body, policyScope, requestID, userName , pass, riskLevel, riskType, guard, ttlDate);
2419         }
2420         
2421         public String createConfigPolicy(String policyName, String policyDescription, String ecompName, String configName,
2422                                                                                 Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID, String userID, String passcode,
2423                                                                                 String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2424                 
2425                 String response = null;
2426                 String configBody = null;
2427                 String resource= "createPolicy";
2428                 if(!checkPermissions(userID, passcode, resource)){
2429                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
2430                         response = XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource;
2431                         return response;
2432                 }
2433                 
2434                 //check body for JSON form and remove single quotes if present
2435                 if (configType.equalsIgnoreCase("JSON")) {
2436                         if (body.contains("'")) {
2437                                 configBody = body.replace("'", "\"");
2438                         } else {
2439                                 configBody = body;
2440                         }
2441                 } else {
2442                         configBody = body;
2443                 }
2444                 
2445                 boolean levelCheck = isNumeric(riskLevel);
2446                 
2447                 if (policyName==null||policyName.equalsIgnoreCase("")){
2448                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2449                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2450                 } else if (ecompName==null||ecompName.equalsIgnoreCase("")){
2451                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.");
2452                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.";
2453                 } else if (configName==null||configName.equalsIgnoreCase("")){
2454                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.");
2455                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.";
2456                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2457                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2458                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2459                 } else if (!levelCheck){
2460                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2461                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2462                 }else {
2463
2464                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Base", policyName, policyDescription, ecompName, configName, configAttributes, configType, 
2465                                 configBody, false, policyScope,0, riskLevel, riskType, guard, ttlDate);
2466
2467                         //send JSON object to PAP
2468                         response = (String) callPAP(newPAPPolicy, new String[] {"operation=create", "apiflag=api", "policyType=Config"}, requestID, "Config");
2469                 }
2470                 return response;
2471
2472         }
2473         
2474         /*
2475          * Create Config Policy API Implementation
2476          */
2477         public String updateConfigPolicy(String policyName, String policyDescription, String ecompName, String configName,
2478                         Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID,
2479                         String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2480                 return updateConfigPolicy(policyName, policyDescription, ecompName, configName,
2481                                 configAttributes, configType, body, policyScope, requestID, userName, pass, riskLevel, riskType, guard, ttlDate);
2482         }
2483         
2484         public String updateConfigPolicy(String policyName, String policyDescription, String ecompName, String configName,
2485                                                                                 Map<String, String> configAttributes, String configType, String body, String policyScope, 
2486                                                                                 UUID requestID, String userID, String passcode,String riskLevel, String riskType, String guard, 
2487                                                                                 String ttlDate) throws Exception {
2488                 
2489                 String response = null;
2490                 String configBody = null;
2491                 String resource= "updatePolicy";
2492                 if(!checkPermissions(userID, passcode, resource)){
2493                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
2494                         response = XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource;
2495                         return response;
2496                 }
2497                 //check body for JSON form and remove single quotes if present
2498                 if (configType.equalsIgnoreCase("JSON")) {
2499                         if (body.contains("'")) {
2500                                 configBody = body.replace("'", "\"");
2501                         } else {
2502                                 configBody = body;
2503                         }
2504                 } else {
2505                         configBody = body;
2506                 }
2507                 
2508                 boolean levelCheck = isNumeric(riskLevel);
2509                 
2510                 if (policyName==null||policyName.equalsIgnoreCase("")){
2511                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2512                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2513                 } else if (ecompName==null||ecompName.equalsIgnoreCase("")){
2514                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.");
2515                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.";
2516                 } else if (configName==null||configName.equalsIgnoreCase("")){
2517                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.");
2518                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.";
2519                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2520                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2521                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2522                 } else if (!levelCheck){
2523                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2524                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2525                 } else {
2526
2527                         //set values for basic policy information
2528                         String policyType = "Config";
2529                         String configPolicyType = "base";
2530
2531                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy(configPolicyType, policyName, policyDescription, ecompName, configName, configAttributes, configType, 
2532                                 configBody, true, policyScope,0, riskLevel, riskType, guard, ttlDate);
2533
2534                         //send JSON object to PAP
2535                         response = (String) callPAP(newPAPPolicy, new String[] {"operation=update", "apiflag=api", "policyType=" + policyType}, requestID, "Config");
2536                 
2537                 }
2538                 return response;
2539
2540         }
2541         
2542         
2543         /*
2544          * Create Config Firewall Policy API implementation
2545          */
2546         public String createConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID,
2547                         String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2548                 return createConfigFirewallPolicy(policyName, firewallJson, policyScope, requestID, userName, pass, riskLevel, riskType, guard, ttlDate);
2549         }
2550         
2551         public String createConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, String userID, String passcode,
2552                         String riskLevel, String riskType, String guard, String ttlDate) throws Exception {             
2553                 
2554                 String response = null;
2555                 String resource= "createPolicy";
2556                 if(!checkPermissions(userID, passcode, resource)){
2557                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
2558                         response = XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource;
2559                         return response;
2560                 }
2561                 
2562                 //set values for basic policy information
2563                 String configName = firewallJson.get("configName").toString();
2564         //String configDescription = firewallJson.get("configDescription").toString();
2565                 String configDescription = "";
2566                 String json = firewallJson.toString();
2567                 
2568                 boolean levelCheck = isNumeric(riskLevel);
2569
2570                 if (!isJSONValid(json)) {
2571                         logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Invalid JSON for firewallJson: " + json);
2572                         throw new PolicyDecisionException(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Invalid JSON for firewallJson: " + json);
2573                 }
2574                 
2575                 if (policyName==null||policyName.equalsIgnoreCase("")){
2576                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2577                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2578                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2579                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2580                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2581                 } else if (!levelCheck){
2582                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2583                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2584                 } else {
2585                         
2586                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Firewall Config", policyName, configDescription, configName, false, policyScope, json, 0, 
2587                                         riskLevel, riskType, guard, ttlDate);
2588                         
2589                         //send JSON object to PAP
2590                         response = (String) callPAP(newPAPPolicy, new String[] {"operation=create", "apiflag=api", "policyType=Config"}, requestID, "ConfigFirewall");
2591                 }
2592
2593                 return response;
2594         } 
2595         
2596         /*
2597          * Update Config Firewall Policy API implementation
2598          */
2599         public String updateConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, String riskLevel, String riskType, 
2600                         String guard, String ttlDate) throws Exception {
2601                 return updateConfigFirewallPolicy(policyName, firewallJson, policyScope, requestID, userName, pass, riskLevel, riskType, guard, ttlDate);
2602         }
2603         
2604         public String updateConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, String userID, String passcode,
2605                         String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2606                 
2607                 String response = null;
2608                 String resource= "updatePolicy";
2609                 if(!checkPermissions(userID, passcode, resource)){
2610                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
2611                         response = XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource;
2612                         return response;
2613                 }
2614                 String configName = firewallJson.get("configName").toString();
2615             //String configDescription = firewallJson.get("configDescription").toString();
2616                 String configDescription = "";  //ASK Lak about this...****
2617                 String json = firewallJson.toString();
2618                 boolean levelCheck = isNumeric(riskLevel);
2619                 
2620                 if (policyName==null||policyName.equalsIgnoreCase("")){
2621                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2622                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2623                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2624                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2625                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2626                 } else if (!levelCheck){
2627                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2628                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2629                 } else {
2630                         
2631                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Firewall Config", policyName, configDescription, configName, true, policyScope, json, 0,
2632                                                                                                                   riskLevel, riskType, guard, ttlDate);
2633                 
2634                         //send JSON object to PAP
2635                         response = (String) callPAP(newPAPPolicy, new String[] {"operation=update", "apiflag=api", "policyType=Config"}, requestID, "ConfigFirewall");
2636                 }
2637                 
2638                 return response;
2639         }
2640         
2641         /*
2642          * Create or Update BRMS Raw Config Policy API implementation
2643          */
2644         public String createUpdateBRMSRawPolicy(String policyName, 
2645                         String policyDescription, 
2646                         Map<AttributeType, Map<String, String>>  dyanamicFieldConfigAttributes,
2647                         String brmsRawBody, 
2648                         String policyScope, 
2649                         Boolean isEdit, 
2650                         UUID requestID,
2651                         String riskLevel, 
2652                         String riskType, 
2653                         String guard, 
2654                         String ttlDate) {
2655                 
2656                 String response = null;
2657                 String operation = null;
2658                 
2659                 
2660                 if (isEdit){
2661                         operation = "update";
2662                 } else {
2663                         operation = "create";
2664                 }
2665                 
2666                 boolean levelCheck = isNumeric(riskLevel);
2667                 
2668                 if (policyName==null||policyName.equalsIgnoreCase("")){
2669                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2670                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2671                 } else if(policyDescription==null || policyDescription.equalsIgnoreCase("")){
2672                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policyDescription given.");
2673                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No policyDescription given.";
2674                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2675                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2676                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2677                 } else if (brmsRawBody==null ||brmsRawBody.equalsIgnoreCase("")){
2678                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No rule body given.");
2679                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No rule body given.";
2680                 }  else if (!levelCheck){
2681                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2682                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2683                 } else {
2684                         /*String configPolicyType, String policyName, String description, 
2685                                         String configName, Boolean editPolicy, String domain, 
2686                                         Map<String,String> dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, 
2687                                         String configBodyData*/
2688                         
2689                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Raw",policyName,policyDescription,
2690                                                                                                                         "BRMS_RAW_RULE",isEdit,policyScope, 
2691                                                                                                                         dyanamicFieldConfigAttributes.get(AttributeType.RULE), 0, "DROOLS", 
2692                                                                                                                         brmsRawBody, riskLevel, riskType, guard, ttlDate);
2693                 
2694                         //send JSON object to PAP
2695                         try {
2696                                 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigBrmsRaw");
2697                         } catch (Exception e) {
2698                                 // TODO Auto-generated catch block
2699                                 e.printStackTrace();
2700                         }
2701                 }
2702                 
2703                 return response;
2704         }
2705         
2706         /*
2707          * Create or Update BRMS Param Config Policy API implementation
2708          */
2709         public String createUpdateBRMSParamPolicy(String policyName, 
2710                         String policyDescription, 
2711                         Map<AttributeType, Map<String, String>>  dyanamicFieldConfigAttributes,
2712                         String brmsRawBody, 
2713                         String policyScope, 
2714                         Boolean isEdit, 
2715                         UUID requestID,
2716                         Map<AttributeType, Map<String, String>> drlRuleAndUIParams,
2717                         String riskLevel, String riskType, String guard, String ttlDate) {
2718                 
2719                 String response = null;
2720                 String operation = null;
2721                 
2722                 
2723                 if (isEdit){
2724                         operation = "update";
2725                 } else {
2726                         operation = "create";
2727                 }
2728                 
2729                 boolean levelCheck = isNumeric(riskLevel);
2730                 
2731                 if (policyName==null||policyName.equalsIgnoreCase("")){
2732                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2733                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2734                 } else if(policyDescription==null || policyDescription.equalsIgnoreCase("")){
2735                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policyDescription given.");
2736                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No policyDescription given.";
2737                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2738                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2739                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2740                 } else if ((dyanamicFieldConfigAttributes==null)){
2741                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Rule Attributes given.");
2742                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Rule Attributes given.";
2743                 } else if (!levelCheck){
2744                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2745                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2746                 }else {
2747                         /*public StdPAPPolicy (String configPolicyType, String policyName, String description, 
2748                                         String configName, Boolean editPolicy, String domain, 
2749                                         Map<String,String> dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, 
2750                                         String configBodyData,Map<String,String> drlRuleAndUIParams) */
2751                         
2752                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Param",policyName,policyDescription,
2753                                                                                                                         "BRMS_PARAM_RULE",isEdit,policyScope, 
2754                                                                                                                         drlRuleAndUIParams.get(AttributeType.MATCHING), 0, "DROOLS", 
2755                                                                                                                         brmsRawBody, drlRuleAndUIParams.get(AttributeType.RULE), riskLevel, riskType, guard, ttlDate);
2756                 
2757                         //send JSON object to PAP
2758                         try {
2759                                 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigBrmsParam");
2760                         } catch (Exception e) {
2761                                 // TODO Auto-generated catch block
2762                                 e.printStackTrace();
2763                         }
2764                 }
2765                 
2766                 return response;
2767         }
2768         
2769         /*
2770          * Create or Update Action Policy API implementation
2771          */
2772         public String createUpdateActionPolicy(String policyName, String policyDescription, Map<String,String> componentAttributes, List<String> dynamicRuleAlgorithmLabels,
2773                                                                 List<String> dynamicRuleAlgorithmField1, List<String> dynamicRuleAlgorithmFunctions, List<String> dynamicRuleAlgorithmField2,
2774                                                                 String actionPerformer, String actionAttribute, String policyScope, Boolean isEdit, UUID requestID) {
2775                 
2776                 String response = null;
2777                 String operation = null;
2778                 
2779                 if (isEdit){
2780                         operation = "update";
2781                 } else {
2782                         operation = "create";
2783                 }
2784                 
2785                 if (policyName==null||policyName.equalsIgnoreCase("")){
2786                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2787                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2788                         return response;
2789                 } else if (componentAttributes==null||componentAttributes.equals("")){
2790                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given.");
2791                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given.";
2792                         return response;
2793                 } else if (actionAttribute==null||actionAttribute.equalsIgnoreCase("")){
2794                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Attribute given.");
2795                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Attribute given.";
2796                         return response;
2797                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2798                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2799                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2800                         return response;
2801                 } else if (actionPerformer==null||actionPerformer.equalsIgnoreCase("")){
2802                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Performer given.");
2803                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Performer given.";
2804                         return response;
2805                 } else if (!actionPerformer.equals("PEP")) {
2806                         if (!actionPerformer.equals("PDP")) {
2807                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Performer given.");
2808                                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Performer given.";
2809                                 return response;
2810                         }
2811                 }
2812                 
2813                 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyDescription, componentAttributes, dynamicRuleAlgorithmLabels, dynamicRuleAlgorithmFunctions, 
2814                                         dynamicRuleAlgorithmField1, dynamicRuleAlgorithmField2, actionPerformer, actionAttribute, isEdit, policyScope, 0);
2815
2816                         //send JSON object to PAP
2817                 try {
2818                         response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Action"}, requestID, "Action");
2819                 } catch (Exception e) {
2820                                 // TODO Auto-generated catch block
2821                         e.printStackTrace();
2822                 }
2823                         
2824                 return response;
2825
2826         }
2827         
2828         /*
2829          * Create or Update Decision Policy implementation
2830          */
2831         private String createUpdateDecisionPolicy(String policyName, String policyDescription, String ecompName, RuleProvider ruleProvider, Map<String,String> componentAttributes, Map<String,String> settings,
2832                         List<String> dynamicRuleAlgorithmLabels, List<String> dynamicRuleAlgorithmField1, List<String> dynamicRuleAlgorithmFunctions, List<String> dynamicRuleAlgorithmField2,
2833                         String policyScope, Boolean isEdit, UUID requestID) {
2834                 
2835                 String response = null;
2836                 String operation = null;
2837                 
2838                 if (isEdit){
2839                         operation = "update";
2840                 } else {
2841                         operation = "create";
2842                 }
2843                 
2844                 if (policyName==null||policyName.equalsIgnoreCase("")){
2845                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2846                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2847                 } else if (ecompName==null||ecompName.equalsIgnoreCase("")){
2848                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.");
2849                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.";
2850                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2851                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2852                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2853                 } else {
2854                         
2855                         if (ruleProvider==null) {
2856                                 ruleProvider = RuleProvider.CUSTOM ;
2857                         }
2858                         
2859                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyDescription, ecompName, ruleProvider.toString(), componentAttributes, settings, dynamicRuleAlgorithmLabels, dynamicRuleAlgorithmFunctions, 
2860                                                                         dynamicRuleAlgorithmField1, dynamicRuleAlgorithmField2, null, null, null, isEdit, policyScope, 0);
2861                 
2862                         //send JSON object to PAP
2863                         try {
2864                                 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Decision"}, requestID, "Decision");
2865                         } catch (Exception e) {
2866                                 // TODO Auto-generated catch block
2867                                 e.printStackTrace();
2868                         }
2869                 }
2870                 
2871                 return response;
2872         }
2873         
2874         /*
2875          * Create or Update ClosedLoop_Fault policy implementation
2876          */
2877         private String createUpdateClosedLoopPolicy(String policyName, JsonObject configBody, String policyDescription, String policyScope, Boolean isEdit, 
2878                         UUID requestID,String riskLevel, String riskType, String guard, String ttlDate) {
2879                 
2880                 String response = null;
2881                 String operation = null;
2882                 String oldPolicyName = null;
2883                 
2884                 if (isEdit){
2885                         operation = "update";
2886                         if (policyName.endsWith("_Draft")) {
2887                                 oldPolicyName = policyName + "_Draft.1";
2888                         }
2889                 } else {
2890                         operation = "create";
2891                 }
2892                 
2893                 boolean levelCheck = isNumeric(riskLevel);
2894                 
2895                 // get values and attributes from the JsonObject
2896                 String ecompName = configBody.get("ecompname").toString().replace("\"", "");
2897                 String jsonBody = configBody.toString();
2898
2899                 
2900                 if (policyName==null||policyName.equalsIgnoreCase("")){
2901                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2902                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2903                 } else if (ecompName==null||ecompName.equals("")){
2904                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.");
2905                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.";
2906                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2907                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2908                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2909                 } else if (!levelCheck){
2910                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2911                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2912                 } else {
2913                         
2914
2915                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_Fault", policyName, policyDescription, ecompName, 
2916                                         jsonBody, false, oldPolicyName, null, isEdit, policyScope, 0, riskLevel, riskType, guard, ttlDate); 
2917
2918                         //send JSON object to PAP
2919                         try {
2920                                 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigClosedLoop");
2921                         } catch (Exception e) {
2922                                 // TODO Auto-generated catch block
2923                                 e.printStackTrace();
2924                         }
2925                 }
2926
2927                 return response;
2928                 
2929         }
2930         
2931         private String createUpdateClosedLoopPmPolicy(String policyName, JsonObject configBody, String policyDescription, String policyScope, Boolean isEdit, 
2932                         UUID requestID, String riskLevel, String riskType, String guard, String ttlDate) {
2933                 
2934                 String response = null;
2935                 String operation = null;
2936                 String oldPolicyName = null;
2937                 
2938                 if (isEdit){
2939                         operation = "update";
2940                 } else {
2941                         operation = "create";
2942                 }
2943                 
2944                 boolean levelCheck = isNumeric(riskLevel);
2945                 
2946                 // get values and attributes from the JsonObject
2947                 String ecompName = configBody.get("ecompname").toString().replace("\"", "");
2948                 String serviceType = configBody.get("serviceTypePolicyName").toString().replace("\"", "");
2949                 String jsonBody = configBody.toString();
2950
2951                 
2952                 if (policyName==null||policyName.equalsIgnoreCase("")){
2953                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2954                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2955                 } else if (ecompName==null||ecompName.equals("")){
2956                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.");
2957                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.";
2958                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2959                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2960                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2961                 } else if (!levelCheck){
2962                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2963                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2964                 } else {
2965                         
2966
2967                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_PM", policyName, policyDescription, ecompName, 
2968                                         jsonBody, false, oldPolicyName, serviceType, isEdit, policyScope, 0, riskLevel, riskType, guard, ttlDate); 
2969
2970                         //send JSON object to PAP
2971                         try {
2972                                 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigClosedLoop");
2973                         } catch (Exception e) {
2974                                 // TODO Auto-generated catch block
2975                                 e.printStackTrace();
2976                         }
2977                 }
2978
2979                 return response;
2980                 
2981         }
2982         
2983         public Boolean validateNONASCIICharactersAndAllowSpaces(Object json){
2984                 Boolean isValidForm = false;
2985                 if (json instanceof String) {
2986                         String jsonString = (String)json;
2987                         if (jsonString.isEmpty()) {
2988                                 logger.info("JSON String is empty so cannot validate NON ACSII Characters.");
2989                         } else {
2990                                 if(CharMatcher.ASCII.matchesAllOf((CharSequence) jsonString)){
2991                                         logger.info("The Value does not contain ASCII Characters");
2992                                          isValidForm = true;
2993                                 }else{
2994                                         logger.error("The Value Contains Non ASCII Characters");
2995                                         isValidForm = false;
2996                                 }       
2997                         }
2998                 } else if (json instanceof JsonObject) {
2999                         JsonObject jsonObj = (JsonObject)json;
3000                         if (jsonObj.isEmpty()){
3001                                 logger.info("JSON object is empty so cannot validate NON ACSII Characters.");
3002                         } else {
3003                                 if(CharMatcher.ASCII.matchesAllOf((CharSequence) jsonObj.toString())){
3004                                         logger.info("The Value does not contain ASCII Characters");
3005                                          isValidForm = true;
3006                                 }else{
3007                                         logger.error("The Value Contains Non ASCII Characters");
3008                                         isValidForm = false;
3009                                 }       
3010                         }
3011                         
3012                 }
3013                 
3014                 return isValidForm;
3015         }
3016         
3017         private String createUpdateMicroServicesPolicy(String policyName, JsonObject microServiceAttributes, String ecompName, String policyScope, Boolean isEdit, UUID requestID,
3018                         String riskLevel, String riskType, String guard, String ttlDate) {
3019                 
3020                 String response = null;
3021                 String operation = null;
3022                 
3023                 if (isEdit){
3024                         operation = "update";
3025                 } else {
3026                         operation = "create";
3027                 }
3028                 
3029                 boolean levelCheck = isNumeric(riskLevel);
3030                 
3031                 // get values and attributes from the JsonObject
3032                 String microService = microServiceAttributes.get("service").toString().replace("\"", "");
3033                 String uuid = microServiceAttributes.get("uuid").toString().replace("\"", "");
3034                 String msLocation = microServiceAttributes.get("location").toString().replace("\"", "");;
3035                 String policyDescription = microServiceAttributes.get("description").toString().replace("\"", "");
3036                 String configName = microServiceAttributes.get("configName").toString().replace("\"", "");
3037                 String priority = microServiceAttributes.get("priority").toString().replace("\"", "");
3038                 String version = microServiceAttributes.get("version").toString().replace("\"", "");
3039
3040                 
3041                 if (policyName==null||policyName.equalsIgnoreCase("")){
3042                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
3043                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
3044                 } else if (ecompName==null||ecompName.equals("")){
3045                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.");
3046                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.";
3047                 } else if (configName==null||configName.equalsIgnoreCase("")){
3048                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Configuration Name given.");
3049                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Configuration Name given.";
3050                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
3051                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
3052                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
3053                 } else if (!levelCheck){
3054                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
3055                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
3056                 } else {
3057                         
3058
3059                         StdPAPPolicy newPAPPolicy = new StdPAPPolicy("DCAE Micro Service", policyName, policyDescription, ecompName, 
3060                                                         configName, microService, uuid, msLocation, microServiceAttributes.toString(), priority, 
3061                                                         version, isEdit, policyScope, 0, riskLevel, riskType, guard, ttlDate); 
3062
3063                         //send JSON object to PAP
3064                         try {
3065                                 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigMS");
3066                         } catch (Exception e) {
3067                                 // TODO Auto-generated catch block
3068                                 e.printStackTrace();
3069                         }
3070                 }
3071
3072                 return response;
3073                 
3074         }
3075         
3076         
3077         /*
3078          * Push a policy to the PDP API implementation
3079          */
3080         public String pushPolicy(String policyScope, String policyName, String policyType, String pdpGroup, UUID requestID) throws Exception {
3081                 return pushPolicy(policyScope, policyName, policyType, pdpGroup, requestID, userName, pass);
3082         }
3083         
3084         public String pushPolicy(String policyScope, String policyName, String policyType, String pdpGroup, UUID requestID, String userID, String passcode) throws Exception {
3085                 String resource= "pushPolicy";
3086                 if(!checkPermissions(userID, passcode, resource)){
3087                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
3088                         return (XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
3089                 }
3090                 String response = null;
3091                 String filePrefix = null;
3092                 String clientScope = null;
3093                 String activeVersion = null;
3094                 
3095                 //get the client scope based policy type
3096                 if (policyType.equalsIgnoreCase("Firewall")){
3097                         clientScope = "ConfigFirewall";
3098                         filePrefix = "Config_FW_";
3099                 } else if (policyType.equalsIgnoreCase("Action")) {
3100                         clientScope = "Action";
3101                         filePrefix = "Action_";
3102                 } else if (policyType.equalsIgnoreCase("Decision")){
3103                         clientScope = "Decision";
3104                         filePrefix = "Decision_";
3105                 } else if (policyType.equalsIgnoreCase("Base")){
3106                         clientScope = "Config";
3107                         filePrefix = "Config_";
3108                 } else if (policyType.equalsIgnoreCase("ClosedLoop_Fault")){
3109                         clientScope = "ConfigClosedLoop";
3110                         filePrefix = "Config_Fault_";
3111                 } else if (policyType.equalsIgnoreCase("ClosedLoop_PM")){
3112                         clientScope = "ConfigClosedLoop";
3113                         filePrefix = "Config_PM_";
3114                 } else if (policyType.equalsIgnoreCase("MicroService")) {
3115                         clientScope = "ConfigMS";
3116                         filePrefix = "Config_MS_";
3117                 }else if (policyType.equalsIgnoreCase("BRMS_RAW")){
3118                         clientScope = "ConfigBrmsRaw";
3119                         filePrefix = "Config_BRMS_Raw_";
3120                 } else if (policyType.equalsIgnoreCase("BRMS_PARAM")){
3121                         clientScope = "ConfigBrmsParam";
3122                         filePrefix = "Config_BRMS_Param_";
3123                 } else {
3124                         clientScope = null;
3125                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + " is not a valid Policy Type.");
3126                         return XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + " is not a valid Policy Type.";
3127                 }
3128                 
3129                 logger.debug("clientScope is " + clientScope);
3130                 logger.debug("filePrefix is " + filePrefix);
3131                 
3132                 if (pdpGroup == null) {
3133                         pdpGroup = "default";
3134                 }
3135                 
3136                 if (policyName==null||policyName.equalsIgnoreCase("")){
3137                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
3138                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
3139                 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
3140                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
3141                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
3142                 } else if (policyType==null||policyType.equalsIgnoreCase("")){
3143                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Type given.");
3144                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Type given.";
3145                 } else {
3146                         // requestID null check. 
3147                         if(requestID==null){
3148                                 requestID =  UUID.randomUUID();
3149                                 logger.debug("Request ID not provided.  Generating request ID " + requestID.toString());
3150                         }
3151
3152                         // change call to getActiveVersion to pass requestID for PAP to receive on the GET process so PAP won't generate another 
3153         //              activeVersion = getActiveVersion(policyScope, filePrefix, policyName, clientScope);
3154                         activeVersion = getActiveVersion(policyScope, filePrefix, policyName, clientScope, requestID);
3155                         logger.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is " + activeVersion);
3156                         
3157                         String id = null;
3158                         if (activeVersion.equalsIgnoreCase("pe100")) {
3159                                 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! "
3160                                                 + "\n Contact Administrator for this Scope. ");
3161                                 return XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! "
3162                                                 + "Contact Administrator for this Scope. ";
3163                                                 
3164                         } else if (activeVersion.equalsIgnoreCase("pe300")) {
3165                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404.  "
3166                                                 + "This indicates a problem with getting the version from the PAP or the policy does not exist.");
3167                                 return XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404.  "
3168                                                 + "This indicates a problem with getting the version from the PAP or the policy does not exist.";
3169                         }
3170                         
3171                         
3172                         if (!activeVersion.equalsIgnoreCase("0")) {
3173                                 id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml";
3174                                 logger.debug("The policyId is " + id);
3175                         } else {
3176                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy.  "
3177                                                 + "This indicates the policy does not exist, please verify the policy exists.");
3178                                 return XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. could not retrieve the activeVersion for this policy.  "
3179                                                 + "This indicates the policy does not exist, please verify the policy exists.";
3180                         }
3181
3182                         // change call to getgitPath to pass requestID for PAP to receive on the GET process so PAP won't generate another 
3183                         // String gitPath = getGitPath(policyScope, filePrefix, policyName, activeVersion, clientScope);
3184                         String gitPath = getGitPath(policyScope, filePrefix, policyName, activeVersion, clientScope, requestID);
3185                         logger.debug("Full gitPath policy xml file: " + gitPath);
3186
3187                         // change call to getSelectedURI to pass requestID for PAP to receive on the GET process so PAP won't generate another 
3188                         // URI selectedURI = getSelectedURI(gitPath, clientScope);
3189                         URI selectedURI = getSelectedURI(gitPath, clientScope, requestID);
3190                         
3191                         logger.debug("The selectedURI is : " + selectedURI.toString());
3192                         String name = filePrefix+policyName;
3193                                         
3194                         StdPDPPolicy selectedPolicy = new StdPDPPolicy(id, true, name, selectedURI, isValid, policyId, description, pushVersion);
3195                         
3196                         logger.debug("StdPDPPolicy object contains: " + selectedPolicy.getId() + ", " + selectedPolicy.getName() + ", " + selectedPolicy.getLocation().toString());
3197                         
3198                         response = copyPolicy(selectedPolicy, pdpGroup, clientScope, requestID);
3199                         
3200                         logger.debug("copyPolicy response:  " + response);
3201                         
3202                         if(response.contains("successfully")){
3203                                 response = (String) callPAP(selectedPolicy, new String[]{"groupId=" + pdpGroup, "policyId="+id, "apiflag=addPolicyToGroup", "operation=PUT"}, requestID, clientScope);
3204                         }
3205                         
3206                         logger.debug("Final API response: " + response);
3207                 }
3208                 
3209                 return response;
3210                 
3211         }
3212         
3213         private String deletePolicyFromPAP(DeletePolicyParameters parameters) {
3214                 String response = null;
3215                 String clientScope = null;
3216                 String pdpGroup = parameters.getPdpGroup();
3217                 
3218                 if (pdpGroup==null){
3219                         pdpGroup="NA";
3220                 }
3221                 
3222                 //get the client scope based policy type
3223                 if (parameters.getPolicyName().contains("Config_FW")){
3224                         clientScope = "ConfigFirewall";
3225                 } else if (parameters.getPolicyName().contains("Action")) {
3226                         clientScope = "Action";
3227                 } else if (parameters.getPolicyName().contains("Decision")){
3228                         clientScope = "Decision";
3229                 } else if (parameters.getPolicyName().contains("Config_Fault")){
3230                         clientScope = "ConfigClosedLoop";
3231                 } else if (parameters.getPolicyName().contains("Config_PM")){
3232                         clientScope = "ConfigClosedLoop";
3233                 } else if (parameters.getPolicyName().contains("Config_MS")){
3234                         clientScope = "ConfigMS";
3235                 } else if (parameters.getPolicyName().contains("Config_BRMS_Raw")){
3236                         clientScope = "ConfigBrmsRaw";
3237                 } else if (parameters.getPolicyName().contains("Config_BRMS_Param")){
3238                         clientScope = "ConfigBrmsParam";
3239                 } else {
3240                         clientScope = "Config";
3241                 }
3242                 
3243                 logger.debug("clientScope is " + clientScope);
3244                 
3245                 if (clientScope==null||clientScope.equals("")){
3246                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + parameters.getPolicyName() + " is not a valid Policy Name.");
3247                         return XACMLErrorConstants.ERROR_DATA_ISSUE + parameters.getPolicyName() + " is not a valid Policy Name.";
3248                 }
3249                 
3250                 if (parameters.getPolicyName()==null||parameters.getPolicyName().equalsIgnoreCase("")){
3251                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
3252                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
3253                 } else if (parameters.getDeleteCondition()==null||parameters.getDeleteCondition().equals("")){
3254                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given.");
3255                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given.";
3256                 } else {
3257                         
3258                         StdPAPPolicy deletePapPolicy = new StdPAPPolicy(parameters.getPolicyName(), parameters.getDeleteCondition().toString()); 
3259
3260                         //send JSON object to PAP
3261                         try {
3262                                 response = (String) callPAP(deletePapPolicy, new String[] {"groupId="+pdpGroup, "apiflag=deletePapApi", "operation=delete" }, parameters.getRequestID(), clientScope);
3263                         } catch (Exception e) {
3264                                 // TODO Auto-generated catch block
3265                                 e.printStackTrace();
3266                         }               
3267                         
3268                 }
3269                 
3270                 return response;
3271         }
3272         
3273         private String deletePolicyFromPDP(DeletePolicyParameters parameters) {
3274                 String response = null;
3275                 String clientScope = null;
3276                 String pdpGroup = parameters.getPdpGroup();
3277                 
3278                 if (pdpGroup==null){
3279                         pdpGroup="NA";
3280                 }
3281                 
3282                 //get the client scope based policy type
3283                 if (parameters.getPolicyName().contains("Config_FW")){
3284                         clientScope = "ConfigFirewall";
3285                 } else if (parameters.getPolicyName().contains("Action")) {
3286                         clientScope = "Action";
3287                 } else if (parameters.getPolicyName().contains("Decision")){
3288                         clientScope = "Decision";
3289                 } else if (parameters.getPolicyName().contains("Config_Fault")){
3290                         clientScope = "ConfigClosedLoop";
3291                 } else if (parameters.getPolicyName().contains("Config_PM")){
3292                         clientScope = "ConfigClosedLoop";
3293                 } else if (parameters.getPolicyName().contains("Config_MS")){
3294                         clientScope = "ConfigMS";
3295                 }else if (parameters.getPolicyName().contains("Config_BRMS_Raw")){
3296                         clientScope = "ConfigBrmsRaw";
3297                 } else if (parameters.getPolicyName().contains("Config_BRMS_Param")){
3298                         clientScope = "ConfigBrmsParam";
3299                 } else {
3300                         clientScope = "Config";
3301                 }
3302                 
3303                 logger.debug("clientScope is " + clientScope);
3304                 
3305                 if (clientScope==null||clientScope.equals("")){
3306                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + parameters.getPolicyName() + " is not a valid Policy Name.");
3307                         return XACMLErrorConstants.ERROR_DATA_ISSUE + parameters.getPolicyName() + " is not a valid Policy Name.";
3308                 }
3309                 
3310                 if (parameters.getPolicyName()==null||parameters.getPolicyName().equalsIgnoreCase("")){
3311                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
3312                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
3313                 } else if (parameters.getPdpGroup()==null||parameters.getPdpGroup().equals("")){
3314                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given.");
3315                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given.";
3316                 } else {
3317                         
3318                         //send JSON object to PAP
3319                         try {
3320                                 response = (String) callPAP(null, new String[] {"policyName="+parameters.getPolicyName(), "groupId="+pdpGroup, "apiflag=deletePdpApi", "operation=delete" }, parameters.getRequestID(), clientScope);
3321                         } catch (Exception e) {
3322                                 // TODO Auto-generated catch block
3323                                 e.printStackTrace();
3324                         }               
3325                         
3326                 }
3327                 
3328                 return response;
3329         }
3330         
3331         /*
3332          * Copy a single Policy file from the input stream to the PAP Servlet.
3333          * Either this works (silently) or it throws an exception.
3334          * 
3335          */
3336         public String copyFile(String policyId, String group, StdPAPPolicy location, String clientScope, UUID requestID) throws PAPException {
3337                 String response = null;
3338                 //String clientScope = null;
3339                 
3340                 // send the policy file to the PAP Servlet
3341                 try {
3342                         response = (String) callPAP(location, new String[] {"groupId=" + group, "policyId="+policyId, "apiflag=api", "operation=post"}, requestID, clientScope);
3343                 } catch (Exception e) {
3344                         String message = "Unable to PUT policy '" + policyId + "', e:" + e;
3345                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
3346                         throw new PAPException(message);
3347                 }
3348                 
3349                 return response;
3350         }
3351         
3352         public String copyPolicy(PDPPolicy policy, String group, String policyType, UUID requestID) throws PAPException {
3353                 String response = null;
3354                 
3355                 if (policy == null || group == null) {
3356                         throw new PAPException("Null input policy="+policy+"  group="+group);
3357                 }
3358                 try {
3359                         StdPAPPolicy location = new StdPAPPolicy(policy.getLocation());
3360                         response = copyFile(policy.getId(), group, location, policyType, requestID);
3361                 } catch (Exception e) {
3362                         String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
3363                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
3364                         throw new PAPException(message);
3365                 }
3366                 
3367                 return response;
3368         }
3369
3370         public Object callPAP(Object content, String[] parameters, UUID requestID, String clientScope) throws Exception {
3371                 String response = null;
3372                 HttpURLConnection connection = null;
3373                 String requestMethod = null;
3374                 String operation = null;
3375                 responseCode = 0; 
3376                 // Checking for the available PDPs is done during the first Request and the List is going to have the connected PDP as first element.
3377                 // This makes it Real-Time to change the list depending on their availability.
3378                 if (paps == null || paps.isEmpty()) {
3379                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
3380                 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
3381                 }else {
3382                         int papsCount = 0;
3383                         boolean connected = false;
3384                         while (papsCount < paps.size()) {
3385                                 try {
3386                                         String fullURL = paps.get(0);
3387                                         if (parameters != null && parameters.length > 0) {
3388                                                 String queryString = "";
3389                                                 for (String p : parameters) {
3390                                                         queryString += "&" + p;
3391                                                         if (p.equalsIgnoreCase("operation=post")){
3392                                                                 requestMethod = "POST";
3393                                                         } else if (p.equalsIgnoreCase("operation=delete")){
3394                                                                 requestMethod = "DELETE";
3395                                                                 operation = "delete";
3396                                                         } else {
3397                                                                 requestMethod = "PUT";
3398                                                                 if (p.equalsIgnoreCase("operation=create")){
3399                                                                         operation = "create";
3400                                                                 } else if (p.equalsIgnoreCase("operation=update")){
3401                                                                         operation = "update";
3402                                                                 } else if (p.equalsIgnoreCase("operation=createDictionary")){
3403                                                                         operation = "createDictionary";
3404                                                                 }
3405                                                         }
3406                                                 }
3407                                                 fullURL += "?" + queryString.substring(1);
3408                                         }
3409         
3410                                         URL url = new URL (fullURL);
3411                                         
3412                                         //Open the connection
3413                                         connection = (HttpURLConnection)url.openConnection();
3414                                         
3415                                         // Setting Content-Type
3416                                         connection.setRequestProperty("Content-Type",
3417                                                         "application/json");
3418                                         
3419                                         // Adding Authorization
3420                                         connection.setRequestProperty("Authorization", "Basic "
3421                                                         + encodingPAP.get(0));
3422                                         
3423                                         connection.setRequestProperty("Environment", environment);
3424                                         connection.setRequestProperty("ClientScope", clientScope);
3425                                         
3426                                         //set the method and headers
3427                                         connection.setRequestMethod(requestMethod);
3428                                         connection.setUseCaches(false);
3429                                         connection.setInstanceFollowRedirects(false);
3430                                         connection.setDoOutput(true);
3431                                         connection.setDoInput(true);
3432                                         // Adding RequestID
3433                                         if (requestID == null) {
3434                                                 requestID = UUID.randomUUID();
3435                                                 logger.info("No request ID provided, sending generated ID: " + requestID.toString());
3436                                         } else {
3437                                                 logger.info("Using provided request ID: " + requestID.toString());
3438                                         }
3439                                         connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
3440
3441                                         if (content != null) {
3442                                                 if (content instanceof InputStream) {
3443                                                         try {
3444                                                                 //send  current configuration
3445                                                                 try (OutputStream os = connection.getOutputStream()) {
3446                                                                         int count = IOUtils.copy((InputStream)content, os);
3447                                                                         if (logger.isDebugEnabled()) {
3448                                                                                 logger.debug("copied to output, bytes=" + count);
3449                                                                         }
3450                                                                 }
3451                                                         } catch (Exception e) {
3452                                                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to write content in 'PUT'", e);
3453                                                                 throw e;
3454                                                         }
3455                                                 } else {
3456                                                         // the content is an object to be encoded in JSON
3457                                                         ObjectMapper mapper = new ObjectMapper();
3458                                                         if(!junit){
3459                                                                 mapper.writeValue(connection.getOutputStream(), content);
3460                                                         }
3461                                                 }
3462                                         }
3463         
3464                                         //DO the connect
3465                                         connection.connect();
3466                                         responseCode = connection.getResponseCode();
3467                                         // If Connected to PAP then break from the loop and continue with the Request 
3468                                         if (connection.getResponseCode() > 0 || junit) {
3469                                                 connected = true;
3470                                                 break;
3471
3472                                         } else {
3473                                                 logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
3474                                         }
3475                                 } catch (Exception e) {
3476                                         // This means that the PAP is not working 
3477                                         if (junit) {
3478                                                 connected = true;
3479                                                 break;
3480                                         }
3481                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
3482                                 }
3483                                 papsCount++;
3484                         }
3485         
3486                         if (connected) {
3487                                 //Read the Response
3488                                 logger.debug("connected to the PAP : " + paps.get(0));
3489                                 logger.debug("--- Response: ---");
3490                                 Map<String, List<String>> headers = connection.getHeaderFields();
3491                                 for (String key : headers.keySet()) {
3492                                         logger.debug("Header :" + key + "  Value: " + headers.get(key));
3493                                 }
3494                                 try {
3495                                         if (responseCode == 200 || junit) {
3496                                                 
3497                                                 // Check for successful creation of policy
3498                                                 String isSuccess = null;
3499                                                 if(!junit){ //is this a junit test?
3500                                                         isSuccess = connection.getHeaderField("successMapKey");
3501                                                         operation = connection.getHeaderField("operation");
3502                                                 } else {
3503                                                         isSuccess = "success";
3504                                                 }
3505                                                 
3506                                                 if (isSuccess.equals("success")) {
3507                                                         if (operation.equals("update")) {
3508                                                                 logger.info("Transaction ID: " + requestID + " --Policy Updated Successfully!" );
3509                                                                 response = "Transaction ID: " + requestID + " --Policy with the name " + connection.getHeaderField("policyName") + " was successfully updated.";
3510                                                         } else if (operation.equals("delete")) {
3511                                                                 logger.info("Transaction ID: " + requestID + " --Policy Deleted Successfully!");
3512                                                                 response = "Transaction ID: " + requestID + " --The policy was successfully deleted.";    
3513                                                         } else if (operation.equals("import")) {
3514                                                                 logger.info("Transaction ID: " + requestID + " --Policy Engine Import Successful!");
3515                                                                 response = "Transaction ID: " + requestID + " --The policy engine import for " + connection.getHeaderField("service") +  " was successfull.";    
3516                                                         }else {
3517                                                                 logger.info("Transaction ID: " + requestID + " --Policy Created Successfully!" );
3518                                                                 response = "Transaction ID: " + requestID + " --Policy with the name " + connection.getHeaderField("policyName") + " was successfully created.";
3519                                                         }
3520                                                                         
3521                                                 } else {
3522                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to Create/Update the Policy!");
3523                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to Create/Update the Policy!";
3524                                                 }
3525                                         } else if (connection.getResponseCode() == 202) {
3526                                                 if (connection.getHeaderField("operation")!=null && connection.getHeaderField("operation").equalsIgnoreCase("delete")){
3527                                                         if (connection.getHeaderField("lockdown")!=null && connection.getHeaderField("lockdown").equals("true")){
3528                                                                 logger.warn("Transaction ID: " + requestID + "Policies are locked down.");
3529                                                                 response = "Transaction ID: " + requestID + " --Policies are locked down, please try again later.";
3530                                                         }
3531                                                 }
3532                                         } else if (connection.getResponseCode() == 204) {
3533                                                 if (connection.getHeaderField("operation")!=null && connection.getHeaderField("operation").equals("push")){
3534                                                         logger.info("Transaction ID: " + requestID + " --Policy '" + connection.getHeaderField("policyId") +
3535                                                                         "' was successfully pushed to the PDP group '" + connection.getHeaderField("groupId") + "'.");
3536                                                         response = "Transaction ID: " + requestID + " --Policy '" + connection.getHeaderField("policyId") +
3537                                                                         "' was successfully pushed to the PDP group '" + connection.getHeaderField("groupId") + "'.";
3538                                                 }
3539                                         } else if (connection.getResponseCode() == 400 && connection.getHeaderField("error")!=null){
3540                                                 if (connection.getHeaderField("error").equals("noPolicyExist")) {
3541                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.");
3542                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
3543                                                 } else if (connection.getHeaderField("error").equals("invalidPolicyName")) {
3544                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
3545                                         + "policyName must be the full name of the file to be deleted including version and extension");
3546                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
3547                                                                 + "policyName must be the full name of the file to be deleted including version and extension";
3548                                                 } else if (connection.getHeaderField("error").equals("actionPolicyDB")){
3549                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + connection.getHeaderField("actionAttribute") + " in the ActionPolicyDict table.");
3550                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid actionAttribute given.";
3551                                                 } else if (connection.getHeaderField("error").equals("serviceModelDB")){
3552                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Service or Version.  The Service Model, " 
3553                                                                         + connection.getHeaderField("modelName") + " of version " + connection.getHeaderField("modelVersion") 
3554                                                                         + " was not found in the dictionary.");
3555                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Service or Version.  The Service Model, " 
3556                                                                         + connection.getHeaderField("modelName") + " of version " + connection.getHeaderField("modelVersion") 
3557                                                                         + " was not found in the dictionary.";
3558                                                 } else if (connection.getHeaderField("error").equals("FWDBError")){
3559                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error when inserting Firewall ConfigBody data into database.");
3560                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error when inserting Firewall ConfigBody data into the database.";
3561                                                 } else if (connection.getHeaderField("error").equals("savePolicy")){
3562                                                         logger.error(connection.getHeaderField("message"));
3563                                                         response = connection.getHeaderField("message");
3564                                                 }
3565                                         } else if (connection.getResponseCode() == 403) {
3566                                                 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " 
3567                                                                         + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ");
3568                                                 response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " 
3569                                                                 + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. "; 
3570                                         } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error")!=null) {
3571                                                 if (connection.getHeaderField("error").equals("unknownGroupId")){
3572                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message"));
3573                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message") +  
3574                                                                         " Please check the pdpGroup you are requesting to move the policy to.";
3575                                                 }
3576                                         } else if (connection.getResponseCode() == 409 && connection.getHeaderField("error")!=null) {
3577                                                 if (connection.getHeaderField("error").equals("modelExistsDB")) {
3578                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Import Value Exist Error");
3579                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Import Value Exist Error:  The import value "+connection.getHeaderField("service")+" already exist on the PAP. "
3580                                                                         + "Please create a new import value.";
3581                                                 }else if (connection.getHeaderField("error").equals("policyExists")){
3582                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Exist Error");
3583                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Exist Error:  The Policy "+connection.getHeaderField("policyName")+" already exist on the PAP. "
3584                                                                         + "Please create a new policy or use the update API to modify the existing one.";
3585                                                 }
3586                                         } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error")!=null) {
3587                                                 if (connection.getHeaderField("error").equals("jpautils")){
3588                                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Could not create JPAUtils instance on the PAP");
3589                                                         response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Could not create JPAUtils instance on the PAP";
3590                                                 } else if (connection.getHeaderField("error").equals("deleteDB")){
3591                                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to delete Policy from database.");
3592                                                         response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to delete Policy from database.";
3593                                                 } else if (connection.getHeaderField("error").equals("deleteFile")){
3594                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file.");
3595                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file";
3596                                                 } else if (connection.getHeaderField("error").equals("groupUpdate")){
3597                                                         logger.error(connection.getHeaderField("message"));
3598                                                         response = connection.getHeaderField("message");
3599                                                 }else if (connection.getHeaderField("error").equals("unknown")){
3600                                                         logger.error(XACMLErrorConstants.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason.  Check the file system and other logs for further information.");
3601                                                         response = XACMLErrorConstants.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason.  Check the file system and other logs for further information.";
3602                                                 } else if (connection.getHeaderField("error").equals("deleteConfig")){
3603                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the configuration or action body file in specified location");
3604                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the configuration or action body file in specified location.";
3605                                                 }else if (connection.getHeaderField("error").equals("missing")){
3606                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to create value in database because service does match a value in file");
3607                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to create value in database because service does match a value in file";
3608                                                 }else if (connection.getHeaderField("error").equals("importDB")){
3609                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Database errors during policy engine import");
3610                                                         response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Database errors during policy engine import";
3611                                                 }else if (connection.getHeaderField("error").equals("policyCopyError")){
3612                                                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + connection.getHeaderField("message"));
3613                                                         response = XACMLErrorConstants.ERROR_PROCESS_FLOW + connection.getHeaderField("message");
3614                                                 }else if (connection.getHeaderField("error").equals("addGroupError")){
3615                                                         logger.error(connection.getHeaderField("message"));
3616                                                         response = connection.getHeaderField("message");
3617                                                 }else if (connection.getHeaderField("error").equals("error")){
3618                                                         logger.error(XACMLErrorConstants.ERROR_UNKNOWN + "Could not create or update the policy for and unknown reason");
3619                                                         response = XACMLErrorConstants.ERROR_UNKNOWN + "Could not create or update the policy for and unknown reason";
3620                                                 }
3621                                         } else {
3622                                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST:  Error occured while attempting perform this operation.. the request may be incorrect.");
3623                                                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST:  Error occured while attempting perform this operation.. the request may be incorrect.";
3624                                         }
3625                                 } catch (IOException e) {
3626                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
3627                                         response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + e;
3628                                         throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"ERROR in connecting to the PAP ", e);
3629                                 } 
3630                                 
3631                                 if (junit){
3632                                         response = "success";
3633                                 }
3634                                 return response;
3635         
3636                         } else {
3637                                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps;
3638                                 return response;
3639                         }       
3640                 }
3641         
3642         }
3643         
3644         // change getSelectedURI method to receive requestID to be used to send to PAP on the GET request so PAP won't generate another
3645         // private URI getSelectedURI(String gitPath, String clientScope){
3646         private URI getSelectedURI(String gitPath, String clientScope, UUID requestID){
3647                 //Connect to the PAP
3648                 URI selectedURI = null;
3649                 HttpURLConnection connection = null;
3650                 String [] parameters = {"apiflag=uri", "gitPath="+gitPath};
3651
3652
3653                 // Checking for the available PDPs is done during the first Request and the List is going to have the connected PDP as first element.
3654                 // This makes it Real-Time to change the list depending on their availability.
3655                 if (paps == null || paps.isEmpty()) {
3656                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
3657                 try {
3658                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
3659                 } catch (Exception e) {
3660                         logger.error(e.getMessage());
3661                 }
3662                 }else {
3663                         int papsCount = 0;
3664                         boolean connected = false;
3665                         while (papsCount < paps.size()) {
3666                                 try {
3667                                         String fullURL = paps.get(0);
3668                                         if (parameters != null && parameters.length > 0) {
3669                                                 String queryString = "";
3670                                                 for (String p : parameters) {
3671                                                         queryString += "&" + p;
3672                                                 }
3673                                                 fullURL += "?" + queryString.substring(1);
3674                                         }
3675         
3676                                         URL url = new URL (fullURL);
3677                                         
3678                                         //Open the connection
3679                                         connection = (HttpURLConnection)url.openConnection();
3680                                         
3681                                         // Setting Content-Type
3682                                         connection.setRequestProperty("Content-Type",
3683                                                         "application/json");
3684                                         
3685                                         // Adding Authorization
3686                                         connection.setRequestProperty("Authorization", "Basic "
3687                                                         + encodingPAP.get(0));
3688                                         
3689                                         connection.setRequestProperty("Environment", environment);
3690                                         connection.setRequestProperty("ClientScope", clientScope);
3691                                         
3692                                         //set the method and headers
3693                                         connection.setRequestMethod("GET");
3694                                         connection.setUseCaches(false);
3695                                         connection.setInstanceFollowRedirects(false);
3696                                         connection.setDoOutput(true);
3697                                         connection.setDoInput(true);
3698
3699                                         // set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
3700                                         connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
3701         
3702                                         //DO the connect
3703                                         connection.connect();
3704                                         responseCode = connection.getResponseCode();
3705                                         // If Connected to PAP then break from the loop and continue with the Request 
3706                                         if (connection.getResponseCode() > 0) {
3707                                                 connected = true;
3708                                                 break;
3709
3710                                         } else {
3711                                                 logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
3712                                         }
3713                                 } catch (Exception e) {
3714                                         // This means that the PAP is not working 
3715                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
3716                                 }
3717                                 papsCount++;
3718                         }
3719         
3720                         if (connected) {
3721                                 //Read the Response
3722                                 logger.debug("connected to the PAP : " + paps.get(0));
3723                                 logger.debug("--- Response: ---");
3724                                 Map<String, List<String>> headers = connection.getHeaderFields();
3725                                 for (String key : headers.keySet()) {
3726                                         logger.debug("Header :" + key + "  Value: " + headers.get(key));
3727                                 }
3728                                 try {
3729                                         if (connection.getResponseCode() == 200) {
3730                                                 // Check for successful creation of policy
3731                                                 String uri = connection.getHeaderField("selectedURI");
3732                                                 logger.debug("URI from Header: " + uri);
3733                                                 if (uri != null && !uri.equalsIgnoreCase("")) {
3734                                                         selectedURI = URI.create(uri);
3735                                                         return selectedURI;
3736                                                 } else {
3737                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
3738                                                 }
3739                                         } else if (connection.getResponseCode() == 404) {
3740                                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is " 
3741                                                                         + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP");
3742                                         } else {
3743                                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST:  Error occured while getting the gitPath from the PAP. The request may be incorrect.");
3744                                         }
3745                                 } catch (IOException e) {
3746                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
3747                                         try {
3748                                                 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
3749                                         } catch (Exception e1) {
3750                                                 logger.error(e1.getMessage());
3751                                         }
3752                                 } 
3753         
3754                         } else {
3755                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
3756                                 try {
3757                                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
3758                                 } catch (Exception e) {
3759                                         logger.error(e.getMessage());
3760                                 }
3761                         }       
3762                 }
3763                 return selectedURI;
3764                                                 
3765         }
3766         
3767         // Make a call to the PAP to get the gitPath
3768         // change getGitPath method to receive requestID to be used to send to PAP on the GET request so PAP won't generate another
3769         // private String getGitPath(String policyScope, String filePrefix, String policyName, String activeVersion, String clientScope){
3770         private String getGitPath(String policyScope, String filePrefix, String policyName, String activeVersion, String clientScope, UUID requestID){
3771
3772                 //Connect to the PAP
3773                 String gitPath = null;
3774                 HttpURLConnection connection = null;
3775                 String [] parameters = {"apiflag=gitPath", "policyScope="+policyScope, "filePrefix="+filePrefix, 
3776                                                                         "policyName="+policyName, "activeVersion="+activeVersion};
3777                 
3778
3779                 // Checking for the available PDPs is done during the first Request and the List is going to have the connected PDP as first element.
3780                 // This makes it Real-Time to change the list depending on their availability.
3781                 if (paps == null || paps.isEmpty()) {
3782                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
3783                 try {
3784                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
3785                 } catch (Exception e) {
3786                         logger.error(e.getMessage());
3787                 }
3788                 }else {
3789                         int papsCount = 0;
3790                         boolean connected = false;
3791                         while (papsCount < paps.size()) {
3792                                 try {
3793                                         String fullURL = paps.get(0);
3794                                         if (parameters != null && parameters.length > 0) {
3795                                                 String queryString = "";
3796                                                 for (String p : parameters) {
3797                                                         queryString += "&" + p;
3798                                                 }
3799                                                 fullURL += "?" + queryString.substring(1);
3800                                         }
3801         
3802                                         URL url = new URL (fullURL);
3803                                         
3804                                         //Open the connection
3805                                         connection = (HttpURLConnection)url.openConnection();
3806                                         
3807                                         // Setting Content-Type
3808                                         connection.setRequestProperty("Content-Type",
3809                                                         "application/json");
3810                                         
3811                                         // Adding Authorization
3812                                         connection.setRequestProperty("Authorization", "Basic "
3813                                                         + encodingPAP.get(0));
3814                                         
3815                                         connection.setRequestProperty("Environment", environment);
3816                                         connection.setRequestProperty("ClientScope", clientScope);
3817                                         
3818                                         //set the method and headers
3819                                         connection.setRequestMethod("GET");
3820                                         connection.setUseCaches(false);
3821                                         connection.setInstanceFollowRedirects(false);
3822                                         connection.setDoOutput(true);
3823                                         connection.setDoInput(true);
3824
3825                                         // set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
3826                                         connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
3827         
3828                                         //DO the connect
3829                                         connection.connect();
3830         
3831                                         // If Connected to PAP then break from the loop and continue with the Request 
3832                                         if (connection.getResponseCode() > 0) {
3833                                                 connected = true;
3834                                                 break;
3835
3836                                         } else {
3837                                                 logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
3838                                         }
3839                                 } catch (Exception e) {
3840                                         // This means that the PAP is not working 
3841                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
3842                                 }
3843                                 papsCount++;
3844                         }
3845         
3846                         if (connected) {
3847                                 //Read the Response
3848                                 logger.debug("connected to the PAP : " + paps.get(0));
3849                                 logger.debug("--- Response: ---");
3850                                 Map<String, List<String>> headers = connection.getHeaderFields();
3851                                 for (String key : headers.keySet()) {
3852                                         logger.debug("Header :" + key + "  Value: " + headers.get(key));
3853                                 }
3854                                 try {
3855                                         if (connection.getResponseCode() == 200) {
3856                                                 // Check for successful creation of policy
3857                                                 gitPath = connection.getHeaderField("gitPath");
3858                                                 this.policyId = connection.getHeaderField("policyId");
3859                                                 this.description = connection.getHeaderField("description");
3860                                                 this.pushVersion = connection.getHeaderField("version");
3861                                                 String isValid = connection.getHeaderField("isValid");
3862                                                 this.isValid = Boolean.parseBoolean(isValid);
3863                                                 
3864                                                 logger.debug("GitPath from Header: " + gitPath);
3865                                                 logger.debug("policyId from Header: " + policyId);
3866                                                 logger.debug("description from Header: " + description);
3867                                                 logger.debug("version from Header: " + pushVersion);
3868                                                 logger.debug("isValid from Header: " + isValid);
3869                                                 
3870                                                 if (gitPath != null && !gitPath.equalsIgnoreCase("")) {
3871                                                         return gitPath;
3872                                                 } else {
3873                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
3874                                                 }
3875                                         } else if (connection.getResponseCode() == 404) {
3876                                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is " 
3877                                                                         + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP");
3878                                         } else {
3879                                                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST:  Error occured while getting the gitPath from the PAP. The request may be incorrect.");
3880                                         }
3881                                 } catch (IOException e) {
3882                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
3883                                         try {
3884                                                 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
3885                                         } catch (Exception e1) {
3886                                                 logger.error(e1.getMessage());
3887                                         }
3888                                 } 
3889         
3890                         } else {
3891                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
3892                                 try {
3893                                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
3894                                 } catch (Exception e) {
3895                                         logger.error(e.getMessage());
3896                                 }
3897                         }       
3898                 }
3899                 return gitPath;
3900                                                 
3901         }
3902
3903         // change getActiveVersion method to receive requestID to be used to send to PAP on the GET request so PAP won't generate another
3904 //      private String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope) {
3905         private String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope, UUID requestID) {         
3906
3907                 //Connect to the PAP
3908                 String version = null;
3909                 HttpURLConnection connection = null;
3910                 String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName};
3911                 
3912
3913                 // Checking for the available PDPs is done during the first Request and the List is going to have the connected PDP as first element.
3914                 // This makes it Real-Time to change the list depending on their availability.
3915                 if (paps == null || paps.isEmpty()) {
3916                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
3917                 try {
3918                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
3919                 } catch (Exception e) {
3920                         logger.error(e.getMessage());
3921                 }
3922                 }else {
3923                         int papsCount = 0;
3924                         boolean connected = false;
3925                         while (papsCount < paps.size()) {
3926                                 try {
3927                                         String fullURL = paps.get(0);
3928                                         if (parameters != null && parameters.length > 0) {
3929                                                 String queryString = "";
3930                                                 for (String p : parameters) {
3931                                                         queryString += "&" + p;
3932                                                 }
3933                                                 fullURL += "?" + queryString.substring(1);
3934                                         }
3935         
3936                                         URL url = new URL (fullURL);
3937                                         
3938                                         //Open the connection
3939                                         connection = (HttpURLConnection)url.openConnection();
3940                                         
3941                                         // Setting Content-Type
3942                                         connection.setRequestProperty("Content-Type",
3943                                                         "application/json");
3944                                         
3945                                         // Adding Authorization
3946                                         connection.setRequestProperty("Authorization", "Basic "
3947                                                         + encodingPAP.get(0));
3948                                         
3949                                         connection.setRequestProperty("Environment", environment);
3950                                         connection.setRequestProperty("ClientScope", clientScope);
3951
3952                                         
3953                                         //set the method and headers
3954                                         connection.setRequestMethod("GET");
3955                                         connection.setUseCaches(false);
3956                                         connection.setInstanceFollowRedirects(false);
3957                                         connection.setDoOutput(true);
3958                                         connection.setDoInput(true);
3959
3960                                         // set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
3961                                         connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
3962         
3963                                         //DO the connect
3964                                         connection.connect();
3965         
3966                                         // If Connected to PAP then break from the loop and continue with the Request 
3967                                         if (connection.getResponseCode() > 0) {
3968                                                 connected = true;
3969                                                 break;
3970
3971                                         } else {
3972                                                 logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
3973                                         }
3974                                 } catch (Exception e) {
3975                                         // This means that the PAP is not working 
3976                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
3977                                 }
3978                                 papsCount++;
3979                         }
3980         
3981                         if (connected) {
3982                                 //Read the Response
3983                                 logger.debug("connected to the PAP : " + paps.get(0));
3984                                 logger.debug("--- Response: ---");
3985                                 Map<String, List<String>> headers = connection.getHeaderFields();
3986                                 for (String key : headers.keySet()) {
3987                                         logger.debug("Header :" + key + "  Value: " + headers.get(key));
3988                                 }
3989                                 try {
3990                                         if (connection.getResponseCode() == 200) {
3991                                                 // Check for successful creation of policy
3992                                                 version = connection.getHeaderField("version");
3993                                                 logger.debug("ActiveVersion from the Header: " + version);
3994                                         } else if (connection.getResponseCode() == 403) {
3995                                                 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " 
3996                                                                 + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ");
3997                                                 version = "pe100";
3998                                         } else if (connection.getResponseCode() == 404) {
3999                                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is " 
4000                                                                         + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP");
4001                                                 version = "pe300";
4002                                         } else {
4003                                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST:  Error occured while getting the version from the PAP. The request may be incorrect.");
4004                                         }
4005                                 } catch (IOException e) {
4006                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
4007                                         try {
4008                                                 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
4009                                         } catch (Exception e1) {
4010                                                 logger.error(e1.getMessage());
4011                                         }
4012                                 } 
4013         
4014                         } else {
4015                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
4016                                 try {
4017                                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
4018                                 } catch (Exception e) {
4019                                         logger.error(e.getMessage());
4020                                 }
4021                         }       
4022                 }
4023                 return version;
4024         }
4025         
4026         // Validation for json inputs
4027         public static boolean isJSONValid(String data) {
4028                 try {
4029                         new JSONObject(data);
4030                         InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
4031                         JsonReader jsonReader = Json.createReader(stream);
4032                         logger.debug("Json Value is: " + jsonReader.read().toString() );
4033                 } catch (Exception e) {
4034                         return false;
4035                 }
4036                 return true;
4037         }
4038         
4039         /*
4040          * Rotate the PDP list upon WEBsocket Failures
4041          */
4042         public static void rotateList() {
4043                 Collections.rotate(pdps, -1);
4044                 Collections.rotate(encoding, -1);
4045                 /* not required for 1510. //TODO uncomment when PAP API has been implemented
4046                  * This Broke the PyPDP :( Since there is no PAP LIST yet. 
4047                 Collections.rotate(paps,  -1);
4048                 Collections.rotate(encodingPAP, -1);
4049                 */
4050         }
4051
4052         /*
4053          * Get the latest PDP
4054          */
4055         public static String getPDPURL() {
4056                 return pdps.get(0);
4057         }
4058         
4059         /*
4060          * Get the latest PAP
4061          */
4062         public static String getPAPURL() {
4063                 return paps.get(0);
4064         }
4065         
4066         private JsonObject stringToJsonObject(String value) throws Exception{
4067                 JsonReader jsonReader = Json.createReader(new StringReader(value));
4068                 JsonObject object = jsonReader.readObject();
4069                 jsonReader.close();
4070                 return object;
4071         }
4072         
4073         private String getJsonResponseString() {
4074                 String jsonString = "{\"Response\":[{\"Status\":{\"StatusCode\":{\"Value\":\"urn:oasis:names:tc:xacml:1.0:status:ok\"}},"
4075                                 + "\"AssociatedAdvice\":[{\"AttributeAssignment\":[{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\","
4076                                 + "\"Issuer\":\"\",\"AttributeId\":\"type\",\"Value\":\"Configuration\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},"
4077                                 + "{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"URLID\",\"Value\":"
4078                                 + "\"$URL/Config/JunitTest.Config_testing.1.json\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#anyURI\"},{\"Category\":"
4079                                 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"PolicyName\",\"Value\":"
4080                                 + "\"JunitTest.Config_testing.1.xml\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":"
4081                                 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"VersionNumber\",\"Value\":"
4082                                 + "\"1\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\","
4083                                 + "\"Issuer\":\"\",\"AttributeId\":\"matching:ECOMPName\",\"Value\":\"test\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},"
4084                                 + "{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"matching:ConfigName\","
4085                                 + "\"Value\":\"TestName\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":"
4086                                 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"matching:service\","
4087                                 + "\"Value\":\"ControllerServiceOpendcaeCapsuleServiceInstance\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},"
4088                                 + "{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"matching:uuid\","
4089                                 + "\"Value\":\"TestUUID\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":"
4090                                 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"matching:Location\","
4091                                 + "\"Value\":\"Edge\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":"
4092                                 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"Priority\",\"Value\":\"1\",\"DataType\":"
4093                                 + "\"http://www.w3.org/2001/XMLSchema#string\"}],\"Id\":\"MSID\"}],\"Decision\":\"Permit\"}]}";
4094                 
4095                 return jsonString;
4096         }
4097         
4098         public PolicyChangeResponse policyEngineImport(ImportParameters importParameters) throws Exception {
4099                 return policyEngineImport(importParameters, userName,  pass);
4100         }
4101         
4102         public PolicyChangeResponse policyEngineImport(ImportParameters importParameters, String userID, String passcode) throws Exception {
4103                 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
4104                 String resource= "policyEngineImport";
4105                 if(!checkPermissions(userID, passcode, resource)){
4106                         logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
4107                         response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
4108                         response.setResponseCode(401);
4109                         return response;
4110                 }
4111                 InputStream targetStream = null;
4112                 if(importParameters.getServiceName()!=null && importParameters.getVersion()!=null && importParameters.getServiceType()!=null){
4113                         // This is Config Class Policy. 
4114                         if(importParameters.getFilePath()!=null){
4115                                 File input = new File(importParameters.getFilePath());
4116                                 if (input.getName().endsWith(".xmi") ||  input.getName().endsWith(".zip")){
4117                                     try {
4118                                         if (input.exists()){
4119                                                 targetStream = new FileInputStream(input);
4120                                         }else {
4121                                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "File provided in ImportParameters does not exists.");
4122                                                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "File provided in ImportParameters does not exist.");                
4123                                                         return response;
4124                                         }
4125                                         } catch (Exception e) {
4126                                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error reading in File");
4127                                                 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided");
4128                                         }       
4129                                 }else{
4130                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Data type.");
4131                                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .xmi or .zip.");               
4132                                         return response;
4133                                 }
4134                                 String[] parameters = new String[] {"importService=" + importParameters.getServiceType(), "serviceName=" 
4135                                                 + importParameters.getServiceName(), "fileName=" + input.getName(), "version=" + importParameters.getVersion()};
4136                                 String responseMessage =  (String) callPAP(targetStream, parameters, importParameters.getRequestID(), "importMS");
4137                                 response.setResponseMessage(responseMessage);
4138                         }else{
4139                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing required ImportParameters value.");
4140                                 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing required ImportParameters value.");         
4141                         }
4142                 }else{
4143                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing required ImportParameters value.");
4144                         response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing required ImportParameters value.");         
4145                 }       
4146                 return response;
4147         }
4148         
4149         /*
4150          * Give userID, Passcode and the Resoruce they are requesting for. 
4151          */
4152         private boolean checkPermissions(String userID, String passcode, String resource){
4153                 Boolean result = false;
4154                 if(pyPDPClientFile!=null){
4155                         // Backward compatible pyPDP called us. So validate the user names and scope.
4156                         Path clientPath = Paths.get(pyPDPClientFile);
4157                         if (Files.notExists(clientPath)) {
4158                                 result = false;
4159                         }else if(clientPath.toString().endsWith(".properties")) {
4160                                 try {
4161                                         HashMap<String, ArrayList<String>> clientMap = readProps(clientPath);
4162                                         if (clientMap.containsKey(userID) && clientMap.get(userID).get(0).equals(passcode)) {
4163                                                 result= true;
4164                                         }
4165                                 } catch (Exception e) {
4166                                         result = false;
4167                                 }
4168                         }
4169                 }else{
4170                         //Allowing Every Client who ever don't have access for AAF and Backup Client file
4171                         result = true;
4172                 }
4173                 return result;
4174         }
4175         
4176         private HashMap<String, ArrayList<String>> readProps(Path clientPath) throws Exception{
4177                 InputStream in;
4178                 Properties clientProp = new Properties();
4179                 try {
4180                         in = new FileInputStream(clientPath.toFile());
4181                         clientProp.load(in);
4182                 } catch (IOException e) {
4183                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
4184                         throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e);
4185                 }
4186                 // Read the Properties and Load the Clients and their scopes.
4187                 HashMap<String, ArrayList<String>>clientMap = new HashMap<String, ArrayList<String>>();
4188                 // 
4189                 for (Object propKey : clientProp.keySet()) {
4190                         String clientID = (String)propKey; 
4191                         String clientValue = clientProp.getProperty(clientID);
4192                         if (clientValue != null) {
4193                                 if (clientValue.contains(",")) {
4194                                         ArrayList<String> clientValues = new ArrayList<String>(Arrays.asList(clientValue.split("\\s*,\\s*")));
4195                                         if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){
4196                                                 clientMap.put(clientID, clientValues);
4197                                         }
4198                                 } 
4199                         }
4200                 }
4201                 if (clientMap == null || clientMap.isEmpty()) {
4202                         logger.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!");
4203                         throw new Exception("Empty Client file");
4204                 }
4205                 return clientMap;
4206         }
4207         
4208         protected boolean isNumeric(String str)
4209         {
4210                 for (char c : str.toCharArray())
4211                 {
4212                         if (!Character.isDigit(c)) return false;
4213                 }
4214                 return true;
4215         } 
4216         
4217         private String ConvertDate(Date date){
4218                 String strDate = null;
4219                 if (date!=null)
4220                 {
4221                         SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
4222                         strDate = dateformatJava.format(date);
4223                 }
4224                 
4225                 return strDate;
4226         }
4227 }