Enhancement to use the common CryptoUtils
[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.config.PDPApiAuth;
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 = PDPApiAuth.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         if (responseCode == 200 || isJunit) {
335             // Check for successful creation of policy
336             String isSuccess = null;
337             if (!isJunit) { // is this a junit test?
338                 isSuccess = connection.getHeaderField("successMapKey");
339                 operation = connection.getHeaderField("operation");
340             } else {
341                 isSuccess = SUCCESS;
342             }
343             if (SUCCESS.equals(isSuccess)) {
344                 if ("update".equals(operation)) {
345                     response = "Transaction ID: " + requestID + " --Policy with the name "
346                             + connection.getHeaderField("policyName") + " was successfully updated. ";
347                     if (connection.getHeaderField("safetyChecker") != null) {
348                         response = response + "\n\nPolicy Safety Checker Warning: This closedLoopControlName "
349                                 + "is potentially in conflict with " + connection.getHeaderField("conflictCLName")
350                                 + " that already exists." + " See detailed information on ClosedLoop Pairs below: "
351                                 + "\n\n" + connection.getHeaderField("safetyChecker");
352                     }
353                 } else if ("create".equals(operation)) {
354                     response = "Transaction ID: " + requestID + " --Policy with the name "
355                             + connection.getHeaderField("policyName") + " was successfully created.";
356                     if (connection.getHeaderField("safetyChecker") != null) {
357                         response = response + "\n\nPolicy Safety Checker Warning: This closedLoopControlName "
358                                 + "is potentially in conflict with " + connection.getHeaderField("conflictCLName")
359                                 + " that already exists. " + "See detailed information on ClosedLoop Pairs below: "
360                                 + "\n\n" + connection.getHeaderField("safetyChecker");
361                     }
362                 } else if ("delete".equals(operation)) {
363                     response = "Transaction ID: " + requestID + " --The policy was successfully deleted.";
364                 } else if ("import".equals(operation)) {
365                     response = "Transaction ID: " + requestID + " --The policy engine import for "
366                             + connection.getHeaderField("service") + " was successfull.";
367                 } else if ("createDictionary".equals(operation)) {
368                     response = "Transaction ID: " + requestID + " --Dictionary Item was added successfully!";
369                 } else if ("updateDictionary".equals(operation)) {
370                     response = "Transaction ID: " + requestID + " --Dictionary Item was updated successfully!";
371                 } else if ("getDictionary".equals(operation)) {
372                     String json = null;
373                     try {
374
375                         // get the json string from the response
376                         final InputStream is = connection.getInputStream();
377
378                         // read the inputStream into a buffer (trick found online scans entire input
379                         // looking for end-of-file)
380                         final java.util.Scanner scanner = new java.util.Scanner(is);
381                         scanner.useDelimiter("\\A");
382                         json = scanner.hasNext() ? scanner.next() : "";
383                         scanner.close();
384
385                     } catch (final IOException e1) {
386                         LOGGER.error(e1.getMessage() + e1);
387                     }
388                     response = "Transaction ID: " + requestID + " --Dictionary Items Retrieved " + json;
389                 } else if ("getMetrics".equals(operation)) {
390                     response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved "
391                             + connection.getHeaderField("metrics");
392                 }
393                 LOGGER.info(response);
394             } else {
395                 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE
396                         + "Operation unsuccessful, unable to complete the request!";
397                 LOGGER.error(message);
398                 response = message;
399             }
400         } else if (connection.getResponseCode() == 202) {
401             if ("delete".equalsIgnoreCase(connection.getHeaderField("operation"))
402                     && "true".equals(connection.getHeaderField("lockdown"))) {
403                 response = "Transaction ID: " + requestID + " --Policies are locked down, please try again later.";
404                 LOGGER.warn(response);
405             }
406         } else if (connection.getResponseCode() == 204) {
407             if ("push".equals(connection.getHeaderField("operation"))) {
408                 response = "Transaction ID: " + requestID + " --Policy '" + connection.getHeaderField("policyId")
409                         + "' was successfully pushed to the PDP group '" + connection.getHeaderField("groupId") + "'.";
410                 LOGGER.info(response);
411             }
412         } else if (connection.getResponseCode() == 400 && connection.getHeaderField("error") != null) {
413             response = connection.getHeaderField("error");
414             LOGGER.error(response);
415         } else if (connection.getResponseCode() == 403) {
416             response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is "
417                     + connection.getResponseCode()
418                     + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
419             LOGGER.error(response);
420         } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error") != null) {
421             if ("UnknownGroup".equals(connection.getHeaderField("error"))) {
422                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message")
423                         + " Please check the pdpGroup you are requesting to push the policy to.";
424                 LOGGER.error(response);
425             } else if ("policyNotAvailableForEdit".equals(connection.getHeaderField("error"))) {
426                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message");
427             }
428         } else if (connection.getResponseCode() == 409 && connection.getHeaderField("error") != null) {
429             if ("modelExistsDB".equals(connection.getHeaderField("error"))) {
430                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Import Value Exist Error:  The import value "
431                         + connection.getHeaderField("service") + " already exist on the PAP. "
432                         + "Please create a new import value.";
433             } else if ("policyExists".equals(connection.getHeaderField("error"))) {
434                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Exist Error:  The Policy "
435                         + connection.getHeaderField("policyName") + " already exist on the PAP. "
436                         + "Please create a new policy or use the update API to modify the existing one.";
437             } else if ("dictionaryItemExists".equals(connection.getHeaderField("error"))) {
438                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
439                         + "Dictionary Item Exist Error:  The Dictionary Item already exist in the database. "
440                         + "Please create a new Dictionary Item or use the update API to modify the existing one.";
441             } else if ("duplicateGroup".equals(connection.getHeaderField("error"))) {
442                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
443                         + "Group Policy Scope List Exist Error:  "
444                         + "The Group Policy Scope List for this Dictionary Item already exist in the database. "
445                         + "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. "
446                         + "Please review the request and "
447                         + "verify that the groupPolicyScopeListData1 is unique compared to existing groups.";
448             } else if ("PolicyInPDP".equals(connection.getHeaderField("error"))) {
449                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
450                         + "Policy Exist Error:  The Policy trying to be deleted is active in PDP. "
451                         + "Active PDP Polcies are not allowed to be deleted from PAP. "
452                         + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP";
453             }
454             LOGGER.error(response);
455         } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) {
456             if ("jpautils".equals(connection.getHeaderField("error"))) {
457                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Could not create JPAUtils instance on the PAP";
458             } else if ("deleteDB".equals(connection.getHeaderField("error"))) {
459                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to delete Policy from database.";
460             } else if ("deleteFile".equals(connection.getHeaderField("error"))) {
461                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file";
462             } else if ("groupUpdate".equals(connection.getHeaderField("error"))) {
463                 response = connection.getHeaderField("message");
464             } else if ("unknown".equals(connection.getHeaderField("error"))) {
465                 response = XACMLErrorConstants.ERROR_UNKNOWN
466                         + "Failed to delete the policy for an unknown reason.  "
467                         + "Check the file system and other logs for further information.";
468             } else if ("deleteConfig".equals(connection.getHeaderField("error"))) {
469                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
470                         + "Cannot delete the configuration or action body file in specified location.";
471             } else if ("missing".equals(connection.getHeaderField("error"))) {
472                 response = XACMLErrorConstants.ERROR_DATA_ISSUE
473                         + "Failed to create value in database because service does match a value in file";
474             } else if ("importDB".equals(connection.getHeaderField("error"))) {
475                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Database errors during policy engine import";
476             } else if ("policyCopyError".equals(connection.getHeaderField("error"))) {
477                 response = XACMLErrorConstants.ERROR_PROCESS_FLOW + connection.getHeaderField("message");
478             } else if ("addGroupError".equals(connection.getHeaderField("error"))) {
479                 response = connection.getHeaderField("message");
480             } else if ("validation".equals(connection.getHeaderField("error"))) {
481                 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Validation errors during policy engine "
482                         + connection.getHeaderField("operation") + " for " + connection.getHeaderField("service");
483             } else if ("error".equals(connection.getHeaderField("error"))) {
484                 response = XACMLErrorConstants.ERROR_UNKNOWN
485                         + "Could not create or update the policy for and unknown reason";
486             } else {
487                 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
488                         + "Error occured while attempting perform this operation.. "
489                         + "the request may be incorrect or the PAP is unreachable. "
490                         + connection.getHeaderField("error");
491             }
492             LOGGER.error(response);
493         } else {
494             response =
495                     XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error occured while attempting perform this operation.. "
496                             + "the request may be incorrect or the PAP is unreachable.";
497             LOGGER.error(response);
498         }
499         return response;
500     }
501
502     private String checkParameter(final String[] parameters, String fullURL) {
503         if (parameters != null && parameters.length > 0) {
504             String queryString = "";
505             for (final String p : parameters) {
506                 queryString += "&" + p;
507                 if (p.equalsIgnoreCase("operation=post")) {
508                     requestMethod = "POST";
509                 } else if (p.equalsIgnoreCase("operation=delete")) {
510                     requestMethod = "DELETE";
511                     operation = "delete";
512                 } else if (p.equalsIgnoreCase("operation=get")) {
513                     requestMethod = "GET";
514                     operation = "get";
515                 } else if (p.equalsIgnoreCase("operation=put") || p.equalsIgnoreCase("operation=create")
516                         || p.equalsIgnoreCase("operation=update") || p.equalsIgnoreCase("operation=createDictionary")) {
517                     requestMethod = "PUT";
518                     if (p.equalsIgnoreCase("operation=create")) {
519                         operation = "create";
520                     } else if (p.equalsIgnoreCase("operation=update")) {
521                         operation = "update";
522                     } else if (p.equalsIgnoreCase("operation=createDictionary")) {
523                         operation = "createDictionary";
524                     }
525                 } else if (p.equalsIgnoreCase("importService=MICROSERVICE")
526                         || p.equalsIgnoreCase("importService=BRMSPARAM")) {
527                     requestMethod = "PUT";
528                 }
529             }
530             fullURL += "?" + queryString.substring(1);
531         }
532         return fullURL;
533     }
534
535     public StdPDPPolicy pushPolicy(final String policyScope, final String filePrefix, final String policyName,
536             final String clientScope, final String pdpGroup, UUID requestID) throws PolicyException {
537         final String json = "{ " + "\"apiflag\": \"api\"," + "\"policyScope\": \"" + policyScope + "\","
538                 + "\"filePrefix\": \"" + filePrefix + "\"," + "\"policyName\": \"" + policyName + "\","
539                 + "\"clientScope\": \"" + clientScope + "\"," + "\"pdpGroup\": \"" + pdpGroup + "\"}";
540
541         HttpURLConnection connection = null;
542         responseCode = 0;
543         if (paps == null || paps.isEmpty()) {
544             final String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAPs List is Empty.";
545             LOGGER.error(message);
546             throw new PolicyException(message);
547         }
548         int papsCount = 0;
549         boolean connected = false;
550         while (papsCount < paps.size()) {
551             try {
552                 String fullURL = getPAP();
553                 fullURL = (fullURL.endsWith("/")) ? fullURL + "onap/pushPolicy" : fullURL + "/onap/pushPolicy";
554                 final URL url = new URL(fullURL);
555                 LOGGER.debug("--- Sending Request to PAP : " + url.toString() + " ---");
556                 // Open the connection
557                 connection = (HttpURLConnection) url.openConnection();
558                 // Setting Content-Type
559                 connection.setRequestProperty("Content-Type", "application/json");
560                 // Adding Authorization
561                 connection.setRequestProperty("Authorization", "Basic " + getPAPEncoding());
562                 connection.setRequestProperty("Environment", environment);
563                 connection.setRequestProperty("ClientScope", clientScope);
564                 // set the method and headers
565                 connection.setRequestMethod("POST");
566                 connection.setUseCaches(false);
567                 connection.setInstanceFollowRedirects(false);
568                 connection.setDoOutput(true);
569                 // Adding RequestID
570                 if (requestID == null) {
571                     requestID = UUID.randomUUID();
572                     LOGGER.info("No request ID provided, sending generated ID: " + requestID.toString());
573                 } else {
574                     LOGGER.info("Using provided request ID: " + requestID.toString());
575                 }
576                 connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
577                 // DO the connect
578                 try (OutputStream os = connection.getOutputStream()) {
579                     final int count = IOUtils.copy(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), os);
580                     if (LOGGER.isDebugEnabled()) {
581                         LOGGER.debug("copied to output, bytes=" + count);
582                     }
583                 }
584                 connection.connect();
585                 responseCode = connection.getResponseCode();
586                 // If Connected to PAP then break from the loop and continue
587                 // with the Request
588                 if (connection.getResponseCode() > 0 || isJunit) {
589                     connected = true;
590                     break;
591                 } else {
592                     LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "PAP Response Code : "
593                             + connection.getResponseCode());
594                     rotatePAPList();
595                 }
596             } catch (final Exception e) {
597                 // This means that the PAP is not working
598                 if (isJunit) {
599                     connected = true;
600                     break;
601                 }
602                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
603                 rotatePAPList();
604             }
605             papsCount++;
606         }
607         if (connected) {
608             // Read the Response
609             LOGGER.debug("connected to the PAP : " + getPAP());
610             LOGGER.debug("--- Response: ---");
611             if (connection != null) {
612                 final Map<String, List<String>> headers = connection.getHeaderFields();
613                 for (final String key : headers.keySet()) {
614                     LOGGER.debug("Header :" + key + "  Value: " + headers.get(key));
615                 }
616                 try {
617                     if (responseCode == 202) {
618                         final StdPDPPolicy policy =
619                                 (StdPDPPolicy) new ObjectInputStream(connection.getInputStream()).readObject();
620                         return policy;
621                     }
622                 } catch (IOException | ClassNotFoundException e) {
623                     LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
624                     throw new PolicyException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Decoding the result ", e);
625                 }
626             }
627             return null;
628         } else {
629             return null;
630         }
631     }
632 }