2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.openecomp.policy.pdp.rest.api.services;
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;
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;
36 import java.util.UUID;
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;
47 import com.att.research.xacml.util.XACMLProperties;
48 import com.fasterxml.jackson.databind.ObjectMapper;
50 public class PAPServices {
51 private static final String SUCCESS = "success";
52 private static Logger LOGGER = FlexLogger.getLogger(PAPServices.class
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;
64 public PAPServices() {
65 environment = PDPApiAuth.getEnvironment();
67 synchronized (papResourceLock) {
68 String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS);
70 urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
72 paps = Arrays.asList(urlList.split(","));
77 private String getPAPEncoding(){
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));
87 private void rotatePAPList(){
88 synchronized (papResourceLock) {
89 Collections.rotate(paps, -1);
93 private String getPAP(){
95 synchronized (papResourceLock) {
101 public int getResponseCode() {
105 public Object callPAP(Object content, String[] parameters, UUID requestID,
106 String clientScope) throws PolicyException {
107 String response = null;
108 HttpURLConnection connection = null;
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
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);
120 boolean connected = false;
121 while (papsCount < paps.size()) {
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);
142 if (requestID == null) {
143 requestID = UUID.randomUUID();
144 LOGGER.info("No request ID provided, sending generated ID: "
145 + requestID.toString());
147 LOGGER.info("Using provided request ID: "
148 + requestID.toString());
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);
160 } else if(content != null){
161 // the content is an object to be encoded in JSON
162 ObjectMapper mapper = new ObjectMapper();
164 mapper.writeValue(connection.getOutputStream(),
169 connection.connect();
170 responseCode = connection.getResponseCode();
171 // If Connected to PAP then break from the loop and continue
173 if (connection.getResponseCode() > 0 || junit) {
177 LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode());
180 } catch (Exception e) {
181 // This means that the PAP is not working
186 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
187 + "PAP connection Error : " + e);
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));
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);
215 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR
216 + "Unable to get valid response from PAP(s) " + paps;
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.");
228 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
229 } catch (Exception e) {
230 LOGGER.error(e.getMessage());
234 boolean connected = false;
235 while (papsCount < paps.size()) {
237 String fullURL = getPAP();
238 if (parameters != null && parameters.length > 0) {
239 String queryString = "";
240 for (String p : parameters) {
241 queryString += "&" + p;
243 fullURL += "?" + queryString.substring(1);
246 URL url = new URL (fullURL);
248 //Open the connection
249 connection = (HttpURLConnection)url.openConnection();
251 // Setting Content-Type
252 connection.setRequestProperty("Content-Type",
255 // Adding Authorization
256 connection.setRequestProperty("Authorization", "Basic "
259 connection.setRequestProperty("Environment", environment);
260 connection.setRequestProperty("ClientScope", clientScope);
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);
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());
275 connection.connect();
277 // If Connected to PAP then break from the loop and continue with the Request
278 if (connection.getResponseCode() > 0) {
283 LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
285 } catch (Exception e) {
286 // This means that the PAP is not working
287 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
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));
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. ");
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");
315 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect.");
317 } catch (IOException e) {
318 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
320 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
321 } catch (Exception e1) {
322 LOGGER.error(e1.getMessage());
327 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
329 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
330 } catch (Exception e) {
331 LOGGER.error(e.getMessage());
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.");
350 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
351 } catch (Exception e) {
352 LOGGER.error(e.getMessage());
356 boolean connected = false;
357 while (papsCount < paps.size()) {
359 String fullURL = getPAP();
360 if (parameters != null && parameters.length > 0) {
361 String queryString = "";
362 for (String p : parameters) {
363 queryString += "&" + p;
365 fullURL += "?" + queryString.substring(1);
368 URL url = new URL (fullURL);
370 //Open the connection
371 connection = (HttpURLConnection)url.openConnection();
373 // Setting Content-Type
374 connection.setRequestProperty("Content-Type",
377 // Adding Authorization
378 connection.setRequestProperty("Authorization", "Basic "
381 connection.setRequestProperty("Environment", environment);
382 connection.setRequestProperty("ClientScope", clientScope);
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);
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());
396 connection.connect();
398 // If Connected to PAP then break from the loop and continue with the Request
399 if (connection.getResponseCode() > 0) {
404 LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
406 } catch (Exception e) {
407 // This means that the PAP is not working
408 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
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));
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"));
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);
437 /*if (gitPath != null && !gitPath.equalsIgnoreCase("")) {
439 }*/ if (gitPath == null || gitPath.trim().isEmpty()) {
440 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
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");
446 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST: Error occured while getting the gitPath from the PAP. The request may be incorrect.");
448 } catch (IOException e) {
449 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
451 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
452 } catch (Exception e1) {
453 LOGGER.error(e1.getMessage());
458 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
460 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
461 } catch (Exception e) {
462 LOGGER.error(e.getMessage());
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;
471 StdPDPPolicy selectedPolicy;
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);
478 return selectedPolicy;
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.");
488 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
489 } catch (Exception e) {
490 LOGGER.error(e.getMessage());
494 boolean connected = false;
495 while (papsCount < paps.size()) {
497 String fullURL = getPAP();
498 if (parameters != null && parameters.length > 0) {
499 String queryString = "";
500 for (String p : parameters) {
501 queryString += "&" + p;
503 fullURL += "?" + queryString.substring(1);
506 URL url = new URL (fullURL);
508 //Open the connection
509 connection = (HttpURLConnection)url.openConnection();
511 // Setting Content-Type
512 connection.setRequestProperty("Content-Type",
515 // Adding Authorization
516 connection.setRequestProperty("Authorization", "Basic "
519 connection.setRequestProperty("Environment", environment);
520 connection.setRequestProperty("ClientScope", clientScope);
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);
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());
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) {
542 LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
544 } catch (Exception e) {
545 // This means that the PAP is not working
546 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
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));
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);
569 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
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");
575 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST: Error occured while getting the gitPath from the PAP. The request may be incorrect.");
577 } catch (IOException e) {
578 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
580 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
581 } catch (Exception e1) {
582 LOGGER.error(e1.getMessage());
587 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
589 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
590 } catch (Exception e) {
591 LOGGER.error(e.getMessage());
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");
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) {
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");
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) {
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");
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)) {
643 //get the json string from the response
644 InputStream is = connection.getInputStream();
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() : "";
652 } catch (IOException e1) {
653 LOGGER.error(e1.getMessage());
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");
659 LOGGER.info(response);
661 String message = XACMLErrorConstants.ERROR_DATA_ISSUE
662 + "Operation unsuccessful, unable to complete the request!";
663 LOGGER.error(message);
666 } else if (connection.getResponseCode() == 202) {
667 if ("delete".equalsIgnoreCase(connection.getHeaderField("operation")) &&
668 "true".equals(connection.getHeaderField("lockdown"))) {
669 response = "Transaction ID: "
671 + " --Policies are locked down, please try again later.";
672 LOGGER.warn(response);
674 } else if (connection.getResponseCode() == 204) {
675 if ("push".equals(connection.getHeaderField("operation"))) {
676 response = "Transaction ID: "
679 + connection.getHeaderField("policyId")
680 + "' was successfully pushed to the PDP group '"
681 + connection.getHeaderField("groupId") + "'.";
682 LOGGER.info(response);
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);
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.";
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";
757 LOGGER.error(response);
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);
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";
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";
789 }else if (p.equalsIgnoreCase("importService=MICROSERVICE")||p.equalsIgnoreCase("importService=BRMSPARAM")){
790 requestMethod = "PUT";
793 fullURL += "?" + queryString.substring(1);
798 public StdPDPPolicy pushPolicy(String policyScope, String filePrefix,
799 String policyName, String clientScope, String pdpGroup,
800 UUID requestID) throws PolicyException {
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;
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);
817 boolean connected = false;
818 while (papsCount < paps.size()) {
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);
838 if (requestID == null) {
839 requestID = UUID.randomUUID();
840 LOGGER.info("No request ID provided, sending generated ID: "
841 + requestID.toString());
843 LOGGER.info("Using provided request ID: "
844 + requestID.toString());
846 connection.setRequestProperty("X-ECOMP-RequestID",
847 requestID.toString());
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);
855 connection.connect();
856 responseCode = connection.getResponseCode();
857 // If Connected to PAP then break from the loop and continue
859 if (connection.getResponseCode() > 0 || junit) {
863 LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode());
866 } catch (Exception e) {
867 // This means that the PAP is not working
872 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
873 + "PAP connection Error : " + e);
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));
887 if(responseCode==202){
888 StdPDPPolicy policy = (StdPDPPolicy) new ObjectInputStream(connection.getInputStream()).readObject();
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);