CHeckstyle and JUnit for base package in ONAP-REST
[policy/engine.git] / ONAP-PDP-REST / src / main / java / org / onap / policy / pdp / rest / api / services / PAPServices.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PDP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdp.rest.api.services;
22
23 import com.att.research.xacml.util.XACMLProperties;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.ObjectInputStream;
29 import java.io.OutputStream;
30 import java.net.HttpURLConnection;
31 import java.net.URL;
32 import java.nio.charset.StandardCharsets;
33 import java.util.Arrays;
34 import java.util.Base64;
35 import java.util.Collections;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.UUID;
39 import org.apache.commons.io.IOUtils;
40 import org.onap.policy.api.PolicyException;
41 import org.onap.policy.common.logging.flexlogger.FlexLogger;
42 import org.onap.policy.common.logging.flexlogger.Logger;
43 import org.onap.policy.pdp.rest.restauth.AuthenticationService;
44 import org.onap.policy.rest.XacmlRestProperties;
45 import org.onap.policy.utils.PeCryptoUtils;
46 import org.onap.policy.xacml.api.XACMLErrorConstants;
47 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
48
49 public class PAPServices {
50     private static final String SUCCESS = "success";
51     private static Logger LOGGER = FlexLogger.getLogger(PAPServices.class.getName());
52
53     private int responseCode = 0;
54     private static String environment = "DEVL";
55     private static Boolean isJunit = false;
56     private static List<String> paps = null;
57     private static final Object papResourceLock = new Object();
58     private String operation = null;
59     private String requestMethod = null;
60     private String encoding = null;
61
62     public static void setJunit(final boolean isJunit) {
63         PAPServices.isJunit = isJunit;
64     }
65
66     public PAPServices() {
67         environment = AuthenticationService.getEnvironment();
68         if (paps == null) {
69             synchronized (papResourceLock) {
70                 String urlList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URLS);
71                 if (urlList == null) {
72                     urlList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
73                 }
74                 paps = Arrays.asList(urlList.split(","));
75             }
76         }
77     }
78
79     private String getPAPEncoding() {
80         if (encoding == null) {
81             String userID = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
82             String pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
83             Base64.Encoder encoder = Base64.getEncoder();
84             encoding = encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8));
85         }
86         return encoding;
87     }
88
89     private void rotatePAPList() {
90         synchronized (papResourceLock) {
91             Collections.rotate(paps, -1);
92         }
93     }
94
95     private String getPAP() {
96         String result;
97         synchronized (papResourceLock) {
98             result = paps.get(0);
99         }
100         return result;
101     }
102
103     public static void setPaps(final List<String> paps) {
104         PAPServices.paps = paps;
105     }
106
107     public int getResponseCode() {
108         return responseCode;
109     }
110
111     public Object callPAP(final Object content, final String[] parameters, UUID requestID, final String clientScope)
112             throws PolicyException {
113         String response = null;
114         HttpURLConnection connection = null;
115         responseCode = 0;
116         // Checking for the available PAPs is done during the first Request and
117         // the List is going to have the connected PAP as first element.
118         // This makes it Real-Time to change the list depending on their
119         // availability.
120         if (paps == null || paps.isEmpty()) {
121             final String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAPs List is Empty.";
122             LOGGER.error(message);
123             throw new PolicyException(message);
124         }
125         int papsCount = 0;
126         boolean connected = false;
127         while (papsCount < paps.size()) {
128             try {
129                 String fullURL = getPAP();
130                 fullURL = checkParameter(parameters, fullURL);
131                 final URL url = new URL(fullURL);
132                 LOGGER.info("--- Sending Request to PAP : " + url.toString() + " ---" + " RequestId:" + requestID);
133                 // Open the connection
134                 connection = (HttpURLConnection) url.openConnection();
135                 // Setting Content-Type
136                 connection.setRequestProperty("Content-Type", "application/json");
137                 // Adding Authorization
138                 connection.setRequestProperty("Authorization", "Basic " + getPAPEncoding());
139                 connection.setRequestProperty("Environment", environment);
140                 connection.setRequestProperty("ClientScope", clientScope);
141                 // set the method and headers
142                 connection.setRequestMethod(requestMethod);
143                 connection.setUseCaches(false);
144                 connection.setInstanceFollowRedirects(false);
145                 connection.setDoOutput(true);
146                 connection.setDoInput(true);
147                 // Adding RequestID
148                 if (requestID == null) {
149                     requestID = UUID.randomUUID();
150                     LOGGER.debug("No request ID provided, sending generated ID: " + requestID.toString());
151                 } else {
152                     LOGGER.debug("Using provided request ID: " + requestID.toString());
153                 }
154                 connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
155                 if (content != null && (content instanceof InputStream)) {
156                     // send current configuration
157                     try (OutputStream os = connection.getOutputStream()) {
158                         final int count = IOUtils.copy((InputStream) content, os);
159                         if (LOGGER.isDebugEnabled()) {
160                             LOGGER.debug("copied to output, bytes=" + count);
161                         }
162                     }
163                 } else if (content != null) {
164                     // the content is an object to be encoded in JSON
165                     final ObjectMapper mapper = new ObjectMapper();
166                     if (!isJunit) {
167                         mapper.writeValue(connection.getOutputStream(), content);
168                     }
169                 } else {
170                     LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE + "content is null for calling: " + url.getHost()
171                             + requestID.toString());
172                 }
173                 // DO the connect
174                 connection.connect();
175                 responseCode = connection.getResponseCode();
176                 // If Connected to PAP then break from the loop and continue
177                 // with the Request
178                 if (connection.getResponseCode() > 0 || isJunit) {
179                     connected = true;
180                     break;
181                 } else {
182                     LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "PAP Response Code : "
183                             + connection.getResponseCode());
184                     rotatePAPList();
185                 }
186             } catch (final Exception e) {
187                 // This means that the PAP is not working
188                 if (isJunit) {
189                     connected = true;
190                     break;
191                 }
192                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
193                 rotatePAPList();
194             }
195             papsCount++;
196         }
197         if (connected) {
198             // Read the Response
199             LOGGER.debug("connected to the PAP : " + getPAP());
200             LOGGER.debug("--- Response: ---");
201             if (connection != null) {
202                 final Map<String, List<String>> headers = connection.getHeaderFields();
203                 for (final String key : headers.keySet()) {
204                     LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
205                 }
206
207                 try {
208                     response = checkResponse(connection, requestID);
209                 } catch (final IOException e) {
210                     LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
211                     response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + e;
212                     throw new PolicyException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Decoding the result ", e);
213                 }
214                 if (isJunit) {
215                     response = SUCCESS;
216                 }
217             } else {
218                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null";
219                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null - RequestId: " + requestID);
220             }
221             return response;
222         } else {
223             response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get valid response from PAP(s) " + paps;
224             LOGGER.error("For RequestId: " + requestID + ", " + response);
225             return response;
226         }
227     }
228
229     public String getActiveVersion(final String policyScope, final String filePrefix, final String policyName,
230             final String clientScope, final UUID requestID) {
231         String version = null;
232         HttpURLConnection connection = null;
233         final String[] parameters = {"apiflag=version", "policyScope=" + policyScope, "filePrefix=" + filePrefix,
234                 "policyName=" + policyName};
235         if (paps == null || paps.isEmpty()) {
236             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
237         } else {
238             int papsCount = 0;
239             boolean connected = false;
240             while (papsCount < paps.size()) {
241                 try {
242                     String fullURL = getPAP();
243                     if (parameters != null && parameters.length > 0) {
244                         String queryString = "";
245                         for (final String p : parameters) {
246                             queryString += "&" + p;
247                         }
248                         fullURL += "?" + queryString.substring(1);
249                     }
250
251                     final URL url = new URL(fullURL);
252
253                     // Open the connection
254                     connection = (HttpURLConnection) url.openConnection();
255
256                     // Setting Content-Type
257                     connection.setRequestProperty("Content-Type", "application/json");
258
259                     // Adding Authorization
260                     connection.setRequestProperty("Authorization", "Basic " + getPAPEncoding());
261
262                     connection.setRequestProperty("Environment", environment);
263                     connection.setRequestProperty("ClientScope", clientScope);
264
265                     // set the method and headers
266                     connection.setRequestMethod("GET");
267                     connection.setUseCaches(false);
268                     connection.setInstanceFollowRedirects(false);
269                     connection.setDoOutput(true);
270                     connection.setDoInput(true);
271                     connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
272
273                     // DO the connect
274                     connection.connect();
275
276                     // If Connected to PAP then break from the loop and continue with the Request
277                     if (connection.getResponseCode() > 0) {
278                         connected = true;
279                         break;
280
281                     } else {
282                         LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
283                     }
284                 } catch (final Exception e) {
285                     // This means that the PAP is not working
286                     LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
287                     rotatePAPList();
288                 }
289                 papsCount++;
290             }
291
292             if (connected) {
293                 // Read the Response
294                 LOGGER.debug("connected to the PAP : " + getPAP());
295                 LOGGER.debug("--- Response: ---");
296                 final Map<String, List<String>> headers = connection.getHeaderFields();
297                 for (final String key : headers.keySet()) {
298                     LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
299                 }
300                 try {
301                     if (connection.getResponseCode() == 200) {
302                         // Check for successful creation of policy
303                         version = connection.getHeaderField("version");
304                         LOGGER.debug("ActiveVersion from the Header: " + version);
305                     } else if (connection.getResponseCode() == 403) {
306                         LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is "
307                                 + connection.getResponseCode()
308                                 + ". 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()
313                                 + ". This indicates a problem with getting the version from the PAP");
314                         version = "pe300";
315                     } else {
316                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
317                                 + "BAD REQUEST:  Error occured while getting the version from the PAP. "
318                                 + "The request may be incorrect. The response code of the URL is '"
319                                 + connection.getResponseCode() + "'");
320                     }
321                 } catch (final IOException e) {
322                     LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
323                 }
324             } else {
325                 LOGGER.error(
326                         XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
327             }
328         }
329         return version;
330     }
331
332     private String checkResponse(final HttpURLConnection connection, final UUID requestID) throws IOException {
333         String response = null;
334         LOGGER.info("PAPServices:checkResponse - RequestId: " + requestID + ", ResponseCode: " + responseCode);
335         if (responseCode == 200 || isJunit) {
336             // Check for successful creation of policy
337             String isSuccess = null;
338             if (!isJunit) { // is this a junit test?
339                 isSuccess = connection.getHeaderField("successMapKey");
340                 operation = connection.getHeaderField("operation");
341             } else {
342                 isSuccess = SUCCESS;
343             }
344             if (SUCCESS.equals(isSuccess)) {
345                 if ("update".equals(operation)) {
346                     response = "Transaction ID: " + requestID + " --Policy with the name "
347                             + connection.getHeaderField("policyName") + " was successfully updated. ";
348                     if (connection.getHeaderField("safetyChecker") != null) {
349                         response = response + "\n\nPolicy Safety Checker Warning: This closedLoopControlName "
350                                 + "is potentially in conflict with " + connection.getHeaderField("conflictCLName")
351                                 + " that already exists." + " See detailed information on ClosedLoop Pairs below: "
352                                 + "\n\n" + connection.getHeaderField("safetyChecker");
353                     }
354                 } else if ("create".equals(operation)) {
355                     response = "Transaction ID: " + requestID + " --Policy with the name "
356                             + connection.getHeaderField("policyName") + " was successfully created.";
357                     if (connection.getHeaderField("safetyChecker") != null) {
358                         response = response + "\n\nPolicy Safety Checker Warning: This closedLoopControlName "
359                                 + "is potentially in conflict with " + connection.getHeaderField("conflictCLName")
360                                 + " that already exists. " + "See detailed information on ClosedLoop Pairs below: "
361                                 + "\n\n" + connection.getHeaderField("safetyChecker");
362                     }
363                 } else if ("delete".equals(operation)) {
364                     response = "Transaction ID: " + requestID + " --The policy was successfully deleted.";
365                 } else if ("import".equals(operation)) {
366                     response = "Transaction ID: " + requestID + " --The policy engine import for "
367                             + connection.getHeaderField("service") + " was successfull.";
368                 } else if ("createDictionary".equals(operation)) {
369                     response = "Transaction ID: " + requestID + " --Dictionary Item was added successfully!";
370                 } else if ("updateDictionary".equals(operation)) {
371                     response = "Transaction ID: " + requestID + " --Dictionary Item was updated successfully!";
372                 } else if ("getDictionary".equals(operation)) {
373                     String json = null;
374                     try {
375
376                         // get the json string from the response
377                         final InputStream is = connection.getInputStream();
378
379                         // read the inputStream into a buffer (trick found online scans entire input
380                         // looking for end-of-file)
381                         final java.util.Scanner scanner = new java.util.Scanner(is);
382                         scanner.useDelimiter("\\A");
383                         json = scanner.hasNext() ? scanner.next() : "";
384                         scanner.close();
385
386                     } catch (final IOException e1) {
387                         LOGGER.error(e1.getMessage() + e1);
388                     }
389                     response = "Transaction ID: " + requestID + " --Dictionary Items Retrieved " + json;
390                 } else if ("getMetrics".equals(operation)) {
391                     response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved "
392                             + connection.getHeaderField("metrics");
393                 }
394                 LOGGER.info(response);
395             } else {
396                 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE
397                         + "Operation unsuccessful, unable to complete the request!";
398                 LOGGER.error(message);
399                 response = message;
400             }
401         } else if (connection.getResponseCode() == 202) {
402             if ("delete".equalsIgnoreCase(connection.getHeaderField("operation"))
403                     && "true".equals(connection.getHeaderField("lockdown"))) {
404                 response = "Transaction ID: " + requestID + " --Policies are locked down, please try again later.";
405                 LOGGER.warn(response);
406             }
407         } else if (connection.getResponseCode() == 204) {
408             if ("push".equals(connection.getHeaderField("operation"))) {
409                 response = "Transaction ID: " + requestID + " --Policy '" + connection.getHeaderField("policyId")
410                         + "' was successfully pushed to the PDP group '" + connection.getHeaderField("groupId") + "'.";
411                 LOGGER.info(response);
412             }
413         } else if (connection.getResponseCode() == 400 && connection.getHeaderField("error") != null) {
414             response = connection.getHeaderField("error");
415             LOGGER.error(response);
416         } else if (connection.getResponseCode() == 403) {
417             response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is "
418                     + connection.getResponseCode()
419                     + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
420             LOGGER.error(response);
421         } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error") != null) {
422             if ("UnknownGroup".equals(connection.getHeaderField("error"))) {
423                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message")
424                         + " Please check the pdpGroup you are requesting to push the policy to.";
425                 LOGGER.error(response);
426             } else if ("policyNotAvailableForEdit".equals(connection.getHeaderField("error"))) {
427                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message");
428             }
429         } else if (connection.getResponseCode() == 409 && connection.getHeaderField("error") != null) {
430             if ("modelExistsDB".equals(connection.getHeaderField("error"))) {
431                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Import Value Exist Error:  The import value "
432                         + connection.getHeaderField("service") + " already exist on the PAP. "
433                         + "Please create a new import value.";
434             } else if ("policyExists".equals(connection.getHeaderField("error"))) {
435                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Exist Error:  The Policy "
436                         + connection.getHeaderField("policyName") + " already exist on the PAP. "
437                         + "Please create a new policy or use the update API to modify the existing one.";
438             } else if ("dictionaryItemExists".equals(connection.getHeaderField("error"))) {
439                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
440                         + "Dictionary Item Exist Error:  The Dictionary Item already exist in the database. "
441                         + "Please create a new Dictionary Item or use the update API to modify the existing one.";
442             } else if ("duplicateGroup".equals(connection.getHeaderField("error"))) {
443                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
444                         + "Group Policy Scope List Exist Error:  "
445                         + "The Group Policy Scope List for this Dictionary Item already exist in the database. "
446                         + "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. "
447                         + "Please review the request and "
448                         + "verify that the groupPolicyScopeListData1 is unique compared to existing groups.";
449             } else if ("PolicyInPDP".equals(connection.getHeaderField("error"))) {
450                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
451                         + "Policy Exist Error:  The Policy trying to be deleted is active in PDP. "
452                         + "Active PDP Polcies are not allowed to be deleted from PAP. "
453                         + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP";
454             }
455             LOGGER.error(response);
456         } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) {
457             if ("jpautils".equals(connection.getHeaderField("error"))) {
458                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Could not create JPAUtils instance on the PAP";
459             } else if ("deleteDB".equals(connection.getHeaderField("error"))) {
460                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to delete Policy from database.";
461             } else if ("deleteFile".equals(connection.getHeaderField("error"))) {
462                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file";
463             } else if ("groupUpdate".equals(connection.getHeaderField("error"))) {
464                 response = connection.getHeaderField("message");
465             } else if ("unknown".equals(connection.getHeaderField("error"))) {
466                 response = XACMLErrorConstants.ERROR_UNKNOWN
467                         + "Failed to delete the policy for an unknown reason.  "
468                         + "Check the file system and other logs for further information.";
469             } else if ("deleteConfig".equals(connection.getHeaderField("error"))) {
470                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
471                         + "Cannot delete the configuration or action body file in specified location.";
472             } else if ("missing".equals(connection.getHeaderField("error"))) {
473                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
474                         + "Failed to create value in database because service does match a value in file";
475             } else if ("importDB".equals(connection.getHeaderField("error"))) {
476                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Database errors during policy engine import";
477             } else if ("policyCopyError".equals(connection.getHeaderField("error"))) {
478                 response = XACMLErrorConstants.ERROR_PROCESS_FLOW + connection.getHeaderField("message");
479             } else if ("addGroupError".equals(connection.getHeaderField("error"))) {
480                 response = connection.getHeaderField("message");
481             } else if ("validation".equals(connection.getHeaderField("error"))) {
482                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Validation errors during policy engine "
483                         + connection.getHeaderField("operation") + " for " + connection.getHeaderField("service");
484             } else if ("error".equals(connection.getHeaderField("error"))) {
485                 response = XACMLErrorConstants.ERROR_UNKNOWN
486                         + "Could not create or update the policy for and unknown reason";
487             } else {
488                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
489                         + "Error occured while attempting perform this operation.. "
490                         + "the request may be incorrect or the PAP is unreachable. "
491                         + connection.getHeaderField("error");
492             }
493             LOGGER.error(response);
494         } else {
495             response =
496                     XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error occured while attempting perform this operation.. "
497                             + "the request may be incorrect or the PAP is unreachable.";
498             LOGGER.error(response);
499         }
500         return response;
501     }
502
503     private String checkParameter(final String[] parameters, String fullURL) {
504         if (parameters != null && parameters.length > 0) {
505             String queryString = "";
506             for (final String p : parameters) {
507                 queryString += "&" + p;
508                 if (p.equalsIgnoreCase("operation=post")) {
509                     requestMethod = "POST";
510                 } else if (p.equalsIgnoreCase("operation=delete")) {
511                     requestMethod = "DELETE";
512                     operation = "delete";
513                 } else if (p.equalsIgnoreCase("operation=get")) {
514                     requestMethod = "GET";
515                     operation = "get";
516                 } else if (p.equalsIgnoreCase("operation=put") || p.equalsIgnoreCase("operation=create")
517                         || p.equalsIgnoreCase("operation=update") || p.equalsIgnoreCase("operation=createDictionary")) {
518                     requestMethod = "PUT";
519                     if (p.equalsIgnoreCase("operation=create")) {
520                         operation = "create";
521                     } else if (p.equalsIgnoreCase("operation=update")) {
522                         operation = "update";
523                     } else if (p.equalsIgnoreCase("operation=createDictionary")) {
524                         operation = "createDictionary";
525                     }
526                 } else if (p.equalsIgnoreCase("importService=MICROSERVICE")
527                         || p.equalsIgnoreCase("importService=BRMSPARAM")) {
528                     requestMethod = "PUT";
529                 }
530             }
531             fullURL += "?" + queryString.substring(1);
532         }
533         return fullURL;
534     }
535
536     public StdPDPPolicy pushPolicy(final String policyScope, final String filePrefix, final String policyName,
537             final String clientScope, final String pdpGroup, UUID requestID) throws PolicyException {
538         final String json = "{ " + "\"apiflag\": \"api\"," + "\"policyScope\": \"" + policyScope + "\","
539                 + "\"filePrefix\": \"" + filePrefix + "\"," + "\"policyName\": \"" + policyName + "\","
540                 + "\"clientScope\": \"" + clientScope + "\"," + "\"pdpGroup\": \"" + pdpGroup + "\"}";
541
542         HttpURLConnection connection = null;
543         responseCode = 0;
544         if (paps == null || paps.isEmpty()) {
545             final String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAPs List is Empty.";
546             LOGGER.error(message);
547             throw new PolicyException(message);
548         }
549         int papsCount = 0;
550         boolean connected = false;
551         while (papsCount < paps.size()) {
552             try {
553                 String fullURL = getPAP();
554                 fullURL = (fullURL.endsWith("/")) ? fullURL + "onap/pushPolicy" : fullURL + "/onap/pushPolicy";
555                 final URL url = new URL(fullURL);
556                 LOGGER.debug("--- Sending Request to PAP : " + url.toString() + " ---");
557                 // Open the connection
558                 connection = (HttpURLConnection) url.openConnection();
559                 // Setting Content-Type
560                 connection.setRequestProperty("Content-Type", "application/json");
561                 // Adding Authorization
562                 connection.setRequestProperty("Authorization", "Basic " + getPAPEncoding());
563                 connection.setRequestProperty("Environment", environment);
564                 connection.setRequestProperty("ClientScope", clientScope);
565                 // set the method and headers
566                 connection.setRequestMethod("POST");
567                 connection.setUseCaches(false);
568                 connection.setInstanceFollowRedirects(false);
569                 connection.setDoOutput(true);
570                 // Adding RequestID
571                 if (requestID == null) {
572                     requestID = UUID.randomUUID();
573                     LOGGER.info("No request ID provided, sending generated ID: " + requestID.toString());
574                 } else {
575                     LOGGER.info("Using provided request ID: " + requestID.toString());
576                 }
577                 connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
578                 // DO the connect
579                 try (OutputStream os = connection.getOutputStream()) {
580                     final int count = IOUtils.copy(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), os);
581                     if (LOGGER.isDebugEnabled()) {
582                         LOGGER.debug("copied to output, bytes=" + count);
583                     }
584                 }
585                 connection.connect();
586                 responseCode = connection.getResponseCode();
587                 // If Connected to PAP then break from the loop and continue
588                 // with the Request
589                 if (connection.getResponseCode() > 0 || isJunit) {
590                     connected = true;
591                     break;
592                 } else {
593                     LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "PAP Response Code : "
594                             + connection.getResponseCode());
595                     rotatePAPList();
596                 }
597             } catch (final Exception e) {
598                 // This means that the PAP is not working
599                 if (isJunit) {
600                     connected = true;
601                     break;
602                 }
603                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
604                 rotatePAPList();
605             }
606             papsCount++;
607         }
608         if (connected) {
609             // Read the Response
610             LOGGER.debug("connected to the PAP : " + getPAP());
611             LOGGER.debug("--- Response: ---");
612             if (connection != null) {
613                 final Map<String, List<String>> headers = connection.getHeaderFields();
614                 for (final String key : headers.keySet()) {
615                     LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
616                 }
617                 try {
618                     if (responseCode == 202) {
619                         final StdPDPPolicy policy =
620                                 (StdPDPPolicy) new ObjectInputStream(connection.getInputStream()).readObject();
621                         return policy;
622                     }
623                 } catch (IOException | ClassNotFoundException e) {
624                     LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
625                     throw new PolicyException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Decoding the result ", e);
626                 }
627             }
628             return null;
629         } else {
630             return null;
631         }
632     }
633 }