5aa3360ca6222e2b7d9f0957d0a100be20e7abcd
[policy/engine.git] / ECOMP-PDP-REST / src / main / java / org / openecomp / policy / pdp / rest / api / services / PAPServices.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PDP-REST
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 package org.openecomp.policy.pdp.rest.api.services;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.ObjectInputStream;
26 import java.io.OutputStream;
27 import java.net.HttpURLConnection;
28 import java.net.URI;
29 import java.net.URL;
30 import java.nio.charset.StandardCharsets;
31 import java.util.Arrays;
32 import java.util.Base64;
33 import java.util.Collections;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.UUID;
37
38 import org.apache.commons.io.IOUtils;
39 import org.openecomp.policy.api.PolicyException;
40 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
41 import org.openecomp.policy.common.logging.flexlogger.Logger;
42 import org.openecomp.policy.pdp.rest.config.PDPApiAuth;
43 import org.openecomp.policy.rest.XACMLRestProperties;
44 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
45 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
46
47 import com.att.research.xacml.util.XACMLProperties;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49
50 public class PAPServices {
51     private static final String SUCCESS = "success";
52     private static Logger LOGGER = FlexLogger.getLogger(PAPServices.class
53             .getName());
54     
55     private int responseCode = 0;
56     private static String environment = "DEVL";
57     private static Boolean junit = false;
58     private static List<String> paps = null;
59     private static final Object papResourceLock = new Object();
60     private String operation = null;
61     private String requestMethod = null;
62     private String encoding = null; 
63
64     public PAPServices() {
65         environment = PDPApiAuth.getEnvironment();
66         if(paps == null){
67             synchronized (papResourceLock) {
68                 String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS);
69                 if(urlList == null){
70                     urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
71                 }
72                 paps = Arrays.asList(urlList.split(","));
73             }
74         }
75     }
76     
77     private String getPAPEncoding(){
78         if(encoding  == null){
79             String userID =  XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
80             String pass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
81             Base64.Encoder encoder = Base64.getEncoder();
82             encoding =  encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8));
83         }
84         return encoding;
85     }
86     
87     private void rotatePAPList(){
88         synchronized (papResourceLock) {
89             Collections.rotate(paps, -1);
90         }
91     }
92     
93     private String getPAP(){
94         String result;
95         synchronized (papResourceLock) {
96             result = paps.get(0);
97         }
98         return result;
99     }
100
101     public int getResponseCode() {
102         return responseCode;
103     }
104
105     public Object callPAP(Object content, String[] parameters, UUID requestID,
106             String clientScope) throws PolicyException {
107         String response = null;
108         HttpURLConnection connection = null;
109         responseCode = 0;
110         // Checking for the available PAPs is done during the first Request and
111         // the List is going to have the connected PAP as first element.
112         // This makes it Real-Time to change the list depending on their
113         // availability.
114         if (paps == null || paps.isEmpty()) {
115             String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.";
116             LOGGER.error(message);
117             throw new PolicyException(message);
118         }
119         int papsCount = 0;
120         boolean connected = false;
121         while (papsCount < paps.size()) {
122             try {
123                 String fullURL = getPAP();
124                 fullURL = checkParameter(parameters, fullURL);
125                 URL url = new URL(fullURL);
126                 LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---");
127                 // Open the connection
128                 connection = (HttpURLConnection) url.openConnection();
129                 // Setting Content-Type
130                 connection.setRequestProperty("Content-Type","application/json");
131                 // Adding Authorization
132                 connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding());
133                 connection.setRequestProperty("Environment", environment);
134                 connection.setRequestProperty("ClientScope", clientScope);
135                 // set the method and headers
136                 connection.setRequestMethod(requestMethod);
137                 connection.setUseCaches(false);
138                 connection.setInstanceFollowRedirects(false);
139                 connection.setDoOutput(true);
140                 connection.setDoInput(true);
141                 // Adding RequestID
142                 if (requestID == null) {
143                     requestID = UUID.randomUUID();
144                     LOGGER.info("No request ID provided, sending generated ID: "
145                             + requestID.toString());
146                 } else {
147                     LOGGER.info("Using provided request ID: "
148                             + requestID.toString());
149                 }
150                 connection.setRequestProperty("X-ECOMP-RequestID",
151                         requestID.toString());
152                 if (content != null && (content instanceof InputStream)) {
153                     // send current configuration
154                     try (OutputStream os = connection.getOutputStream()) {
155                         int count = IOUtils.copy((InputStream) content, os);
156                         if (LOGGER.isDebugEnabled()) {
157                             LOGGER.debug("copied to output, bytes=" + count);
158                         }
159                     }
160                 } else if(content != null){
161                     // the content is an object to be encoded in JSON
162                     ObjectMapper mapper = new ObjectMapper();
163                     if (!junit) {
164                         mapper.writeValue(connection.getOutputStream(),
165                                 content);
166                     }
167                 }
168                 // DO the connect
169                 connection.connect();
170                 responseCode = connection.getResponseCode();
171                 // If Connected to PAP then break from the loop and continue
172                 // with the Request
173                 if (connection.getResponseCode() > 0 || junit) {
174                     connected = true;
175                     break;
176                 } else {
177                     LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : "  + connection.getResponseCode());
178                     rotatePAPList();
179                 }
180             } catch (Exception e) {
181                 // This means that the PAP is not working
182                 if (junit) {
183                     connected = true;
184                     break;
185                 }
186                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
187                         + "PAP connection Error : " + e);
188                 rotatePAPList();
189             }
190             papsCount++;
191         }
192         if (connected) {
193             // Read the Response
194             LOGGER.debug("connected to the PAP : " + getPAP());
195             LOGGER.debug("--- Response: ---");
196             Map<String, List<String>> headers = connection.getHeaderFields();
197             for (String key : headers.keySet()) {
198                 LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
199             }
200                 
201             try {
202                 response = checkResponse(connection, requestID);
203             } catch (IOException e) {
204                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
205                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + e;
206                 throw new PolicyException(
207                         XACMLErrorConstants.ERROR_SYSTEM_ERROR
208                                 + "Decoding the result ", e);
209             }
210             if (junit) {
211                 response = SUCCESS;
212             }
213             return response;
214         } else {
215             response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
216                     + "Unable to get valid response from PAP(s) " + paps;
217             return response;
218         }
219     }
220     
221     public String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope, UUID requestID) {
222         String version = null;
223         HttpURLConnection connection = null;
224         String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName};
225         if (paps == null || paps.isEmpty()) {
226             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
227             try {
228                 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
229             } catch (Exception e) {
230                 LOGGER.error(e.getMessage());
231             }
232             }else {
233                 int papsCount = 0;
234                 boolean connected = false;
235                 while (papsCount < paps.size()) {
236                     try {
237                         String fullURL = getPAP();
238                         if (parameters != null && parameters.length > 0) {
239                             String queryString = "";
240                             for (String p : parameters) {
241                                 queryString += "&" + p;
242                             }
243                             fullURL += "?" + queryString.substring(1);
244                         }
245         
246                         URL url = new URL (fullURL);
247                         
248                         //Open the connection
249                         connection = (HttpURLConnection)url.openConnection();
250                         
251                         // Setting Content-Type
252                         connection.setRequestProperty("Content-Type",
253                                 "application/json");
254                         
255                         // Adding Authorization
256                         connection.setRequestProperty("Authorization", "Basic "
257                                 + getPAPEncoding());
258                         
259                         connection.setRequestProperty("Environment", environment);
260                         connection.setRequestProperty("ClientScope", clientScope);
261
262                         
263                         //set the method and headers
264                         connection.setRequestMethod("GET");
265                         connection.setUseCaches(false);
266                         connection.setInstanceFollowRedirects(false);
267                         connection.setDoOutput(true);
268                         connection.setDoInput(true);
269                         // mb1915 - begin
270                         // mb1915 - set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
271                         connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
272                         // mb1915 - end
273         
274                         //DO the connect
275                         connection.connect();
276         
277                         // If Connected to PAP then break from the loop and continue with the Request 
278                         if (connection.getResponseCode() > 0) {
279                             connected = true;
280                             break;
281
282                         } else {
283                             LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
284                         }
285                     } catch (Exception e) {
286                         // This means that the PAP is not working 
287                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
288                         rotatePAPList();
289                     }
290                     papsCount++;
291                 }
292         
293                 if (connected) {
294                     //Read the Response
295                     LOGGER.debug("connected to the PAP : " + getPAP());
296                     LOGGER.debug("--- Response: ---");
297                     Map<String, List<String>> headers = connection.getHeaderFields();
298                     for (String key : headers.keySet()) {
299                         LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
300                     }
301                     try {
302                         if (connection.getResponseCode() == 200) {
303                             // Check for successful creation of policy
304                             version = connection.getHeaderField("version");
305                             LOGGER.debug("ActiveVersion from the Header: " + version);
306                         } else if (connection.getResponseCode() == 403) {
307                             LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " 
308                                     + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ");
309                             version = "pe100";
310                         } else if (connection.getResponseCode() == 404) {
311                             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is " 
312                                         + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP");
313                             version = "pe300";
314                         } else {
315                             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST:  Error occured while getting the version from the PAP. The request may be incorrect.");
316                         }
317                     } catch (IOException e) {
318                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
319                         try {
320                             throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
321                         } catch (Exception e1) {
322                             LOGGER.error(e1.getMessage());
323                         }
324                     } 
325         
326                 } else {
327                     LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
328                     try {
329                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
330                     } catch (Exception e) {
331                         LOGGER.error(e.getMessage());
332                     }
333                 }   
334             }
335             return version;
336     }
337     
338     public StdPDPPolicy getGitPath(String policyScope, String filePrefix, String policyName, String activeVersion, String clientScope, UUID requestID, String id) throws PolicyException{
339         String gitPath = null;
340         Boolean isValid = false;
341         String policyId= null;
342         String description = null;
343         String pushVersion = null;
344         HttpURLConnection connection = null;
345         String [] parameters = {"apiflag=gitPath", "policyScope="+policyScope, "filePrefix="+filePrefix, 
346                                     "policyName="+policyName, "activeVersion="+activeVersion};
347         if (paps == null || paps.isEmpty()) {
348             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
349             try {
350                 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
351             } catch (Exception e) {
352                 LOGGER.error(e.getMessage());
353             }
354             }else {
355                 int papsCount = 0;
356                 boolean connected = false;
357                 while (papsCount < paps.size()) {
358                     try {
359                         String fullURL = getPAP();
360                         if (parameters != null && parameters.length > 0) {
361                             String queryString = "";
362                             for (String p : parameters) {
363                                 queryString += "&" + p;
364                             }
365                             fullURL += "?" + queryString.substring(1);
366                         }
367         
368                         URL url = new URL (fullURL);
369                         
370                         //Open the connection
371                         connection = (HttpURLConnection)url.openConnection();
372                         
373                         // Setting Content-Type
374                         connection.setRequestProperty("Content-Type",
375                                 "application/json");
376                         
377                         // Adding Authorization
378                         connection.setRequestProperty("Authorization", "Basic "
379                                 +getPAPEncoding());
380                         
381                         connection.setRequestProperty("Environment", environment);
382                         connection.setRequestProperty("ClientScope", clientScope);
383                         
384                         //set the method and headers
385                         connection.setRequestMethod("GET");
386                         connection.setUseCaches(false);
387                         connection.setInstanceFollowRedirects(false);
388                         connection.setDoOutput(true);
389                         connection.setDoInput(true);
390                         // mb1915 - begin
391                         // mb1915 - set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
392                         connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
393                         // mb1915 - end
394         
395                         //DO the connect
396                         connection.connect();
397         
398                         // If Connected to PAP then break from the loop and continue with the Request 
399                         if (connection.getResponseCode() > 0) {
400                             connected = true;
401                             break;
402
403                         } else {
404                             LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
405                         }
406                     } catch (Exception e) {
407                         // This means that the PAP is not working 
408                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
409                         rotatePAPList();
410                     }
411                     papsCount++;
412                 }
413         
414                 if (connected) {
415                     //Read the Response
416                     LOGGER.debug("connected to the PAP : " + getPAP());
417                     LOGGER.debug("--- Response: ---");
418                     Map<String, List<String>> headers = connection.getHeaderFields();
419                     for (String key : headers.keySet()) {
420                         LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
421                     }
422                     try {
423                         if (connection.getResponseCode() == 200) {
424                             // Check for successful creation of policy
425                             gitPath = connection.getHeaderField("gitPath");
426                             policyId = connection.getHeaderField("policyId");
427                             description = connection.getHeaderField("description");
428                             pushVersion = connection.getHeaderField("version");
429                             isValid = Boolean.parseBoolean(connection.getHeaderField("isValid"));
430                             
431                             LOGGER.debug("GitPath from Header: " + gitPath);
432                             LOGGER.debug("policyId from Header: " + policyId);
433                             LOGGER.debug("description from Header: " + description);
434                             LOGGER.debug("version from Header: " + pushVersion);
435                             LOGGER.debug("isValid from Header: " + isValid);
436                             
437                             /*if (gitPath != null && !gitPath.equalsIgnoreCase("")) {
438                                 return gitPath;
439                             }*/ if (gitPath == null || gitPath.trim().isEmpty()) {
440                                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
441                             }
442                         } else if (connection.getResponseCode() == 404) {
443                             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is " 
444                                         + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP");
445                         } else {
446                             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST:  Error occured while getting the gitPath from the PAP. The request may be incorrect.");
447                         }
448                     } catch (IOException e) {
449                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
450                         try {
451                             throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
452                         } catch (Exception e1) {
453                             LOGGER.error(e1.getMessage());
454                         }
455                     } 
456         
457                 } else {
458                     LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
459                     try {
460                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
461                     } catch (Exception e) {
462                         LOGGER.error(e.getMessage());
463                     }
464                 }   
465             }
466         LOGGER.debug("Full gitPath policy xml file: " + gitPath);
467         URI selectedURI = getSelectedURI(gitPath, clientScope, requestID);
468         LOGGER.debug("The selectedURI is : " + selectedURI.toString());
469         String name = filePrefix+policyName;
470                 
471         StdPDPPolicy selectedPolicy;
472         try {
473             selectedPolicy = new StdPDPPolicy(id, true, name, selectedURI, isValid, policyId, description, pushVersion);
474         } catch (IOException e) {
475             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+e.getMessage());
476             throw new PolicyException(e);
477         }
478         return selectedPolicy;
479     }
480     
481     private URI getSelectedURI(String gitPath, String clientScope, UUID requestID){
482         URI selectedURI = null;
483         HttpURLConnection connection = null;
484         String [] parameters = {"apiflag=uri", "gitPath="+gitPath};
485         if (paps == null || paps.isEmpty()) {
486             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
487             try {
488                 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
489             } catch (Exception e) {
490                 LOGGER.error(e.getMessage());
491             }
492             }else {
493                 int papsCount = 0;
494                 boolean connected = false;
495                 while (papsCount < paps.size()) {
496                     try {
497                         String fullURL = getPAP();
498                         if (parameters != null && parameters.length > 0) {
499                             String queryString = "";
500                             for (String p : parameters) {
501                                 queryString += "&" + p;
502                             }
503                             fullURL += "?" + queryString.substring(1);
504                         }
505         
506                         URL url = new URL (fullURL);
507                         
508                         //Open the connection
509                         connection = (HttpURLConnection)url.openConnection();
510                         
511                         // Setting Content-Type
512                         connection.setRequestProperty("Content-Type",
513                                 "application/json");
514                         
515                         // Adding Authorization
516                         connection.setRequestProperty("Authorization", "Basic "
517                                 + getPAPEncoding());
518                         
519                         connection.setRequestProperty("Environment", environment);
520                         connection.setRequestProperty("ClientScope", clientScope);
521                         
522                         //set the method and headers
523                         connection.setRequestMethod("GET");
524                         connection.setUseCaches(false);
525                         connection.setInstanceFollowRedirects(false);
526                         connection.setDoOutput(true);
527                         connection.setDoInput(true);
528                         // mb1915 - begin  
529                         // mb1915 - set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
530                         connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
531                         // mb1915 - end
532         
533                         //DO the connect
534                         connection.connect();
535                         responseCode = connection.getResponseCode();
536                         // If Connected to PAP then break from the loop and continue with the Request 
537                         if (connection.getResponseCode() > 0) {
538                             connected = true;
539                             break;
540
541                         } else {
542                             LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
543                         }
544                     } catch (Exception e) {
545                         // This means that the PAP is not working 
546                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
547                         rotatePAPList();
548                     }
549                     papsCount++;
550                 }
551         
552                 if (connected) {
553                     //Read the Response
554                     LOGGER.debug("connected to the PAP : " + getPAP());
555                     LOGGER.debug("--- Response: ---");
556                     Map<String, List<String>> headers = connection.getHeaderFields();
557                     for (String key : headers.keySet()) {
558                         LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
559                     }
560                     try {
561                         if (connection.getResponseCode() == 200) {
562                             // Check for successful creation of policy
563                             String uri = connection.getHeaderField("selectedURI");
564                             LOGGER.debug("URI from Header: " + uri);
565                             if (uri != null && !uri.equalsIgnoreCase("")) {
566                                 selectedURI = URI.create(uri);
567                                 return selectedURI;
568                             } else {
569                                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
570                             }
571                         } else if (connection.getResponseCode() == 404) {
572                             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is " 
573                                         + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP");
574                         } else {
575                             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST:  Error occured while getting the gitPath from the PAP. The request may be incorrect.");
576                         }
577                     } catch (IOException e) {
578                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
579                         try {
580                             throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
581                         } catch (Exception e1) {
582                             LOGGER.error(e1.getMessage());
583                         }
584                     } 
585         
586                 } else {
587                     LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
588                     try {
589                         throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
590                     } catch (Exception e) {
591                         LOGGER.error(e.getMessage());
592                     }
593                 }   
594             }
595             return selectedURI;
596     }
597     
598     private String checkResponse(HttpURLConnection connection, UUID requestID) throws IOException {
599         String response = null;
600         if (responseCode == 200 || junit) {         
601             // Check for successful creation of policy
602             String isSuccess = null;
603             if (!junit) { // is this a junit test?
604                 isSuccess = connection.getHeaderField("successMapKey");
605                 operation = connection.getHeaderField("operation");
606             } else {
607                 isSuccess = SUCCESS;
608             }
609             if (SUCCESS.equals(isSuccess)) {
610                 if ("update".equals(operation)) {
611                     response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName")
612                             + " was successfully updated. ";
613                     if (connection.getHeaderField("safetyChecker")!=null) {
614                         response = response 
615                                                 + "\n\nPolicy Safety Checker Warning: This closedLoopControlName "
616                                                 + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") 
617                                                 +  " that already exists." + " See detailed information on ClosedLoop Pairs below: "
618                                                 +"\n\n"+connection.getHeaderField("safetyChecker");
619                     }
620                 } else if ("create".equals(operation)) {
621                         response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName")
622                             + " was successfully created.";
623                     if (connection.getHeaderField("safetyChecker")!=null) {
624                         response = response 
625                                                 + "\n\nPolicy Safety Checker Warning: This closedLoopControlName "
626                                                 + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") 
627                                                 +  " that already exists. " + "See detailed information on ClosedLoop Pairs below: "
628                                                 +"\n\n"+connection.getHeaderField("safetyChecker");
629                     }
630                 } else if ("delete".equals(operation)) {
631                     response = "Transaction ID: " + requestID + " --The policy was successfully deleted.";
632                 } else if ("import".equals(operation)) {
633                     response = "Transaction ID: " + requestID + " --The policy engine import for "+ connection.getHeaderField("service")
634                             + " was successfull.";
635                 } else if ("createDictionary".equals(operation)) {
636                     response = "Transaction ID: " + requestID + " --Dictionary Item was added successfully!";
637                 } else if ("updateDictionary".equals(operation)) {
638                     response = "Transaction ID: " + requestID + " --Dictionary Item was updated successfully!";
639                 } else if ("getDictionary".equals(operation)) {
640                     String json =  null;
641                     try {
642                         
643                         //get the json string from the response 
644                         InputStream is = connection.getInputStream();
645                             
646                         // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
647                         java.util.Scanner scanner = new java.util.Scanner(is);
648                         scanner.useDelimiter("\\A");
649                         json =  scanner.hasNext() ? scanner.next() : "";
650                         scanner.close();
651                         
652                     } catch (IOException e1) {
653                         LOGGER.error(e1.getMessage());
654                     }
655                     response = "Transaction ID: " + requestID + " --Dictionary Items Retrieved " + json;
656                 } else if ("getMetrics".equals(operation)) {
657                         response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved " + connection.getHeaderField("metrics");
658                 }
659                 LOGGER.info(response);
660             } else {
661                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE
662                         + "Operation unsuccessful, unable to complete the request!";
663                 LOGGER.error(message);
664                 response = message;
665             }
666         } else if (connection.getResponseCode() == 202) {
667             if ("delete".equalsIgnoreCase(connection.getHeaderField("operation")) &&
668                     "true".equals(connection.getHeaderField("lockdown"))) {
669                 response = "Transaction ID: "
670                         + requestID
671                         + " --Policies are locked down, please try again later.";
672                 LOGGER.warn(response);
673             }
674         } else if (connection.getResponseCode() == 204) {
675             if ("push".equals(connection.getHeaderField("operation"))) {
676                 response = "Transaction ID: "
677                         + requestID
678                         + " --Policy '"
679                         + connection.getHeaderField("policyId")
680                         + "' was successfully pushed to the PDP group '"
681                         + connection.getHeaderField("groupId") + "'.";
682                 LOGGER.info(response);
683             }
684         } else if (connection.getResponseCode() == 400  && connection.getHeaderField("error") != null) {
685                 response = connection.getHeaderField("error");
686             LOGGER.error(response);
687         } else if (connection.getResponseCode() == 403) {
688             response = XACMLErrorConstants.ERROR_PERMISSIONS
689                     + "response code of the URL is "
690                     + connection.getResponseCode()
691                     + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
692             LOGGER.error(response);
693         } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error") != null) {
694             if ("unknownGroupId".equals(connection.getHeaderField("error"))) {
695                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
696                         + connection.getHeaderField("message")
697                         + " Please check the pdpGroup you are requesting to move the policy to.";
698                 LOGGER.error(response);
699             }
700         } else if (connection.getResponseCode() == 409  && connection.getHeaderField("error") != null) {
701             if ("modelExistsDB".equals(connection.getHeaderField("error"))) {
702                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
703                         + "Import Value Exist Error:  The import value "
704                         + connection.getHeaderField("service")
705                         + " already exist on the PAP. "
706                         + "Please create a new import value.";
707             } else if ("policyExists".equals(connection.getHeaderField("error"))) {
708                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
709                         + "Policy Exist Error:  The Policy "
710                         + connection.getHeaderField("policyName")
711                         + " already exist on the PAP. "
712                         + "Please create a new policy or use the update API to modify the existing one.";
713             } else if ("dictionaryItemExists".equals(connection.getHeaderField("error"))) {
714                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
715                         + "Dictionary Item Exist Error:  The Dictionary Item already exist in the database. "
716                         + "Please create a new Dictionary Item or use the update API to modify the existing one.";
717             } else if ("duplicateGroup".equals(connection.getHeaderField("error"))) {
718                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
719                         + "Group Policy Scope List Exist Error:  The Group Policy Scope List for this Dictionary Item already exist in the database. "
720                         + "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. "
721                         + "Please review the request and verify that the groupPolicyScopeListData1 is unique compared to existing groups.";
722             }
723             LOGGER.error(response);
724         } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) {
725             if ("jpautils".equals(connection.getHeaderField("error"))) {
726                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
727                         + "Could not create JPAUtils instance on the PAP";
728             } else if ("deleteDB".equals(connection.getHeaderField("error"))) {
729                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
730                         + "Failed to delete Policy from database.";
731             } else if ("deleteFile".equals(connection.getHeaderField("error"))) {
732                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
733                         + "Cannot delete the policy file";
734             } else if ("groupUpdate".equals(connection.getHeaderField("error"))) {
735                 response = connection.getHeaderField("message");
736             } else if ("unknown".equals(connection.getHeaderField("error"))) {
737                 response = XACMLErrorConstants.ERROR_UNKNOWN
738                         + "Failed to delete the policy for an unknown reason.  Check the file system and other logs for further information.";
739             } else if ("deleteConfig".equals(connection.getHeaderField("error"))) {
740                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
741                         + "Cannot delete the configuration or action body file in specified location.";
742             } else if ("missing".equals(connection.getHeaderField("error"))) {
743                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
744                         + "Failed to create value in database because service does match a value in file";
745             } else if ("importDB".equals(connection.getHeaderField("error"))) {
746                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
747                         + "Database errors during policy engine import";
748             } else if ("policyCopyError".equals(connection.getHeaderField("error"))) {
749                 response = XACMLErrorConstants.ERROR_PROCESS_FLOW
750                         + connection.getHeaderField("message");
751             } else if ("addGroupError".equals(connection.getHeaderField("error"))) {
752                 response = connection.getHeaderField("message");
753             } else if ("error".equals(connection.getHeaderField("error"))) {
754                 response = XACMLErrorConstants.ERROR_UNKNOWN
755                         + "Could not create or update the policy for and unknown reason";
756             }
757             LOGGER.error(response);
758         } else {
759             response = XACMLErrorConstants.ERROR_DATA_ISSUE
760                     + "BAD REQUEST:  Error occured while attempting perform this operation.. the request may be incorrect.";
761             LOGGER.error(response);
762         }
763         return response;
764     }
765
766     private String checkParameter(String[] parameters, String fullURL) {
767         if (parameters != null && parameters.length > 0) {
768             String queryString = "";
769             for (String p : parameters) {
770                 queryString += "&" + p;
771                 if (p.equalsIgnoreCase("operation=post")) {
772                     requestMethod = "POST";
773                 } else if (p.equalsIgnoreCase("operation=delete")) {
774                     requestMethod = "DELETE";
775                     operation = "delete";
776                 } else if (p.equalsIgnoreCase("operation=get")) {
777                     requestMethod = "GET";
778                     operation = "get";
779                 } else if (p.equalsIgnoreCase("operation=put")||p.equalsIgnoreCase("operation=create")
780                         ||p.equalsIgnoreCase("operation=update")||p.equalsIgnoreCase("operation=createDictionary")){
781                         requestMethod = "PUT";
782                     if (p.equalsIgnoreCase("operation=create")) {
783                         operation = "create";
784                     } else if (p.equalsIgnoreCase("operation=update")) {
785                         operation = "update";
786                     } else if (p.equalsIgnoreCase("operation=createDictionary")){
787                                                 operation = "createDictionary";
788                                         }
789                 }else if (p.equalsIgnoreCase("importService=MICROSERVICE")||p.equalsIgnoreCase("importService=BRMSPARAM")){
790                         requestMethod = "PUT";
791                 }
792             }
793             fullURL += "?" + queryString.substring(1);
794         }
795         return fullURL;
796     }
797
798         public StdPDPPolicy pushPolicy(String policyScope, String filePrefix,
799                         String policyName, String clientScope, String pdpGroup,
800                         UUID requestID) throws PolicyException {
801                 String json = "{ "
802                                 + "\"apiflag\": \"api\","
803                                 + "\"policyScope\": \""+policyScope+"\","
804                                 + "\"filePrefix\": \""+filePrefix+"\","
805                                 + "\"policyName\": \""+policyName+"\","
806                                 + "\"clientScope\": \""+clientScope+"\","
807                                 + "\"pdpGroup\": \""+pdpGroup+"\"}";
808         //String response = null;
809         HttpURLConnection connection = null;
810         responseCode = 0;
811         if (paps == null || paps.isEmpty()) {
812             String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.";
813             LOGGER.error(message);
814             throw new PolicyException(message);
815         }
816         int papsCount = 0;
817         boolean connected = false;
818         while (papsCount < paps.size()) {
819             try {
820                 String fullURL = getPAP();
821                 fullURL = (fullURL.endsWith("/"))? fullURL+"ecomp/pushPolicy" : fullURL+"/ecomp/pushPolicy";
822                 URL url = new URL(fullURL);
823                 LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---");
824                 // Open the connection
825                 connection = (HttpURLConnection) url.openConnection();
826                 // Setting Content-Type
827                 connection.setRequestProperty("Content-Type","application/json");
828                 // Adding Authorization
829                 connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding());
830                 connection.setRequestProperty("Environment", environment);
831                 connection.setRequestProperty("ClientScope", clientScope);
832                 // set the method and headers
833                 connection.setRequestMethod("POST");
834                 connection.setUseCaches(false);
835                 connection.setInstanceFollowRedirects(false);
836                 connection.setDoOutput(true);
837                 // Adding RequestID
838                 if (requestID == null) {
839                     requestID = UUID.randomUUID();
840                     LOGGER.info("No request ID provided, sending generated ID: "
841                             + requestID.toString());
842                 } else {
843                     LOGGER.info("Using provided request ID: "
844                             + requestID.toString());
845                 }
846                 connection.setRequestProperty("X-ECOMP-RequestID",
847                         requestID.toString());
848                 // DO the connect
849                 try (OutputStream os = connection.getOutputStream()) {
850                     int count = IOUtils.copy(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), os);
851                     if (LOGGER.isDebugEnabled()) {
852                         LOGGER.debug("copied to output, bytes=" + count);
853                     }
854                 }
855                 connection.connect();
856                 responseCode = connection.getResponseCode();
857                 // If Connected to PAP then break from the loop and continue
858                 // with the Request
859                 if (connection.getResponseCode() > 0 || junit) {
860                     connected = true;
861                     break;
862                 } else {
863                     LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : "  + connection.getResponseCode());
864                     rotatePAPList();
865                 }
866             } catch (Exception e) {
867                 // This means that the PAP is not working
868                 if (junit) {
869                     connected = true;
870                     break;
871                 }
872                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
873                         + "PAP connection Error : " + e);
874                 rotatePAPList();
875             }
876             papsCount++;
877         }
878         if (connected) {
879             // Read the Response
880             LOGGER.debug("connected to the PAP : " + getPAP());
881             LOGGER.debug("--- Response: ---");
882             Map<String, List<String>> headers = connection.getHeaderFields();
883             for (String key : headers.keySet()) {
884                 LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
885             }
886             try {
887                 if(responseCode==202){
888                         StdPDPPolicy policy = (StdPDPPolicy) new ObjectInputStream(connection.getInputStream()).readObject();
889                         return policy;
890                 }
891             } catch (IOException | ClassNotFoundException e) {
892                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
893                 throw new PolicyException(
894                         XACMLErrorConstants.ERROR_SYSTEM_ERROR
895                                 + "Decoding the result ", e);
896             }
897             return null;
898         } else {
899             return null;
900         }
901     }
902 }